From 11f9676bb51ec75b890c409576c8396dbaac105e Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:09:01 +0200 Subject: [PATCH 01/15] chore(domql): rename .local to .sandbox Work that stays out of the repository now goes in .sandbox/, which Git ignores: experiments, notes, scratch and temporary files, and benchmark baselines. The full gate's package consumers still install outside the repository, and Test-Packages.ps1 says why. --- .gitignore | 4 ++-- CLAUDE.md | 4 ++-- CONTRIBUTING.md | 3 ++- scripts/Test-Packages.ps1 | 1 + tests/DocumentLinks.test.js | 4 ++-- 5 files changed, 9 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 4b90e7b..e4cb8df 100644 --- a/.gitignore +++ b/.gitignore @@ -16,8 +16,8 @@ nuget/wwwroot/ # The browser CI installs for the browser tests. .playwright/ -# Work that belongs to a person: experiments, spikes and notes. -.local/ +# Work that stays out of the repository: experiments, spikes, notes, scratch and temporary files, and benchmark baselines. +.sandbox/ # npm's logs. npm-debug.log* diff --git a/CLAUDE.md b/CLAUDE.md index 4e735c3..357c373 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -40,7 +40,7 @@ Use these sources rather than inventing scope, status or style rules. | `VERSION-HISTORY.md` | Each DOMQL version and what it changed | | `CHANGELOG.md` | Each release of the packages and what it changed | | `nuget/` | The package project, which distributes the bundle, and the library guide | -| `.local/` | Personal experiments, spikes, notes and benchmark baselines; ignored by Git | +| `.sandbox/` | Work that stays out of the repository: experiments, spikes, notes, scratch and temporary files, and benchmark baselines; ignored by Git | Add a folder when a new responsibility needs one. Keep dependencies in this direction: @@ -100,7 +100,7 @@ Tests mirror `src/` under `tests/`. Layout, geometry and browser-managed state b | `./build.ps1 -Browser` | Repository root | Gate including browser tests | | `./build.ps1 -Browser -Full` | Repository root | The full gate: the gate including browser tests, then the NuGet package packed and verified as consumers install it | -Every compiler warning is a build failure. Keep `*.bench.js` and `*.scale.js` beside the corresponding tests, store baselines in `.local/`, and record a measurement that decides something in the design, beside the decision it settles. +Every compiler warning is a build failure. Keep `*.bench.js` and `*.scale.js` beside the corresponding tests, store baselines in `.sandbox/`, and record a measurement that decides something in the design, beside the decision it settles. ## Documentation and versions diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 29c45f7..23e6420 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -47,6 +47,7 @@ Run the full build from the repository root: | `docs/` | The design and the status overview | | `VERSION-HISTORY.md` | Each DOMQL version and what it changed | | `CHANGELOG.md` | Each release of the packages and what it changed | +| `.sandbox/` | Your own work that stays out of the repository, which Git ignores: experiments, notes, scratch and temporary files, and benchmark baselines | The [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md) defines the language and its runtime, and the [DOMQL specification](spec/README.md) the DOM vocabulary, how queries are carried out, and the public API. The [Nexo design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/nexo-design.md) and the [DOMQL design](docs/domql-design.md) set out how each is built. If a change affects either contract, update the relevant document before implementing it. The [status overview](docs/features-status.md) tracks what is implemented, what is being built, and what remains. @@ -85,7 +86,7 @@ Two details to keep in mind: - **Module registration persists.** A test that registers a module needs its own `domql` instance. Call `vi.resetModules()` and import it afresh so tests remain independent of execution order. - **README examples are tested.** When you change an example in the package guide, update its fixture in `tests/_examples/` and the answer `tests/PackageReadme.test.js` expects. The repository README's examples run as they are written. -For performance changes, run `npm run bench` from `tests/` for simulated-DOM benchmarks and `npm run scale` for Chromium workloads: a watch of 1,000 to 100,000 rows, a drag through owned writes, an edit in a large editor, a behavior's deliveries and owners, and transient measurements beside many observers. Name a file to run one workload, as `npm run scale -- dom/OwnedWrites.scale.js`; each reports the machine's load as it ran, its own included, so compare runs made at a low load alone. Compare against a baseline, keep gains that repeat beyond measurement noise, and record a conclusion that decides something in the [design](docs/domql-design.md), beside the decision it settles. Report the memory a change retains apart from what it allocates: a bound can slow a case's allocation and still end growth that outlived disposal, as [D84](docs/decisions.md#d84) did. Benchmarks are separate from the build gate. +For performance changes, run `npm run bench` from `tests/` for simulated-DOM benchmarks and `npm run scale` for Chromium workloads: a watch of 1,000 to 100,000 rows, a drag through owned writes, an edit in a large editor, a behavior's deliveries and owners, and transient measurements beside many observers. Name a file to run one workload, as `npm run scale -- dom/OwnedWrites.scale.js`; each reports the machine's load as it ran, its own included, so compare runs made at a low load alone. Compare against a baseline kept in `.sandbox/`, keep gains that repeat beyond measurement noise, and record a conclusion that decides something in the [design](docs/domql-design.md), beside the decision it settles. Report the memory a change retains apart from what it allocates: a bound can slow a case's allocation and still end growth that outlived disposal, as [D84](docs/decisions.md#d84) did. Benchmarks are separate from the build gate. diff --git a/scripts/Test-Packages.ps1 b/scripts/Test-Packages.ps1 index 0a8825a..7d058ab 100644 --- a/scripts/Test-Packages.ps1 +++ b/scripts/Test-Packages.ps1 @@ -103,6 +103,7 @@ foreach ($name in $expected.Keys) { Write-Host " $name holds the $($listed.Count) files its list names" } +# Outside the repository, not in .sandbox/: within it, Node and TypeScript would also search the repository's own node_modules, which no consumer has. $work = Join-Path ([System.IO.Path]::GetTempPath()) "domql-packages-$([guid]::NewGuid().ToString('N'))" $previousPackages = $env:NUGET_PACKAGES diff --git a/tests/DocumentLinks.test.js b/tests/DocumentLinks.test.js index 5b61e55..6aa418a 100644 --- a/tests/DocumentLinks.test.js +++ b/tests/DocumentLinks.test.js @@ -6,8 +6,8 @@ import { describe, it, expect } from 'vitest'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); -/** The folders that hold no document of DOMQL's: Git's, dependencies, build outputs, the browser CI installs, and the notes Git ignores. */ -const SKIPPED = new Set(['.git', '.local', '.playwright', '.vs', '.idea', 'artifacts', 'bin', 'node_modules', 'obj', 'wwwroot']); +/** The folders that hold no document of DOMQL's: Git's, dependencies, build outputs, the browser CI installs, and the sandbox Git ignores. */ +const SKIPPED = new Set(['.git', '.sandbox', '.playwright', '.vs', '.idea', 'artifacts', 'bin', 'node_modules', 'obj', 'wwwroot']); /** The kinds of file a link into Nexo may stand in; a document's own links are read in Markdown alone. */ const LINKING = new Set(['.md', '.js', '.mjs', '.ts', '.ps1', '.yml', '.json']); From abab1f9a264fdde49c6f0ce9b63d2d9867c9ec83 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Mon, 30 Nov 2026 03:29:33 +0200 Subject: [PATCH 02/15] fix(domql)!: watch a box's size as laid out size is the border box as the box is drawn, transforms applied, and partly observable: a transform or an animation, its own or an ancestor's, changes it with no resize observer reporting it, where it was called observable. layoutSize is the size layout gives the box, along its writing mode's axes, as the browser's resize observer reports it, a maintained member every change of its layout reports. The specification opens 1.0.0-preview.2 and the runtime 1.0.0-preview.4. D111 records it. BREAKING CHANGE: a watch of size is refused unless it accepts partial observation. Watch layoutSize where the size as laid out is needed, or accept partial observation to keep the box as drawn. --- CHANGELOG.md | 9 ++ README.md | 2 +- VERSION-HISTORY.md | 27 ++++++ docs/decisions.md | 19 ++++ docs/domql-design.md | 8 +- docs/features-status.md | 7 +- nuget/README.md | 6 +- package-lock.json | 4 +- package.json | 2 +- spec/README.md | 4 +- spec/api.md | 2 +- spec/queries.md | 4 +- spec/vocabulary.md | 28 +++++- spec/watches.md | 2 +- src/Versions.mjs | 4 +- src/dom/BrowserObservationImplementations.mjs | 57 ++++++++++++ src/dom/BrowserVocabularyDeclarations.mjs | 7 +- src/dom/BrowserVocabularyImplementations.mjs | 18 ++++ tests/DocumentExamples.test.js | 1 + tests/Domql.browser.js | 12 +-- tests/Domql.test.js | 4 +- .../BrowserObservationImplementations.test.js | 86 ++++++++++++++++++ .../dom/BrowserVocabularyDeclarations.test.js | 11 +-- tests/dom/LayoutSize.browser.js | 88 +++++++++++++++++++ tests/language/LanguageResolver.test.js | 9 +- tests/vitest.engines.config.js | 4 +- 26 files changed, 383 insertions(+), 42 deletions(-) create mode 100644 tests/dom/LayoutSize.browser.js diff --git a/CHANGELOG.md b/CHANGELOG.md index a1af7ba..e1f386d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ Each release of DOMQL's packages, newest first. The npm package `@formaui-net/do - **An entry is dated when its release is cut,** and reads *Unreleased* until then. [Cutting a release](CONTRIBUTING.md#cut-a-release) tags its commit, and its packages are published from that tag. - **A change a caller can notice** is listed in the newest entry while it is unreleased. Once it is released, the change opens the next version's entry, and the sources declare that version in the same commit. + + +## `1.0.0-preview.4` + +*Unreleased · specification `1.0.0-preview.2` · Nexo language `1.0.0-preview.1` · definition format 38* + +- An element's `layoutSize` answers the size layout gives its border box, along its writing mode's axes, `{ inline, block }`, a transform aside, from the browser's resize observer, and a watch follows every change of it. +- A watch of an element's `size` is refused unless it accepts partial observation, since a transform changes the box as it is drawn with no observer reporting it. Watch `layoutSize`, or accept partial observation. + ## `1.0.0-preview.3` diff --git a/README.md b/README.md index 69ed0ae..a4149d3 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ DOMQL is a JavaScript library for querying the DOM, allowing you to read information from a document once or observe it as it changes. Its queries are written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md). -> **Preview.** No breaking redesign is planned, and a version that breaks what the one before it allowed says how to migrate. The runtime, `1.0.0-preview.3`, implements DOMQL's specification `1.0.0-preview.1` on Nexo's language `1.0.0-preview.1`, definition version 38. DOMQL declares the DOM as types of its own. It is published to npm and NuGet, as [installing it](#install) sets out, and you can also [build and try it locally](#build-and-try-it). See [the status overview](docs/features-status.md), and [what 1.0 requires](docs/features-status.md#what-1-0-requires). +> **Preview.** No breaking redesign is planned, and a version that breaks what the one before it allowed says how to migrate. The runtime, `1.0.0-preview.4`, implements DOMQL's specification `1.0.0-preview.2` on Nexo's language `1.0.0-preview.1`, definition version 38. DOMQL declares the DOM as types of its own. It is published to npm and NuGet, as [installing it](#install) sets out, and you can also [build and try it locally](#build-and-try-it). See [the status overview](docs/features-status.md), and [what 1.0 requires](docs/features-status.md#what-1-0-requires). ## Features diff --git a/VERSION-HISTORY.md b/VERSION-HISTORY.md index c4403a4..62a6366 100644 --- a/VERSION-HISTORY.md +++ b/VERSION-HISTORY.md @@ -13,6 +13,33 @@ Each entry says what its version breaks: - **From `1.0.0-beta.1` until the first release candidate,** through the betas and the previews, a decision may be replaced where a demonstrated fault, an ambiguous contract or a measured cost justifies it, whether or not Forma has met it, as [D100](docs/decisions.md#d100) records. A version that breaks what the one before it allowed says, beside each break, how a query, a caller or a module migrates. - **From `1.0.0-rc.1` on,** nothing breaks before 2.0, as [FormaUI Versioning's stages](https://github.com/FormaUI/Versioning/blob/v1.0.0-preview.1/docs/versions.md#stages) promise. + + +## `1.0.0-preview.2` + +*Unreleased · Nexo language `1.0.0-preview.1` · definition format 38* + +```domql +box.layoutSize?.inline // the size layout gives the box along its line, a transform aside; NEXO3001 before, no such member +box.size // the box as it is drawn; watched, DOMQL3003 unless the watch accepts partial observation, accepted before though a transform went unheard +``` + +```js +await domql.query('box.layoutSize', { box }).evaluateAsync(); // { inline: 200, block: 50 } under scale(0.5), as laid out, once the browser reports it +domql.query('box.size', { box }).evaluate(); // { width: 100, height: 25 } under scale(0.5), as drawn, as before +domql.query('box.size', { box }).watch(); // DOMQL3003; a watch that missed every transform before +domql.query('box.size', { box }).watch({ acceptPartialObservation: true }); // the box as drawn, a transform missed until another change is observed +``` + +**Vocabulary** + +- [`layoutSize`](spec/vocabulary.md#property-element-layoutsize) is the size layout gives an element's border box, along the axes of its writing mode, `inline` and `block`, a transform aside, as the browser's resize observation measures it. It reads a maintained observation of its own, [`layoutSize`](spec/vocabulary.md#observations-types), so it is observable, null where the element is laid out as no one box, and pending until the browser first reports it, as [D111](docs/decisions.md#d111) records. +- [`size`](spec/vocabulary.md#property-element-size) is the box as it is drawn, as it was read, and partly observable: a transform or an animation, its own or an ancestor's, and the size of an inline box are missed, where it was called observable and missed them. + +**Breaking:** + +- A watch of `size` is refused unless it accepts partial observation, DOMQL3003. Watch `layoutSize` where the size as laid out is what it needs, reading `inline` and `block` for `width` and `height` along a horizontal line, or pass `acceptPartialObservation: true` to keep the box as drawn. + ## `1.0.0-preview.1` diff --git a/docs/decisions.md b/docs/decisions.md index 94b21da..c3e8b74 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -1697,3 +1697,22 @@ Each entry is one of three kinds: - Publishing an npm package of `1.0.0-preview.1` from another commit, which would give a fixed release a package its full gate never built. - Waiting for the NuGet package to depend on Nexo's as well, which changes how a .NET application serves the language, and which [consuming the language](features-status.md#consuming-nexo) plans on its own. - Moving npm's `latest` to a preview, so the package's page shows it rather than the deprecated placeholder that holds `latest` until 1.0: a pre-release would become the default install, which [FormaUI Versioning's publication](https://github.com/FormaUI/Versioning/blob/v1.0.0-preview.1/docs/packages.md#publication) forbids. npm's page shows the version `latest` names, so it shows the placeholder's deprecation, as `npm install @formaui-net/domql` warns, naming `@preview`. + + + +## D111 — `size` is the box as drawn, and `layoutSize` the box as laid out + +*November 30, 2026* + +- **Kind:** Contract, correcting a fault; a feature Forma's scripts need, as [what 1.0 requires](features-status.md#what-1-0-requires) allows. +- **Decision:** + - `size` stays the border box as it is drawn, transforms applied, as `rect` measures it, and is partly observable. It misses a transform or an animation, its own or an ancestor's, and the size of an inline box. + - `layoutSize`, a new member, is the border box as layout gives it, along the writing mode's axes: `LogicalSize { inline, block }`. It reads a maintained observation of its own, `layoutSize`, which samples the browser's resize observation, so it is observable. It is null where the element is laid out as no one box, and pending until the browser's first report. Chromium, Firefox and WebKit each make one for a box of any size, a hidden or a detached element included, as they lay the page out, so an element of a hidden document waits until the document is shown, as one `intersects` reads does. +- **Why:** + - `size` read `getClientRects()`, the box as drawn, but its one observation was the resize observer, which reports the box as laid out. A transform changed `size` with nothing observing it, while the specification called it observable. In Chromium, a watch of `size` stayed at 200×50 after `scale(0.5)`, where a refresh read 100×25. + - Forma's stepper reads a box's size from C# to decide whether its steps' names fit. It needs the size layout gives the box, along its writing mode, which no member answered. + - A maintained member waits for the browser's first report, so a watch's first snapshot is the size as laid out. A script that read the box as drawn first, then corrected it, sent a wrong size and a second crossing under a transform. +- **Breaks:** a watch of `size` is refused unless it accepts partial observation (`DOMQL3003`). It migrates by accepting partial observation, or by watching `layoutSize`, where the size as laid out is what it needs. +- **Declined:** + - Making `size` the box as laid out. A synchronous read can't give the untransformed, fractional border box for every box, and `size` would then disagree with `rect`. + - A maintained `size`. `evaluate` would answer null for it until the browser's first report, breaking every synchronous read of it. diff --git a/docs/domql-design.md b/docs/domql-design.md index fa15934..ab9b783 100644 --- a/docs/domql-design.md +++ b/docs/domql-design.md @@ -1,6 +1,6 @@ -# DOMQL Design v1.0.0-preview.1 +# DOMQL Design v1.0.0-preview.2 -The [DOMQL specification](../spec/README.md) is the contract: DOMQL's module, which declares the DOM as Nexo's domain, and the host that carries queries out against a document. This design sets out how this implementation is built to meet it, and the reasons behind the choices that shape it. It describes DOMQL's version `1.0.0-preview.1` on Nexo's definition version 38, as the specification does, and an outline of the C# half, which waits for its design; [the status overview](features-status.md) says where the implementation still differs. [Nexo's design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/nexo-design.md), at the release DOMQL builds against, sets out how the language and its runtime are built. +The [DOMQL specification](../spec/README.md) is the contract: DOMQL's module, which declares the DOM as Nexo's domain, and the host that carries queries out against a document. This design sets out how this implementation is built to meet it, and the reasons behind the choices that shape it. It describes DOMQL's version `1.0.0-preview.2` on Nexo's definition version 38, as the specification does, and an outline of the C# half, which waits for its design; [the status overview](features-status.md) says where the implementation still differs. [Nexo's design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/nexo-design.md), at the release DOMQL builds against, sets out how the language and its runtime are built. In this document: @@ -139,13 +139,13 @@ public sealed record PanelState(double? Width, bool HasFocus); DomqlQuery typed = Domql.Query( """ panel { - width = it.size?.width, + width = it.layoutSize?.inline, hasFocus = it.focusWithin } """, ("panel", panel)); -DomqlQuery untyped = Domql.Query("panel { size = it.size }", ("panel", panel)); +DomqlQuery untyped = Domql.Query("panel { size = it.layoutSize }", ("panel", panel)); ``` A `DomqlQuery` answers a `T`, mapped by its declared contract, which matches the result's fields to the constructor parameters of `T` by name regardless of case, so a field `nearend` fills a parameter `NearEnd`, and reports an ambiguity where two fields differ only in case, since DOMQL itself tells them apart; a `DomqlQuery` answers a `DomqlSnapshot` giving structured access to its values. C# has no C# type standing for each vocabulary concept: a module contributes its declarations and implementations, and the text names what the query reads. `Domql.TryQuery` attempts exactly what `Domql.Query` does, making a query and checking the syntax and the structural rules that need no vocabulary, an empty object expression, a duplicate field and a reserved name among them, without resolving its vocabulary or evaluating anything, so a successful return means the query was made, not that it is ready to be carried out: a syntax or structure failure returns false with a diagnostic, and any other failure is thrown, never swallowed. A vocabulary failure, such as an unknown member, arrives when the query is resolved. C# cancels with a `CancellationToken` where JavaScript takes a `signal`. diff --git a/docs/features-status.md b/docs/features-status.md index 043ef8b..e836c88 100644 --- a/docs/features-status.md +++ b/docs/features-status.md @@ -2,11 +2,11 @@ ## Current state -**DOMQL is in its preview, `1.0.0-preview.1`. Its vocabulary, queries, watches, events, executions and behaviors are implemented on Nexo's language `1.0.0-preview.1`, definition version 38. The specification describes DOMQL's `1.0.0-preview.1`, which the implementation follows: the DOM declared as DOMQL's own types, read through the `Domql` module every query imports. Every [planned capability](#planned-capabilities) is implemented or declined but the C# half's, A1 and A5's queue, which wait for its design.** +**DOMQL is in its preview, `1.0.0-preview.2`. Its vocabulary, queries, watches, events, executions and behaviors are implemented on Nexo's language `1.0.0-preview.1`, definition version 38. The specification describes DOMQL's `1.0.0-preview.2`, which the implementation follows: the DOM declared as DOMQL's own types, read through the `Domql` module every query imports. Every [planned capability](#planned-capabilities) is implemented or declined but the C# half's, A1 and A5's queue, which wait for its design.** | Version | Implementation | Specification | | --- | --- | --- | -| DOMQL specification | `1.0.0-preview.1` | `1.0.0-preview.1` | +| DOMQL specification | `1.0.0-preview.2` | `1.0.0-preview.2` | | Nexo language | `1.0.0-preview.1` | `1.0.0-preview.1` | | Definition format | 38 | 38 | @@ -24,7 +24,7 @@ The [specification](../spec/README.md) defines the contract, and the [design](do | --- | --- | | [The C# half](#the-c-half) | Waits for its design | | [Planned capabilities](#planned-capabilities) | The C# half's alone remain, waiting for its design | -| [Release](#release) | Done: `1.0.0-preview.3`, whose npm package changes only the README it carries, is released | +| [Release](#release) | `1.0.0-preview.3` is released; `1.0.0-preview.4`, on the specification `1.0.0-preview.2`, is unreleased | | [What 1.0 requires](#what-1-0-requires) | Six requirements, two met | - **A specification version collects the changes between two releases.** A change to DOMQL's contract joins the [version history](../VERSION-HISTORY.md)'s newest entry while it reads *Unreleased*, and opens the next version's entry once it is released, as [D79](decisions.md#d79) records. @@ -60,6 +60,7 @@ Each feature, the contract that states it, its state in the implementation, and | Extension modules: their types, extensions read with `:`, observations, event sources and executions | [Extension modules](../spec/vocabulary.md#extension-modules) | Implemented | [`alpha.278`](../VERSION-HISTORY.md#v1-0-0-alpha-278) | | The DOM declared as DOMQL's own reference types, and the cast from `Aria` to `Element` | [Nodes](../spec/nodes-and-shadow-trees.md#nodes), [types](../spec/vocabulary.md#vocabulary-types) | Implemented | [`alpha.278`](../VERSION-HISTORY.md#v1-0-0-alpha-278) | | Diagnostic codes of DOMQL's own | [Errors](../spec/errors.md) | Implemented | [`alpha.278`](../VERSION-HISTORY.md#v1-0-0-alpha-278) | +| The size layout gives a box, `layoutSize`, along its writing mode's axes, and `size`, the box as it is drawn, partly observable | [`layoutSize`](../spec/vocabulary.md#property-element-layoutsize), [`size`](../spec/vocabulary.md#property-element-size) | Implemented, as [D111](decisions.md#d111) records | [`preview.2`](../VERSION-HISTORY.md#v1-0-0-preview-2) | | Scrolling: `scroll` of an element and of the window, `scrollContainer`, and the padding box, `clientRect` | [Element `scroll`](../spec/vocabulary.md#property-element-scroll), [`scrollContainer`](../spec/vocabulary.md#function-element-scrollcontainer), [`clientRect`](../spec/vocabulary.md#property-element-clientrect) | Implemented | [`alpha.280`](../VERSION-HISTORY.md#v1-0-0-alpha-280) | | Measurements of layout compared within a tolerance | [Tolerance](../spec/vocabulary.md#vocabulary-tolerance) | Implemented | [`alpha.280`](../VERSION-HISTORY.md#v1-0-0-alpha-280) | | The observation target `children`, and a document's size | [Observation targets](../spec/vocabulary.md#observations-targets) | Implemented | [`alpha.280`](../VERSION-HISTORY.md#v1-0-0-alpha-280) | diff --git a/nuget/README.md b/nuget/README.md index 4315e78..14615a3 100644 --- a/nuget/README.md +++ b/nuget/README.md @@ -4,7 +4,7 @@ DOMQL is a JavaScript library for querying the DOM, allowing you to read information from a document once or observe it as it changes. This guide takes you from your first query to watching results, handling events and extending the library. Its queries are written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md). -> **Preview:** no breaking redesign is planned, and a version that breaks what the one before it allowed says how to migrate. `formaui-net.DOMQL` is published to NuGet as a pre-release, which you [install by name](#install-and-load). The package distributes a JavaScript ES module; the API in this guide runs in JavaScript. Every example here runs on this preview. The runtime, `1.0.0-preview.3`, implements DOMQL's specification `1.0.0-preview.1` on Nexo's language `1.0.0-preview.1`, definition version 38. [The status overview](https://github.com/FormaUI/DOMQL/blob/main/docs/features-status.md) says what is implemented and what is being built. +> **Preview:** no breaking redesign is planned, and a version that breaks what the one before it allowed says how to migrate. `formaui-net.DOMQL` is published to NuGet as a pre-release, which you [install by name](#install-and-load). The package distributes a JavaScript ES module; the API in this guide runs in JavaScript. Every example here runs on this preview. The runtime, `1.0.0-preview.4`, implements DOMQL's specification `1.0.0-preview.2` on Nexo's language `1.0.0-preview.1`, definition version 38. [The status overview](https://github.com/FormaUI/DOMQL/blob/main/docs/features-status.md) says what is implemented and what is being built. ## In this guide @@ -205,7 +205,7 @@ Call `dispose()` when you no longer need updates. It stops the watch's listeners ### Observation limits -A watch can only respond to changes reported by its members' observations. Some members have gaps: `matches` misses pointer state such as `:hover`, and `rect` can miss position changes that none of its observations detect. +A watch can only respond to changes reported by its members' observations. Some members have gaps: `matches` misses pointer state such as `:hover`, `rect` can miss position changes that none of its observations detect, and `size` misses a transform, which changes the size a box is drawn at but not its layout. To watch a box's size, watch `layoutSize`, which every change of its layout reports. Watching a partly observable member requires an explicit option: @@ -798,6 +798,8 @@ panel.scroll { } ``` +`rect` and `size` measure the box as it is drawn, its transforms and its ancestors' applied. `layoutSize` is the size layout gives the box, along its writing mode's axes, `inline` and `block`, with any transform left aside, as the browser's resize observer measures it. It is pending until the browser first reports the box, as it lays the page out: `evaluate` fails on it, so read it with `evaluateAsync` or a watch, whose first snapshot waits for that report. + `scrollContainer()` finds the nearest ancestor the user can scroll, across shadow roots and slots, and is null where the window scrolls the element. `sizeLimits` reads the `min-width`, `max-width`, `min-height` and `max-height` a box is kept within, in pixels, each null where it is no length. A watch compares each measurement within a twentieth of a pixel, so a box settling by less reports no change. ### Read values and text diff --git a/package-lock.json b/package-lock.json index 141ee15..977d525 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@formaui-net/domql", - "version": "1.0.0-preview.3", + "version": "1.0.0-preview.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@formaui-net/domql", - "version": "1.0.0-preview.3", + "version": "1.0.0-preview.4", "license": "Apache-2.0", "dependencies": { "@formaui-net/nexo": "^1.0.0-preview.1" diff --git a/package.json b/package.json index badc078..92c1bb2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@formaui-net/domql", - "version": "1.0.0-preview.3", + "version": "1.0.0-preview.4", "description": "DOMQL is a JavaScript library for querying the DOM, allowing you to read information from a document once or observe it as it changes.", "license": "Apache-2.0", "author": "Eyal Alon", diff --git a/spec/README.md b/spec/README.md index 976c363..feab9c6 100644 --- a/spec/README.md +++ b/spec/README.md @@ -1,4 +1,4 @@ -# DOMQL Specification v1.0.0-preview.1 +# DOMQL Specification v1.0.0-preview.2 DOMQL reads the DOM and shapes what it reads as data, keeps that data current as the document changes, delivers the page's events as data, and carries out the executions its own module and its extensions declare. Its queries are scripts written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md), whose specification holds two contracts: the language's, what a script means, and the runtime's, how a host binds, resolves and evaluates a script. DOMQL declares the DOM as Nexo's domain, in a module like any other, and is the host that carries each query out against a document. It adds no language rule: a rule of the language or of its runtime is Nexo's, and this specification links to it. @@ -6,7 +6,7 @@ This specification is the authoritative contract for DOMQL. It states what DOMQL -**Version.** This specification describes DOMQL's version `1.0.0-preview.1`, which changes as DOMQL's contract does, apart from its runtime's version and from Nexo's language. It describes DOMQL on Nexo's language version `1.0.0-preview.1`, of [definition version 38](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md#version). An implementation says which specification it follows, and which language version its Nexo runtime follows, in `domql.info.versions`, as [the API](api.md#api-entry-points-and-operations) sets out. +**Version.** This specification describes DOMQL's version `1.0.0-preview.2`, which changes as DOMQL's contract does, apart from its runtime's version and from Nexo's language. It describes DOMQL on Nexo's language version `1.0.0-preview.1`, of [definition version 38](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md#version). An implementation says which specification it follows, and which language version its Nexo runtime follows, in `domql.info.versions`, as [the API](api.md#api-entry-points-and-operations) sets out. ## What it covers diff --git a/spec/api.md b/spec/api.md index d756dc1..e60e34d 100644 --- a/spec/api.md +++ b/spec/api.md @@ -40,7 +40,7 @@ const size = domql.evaluate('panel.size', { panel }); const panelQuery = domql.query('panel { size = it.size }', { panel }); const now = panelQuery.evaluate(); // Its result now. const width = panelQuery.select('size', 'width'); // Its width alone: width.evaluate() runs the query and answers it. -const watch = panelQuery.watch({ signal }); // Its result kept current until the signal aborts. +const watch = panelQuery.watch({ acceptPartialObservation: true, signal }); // Its result kept current until the signal aborts, but for a transform, which no observer reports. ``` Both ways offer the same six operations. Which one a query takes follows from what it does: a query that reads the page is evaluated or watched, one that listens to it is subscribed to, and one that changes it is executed or run. diff --git a/spec/queries.md b/spec/queries.md index a1b9a1a..c5d21d9 100644 --- a/spec/queries.md +++ b/spec/queries.md @@ -66,7 +66,7 @@ A caller can take that result once, keep it current as the document changes, or // From text, binding its parameters by name. const panelQuery = domql.query(` panel { - size = it.size, + size = it.layoutSize, hasFocus = it.focusWithin } `, { panel }); @@ -165,7 +165,7 @@ The object `domql.query` answers is a query object, whatever it holds, and what `query.select(...path)` answers a selection, a part of the query's result. A selection belongs to the query, as its definition and bindings do, and every operation on it starts work of its own, where a selected view belongs to a running watch, as [sharing a watch](watches.md#sharing-a-watch) sets out. It offers `select(...path)`, `evaluate(options?)`, `evaluateAsync(options?)` and `watch(options?)`. A path holds the names of written fields, of a dictionary's `entries` and a pair's `key` and `value`, and list indices that are not negative; a local is no field, so it is never part of a path. ```js -const width = panelQuery.select("size", "width"); // As panelQuery.select("size").select("width"). +const width = panelQuery.select("size", "inline"); // As panelQuery.select("size").select("inline"). const currentWidth = await width.evaluateAsync(); diff --git a/spec/vocabulary.md b/spec/vocabulary.md index e87f7ed..bcde012 100644 --- a/spec/vocabulary.md +++ b/spec/vocabulary.md @@ -71,6 +71,7 @@ DOMQL's module declares each of its types with its members, as Nexo's [declaring | Structured type | What it is | Properties | | --- | --- | --- | | `Size` | A width and a height | `width`, `height`: `Number` | +| `LogicalSize` | A box's size along the axes of its writing mode | `inline`, `block`: `Number` | | `Rectangle` | A box's edges and size | `left`, `top`, `right`, `bottom`, `width`, `height`: `Number` | | `Selection` | A text selection's range | `start`, `end`: `Number` | | `DocumentSelection` | The document's selection as it stands | `type`: `String`; `collapsed`: `Boolean`; `rangeCount`: `Number`; `anchorElement`, `focusElement`: `Element?`; `range`: `Range?` | @@ -102,7 +103,7 @@ An element with a layout box whose dimensions are zero has actual measurements o - **What it absorbs.** A box settling by a unit of the browser's layout, 1/64 of a pixel in Chromium and WebKit and 1/60 in Firefox, and the rounding of the arithmetic that answers a measurement, as `right` is `left` and `width` added. - **What it reports.** Any move a device pixel shows, which is a quarter of a pixel at a device pixel ratio of 4. A move made in steps smaller than the tolerance is reported once the steps add up to more, since each is compared with the measurement last reported. -- **Who declares it.** `rect`, `clientRect`, `rectRelativeTo`, `size`, `clientSize`, `scroll` and `grid` of an element, and `size` and `scroll` of the window. A number computed from one, as `it.rect?.width / 2`, compares exactly, as Nexo's [arithmetic](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/expressions.md#arithmetic-watching) sets out, and an evaluation once is never rounded. +- **Who declares it.** `rect`, `clientRect`, `rectRelativeTo`, `size`, `clientSize`, `layoutSize`, `scroll` and `grid` of an element, and `size` and `scroll` of the window. A number computed from one, as `it.rect?.width / 2`, compares exactly, as Nexo's [arithmetic](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/expressions.md#arithmetic-watching) sets out, and an evaluation once is never rounded. Scrolling reads the same way, along the axes of a box's writing mode: @@ -128,6 +129,7 @@ A property exposes a value, read by property access, and takes no argument. Each | Element | [`clientRect`](#property-element-clientrect) | `Rectangle?` | | Element | [`size`](#property-element-size) | `Size?` | | Element | [`clientSize`](#property-element-clientsize) | `Size?` | +| Element | [`layoutSize`](#property-element-layoutsize) | `LogicalSize?` | | Element | [`scroll`](#property-element-scroll) | `Scroll?` | | Element | [`grid`](#property-element-grid) | `Grid?` | | Element | [`selection`](#property-element-selection) | `Selection?` | @@ -244,9 +246,9 @@ A property exposes a value, read by property access, and takes no argument. Each **Type:** `Size?` **Reads:** Fresh **Tolerance:** [0.05](#vocabulary-tolerance) -**Result.** Its border box's `width` and `height` +**Result.** Its border box's `width` and `height`, as the box is drawn, its own transforms and its ancestors' applied, as `rect` measures it -**Changes.** Observable +**Changes.** Partly observable: its box's size as layout gives it is observed; a transform or an animation, its own or an ancestor's, which changes the box as it is drawn without resizing it, is not, nor the size of an inline box, which flows as fragments no resize observer measures. [`layoutSize`](#property-element-layoutsize) is the size layout gives the box, which every change of it reports @@ -260,6 +262,23 @@ A property exposes a value, read by property access, and takes no argument. Each **Changes.** Partly observable: its border box and its content box are observed, so a scrollbar appearing or going and a border changing are; a border and padding changing so that one grows by as much as the other shrinks, which leaves both boxes as they were, is not + + +### Element: layoutSize + +**Type:** `LogicalSize?` **Reads:** Maintained **Tolerance:** [0.05](#vocabulary-tolerance) + +**Result.** The size layout gives its border box, along the axes of its writing mode, `inline` and `block`, as the browser's resize observation measures it: a transform, its own or an ancestor's, changes how the box is drawn, which [`size`](#property-element-size) answers, and not its layout, which this answers. A box in a vertical writing mode, 40 pixels wide and 300 high, is 300 along its inline axis and 40 along its block axis. + +It is null where the element is laid out as no one box: while it has no layout box, as [measurements and layout](#vocabulary-measurements-and-layout) set out, and while it is an inline box of text and elements, `display: inline` on an element its own content doesn't replace, which flows as fragments no resize observer measures. An element replaced by what it shows, as an image, a video or a form control, is one box whatever its display, and so is an SVG element, which the resize observation measures by its bounding box. It is pending until the browser first reports the element, which it does as it lays the page out, so not while the document is hidden: `evaluate` fails on it, as on any [maintained member](evaluation.md#waiting-for-maintained-members), and `evaluateAsync` and a watch's first snapshot wait for that report. So the first snapshot holds the size as laid out, never a size the box was drawn at before it. + +**Changes.** Observable + +```domql +list.layoutSize?.inline // The space its items have along a line. +(item.layoutSize?.inline ?? 0) > (list.layoutSize?.inline ?? 0) // Whether an item is longer than the line. +``` + ### Element: scroll @@ -1508,7 +1527,7 @@ A query converts with the four conversions [Nexo's own module](https://github.co ## Observations -A member names the [observations](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/observations.md#observations) that cover its changes, each by its type and its target, and DOMQL starts each one that a watch, a waiting evaluation or an event's object expression needs, and stops it once nothing needs it. DOMQL's module declares the browser's observations as eleven observation types, each animation frame as a twelfth, and the state a behavior offers as a thirteenth, which the members of any module and module code through its [environment](#extension-modules-environment) can name, and five observation targets. +A member names the [observations](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/observations.md#observations) that cover its changes, each by its type and its target, and DOMQL starts each one that a watch, a waiting evaluation or an event's object expression needs, and stops it once nothing needs it. DOMQL's module declares the browser's observations as twelve observation types, each animation frame as a thirteenth, and the state a behavior offers as a fourteenth, which the members of any module and module code through its [environment](#extension-modules-environment) can name, and five observation targets. @@ -1522,6 +1541,7 @@ Each type is shared by equivalent requests, those of the same target and the sam | `mutation` | Invalidation | A node's attributes, its children or its text, and its descendants' where `subtree` says so | `attributes`: `true`, or a list of attribute names; `childList`, `subtree` and `characterData`, Booleans, false when omitted; at least one of attributes, children and text is observed | All four | | `attachment` | Invalidation | Whether a node is attached to its document, through every shadow root between them, a node another document owns inserted into the window's document included | None | None | | `intersection` | Maintained | Whether the browser reports an element intersecting a root, or the window where the root is null, grown by a margin in CSS pixels; pending until its first report. It takes a new sample by observing the element again, which the browser reports after it lays out its next frame | `root`, an element or null, null when omitted; `margin`, a number, 0 when omitted | `root`, `margin` | +| `layoutSize` | Maintained | The size layout gives an element's border box along the axes of its writing mode, a transform aside, as the browser's resize observation reports it; pending until its first report, which the browser makes once it has laid the element out. It takes a new sample by observing the element again | None | None | | `media` | Invalidation | Whether a media query matches | `query`, the media query | `query` | | `pixelRatio` | Invalidation | The device pixel ratio | None | None | | `event` | Invalidation | Events of the given types reaching the target, or reaching it in the capture phase | `types`, a list of event types; `capture`, a Boolean, false when omitted | `types`, `capture` | diff --git a/spec/watches.md b/spec/watches.md index 367dbee..e4ef733 100644 --- a/spec/watches.md +++ b/spec/watches.md @@ -81,7 +81,7 @@ Every member declares how its result changes, by the categories [Nexo defines](h A watch is checked against every member its query may read. A member of a value of `Any` is selected as the query is evaluated, so the watch is checked against every declaration of its name Nexo could select, as Nexo's [candidate declarations](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/resolution.md) overestimate them: a watch over `panel:bag.rect`, where a module's extension member `bag` answers `Any`, takes `acceptPartialObservation`, as one over `panel.rect` does. | Derived | A list's `first` or `where` | Allowed wherever what it derives from is. | -A literal is constant, so a watched object expression can carry one: `viewport { kind = "viewport", width = it.size?.width }`. +A literal is constant, so a watched object expression can carry one: `viewport { kind = "viewport", width = it.layoutSize?.inline }`. diff --git a/src/Versions.mjs b/src/Versions.mjs index f2dbdea..a55a55b 100644 --- a/src/Versions.mjs +++ b/src/Versions.mjs @@ -6,10 +6,10 @@ import { nexo } from '@formaui-net/nexo'; export class Versions { /** The runtime release version, which the package and the bundle carry. */ - static runtime = '1.0.0-preview.3'; + static runtime = '1.0.0-preview.4'; /** The DOMQL specification version the implementation follows. */ - static specification = '1.0.0-preview.1'; + static specification = '1.0.0-preview.2'; /** The language specification version the Nexo runtime DOMQL runs on follows, as that runtime reports it. */ static language = nexo.info.versions.language; diff --git a/src/dom/BrowserObservationImplementations.mjs b/src/dom/BrowserObservationImplementations.mjs index 97a3cb2..e97d5cc 100644 --- a/src/dom/BrowserObservationImplementations.mjs +++ b/src/dom/BrowserObservationImplementations.mjs @@ -36,6 +36,7 @@ export class BrowserObservationImplementations { observeMutation: input => BrowserObservationImplementations.#observeMutation(input, mutationObservers), observeAttachment: input => BrowserObservationImplementations.#observeAttachment(input, mutationObservers), observeIntersection: BrowserObservationImplementations.#observeIntersection, + observeLayoutSize: BrowserObservationImplementations.#observeLayoutSize, observeMedia: BrowserObservationImplementations.#observeMedia, observePixelRatio: BrowserObservationImplementations.#observePixelRatio, observeEvents: BrowserObservationImplementations.#observeEvents, @@ -221,6 +222,62 @@ export class BrowserObservationImplementations { }; } + /** + * The size layout gives an element's border box, along the axes of its writing mode, a transform aside, as the browser's resize observation measures it; pending until its first report, which the browser makes + * once it has laid the element out. It takes a new sample by observing the element again, which the browser reports with its next layout, whatever it reported before. + */ + static #observeLayoutSize({ request: { target }, notify, env: { window } }) { + let latest = { pending: true, value: null }; + // The border box a report gives, one for the element's box, in a list as engines give it now, or alone, as some gave it before. + const sampleOf = ({ borderBoxSize: sizes }) => { + const box = sizes[0] ?? sizes; + + return { pending: false, value: { inline: box.inlineSize, block: box.blockSize } }; + }; + + // The new sample asked for, which the next report answers, or null while none is. + let resampling = null; + const resampled = () => { + resampling?.resolve(); + resampling = null; + }; + const observer = new window.ResizeObserver(entries => { + latest = sampleOf(entries.at(-1)); + resampled(); + notify(); + }); + + try { + observer.observe(target, { box: 'border-box' }); + } catch (error) { + observer.disconnect(); + + throw error; + } + + return { + stop: () => { + observer.disconnect(); + resampled(); + }, + sample: () => latest, + resampleAsync: () => { + if (resampling === null) { + const asked = {}; + + asked.promise = new Promise(resolve => { + asked.resolve = resolve; + }); + resampling = asked; + observer.unobserve(target); + observer.observe(target, { box: 'border-box' }); + } + + return resampling.promise; + }, + }; + } + /** Whether a media query matches. */ static #observeMedia({ request: { arguments: { query } }, notify, env: { window } }) { const list = window.matchMedia(query); diff --git a/src/dom/BrowserVocabularyDeclarations.mjs b/src/dom/BrowserVocabularyDeclarations.mjs index 25636f2..c9b513a 100644 --- a/src/dom/BrowserVocabularyDeclarations.mjs +++ b/src/dom/BrowserVocabularyDeclarations.mjs @@ -74,6 +74,8 @@ const STYLE = { changes: 'partly-observable', misses: 'rules matching from elsew const RENDERING = [ANCESTRY_STYLE, RESIZE]; const RENDERING_MISSES = 'a stylesheet\'s rules hiding or showing it where its box keeps its size, as a box of no size, and content-visibility skipping it'; const MEASURED = { tolerance: LAYOUT_TOLERANCE }; +// What changes the size of a box as it is drawn without resizing its layout, which no resize observer reports. +const DRAWN_SIZE_MISSES = 'a transform or an animation, its own or an ancestor\'s, which changes the box as it is drawn without resizing it, and the size of an inline box, which flows as fragments no resize observer measures'; // An element's place among its siblings, which the structure of its tree decides, as its parent does. const SIBLINGS = { changes: 'partly-observable', misses: 'a detached tree inserted into another detached tree or into a shadow root', observations: [{ type: 'mutation', of: 'root', childList: true, subtree: true }] }; @@ -193,7 +195,8 @@ export class BrowserVocabularyDeclarations { implementing('rect', property('rect', 'Rectangle?', { updates: updatesOf({ ...GEOMETRY, ...MEASURED, observations: [RESIZE, SCROLLING, WINDOW_RESIZE] }) })), implementing('clientRect', property('clientRect', 'Rectangle?', { updates: updatesOf({ ...GEOMETRY, ...MEASURED, observations: [CLIENT_RESIZE, SCROLLING, WINDOW_RESIZE] }) })), - implementing('size', property('size', 'Size?', { updates: updatesOf({ ...MEASURED, observations: [RESIZE] }) })), + implementing('size', property('size', 'Size?', { updates: updatesOf({ changes: 'partly-observable', misses: DRAWN_SIZE_MISSES, ...MEASURED, observations: [RESIZE] }) })), + implementing('layoutSize', property('layoutSize', 'LogicalSize?', { updates: updatesOf({ reads: 'maintained', ...MEASURED, observations: [{ type: 'layoutSize', of: 'receiver' }] }) })), implementing('clientSize', property('clientSize', 'Size?', { updates: updatesOf({ changes: 'partly-observable', misses: 'a change that leaves its border box and its content box as they were, as its border and padding changing by the same amount', ...MEASURED, observations: [CLIENT_RESIZE] }) })), implementing('scroll', property('scroll', 'Scroll?', { updates: updatesOf({ @@ -374,6 +377,7 @@ export class BrowserVocabularyDeclarations { ]), structuredType('Size', { width: 'Number', height: 'Number' }), + structuredType('LogicalSize', { inline: 'Number', block: 'Number' }), structuredType('Rectangle', { left: 'Number', top: 'Number', right: 'Number', bottom: 'Number', width: 'Number', height: 'Number' }), structuredType('Selection', { start: 'Number', end: 'Number' }), // The document's selection as it stands: its type, whether it is collapsed, its ranges, the elements its anchor and its focus are in, and its first range. @@ -449,6 +453,7 @@ export class BrowserVocabularyDeclarations { observationType('mutation', 'invalidation', 'observeMutation', { identity: ['attributes', 'childList', 'subtree', 'characterData'] }), observationType('attachment', 'invalidation', 'observeAttachment'), observationType('intersection', 'maintained', 'observeIntersection', { identity: ['root', 'margin'] }), + observationType('layoutSize', 'maintained', 'observeLayoutSize'), observationType('media', 'invalidation', 'observeMedia', { identity: ['query'] }), observationType('pixelRatio', 'invalidation', 'observePixelRatio'), observationType('event', 'invalidation', 'observeEvents', { identity: ['types', 'capture'] }), diff --git a/src/dom/BrowserVocabularyImplementations.mjs b/src/dom/BrowserVocabularyImplementations.mjs index b41c7cb..07cad4e 100644 --- a/src/dom/BrowserVocabularyImplementations.mjs +++ b/src/dom/BrowserVocabularyImplementations.mjs @@ -29,6 +29,12 @@ const PIXELS = /^-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?px$/i; /** The media elements. */ const MEDIA_ELEMENTS = new Set(['audio', 'video']); +/** The elements whose box shows content of their own in place of their children's, laid out as one box whatever their display: replaced elements and form controls, as HTML renders them. */ +const REPLACED_ELEMENTS = new Set(['img', 'video', 'audio', 'canvas', 'iframe', 'embed', 'object', 'input', 'textarea', 'select', 'button', 'progress', 'meter', 'math']); + +/** The namespace of SVG's elements. */ +const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; + /** The platforms whose primary shortcut modifier is Meta, Command on their keyboards, by the name `navigator.userAgentData` gives them. */ const APPLE_PLATFORMS = new Set(['macOS', 'iOS']); @@ -73,6 +79,8 @@ export class BrowserVocabularyImplementations { devicePixelRatio: ({ receiver: window }) => window.devicePixelRatio, // The property reads the rectangle against the layout viewport, and rectRelativeTo against the element it is given. rect: ({ receiver: element, args: { relativeTo = null } }) => BrowserVocabularyImplementations.#rect(element, relativeTo), + // The size layout gives its border box, as the browser's resize observation last measured it, where it is laid out as one box. + layoutSize: ({ receiver: element, env: { window }, samples: [size] }) => (size === null || !BrowserVocabularyImplementations.#isLaidOutAsOneBox(element, window) ? null : size), size: ({ receiver: element }) => { const rect = BrowserVocabularyImplementations.boxOf(element); @@ -203,6 +211,16 @@ export class BrowserVocabularyImplementations { return element.isConnected && element.getClientRects().length > 0; } + /** + * Whether the element is laid out as one box, which a resize observer measures: it has a layout box, and isn't an inline box of text and elements, `display: inline` on an element that replaces its content with + * none of its own, which flows as fragments a resize observer reports as of no size. An element replaced by what it shows, as an image, a video or a form control, is one box whatever its display, and so is an + * SVG element, whose box a resize observer measures as its bounding box. + */ + static #isLaidOutAsOneBox(element, window) { + return BrowserVocabularyImplementations.#hasBox(element) + && (REPLACED_ELEMENTS.has(element.localName) || element.namespaceURI === SVG_NAMESPACE || window.getComputedStyle(element).display !== 'inline'); + } + /** * The element's border box, or null where it has no layout box. Its client rects answer both for nearly every element: none where it has no box, and one that is its bounding box * where it is laid out whole; an element split into several, as an inline one across lines, asks the browser for the box that bounds them. diff --git a/tests/DocumentExamples.test.js b/tests/DocumentExamples.test.js index e0cecea..b10b8cb 100644 --- a/tests/DocumentExamples.test.js +++ b/tests/DocumentExamples.test.js @@ -87,6 +87,7 @@ const DOCUMENTS = { 'spec/vocabulary.md': [ { about: 'a member of each kind', each: true, context: COMPARED }, { about: 'scrolling', each: true, context: COMPARED }, + { about: 'the size layout gives a box', each: true, context: COMPARED }, { about: 'built-in executions', each: true }, ], 'spec/evaluation.md': [], diff --git a/tests/Domql.browser.js b/tests/Domql.browser.js index 581abed..b6af046 100644 --- a/tests/Domql.browser.js +++ b/tests/Domql.browser.js @@ -68,24 +68,24 @@ describe('domql evaluateAsync in a browser', () => { it('follows the layout a browser decides, reporting a snapshot when the size changes', async () => { const snapshots = []; - const watch = domql.query('item.size', { item: inside }).watch(); + const watch = domql.query('item.layoutSize', { item: inside }).watch(); watch.subscribe('change', (sender, args) => snapshots.push(args.value)); watches.push(watch); await frame(); - expect(snapshots).toEqual([{ width: 200, height: 40 }]); + expect(snapshots).toEqual([{ inline: 200, block: 40 }]); inside.style.height = '60px'; await frame(); - expect(snapshots).toEqual([{ width: 200, height: 40 }, { width: 200, height: 60 }]); + expect(snapshots).toEqual([{ inline: 200, block: 40 }, { inline: 200, block: 60 }]); expect(watch.status).toBe('ready'); }); it('follows what a function call reads, the branch a changed condition selects in its body, and what it captures, made anew at each evaluation', async () => { const snapshots = []; - const watch = domql.query('let wide = item["data-wide"] == "yes"\nlet measure = function(box) if wide then box.size?.width ?? 0 else box.size?.height ?? 0 end end\nreturn measure(item)', { item: inside }).watch(); + const watch = domql.query('let wide = item["data-wide"] == "yes"\nlet measure = function(box) if wide then box.layoutSize?.inline ?? 0 else box.layoutSize?.block ?? 0 end end\nreturn measure(item)', { item: inside }).watch(); watch.subscribe('change', (sender, args) => snapshots.push(args.value)); watches.push(watch); @@ -302,7 +302,7 @@ describe('domql evaluateAsync in a browser', () => { it('stops reporting once it is disposed', async () => { const snapshots = []; - const watch = domql.query('item.size', { item: inside }).watch(); + const watch = domql.query('item.layoutSize', { item: inside }).watch(); watch.subscribe('change', (sender, args) => snapshots.push(args.value)); await frame(); @@ -310,7 +310,7 @@ describe('domql evaluateAsync in a browser', () => { inside.style.height = '80px'; await frame(); - expect(snapshots).toEqual([{ width: 200, height: 40 }]); + expect(snapshots).toEqual([{ inline: 200, block: 40 }]); }); describe('subscribe', () => { diff --git a/tests/Domql.test.js b/tests/Domql.test.js index e27dbc7..2a06ff0 100644 --- a/tests/Domql.test.js +++ b/tests/Domql.test.js @@ -1436,13 +1436,13 @@ describe('domql evaluates', () => { }); it('is the same whatever the options, the policy of a watch checked against it each time, and made again for bindings of other types or other selecting values', () => { - const query = domql.query('panel?.size', { panel }); + const query = domql.query('panel?.layoutSize', { panel }); const before = query.resolve(); expect(query.resolve({ watch: true, acceptPartialObservation: true })).toBe(before); expect(query.resolve({ watch: true })).toBe(before); expect(() => domql.query('panel.rect', { panel }).resolve({ watch: true })).toThrow(expect.objectContaining({ kind: 'validation', code: 'DOMQL3003', message: expect.stringContaining('accepts partial observation') })); - expect(domql.query('panel?.size', { panel: null }).resolve()).not.toBe(before); + expect(domql.query('panel?.layoutSize', { panel: null }).resolve()).not.toBe(before); expect(domql.query('panel.on(type) { button = it.button }', { panel, type: 'click' }).resolve()).not.toBe(domql.query('panel.on(type) { button = it.button }', { panel, type: 'pointerdown' }).resolve()); }); diff --git a/tests/dom/BrowserObservationImplementations.test.js b/tests/dom/BrowserObservationImplementations.test.js index 6e3e9ba..5f4d278 100644 --- a/tests/dom/BrowserObservationImplementations.test.js +++ b/tests/dom/BrowserObservationImplementations.test.js @@ -236,6 +236,92 @@ describe('BrowserObservationImplementations', () => { }); }); + describe('layoutSize', () => { + /** A window whose resize observer the test controls: it records what it observes, unobserves and disconnects, with the box it observes. */ + const createResizeWindow = () => { + const fake = { + observer: null, + ResizeObserver: class { + constructor(callback) { + this.callback = callback; + this.steps = []; + fake.observer = this; + } + + observe(target, options) { + this.steps.push(['observe', target, options]); + } + + unobserve(target) { + this.steps.push(['unobserve', target]); + } + + disconnect() { + this.steps.push(['disconnect']); + } + }, + }; + + return fake; + }; + + const element = document.createElement('div'); + const start = (fake, notify = () => {}) => BrowserObservationImplementations.implementations.observeLayoutSize({ request: { type: 'layoutSize', target: element, arguments: {} }, notify, env: { window: fake } }); + const report = (inlineSize, blockSize) => ({ borderBoxSize: [{ inlineSize, blockSize }] }); + + it('is pending until the browser first reports the element, and holds the border box of its latest report along its writing mode after', () => { + const fake = createResizeWindow(); + let changes = 0; + const observation = start(fake, () => changes++); + + expect(fake.observer.steps).toEqual([['observe', element, { box: 'border-box' }]]); + expect(observation.sample()).toEqual({ pending: true, value: null }); + + fake.observer.callback([report(10, 20), report(300, 40)]); + + expect(observation.sample()).toEqual({ pending: false, value: { inline: 300, block: 40 } }); + expect(changes).toBe(1); + }); + + it('reads a border box an engine reports alone, outside a list', () => { + const fake = createResizeWindow(); + const observation = start(fake); + + fake.observer.callback([{ borderBoxSize: { inlineSize: 50, blockSize: 12 } }]); + + expect(observation.sample()).toEqual({ pending: false, value: { inline: 50, block: 12 } }); + }); + + it('takes a new sample by observing the element again, settling at the report that follows, once for every ask before it, and settles one it waits for as it stops', async () => { + const fake = createResizeWindow(); + const observation = start(fake); + const settled = []; + + fake.observer.callback([report(100, 20)]); + + const first = observation.resampleAsync().then(() => settled.push('first')); + const second = observation.resampleAsync().then(() => settled.push('second')); + + expect(fake.observer.steps.slice(1)).toEqual([['unobserve', element], ['observe', element, { box: 'border-box' }]]); + + await Promise.resolve(); + expect(settled).toEqual([]); + + fake.observer.callback([report(120, 20)]); + await Promise.all([first, second]); + + expect(settled).toEqual(['first', 'second']); + expect(observation.sample()).toEqual({ pending: false, value: { inline: 120, block: 20 } }); + + const waiting = observation.resampleAsync(); + + observation.stop(); + + await expect(waiting).resolves.toBeUndefined(); + expect(fake.observer.steps.at(-1)).toEqual(['disconnect']); + }); + }); + describe('selector', () => { /** Starts the observation of what the selector reads in the document, and answers how often it has reported. */ const observe = selector => { diff --git a/tests/dom/BrowserVocabularyDeclarations.test.js b/tests/dom/BrowserVocabularyDeclarations.test.js index 311ed78..3e0363a 100644 --- a/tests/dom/BrowserVocabularyDeclarations.test.js +++ b/tests/dom/BrowserVocabularyDeclarations.test.js @@ -50,10 +50,11 @@ describe('BrowserVocabularyDeclarations', () => { it('declares the DOM\'s reference types, the views of an element and the structured types of its measurements and events', () => { expect(module.types.map(type => `${type.kind} ${type.name}${type.supertype === undefined ? '' : ` : ${type.supertype}`}${type.abstract ? ', abstract' : ''}`)).toEqual([ 'reference Node, abstract', 'reference Element : Node', 'reference Document : Node', 'reference DocumentFragment : Node', 'reference ShadowRoot : Node', 'reference Window', 'reference Shadow', 'reference Aria', 'reference Range', - 'structured Size', 'structured Rectangle', 'structured Selection', 'structured DocumentSelection', 'structured Grid', 'structured Scroll', 'structured ScrollAxis', 'structured Playback', 'structured Location', 'structured SizeLimits', 'structured File', 'structured ClipboardContent', 'structured ClipboardEntry', 'structured Listening', 'structured DomEvent', 'structured FocusEvent', 'structured InputEvent', 'structured ClipboardEvent', 'structured CompositionEvent', 'structured ToggleEvent', 'structured AnimationEvent', 'structured PointerEvent', 'structured TouchEvent', 'structured Touch', 'structured WheelEvent', 'structured KeyboardEvent', 'structured DragEvent', + 'structured Size', 'structured LogicalSize', 'structured Rectangle', 'structured Selection', 'structured DocumentSelection', 'structured Grid', 'structured Scroll', 'structured ScrollAxis', 'structured Playback', 'structured Location', 'structured SizeLimits', 'structured File', 'structured ClipboardContent', 'structured ClipboardEntry', 'structured Listening', 'structured DomEvent', 'structured FocusEvent', 'structured InputEvent', 'structured ClipboardEvent', 'structured CompositionEvent', 'structured ToggleEvent', 'structured AnimationEvent', 'structured PointerEvent', 'structured TouchEvent', 'structured Touch', 'structured WheelEvent', 'structured KeyboardEvent', 'structured DragEvent', ]); expect(module.types.filter(type => type.kind === 'structured').map(type => `${type.name} { ${type.members.filter(member => member.kind === 'property').map(member => `${member.name}: ${member.result}`).join(', ')} }`)).toEqual([ 'Size { width: Number, height: Number }', + 'LogicalSize { inline: Number, block: Number }', 'Rectangle { left: Number, top: Number, right: Number, bottom: Number, width: Number, height: Number }', 'Selection { start: Number, end: Number }', 'DocumentSelection { type: String, collapsed: Boolean, rangeCount: Number, anchorElement: Element?, focusElement: Element?, range: Range? }', @@ -89,7 +90,7 @@ describe('BrowserVocabularyDeclarations', () => { 'Node.children', 'Node.parent', 'Node.root', 'Node.host', 'Node.first', 'Node.all', 'Node.contains', 'Element.disabled', 'Element.readonly', 'Element.textEditable', 'Element.focused', 'Element.focusWithin', 'Element.displayed', 'Element.focusable', 'Element.hovered', 'Element.popoverOpen', 'Element.checked', 'Element.indeterminate', 'Element.autofilled', 'Element.localName', 'Element.classes', 'Element.text', 'Element.html', 'Element.value', 'Element.playback', 'Element.inlineStyle', 'Element.files', 'Element.sizeLimits', - 'Element.rect', 'Element.clientRect', 'Element.size', 'Element.clientSize', 'Element.scroll', 'Element.grid', 'Element.selection', 'Element.shadow', 'Element.aria', 'Element.direction', 'Element.attached', 'Element.hasChildren', 'Element.hasSelection', + 'Element.rect', 'Element.clientRect', 'Element.size', 'Element.layoutSize', 'Element.clientSize', 'Element.scroll', 'Element.grid', 'Element.selection', 'Element.shadow', 'Element.aria', 'Element.direction', 'Element.attached', 'Element.hasChildren', 'Element.hasSelection', 'Element.previousSibling', 'Element.nextSibling', 'Element.index', 'Element.hasPointerCapture', 'Element[]', 'Element.attribute', 'Element.class', 'Element.style', 'Element.intersects', 'Element.overlaps', 'Element.matches', 'Element.rectRelativeTo', 'Element.closest', 'Element.scrollContainer', 'Element.on', 'Element.dispatch', 'Element.focus', 'Element.scrollTo', 'Element.scrollBy', 'Element.scrollIntoView', 'Element.showPopover', 'Element.hidePopover', 'Element.showModal', 'Element.capturePointer', 'Element.releasePointer', 'Element.play', 'Element.pause', 'Element.mute', 'Element.unmute', 'Element.markIndeterminate', 'Element.clearIndeterminate', 'Element.replaceValue', 'Element.select', 'Element.ownAttribute', 'Element.ownClass', 'Element.ownStyle', 'Element.ownText', 'Element.ownFileSource', 'Element.close', @@ -134,7 +135,7 @@ describe('BrowserVocabularyDeclarations', () => { const measured = typeMembers.filter(({ member }) => member.updates?.tolerance !== undefined).map(({ type, member }) => `${nameOf(type, member)} within ${member.updates.tolerance}`); expect(measured).toEqual([ - 'Element.rect within 0.05', 'Element.clientRect within 0.05', 'Element.size within 0.05', 'Element.clientSize within 0.05', 'Element.scroll within 0.05', 'Element.grid within 0.05', 'Element.rectRelativeTo within 0.05', + 'Element.rect within 0.05', 'Element.clientRect within 0.05', 'Element.size within 0.05', 'Element.layoutSize within 0.05', 'Element.clientSize within 0.05', 'Element.scroll within 0.05', 'Element.grid within 0.05', 'Element.rectRelativeTo within 0.05', 'Window.size within 0.05', 'Window.scroll within 0.05', 'Range.rect within 0.05', ]); }); @@ -392,10 +393,10 @@ describe('BrowserVocabularyDeclarations', () => { expect([...new Set(named)].sort()).toEqual(module.observationTargets.map(target => target.name).sort()); }); - it('are maintained only for the member that reads maintained values', () => { + it('are maintained only for the members that read maintained values', () => { const maintained = evaluated.filter(declaration => declaration.updates.observations.some(observation => registry.getObservationType(observation.type).contract === 'maintained')); - expect(maintained.map(declaration => declaration.name)).toEqual(['intersects']); + expect(maintained.map(declaration => declaration.name)).toEqual(['layoutSize', 'intersects']); expect(maintained.every(declaration => declaration.updates.reads === 'maintained')).toBe(true); }); }); diff --git a/tests/dom/LayoutSize.browser.js b/tests/dom/LayoutSize.browser.js new file mode 100644 index 0000000..d8b7ea4 --- /dev/null +++ b/tests/dom/LayoutSize.browser.js @@ -0,0 +1,88 @@ +import { afterEach, beforeEach, describe, it, expect } from 'vitest'; +import { domql } from '#domql/domql.js'; + +/** Adds an element with the style to the document, which a real browser lays out. */ +const add = (style, parent = document.body) => { + const element = document.createElement('div'); + + element.style.cssText = style; + parent.append(element); + + return element; +}; + +/** The size layout gives a box, which each engine's resize observer reports, its first report included, in Chromium, Firefox and WebKit. */ +describe('layoutSize in a browser', () => { + beforeEach(() => { + document.body.style.margin = '0'; + }); + + afterEach(() => { + document.body.innerHTML = ''; + }); + + describe('the size layout gives a box', () => { + // Settles once the browser has laid out and painted twice, so a resize observer has reported what changed; a test ends with it, so the next one starts no observation while the browser still delivers + // the resize observer's reports, which it would report as undelivered. + const afterLayout = () => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); + + it('is its border box along the axes of its writing mode, as the resize observer measures it, pending until its first report', async () => { + const box = add('width: 120px; height: 40px; padding: 10px; border: 2px solid'); + const vertical = add('writing-mode: vertical-rl; width: 40px; height: 300px'); + + expect(await domql.query('{ box = box.layoutSize, vertical = vertical.layoutSize }', { box, vertical }).evaluateAsync()).toEqual({ + box: { inline: 144, block: 64 }, vertical: { inline: 300, block: 40 }, + }); + await afterLayout(); + }); + + it('leaves a transform aside, which changes the size a box is drawn at, and so a watch of size, which misses it, but not its layout', async () => { + const box = add('width: 200px; height: 50px; transform-origin: 0 0'); + + box.style.transform = 'scale(0.5)'; + + expect(await domql.query('{ drawn = box.size, laidOut = box.layoutSize }', { box }).evaluateAsync()).toEqual({ + drawn: { width: 100, height: 25 }, laidOut: { inline: 200, block: 50 }, + }); + await afterLayout(); + }); + + it('is null where the element is no one box: detached, not rendered, or an inline box of text, but an inline image and an SVG shape are one', async () => { + const hidden = add('display: none; width: 30px; height: 30px'); + const span = document.createElement('span'); + const image = document.createElement('img'); + const drawing = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + + span.textContent = 'words that flow'; + image.style.cssText = 'display: inline; width: 16px; height: 12px'; + drawing.innerHTML = ''; + document.body.append(span, image, drawing); + + const shape = drawing.firstElementChild; + + expect(await domql.query('{ detached = detached.layoutSize, hidden = hidden.layoutSize, span = span.layoutSize, image = image.layoutSize, shape = shape.layoutSize }', { detached: document.createElement('div'), hidden, span, image, shape }).evaluateAsync()).toEqual({ + detached: null, hidden: null, span: null, image: { inline: 16, block: 12 }, shape: { inline: 40, block: 10 }, + }); + await afterLayout(); + }); + + it('is watched from the size laid out first, under a transform too, and follows each resize, with no partial observation to accept', async () => { + const box = add('width: 200px; height: 50px; transform: scale(0.5)'); + const snapshots = []; + const watch = domql.query('box.layoutSize', { box }).watch({ schedule: 'immediate' }); + + watch.subscribe('change', (sender, args) => snapshots.push(args.value)); + await watch.readyAsync(); + + // Ready settles inside the resize observer's report, so the box is resized once the browser has delivered it. + await afterLayout(); + box.style.width = '240px'; + await afterLayout(); + box.style.transform = 'scale(2)'; + await afterLayout(); + watch.dispose(); + + expect(snapshots).toEqual([{ inline: 200, block: 50 }, { inline: 240, block: 50 }]); + }); + }); +}); diff --git a/tests/language/LanguageResolver.test.js b/tests/language/LanguageResolver.test.js index f88eeec..115c231 100644 --- a/tests/language/LanguageResolver.test.js +++ b/tests/language/LanguageResolver.test.js @@ -511,8 +511,15 @@ describe('LanguageResolver', () => { expect(error.message).toContain("'Element.rect' (which misses a move its own size"); }); + it('refuses a watch of the size a box is drawn at unless it accepts partial observation, since a transform changes it without resizing the box', () => { + const error = failure('DOMQL3003', 'panel.size', { panel }, { watch: true }); + + expect(error.message).toContain("'Element.size' (which misses a transform or an animation, its own or an ancestor's"); + expect(() => resolve('panel.size', { panel }, { watch: true, acceptPartialObservation: true })).not.toThrow(); + }); + it('lets a watch follow what is observable', () => { - expect(() => resolve('panel.size', { panel }, { watch: true })).not.toThrow(); + expect(() => resolve('panel.layoutSize', { panel }, { watch: true })).not.toThrow(); }); it('lists the declarations a request uses', () => { diff --git a/tests/vitest.engines.config.js b/tests/vitest.engines.config.js index 9e12bbe..7efe82a 100644 --- a/tests/vitest.engines.config.js +++ b/tests/vitest.engines.config.js @@ -4,13 +4,13 @@ import { defineConfig } from 'vitest/config'; const resolved = path => decodeURIComponent(new URL(path, import.meta.url).pathname); // The browser tests of what browser engines decide differently, run in Chromium, Firefox and WebKit: where a focus event inside a shadow root reaches and whether -// removing the focused element fires one, and where a box's scroll origin lies. `npm run test:engines` runs them. +// removing the focused element fires one, where a box's scroll origin lies, and what a resize observer first reports of a box, the size layout gives it. `npm run test:engines` runs them. export default defineConfig({ resolve: { alias: [{ find: '#domql/', replacement: resolved('../src/') }], }, test: { - include: ['dom/FocusChain.browser.js', 'dom/ReversedScrolling.browser.js'], + include: ['dom/FocusChain.browser.js', 'dom/ReversedScrolling.browser.js', 'dom/LayoutSize.browser.js'], browser: { enabled: true, provider: 'playwright', From 5d1e9fa8e37299acc86950c9dd8045283de4c83d Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Mon, 30 Nov 2026 03:30:39 +0200 Subject: [PATCH 03/15] feat(domql): hear autofill the page animates autofilled observes animationstart and animationcancel on its field, so a page whose style starts an animation on a field as the browser fills or empties it, as a rule for :autofill naming one does, is followed. DOMQL still writes no stylesheet into the page. D112 records it. --- CHANGELOG.md | 1 + VERSION-HISTORY.md | 2 ++ docs/decisions.md | 13 ++++++++++++ docs/features-status.md | 2 +- spec/vocabulary.md | 2 +- src/dom/BrowserVocabularyDeclarations.mjs | 4 +++- tests/dom/QueryEvaluator.test.js | 24 +++++++++++++++++++++++ 7 files changed, 45 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e1f386d..dab0ad7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ Each release of DOMQL's packages, newest first. The npm package `@formaui-net/do - An element's `layoutSize` answers the size layout gives its border box, along its writing mode's axes, `{ inline, block }`, a transform aside, from the browser's resize observer, and a watch follows every change of it. - A watch of an element's `size` is refused unless it accepts partial observation, since a transform changes the box as it is drawn with no observer reporting it. Watch `layoutSize`, or accept partial observation. +- A watch of `autofilled` follows an animation the page's style starts on a field as the browser fills or empties it. diff --git a/VERSION-HISTORY.md b/VERSION-HISTORY.md index 62a6366..6c3b182 100644 --- a/VERSION-HISTORY.md +++ b/VERSION-HISTORY.md @@ -22,6 +22,7 @@ Each entry says what its version breaks: ```domql box.layoutSize?.inline // the size layout gives the box along its line, a transform aside; NEXO3001 before, no such member box.size // the box as it is drawn; watched, DOMQL3003 unless the watch accepts partial observation, accepted before though a transform went unheard +field.autofilled // watched: follows an animation the page's style starts on the field as it is filled or emptied; heard only input, change and reset before ``` ```js @@ -35,6 +36,7 @@ domql.query('box.size', { box }).watch({ acceptPartialObservation: true }); // t - [`layoutSize`](spec/vocabulary.md#property-element-layoutsize) is the size layout gives an element's border box, along the axes of its writing mode, `inline` and `block`, a transform aside, as the browser's resize observation measures it. It reads a maintained observation of its own, [`layoutSize`](spec/vocabulary.md#observations-types), so it is observable, null where the element is laid out as no one box, and pending until the browser first reports it, as [D111](docs/decisions.md#d111) records. - [`size`](spec/vocabulary.md#property-element-size) is the box as it is drawn, as it was read, and partly observable: a transform or an animation, its own or an ancestor's, and the size of an inline box are missed, where it was called observable and missed them. +- [`autofilled`](spec/vocabulary.md#state-element-autofilled) observes `animationstart` and `animationcancel` on its field too, so a page whose style starts an animation on a field as the browser fills or empties it is followed, as [D112](docs/decisions.md#d112) records. **Breaking:** diff --git a/docs/decisions.md b/docs/decisions.md index c3e8b74..1e5c063 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -1716,3 +1716,16 @@ Each entry is one of three kinds: - **Declined:** - Making `size` the box as laid out. A synchronous read can't give the untransformed, fractional border box for every box, and `size` would then disagree with `rect`. - A maintained `size`. `evaluate` would answer null for it until the browser's first report, breaking every synchronous read of it. + + + +## D112 — `autofilled` follows an animation the page starts on a filled field + +*November 30, 2026* + +- **Kind:** Contract, extending [D17](#d17); a feature Forma's scripts need. +- **Decision:** `autofilled` also observes `animationstart` and `animationcancel` on its field. A page whose style starts an animation on a field as the browser fills or empties it, as a rule for `:autofill` naming one does, is then followed. It stays partly observable: a fill with no event and no such animation is still missed. +- **Why:** + - Forma now watches whether a field is autofilled from C#, to render its filled state. It relies on its own stylesheet's animation on `:autofill`, the one signal a browser gives for a fill it makes as the page loads. + - The observation reads only what the page's own style already does, so DOMQL still writes no stylesheet, as D17 requires. In Node, a watch of a field whose `:autofill` match changed with each animation reported `[false, true, false]`. +- **Declined:** an observation of DOMQL's own that writes the animation rule into the page, which D17 declined. diff --git a/docs/features-status.md b/docs/features-status.md index e836c88..38ca28a 100644 --- a/docs/features-status.md +++ b/docs/features-status.md @@ -67,7 +67,7 @@ Each feature, the contract that states it, its state in the implementation, and | The focused element, `Domql.document.activeElement`, through open shadow roots | [`activeElement`](../spec/vocabulary.md#property-document-activeelement) | Implemented | [`alpha.281`](../VERSION-HISTORY.md#v1-0-0-alpha-281) | | An element's `direction`, as `dir` decides it along its ancestry | [`direction`](../spec/vocabulary.md#property-element-direction) | Implemented | [`alpha.281`](../VERSION-HISTORY.md#v1-0-0-alpha-281) | | States `displayed` and `focusable` | [`displayed`](../spec/vocabulary.md#state-element-displayed), [`focusable`](../spec/vocabulary.md#state-element-focusable) | Implemented | [`alpha.281`](../VERSION-HISTORY.md#v1-0-0-alpha-281) | -| A control's `value`, and states `indeterminate` and `autofilled` | [`value`](../spec/vocabulary.md#property-element-value), [`indeterminate`](../spec/vocabulary.md#state-element-indeterminate), [`autofilled`](../spec/vocabulary.md#state-element-autofilled) | Implemented; no observation follows autofill itself, as [D17](decisions.md#d17) records | [`alpha.282`](../VERSION-HISTORY.md#v1-0-0-alpha-282) | +| A control's `value`, and states `indeterminate` and `autofilled` | [`value`](../spec/vocabulary.md#property-element-value), [`indeterminate`](../spec/vocabulary.md#state-element-indeterminate), [`autofilled`](../spec/vocabulary.md#state-element-autofilled) | Implemented; no observation of DOMQL's own follows autofill itself, as [D17](decisions.md#d17) records, and an animation the page's style starts on a field as it is filled or emptied is observed, as [D112](decisions.md#d112) records | [`alpha.282`](../VERSION-HISTORY.md#v1-0-0-alpha-282), [`preview.2`](../VERSION-HISTORY.md#v1-0-0-preview-2) | | An element's `text`, `html`, `localName`, `classes` and `inlineStyle[property]` | [`text`](../spec/vocabulary.md#property-element-text), [`html`](../spec/vocabulary.md#property-element-html), [`inlineStyle`](../spec/vocabulary.md#function-element-inlinestyle) | Implemented | [`alpha.282`](../VERSION-HISTORY.md#v1-0-0-alpha-282) | | A media element's `playback`, observed through its media events | [`playback`](../spec/vocabulary.md#property-element-playback) | Implemented | [`alpha.282`](../VERSION-HISTORY.md#v1-0-0-alpha-282) | | The document selection, `Domql.document.selection`, its `Range`, and an editable element's `selection` | [Document `selection`](../spec/vocabulary.md#property-document-selection), [`Range`](../spec/vocabulary.md#property-range-rect), [Element `selection`](../spec/vocabulary.md#property-element-selection) | Implemented; an element's `selection` and `hasSelection` observable, as [D20](decisions.md#d20) records | [`alpha.283`](../VERSION-HISTORY.md#v1-0-0-alpha-283) | diff --git a/spec/vocabulary.md b/spec/vocabulary.md index bcde012..b8697c3 100644 --- a/spec/vocabulary.md +++ b/spec/vocabulary.md @@ -1120,7 +1120,7 @@ Whether the Tab key reaches it, and in what order, is sequential focus navigatio **True when.** It matches `:autofill`, or `:-webkit-autofill` in a browser that knows no other: the browser filled its value, from a saved address or password, and the user has not edited it since -**Changes.** Partly observable: the user's input and changes in its tree are observed, which the browser fires as it fills a field the user chose a suggestion for; the browser filling a field on its own, as a password manager does as the page loads, fires no event and is not. No observation follows the filling itself, since one would write a stylesheet into the page, which watching never does +**Changes.** Partly observable: the user's input and changes in its tree are observed, which the browser fires as it fills a field the user chose a suggestion for; and so is an animation the page's style starts on it as it is filled or emptied, as a rule for `:autofill` naming one does, `animationstart` and `animationcancel`; the browser filling a field on its own, as a password manager does as the page loads, fires no event and is not, unless the page's style starts such an animation. No observation of DOMQL's own follows the filling itself, since one would write a stylesheet into the page, which watching never does diff --git a/src/dom/BrowserVocabularyDeclarations.mjs b/src/dom/BrowserVocabularyDeclarations.mjs index c9b513a..39b11c2 100644 --- a/src/dom/BrowserVocabularyDeclarations.mjs +++ b/src/dom/BrowserVocabularyDeclarations.mjs @@ -76,6 +76,8 @@ const RENDERING_MISSES = 'a stylesheet\'s rules hiding or showing it where its b const MEASURED = { tolerance: LAYOUT_TOLERANCE }; // What changes the size of a box as it is drawn without resizing its layout, which no resize observer reports. const DRAWN_SIZE_MISSES = 'a transform or an animation, its own or an ancestor\'s, which changes the box as it is drawn without resizing it, and the size of an inline box, which flows as fragments no resize observer measures'; +// An animation the page's style starts on a field as the browser fills it or empties it, as a rule for `:autofill` naming one does. +const AUTOFILL_ANIMATION = { type: 'event', of: 'receiver', types: ['animationstart', 'animationcancel'] }; // An element's place among its siblings, which the structure of its tree decides, as its parent does. const SIBLINGS = { changes: 'partly-observable', misses: 'a detached tree inserted into another detached tree or into a shadow root', observations: [{ type: 'mutation', of: 'root', childList: true, subtree: true }] }; @@ -191,7 +193,7 @@ export class BrowserVocabularyDeclarations { observations: [USER_INPUT, { type: 'mutation', of: 'root', attributes: ['checked', 'name', 'type', 'value'], childList: true, subtree: true }], }), }), - state('autofilled', 'autofilled', { updates: updatesOf({ changes: 'partly-observable', misses: 'the browser filling a field on its own, as a password manager does as the page loads, which fires no event', observations: [USER_INPUT] }) }), + state('autofilled', 'autofilled', { updates: updatesOf({ changes: 'partly-observable', misses: 'the browser filling a field on its own, as a password manager does as the page loads, which fires no event, where the page\'s style starts no animation on the field as it is filled or emptied', observations: [USER_INPUT, AUTOFILL_ANIMATION] }) }), implementing('rect', property('rect', 'Rectangle?', { updates: updatesOf({ ...GEOMETRY, ...MEASURED, observations: [RESIZE, SCROLLING, WINDOW_RESIZE] }) })), implementing('clientRect', property('clientRect', 'Rectangle?', { updates: updatesOf({ ...GEOMETRY, ...MEASURED, observations: [CLIENT_RESIZE, SCROLLING, WINDOW_RESIZE] }) })), diff --git a/tests/dom/QueryEvaluator.test.js b/tests/dom/QueryEvaluator.test.js index 24aebd9..eba0a16 100644 --- a/tests/dom/QueryEvaluator.test.js +++ b/tests/dom/QueryEvaluator.test.js @@ -623,6 +623,30 @@ describe('QueryEvaluator', () => { expect(read('e.autofilled', { e: document.getElementById('field') })).toBe(false); }); + + it('follows a field being filled and emptied where the style of the page starts an animation on it as it is, as a rule for :autofill does', async () => { + document.body.innerHTML = ''; + const field = document.getElementById('field'); + let isFilled = false; + const matches = field.matches.bind(field); + + field.matches = selector => (selector === ':autofill' || selector === ':-webkit-autofill' ? isFilled : matches(selector)); + + const watch = domql.query('e.autofilled', { e: field }).watch({ schedule: 'immediate', acceptPartialObservation: true }); + const values = []; + + watch.subscribe('change', (sender, args) => values.push(args.value)); + await watch.readyAsync(); + isFilled = true; + field.dispatchEvent(new window.Event('animationstart')); + await new Promise(resolve => setTimeout(resolve)); + isFilled = false; + field.dispatchEvent(new window.Event('animationcancel')); + await new Promise(resolve => setTimeout(resolve)); + watch.dispose(); + + expect(values).toEqual([false, true, false]); + }); }); describe('size limits and files', () => { From 7845e71e221f9c81052b52b26cc7732c9c4a3827 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Mon, 30 Nov 2026 03:31:01 +0200 Subject: [PATCH 04/15] feat(domql): answer an event source's occurrence An event source may declare answers, the type of what its subscription answers each occurrence with. deliver fulfils, once every subscription has applied the occurrence, with the first subscription's answer, its handler's return or what the promise it returns fulfils with, captured as that type. An answer the type refuses rejects with DOMQL5025, and answers on anything but an event source is refused with DOMQL4016. D113 records it. --- CHANGELOG.md | 1 + VERSION-HISTORY.md | 10 ++ docs/decisions.md | 22 +++++ docs/domql-design.md | 2 +- docs/features-status.md | 2 +- nuget/README.md | 2 + spec/behaviors.md | 9 ++ spec/errors.md | 2 + spec/vocabulary.md | 6 +- src/dom/Behaviors.mjs | 11 ++- src/dom/DispatchTable.mjs | 11 ++- src/dom/EventListener.mjs | 91 ++++++++++++++---- src/domql.d.ts | 11 ++- src/domql.js | 6 ++ tests/_types/usage.ts | 5 +- tests/dom/Behaviors.test.js | 96 ++++++++++++++++++- .../dom/BrowserVocabularyDeclarations.test.js | 2 +- tests/dom/DispatchTable.test.js | 22 +++-- 18 files changed, 267 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dab0ad7..bd3590c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ Each release of DOMQL's packages, newest first. The npm package `@formaui-net/do - An element's `layoutSize` answers the size layout gives its border box, along its writing mode's axes, `{ inline, block }`, a transform aside, from the browser's resize observer, and a watch follows every change of it. - A watch of an element's `size` is refused unless it accepts partial observation, since a transform changes the box as it is drawn with no observer reporting it. Watch `layoutSize`, or accept partial observation. - A watch of `autofilled` follows an animation the page's style starts on a field as the browser fills or empties it. +- An event source declaring `answers` is answered: `deliver` fulfils with its first subscription's answer, the handler's return or its promise's value, captured as the declared type, where it fulfilled with undefined. diff --git a/VERSION-HISTORY.md b/VERSION-HISTORY.md index 6c3b182..681ef51 100644 --- a/VERSION-HISTORY.md +++ b/VERSION-HISTORY.md @@ -32,12 +32,22 @@ domql.query('box.size', { box }).watch(); // DOMQL3 domql.query('box.size', { box }).watch({ acceptPartialObservation: true }); // the box as drawn, a transform missed until another change is observed ``` +```js +{ name: 'destinations', kind: 'function', invokedBy: 'host', requestKind: 'subscription', behavior: 'navigation', result: 'Request', answers: 'String?' } // an event source answered; NEXO4030 before + +const destination = await deliver('destinations', request); // the first subscription's answer, as String?; undefined before, whatever its handler returned +``` + **Vocabulary** - [`layoutSize`](spec/vocabulary.md#property-element-layoutsize) is the size layout gives an element's border box, along the axes of its writing mode, `inline` and `block`, a transform aside, as the browser's resize observation measures it. It reads a maintained observation of its own, [`layoutSize`](spec/vocabulary.md#observations-types), so it is observable, null where the element is laid out as no one box, and pending until the browser first reports it, as [D111](docs/decisions.md#d111) records. - [`size`](spec/vocabulary.md#property-element-size) is the box as it is drawn, as it was read, and partly observable: a transform or an animation, its own or an ancestor's, and the size of an inline box are missed, where it was called observable and missed them. - [`autofilled`](spec/vocabulary.md#state-element-autofilled) observes `animationstart` and `animationcancel` on its field too, so a page whose style starts an animation on a field as the browser fills or empties it is followed, as [D112](docs/decisions.md#d112) records. +**Modules** + +- [An event source is answered](spec/behaviors.md#behaviors-answers) where it declares `answers`, the type of the answer: each subscription's handler answers an occurrence with what it returns, or what its promise fulfils with, and `deliver`'s promise fulfils with the first subscription's answer, captured as that type, where it fulfilled with undefined. An answer the type refuses rejects with `DOMQL5025`, and `answers` declared by anything but an event source is refused with `DOMQL4016`, as [D113](docs/decisions.md#d113) records. + **Breaking:** - A watch of `size` is refused unless it accepts partial observation, DOMQL3003. Watch `layoutSize` where the size as laid out is what it needs, reading `inline` and `block` for `width` and `height` along a horizontal line, or pass `acceptPartialObservation: true` to keep the box as drawn. diff --git a/docs/decisions.md b/docs/decisions.md index 1e5c063..4eb4163 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -1729,3 +1729,25 @@ Each entry is one of three kinds: - Forma now watches whether a field is autofilled from C#, to render its filled state. It relies on its own stylesheet's animation on `:autofill`, the one signal a browser gives for a fill it makes as the page loads. - The observation reads only what the page's own style already does, so DOMQL still writes no stylesheet, as D17 requires. In Node, a watch of a field whose `:autofill` match changed with each animation reported `[false, true, false]`. - **Declined:** an observation of DOMQL's own that writes the animation rule into the page, which D17 declined. + + + +## D113 — An event source can be answered + +*November 30, 2026* + +- **Kind:** Contract, extending [D50](#d50); a feature Forma's scripts need. +- **Decision:** + - An event source may declare `answers`, the type of an answer, written as a declared binding's type is. DOMQL keeps it beside the source's request kind and gives Nexo the declaration without it. + - Each subscription's handler answers an occurrence with what it returns, or with what the promise it returns fulfils with. + - `deliver`'s promise fulfils, once every subscription has applied the occurrence, with the first subscription's answer, captured as the declared type through DOMQL's registry, as a binding of that type is. The other subscriptions' answers are not taken, so a subscription that only observes, answering nothing, fails no delivery. + - An answer the type refuses rejects with `DOMQL5025`, located at the subscription, and goes to the window's error reporting. `answers` on anything but an event source, or other than a string, is refused with `DOMQL4016` as the module is created. + - A notation that names no type is refused as the first answer is captured, with `DOMQL5025`: Nexo reads a binding's type only where a value is bound, so creating the module checks no more than that it is a string. +- **Why:** + - Forma's culture coordinator now asks .NET for a page's address in a culture before it navigates, and waits for the value. As an occurrence and a command answering it, that was a second crossing and a correlation of its own. As one answered delivery, it is the one round trip it is today. + - The acknowledgment already settled as the handler's promise did; carrying its value adds no new path, only the value. + - The first subscription's answer is deterministic, since subscriptions are called in the order they subscribed. +- **Declined:** + - A command the subscriber sends back. It needs an identity for each question, and a second crossing. + - Every subscription's answer, as a list. No caller asks several subscribers one question, and a list would make every answer's type a list. + - An untyped answer. A behavior would check what .NET sends itself, where DOMQL captures every other value that crosses into a module by its declared type. diff --git a/docs/domql-design.md b/docs/domql-design.md index ab9b783..e94ece0 100644 --- a/docs/domql-design.md +++ b/docs/domql-design.md @@ -91,7 +91,7 @@ Each operation makes one environment as it starts, frozen, holding its window, i A member reading the state a behavior offers is given Nexo with an implementation that wraps its own, adding the instance its environment's owner finds on its receiver, so Nexo calls it as any member. The `behavior` observation is kept beside the instances by the behavior's name and the receiver, its name alone since its identity can hold nothing of a module or an owner; a behavior of one name in two modules, or of two owners, tells both modules' observations, whose members read what changed for their own. An instance tells them as it starts, after its update, on both receivers where it moves, as it ends, and as its `notify` is called. -A subscription to a behavior's event source is kept beside the instances, by the module, the behavior and the source, then its owner and its receiver, and never by an instance, so it hears every instance there and outlives each. `deliver` closes over the instance's entry, whose receiver an update moves, so an occurrence goes to the receiver the instance runs on as it is delivered; the entry is marked ended as the instance ends, before its disposal runs. Delivering copies the receiver's subscriptions before handing the occurrence to the first, so one a handler adds or stops changes who hears the next occurrence, never this one, and joins their acknowledgments with `Promise.all` where more than one hears it; one subscription's acknowledgment is the delivery's own. In five paired rounds against the commit before it, in Chromium, a pointer move one subscription hears took 15 to 24% less time and allocated 13 to 19% less, about 0.5 µs and 450 bytes a move, and one four subscriptions hear measured within noise. An occurrence no subscription hears answers one rejection, `DOMQL5017` located at the behavior, made as the first is delivered and handled as it is made, and kept for the instance and its source until a subscription to the source listens for the instance's owner on its receiver, or the instance ends, since what it says is the same for each. An error made for each, whose stack Nexo writes as it makes it, had cost nearly all of the delivery: in five paired rounds against the commit before it, in Chromium, a pointer move no subscription hears took 0.20 µs rather than 13.95, and allocated 244 bytes rather than 4.7 KB. +A subscription to a behavior's event source is kept beside the instances, by the module, the behavior and the source, then its owner and its receiver, and never by an instance, so it hears every instance there and outlives each. `deliver` closes over the instance's entry, whose receiver an update moves, so an occurrence goes to the receiver the instance runs on as it is delivered; the entry is marked ended as the instance ends, before its disposal runs. Delivering copies the receiver's subscriptions before handing the occurrence to the first, so one a handler adds or stops changes who hears the next occurrence, never this one, and joins their acknowledgments with `Promise.all` where more than one hears it, fulfilling with the first's answer; one subscription's acknowledgment is the delivery's own. An answer is captured by the event listener of its subscription, as the type its source declares it answers, through the instance's registry, as a binding of that type is captured, so an answer reaches the behavior as data of that type, as every value crossing into module code does. In five paired rounds against the commit before it, in Chromium, a pointer move one subscription hears took 15 to 24% less time and allocated 13 to 19% less, about 0.5 µs and 450 bytes a move, and one four subscriptions hear measured within noise. An occurrence no subscription hears answers one rejection, `DOMQL5017` located at the behavior, made as the first is delivered and handled as it is made, and kept for the instance and its source until a subscription to the source listens for the instance's owner on its receiver, or the instance ends, since what it says is the same for each. An error made for each, whose stack Nexo writes as it makes it, had cost nearly all of the delivery: in five paired rounds against the commit before it, in Chromium, a pointer move no subscription hears took 0.20 µs rather than 13.95, and allocated 244 bytes rather than 4.7 KB. An event listener answers each event's acknowledgment from what its handler did: one promise, already fulfilled, shared by every event a handler applied as it returned, since it holds nothing of the event; a promise of its own only where the handler returned one, or the event waits while the listener starts, kept until it settles so disposal rejects it; and a rejected one, handled as it is made, where the event failed. In five paired rounds against the commit before it, projecting an event measured within the rounds' noise, a median of 111,000 events a second against 106,000 for one read of a panel; an acknowledgment of its own for every event had cost about a tenth. diff --git a/docs/features-status.md b/docs/features-status.md index 38ca28a..89f0ee3 100644 --- a/docs/features-status.md +++ b/docs/features-status.md @@ -107,7 +107,7 @@ Each feature, the contract that states it, its state in the implementation, and | An operation's owner, which every implementation receives in one environment for the operation | [The owner](../spec/behaviors.md#behaviors-the-owner), [the environment](../spec/vocabulary.md#extension-modules-environment) | Implemented, as [D47](decisions.md#d47) records | [`alpha.302`](../VERSION-HISTORY.md#v1-0-0-alpha-302) | | Commands to a running behavior, reaching its instance for their owner on their receiver | [Commands](../spec/behaviors.md#behaviors-commands) | Implemented, as [D48](decisions.md#d48) records | [`alpha.302`](../VERSION-HISTORY.md#v1-0-0-alpha-302) | | Occurrences a behavior offers, through event sources of its module bound to its owner and receiver | [Occurrences](../spec/behaviors.md#behaviors-occurrences) | Implemented, as [D49](decisions.md#d49) records | [`alpha.303`](../VERSION-HISTORY.md#v1-0-0-alpha-303) | -| A delivery acknowledged once each subscription applied it | [Acknowledgment](../spec/behaviors.md#behaviors-acknowledgment) | Implemented, as [D50](decisions.md#d50) records | [`alpha.303`](../VERSION-HISTORY.md#v1-0-0-alpha-303) | +| A delivery acknowledged once each subscription applied it, and answered where its source declares `answers` | [Acknowledgment](../spec/behaviors.md#behaviors-acknowledgment), [answers](../spec/behaviors.md#behaviors-answers) | Implemented, as [D50](decisions.md#d50) and [D113](decisions.md#d113) record | [`alpha.303`](../VERSION-HISTORY.md#v1-0-0-alpha-303), [`preview.2`](../VERSION-HISTORY.md#v1-0-0-preview-2) | | State a behavior offers, read by its module's members and followed through the `behavior` observation | [State](../spec/behaviors.md#behaviors-state) | Implemented, as [D52](decisions.md#d52) records | [`alpha.304`](../VERSION-HISTORY.md#v1-0-0-alpha-304) | | DOMQL's observations and frames for module code, `env.observe` and `env.frame`, a frame's writes before its reads | [The environment](../spec/vocabulary.md#extension-modules-environment) | Implemented, as [D53](decisions.md#d53) records | [`alpha.305`](../VERSION-HISTORY.md#v1-0-0-alpha-305) | | Queries from module code, `env.domql`, and no execution while a query is evaluated | [The environment](../spec/vocabulary.md#extension-modules-environment) | Implemented, as [D54](decisions.md#d54) records | [`alpha.305`](../VERSION-HISTORY.md#v1-0-0-alpha-305) | diff --git a/nuget/README.md b/nuget/README.md index 14615a3..7ec8b61 100644 --- a/nuget/README.md +++ b/nuget/README.md @@ -1282,6 +1282,8 @@ A behavior reports what happens, a drop, a move or a choice, as an occurrence: i `deliver` answers a promise that settles once each subscription has applied the occurrence, a handler's returned promise included, and rejects where none listens or one failed; a behavior that doesn't need to know may leave it. +A behavior that asks its caller what to do, as which address to go to, declares the answer's type on the source, `answers: 'String?'`. The first subscription's handler answers by returning the value, or a promise of it, and `deliver`'s promise fulfils with that answer, captured as the declared type, so the question and its answer are one delivery: `const destination = await deliver('destinations', request)` holds the subscription's answer. + ```js domql.registerModule(domql.createModule('Pickers', { types: [{ diff --git a/spec/behaviors.md b/spec/behaviors.md index d46d37a..bb495e4 100644 --- a/spec/behaviors.md +++ b/spec/behaviors.md @@ -66,6 +66,15 @@ What a behavior reports, a drop, a move, a placement or an editor's change, is a The `deliver` an event source of a module's own implementation receives answers the same acknowledgment, of its one subscription. + + +**Answers.** An event source that declares `answers`, the type of an answer in type notation, written as a [declared binding's](queries.md#making-a-query-declared-types) type is, is answered by its subscriptions, so a behavior that asks what to do learns it from the same delivery: + +- **What a subscription answers.** Its handler answers the occurrence with what it returns, or with what the promise it returns fulfils with. +- **What `deliver` answers.** Its promise fulfils, once every subscription has applied the occurrence, with the answer of the first to subscribe, captured as the declared type as a binding of that type is: its declared fields alone, null where the handler answers nothing and the type takes null. The answers of the subscriptions after it are not taken, so nothing checks them, as for a source that declares none. +- **An answer the type refuses** is the handler's failure: the promise rejects with `DOMQL5025`, located at the subscription, its `cause` the refusal, which goes to the window's error reporting as well. A notation that names no type is refused so too, as the first answer is captured, since a notation is read as a binding's type is, where a value is given. +- **A source that declares none** fulfils with undefined, whatever its handlers return. + ## Handling inside the native dispatch diff --git a/spec/errors.md b/spec/errors.md index fc596b5..0570258 100644 --- a/spec/errors.md +++ b/spec/errors.md @@ -85,6 +85,7 @@ A module refused as it is created or registered, a module loaded on request that | `DOMQL4013` | An event source of a behavior declaring an `impl` or parameters, which DOMQL carries out | | `DOMQL4014` | A module's loader answering no module of its name | | `DOMQL4015` | A module loaded that is neither registered nor given a loader | +| `DOMQL4016` | An `answers` declared by anything but an event source, or that is no string, or an empty one | @@ -118,3 +119,4 @@ A failure while a request is carried out, located in the query where it concerns | `DOMQL5022` | A maintained observation failing to take the new sample a refresh asked for, its failure the error's `cause` | | `DOMQL5023` | A module's loader failing, its failure the error's `cause` | | `DOMQL5024` | An occurrence a throttled subscription dropped for a later one | +| `DOMQL5025` | An answer a subscription gave an occurrence that the type its event source declares it answers refuses, or whose notation names no type, the refusal the error's `cause` | diff --git a/spec/vocabulary.md b/spec/vocabulary.md index b8697c3..9e7b6b0 100644 --- a/spec/vocabulary.md +++ b/spec/vocabulary.md @@ -1676,14 +1676,14 @@ A module declares an event source or an execution as a [host call](https://githu | Host call | `requestKind` | `executionMode` | Its `result` | Its implementation receives | It answers | | --- | --- | --- | --- | --- | --- | -| Event source | `subscription` | Refused | The type of each event it delivers, `@selected` where an event type selects it | `receiver`, `args`, `env` and `deliver`, which each event is handed to and which answers its [acknowledgment](behaviors.md#behaviors-acknowledgment) | An object whose `stop()` ends the listening | +| Event source | `subscription` | Refused | The type of each event it delivers, `@selected` where an event type selects it | `receiver`, `args`, `env` and `deliver`, which each event is handed to and which answers its [acknowledgment](behaviors.md#behaviors-acknowledgment), with the subscription's [answer](behaviors.md#behaviors-answers) where it declares `answers` | An object whose `stop()` ends the listening | | Event source of a behavior, declaring `behavior` | `subscription` | Refused | The type of each occurrence it delivers | Nothing: DOMQL carries it out, so it declares no `impl` and no parameters | — | | Once execution | `execution` | `once` | The type of its result | `receiver`, `args`, `env` and `signal`, which aborts it | Its result, or a promise of it | | Command, a once execution declaring `behavior` | `execution` | `once` | The type of its result | What a once execution receives, and `instance`, the running instance of its behavior | Its result, or a promise of it | | Continuous execution | `execution` | `continuous` | None; one declared is refused | `receiver`, `args`, `env`, `reportError`, which a failure while it runs is reported through, `deliver(source, value)`, which hands an [occurrence](behaviors.md#behaviors-occurrences) to its module's event source of that name, and `notify()`, which says the [state it offers](behaviors.md#behaviors-state) may have changed | An object whose `update(receiver, args)` applies new arguments and whose `dispose()` ends it, started before it returns | -A [command](behaviors.md#behaviors-commands) and an [event source of occurrences](behaviors.md#behaviors-occurrences) declare the behavior they reach as their `behavior`, the name of a continuous execution their module declares, which DOMQL keeps beside their request kind and gives Nexo the declaration without; so does a member the evaluator invokes reading the [state a behavior offers](behaviors.md#behaviors-state), whose implementation receives the behavior's `instance`. A behavior itself names none. +An event source, a behavior's or one its module implements, may declare `answers`, the type of what its subscription answers each event with, as [answers](behaviors.md#behaviors-answers) set out, which DOMQL keeps beside its request kind and gives Nexo the declaration without. A [command](behaviors.md#behaviors-commands) and an [event source of occurrences](behaviors.md#behaviors-occurrences) declare the behavior they reach as their `behavior`, the name of a continuous execution their module declares, which DOMQL keeps beside their request kind and gives Nexo the declaration without; so does a member the evaluator invokes reading the [state a behavior offers](behaviors.md#behaviors-state), whose implementation receives the behavior's `instance`. A behavior itself names none. -`domql.createModule` refuses, with a module error naming the declaration, the type it stands within and the key, of the code [errors](errors.md#errors-module) give, a host call whose `requestKind` is missing or neither `subscription` nor `execution`; an execution whose `executionMode` is missing or neither `once` nor `continuous`; an event source given an `executionMode`, or declaring no result, since each event it delivers is the value its subscription projects; a member the evaluator invokes given either key, an unnamed indexer named `[]`, as Nexo names it; a continuous execution that declares a result; a `behavior` on a continuous execution, or naming no behavior by a name; one naming no continuous execution of its module; and an event source of a behavior declaring an `impl` or parameters. `domql.registerModule` refuses a module declaring a host call its catalog holds nothing of, as a module `domql.createModule` did not make. So an execution whose mode was left out is refused as an execution missing its mode. +`domql.createModule` refuses, with a module error naming the declaration, the type it stands within and the key, of the code [errors](errors.md#errors-module) give, a host call whose `requestKind` is missing or neither `subscription` nor `execution`; an execution whose `executionMode` is missing or neither `once` nor `continuous`; an event source given an `executionMode`, or declaring no result, since each event it delivers is the value its subscription projects; a member the evaluator invokes given either key, an unnamed indexer named `[]`, as Nexo names it; a continuous execution that declares a result; a `behavior` on a continuous execution, or naming no behavior by a name; one naming no continuous execution of its module; an event source of a behavior declaring an `impl` or parameters; and an `answers` declared by anything but an event source, or other than a string of a type's notation. `domql.registerModule` refuses a module declaring a host call its catalog holds nothing of, as a module `domql.createModule` did not make. So an execution whose mode was left out is refused as an execution missing its mode. On a receiver of unknown type, a host call has no declaration yet, so its [candidates](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/host-calls.md#runtime-host-calls), every declaration that takes the call as it is written, say what it does, as they say who invokes it. Where they disagree on what they request, the request is refused as ambiguous with a validation error, located at the call. diff --git a/src/dom/Behaviors.mjs b/src/dom/Behaviors.mjs index dfc07dd..2278919 100644 --- a/src/dom/Behaviors.mjs +++ b/src/dom/Behaviors.mjs @@ -186,12 +186,13 @@ export class Behaviors { /** * Hands an occurrence of the running instance to every subscription of its source listening for its owner on its receiver, in the order they subscribed, each projecting it and calling its handler before this returns, - * and answers a promise that settles once each has applied it, or rejects with the first failure, and with `DOMQL5017` where none listens. + * and answers a promise that settles once each has applied it, fulfilled with the answer of the first to subscribe, whose answer alone is taken, which a source that answers nothing gives as undefined, or rejects + * with the first failure, and with `DOMQL5017` where none listens. * @param {RunningBehavior} running The instance delivering it. * @param {string} source The event source it is an occurrence of. * @param {unknown} value The occurrence. * @param {object} location Where the behavior stands, which a delivery no subscription hears is located at. - * @returns {Promise} + * @returns {Promise} */ deliver(running, source, value, location) { const receivers = this.#listening.get(Behaviors.#keyOf(running.module, running.name, source))?.get(running.owner)?.get(running.receiver); @@ -200,13 +201,13 @@ export class Behaviors { return this.#unheardBy(running, source, location); } - // One subscription's acknowledgment is the delivery's, fulfilled with nothing as it applies the occurrence, or rejected with its failure, as joining it alone would be. + // One subscription's acknowledgment is the delivery's, fulfilled with its answer as it applies the occurrence, or rejected with its failure, as joining it alone would be. if (receivers.length === 1) { return receivers[0](value); } - // A handler that subscribes or stops another as it receives the occurrence changes who hears the next, never this one. - return Promise.all([...receivers].map(receive => receive(value))).then(() => undefined); + // A handler that subscribes or stops another as it receives the occurrence changes who hears the next, never this one. The first to subscribe answers, and the others' answers are not taken. + return Promise.all([...receivers].map((receive, index) => receive(value, index === 0))).then(([answer]) => answer); } /** The rejection of an occurrence of the running instance's source that no subscription hears, made at the first and answered until a subscription to the source listens for it. */ diff --git a/src/dom/DispatchTable.mjs b/src/dom/DispatchTable.mjs index 542ca3c..1036ae8 100644 --- a/src/dom/DispatchTable.mjs +++ b/src/dom/DispatchTable.mjs @@ -123,9 +123,14 @@ export class DispatchTable { return null; } - const { invokedBy, requestKind, executionMode, impl, result, behavior } = member; + const { invokedBy, requestKind, executionMode, impl, result, behavior, answers } = member; const name = member.kind === 'indexer' && member.name == null ? '[]' : member.name; + // What an event source's subscription answers each event with, which the acknowledgment its source receives fulfils with; any other declaration answers nothing. + if (answers !== undefined && (invokedBy !== 'host' || requestKind !== 'subscription' || typeof answers !== 'string' || answers === '')) { + fail('DOMQL4016', 'An event source declares what its subscription answers each event with as answers, the type of the answer, written as the type of a declared binding is; nothing else answers', name, 'answers'); + } + if (invokedBy !== 'host') { for (const [key, value] of [['requestKind', requestKind], ['executionMode', executionMode]]) { if (value !== undefined) { @@ -182,7 +187,7 @@ export class DispatchTable { } } - return { requestKind, executionMode: executionMode ?? null, implementation: impl, type, module, behavior: behavior ?? null }; + return { requestKind, executionMode: executionMode ?? null, implementation: impl, type, module, behavior: behavior ?? null, answers: answers ?? null }; } /** Why a declaration's `behavior` is refused. */ @@ -203,7 +208,7 @@ export class DispatchTable { return impl === undefined ? declaration : { ...declaration, impl: input => impl({ ...input, instance: behaviors?.find(module, behavior, input.env?.owner ?? null, input.receiver) ?? null }) }; } - const { requestKind, executionMode, impl, behavior, ...declaration } = member; + const { requestKind, executionMode, impl, behavior, answers, ...declaration } = member; return declaration; } diff --git a/src/dom/EventListener.mjs b/src/dom/EventListener.mjs index 09861d6..1fc248a 100644 --- a/src/dom/EventListener.mjs +++ b/src/dom/EventListener.mjs @@ -5,7 +5,7 @@ import { NexoError } from '@formaui-net/nexo'; -/** A promise of an event's acknowledgment, with what settles it. @typedef {{ promise: Promise, resolve: () => void, reject: (error: unknown) => void }} Acknowledgment */ +/** A promise of an event's acknowledgment, with what settles it, fulfilled with the subscription's answer where its source declares one. @typedef {{ promise: Promise, resolve: (answer?: unknown) => void, reject: (error: unknown) => void }} Acknowledgment */ export class EventListener { #evaluator; @@ -21,6 +21,10 @@ export class EventListener { #handler; #reportError; + /** What finds, for the prepared call, what captures the answer the handler gives each event; and what captures it for the source listened to, null where it answers nothing. */ + #answerOf; + #answer = null; + /** What carries out the subscription's reactions to an event's projected value, answering a promise of each one's result, or null for a subscription that has none. @type {((value: unknown) => readonly Promise[]) | null} */ #react; @@ -70,6 +74,8 @@ export class EventListener { * @param {(pointer: string) => object} dependencies.getLocation Where a pointer into the subscription's definition stands, which a failure to start is located at. * @param {import('./Observations.mjs').Observations} dependencies.observations The observations of the window, which the projections hold sessions on. * @param {(error: unknown) => void} dependencies.reportError The environment's error reporting, which a failure of the handler reaches. + * @param {(call: object) => ((answer: unknown) => unknown) | null} [dependencies.answerOf] What captures the answer the handler gives each event, as the type the prepared call's event source declares it answers with, or null + * where it declares none; an acknowledgment then fulfils with the answer captured, where it fulfils with nothing. * @param {(sender: EventListener, args: object) => unknown} dependencies.handler Receives the event listener and, for each event, `status: 'ready'` with its projected result as `value`, and the promises of its reactions' * results as `reactions` where it has reactions, or `status: 'failed'` with the `error` that capturing or projecting it raised. What it returns is not awaited. * @param {((value: unknown) => readonly Promise[]) | null} [dependencies.react] Carries out the subscription's reactions to an event's projected value, within its delivery; null where it has none. @@ -77,8 +83,9 @@ export class EventListener { * @param {{ set: (callback: () => void, delay: number) => unknown, clear: (timer: unknown) => void }} [dependencies.timers] The window's timers, which a throttle waits on. * @param {AbortSignal} [dependencies.signal] Disposes the event listener when it aborts. */ - constructor({ evaluator, sourceOf, getLocation, observations, reportError, handler, react = null, throttle = null, timers, signal }) { + constructor({ evaluator, sourceOf, getLocation, observations, reportError, handler, answerOf = () => null, react = null, throttle = null, timers, signal }) { this.#evaluator = evaluator; + this.#answerOf = answerOf; this.#react = react; this.#throttle = throttle; this.#timers = timers; @@ -173,11 +180,13 @@ export class EventListener { this.#sourceCall = call; this.#preparedCall = call; + this.#answer = this.#answerOf(call); const start = this.#sourceOf(call); - // Each event is projected during its delivery, captured as its type declares before anything else reads it, and answers its acknowledgment, which a source may leave. - const deliver = event => this.#receive(event); + // Each event is projected during its delivery, captured as its type declares before anything else reads it, and answers its acknowledgment, which a source may leave. A source whose subscriptions answer says + // whether this one's answer is taken, as it is the first to subscribe; one of a module's own has this subscription alone, whose answer is. + const deliver = (event, isAnswerTaken = true) => this.#receive(event, isAnswerTaken); let sourceHandle; @@ -200,20 +209,22 @@ export class EventListener { * and keeps those retained before it, and the event listener goes on listening. A projection refused because a module registered since made the resolution stale is made again through the subscription prepared again. * Nothing it does throws into the source that delivers the event. */ - #receive(event) { + #receive(event, isAnswerTaken) { if (this.#status === 'disposed') { return EventListener.#rejected(this.#ended()); } try { - return this.#project(event); + return this.#project(event, isAnswerTaken ? this.#answer : null); } catch (error) { return EventListener.#rejected(error); } } - /** Projects the event and has its handler called, now or once the caller holds the event listener, answering the promise that settles once the handler has applied it. */ - #project(event) { + /** + * Projects the event and has its handler called, now or once the caller holds the event listener, answering the promise that settles once the handler has applied it, with its answer captured where it is taken. + */ + #project(event, answer) { let projection = this.#evaluator.project(this.#preparedCall, event, { observations: this.#observations, consumer: this }); if (projection.error?.code === 'NEXO2040') { @@ -251,10 +262,10 @@ export class EventListener { if (this.#react !== null) { const reactions = this.#react(projection.value); - return this.#runOrHold(() => this.#call({ status: 'ready', value: projection.value, reactions })); + return this.#runOrHold(() => this.#call({ status: 'ready', value: projection.value, reactions }, answer)); } - return this.#hand(true, () => this.#call({ status: 'ready', value: projection.value })); + return this.#hand(true, () => this.#call({ status: 'ready', value: projection.value }, answer)); } /** @@ -323,9 +334,9 @@ export class EventListener { const acknowledgment = {}; acknowledgment.promise = new Promise((resolve, reject) => { - acknowledgment.resolve = () => { + acknowledgment.resolve = answer => { this.#acknowledgments.delete(acknowledgment); - resolve(); + resolve(answer); }; acknowledgment.reject = error => { this.#acknowledgments.delete(acknowledgment); @@ -355,6 +366,22 @@ export class EventListener { return NexoError.evaluation('DOMQL5020', `The subscription failed to apply the occurrence: ${cause?.message ?? String(cause)}`, this.#getLocation(this.#preparedCall.pointer), { cause }); } + /** + * The answer the handler gave an event, captured by the capture given, as the type its source declares it answers with, as a binding of that type is captured. One that type refuses is the handler's failure, + * `DOMQL5025` located at the subscription, its cause the refusal, which goes to the environment's error reporting as a failure of the handler does. + */ + #captureAnswer(capture, answer) { + try { + return capture(answer); + } catch (cause) { + const error = NexoError.evaluation('DOMQL5025', `The subscription answered the occurrence with a value its event source's declared answer refuses: ${cause?.message ?? String(cause)}`, this.#getLocation(this.#preparedCall.pointer), { cause }); + + this.#reportError(error); + + throw error; + } + } + /** A promise rejected with the failure, handled, so a source that leaves it is never reported for it. */ static #rejected(error) { const promise = Promise.reject(error); @@ -395,9 +422,10 @@ export class EventListener { /** * Calls the handler with the event listener and the event's arguments, unless it is disposed, and answers the promise that settles once the handler has applied the event: as it returns, or as the promise it returns - * fulfils. A failure of the handler, thrown or rejected, goes to the environment's error reporting, and never back to the handler; it rejects the promise, as a failed event the handler received does. + * fulfils, with its answer captured where it is taken, the capture given. A failure of the handler, thrown or rejected, goes to the environment's error reporting, and never back to the handler; it rejects the + * promise, as a failed event the handler received does. */ - #call(args) { + #call(args, answer = null) { if (this.#status === 'disposed') { return EventListener.#rejected(this.#ended()); } @@ -413,14 +441,43 @@ export class EventListener { } if (typeof result?.then !== 'function') { - return args.status === 'ready' ? EventListener.#applied : EventListener.#rejected(this.#failed(args.error)); + if (args.status !== 'ready') { + return EventListener.#rejected(this.#failed(args.error)); + } + + if (answer === null) { + return EventListener.#applied; + } + + try { + return Promise.resolve(this.#captureAnswer(answer, result)); + } catch (error) { + return EventListener.#rejected(error); + } } - // A handler applies the event once the promise it returned fulfils, unless the event listener ends first. + // A handler applies the event once the promise it returned fulfils, unless the event listener ends first, which settled the acknowledgment already, and answers it with what the promise fulfils with. const acknowledgment = this.#acknowledge(); + const applied = value => { + if (this.#status === 'disposed') { + return; + } + + if (args.status !== 'ready') { + acknowledgment.reject(this.#failed(args.error)); + } else if (answer === null) { + acknowledgment.resolve(); + } else { + try { + acknowledgment.resolve(this.#captureAnswer(answer, value)); + } catch (error) { + acknowledgment.reject(error); + } + } + }; try { - result.then(() => (args.status === 'ready' ? acknowledgment.resolve() : acknowledgment.reject(this.#failed(args.error))), error => { + result.then(applied, error => { this.#reportError(error); acknowledgment.reject(this.#failed(error)); }); diff --git a/src/domql.d.ts b/src/domql.d.ts index a6518fb..fb147c1 100644 --- a/src/domql.d.ts +++ b/src/domql.d.ts @@ -571,11 +571,11 @@ export interface DomqlMemberImplementationInput { readonly samples?: readonly unknown[]; /** * An event source: the function each event is handed to, `deliver(event)`. A continuous execution: the function each occurrence is handed to, `deliver(source, value)`, by the name of its module's event source. Each - * answers a promise that settles once each subscription has applied what it delivered, and never throws. + * answers a promise that settles once each subscription has applied what it delivered, fulfilled with the first subscription's answer where the event source declares `answers`, and with undefined otherwise, and never throws. */ readonly deliver?: { - (event: unknown): Promise; - (source: string, value: unknown): Promise; + (event: unknown): Promise; + (source: string, value: unknown): Promise; }; /** A once execution: the signal that aborts it. */ readonly signal?: AbortSignal; @@ -612,6 +612,11 @@ export interface DomqlMemberDeclaration { * An event source of occurrences declares no `impl` and no parameters. */ behavior?: string; + /** + * An event source: the type its subscription answers each event with, in type notation, written as a declared binding's type is, as `String?` or `Culture.Destination?`. The acknowledgment its `deliver` answers fulfils + * with the first subscription's answer, its handler's return or what the promise it returns fulfils with, captured as that type. + */ + answers?: string; /** The form its arguments take where it has parameters, an optional one included: one for each parameter, in order, the required ones before the optional ones, or one options object whose fields supply them; a function alone takes it. */ arguments?: 'positional' | 'options'; /** Its parameters; a property takes none. */ diff --git a/src/domql.js b/src/domql.js index 6e19c25..17a7cc1 100644 --- a/src/domql.js +++ b/src/domql.js @@ -496,6 +496,11 @@ class Domql { return { set: (callback, delay) => window.setTimeout(callback, delay), clear: timer => window.clearTimeout(timer) }; } + /** What captures a subscription's answer as the type its event source declares it answers with, through DOMQL's registry, as a binding of that type is captured; null where the source answers nothing. */ + static #answerOf(notation) { + return notation === null ? null : answer => Domql.#moduleRegistry.createBindings({ answer }, { types: { answer: notation } }).readValue('answer'); + } + /** * Listens to the subscription's event source from the call on, so an event that follows the call is heard, and answers the event listener; a source that cannot start fails the call. * Each event is captured and projected through the object expression that follows the source, in the task the event is delivered in, and the handler receives the event listener and the result, or the failure. The source's receiver and arguments are evaluated once, as listening starts. @@ -536,6 +541,7 @@ class Domql { observations: Domql.#getObservations(window), reportError: Domql.#createErrorReporter(window), handler, + answerOf: call => Domql.#answerOf(DispatchTable.get(call.declaration).answers), react, throttle: throttle ?? null, timers: throttle === undefined ? undefined : Domql.#timersOf(window), diff --git a/tests/_types/usage.ts b/tests/_types/usage.ts index 1d2b452..38126ff 100644 --- a/tests/_types/usage.ts +++ b/tests/_types/usage.ts @@ -268,6 +268,7 @@ const ownedWatch: DomqlWatch = domql.query('panel.children.count // An event source of a behavior names it, and the behavior hands it each occurrence, awaiting its acknowledgment where it needs one. const drops: DomqlMemberDeclaration = { name: 'drops', kind: 'function', invokedBy: 'host', requestKind: 'subscription', behavior: 'dropZone', result: 'Domql.Element' }; +const destinations: DomqlMemberDeclaration = { name: 'destinations', kind: 'function', invokedBy: 'host', requestKind: 'subscription', behavior: 'dropZone', result: 'String', answers: 'String?' }; const dropZone: DomqlMemberDeclaration = { name: 'dropZone', kind: 'function', @@ -276,7 +277,7 @@ const dropZone: DomqlMemberDeclaration = { executionMode: 'continuous', impl: ({ receiver, deliver }) => { const drop = async (event: Event) => { - const applied: Promise | undefined = deliver?.('drops', event.target); + const applied: Promise | undefined = deliver?.('drops', event.target); await applied; }; @@ -519,4 +520,4 @@ const listed: DomqlDefinitionNode = { kind: 'list', items: [{ kind: 'literal', v const last: DomqlDefinitionNode = { kind: 'indexerAccess', receiver: { kind: 'local', name: 'rows' }, argument: { kind: 'fromEndIndex', offset: { kind: 'literal', value: 1 } } }; const imported: DomqlDefinition = { version: 38, imports: [{ module: 'Domql' }], expression: { kind: 'memberAccess', receiver: { kind: 'namespace', name: 'Domql' }, name: 'document' } }; -export { routing, following, painting, styled, trapped, counting, drops, dropZone, release, owned, released, ownedCount, ownedWatch, bound, version, specificationVersion, languageVersion, formatted, formattedText, kind, typeText, count, anything, waited, shorthand, selected, selectedAsync, selectedWatch, key, listening, status, snapshot, failure, ready, refreshed, viewed, viewStatus, viewReady, smaller, held, livingSnapshot, livingReady, livingRefreshed, watchedAgain, keptAgain, clicking, source, moved, stepped, trapping, reported }; +export { routing, following, painting, styled, trapped, counting, drops, destinations, dropZone, release, owned, released, ownedCount, ownedWatch, bound, version, specificationVersion, languageVersion, formatted, formattedText, kind, typeText, count, anything, waited, shorthand, selected, selectedAsync, selectedWatch, key, listening, status, snapshot, failure, ready, refreshed, viewed, viewStatus, viewReady, smaller, held, livingSnapshot, livingReady, livingRefreshed, watchedAgain, keptAgain, clicking, source, moved, stepped, trapping, reported }; diff --git a/tests/dom/Behaviors.test.js b/tests/dom/Behaviors.test.js index ac10b77..1573297 100644 --- a/tests/dom/Behaviors.test.js +++ b/tests/dom/Behaviors.test.js @@ -285,8 +285,8 @@ describe('Behaviors\' occurrences', () => { const hostCall = (name, overrides) => ({ name, kind: 'function', invokedBy: 'host', ...overrides }); /** - * A module of a zone behavior, `zone(label)`, whose instance delivers what `drop(key)` and `hover(key)` give it to its event sources `drops` and `hovers`, and its deliver as it was given; and `beats`, an event - * source of its own implementation, whose deliver the tests keep. + * A module of a zone behavior, `zone(label)`, whose instance delivers what `drop(key)`, `hover(key)` and `ask(key)` give it to its event sources `drops`, `hovers` and `asks`, the last answered with a drop, and keeps + * its deliver as it was given; and `beats`, an event source of its own implementation, whose deliver the tests keep. */ const zonesModule = () => isolated.createModule('Zones', { types: [ @@ -302,6 +302,7 @@ describe('Behaviors\' occurrences', () => { label, deliver, drop: key => deliver('drops', { key, label: instance.label }), hover: key => deliver('hovers', { key, label: instance.label }), + ask: key => deliver('asks', { key, label: instance.label }), update: (receiver, next) => Object.assign(instance, next), dispose: () => {}, }; @@ -313,6 +314,7 @@ describe('Behaviors\' occurrences', () => { }), hostCall('drops', { requestKind: 'subscription', behavior: 'zone', result: 'Drop' }), hostCall('hovers', { requestKind: 'subscription', behavior: 'zone', result: 'Drop' }), + hostCall('asks', { requestKind: 'subscription', behavior: 'zone', result: 'Drop', answers: 'Zones.Drop?' }), ], }, ], @@ -570,6 +572,65 @@ describe('Behaviors\' occurrences', () => { expect(reported).toEqual([expect.objectContaining({ message: 'broken handler' })]); }); + it('fulfils with the answer of the first subscription to a source that answers, captured as the type it declares, once every subscription has applied the occurrence', async () => { + let finish; + let isSettled = false; + + listen('asks', { zone }, {}, args => ({ key: `${args.value.key}!`, label: 'first', extra: true })); + listen('asks', { zone }, {}, () => new Promise(resolve => { + finish = resolve; + }).then(() => ({ key: 'second', label: 'second' }))); + // A later subscription's answer is never taken, so one the type would refuse fails nothing. + listen('asks', { zone }, {}, () => ({ key: 3 })); + run({ zone }); + + const answered = zones[0].ask('a'); + + answered.then(() => { + isSettled = true; + }); + await Promise.resolve(); + expect(isSettled).toBe(false); + + finish(); + await expect(answered).resolves.toEqual({ key: 'a!', label: 'first' }); + expect(reported).toEqual([]); + }); + + it('takes no answer a handler gives once its subscription has ended, which rejected the occurrence with DOMQL5017 as it ended', async () => { + let finish; + const { listener } = listen('asks', { zone }, {}, () => new Promise(resolve => { + finish = resolve; + })); + + run({ zone }); + + const answered = zones[0].ask('a'); + + listener.dispose(); + finish({ key: 3 }); + + await expect(answered).rejects.toMatchObject({ code: 'DOMQL5017' }); + await Promise.resolve(); + expect(reported).toEqual([]); + }); + + it('answers with what the promise its handler returns fulfils with, null where the handler answers nothing, and rejects an answer its type refuses with DOMQL5025, reporting it', async () => { + listen('asks', { zone }, {}, ({ value: { key } }) => { + if (key === 'none') { + return undefined; + } + + return key === 'wrong' ? { key: 3, label: 'wrong' } : Promise.resolve({ key, label: 'later' }); + }); + run({ zone }); + + await expect(zones[0].ask('a')).resolves.toEqual({ key: 'a', label: 'later' }); + await expect(zones[0].ask('none')).resolves.toBeNull(); + await expect(zones[0].ask('wrong')).rejects.toMatchObject({ kind: 'evaluation', code: 'DOMQL5025', cause: expect.objectContaining({ code: 'NEXO2045' }) }); + expect(reported).toEqual([expect.objectContaining({ code: 'DOMQL5025' })]); + }); + it('rejects where no subscription listens, or one ends before it applies the occurrence, with DOMQL5017', async () => { run({ zone }); @@ -693,6 +754,29 @@ describe('Behaviors\' occurrences', () => { await expect(deliver(2)).rejects.toMatchObject({ code: 'DOMQL5017' }); expect(received).toEqual([1]); }); + + it('answers an event an event source of a module\'s own delivers with its subscription\'s answer, where the source declares one', async () => { + let deliver; + + isolated.registerModule(isolated.createModule('Questions', { + types: [{ + name: 'QuestionElements', kind: 'extension', target: 'Domql.Element', + members: [hostCall('questions', { + requestKind: 'subscription', result: 'Number', answers: 'Number?', + impl: ({ deliver: delivers }) => { + deliver = delivers; + + return { stop: () => {} }; + }, + })], + }], + })); + + const questions = isolated.query('import Questions\nzone:questions()', { zone }).subscribe((sender, args) => args.value * 2); + + await expect(deliver(21)).resolves.toBe(42); + questions.dispose(); + }); }); describe('a behavior\'s event source', () => { @@ -720,6 +804,14 @@ describe('Behaviors\' occurrences', () => { }); }); + it('is the one declaration that answers, refused where anything else declares answers, or answers no type by its notation, with DOMQL4016', () => { + const refusal = 'An event source declares what its subscription answers each event with as answers, the type of the answer, written as the type of a declared binding is; nothing else answers'; + + expect(refusalOf([lamp, hostCall('switch', { requestKind: 'execution', executionMode: 'once', behavior: 'lamp', result: 'Number', answers: 'Number' })])).toEqual({ code: 'DOMQL4016', message: refusal, module: 'Desk', type: 'DeskElements', declaration: 'switch', declarationKey: 'answers' }); + expect(refusalOf([lamp, { name: 'brightness', kind: 'property', result: 'Number', answers: 'Number' }]).code).toBe('DOMQL4016'); + expect(refusalOf([lamp, hostCall('glows', { requestKind: 'subscription', behavior: 'lamp', result: 'Number', answers: '' })]).code).toBe('DOMQL4016'); + }); + it('is refused where its behavior is no continuous execution of its module', () => { expect(refusalOf([lamp, hostCall('glows', { requestKind: 'subscription', behavior: 'lantern', result: 'Number' })]).code).toBe('DOMQL4012'); }); diff --git a/tests/dom/BrowserVocabularyDeclarations.test.js b/tests/dom/BrowserVocabularyDeclarations.test.js index 3e0363a..e090b35 100644 --- a/tests/dom/BrowserVocabularyDeclarations.test.js +++ b/tests/dom/BrowserVocabularyDeclarations.test.js @@ -292,7 +292,7 @@ describe('BrowserVocabularyDeclarations', () => { result: '@selected', parameters: [{ name: 'type', type: 'String', fixed: true, selects: 'type', selector: 'event' }, { name: 'options', type: 'Listening?', required: false, default: null, nulls: 'accept' }], }); - expect(DispatchTable.get(member)).toEqual({ requestKind: 'subscription', executionMode: null, implementation: undefined, type: type.name, module: 'Domql', behavior: null }); + expect(DispatchTable.get(member)).toEqual({ requestKind: 'subscription', executionMode: null, implementation: undefined, type: type.name, module: 'Domql', behavior: null, answers: null }); } expect(module.typeSelectors).toEqual([{ name: 'event' }]); diff --git a/tests/dom/DispatchTable.test.js b/tests/dom/DispatchTable.test.js index 591cce0..b3a112a 100644 --- a/tests/dom/DispatchTable.test.js +++ b/tests/dom/DispatchTable.test.js @@ -33,13 +33,23 @@ describe('DispatchTable', () => { }); const [beats, mark, size] = module.members; - expect(DispatchTable.get(beats)).toEqual({ requestKind: 'subscription', executionMode: null, implementation: start, type: null, module: 'Desk', behavior: null }); - expect(DispatchTable.get(mark)).toEqual({ requestKind: 'execution', executionMode: 'once', implementation: execute, type: null, module: 'Desk', behavior: null }); + expect(DispatchTable.get(beats)).toEqual({ requestKind: 'subscription', executionMode: null, implementation: start, type: null, module: 'Desk', behavior: null, answers: null }); + expect(DispatchTable.get(mark)).toEqual({ requestKind: 'execution', executionMode: 'once', implementation: execute, type: null, module: 'Desk', behavior: null, answers: null }); expect(DispatchTable.get(size)).toBeUndefined(); expect([beats, mark].map(declaration => ['requestKind', 'executionMode', 'impl'].some(key => key in declaration))).toEqual([false, false]); expect(typeof size.impl).toBe('function'); }); + it('keeps the type an event source answers each event with, and gives Nexo the declaration without it', () => { + const module = DispatchTable.createModule('Desk', { + members: [hostCall({ name: 'asks', requestKind: 'subscription', result: 'Number', answers: 'String?', impl: () => ({ stop: () => {} }) })], + }); + const [asks] = module.members; + + expect(DispatchTable.get(asks).answers).toBe('String?'); + expect(Object.keys(asks)).not.toContain('answers'); + }); + it('keeps a host call standing within a type, and one declaration standing in several types for each declaration the module makes of it', () => { const start = () => ({ stop: () => {} }); const beats = hostCall({ name: 'beats', requestKind: 'subscription', result: 'Number', impl: start }); @@ -52,17 +62,17 @@ describe('DispatchTable', () => { }); const [lamp, fan, extension] = module.types; - expect(DispatchTable.get(lamp.members[0])).toEqual({ requestKind: 'subscription', executionMode: null, implementation: start, type: 'Lamp', module: 'Desk', behavior: null }); - expect(DispatchTable.get(fan.members[1])).toEqual({ requestKind: 'subscription', executionMode: null, implementation: start, type: 'Fan', module: 'Desk', behavior: null }); + expect(DispatchTable.get(lamp.members[0])).toEqual({ requestKind: 'subscription', executionMode: null, implementation: start, type: 'Lamp', module: 'Desk', behavior: null, answers: null }); + expect(DispatchTable.get(fan.members[1])).toEqual({ requestKind: 'subscription', executionMode: null, implementation: start, type: 'Fan', module: 'Desk', behavior: null, answers: null }); expect(DispatchTable.get(fan.members[0])).toBeUndefined(); - expect(DispatchTable.get(extension.members[0])).toEqual({ requestKind: 'execution', executionMode: 'continuous', implementation: undefined, type: 'DeskElements', module: 'Desk', behavior: null }); + expect(DispatchTable.get(extension.members[0])).toEqual({ requestKind: 'execution', executionMode: 'continuous', implementation: undefined, type: 'DeskElements', module: 'Desk', behavior: null, answers: null }); expect('impl' in lamp.members[0]).toBe(false); }); it('keeps a host call declared without an implementation, resolved against and never carried out', () => { const [mark] = DispatchTable.createModule('Desk', { members: [hostCall({ requestKind: 'execution', executionMode: 'continuous' })] }).members; - expect(DispatchTable.get(mark)).toEqual({ requestKind: 'execution', executionMode: 'continuous', implementation: undefined, type: null, module: 'Desk', behavior: null }); + expect(DispatchTable.get(mark)).toEqual({ requestKind: 'execution', executionMode: 'continuous', implementation: undefined, type: null, module: 'Desk', behavior: null, answers: null }); }); it('refuses a host call whose request kind is missing or unknown', () => { From f0b6e514880332be3e4846c49fb1d8bd041ef484 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:56:55 +0200 Subject: [PATCH 05/15] build(domql): run on Nexo 1.0.0-preview.4 DOMQL depends on Nexo's 1.0.0-preview.4, which its lock installs, and describes itself on language 1.0.0-preview.3. A refusal of root says that a binding named root is read as ~root. Every link into Nexo's documents follows the pin to the new tag. D114 records it. --- CHANGELOG.md | 3 +- CLAUDE.md | 6 ++-- CONTRIBUTING.md | 4 +-- README.md | 6 ++-- VERSION-HISTORY.md | 21 +++++++++----- docs/decisions.md | 33 +++++++++++++++------- docs/domql-design.md | 4 +-- docs/features-status.md | 20 +++++++------- nuget/README.md | 10 +++---- package-lock.json | 8 +++--- package.json | 2 +- spec/README.md | 8 +++--- spec/api.md | 4 +-- spec/errors.md | 4 +-- spec/evaluation.md | 8 +++--- spec/events.md | 6 ++-- spec/executions.md | 6 ++-- spec/nodes-and-shadow-trees.md | 2 +- spec/queries.md | 12 ++++---- spec/results.md | 4 +-- spec/terms.md | 4 +-- spec/vocabulary.md | 50 +++++++++++++++++----------------- spec/watches.md | 6 ++-- tests/Domql.test.js | 6 ++-- 24 files changed, 129 insertions(+), 108 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd3590c..c7cc9e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,12 +9,13 @@ Each release of DOMQL's packages, newest first. The npm package `@formaui-net/do ## `1.0.0-preview.4` -*Unreleased · specification `1.0.0-preview.2` · Nexo language `1.0.0-preview.1` · definition format 38* +*Unreleased · specification `1.0.0-preview.2` · Nexo language `1.0.0-preview.3` · definition format 38* - An element's `layoutSize` answers the size layout gives its border box, along its writing mode's axes, `{ inline, block }`, a transform aside, from the browser's resize observer, and a watch follows every change of it. - A watch of an element's `size` is refused unless it accepts partial observation, since a transform changes the box as it is drawn with no observer reporting it. Watch `layoutSize`, or accept partial observation. - A watch of `autofilled` follows an animation the page's style starts on a field as the browser fills or empties it. - An event source declaring `answers` is answered: `deliver` fulfils with its first subscription's answer, the handler's return or its promise's value, captured as the declared type, where it fulfilled with undefined. +- Runs on Nexo's language `1.0.0-preview.3`, from Nexo's release `1.0.0-preview.4`, as the [version history](VERSION-HISTORY.md#v1-0-0-preview-2) sets out: a refusal of `root` written where no object expression encloses it, or read other than through its fields, says that a binding named root is read as `~root`. `domql.info.versions.language` reports `1.0.0-preview.3`. diff --git a/CLAUDE.md b/CLAUDE.md index 357c373..328fce5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,9 +10,9 @@ Read the documents that govern the affected contract: | Document | Authority | | --- | --- | -| [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md) | Nexo's two contracts, at the release DOMQL builds against: the language's, what a query means, and the runtime's, how DOMQL as its host binds, resolves, evaluates and registers modules | +| [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md) | Nexo's two contracts, at the release DOMQL builds against: the language's, what a query means, and the runtime's, how DOMQL as its host binds, resolves, evaluates and registers modules | | [DOMQL specification](spec/README.md) | DOMQL's module and DOMQL as host: queries, nodes and shadow trees, the built-in vocabulary, evaluation, watching, results, events, executions, and the public API, one document per subject | -| [Nexo design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/nexo-design.md) | How Nexo is built: its stages, modules, evaluation and tooling | +| [Nexo design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/nexo-design.md) | How Nexo is built: its stages, modules, evaluation and tooling | | [DOMQL design](docs/domql-design.md) | How DOMQL is built: its architecture, resolution, sessions, watching, comparing and patching, the C# half, and the decisions not taken | | [Status](docs/features-status.md) | What is implemented, the migration to Nexo, the planned capabilities, open decisions and deferred work | | [Decisions](docs/decisions.md) | Each decision taken without stopping to ask, with why and what was declined, for review | @@ -47,7 +47,7 @@ Add a folder when a new responsibility needs one. Keep dependencies in this dire - `dom/` may depend on Nexo and `snapshots/`. - `snapshots/` may depend on Nexo. -The language is Nexo, the package `@formaui-net/nexo`, which DOMQL imports by its name and installs from npm, at the release `package.json` declares as the lowest it works with and its lock installs, so a change reaches DOMQL only when that version moves to a release that holds it; with `NEXO_SOURCE` naming a checkout, `build.ps1` links that checkout's working tree in the package's place instead. A change to the language is made there, and a change DOMQL needs of it in both repositories together, with `NEXO_SOURCE` set, moving the version once Nexo releases it. Link Nexo's documents at the release's tag, as `https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md`, so they move with it; the link test reads them from a checkout of [FormaUI/Nexo](https://github.com/FormaUI/Nexo) beside this one, named `formaui-net.Nexo`. +The language is Nexo, the package `@formaui-net/nexo`, which DOMQL imports by its name and installs from npm, at the release `package.json` declares as the lowest it works with and its lock installs, so a change reaches DOMQL only when that version moves to a release that holds it; with `NEXO_SOURCE` naming a checkout, `build.ps1` links that checkout's working tree in the package's place instead. A change to the language is made there, and a change DOMQL needs of it in both repositories together, with `NEXO_SOURCE` set, moving the version once Nexo releases it. Link Nexo's documents at the release's tag, as `https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md`, so they move with it; the link test reads them from a checkout of [FormaUI/Nexo](https://github.com/FormaUI/Nexo) beside this one, named `formaui-net.Nexo`. Pass the window and document into DOM code; do not read globals there. Importing the language layer and resolving a query must work without a DOM. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 23e6420..528c397 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,7 +14,7 @@ You'll need: - PowerShell to run the build scripts. - The .NET SDK pinned in `nuget/global.json`. -DOMQL is written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md), which it installs from npm, `@formaui-net/nexo`, at the release `package.json` declares and its lock installs. Its link test reads Nexo's documents at that release's tag from a checkout of [FormaUI/Nexo](https://github.com/FormaUI/Nexo) beside this one, so clone it beside this repository under the name the build looks for: +DOMQL is written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md), which it installs from npm, `@formaui-net/nexo`, at the release `package.json` declares and its lock installs. Its link test reads Nexo's documents at that release's tag from a checkout of [FormaUI/Nexo](https://github.com/FormaUI/Nexo) beside this one, so clone it beside this repository under the name the build looks for: ```sh git clone https://github.com/FormaUI/Nexo.git formaui-net.Nexo @@ -49,7 +49,7 @@ Run the full build from the repository root: | `CHANGELOG.md` | Each release of the packages and what it changed | | `.sandbox/` | Your own work that stays out of the repository, which Git ignores: experiments, notes, scratch and temporary files, and benchmark baselines | -The [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md) defines the language and its runtime, and the [DOMQL specification](spec/README.md) the DOM vocabulary, how queries are carried out, and the public API. The [Nexo design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/nexo-design.md) and the [DOMQL design](docs/domql-design.md) set out how each is built. If a change affects either contract, update the relevant document before implementing it. The [status overview](docs/features-status.md) tracks what is implemented, what is being built, and what remains. +The [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md) defines the language and its runtime, and the [DOMQL specification](spec/README.md) the DOM vocabulary, how queries are carried out, and the public API. The [Nexo design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/nexo-design.md) and the [DOMQL design](docs/domql-design.md) set out how each is built. If a change affects either contract, update the relevant document before implementing it. The [status overview](docs/features-status.md) tracks what is implemented, what is being built, and what remains. ## Develop a change diff --git a/README.md b/README.md index a4149d3..69c13c1 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ **A declarative approach to managing the DOM.** -DOMQL is a JavaScript library for querying the DOM, allowing you to read information from a document once or observe it as it changes. Its queries are written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md). +DOMQL is a JavaScript library for querying the DOM, allowing you to read information from a document once or observe it as it changes. Its queries are written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md). -> **Preview.** No breaking redesign is planned, and a version that breaks what the one before it allowed says how to migrate. The runtime, `1.0.0-preview.4`, implements DOMQL's specification `1.0.0-preview.2` on Nexo's language `1.0.0-preview.1`, definition version 38. DOMQL declares the DOM as types of its own. It is published to npm and NuGet, as [installing it](#install) sets out, and you can also [build and try it locally](#build-and-try-it). See [the status overview](docs/features-status.md), and [what 1.0 requires](docs/features-status.md#what-1-0-requires). +> **Preview.** No breaking redesign is planned, and a version that breaks what the one before it allowed says how to migrate. The runtime, `1.0.0-preview.4`, implements DOMQL's specification `1.0.0-preview.2` on Nexo's language `1.0.0-preview.3`, definition version 38. DOMQL declares the DOM as types of its own. It is published to npm and NuGet, as [installing it](#install) sets out, and you can also [build and try it locally](#build-and-try-it). See [the status overview](docs/features-status.md), and [what 1.0 requires](docs/features-status.md#what-1-0-requires). ## Features @@ -144,7 +144,7 @@ A JavaScript callback gives none of this by itself. A restricted JavaScript API, | --- | --- | | [Library guide](nuget/README.md) | Install DOMQL, learn the language by example and use the API | | [DOMQL specification](spec/README.md) | Queries, the DOM's vocabulary, evaluating and watching a query, its results, events, executions, and the API | -| [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md) | The language DOMQL is written in, and its runtime, at the release DOMQL builds against | +| [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md) | The language DOMQL is written in, and its runtime, at the release DOMQL builds against | | [Version history](VERSION-HISTORY.md) | Each version of DOMQL, with the features it added and what it changed | | [Changelog](CHANGELOG.md) | Each release of the packages and what it changed | | [Design](docs/domql-design.md) | How DOMQL is built, and the decisions it did not take | diff --git a/VERSION-HISTORY.md b/VERSION-HISTORY.md index 681ef51..49c87b9 100644 --- a/VERSION-HISTORY.md +++ b/VERSION-HISTORY.md @@ -17,12 +17,13 @@ Each entry says what its version breaks: ## `1.0.0-preview.2` -*Unreleased · Nexo language `1.0.0-preview.1` · definition format 38* +*Unreleased · Nexo language `1.0.0-preview.3` · definition format 38* ```domql box.layoutSize?.inline // the size layout gives the box along its line, a transform aside; NEXO3001 before, no such member box.size // the box as it is drawn; watched, DOMQL3003 unless the watch accepts partial observation, accepted before though a transform went unheard field.autofilled // watched: follows an animation the page's style starts on the field as it is filled or emptied; heard only input, change and reset before +root.first("a") // NEXO2018, now saying that a binding named root is read as ~root, as ~root.first("a") reads it ``` ```js @@ -38,12 +39,18 @@ domql.query('box.size', { box }).watch({ acceptPartialObservation: true }); // t const destination = await deliver('destinations', request); // the first subscription's answer, as String?; undefined before, whatever its handler returned ``` +DOMQL moves to Nexo's language `1.0.0-preview.3`, by way of `1.0.0-preview.2`, which Nexo's release `1.0.0-preview.4` carries, as [D114](docs/decisions.md#d114) records. Nexo's [language history](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/LANGUAGE-HISTORY.md#v1-0-0-preview-3) sets out its own changes by version; the one below is the one a query meets. + **Vocabulary** - [`layoutSize`](spec/vocabulary.md#property-element-layoutsize) is the size layout gives an element's border box, along the axes of its writing mode, `inline` and `block`, a transform aside, as the browser's resize observation measures it. It reads a maintained observation of its own, [`layoutSize`](spec/vocabulary.md#observations-types), so it is observable, null where the element is laid out as no one box, and pending until the browser first reports it, as [D111](docs/decisions.md#d111) records. - [`size`](spec/vocabulary.md#property-element-size) is the box as it is drawn, as it was read, and partly observable: a transform or an animation, its own or an ancestor's, and the size of an inline box are missed, where it was called observable and missed them. - [`autofilled`](spec/vocabulary.md#state-element-autofilled) observes `animationstart` and `animationcancel` on its field too, so a page whose style starts an animation on a field as the browser fills or empties it is followed, as [D112](docs/decisions.md#d112) records. +**Queries** + +- A `root` written where no object expression encloses it, NEXO2018, and one read other than through its fields, NEXO3012 and NEXO3017, say that a binding named root is read as `~root`. + **Modules** - [An event source is answered](spec/behaviors.md#behaviors-answers) where it declares `answers`, the type of the answer: each subscription's handler answers an occurrence with what it returns, or what its promise fulfils with, and `deliver`'s promise fulfils with the first subscription's answer, captured as that type, where it fulfilled with undefined. An answer the type refuses rejects with `DOMQL5025`, and `answers` declared by anything but an event source is refused with `DOMQL4016`, as [D113](docs/decisions.md#d113) records. @@ -114,13 +121,13 @@ const updates = { changes: 'observable', reads: 'maintained', observations: [{ t typeOf: value => undefined // NEXO5002 as a binding asks it; answer null ``` -DOMQL moves to Nexo's language `1.0.0-preview.1`, by way of `1.0.0-beta.40` and `1.0.0-beta.41`, as [D76](docs/decisions.md#d76), [D87](docs/decisions.md#d87) and [D108](docs/decisions.md#d108) record, and follows its rule that a property names what its receiver is, has or is in, and a function does work: DOMQL's states are properties, as D87 records, and its executions are named by their verbs, as [D88](docs/decisions.md#d88) records. Nexo's [language history](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/LANGUAGE-HISTORY.md#v1-0-0-preview-1) sets out its own changes by version; those below are the ones a query, a caller and a module meet. +DOMQL moves to Nexo's language `1.0.0-preview.1`, by way of `1.0.0-beta.40` and `1.0.0-beta.41`, as [D76](docs/decisions.md#d76), [D87](docs/decisions.md#d87) and [D108](docs/decisions.md#d108) record, and follows its rule that a property names what its receiver is, has or is in, and a function does work: DOMQL's states are properties, as D87 records, and its executions are named by their verbs, as [D88](docs/decisions.md#d88) records. Nexo's [language history](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/LANGUAGE-HISTORY.md#v1-0-0-preview-1) sets out its own changes by version; those below are the ones a query, a caller and a module meet. **Vocabulary** - [Focus is followed into open shadow roots](spec/vocabulary.md#observations-types): `focused`, `focusWithin`, `activeElement` and a selector testing focus report a move between two elements of one open shadow root, which they missed, since its events reach no further than the root, and the focused element's removal, which Firefox and WebKit fire no event for, as [D90](docs/decisions.md#d90) records. - [`scroll`'s offset](spec/vocabulary.md#property-element-scroll) runs as the box's style says, a reversed flex container's included, and stays within its range, so an elastic overscroll past either end reads as that end. -- [States](spec/vocabulary.md#states) are Boolean properties, read without a call, as Nexo's [states and tests](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/vocabulary.md#vocabulary-boolean-functions) set out: an element's `disabled`, `readonly`, `textEditable`, `focusWithin`, `displayed`, `focusable`, `popoverOpen`, `checked`, `indeterminate` and `autofilled`, the document's `visible`, and the ARIA view's `checked` and `disabled`, each a function before. +- [States](spec/vocabulary.md#states) are Boolean properties, read without a call, as Nexo's [states and tests](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/vocabulary.md#vocabulary-boolean-functions) set out: an element's `disabled`, `readonly`, `textEditable`, `focusWithin`, `displayed`, `focusable`, `popoverOpen`, `checked`, `indeterminate` and `autofilled`, the document's `visible`, and the ARIA view's `checked` and `disabled`, each a function before. - Five states take new names as they become properties: an element's `hover` and `focus` are `hovered` and `focused`, the document's `focus` is `focused`, and the window's `share` and `clipboard` are `canShare` and `hasClipboard`. - A state is read through its module as before, `Domql.checked(it)`, and filtered by with a body, `rows.where(it.checked)`; a reference to one, `rows.where(Domql.checked)`, is refused (NEXO3076), since only a function has one. @@ -129,7 +136,7 @@ DOMQL moves to Nexo's language `1.0.0-preview.1`, by way of `1.0.0-beta.40` and - Nexo's own members that make a value of their receiver are functions: a number's `round()`, `floor()`, `ceiling()`, `truncate()` and `abs()`, a text's `trim()`, `lowercase()` and `uppercase()`, and a list's `reverse()`, `distinct()` and `flatten()`, each a property before. - A letter right after a number makes one invalid token, NEXO1000, so `1else` is refused, where it read as `1` and `else`. - A number is written in hexadecimal, octal or binary too, `0xFF`, `0o17` and `0b1010`, and a `_` may stand between two digits of any number, `1_000_000`, where `0xFF` read as `0` and a member written without its dot, NEXO1011. -- [`and` and `or`](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/expressions.md#logical-expressions-negations-and-groups-type) share a type only where their value is used: `it.attached and "here" or "away"` is a `String`, where it was refused. +- [`and` and `or`](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/expressions.md#logical-expressions-negations-and-groups-type) share a type only where their value is used: `it.attached and "here" or "away"` is a `String`, where it was refused. - A conversion of a value of `Any` converts by the type the value turns out to be, failing with NEXO5053 where nothing converts it, where it was refused at resolution. - A computed name through a namespace reads as it does after `@`: `Domql.["window"]` is `Domql.window`. - [A query declares its bindings' types](spec/queries.md#making-a-query-declared-types), `domql.query(text, bindings, { types })`, capturing data as a module's structured type, a map as a dictionary, where every binding was typed from its value. @@ -155,7 +162,7 @@ DOMQL moves to Nexo's language `1.0.0-preview.1`, by way of `1.0.0-beta.40` and **Results** - [A selection](spec/queries.md#selecting-a-result) steps into a dictionary's `entries` and a pair's `key` and `value`, the form [a result holds them](spec/results.md#results-collections) in, where a path into either was refused. -- `domql.format` writes a negated number literal as the number, `-(-1)` as `1`, a call's arguments after a block's `end` on lines of their own, and an empty line between a body's last local and its `return`, at every level, as Nexo's [canonical bodies](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/definition.md#bodies-definition-and-canonical-text) set out. +- `domql.format` writes a negated number literal as the number, `-(-1)` as `1`, a call's arguments after a block's `end` on lines of their own, and an empty line between a body's last local and its `return`, at every level, as Nexo's [canonical bodies](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/definition.md#bodies-definition-and-canonical-text) set out. - Data a result holds nesting deeper than 1,000 levels is refused, NEXO5052, and a `sum` or a `sequence` no finite number holds, NEXO5020. **Modules** @@ -163,7 +170,7 @@ DOMQL moves to Nexo's language `1.0.0-preview.1`, by way of `1.0.0-beta.40` and - [A delivery inside a handler](spec/behaviors.md#behaviors-occurrences) reaches every subscription before the one around it goes on, so a later subscription hears it first, and [an acknowledgment](spec/behaviors.md#behaviors-acknowledgment) rejects at the first failure while others may still be applying the occurrence, as [D93](docs/decisions.md#d93) records; neither changed, the specification promised more. - [A kept value beside an outside writer](spec/vocabulary.md#execution-element-owned-writes-yielding) is judged by a heuristic, and [a committed position](spec/vocabulary.md#execution-element-owned-writes-framework) is let go of once its host confirms the render, not the occurrence's acknowledgment, as [D94](docs/decisions.md#d94) records. - [A transient measurement's read](spec/vocabulary.md#extension-modules-environment) is synchronous and writes nothing, and [a module's state per document](spec/vocabulary.md#extension-modules-state-per-document) is one for each copy of its code, as [D98](docs/decisions.md#d98) and [D99](docs/decisions.md#d99) record. -- [A member reading maintained values](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/members.md) declares a result that can be null, NEXO4071, since it reads as null until its first sample arrives. +- [A member reading maintained values](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/members.md) declares a result that can be null, NEXO4071, since it reads as null until its first sample arrives. - A module's `typeOf` answering nothing is a fault, NEXO5002. - A fixed parameter is required and takes no default, NEXO4072, and an observation takes no expression or predicate parameter, NEXO4055. - A module error names a declaration only by a name that is a string. @@ -684,7 +691,7 @@ DOMQL moves to Nexo's language `1.0.0-beta.15`, which settles what Nexo's status - **Membership compares by key equality alone.** `contains`, `indexOf`, `distinct` and `distinctBy` take numbers, strings, Booleans, references and null, so a list of elements works as before, and one of objects, lists or values of `Any` is refused (NEXO3083), where it was compared by identity. - **A result path is checked wherever it is given,** so `select` refuses a malformed path as it did, and steps into an object's own fields and a list's items alone. - **A module's declarations name Nexo's own types qualified,** as `Nexo.Number`, where the module declares a type of that name. -- **Conditions Nexo told apart by message have codes of their own,** NEXO5043 to NEXO5050 among them, as [Nexo's language history](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/LANGUAGE-HISTORY.md) records. +- **Conditions Nexo told apart by message have codes of their own,** NEXO5043 to NEXO5050 among them, as [Nexo's language history](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/LANGUAGE-HISTORY.md) records. **Breaking:** a query that tested membership in a list of objects, lists or values of `Any` is refused; test a key field instead, as `items.any(it.id == id)`. diff --git a/docs/decisions.md b/docs/decisions.md index 4eb4163..e5912f0 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -409,7 +409,7 @@ Each entry is one of three kinds: - **Kind:** Contract. - **Decision:** `on(type, options?)` takes a second, optional positional argument, a `Listening { capture }`, so `on("click", { capture = true })` listens as the event is captured on its way to its target, and `on("click")` as before, at the target and as it bubbles. It listens passively either way, for observing alone, as [D2](#d2) has it. - **Why:** - - A member's argument form is positional or options, never both, and `on("click")` keeps its form, so the option is a structured value its parameter constructs from the object expression written there, as Nexo's [constructing a structure](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/types.md#types-constructing-a-structure) sets out. + - A member's argument form is positional or options, never both, and `on("click")` keeps its form, so the option is a structured value its parameter constructs from the object expression written there, as Nexo's [constructing a structure](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/types.md#types-constructing-a-structure) sets out. - A structure leaves room for another listening option without changing the argument form, which would break every subscription. - Listening in the capture phase at an ancestor observes an event before any listener nearer its target runs, so a listener there that stops it hides nothing. - **Declined:** @@ -930,7 +930,7 @@ Each entry is one of three kinds: *November 2, 2026* - **Kind:** Contract. -- **Decision:** A host call's function argument reaches its implementation as a kept function, which Nexo's language `1.0.0-beta.20` designed for DOMQL ([C13](features-status.md#planned-extension-contract)), as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d49) record. DOMQL ends it as the execution keeping it ends: a continuous execution's instance ending or accepting other arguments, a once execution's answer settling, a subscription ending. Each call counts as an evaluation of the instance's, so what it reads reads alone. +- **Decision:** A host call's function argument reaches its implementation as a kept function, which Nexo's language `1.0.0-beta.20` designed for DOMQL ([C13](features-status.md#planned-extension-contract)), as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d49) record. DOMQL ends it as the execution keeping it ends: a continuous execution's instance ending or accepting other arguments, a once execution's answer settling, a subscription ending. Each call counts as an evaluation of the instance's, so what it reads reads alone. - **Why:** - A running behavior keeps a test of what it hears, as a route's condition, and calls it inside each event's dispatch; data alone left every such test a protocol of the module's own. - DOMQL alone knows when what it started ends, so it disposes each prepared call then, and a call after that fails with Nexo's code, where it would read a page the caller has moved on from. @@ -1156,7 +1156,7 @@ Each entry is one of three kinds: - **Why:** - Every planned capability is implemented or declined but A1 and A5's queue. What callers use today, the JavaScript half, is complete. - The C# half is a client of that contract. It maps results onto records, drives the operations the JavaScript half offers, and carries across the boundary the order that half already keeps ([D69](#d69)). The questions D46 leaves open are its own: a host's own transport, records a field discriminates, and checking text without a parser in .NET. Should its design need more of the JavaScript half, that is an addition, which a beta allows. - - Nexo holds the same stance: it is in its beta, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d27) record, while its tooling waits for its design, as its [status](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/features-status.md#tooling) records. + - Nexo holds the same stance: it is in its beta, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d27) record, while its tooling waits for its design, as its [status](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/features-status.md#tooling) records. - A caller reads `domql.info.versions` to learn what it can rely on. A beta runtime implementing an alpha specification would promise a stability its contract's version denies. - **Declined:** - Waiting for the C# half. Its design has not started, and the JavaScript half would go without a promise until it ends. @@ -1190,7 +1190,7 @@ Each entry is one of three kinds: - **Kind:** Process. - **Decision:** `nexo.release` pins a release of Nexo, `1.0.0-beta.1` first, and the build extracts the tree of its tag, `v1.0.0-beta.1`, where `nexo.commit` pinned a commit. Every link into Nexo names that tag, so the links move with the pin, `main` among the links it replaces. A link to another commit is a record of the past. - **Why:** - - Nexo now advances its language once per release and cuts each release as a signed tag, as its [D66](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d66) records, so a release is what DOMQL can rely on. + - Nexo now advances its language once per release and cuts each release as a signed tag, as its [D66](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d66) records, so a release is what DOMQL can rely on. - A commit pin named one fix, and moving it rewrote a hash in 81 places across 21 documents. - A link to Nexo's `main` changes under DOMQL's documents, unseen. - **Declined:** Waiting for Nexo's packages on a registry, which would keep DOMQL on a commit until they are published; the packages remain the next step, as [consuming the language](features-status.md#consuming-nexo) sets out. @@ -1220,7 +1220,7 @@ Each entry is one of three kinds: - A release is a signed tag, `v` and its version, on the commit that dates its changelog entry. Its packages are published from that tag. - `1.0.0-beta.2` is the first version collected so. The versions before it stand as they were declared. - **Why:** - - A version a caller relies on is one a release fixes, and DOMQL's version history and Nexo's language history now follow one rule, as Nexo's [D66](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d66) records. + - A version a caller relies on is one a release fixes, and DOMQL's version history and Nexo's language history now follow one rule, as Nexo's [D66](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d66) records. - It narrows [D75](#d75)'s rule that each version advances for its own reason: the specification version's reason is now a release whose contract changed. - **Declined:** Dating a release when its packages are published, which leaves a caller nothing to pin until a registry holds them; DOMQL's packages wait for Nexo's anyway. @@ -1236,7 +1236,7 @@ Each entry is one of three kinds: - Until then, a change fixes, explains, speeds up or documents, or meets a requirement. A feature lands only where Forma's scripts need it, as a decision records. - **Why:** - The beta promised no breaking redesign, but said nothing about when breaks end. - - DOMQL's contract holds Nexo's language, so it can be no more settled than Nexo, which waits for its own 1.0 as its [D67](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d67) records. + - DOMQL's contract holds Nexo's language, so it can be no more settled than Nexo, which waits for its own 1.0 as its [D67](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d67) records. - The planned capabilities came from reading Forma's scripts, so running them is the test of DOMQL's contract. - **Declined:** - Making the C# half a requirement, which would hold 1.0 for a design the owner hasn't decided is needed. @@ -1252,7 +1252,7 @@ Each entry is one of three kinds: - **Decision:** From `1.0.0-beta.1` on, each entry of the [version history](../VERSION-HISTORY.md) leads with examples of what its version changed: a query's in a `domql` block, a caller's or a module's in a `js` block. Each line's comment says what it does at that version and what it did before. The entry's list follows them as the reference. Each example is run at its version when its entry is written; the gate doesn't run them. - **Why:** - The list states each change precisely, but a caller migrating needs the line to write. - - Nexo's language history follows the same rule, as its [D70](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d70) records, and running its examples found what `1.0.0-beta.2`'s entry here misstated: a chain's limit counts terms, and a grouped chain is written `a + b + (c + d)`. + - Nexo's language history follows the same rule, as its [D70](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d70) records, and running its examples found what `1.0.0-beta.2`'s entry here misstated: a chain's limit counts terms, and a grouped chain is written `a + b + (c + d)`. - **Declined:** Running the history's examples in the gate, which would make a record of the past change with later versions. @@ -1262,7 +1262,7 @@ Each entry is one of three kinds: *November 3, 2026* - **Kind:** Contract. -- **Decision:** `domql.query(text, bindings, { types })` declares the type of a top-level binding by its notation, which Nexo's `createBindings` binds as its [declared types](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/bindings.md#runtime-bindings) do. Every binding made from the query keeps the types, `with`'s, an execution's update and a reaction's, and the query keeps a copy of them. +- **Decision:** `domql.query(text, bindings, { types })` declares the type of a top-level binding by its notation, which Nexo's `createBindings` binds as its [declared types](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/bindings.md#runtime-bindings) do. Every binding made from the query keeps the types, `with`'s, an execution's update and a reaction's, and the query keeps a copy of them. - **Why:** - It is the feature the 1.0 freeze allows, as [D80](#d80) records: replacing Forma's scripts needs it. Forma's input router binds its routes as `List` and its overrides as a dictionary of structures, and its culture coordinator binds its starting state as a structure. Data typed from itself is of no module's type, so each was refused (NEXO3042), and routes whose families carry different fields could not be bound at all. - Nexo already captures data as a declared type, a map as a dictionary and a set as a list, and checks it, so DOMQL passes the types through and adds no rule of its own. @@ -1344,7 +1344,7 @@ Each entry is one of three kinds: - **Kind:** Contract, approved by the owner. - **Decision:** - - DOMQL moves to Nexo's language `1.0.0-beta.41`, whose release is Nexo's `1.0.0-beta.2`, and follows its rule that a property names what its receiver is, has or is in, and a function does work, as Nexo's [D77](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d77) records. + - DOMQL moves to Nexo's language `1.0.0-beta.41`, whose release is Nexo's `1.0.0-beta.2`, and follows its rule that a property names what its receiver is, has or is in, and a function does work, as Nexo's [D77](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d77) records. - Every state DOMQL declares is a Boolean property, read without a call, `it.checked`: an element's `disabled`, `readonly`, `textEditable`, `focused`, `focusWithin`, `displayed`, `focusable`, `hovered`, `popoverOpen`, `checked`, `indeterminate` and `autofilled`, the document's `visible` and `focused`, the window's `canShare` and `hasClipboard`, and the ARIA view's `checked` and `disabled`. Each was a Boolean function. - Five take new names as they become properties: @@ -1655,7 +1655,7 @@ Each entry is one of three kinds: *November 5, 2026* - **Kind:** Contract, approved. -- **Decision:** `nexo.release` pins Nexo's release `1.0.0-preview.1`, of language `1.0.0-preview.1`, and DOMQL's documents link to Nexo's at its tag. DOMQL's `1.0.0-preview.1` describes DOMQL on that language, so `domql.format` writes an empty line between a body's last local and its `return`, as Nexo's [D83](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d83) records. +- **Decision:** `nexo.release` pins Nexo's release `1.0.0-preview.1`, of language `1.0.0-preview.1`, and DOMQL's documents link to Nexo's at its tag. DOMQL's `1.0.0-preview.1` describes DOMQL on that language, so `domql.format` writes an empty line between a body's last local and its `return`, as Nexo's [D83](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d83) records. - **Why:** - DOMQL's first release runs on a released Nexo, and Nexo's first preview is its newest release. - The language changed nothing a query relies on: a body's canonical text changes, and reads back as the same definition. @@ -1751,3 +1751,16 @@ Each entry is one of three kinds: - A command the subscriber sends back. It needs an identity for each question, and a second crossing. - Every subscription's answer, as a list. No caller asks several subscribers one question, and a list would make every answer's type a list. - An untyped answer. A behavior would check what .NET sends itself, where DOMQL captures every other value that crosses into a module by its declared type. + + + +## D114 — DOMQL builds against Nexo `1.0.0-preview.4` + +*November 30, 2026* + +- **Kind:** Contract, approved with the start-up DOMQL's modules and queries prepare ahead of time. +- **Decision:** DOMQL depends on `@formaui-net/nexo` at `^1.0.0-preview.4`, which its lock installs, and its documents link to Nexo's at that tag. DOMQL's `1.0.0-preview.2` describes DOMQL on Nexo's language `1.0.0-preview.3`, which `domql.info.versions.language` reports. +- **Why:** + - Nexo's `1.0.0-preview.3` and `1.0.0-preview.4` check a module, its registration and a script once, ahead of time, and record the checks in a manifest a host keeps. DOMQL's start can't read one from a release without them. + - The language changes nothing a query relies on: a refusal of `root` says more, and the rest is Nexo's runtime, which DOMQL uses as a host. +- **Declined:** Waiting for Nexo's next language. Nothing DOMQL needs is waiting there. diff --git a/docs/domql-design.md b/docs/domql-design.md index e94ece0..f5a67de 100644 --- a/docs/domql-design.md +++ b/docs/domql-design.md @@ -1,6 +1,6 @@ # DOMQL Design v1.0.0-preview.2 -The [DOMQL specification](../spec/README.md) is the contract: DOMQL's module, which declares the DOM as Nexo's domain, and the host that carries queries out against a document. This design sets out how this implementation is built to meet it, and the reasons behind the choices that shape it. It describes DOMQL's version `1.0.0-preview.2` on Nexo's definition version 38, as the specification does, and an outline of the C# half, which waits for its design; [the status overview](features-status.md) says where the implementation still differs. [Nexo's design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/nexo-design.md), at the release DOMQL builds against, sets out how the language and its runtime are built. +The [DOMQL specification](../spec/README.md) is the contract: DOMQL's module, which declares the DOM as Nexo's domain, and the host that carries queries out against a document. This design sets out how this implementation is built to meet it, and the reasons behind the choices that shape it. It describes DOMQL's version `1.0.0-preview.2` on Nexo's definition version 38, as the specification does, and an outline of the C# half, which waits for its design; [the status overview](features-status.md) says where the implementation still differs. [Nexo's design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/nexo-design.md), at the release DOMQL builds against, sets out how the language and its runtime are built. In this document: @@ -64,7 +64,7 @@ A selector is read for what it tests by `Selectors`, a scan of its text that nee ## Comparing and patching -The comparer reads what Nexo's [result metadata](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/evaluation.md#runtime-results) records beside each value: the provenance of each item, the source the earliest projection it descends from read, by which a list is matched where Nexo classifies every item's provenance as a reference, each standing once; the origin of each value, which tells whether a number came from the same branch, operand or property as the number before it; and the tolerance it compares within. A result therefore holds data alone, and a change set never names an element. +The comparer reads what Nexo's [result metadata](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/evaluation.md#runtime-results) records beside each value: the provenance of each item, the source the earliest projection it descends from read, by which a list is matched where Nexo classifies every item's provenance as a reference, each standing once; the origin of each value, which tells whether a number came from the same branch, operand or property as the number before it; and the tolerance it compares within. A result therefore holds data alone, and a change set never names an element. The patcher computes the change set that takes one reconciled snapshot to the next, and applies change sets in place to live state. A watch keeps the metadata of the snapshot it holds for the next comparison, so `sourceOf` reads an item's provenance from it, walking the records of the fields and items along the path, and allocates nothing until a caller asks. diff --git a/docs/features-status.md b/docs/features-status.md index 89f0ee3..2ee03f4 100644 --- a/docs/features-status.md +++ b/docs/features-status.md @@ -2,15 +2,15 @@ ## Current state -**DOMQL is in its preview, `1.0.0-preview.2`. Its vocabulary, queries, watches, events, executions and behaviors are implemented on Nexo's language `1.0.0-preview.1`, definition version 38. The specification describes DOMQL's `1.0.0-preview.2`, which the implementation follows: the DOM declared as DOMQL's own types, read through the `Domql` module every query imports. Every [planned capability](#planned-capabilities) is implemented or declined but the C# half's, A1 and A5's queue, which wait for its design.** +**DOMQL is in its preview, `1.0.0-preview.2`. Its vocabulary, queries, watches, events, executions and behaviors are implemented on Nexo's language `1.0.0-preview.3`, definition version 38. The specification describes DOMQL's `1.0.0-preview.2`, which the implementation follows: the DOM declared as DOMQL's own types, read through the `Domql` module every query imports. Every [planned capability](#planned-capabilities) is implemented or declined but the C# half's, A1 and A5's queue, which wait for its design.** | Version | Implementation | Specification | | --- | --- | --- | | DOMQL specification | `1.0.0-preview.2` | `1.0.0-preview.2` | -| Nexo language | `1.0.0-preview.1` | `1.0.0-preview.1` | +| Nexo language | `1.0.0-preview.3` | `1.0.0-preview.3` | | Definition format | 38 | 38 | -- **The language DOMQL runs on.** DOMQL follows Nexo's language `1.0.0-preview.1`, which Nexo's release `1.0.0-preview.1` carries, the version of Nexo's npm package DOMQL installs, as [D108](decisions.md#d108) and [D109](decisions.md#d109) record, and its documents link to [Nexo's documents at that tag](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md), moving with the pin. The language was called Lexica before the [migration](#migration-to-nexo). +- **The language DOMQL runs on.** DOMQL follows Nexo's language `1.0.0-preview.3`, which Nexo's release `1.0.0-preview.4` carries, the version of Nexo's npm package DOMQL installs, as [D108](decisions.md#d108), [D109](decisions.md#d109) and [D114](decisions.md#d114) record, and its documents link to [Nexo's documents at that tag](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md), moving with the pin. The language was called Lexica before the [migration](#migration-to-nexo). - **Packages.** The bundle and type declarations are built, with Nexo bundled inside `domql.js`. The npm package holds DOMQL's sources, which import Nexo's package, and the NuGet package the bundle. Both carry the runtime version, and `release.yml` publishes each from a release's tag: the NuGet package from `1.0.0-preview.1`, and the npm package from `1.0.0-preview.2`. - **The C# half** waits for its design, as [D46](decisions.md#d46) records. @@ -144,9 +144,9 @@ DOMQL moved from Lexica at `0e98b3e`, language `1.0.0-alpha.33`, to Nexo's langu - **One pin.** The migration was planned in checkpoints, each on a Nexo commit pinned as Nexo's work landed. Nexo reached its beta first, and its checklists describe the beta, so DOMQL moved to the beta at one pin, its checkpoints the order of the work, and passed its gate once on the beta: pinning a commit for each checkpoint would have meant writing against interfaces Nexo had already changed again. - **Imports.** DOMQL supplies its own module, `Domql`, as every query's import, and a query writes its other imports. An application configures no imports of its own, so a query's text means the same whatever was configured, as [D4](decisions.md#d4) records. - **Errors.** DOMQL's own conditions take `DOMQL` codes, catalogued in [errors](../spec/errors.md), bounded to the conditions it reports today; an error of Nexo's passing through DOMQL keeps its own code. -- **Module errors.** A module error of DOMQL's own, as its dispatch table's refusals are, is built with `NexoError.module`, which Nexo declared for its hosts in language `1.0.0-beta.2` for DOMQL's migration, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d29) record. -- **Host calls on a receiver of unknown type.** What such a call requests is read from the candidates Nexo answers for it, every declaration that takes the call as it is written, which Nexo answers from language `1.0.0-beta.3` for DOMQL, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d30) record. DOMQL read them from an index of its own before, which counted host calls a query could not reach. -- **What the migration found in Nexo since,** fixed in Nexo's languages `1.0.0-beta.4` to `1.0.0-beta.8`, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/decisions.md#d31) record: a host call on a value of `Any` is refused as Nexo resolves it, where DOMQL refused it as a value to evaluate; a module's own type named `Pair` is named by that name in its declarations; `@Domql` standing alone gives `~Domql`; a watch made stale by a module recognizing values compares within each value's tolerance, as Nexo keeps origins across resolutions of one definition; and a member read through a value of `Any` is compared within the tolerance it declares. +- **Module errors.** A module error of DOMQL's own, as its dispatch table's refusals are, is built with `NexoError.module`, which Nexo declared for its hosts in language `1.0.0-beta.2` for DOMQL's migration, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d29) record. +- **Host calls on a receiver of unknown type.** What such a call requests is read from the candidates Nexo answers for it, every declaration that takes the call as it is written, which Nexo answers from language `1.0.0-beta.3` for DOMQL, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d30) record. DOMQL read them from an index of its own before, which counted host calls a query could not reach. +- **What the migration found in Nexo since,** fixed in Nexo's languages `1.0.0-beta.4` to `1.0.0-beta.8`, as its [decisions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/decisions.md#d31) record: a host call on a value of `Any` is refused as Nexo resolves it, where DOMQL refused it as a value to evaluate; a module's own type named `Pair` is named by that name in its declarations; `@Domql` standing alone gives `~Domql`; a watch made stale by a module recognizing values compares within each value's tolerance, as Nexo keeps origins across resolutions of one definition; and a member read through a value of `Any` is compared within the tolerance it declares. Contracts: [Queries](../spec/queries.md), [types](../spec/vocabulary.md#vocabulary-types), [extension modules](../spec/vocabulary.md#extension-modules), [results](../spec/results.md), [errors](../spec/errors.md). @@ -281,7 +281,7 @@ Its second, `1.0.0-preview.2`, is released, tagged `v1.0.0-preview.2`, and `rele ### Consuming the language -**Current:** DOMQL depends on Nexo's npm package, `@formaui-net/nexo`, from `1.0.0-preview.1`, the release its lock installs and its tests run against, as [D109](decisions.md#d109) records; with `NEXO_SOURCE` naming a Nexo checkout, the build links that checkout's working tree in the package's place. CI checks Nexo out at the release's tag, whose documents the link test reads. It imports the language's entry point alone, and bundles it into `domql.js`. The language's tests that run through DOMQL's entry point are DOMQL's integration tests. +**Current:** DOMQL depends on Nexo's npm package, `@formaui-net/nexo`, from `1.0.0-preview.4`, the release its lock installs and its tests run against, as [D109](decisions.md#d109) records; with `NEXO_SOURCE` naming a Nexo checkout, the build links that checkout's working tree in the package's place. CI checks Nexo out at the release's tag, whose documents the link test reads. It imports the language's entry point alone, and bundles it into `domql.js`. The language's tests that run through DOMQL's entry point are DOMQL's integration tests. **Remaining:** @@ -289,7 +289,7 @@ Its second, `1.0.0-preview.2`, is released, tagged `v1.0.0-preview.2`, and `rele 2. Write the NuGet bundle with `../nexo/nexo.js` as an import, rather than carrying the language inside, as the npm package's sources import `@formaui-net/nexo`. 3. Have the gate check that DOMQL's packages depend on Nexo's and Nexo's on nothing of DOMQL's. -Nexo's packages are published from its `1.0.0-preview.1`, as its [release](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/features-status.md#release) records. +Nexo's packages are published from its `1.0.0-preview.1`, as its [release](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/features-status.md#release) records. ### Packages @@ -318,7 +318,7 @@ Nexo's packages are published from its `1.0.0-preview.1`, as its [release](https | Requirement | Why | State | | --- | --- | --- | -| **Nexo's 1.0.** DOMQL runs on Nexo's 1.0, from its published packages. | DOMQL's contract holds the language its queries are written in, so it promises no more than Nexo does. | Nexo is in its preview, at `1.0.0-preview.1`, as [what Nexo's 1.0 requires](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/features-status.md#what-1-0-requires) sets out. | +| **Nexo's 1.0.** DOMQL runs on Nexo's 1.0, from its published packages. | DOMQL's contract holds the language its queries are written in, so it promises no more than Nexo does. | Nexo is in its preview, at `1.0.0-preview.4`, as [what Nexo's 1.0 requires](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/features-status.md#what-1-0-requires) sets out. | | **Contracts settled.** No decision is open, and each [deferred](#deferred) item and [decision not taken](domql-design.md#decisions-not-taken) is shown to land without a break. | What may still change after 1.0 must be able to change compatibly. | Holds: no decision is open, and each [deferred](#deferred) item and [decision not taken](domql-design.md#decisions-not-taken) lands as an addition or within the implementation. A watch's promise to evaluate its whole query each time was the one that would have made evaluating less a break; [what an evaluation gives](../spec/watches.md#watching-what-an-evaluation-gives) now leaves it to DOMQL. | | **The C# half decided.** It is designed, or decided to follow 1.0 as an addition. | It waits for the owner's design, as [D46](decisions.md#d46) records, and a .NET application may need it to drive DOMQL. | Waits for its design. | | **Published.** DOMQL's packages are on npm and NuGet, tested as consumers install them. | A caller pins a release it can install. | Holds: the NuGet package is published from `1.0.0-preview.1` and the npm package from `1.0.0-preview.2`, each verified as consumers install it before its release. | @@ -343,7 +343,7 @@ This work is separate from the plan above. No order is assigned here. | Work | Status | Remaining | | --- | --- | --- | -| Editor tooling | Waits for Nexo's design | Nexo's, through its syntax tree, in its [tooling](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/features-status.md#tooling), which waits for its design | +| Editor tooling | Waits for Nexo's design | Nexo's, through its syntax tree, in its [tooling](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/features-status.md#tooling), which waits for its design | **Verification outside the gate.** Performance is measured outside the gate, by `npm run bench` and `npm run scale` from `tests/`. `Domql.window.size` following a scrollbar that appears or goes runs in the gate, as a browser test with a launch of its own. diff --git a/nuget/README.md b/nuget/README.md index 7ec8b61..1cbbaa2 100644 --- a/nuget/README.md +++ b/nuget/README.md @@ -2,9 +2,9 @@ **A declarative approach to managing the DOM.** -DOMQL is a JavaScript library for querying the DOM, allowing you to read information from a document once or observe it as it changes. This guide takes you from your first query to watching results, handling events and extending the library. Its queries are written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md). +DOMQL is a JavaScript library for querying the DOM, allowing you to read information from a document once or observe it as it changes. This guide takes you from your first query to watching results, handling events and extending the library. Its queries are written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md). -> **Preview:** no breaking redesign is planned, and a version that breaks what the one before it allowed says how to migrate. `formaui-net.DOMQL` is published to NuGet as a pre-release, which you [install by name](#install-and-load). The package distributes a JavaScript ES module; the API in this guide runs in JavaScript. Every example here runs on this preview. The runtime, `1.0.0-preview.4`, implements DOMQL's specification `1.0.0-preview.2` on Nexo's language `1.0.0-preview.1`, definition version 38. [The status overview](https://github.com/FormaUI/DOMQL/blob/main/docs/features-status.md) says what is implemented and what is being built. +> **Preview:** no breaking redesign is planned, and a version that breaks what the one before it allowed says how to migrate. `formaui-net.DOMQL` is published to NuGet as a pre-release, which you [install by name](#install-and-load). The package distributes a JavaScript ES module; the API in this guide runs in JavaScript. Every example here runs on this preview. The runtime, `1.0.0-preview.4`, implements DOMQL's specification `1.0.0-preview.2` on Nexo's language `1.0.0-preview.3`, definition version 38. [The status overview](https://github.com/FormaUI/DOMQL/blob/main/docs/features-status.md) says what is implemented and what is being built. ## In this guide @@ -1003,7 +1003,7 @@ Modules can also declare Boolean members, properties and functions whose result A member the host invokes, `invokedBy: 'host'`, is a host call that DOMQL carries out: an event source, `requestKind: 'subscription'`, or an execution, `requestKind: 'execution'`, which runs `once` or `continuous` as its `executionMode` says. An event source's implementation receives the receiver, arguments, environment and an event-delivery callback, as `{ receiver, args, env, deliver }`, and returns an object with a `stop` method to end listening. Each event is captured as the type its declaration's result names, and a module adds event types of its own as mappings of DOMQL's type selector `event`, `{ selector: 'event', key, type }`, each naming the type its events are captured as. -[Nexo's modules](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/modules.md#modules) specify the full extension contracts. The next section shows execution modules. +[Nexo's modules](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/modules.md#modules) specify the full extension contracts. The next section shows execution modules. ### Bind data as a module's type @@ -1547,9 +1547,9 @@ filtered.dispose(); ## Learn more - [Repository README](https://github.com/FormaUI/DOMQL): what DOMQL is for, what is built, and how to build and test it. -- [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md): the language DOMQL is written in, its syntax, types, null semantics, imports and extensions, and the runtime contracts of its modules. +- [Nexo specification](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md): the language DOMQL is written in, its syntax, types, null semantics, imports and extensions, and the runtime contracts of its modules. - [DOMQL specification](https://github.com/FormaUI/DOMQL/blob/main/spec/README.md): queries, the DOM's vocabulary, evaluating and watching a query, its results, events, executions, and the API. -- [DOMQL design](https://github.com/FormaUI/DOMQL/blob/main/docs/domql-design.md): how DOMQL is built, and the decisions it did not take, and the [Nexo design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/docs/nexo-design.md): how the language and its runtime are built. +- [DOMQL design](https://github.com/FormaUI/DOMQL/blob/main/docs/domql-design.md): how DOMQL is built, and the decisions it did not take, and the [Nexo design](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/nexo-design.md): how the language and its runtime are built. - [Changelog](https://github.com/FormaUI/DOMQL/blob/main/CHANGELOG.md): each release of the package and what it changed. - [Status](https://github.com/FormaUI/DOMQL/blob/main/docs/features-status.md): what is implemented, what is being built, and what remains. diff --git a/package-lock.json b/package-lock.json index 977d525..2712550 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,7 @@ "version": "1.0.0-preview.4", "license": "Apache-2.0", "dependencies": { - "@formaui-net/nexo": "^1.0.0-preview.1" + "@formaui-net/nexo": "^1.0.0-preview.4" }, "devDependencies": { "esbuild": "^0.25.0" @@ -458,9 +458,9 @@ } }, "node_modules/@formaui-net/nexo": { - "version": "1.0.0-preview.1", - "resolved": "https://registry.npmjs.org/@formaui-net/nexo/-/nexo-1.0.0-preview.1.tgz", - "integrity": "sha512-713+idtSy2efEFqAguoJX6hE4G5OJ0vxSmETqngu9571ruQcuVGZTW6YXAsRkHT7homK1zqB2JPSBD1jth0PbQ==", + "version": "1.0.0-preview.4", + "resolved": "https://registry.npmjs.org/@formaui-net/nexo/-/nexo-1.0.0-preview.4.tgz", + "integrity": "sha512-FfXUg8plHMeGRUzld4C97Jg6G+b7diYLfrTLXn1uS3ACFLc04Hh6f8DnGyUlzwq3pa8ygLYkSobq/TGxF5rtEQ==", "license": "Apache-2.0" }, "node_modules/esbuild": { diff --git a/package.json b/package.json index 92c1bb2..d637a3b 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,7 @@ "bundle": "node scripts/bundle.mjs" }, "dependencies": { - "@formaui-net/nexo": "^1.0.0-preview.1" + "@formaui-net/nexo": "^1.0.0-preview.4" }, "devDependencies": { "esbuild": "^0.25.0" diff --git a/spec/README.md b/spec/README.md index feab9c6..5db1290 100644 --- a/spec/README.md +++ b/spec/README.md @@ -1,12 +1,12 @@ # DOMQL Specification v1.0.0-preview.2 -DOMQL reads the DOM and shapes what it reads as data, keeps that data current as the document changes, delivers the page's events as data, and carries out the executions its own module and its extensions declare. Its queries are scripts written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md), whose specification holds two contracts: the language's, what a script means, and the runtime's, how a host binds, resolves and evaluates a script. DOMQL declares the DOM as Nexo's domain, in a module like any other, and is the host that carries each query out against a document. It adds no language rule: a rule of the language or of its runtime is Nexo's, and this specification links to it. +DOMQL reads the DOM and shapes what it reads as data, keeps that data current as the document changes, delivers the page's events as data, and carries out the executions its own module and its extensions declare. Its queries are scripts written in [Nexo](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md), whose specification holds two contracts: the language's, what a script means, and the runtime's, how a host binds, resolves and evaluates a script. DOMQL declares the DOM as Nexo's domain, in a module like any other, and is the host that carries each query out against a document. It adds no language rule: a rule of the language or of its runtime is Nexo's, and this specification links to it. This specification is the authoritative contract for DOMQL. It states what DOMQL is, not how far its implementation has come: [the status overview](../docs/features-status.md) says what this repository implements, and [the design](../docs/domql-design.md) how it is built. -**Version.** This specification describes DOMQL's version `1.0.0-preview.2`, which changes as DOMQL's contract does, apart from its runtime's version and from Nexo's language. It describes DOMQL on Nexo's language version `1.0.0-preview.1`, of [definition version 38](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md#version). An implementation says which specification it follows, and which language version its Nexo runtime follows, in `domql.info.versions`, as [the API](api.md#api-entry-points-and-operations) sets out. +**Version.** This specification describes DOMQL's version `1.0.0-preview.2`, which changes as DOMQL's contract does, apart from its runtime's version and from Nexo's language. It describes DOMQL on Nexo's language version `1.0.0-preview.3`, of [definition version 38](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md#version). An implementation says which specification it follows, and which language version its Nexo runtime follows, in `domql.info.versions`, as [the API](api.md#api-entry-points-and-operations) sets out. ## What it covers @@ -14,8 +14,8 @@ Five layers meet whenever a query runs. Nexo's specification covers the first tw | Layer | What it owns | Documents | | --- | --- | --- | -| The language | What a query means: its imports, syntax, names and scope, values and types, expressions and functions, members, extensions, and the contracts a vocabulary keeps | [Nexo's language](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/README.md) | -| The runtime | Binding, resolving and evaluating a script for a host, the modules it registers, its definitions and its results | [Nexo's runtime](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/hosting.md) | +| The language | What a query means: its imports, syntax, names and scope, values and types, expressions and functions, members, extensions, and the contracts a vocabulary keeps | [Nexo's language](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md) | +| The runtime | Binding, resolving and evaluating a script for a host, the modules it registers, its definitions and its results | [Nexo's runtime](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/hosting.md) | | DOMQL's module | The DOM as Nexo's domain: its nodes and shadow trees, its members, its states among them, its event sources and event types, its executions, and the observations that follow its changes | [Nodes and shadow trees](nodes-and-shadow-trees.md), [vocabulary](vocabulary.md), [events](events.md) | | DOMQL, the host | Carrying a query out against a document: evaluating it, watching it, and invoking its host calls, delivering its events, carrying out its executions and keeping its behaviors where their module reaches them, through the API a caller uses | [Queries](queries.md), [evaluation](evaluation.md), [watches](watches.md), [results](results.md), [events](events.md), [executions](executions.md), [behaviors](behaviors.md), [the API](api.md), [errors](errors.md) | | The caller | The application around DOMQL: which queries it makes, when it carries each out, and what it does with each result | The caller's own | diff --git a/spec/api.md b/spec/api.md index e60e34d..4b384df 100644 --- a/spec/api.md +++ b/spec/api.md @@ -81,7 +81,7 @@ Each entry point and operation is listed here with what it takes, and the sectio | `query.subscribe(handler, options?)` | Subscribes to a subscription, answering a `DomqlEventListener`, as [subscribing](events.md#subscribing) sets out | | `query.executeAsync(options?)` | Carries out a once execution, answering a promise of its result, as [executing once](executions.md#executions-executing-once) sets out | | `query.run(options?)` | Starts a continuous execution, answering a `DomqlExecutionHandle`, as [running continuously](executions.md#executions-running-continuously) sets out | -| `domql.format(source)` | The canonical text of a text, a definition or a query object, as [formatting](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/definition.md#definition-canonical-text) sets out | +| `domql.format(source)` | The canonical text of a text, a definition or a query object, as [formatting](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/definition.md#definition-canonical-text) sets out | | `domql.createModule(name, contents)` | Creates a module from its declarations, each that runs code carrying its implementation, as [extension modules](vocabulary.md#extension-modules) set out | | `domql.registerModule(module)` | Registers a module's declarations in the instance's registry, as [extension modules](vocabulary.md#extension-modules) set out | | `domql.registerModuleLoader(name, load)` | Registers the loader of a module loaded on request, as [loading a module on request](vocabulary.md#extension-modules-loading) sets out | @@ -177,6 +177,6 @@ An operation that answers a handle, given a signal already aborted, answers a di ## Errors -Every failure is a `NexoError` with its `code`, its `kind`, its `message` and the `location` it concerns, as Nexo's [errors](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/errors.md) set out, and a caller reads the code, the kind and the location rather than the message. A condition of Nexo's keeps its `NEXO` code, and one of DOMQL's own takes a `DOMQL` code, as [errors](errors.md) catalog them. A failure is reported where it arises: a syntax or structure failure as the query is made; a module failure as a module is created or registered, or as a request that uses a declaration without an implementation is carried out; a validation failure as the request is resolved; and an evaluation failure as it is carried out, a missing window among them. +Every failure is a `NexoError` with its `code`, its `kind`, its `message` and the `location` it concerns, as Nexo's [errors](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/errors.md) set out, and a caller reads the code, the kind and the location rather than the message. A condition of Nexo's keeps its `NEXO` code, and one of DOMQL's own takes a `DOMQL` code, as [errors](errors.md) catalog them. A failure is reported where it arises: a syntax or structure failure as the query is made; a module failure as a module is created or registered, or as a request that uses a declaration without an implementation is carried out; a validation failure as the request is resolved; and an evaluation failure as it is carried out, a missing window among them. A failure no handler or caller receives, as an `"error"` event no listener receives, a failure of an `"error"` handler or of a subscription's handler, or one a once execution reports after its caller stopped waiting, goes to the **window's error reporting**, its `reportError`, or the console where the window has none. A watch, an event listener and a waiting evaluation let go of every observation they hold even where letting go of one fails: each attempts every cleanup, reports a failure of one to the window's error reporting, and never lets it replace its result, its error or its cancellation. diff --git a/spec/errors.md b/spec/errors.md index 0570258..947bb69 100644 --- a/spec/errors.md +++ b/spec/errors.md @@ -2,9 +2,9 @@ -Every failure DOMQL reports is a `NexoError`, with its `code`, its `kind`, its `message` and the `location` it concerns, as Nexo's [errors](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/errors.md#diagnostics-codes) set out. A caller reads the code, the kind and the location, never the message. +Every failure DOMQL reports is a `NexoError`, with its `code`, its `kind`, its `message` and the `location` it concerns, as Nexo's [errors](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/errors.md#diagnostics-codes) set out. A caller reads the code, the kind and the location, never the message. -- **Nexo's conditions** keep their codes, `NEXO` and four digits, as Nexo's catalogs give them: [the language's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/errors.md) for what a query may express, and [the runtime's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/errors.md) for definitions, bindings, declarations and the API. A Nexo error passing through DOMQL keeps its code and takes no second one. +- **Nexo's conditions** keep their codes, `NEXO` and four digits, as Nexo's catalogs give them: [the language's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/errors.md) for what a query may express, and [the runtime's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/errors.md) for definitions, bindings, declarations and the API. A Nexo error passing through DOMQL keeps its code and takes no second one. - **DOMQL's own conditions** take codes of DOMQL's prefix, `DOMQL` and four digits, in the ranges Nexo's kinds use, as the tables below give them. - **A code is stable.** It names its condition, never its wording. A new condition takes a new code, and a retired code is never reused. diff --git a/spec/evaluation.md b/spec/evaluation.md index de8f39a..4892d69 100644 --- a/spec/evaluation.md +++ b/spec/evaluation.md @@ -3,7 +3,7 @@ -**Evaluating** a query reads the document once and answers its result. DOMQL evaluates a query as Nexo's [runtime](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/evaluation.md#runtime-evaluation) evaluates a script, synchronously, against the document it runs against, and each member declares how it reads. A caller evaluates with `evaluate`, which answers at once, or with `evaluateAsync`, which also waits for the browser's first report of what a maintained member reads. +**Evaluating** a query reads the document once and answers its result. DOMQL evaluates a query as Nexo's [runtime](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/evaluation.md#runtime-evaluation) evaluates a script, synchronously, against the document it runs against, and each member declares how it reads. A caller evaluates with `evaluate`, which answers at once, or with `evaluateAsync`, which also waits for the browser's first report of what a maintained member reads. ```js const query = domql.query('{ size = panel.size, nearEnd = sentinel.intersects({ root = panel }) }', { panel, sentinel }); @@ -12,7 +12,7 @@ query.evaluate(); // Throws an evaluation error: intersects is mainta await query.evaluateAsync(); // { size: { width: 640, height: 480 }, nearEnd: false } ``` -Evaluating a query is read-only, as [Nexo requires](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/members.md#how-a-member-reads) of every vocabulary. A measurement that needs the document changed first, such as measuring columns at their intrinsic widths under a temporary class, is an [execution](executions.md) of its own. +Evaluating a query is read-only, as [Nexo requires](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/members.md#how-a-member-reads) of every vocabulary. A measurement that needs the document changed first, such as measuring columns at their intrinsic widths under a temporary class, is an [execution](executions.md) of its own. In this document: @@ -28,7 +28,7 @@ In this document: `query.evaluate(options?)` resolves the query, then evaluates it once against the document in a single synchronous pass, following the resolution rather than looking names up again. What an evaluation reads is always the document as it is. Its options are `window` and [`owner`](api.md#api-the-owner). - **The result** is a detached copy, frozen, that holds nothing of the document. A structure a member answers is taken by its data shape alone, the properties its type declares, each read as the value offers it, a getter's included, so a property beside them never reaches a result and an instance of a class answers as the properties its type declares. -- **A member that breaks its contract.** A member whose function answers a type other than the one it declares has broken its contract, and the evaluation fails with an evaluation error naming the member and where it stands in the query; so does a member whose function throws, with the thrown error as its cause. A request that uses a member a module declares and does not implement is refused before anything is evaluated, with a module error naming the declaration, as Nexo's [declarations without an implementation](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/modules.md#modules-declarations-without-an-implementation) set out. +- **A member that breaks its contract.** A member whose function answers a type other than the one it declares has broken its contract, and the evaluation fails with an evaluation error naming the member and where it stands in the query; so does a member whose function throws, with the thrown error as its cause. A request that uses a member a module declares and does not implement is refused before anything is evaluated, with a module error naming the declaration, as Nexo's [declarations without an implementation](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/modules.md#modules-declarations-without-an-implementation) set out. - **A maintained member** cannot be read in a single synchronous pass and fails `evaluate`, with an evaluation error naming the member; `evaluateAsync` waits for it. - **A request of another kind** is refused, as [request kinds and their operations](queries.md#operations-and-request-kinds) set out. @@ -36,7 +36,7 @@ In this document: ## How DOMQL's members read -Each member declares how it reads by [Nexo's contract](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/members.md#how-a-member-reads): DOMQL's members read fresh from the document, as an attribute or a box is, maintained by a browser observation, as `intersects` is, captured, as an event's data is, or derived, as a list's `count` is. +Each member declares how it reads by [Nexo's contract](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/members.md#how-a-member-reads): DOMQL's members read fresh from the document, as an attribute or a box is, maintained by a browser observation, as `intersects` is, captured, as an event's data is, or derived, as a list's `count` is. A member whose result depends on what happened before, as well as on the document as it is, is captured: it keeps that history while a watch or an event listener holds it, and documents what an evaluation once reports without it. diff --git a/spec/events.md b/spec/events.md index c2aff96..13c7ec9 100644 --- a/spec/events.md +++ b/spec/events.md @@ -3,7 +3,7 @@ -An **event source** delivers things that happened, as a click or a key pressed, and a **subscription** shapes each event it delivers into data, read as the event is dispatched. An event source is a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/members.md#members-host-calls) DOMQL carries out by subscribing to it, and a subscription is a query whose chain ends in one: a caller subscribes to it, and the caller's handler receives one result for each event, immutable data that holds no event object and no element. +An **event source** delivers things that happened, as a click or a key pressed, and a **subscription** shapes each event it delivers into data, read as the event is dispatched. An event source is a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/members.md#members-host-calls) DOMQL carries out by subscribing to it, and a subscription is a query whose chain ends in one: a caller subscribes to it, and the caller's handler receives one result for each event, immutable data that holds no event object and no element. ```js const clicks = domql.query(` @@ -30,7 +30,7 @@ In this document: ## Event sources -An event source is subscribed to, and never read or watched: DOMQL starts it as its caller subscribes, and has each event it delivers projected through the object expression that follows it, as Nexo [projects a value its host supplies](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/host-calls.md#runtime-host-calls), each event captured as the members of the type its event type maps to. +An event source is subscribed to, and never read or watched: DOMQL starts it as its caller subscribes, and has each event it delivers projected through the object expression that follows it, as Nexo [projects a value its host supplies](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/host-calls.md#runtime-host-calls), each event captured as the members of the type its event type maps to. | Available on | Source | Delivers | Fixed | | --- | --- | --- | --- | @@ -50,7 +50,7 @@ A subscription listening in the capture phase observes alone, as every subscript ## Event types -DOMQL's module declares the [type selector](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/vocabulary.md#vocabulary-type-selectors) `event`, whose keys are the event types, and a module extends it with event types of its own as it extends DOMQL's types. The built-in event types, the type each maps to, and the members each event offers: +DOMQL's module declares the [type selector](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/vocabulary.md#vocabulary-type-selectors) `event`, whose keys are the event types, and a module extends it with event types of its own as it extends DOMQL's types. The built-in event types, the type each maps to, and the members each event offers: | Event types | Type | Members | | --- | --- | --- | diff --git a/spec/executions.md b/spec/executions.md index 69b86c3..eb5d2f7 100644 --- a/spec/executions.md +++ b/spec/executions.md @@ -3,7 +3,7 @@ -An **execution** is a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/members.md#members-host-calls) DOMQL carries out to change the page. A **once execution** changes it once and answers its result; a **continuous execution** starts something that runs on the page until it is updated or disposed, and has no result, a [behavior](behaviors.md) whose running instance the commands of its module reach. DOMQL's module declares its [built-in executions](vocabulary.md#built-in-executions), each one platform call named by the verb it carries out, as [properties and functions](vocabulary.md#vocabulary-properties-and-functions) set out, and an [extension module](vocabulary.md#extension-modules) declares its own, each with its execution mode and the implementation that carries it out. `executeAsync` carries out a once execution and `run` a continuous one, and no other operation carries out either, as [request kinds and their operations](queries.md#operations-and-request-kinds) set out. +An **execution** is a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/members.md#members-host-calls) DOMQL carries out to change the page. A **once execution** changes it once and answers its result; a **continuous execution** starts something that runs on the page until it is updated or disposed, and has no result, a [behavior](behaviors.md) whose running instance the commands of its module reach. DOMQL's module declares its [built-in executions](vocabulary.md#built-in-executions), each one platform call named by the verb it carries out, as [properties and functions](vocabulary.md#vocabulary-properties-and-functions) set out, and an [extension module](vocabulary.md#extension-modules) declares its own, each with its execution mode and the implementation that carries it out. `executeAsync` carries out a once execution and `run` a continuous one, and no other operation carries out either, as [request kinds and their operations](queries.md#operations-and-request-kinds) set out. ```js // A built-in once execution, answering whether focus landed on the field. @@ -33,8 +33,8 @@ In this document: `query.executeAsync(options?)` carries out a once execution and answers a promise of its result; its options are `window`, [`owner`](api.md#api-the-owner) and `signal`. Each call executes it again. One carried out while a query is evaluated, by a member's implementation, rejects with `DOMQL5021`, executing nothing, since a member reads alone; `run` throws it alike. - **Order.** An execution's implementation is invoked within the call that carries it out, once its preparation has run, so executions carried out in one task, once or continuous, are invoked in the order they are carried out, each seeing what the ones before it changed, as opening a dialog and then focusing a field within it. -- **Preparation first.** Its receiver and its arguments are prepared first, synchronously, as [Nexo's preparation](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/host-calls.md#runtime-host-calls) evaluates them; a failure there rejects the promise and executes nothing. A skipped preparation, where the receiver is null, or an argument whose parameter propagates null is null, executes nothing, and the promise resolves to null, as a member's null is; a null argument whose parameter accepts null is passed as it stands, as [Nexo's null arguments](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/members.md#nullability-a-null-argument-follows-the-parameter) set out. -- **The result.** The execution's implementation receives the receiver, the arguments, the environment and the signal, and may answer its result or a promise of it. The result must be of the type the execution declares, as Nexo [captures a supplied value](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/host-calls.md#runtime-host-calls-capturing), and data alone; a result of another type rejects the promise with an evaluation error naming the execution, and an execution that declares no result resolves to null. An object expression that follows the execution is evaluated against the result once it arrives, as `evaluate` evaluates a query, so a member maintained by an observation fails it, and the promise answers detached, immutable data. +- **Preparation first.** Its receiver and its arguments are prepared first, synchronously, as [Nexo's preparation](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/host-calls.md#runtime-host-calls) evaluates them; a failure there rejects the promise and executes nothing. A skipped preparation, where the receiver is null, or an argument whose parameter propagates null is null, executes nothing, and the promise resolves to null, as a member's null is; a null argument whose parameter accepts null is passed as it stands, as [Nexo's null arguments](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/members.md#nullability-a-null-argument-follows-the-parameter) set out. +- **The result.** The execution's implementation receives the receiver, the arguments, the environment and the signal, and may answer its result or a promise of it. The result must be of the type the execution declares, as Nexo [captures a supplied value](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/host-calls.md#runtime-host-calls-capturing), and data alone; a result of another type rejects the promise with an evaluation error naming the execution, and an execution that declares no result resolves to null. An object expression that follows the execution is evaluated against the result once it arrives, as `evaluate` evaluates a query, so a member maintained by an observation fails it, and the promise answers detached, immutable data. - **Failure.** A failure of the execution, whatever it throws, rejects the promise with an evaluation error naming the execution, whose cause is what was thrown; nothing goes to the error reporting while the caller holds the promise. - **Cancellation.** A signal already aborted rejects with its reason and executes nothing. A signal that aborts while the execution runs rejects the promise with its reason at once, and the execution learns of it through the signal it was given; what it does after that is its own, its result is discarded, and a failure it reports afterwards goes to the window's error reporting, since no caller waits for it. - **No rollback.** An execution can change the document before it fails or is canceled, and DOMQL never undoes what it did; an execution that can be undone offers that as an execution of its own. diff --git a/spec/nodes-and-shadow-trees.md b/spec/nodes-and-shadow-trees.md index a7320a5..ff26c64 100644 --- a/spec/nodes-and-shadow-trees.md +++ b/spec/nodes-and-shadow-trees.md @@ -14,7 +14,7 @@ In this document: ## Nodes -A node is a value of the DOM tree. DOMQL's module declares the nodes as [reference types](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/types.md#reference-types): `Node`, abstract, and beneath it its kinds, `Element`, `Document`, `DocumentFragment`, a document fragment that is no shadow root, and `ShadowRoot`. DOMQL's `typeOf` recognizes a bound node as the kind it is, never as `Node` itself, and each type's `isInstance` checks membership, so a host may still bind a node declared as a `Node`. `Window` is a reference type of a hierarchy of its own, no node, and so is `Range`, a range of a document a selection holds. Text and comment nodes are none of these kinds, and are refused as bindings. +A node is a value of the DOM tree. DOMQL's module declares the nodes as [reference types](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/types.md#reference-types): `Node`, abstract, and beneath it its kinds, `Element`, `Document`, `DocumentFragment`, a document fragment that is no shadow root, and `ShadowRoot`. DOMQL's `typeOf` recognizes a bound node as the kind it is, never as `Node` itself, and each type's `isInstance` checks membership, so a host may still bind a node declared as a `Node`. `Window` is a reference type of a hierarchy of its own, no node, and so is `Range`, a range of a document a selection holds. Text and comment nodes are none of these kinds, and are refused as bindings. diff --git a/spec/queries.md b/spec/queries.md index c5d21d9..fb90fca 100644 --- a/spec/queries.md +++ b/spec/queries.md @@ -82,7 +82,7 @@ const fromDefinition = domql.query(panelQuery.definition, { panel }); ### Its imports -A query uses the vocabulary of the modules it imports, as Nexo's [imports](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/modules.md#scripts-imports) set out, and DOMQL's own module, `Domql`, is imported by every query. +A query uses the vocabulary of the modules it imports, as Nexo's [imports](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/modules.md#scripts-imports) set out, and DOMQL's own module, `Domql`, is imported by every query. - **DOMQL supplies `Domql`.** DOMQL reads every query's text with the import `Domql` supplied, so a query reads the DOM's members, `Domql.document` and `Domql.window`, and names DOMQL's types, as `Element`, without writing `import Domql`. Writing it as well is harmless. - **Another module is imported by the query.** A query that uses a module its caller registered begins with that module's import, `import Charts`, and reads the members its extensions add to DOMQL's types with `:`, as `panel:palette`, as [extension modules](vocabulary.md#extension-modules) set out. Registering a module adds nothing to a query's imports, so a query that does not import a module reads the same before the module is registered and after. A module [loaded on request](vocabulary.md#extension-modules-loading) is loaded before a query importing it is carried out, which its imports name. @@ -93,7 +93,7 @@ A query uses the vocabulary of the modules it imports, as Nexo's [imports](https ### Binding its parameters -Each parameter is bound under the name the query uses, with a value Nexo's [script parameters and bindings](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/scripts.md#scripts-script-parameters) allow, and a result is data, which a caller receives in its own language's form. `with` answers a new query whose bindings replace the old ones whole, of the types the query declares; the query it was called on, and every operation running from it, are unaffected. A query can be made without its bindings and bound afterwards, and a required binding that is missing fails before anything is carried out. +Each parameter is bound under the name the query uses, with a value Nexo's [script parameters and bindings](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/scripts.md#scripts-script-parameters) allow, and a result is data, which a caller receives in its own language's form. `with` answers a new query whose bindings replace the old ones whole, of the types the query declares; the query it was called on, and every operation running from it, are unaffected. A query can be made without its bindings and bound afterwards, and a required binding that is missing fails before anything is carried out. A binding is typed from its value, unless the query [declares its type](#making-a-query-declared-types): every value is typed from itself, a null, an empty list and a list holding nulls among them, so a query is made for an element that is not there yet as it is for one that is. @@ -105,7 +105,7 @@ const another = query.with({ panel: otherPanel, ids: [1, 2] }); -**Declared types.** `domql.query(text, bindings, { types })` declares the type of a top-level binding by its notation, as Nexo's [declared types](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/bindings.md#runtime-bindings) bind it, where data typed from itself would be of no module's type: +**Declared types.** `domql.query(text, bindings, { types })` declares the type of a top-level binding by its notation, as Nexo's [declared types](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/bindings.md#runtime-bindings) bind it, where data typed from itself would be of no module's type: ```js const routed = domql.query("import Forma\nForma.firstKey(routes)", { routes: [{ key: "Enter" }] }, { types: { routes: "List" } }); @@ -134,7 +134,7 @@ A query belongs to the instance of the library that made it, and an instance ref ## Resolution -A request is resolved before it is first carried out, and resolution validates it against the vocabulary its imports make available, as Nexo's [resolution](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/resolution.md#runtime-bindings-and-resolution) sets out; a module a request imports is registered by its caller beforehand. A resolution is kept while Nexo says it is current, so a module registered later leaves a running watch, subscription or execution as it was, unless the module recognizes values its resolution may meet, as [registering a module while requests run](vocabulary.md#extension-modules-registering) sets out. A misspelling or a wrong argument is an error before anything is evaluated; a member's fit to its receiver is checked once the receiver's type is specific enough, which a null receiver's is not; null is always a result. +A request is resolved before it is first carried out, and resolution validates it against the vocabulary its imports make available, as Nexo's [resolution](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/resolution.md#runtime-bindings-and-resolution) sets out; a module a request imports is registered by its caller beforehand. A resolution is kept while Nexo says it is current, so a module registered later leaves a running watch, subscription or execution as it was, unless the module recognizes values its resolution may meet, as [registering a module while requests run](vocabulary.md#extension-modules-registering) sets out. A misspelling or a wrong argument is an error before anything is evaluated; a member's fit to its receiver is checked once the receiver's type is specific enough, which a null receiver's is not; null is always a result. `query.resolve(options?)` resolves a request without evaluating anything, and answers its kind, `value`, `subscription` or `execution`, an execution's `executionMode`, null for a request of another kind, and its type, null for an execution that answers no result; it needs no browser. It answers its definition and the declarations it uses as well, each with its `qualifiedName`, `typeAt(path)`, the type a path reaches, and `getLocation(pointer)`, where a pointer into its definition stands in its text. Its options `watch` and `acceptPartialObservation` resolve it as a watch would, so a watch's refusal of a partly observable member, as [accepting partial observation](watches.md#accepting-partial-observation) sets out, is found before a watch starts. @@ -142,7 +142,7 @@ A request is resolved before it is first carried out, and resolution validates i ## Request kinds and their operations -Evaluating, watching or subscribing to a request reads the document and changes nothing, whatever vocabulary it uses; an [execution](executions.md) explicitly requests effects, carried out only when its caller executes or runs it. The request's source decides its kind: a query gives a value, or ends in a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/members.md#members-host-calls), which DOMQL carries out as its declaration says, by subscribing to an event source, or by executing once or running continuously an execution of that mode. The one entry point serves every request kind, and resolution refuses an operation the kind does not take before anything is evaluated or started, with a validation error that says what the request does and names the operation it takes: +Evaluating, watching or subscribing to a request reads the document and changes nothing, whatever vocabulary it uses; an [execution](executions.md) explicitly requests effects, carried out only when its caller executes or runs it. The request's source decides its kind: a query gives a value, or ends in a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/members.md#members-host-calls), which DOMQL carries out as its declaration says, by subscribing to an event source, or by executing once or running continuously an execution of that mode. The one entry point serves every request kind, and resolution refuses an operation the kind does not take before anything is evaluated or started, with a validation error that says what the request does and names the operation it takes: ```text Cannot execute 'panel.size': it produces a value. @@ -175,6 +175,6 @@ rowsQuery.select(0, "height"); - **A path's shape is checked at once.** `select` refuses, without resolving anything, a path item that is neither a written field's name nor an index that is a whole number and not negative, as `-1` and `1.5` are not. - **A path's fit is checked at resolution.** Whether a field exists, and whether an index applies to a list, is checked when an operation resolves the query, before anything is evaluated or observed; a selection of a query whose vocabulary is not yet registered is therefore made without failing. - **What it gives.** A nullable ancestor and a list index out of range give null, and a list index follows a position, never a particular element. -- **Dictionaries and pairs** are selected in the form a [result holds them](results.md#results-collections), as Nexo's [result paths](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/resolution.md#runtime-result-paths) step into them: `select("counts", "entries")` gives a dictionary's entries, `select("counts", "entries", 0, "value")` the value of its first, and `select("range", "key")` a pair's key. Any other name after a dictionary or a pair is refused at resolution. +- **Dictionaries and pairs** are selected in the form a [result holds them](results.md#results-collections), as Nexo's [result paths](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/resolution.md#runtime-result-paths) step into them: `select("counts", "entries")` gives a dictionary's entries, `select("counts", "entries", 0, "value")` the value of its first, and `select("range", "key")` a pair's key. Any other name after a dictionary or a pair is refused at resolution. - **The whole query.** A selection reads the whole query's result, so the whole query decides its dependencies, its failures and its readiness. - **Its watch** delivers its first value, each change to that value, and its value again after a failed evaluation. It watches snapshots alone; a caller that wants live state of a smaller result writes that result in DOMQL. diff --git a/spec/results.md b/spec/results.md index c8a0c62..fb5a960 100644 --- a/spec/results.md +++ b/spec/results.md @@ -48,7 +48,7 @@ A snapshot never changes once delivered. A new snapshot reuses every immutable b - **What a change set is.** A change set is a [JSON Patch](https://www.rfc-editor.org/rfc/rfc6902) document limited to `replace`, `add`, `remove` and `move`, whose paths are JSON Pointers into the result; applying it to the result it was computed against gives the new result. A field the change set leaves out is unchanged, and a field that became null is replaced with null. An object expression's fields are fixed, so `add` and `remove` apply to list items alone. - **Lists.** A list whose items descend from elements changes by element: an element entering is added, one leaving is removed, one changing position is moved, and one whose result changed is changed inside its item. Any other list changes by position. -- **Identity.** Two elements can project to the same data, so the identity of each item cannot be read back from a snapshot. Each item is matched by the reference it descends from, its provenance, which Nexo's [result metadata](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/evaluation.md#runtime-results-provenance) records beside the result and which neither a result nor a change set ever holds: the source the earliest projection the item descends from read, which Nexo classifies as a reference or as data. A list projected from elements is matched by element, and so are a projection of its items and a list filtered, sliced or ordered from it, each by the element its item first came from. +- **Identity.** Two elements can project to the same data, so the identity of each item cannot be read back from a snapshot. Each item is matched by the reference it descends from, its provenance, which Nexo's [result metadata](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/evaluation.md#runtime-results-provenance) records beside the result and which neither a result nor a change set ever holds: the source the earliest projection the item descends from read, which Nexo classifies as a reference or as data. A list projected from elements is matched by element, and so are a projection of its items and a list filtered, sliced or ordered from it, each by the element its item first came from. - **Its source in the browser.** A watch answers the reference an item descends from to a caller in the browser, through [`sourceOf`](watches.md#watching-source-elements), and never in the result. - **Matched by position.** A list no projection built, one an item of which descends from data or from null, and one in which an element stands twice, are matched by position. DOMQL reads the classification Nexo reports, never inferring a reference from the value. - **What a change set reproduces.** A change set takes the result it was computed against to the reconciled snapshot, the one the watch reports, with every comparison and tolerance applied; it never describes a different, raw evaluation. @@ -89,7 +89,7 @@ A number a conditional gave compares within the tolerance of the member its bran ## Dictionaries and pairs -A result holds a dictionary or a pair as data, in the form Nexo [exports](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/evaluation.md#runtime-host-forms) them: a dictionary as `{ entries: [{ key, value }, …] }`, its entries in their order, and a pair as `{ key, value }`. +A result holds a dictionary or a pair as data, in the form Nexo [exports](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/evaluation.md#runtime-host-forms) them: a dictionary as `{ entries: [{ key, value }, …] }`, its entries in their order, and a pair as `{ key, value }`. - **Compared and changed as data.** A watch compares them as it compares any object and list, and a change set addresses them in that form: an entry's value is changed at `/counts/entries/0/value`, and an entry entering or leaving is added or removed at its position in `entries`. - **A key is data.** A numeric key is an entry's `key`, never a list index, and a change set reaches an entry by its position in `entries`, never by its key. A [selection](queries.md#selecting-a-result) steps into them in that form, as `select("counts", "entries", 0, "value")`. diff --git a/spec/terms.md b/spec/terms.md index 6a97702..71f2f74 100644 --- a/spec/terms.md +++ b/spec/terms.md @@ -2,7 +2,7 @@ -Each term this specification uses, what it means, and where its authoritative explanation is. A term here defines nothing its linked document does not, and a term of the language, as a script, a binding, a member, an import, a module or a host call, is [the language's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/terms.md), and one of the runtime, as a registry, a resolution or a module key, is [the runtime's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/terms.md), each Nexo's. +Each term this specification uses, what it means, and where its authoritative explanation is. A term here defines nothing its linked document does not, and a term of the language, as a script, a binding, a member, an import, a module or a host call, is [the language's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/terms.md), and one of the runtime, as a registry, a resolution or a module key, is [the runtime's](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/terms.md), each Nexo's. In this document: @@ -72,7 +72,7 @@ In this document: | Term | Meaning | Reference | | --- | --- | --- | -| Host call | Nexo's call of a function the host invokes, which ends a query; DOMQL carries each out as an event source or an execution | [Host calls](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/members.md#members-host-calls) | +| Host call | Nexo's call of a function the host invokes, which ends a query; DOMQL carries each out as an event source or an execution | [Host calls](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/members.md#members-host-calls) | | Event source | A host call that delivers things that happened, as `on(type)` does | [Event sources](events.md#event-sources) | | Event type | A key of DOMQL's type selector `event`, which names the type its events are captured as | [Event types](events.md#event-types) | | Subscription | A query whose chain ends in an event source, which shapes each event into data | [Events](events.md#events) | diff --git a/spec/vocabulary.md b/spec/vocabulary.md index 9e7b6b0..aba41e0 100644 --- a/spec/vocabulary.md +++ b/spec/vocabulary.md @@ -17,7 +17,7 @@ Properties and functions are named in camelCase, and names are case-sensitive. B -**Properties and functions.** The vocabulary follows Nexo's rule for [states and tests](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/vocabulary.md#vocabulary-boolean-functions): a property names what its receiver is, has or is in, and a function does work or takes what it needs. +**Properties and functions.** The vocabulary follows Nexo's rule for [states and tests](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/vocabulary.md#vocabulary-boolean-functions): a property names what its receiver is, has or is in, and a function does work or takes what it needs. - **A state is a property.** What the user, the browser or the page sets and clears, as whether an element is checked, focused or hovered, is a Boolean property read without a call, `panel.checked`, as [states](#states) set out. - **An execution is a function.** A change DOMQL makes is named by the verb it carries out and called with its parentheses, whether or not it takes an argument, `panel.focus()`, as [executions](#built-in-executions) set out. @@ -42,7 +42,7 @@ In this document: ## Module members -DOMQL's module, `Domql`, declares two [module members](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/modules.md#namespaces-module-members), read through its namespace, each with no receiver: +DOMQL's module, `Domql`, declares two [module members](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/modules.md#namespaces-module-members), read through its namespace, each with no receiver: | Member | Type | Reads | Changes | | --- | --- | --- | --- | @@ -55,7 +55,7 @@ Neither needs a binding, and a caller's binding named `Domql` is read as `~Domql ## Types -DOMQL's module declares each of its types with its members, as Nexo's [declaring a type](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/modules.md#modules-declaring-a-type) sets out: its reference types, which a query reads through and a result never holds, and its structured types, which hold data. Its `typeOf` recognizes the values a host binds, and each reference type's `isInstance` checks membership: +DOMQL's module declares each of its types with its members, as Nexo's [declaring a type](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/modules.md#modules-declaring-a-type) sets out: its reference types, which a query reads through and a result never holds, and its structured types, which hold data. Its `typeOf` recognizes the values a host binds, and each reference type's `isInstance` checks membership: | Reference type | Supertype | What it is | Where a value has the type | | --- | --- | --- | --- | @@ -99,11 +99,11 @@ An element with a layout box whose dimensions are zero has actual measurements o -**Tolerance.** A member that measures layout in CSS pixels declares a [tolerance](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/members.md#what-a-member-declares-numeric-tolerance) of 0.05, a twentieth of a pixel, for every number it answers, so a watch reports a measurement only once it moves by more than that from the one it last reported, as [comparing snapshots](results.md#comparing-snapshots) sets out: +**Tolerance.** A member that measures layout in CSS pixels declares a [tolerance](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/members.md#what-a-member-declares-numeric-tolerance) of 0.05, a twentieth of a pixel, for every number it answers, so a watch reports a measurement only once it moves by more than that from the one it last reported, as [comparing snapshots](results.md#comparing-snapshots) sets out: - **What it absorbs.** A box settling by a unit of the browser's layout, 1/64 of a pixel in Chromium and WebKit and 1/60 in Firefox, and the rounding of the arithmetic that answers a measurement, as `right` is `left` and `width` added. - **What it reports.** Any move a device pixel shows, which is a quarter of a pixel at a device pixel ratio of 4. A move made in steps smaller than the tolerance is reported once the steps add up to more, since each is compared with the measurement last reported. -- **Who declares it.** `rect`, `clientRect`, `rectRelativeTo`, `size`, `clientSize`, `layoutSize`, `scroll` and `grid` of an element, and `size` and `scroll` of the window. A number computed from one, as `it.rect?.width / 2`, compares exactly, as Nexo's [arithmetic](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/expressions.md#arithmetic-watching) sets out, and an evaluation once is never rounded. +- **Who declares it.** `rect`, `clientRect`, `rectRelativeTo`, `size`, `clientSize`, `layoutSize`, `scroll` and `grid` of an element, and `size` and `scroll` of the window. A number computed from one, as `it.rect?.width / 2`, compares exactly, as Nexo's [arithmetic](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/expressions.md#arithmetic-watching) sets out, and an evaluation once is never rounded. Scrolling reads the same way, along the axes of a box's writing mode: @@ -627,7 +627,7 @@ An element that is no scroll container is scrolled by 0. Null while it has no la ### List: count, first, last -`count`, `first` and `last` are properties [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. +`count`, `first` and `last` are properties [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. @@ -869,7 +869,7 @@ A box whose overflow is not `visible` along one axis computes `visible` as `auto ### List: item -The unnamed indexer, `[index]`, is an indexer [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. +The unnamed indexer, `[index]`, is an indexer [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. @@ -877,7 +877,7 @@ The unnamed indexer, `[index]`, is an indexer [Nexo's own module](https://github ### List: max, min, sum -`max`, `min` and `sum` are functions [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. +`max`, `min` and `sum` are functions [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. @@ -885,7 +885,7 @@ The unnamed indexer, `[index]`, is an indexer [Nexo's own module](https://github ### List: where -`where` is a function [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. +`where` is a function [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/collections.md#collections-list-members) declares, which owns lists, and Nexo's specification defines. @@ -897,7 +897,7 @@ The unnamed indexer, `[index]`, is an indexer [Nexo's own module](https://github ## States -A **state** is what the user, the browser or the page sets and clears over time, as whether an element is checked; a presence, as whether it is focused; or a capability the browser offers, as whether it can share. Each is a Boolean property, as Nexo's [states and tests](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/vocabulary.md#vocabulary-boolean-functions) set out: +A **state** is what the user, the browser or the page sets and clears over time, as whether an element is checked; a presence, as whether it is focused; or a capability the browser offers, as whether it can share. Each is a Boolean property, as Nexo's [states and tests](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/vocabulary.md#vocabulary-boolean-functions) set out: - **Reading one.** A query reads a state where it stands, `it.checked`, or through its module, its receiver first, `Domql.checked(it)`, and each way reaches the one declaration, whose observations follow it. - **Filtering by one.** A query filters by a state with a body, `rows.where(it.checked)`. Only a function has a reference, so `rows.where(Domql.checked)` is refused (NEXO3076). @@ -1229,7 +1229,7 @@ Each reads the element's own attribute under a contract of its own, falling back So `it.checked or it.aria.checked` is whether either says checked, and `it.aria["checked"] == "mixed"` tells a mixed state, which the ARIA view's `checked` answers false for, from the others. The ARIA view's unnamed indexer reads the attribute written on the element, as `it["aria-checked"]` does, and never the element's effective accessibility state. -No other ARIA attribute has a state until one is declared, each with a contract of its own, since not every ARIA attribute is a Boolean; an extension declares one on the ARIA view, a type it does not own, as the [rules for extensions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/extensions.md#extensions) let any module do. +No other ARIA attribute has a state until one is declared, each with a contract of its own, since not every ARIA attribute is a Boolean; an extension declares one on the ARIA view, a type it does not own, as the [rules for extensions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/extensions.md#extensions) let any module do. @@ -1514,7 +1514,7 @@ Module code holds a target the same way, through an owned write it runs with [`e ## Built-in conversions -A query converts with the four conversions [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/modules.md#vocabulary-conversions) declares between the language's types of data, which DOMQL's module, owning none of those types, declares none of; each rejects a value it cannot convert: +A query converts with the four conversions [Nexo's own module](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/modules.md#vocabulary-conversions) declares between the language's types of data, which DOMQL's module, owning none of those types, declares none of; each rejects a value it cannot convert: | From | To | Converts | | --- | --- | --- | @@ -1527,7 +1527,7 @@ A query converts with the four conversions [Nexo's own module](https://github.co ## Observations -A member names the [observations](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/observations.md#observations) that cover its changes, each by its type and its target, and DOMQL starts each one that a watch, a waiting evaluation or an event's object expression needs, and stops it once nothing needs it. DOMQL's module declares the browser's observations as twelve observation types, each animation frame as a thirteenth, and the state a behavior offers as a fourteenth, which the members of any module and module code through its [environment](#extension-modules-environment) can name, and five observation targets. +A member names the [observations](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/observations.md#observations) that cover its changes, each by its type and its target, and DOMQL starts each one that a watch, a waiting evaluation or an event's object expression needs, and stops it once nothing needs it. DOMQL's module declares the browser's observations as twelve observation types, each animation frame as a thirteenth, and the state a behavior offers as a fourteenth, which the members of any module and module code through its [environment](#extension-modules-environment) can name, and five observation targets. @@ -1556,7 +1556,7 @@ Each type is shared by equivalent requests, those of the same target and the sam ### Observation targets -An observation observes its member's receiver, an argument, `{ argument }`, or a target DOMQL's module declares, as Nexo's [observation targets](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/observations.md#observations-targets) set out: +An observation observes its member's receiver, an argument, `{ argument }`, or a target DOMQL's module declares, as Nexo's [observation targets](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/observations.md#observations-targets) set out: | Target | Found from the receiver | Observes | | --- | --- | --- | @@ -1572,7 +1572,7 @@ DOMQL resolves each target as it starts an observation, and each evaluation that ## Extension modules -A module extends the built-in vocabulary as Nexo's [modules](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/modules.md#modules) set out: it declares types of its own, each with its members and operators, states among them, and event types, executions and observation types, and adds members to DOMQL's types in its [extensions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/extensions.md#extensions), each naming the one type it extends qualified, as `{ name: 'ChartElements', kind: 'extension', target: 'Domql.Element', members: [/* … */] }` adds members to elements. `domql.createModule(name, contents)` creates one from its declarations, each that runs code carrying its implementation as its `impl`, and `domql.registerModule(module)` registers it in the instance's registry, which holds DOMQL's module and every module registered with it. A request is resolved against the modules it imports, registered by then, so a module a query imports is registered beforehand, once, rather than for every evaluation. +A module extends the built-in vocabulary as Nexo's [modules](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/modules.md#modules) set out: it declares types of its own, each with its members and operators, states among them, and event types, executions and observation types, and adds members to DOMQL's types in its [extensions](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/extensions.md#extensions), each naming the one type it extends qualified, as `{ name: 'ChartElements', kind: 'extension', target: 'Domql.Element', members: [/* … */] }` adds members to elements. `domql.createModule(name, contents)` creates one from its declarations, each that runs code carrying its implementation as its `impl`, and `domql.registerModule(module)` registers it in the instance's registry, which holds DOMQL's module and every module registered with it. A request is resolved against the modules it imports, registered by then, so a module a query imports is registered beforehand, once, rather than for every evaluation. ```js domql.registerModule(domql.createModule("Charts", { @@ -1593,15 +1593,15 @@ domql.registerModule(domql.createModule("Charts", { domql.query("import Charts\npanel:palette", { panel }).evaluate(); ``` -- **A query imports it, and reads its extensions with `:`.** A query that uses a module's vocabulary imports the module, `import Charts`, as [its imports](queries.md#making-a-query-imports) set out, and reads a member an extension adds with `:`, never `.`: `panel:palette`, or `panel:ChartElements.palette` where two of its extensions declare one name, as Nexo's [extension access](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/extensions.md#extensions-access) sets out. DOMQL's own members stand within its types, so a query reads them with `.`. +- **A query imports it, and reads its extensions with `:`.** A query that uses a module's vocabulary imports the module, `import Charts`, as [its imports](queries.md#making-a-query-imports) set out, and reads a member an extension adds with `:`, never `.`: `panel:palette`, or `panel:ChartElements.palette` where two of its extensions declare one name, as Nexo's [extension access](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/extensions.md#extensions-access) sets out. DOMQL's own members stand within its types, so a query reads them with `.`. - **DOMQL's members win on its types.** A name DOMQL's type declares is read with `.` as DOMQL's, and an extension's member of that name is read with `:` alone. Two modules' extensions declaring one name both register, and a query that reads the name where neither is more specific is refused where it does so (NEXO3024), naming the extensions to write. - **States and work.** A module declares a state as a Boolean property, and a member that does work or takes an argument as a function, as [properties and functions](#vocabulary-properties-and-functions) set out; Nexo refuses neither form, so a module follows the rule itself. -- **What an implementation receives.** Every implementation receives the one object Nexo's [implementations](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/members.md#members-what-an-implementation-receives) receive, whose `env` is the [environment](#extension-modules-environment) of the operation that reaches it. -- **Arguments.** A host call's implementation receives its arguments as Nexo prepares them, by parameter name. A null argument whose parameter accepts null is passed as it stands, as a bound of null meaning the viewport, and one whose parameter propagates null skips the call, as [Nexo's null arguments](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/members.md#nullability-a-null-argument-follows-the-parameter) set out. An option of a structured type, written in place as an object expression, as `buttons = { container = viewport, step = 3 }`, is [constructed](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/types.md#types-constructing-a-structure) as that type's data, a field of a reference type holding the element it names, and reaches the implementation as a frozen structure. +- **What an implementation receives.** Every implementation receives the one object Nexo's [implementations](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/members.md#members-what-an-implementation-receives) receive, whose `env` is the [environment](#extension-modules-environment) of the operation that reaches it. +- **Arguments.** A host call's implementation receives its arguments as Nexo prepares them, by parameter name. A null argument whose parameter accepts null is passed as it stands, as a bound of null meaning the viewport, and one whose parameter propagates null skips the call, as [Nexo's null arguments](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/members.md#nullability-a-null-argument-follows-the-parameter) set out. An option of a structured type, written in place as an object expression, as `buttons = { container = viewport, step = 3 }`, is [constructed](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/types.md#types-constructing-a-structure) as that type's data, a field of a reference type holding the element it names, and reaches the implementation as a frozen structure. -- **Kept functions.** A host call's function argument, as a test of what a behavior hears, `when = it.matches(".pick")`, reaches its implementation as a function it keeps and calls later, a [kept function](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/host-calls.md#runtime-host-calls-kept-functions): each call reads the page as it is then, through the locals and the bindings the call was prepared with, as a query evaluated once reads, so a member it reads reads alone, and is checked against the parameter's contract. DOMQL ends the functions an execution keeps as the execution ends: a continuous execution's as its instance ends, and as an update gives its instance others, once the instance accepted them; a once execution's as its implementation's answer settles, a canceled one's among them; and an event source's as its subscription ends. A call of one afterwards fails with Nexo's NEXO5051, which the implementation receives as it does any failure of the call. +- **Kept functions.** A host call's function argument, as a test of what a behavior hears, `when = it.matches(".pick")`, reaches its implementation as a function it keeps and calls later, a [kept function](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/host-calls.md#runtime-host-calls-kept-functions): each call reads the page as it is then, through the locals and the bindings the call was prepared with, as a query evaluated once reads, so a member it reads reads alone, and is checked against the parameter's contract. DOMQL ends the functions an execution keeps as the execution ends: a continuous execution's as its instance ends, and as an update gives its instance others, once the instance accepted them; a once execution's as its implementation's answer settles, a canceled one's among them; and an event source's as its subscription ends. A call of one afterwards fails with Nexo's NEXO5051, which the implementation receives as it does any failure of the call. - **Reading.** A member's implementation is synchronous and reads alone, as Nexo requires of every vocabulary, so evaluating, watching and subscribing change nothing; a change to the page is an [execution](executions.md). - **Event types.** A module adds event types of its own as keys of DOMQL's type selector `event`, each a mapping, `{ selector: 'event', key, type }`, naming the type its events are captured as, so `on` listens to them as it listens to the built-in ones. - **Observations.** A member of any module names DOMQL's observation types and targets as DOMQL's own members do. DOMQL resolves the targets its own module declares alone, so a module declaring observation targets of its own is refused when it is registered, and an observation type a module declares, which owns no target, observes the receiver or an argument. An observation type a module declares is started by its implementation, which receives `request`, the observation's `type`, its `target` and its `arguments`, each argument the member names resolved to its value; `notify`, which it calls when what it observes may have changed; and `env`, [an observation's environment](#extension-modules-observation-environment). It answers an object whose `stop()` ends the observation and, for a maintained observation, whose `sample()` answers its latest sample, `{ pending, value }`. A maintained observation whose sample can lag behind the page, as one the browser reports after it lays a frame out, offers `resampleAsync()` too: it takes a new sample and answers a promise that settles once that sample has arrived, which a [refresh that resamples](watches.md#watching-resampling) waits for. One that offers none is read as it stands, its sample taken to be current whenever `sample()` answers it. @@ -1626,7 +1626,7 @@ An operation gives every implementation it reaches one environment, its `env`, m -**History per holder.** The environment is one per operation, so a member that reads captured values, keeping what it measured before as Nexo's [captured reading](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/members.md#how-a-member-reads) has its holder keep it, keys that history by its environment and its receiver, in a `WeakMap` of its own: each watch, wait and subscription keeps its own, from its start to its end, and lets it go with the operation, and an evaluation once, whose environment is its own, reports what it sees with none. +**History per holder.** The environment is one per operation, so a member that reads captured values, keeping what it measured before as Nexo's [captured reading](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/members.md#how-a-member-reads) has its holder keep it, keys that history by its environment and its receiver, in a `WeakMap` of its own: each watch, wait and subscription keeps its own, from its start to its end, and lets it go with the operation, and an evaluation once, whose environment is its own, reports what it sees with none. @@ -1640,10 +1640,10 @@ An operation gives every implementation it reaches one environment, its `env`, m ### Registering a module while requests run -A query's imports decide what it resolves against, so a module registered later changes no resolution's meaning: a running watch, subscription or continuous execution keeps the resolution it has, and goes on evaluating and delivering, as Nexo keeps a resolution [current](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/resolution.md#runtime-reuse). +A query's imports decide what it resolves against, so a module registered later changes no resolution's meaning: a running watch, subscription or continuous execution keeps the resolution it has, and goes on evaluating and delivering, as Nexo keeps a resolution [current](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/resolution.md#runtime-reuse). -- **A module that recognizes values.** A module declaring a `typeOf` may recognize values a resolution captures, so it makes stale the resolutions that may meet such a value, as Nexo's [reusing a resolution](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/resolution.md#runtime-reuse) sets out: one whose host call supplies `DomEvent`, whose `target` is a nullable reference, among them. An operation started after it resolves its request again. -- **A running watch or a waiting evaluation made stale** resolves its request again at its next evaluation, which evaluates the whole query anew, as each of its evaluations does, so it goes on as before. A watch compares that evaluation's result as it compares any, within each value's tolerance: Nexo gives every resolution of one definition the same [origins](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/evaluation.md#runtime-results) where it selects the same declarations. Resolving again checks what starting the watch checked, and its refusal is that evaluation's failure. +- **A module that recognizes values.** A module declaring a `typeOf` may recognize values a resolution captures, so it makes stale the resolutions that may meet such a value, as Nexo's [reusing a resolution](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/resolution.md#runtime-reuse) sets out: one whose host call supplies `DomEvent`, whose `target` is a nullable reference, among them. An operation started after it resolves its request again. +- **A running watch or a waiting evaluation made stale** resolves its request again at its next evaluation, which evaluates the whole query anew, as each of its evaluations does, so it goes on as before. A watch compares that evaluation's result as it compares any, within each value's tolerance: Nexo gives every resolution of one definition the same [origins](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/evaluation.md#runtime-results) where it selects the same declarations. Resolving again checks what starting the watch checked, and its refusal is that evaluation's failure. - **A subscription or a once execution made stale** prepares its request again where a value its host call supplies is next projected: at the next event, or as the execution's result arrives. Where that preparation reaches the declaration it was carried out through, the value is projected through it, its locals and the object expression evaluated as that preparation finds them, and a subscription goes on listening with the receiver and the arguments its event source started with. Where it reaches none, or another, the subscription hands its handler the failure `DOMQL5015` and ends, and the once execution rejects with it, its effect standing. Where preparing it again fails, the subscription hands its handler that failure and ends, and the once execution rejects with it. @@ -1672,7 +1672,7 @@ chart.evaluate(); ### Host calls DOMQL carries out -A module declares an event source or an execution as a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/members.md#members-host-calls), a function with `invokedBy: 'host'`, within a type, within an extension, or among its module members, and gives DOMQL what Nexo leaves to its host: the `requestKind` the call makes, `subscription` for an event source or `execution`; an execution's `executionMode`, `once` or `continuous`; and the `impl` that carries it out. `domql.createModule` keeps these in DOMQL's own catalog, and gives Nexo the declaration without them, so Nexo resolves and prepares the call and DOMQL alone invokes it. One declaration standing within several types, as DOMQL's `on` does within `Element`, `Document` and `Window`, is kept for each. +A module declares an event source or an execution as a [host call](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/members.md#members-host-calls), a function with `invokedBy: 'host'`, within a type, within an extension, or among its module members, and gives DOMQL what Nexo leaves to its host: the `requestKind` the call makes, `subscription` for an event source or `execution`; an execution's `executionMode`, `once` or `continuous`; and the `impl` that carries it out. `domql.createModule` keeps these in DOMQL's own catalog, and gives Nexo the declaration without them, so Nexo resolves and prepares the call and DOMQL alone invokes it. One declaration standing within several types, as DOMQL's `on` does within `Element`, `Document` and `Window`, is kept for each. | Host call | `requestKind` | `executionMode` | Its `result` | Its implementation receives | It answers | | --- | --- | --- | --- | --- | --- | @@ -1686,4 +1686,4 @@ An event source, a behavior's or one its module implements, may declare `answers `domql.createModule` refuses, with a module error naming the declaration, the type it stands within and the key, of the code [errors](errors.md#errors-module) give, a host call whose `requestKind` is missing or neither `subscription` nor `execution`; an execution whose `executionMode` is missing or neither `once` nor `continuous`; an event source given an `executionMode`, or declaring no result, since each event it delivers is the value its subscription projects; a member the evaluator invokes given either key, an unnamed indexer named `[]`, as Nexo names it; a continuous execution that declares a result; a `behavior` on a continuous execution, or naming no behavior by a name; one naming no continuous execution of its module; an event source of a behavior declaring an `impl` or parameters; and an `answers` declared by anything but an event source, or other than a string of a type's notation. `domql.registerModule` refuses a module declaring a host call its catalog holds nothing of, as a module `domql.createModule` did not make. So an execution whose mode was left out is refused as an execution missing its mode. -On a receiver of unknown type, a host call has no declaration yet, so its [candidates](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/host-calls.md#runtime-host-calls), every declaration that takes the call as it is written, say what it does, as they say who invokes it. Where they disagree on what they request, the request is refused as ambiguous with a validation error, located at the call. +On a receiver of unknown type, a host call has no declaration yet, so its [candidates](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/host-calls.md#runtime-host-calls), every declaration that takes the call as it is written, say what it does, as they say who invokes it. Where they disagree on what they request, the request is refused as ambiguous with a validation error, located at the call. diff --git a/spec/watches.md b/spec/watches.md index e4ef733..068b8ee 100644 --- a/spec/watches.md +++ b/spec/watches.md @@ -69,7 +69,7 @@ In this document: ## How a member changes -Every member declares how its result changes, by the categories [Nexo defines](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/members.md#how-a-member-changes), and a watch decides by each what it may follow: +Every member declares how its result changes, by the categories [Nexo defines](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/members.md#how-a-member-changes), and a watch decides by each what it may follow: | Category | As in DOMQL | In a watch | | --- | --- | --- | @@ -78,7 +78,7 @@ Every member declares how its result changes, by the categories [Nexo defines](h | Partly observable | A computed style, which a rule outside the element can change unobserved | Allowed when the caller accepts partial observation for that watch; a change the observations miss reaches the watch at its next evaluation, which `refreshAsync` or another observed change causes. | | Unobserved | A member that names no observations | A validation error. | -A watch is checked against every member its query may read. A member of a value of `Any` is selected as the query is evaluated, so the watch is checked against every declaration of its name Nexo could select, as Nexo's [candidate declarations](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/runtime/resolution.md) overestimate them: a watch over `panel:bag.rect`, where a module's extension member `bag` answers `Any`, takes `acceptPartialObservation`, as one over `panel.rect` does. +A watch is checked against every member its query may read. A member of a value of `Any` is selected as the query is evaluated, so the watch is checked against every declaration of its name Nexo could select, as Nexo's [candidate declarations](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/resolution.md) overestimate them: a watch over `panel:bag.rect`, where a module's extension member `bag` answers `Any`, takes `acceptPartialObservation`, as one over `panel.rect` does. | Derived | A list's `first` or `where` | Allowed wherever what it derives from is. | A literal is constant, so a watched object expression can carry one: `viewport { kind = "viewport", width = it.layoutSize?.inline }`. @@ -105,7 +105,7 @@ A watch's dependencies are what its last evaluation actually read: each member a ### Following a change a member misses -A query follows a change its members miss by reading a member that observes it. A body's local runs whether or not anything uses it, as Nexo's [ordered evaluation](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.1/spec/language/scripts.md#bodies-ordered-evaluation) sets out, so it adds the dependency without adding to the result. A row a sibling's edit moves, which `rectRelativeTo` misses, is followed by reading the text around it: +A query follows a change its members miss by reading a member that observes it. A body's local runs whether or not anything uses it, as Nexo's [ordered evaluation](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/language/scripts.md#bodies-ordered-evaluation) sets out, so it adds the dependency without adding to the result. A row a sibling's edit moves, which `rectRelativeTo` misses, is followed by reading the text around it: ```domql let edited = panel.text diff --git a/tests/Domql.test.js b/tests/Domql.test.js index 2a06ff0..c05df6c 100644 --- a/tests/Domql.test.js +++ b/tests/Domql.test.js @@ -1287,7 +1287,7 @@ describe('domql evaluates', () => { try { const query = domql.query(text, { panel }); - expect(parse).toHaveBeenCalledWith(text, [{ module: 'Domql' }]); + expect(parse).toHaveBeenCalledWith(text, [{ module: 'Domql' }], null); expect(parse.mock.results[0].value).toBe(query.definition); } finally { parse.mockRestore(); @@ -4533,8 +4533,8 @@ describe('domql object root', () => { expect(refusalOf('{ a = 1, b = if f then root else null end }', { f: true }).message).toContain(heldBy('b')); }); - it('refuses root where no object expression encloses it, its receiver included, with a structure error', () => { - const message = "'root' refers to the outermost object being built, and no object expression encloses it here"; + it('refuses root where no object expression encloses it, its receiver included, with a structure error saying that a binding named root is read as ~root', () => { + const message = "'root' refers to the outermost object being built, and no object expression encloses it here; a script parameter named root is read as ~root"; expect(getError(() => domql.query('root.a'))).toMatchObject({ kind: 'structure', code: 'NEXO2018', message: expect.stringContaining(message) }); expect(getError(() => domql.query('root { a = 1 }'))).toMatchObject({ kind: 'structure', code: 'NEXO2018', message: expect.stringContaining(message) }); From bf49c527911ade1bf77c3ea145791af349d27e2a Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:57:00 +0200 Subject: [PATCH 06/15] perf(domql): read a call's location as it fails A continuous execution's start, a subscription's start and a once execution find where their call stands only where a failure names it, so one that fails nowhere reads its query's text no second time. In Node, a query's first run took about 0.47 ms where it took 0.58. --- CHANGELOG.md | 1 + src/dom/Behaviors.mjs | 10 +++++----- src/dom/EventListener.mjs | 5 ++--- src/dom/ExecutionHandle.mjs | 18 ++++++++++-------- src/domql.js | 14 ++++++++------ tests/dom/Behaviors.test.js | 21 +++++++++++++++++++++ 6 files changed, 47 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c7cc9e5..5d72211 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ Each release of DOMQL's packages, newest first. The npm package `@formaui-net/do - A watch of `autofilled` follows an animation the page's style starts on a field as the browser fills or empties it. - An event source declaring `answers` is answered: `deliver` fulfils with its first subscription's answer, the handler's return or its promise's value, captured as the declared type, where it fulfilled with undefined. - Runs on Nexo's language `1.0.0-preview.3`, from Nexo's release `1.0.0-preview.4`, as the [version history](VERSION-HISTORY.md#v1-0-0-preview-2) sets out: a refusal of `root` written where no object expression encloses it, or read other than through its fields, says that a binding named root is read as `~root`. `domql.info.versions.language` reports `1.0.0-preview.3`. +- A continuous execution's start, a subscription's start and a once execution find where their call stands only where a failure names it, so one that fails nowhere reads its query's text no second time: in Node, a query's first run took about 0.47 ms where it took 0.58, and its first once execution about 0.51 ms where it took 0.57. diff --git a/src/dom/Behaviors.mjs b/src/dom/Behaviors.mjs index 2278919..d5f37f4 100644 --- a/src/dom/Behaviors.mjs +++ b/src/dom/Behaviors.mjs @@ -191,14 +191,14 @@ export class Behaviors { * @param {RunningBehavior} running The instance delivering it. * @param {string} source The event source it is an occurrence of. * @param {unknown} value The occurrence. - * @param {object} location Where the behavior stands, which a delivery no subscription hears is located at. + * @param {() => object} locate Answers where the behavior stands, which a delivery no subscription hears is located at; called only then. * @returns {Promise} */ - deliver(running, source, value, location) { + deliver(running, source, value, locate) { const receivers = this.#listening.get(Behaviors.#keyOf(running.module, running.name, source))?.get(running.owner)?.get(running.receiver); if (receivers === undefined) { - return this.#unheardBy(running, source, location); + return this.#unheardBy(running, source, locate); } // One subscription's acknowledgment is the delivery's, fulfilled with its answer as it applies the occurrence, or rejected with its failure, as joining it alone would be. @@ -211,7 +211,7 @@ export class Behaviors { } /** The rejection of an occurrence of the running instance's source that no subscription hears, made at the first and answered until a subscription to the source listens for it. */ - #unheardBy(running, source, location) { + #unheardBy(running, source, locate) { let rejections = this.#unheard.get(running); if (rejections === undefined) { @@ -222,7 +222,7 @@ export class Behaviors { let rejected = rejections.get(source); if (rejected === undefined) { - rejected = Promise.reject(NexoError.evaluation('DOMQL5017', `No subscription of '${source}' listens for this owner on this receiver, so no subscriber applied the occurrence '${running.name}' delivered`, location)); + rejected = Promise.reject(NexoError.evaluation('DOMQL5017', `No subscription of '${source}' listens for this owner on this receiver, so no subscriber applied the occurrence '${running.name}' delivered`, locate())); // Handled as it is made, so a behavior that leaves it is never reported for it. rejected.catch(() => {}); diff --git a/src/dom/EventListener.mjs b/src/dom/EventListener.mjs index 1fc248a..4d77f33 100644 --- a/src/dom/EventListener.mjs +++ b/src/dom/EventListener.mjs @@ -176,7 +176,6 @@ export class EventListener { } const { declaration: { name }, pointer } = call; - const location = this.#getLocation(pointer); this.#sourceCall = call; this.#preparedCall = call; @@ -193,11 +192,11 @@ export class EventListener { try { sourceHandle = start(deliver); } catch (error) { - throw NexoError.evaluation('DOMQL5003', `The event source '${name}' failed to start listening`, location, { cause: error }); + throw NexoError.evaluation('DOMQL5003', `The event source '${name}' failed to start listening`, this.#getLocation(pointer), { cause: error }); } if (typeof sourceHandle?.stop !== 'function') { - throw NexoError.evaluation('DOMQL5004', `The event source '${name}' started listening and answered nothing that stops it`, location); + throw NexoError.evaluation('DOMQL5004', `The event source '${name}' started listening and answered nothing that stops it`, this.#getLocation(pointer)); } return sourceHandle; diff --git a/src/dom/ExecutionHandle.mjs b/src/dom/ExecutionHandle.mjs index 0a3c55a..7602bd6 100644 --- a/src/dom/ExecutionHandle.mjs +++ b/src/dom/ExecutionHandle.mjs @@ -163,7 +163,9 @@ export class ExecutionHandle { * an `error` event, and each occurrence it hands `deliver`, from its start on, is delivered to the subscriptions of its source listening for its owner on its receiver. */ #start({ name, module, sources, start, receiver, args, environment, resolution, pointer }) { - const location = resolution.getLocation(pointer); + // Where the execution stands, read once a failure is located there. + let location = null; + const locate = () => (location ??= resolution.getLocation(pointer)); const running = { module, name, owner: this.#owner, receiver, instance: null, hasEnded: false }; let instance; @@ -173,13 +175,13 @@ export class ExecutionHandle { args, env: environment, reportError: error => this.#eventDispatcher.raiseError(error), - deliver: (source, value) => this.#deliver(running, sources, location, source, value), + deliver: (source, value) => this.#deliver(running, sources, locate, source, value), notify: () => this.#behaviors.notify(running), }); } catch (error) { running.hasEnded = true; - throw NexoError.evaluation('DOMQL5007', `The execution '${name}' failed to start`, location, { cause: error }); + throw NexoError.evaluation('DOMQL5007', `The execution '${name}' failed to start`, locate(), { cause: error }); } if (typeof instance?.update !== 'function' || typeof instance?.dispose !== 'function') { @@ -192,7 +194,7 @@ export class ExecutionHandle { this.#eventDispatcher.reportError(error); } - throw NexoError.evaluation('DOMQL5008', `The execution '${name}' started and answered no update and dispose`, location); + throw NexoError.evaluation('DOMQL5008', `The execution '${name}' started and answered no update and dispose`, locate()); } running.instance = instance; @@ -207,19 +209,19 @@ export class ExecutionHandle { * instance that has ended delivers nothing and rejects, and a source its behavior has none of rejects and is raised as an `error` event, since it is the module's mistake. The promise is handled, so a behavior that * leaves it is never reported for it. */ - #deliver(running, sources, location, source, value) { + #deliver(running, sources, locate, source, value) { let delivered; try { if (running.hasEnded) { - delivered = Promise.reject(NexoError.evaluation('DOMQL5018', `The execution '${running.name}' has ended, and delivers nothing more`, location)); + delivered = Promise.reject(NexoError.evaluation('DOMQL5018', `The execution '${running.name}' has ended, and delivers nothing more`, locate())); } else if (!sources.has(source)) { - const error = NexoError.evaluation('DOMQL5019', `'${String(source)}' is no event source of '${running.name}', whose occurrences ${sources.size === 0 ? 'no source of its module delivers' : `are delivered to ${[...sources].map(name => `'${name}'`).join(', ')}`}`, location); + const error = NexoError.evaluation('DOMQL5019', `'${String(source)}' is no event source of '${running.name}', whose occurrences ${sources.size === 0 ? 'no source of its module delivers' : `are delivered to ${[...sources].map(name => `'${name}'`).join(', ')}`}`, locate()); this.#eventDispatcher.raiseError(error); delivered = Promise.reject(error); } else { - delivered = this.#behaviors.deliver(running, source, value, location); + delivered = this.#behaviors.deliver(running, source, value, locate); } } catch (error) { delivered = Promise.reject(error); diff --git a/src/domql.js b/src/domql.js index 17a7cc1..6637044 100644 --- a/src/domql.js +++ b/src/domql.js @@ -592,7 +592,9 @@ class Domql { return null; } - const location = resolution.getLocation(call.pointer); + // Where the call stands, read once a failure is located there. + let location = null; + const locate = () => (location ??= resolution.getLocation(call.pointer)); const { name } = call.declaration; const { module, behavior } = DispatchTable.get(call.declaration); const reached = behavior === null ? {} : { instance: Domql.#behaviors.find(module, behavior, owner, call.receiver) }; @@ -603,7 +605,7 @@ class Domql { execute = Domql.#implementationOf(call); if (reached.instance === null) { - throw NexoError.evaluation('DOMQL5016', `No '${behavior}' runs for this owner on this receiver, and the command '${name}' reaches its running instance alone`, location); + throw NexoError.evaluation('DOMQL5016', `No '${behavior}' runs for this owner on this receiver, and the command '${name}' reaches its running instance alone`, locate()); } } catch (error) { call.dispose(); @@ -612,7 +614,7 @@ class Domql { } const reportError = Domql.#createErrorReporter(window); - const createExecutionError = error => NexoError.evaluation('DOMQL5001', `The execution '${name}' failed: ${error?.message ?? String(error)}`, location, { cause: error }); + const createExecutionError = error => NexoError.evaluation('DOMQL5001', `The execution '${name}' failed: ${error?.message ?? String(error)}`, locate(), { cause: error }); return new Promise((resolve, reject) => { let isSettled = false; @@ -648,7 +650,7 @@ class Domql { let value; try { - value = call.project === undefined ? null : Domql.#projectResult(evaluator, call, result, location); + value = call.project === undefined ? null : Domql.#projectResult(evaluator, call, result, locate); } catch (error) { settle(() => reject(error)); @@ -883,7 +885,7 @@ class Domql { * Projects a once execution's result through its prepared call, or, where a module registered while it ran made the request stale, through the call prepared again, which the execution's own declaration must be, * refusing it otherwise; the execution's effect stands either way. */ - static #projectResult(evaluator, call, result, location) { + static #projectResult(evaluator, call, result, locate) { try { return call.project(result).value; } catch (error) { @@ -898,7 +900,7 @@ class Domql { again.dispose?.(); if (again.kind !== 'prepared' || again.declaration !== call.declaration) { - throw NexoError.evaluation('DOMQL5015', `A module registered since made the request of '${call.declaration.name}' stale, and preparing it again reaches ${again.kind === 'prepared' ? 'another host call' : 'no host call'}; carry it out again`, location); + throw NexoError.evaluation('DOMQL5015', `A module registered since made the request of '${call.declaration.name}' stale, and preparing it again reaches ${again.kind === 'prepared' ? 'another host call' : 'no host call'}; carry it out again`, locate()); } return again.project(result).value; diff --git a/tests/dom/Behaviors.test.js b/tests/dom/Behaviors.test.js index 1573297..3a1e6c7 100644 --- a/tests/dom/Behaviors.test.js +++ b/tests/dom/Behaviors.test.js @@ -631,6 +631,27 @@ describe('Behaviors\' occurrences', () => { expect(reported).toEqual([expect.objectContaining({ code: 'DOMQL5025' })]); }); + it('reads where a call stands only as a failure is located there, so a start, a subscription, a delivery and an execution that fail nowhere read no text again', async () => { + const { TextLocations } = await import('#nexo/language/TextLocations.mjs'); + const locate = vi.spyOn(TextLocations.prototype, 'locate'); + + try { + const { received } = listen('drops', { zone }); + + run({ zone }); + await zones[0].drop('a'); + await isolated.query('zone.focus()', { zone }).executeAsync(); + + expect(received).toEqual([{ key: 'a', label: 'files' }]); + expect(locate).not.toHaveBeenCalled(); + + await expect(zones[0].hover('b')).rejects.toMatchObject({ code: 'DOMQL5017', location: { pointer: '/expression/chain', line: 2, column: 1 } }); + expect(locate).toHaveBeenCalledTimes(1); + } finally { + locate.mockRestore(); + } + }); + it('rejects where no subscription listens, or one ends before it applies the occurrence, with DOMQL5017', async () => { run({ zone }); From a11a9f40622f7987fab546ed88e0081b284f6068 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:57:05 +0200 Subject: [PATCH 07/15] perf(domql): create its module from a manifest DOMQL's sources hold the manifest Nexo makes of DOMQL's own module, which npm run manifest writes and a test holds current. DOMQL creates its module and registry under it, so a start makes none of the checks it records: in Chromium, cold, the import took about 33.5 ms where it took 43. D115 records it. --- CHANGELOG.md | 1 + CLAUDE.md | 2 +- CONTRIBUTING.md | 5 +- docs/decisions.md | 19 +++++++ docs/domql-design.md | 4 +- package.json | 3 +- scripts/module-manifest.mjs | 37 ++++++++++++ scripts/packages/npm.files | 1 + src/dom/BrowserModule.mjs | 24 ++++++-- src/dom/BrowserVocabularyDeclarations.mjs | 18 ++++-- src/dom/DispatchTable.mjs | 69 ++++++++++++++++------- src/dom/ModuleManifest.mjs | 5 ++ src/domql.js | 6 +- tests/dom/BrowserModule.test.js | 14 +++++ tests/dom/DispatchTable.test.js | 47 +++++++++++++++ tests/dom/ModuleManifest.test.js | 32 +++++++++++ 16 files changed, 251 insertions(+), 36 deletions(-) create mode 100644 scripts/module-manifest.mjs create mode 100644 src/dom/ModuleManifest.mjs create mode 100644 tests/dom/ModuleManifest.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d72211..60112ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ Each release of DOMQL's packages, newest first. The npm package `@formaui-net/do - An event source declaring `answers` is answered: `deliver` fulfils with its first subscription's answer, the handler's return or its promise's value, captured as the declared type, where it fulfilled with undefined. - Runs on Nexo's language `1.0.0-preview.3`, from Nexo's release `1.0.0-preview.4`, as the [version history](VERSION-HISTORY.md#v1-0-0-preview-2) sets out: a refusal of `root` written where no object expression encloses it, or read other than through its fields, says that a binding named root is read as `~root`. `domql.info.versions.language` reports `1.0.0-preview.3`. - A continuous execution's start, a subscription's start and a once execution find where their call stands only where a failure names it, so one that fails nowhere reads its query's text no second time: in Node, a query's first run took about 0.47 ms where it took 0.58, and its first once execution about 0.51 ms where it took 0.57. +- DOMQL's module and its registry are created under the manifest Nexo makes of the module, which DOMQL's sources hold, so a start makes none of the checks it records: in Chromium, cold, DOMQL's import took about 33.5 ms where it took 43, and its first resolution and registrations about 2 ms more. DOMQL on a Nexo other than the one it was built against creates its module with every check, as before. diff --git a/CLAUDE.md b/CLAUDE.md index 328fce5..01161f9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -34,7 +34,7 @@ Use these sources rather than inventing scope, status or style rules. | `src/dom/` | Evaluation, watches, events, executions, observations, sessions and built-in implementations | | `src/snapshots/` | Computing, comparing, dispatching and applying snapshot updates using identity metadata; no DOM access | | `tests/` | Tests mirroring the source folders | -| `scripts/` | Bundling scripts, and the package's file lists and verification | +| `scripts/` | Bundling scripts, the manifest of DOMQL's own module, and the package's file lists and verification | | `spec/` | The specification, one document per subject, indexed by `spec/README.md` | | `docs/` | The design, the status overview and the decisions | | `VERSION-HISTORY.md` | Each DOMQL version and what it changed | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 528c397..2492947 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -41,7 +41,7 @@ Run the full build from the repository root: | `src/dom/` | DOM evaluation, observations, watches, events, executions and the dispatch table of host calls | | `src/snapshots/` | Snapshot comparison and updates | | `tests/` | Tests arranged to match the source folders | -| `scripts/` | Bundling scripts | +| `scripts/` | Bundling scripts, and the one that writes the manifest of DOMQL's own module, `npm run manifest` | | `nuget/` | Package project and library guide | | `spec/` | The specification, split by subject, with its index | | `docs/` | The design and the status overview | @@ -81,9 +81,10 @@ The simulated DOM does not calculate layout. Run browser tests from the reposito You can also run `npm run test:browser` from `tests/`, and `npm run test:engines` for the tests run in each engine. -Two details to keep in mind: +Three details to keep in mind: - **Module registration persists.** A test that registers a module needs its own `domql` instance. Call `vi.resetModules()` and import it afresh so tests remain independent of execution order. +- **DOMQL's own module has a manifest.** After a change to its declarations, run `npm run manifest` from the repository root, which writes `src/dom/ModuleManifest.mjs` again; a test fails until it does. - **README examples are tested.** When you change an example in the package guide, update its fixture in `tests/_examples/` and the answer `tests/PackageReadme.test.js` expects. The repository README's examples run as they are written. For performance changes, run `npm run bench` from `tests/` for simulated-DOM benchmarks and `npm run scale` for Chromium workloads: a watch of 1,000 to 100,000 rows, a drag through owned writes, an edit in a large editor, a behavior's deliveries and owners, and transient measurements beside many observers. Name a file to run one workload, as `npm run scale -- dom/OwnedWrites.scale.js`; each reports the machine's load as it ran, its own included, so compare runs made at a low load alone. Compare against a baseline kept in `.sandbox/`, keep gains that repeat beyond measurement noise, and record a conclusion that decides something in the [design](docs/domql-design.md), beside the decision it settles. Report the memory a change retains apart from what it allocates: a bound can slow a case's allocation and still end growth that outlived disposal, as [D84](docs/decisions.md#d84) did. Benchmarks are separate from the build gate. diff --git a/docs/decisions.md b/docs/decisions.md index e5912f0..9582c9d 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -1764,3 +1764,22 @@ Each entry is one of three kinds: - Nexo's `1.0.0-preview.3` and `1.0.0-preview.4` check a module, its registration and a script once, ahead of time, and record the checks in a manifest a host keeps. DOMQL's start can't read one from a release without them. - The language changes nothing a query relies on: a refusal of `root` says more, and the rest is Nexo's runtime, which DOMQL uses as a host. - **Declined:** Waiting for Nexo's next language. Nothing DOMQL needs is waiting there. + + + +## D115 — DOMQL creates its own module under a manifest its build makes + +*November 30, 2026* + +- **Kind:** Implementation, approved with the start-up DOMQL's modules and queries prepare ahead of time. +- **Decision:** + - DOMQL's sources hold `ModuleManifest`, the manifest `nexo.prepare` makes of DOMQL's own module, of the contents its dispatch table gives Nexo. + - `scripts/module-manifest.mjs` writes it, run as `npm run manifest`, and a test fails while it differs from the one the module's declarations give. + - DOMQL creates its module and its registry under it as it is imported. +- **Why:** + - Every start made the checks of DOMQL's module and of its registration, which its declarations alone decide, so its build can make them once. + - In Chromium, cold, over four alternating rounds of 11 runs, DOMQL's import took about 33.5 ms where it took 43. The first query's resolution and the first registrations took about 2 ms more, as Nexo resolves notations as they are first read. A start took about 50.5 ms where it took 58. + - Nexo reads a manifest of another implementation as holding no module, so a host that installs a later Nexo beside DOMQL's npm package starts as it did, every check made. +- **Declined:** + - Writing the manifest as the bundle is built. The npm package ships the sources, which must hold it. + - Preparing the module at import. It makes the very checks it would save. diff --git a/docs/domql-design.md b/docs/domql-design.md index f5a67de..e51a246 100644 --- a/docs/domql-design.md +++ b/docs/domql-design.md @@ -21,7 +21,7 @@ DOMQL is Nexo's host. It registers its module in a Nexo registry beside the modu | --- | --- | --- | | Entry point | Makes query objects from text or a definition, keeps their resolutions, registers modules, and composes the parts below into the public API | `domql.js` | | Query objects | A request's definition and bindings, through which every operation on it is carried out | `DomqlQuery` | -| The module | DOMQL's declarations, its types with their members within them, its recognition of the DOM's values, the implementations of its members and of its executions, the targets its owned writes hold, and the functions that start its observations, with what a selector reads | `BrowserVocabularyDeclarations`, `BrowserVocabularyImplementations`, `BrowserExecutionImplementations`, `OwnedWrites`, `BrowserObservationImplementations`, `Selectors`, `BrowserModule` | +| The module | DOMQL's declarations, the manifest Nexo makes of them, its types with their members within them, its recognition of the DOM's values, the implementations of its members and of its executions, the targets its owned writes hold, and the functions that start its observations, with what a selector reads | `BrowserVocabularyDeclarations`, `BrowserVocabularyImplementations`, `BrowserExecutionImplementations`, `OwnedWrites`, `BrowserObservationImplementations`, `Selectors`, `BrowserModule`, `ModuleManifest` | | Evaluation | Nexo's evaluator under hooks that record what an evaluation reads and hold the sessions that keep it observed | `QueryEvaluator`, `QueryEvaluation` | | Observations | Sessions on shared observations, each observation started on its first session and stopped with its last, and the mutation observers of DOMQL's own, which a transient measurement drains | `Observations`, `ObservationSession`, `SessionCache`, `MutationObservers` | | Frames | A window's animation frames, each running the writes module code asks for, then the reads, the evaluations of the watches scheduled by frame among them | `FrameSchedule` | @@ -33,6 +33,8 @@ DOMQL is Nexo's host. It registers its module in a Nexo registry beside the modu The DOM enters as late as it can. Making and resolving a query read no DOM, so they work in Node.js; code under `src/dom/` reads the window and the document it is given, never a global, and code under `src/snapshots/` reads no DOM at all, only the results and the metadata Nexo records beside them. Dependencies point one way: `dom/` depends on Nexo and `snapshots/`, and `snapshots/` on Nexo alone. +DOMQL creates its module, and the registry it registers it in, as it is imported, under `ModuleManifest`, the manifest Nexo makes of the module, so neither makes the checks of its declarations and their registration that the manifest records, as [Nexo's preparing modules](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/modules.md#modules-preparing) sets out. DOMQL's own checks of its host calls are made either way. `npm run manifest`, from the repository root, runs `scripts/module-manifest.mjs`, which writes the manifest as the dispatch table gives Nexo the module's contents. A test fails while the manifest the sources hold differs from the one the declarations give. Nexo reads a manifest another implementation made as holding no module, so DOMQL on a Nexo other than the one it was built against, as a host may install beside DOMQL's npm package, creates its module with every check. In Chromium, cold, the import took about 33.5 ms where it took 43, and the first query's resolution and the first registrations about 2 ms more, as Nexo resolves the module's notations as they are first read. [D115](decisions.md#d115) records the measurement. + DOMQL's `typeOf` and its types' `isInstance` recognize a node by its `nodeType` and a window by its being its own `window`, never by a global's prototype, so a node of another window is recognized as one of the window a query runs in is. A node holds functions, which data never does, so data that names a `nodeType` is never taken for a node. ## Resolution diff --git a/package.json b/package.json index d637a3b..c88d7a6 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,8 @@ "access": "public" }, "scripts": { - "bundle": "node scripts/bundle.mjs" + "bundle": "node scripts/bundle.mjs", + "manifest": "node scripts/module-manifest.mjs" }, "dependencies": { "@formaui-net/nexo": "^1.0.0-preview.4" diff --git a/scripts/module-manifest.mjs b/scripts/module-manifest.mjs new file mode 100644 index 0000000..4abbe38 --- /dev/null +++ b/scripts/module-manifest.mjs @@ -0,0 +1,37 @@ +/** + * module-manifest — the manifest Nexo makes of DOMQL's own module, written into the module DOMQL creates its module and registry under + */ + +import { readFile, writeFile } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { BrowserModule } from '../src/dom/BrowserModule.mjs'; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); + +/** Where DOMQL's sources hold the manifest. */ +export const moduleManifestPath = resolve(root, 'src', 'dom', 'ModuleManifest.mjs'); + +/** The text of the module holding the manifest Nexo makes of DOMQL's own module, as the Nexo DOMQL builds against makes it. */ +export function moduleManifestText() { + return [ + '/**', + " * ModuleManifest — the manifest Nexo makes of DOMQL's own module, which DOMQL creates its module and registry under; written by scripts/module-manifest.mjs", + ' */', + '', + `export const ModuleManifest = Object.freeze(${JSON.stringify(BrowserModule.prepare())});`, + '', + ].join('\n'); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const text = moduleManifestText(); + const current = await readFile(moduleManifestPath, 'utf8').catch(() => null); + + if (current === text) { + console.log(`${moduleManifestPath} is current`); + } else { + await writeFile(moduleManifestPath, text); + console.log(`Wrote the manifest of DOMQL's own module to ${moduleManifestPath}`); + } +} diff --git a/scripts/packages/npm.files b/scripts/packages/npm.files index 2561e0f..19cd792 100644 --- a/scripts/packages/npm.files +++ b/scripts/packages/npm.files @@ -18,6 +18,7 @@ src/dom/EventListener.mjs src/dom/ExecutionHandle.mjs src/dom/FocusChain.mjs src/dom/FrameSchedule.mjs +src/dom/ModuleManifest.mjs src/dom/MutationObservers.mjs src/dom/ObservationSession.mjs src/dom/Observations.mjs diff --git a/src/dom/BrowserModule.mjs b/src/dom/BrowserModule.mjs index 01b32c5..c9ce218 100644 --- a/src/dom/BrowserModule.mjs +++ b/src/dom/BrowserModule.mjs @@ -7,21 +7,35 @@ import { BrowserExecutionImplementations } from './BrowserExecutionImplementatio import { BrowserObservationImplementations } from './BrowserObservationImplementations.mjs'; import { BrowserVocabularyDeclarations } from './BrowserVocabularyDeclarations.mjs'; import { BrowserVocabularyImplementations } from './BrowserVocabularyImplementations.mjs'; +import { DispatchTable } from './DispatchTable.mjs'; import { MutationObservers } from './MutationObservers.mjs'; export class BrowserModule { /** * The DOM module, whose members read the window and the document they are given, whose executions change them, and whose observation types start observations of them, the state of the behaviors running among them. - * @param {{ behaviors?: Behaviors, mutationObservers?: MutationObservers }} [dependencies] The behaviors running in this instance of DOMQL, whose state the `behavior` observation follows, and its mutation observers, - * which its observations and its owned writes run and a transient measurement drains; a module of its own has those of its own. + * @param {{ behaviors?: Behaviors, mutationObservers?: MutationObservers, moduleManifest?: object | null }} [dependencies] The behaviors running in this instance of DOMQL, whose state the `behavior` observation + * follows, and its mutation observers, which its observations and its owned writes run and a transient measurement drains, a module of its own having those of its own; and the manifest `prepare` made of it, which + * the module is created under without the checks it records. */ - static create({ behaviors = new Behaviors(), mutationObservers = new MutationObservers() } = {}) { - return BrowserVocabularyDeclarations.createModule({ + static create({ behaviors = new Behaviors(), mutationObservers = new MutationObservers(), moduleManifest = null } = {}) { + return BrowserVocabularyDeclarations.createModule(BrowserModule.#implementationsOf(behaviors, mutationObservers), { moduleManifest }); + } + + /** The manifest Nexo makes of the DOM module, every check of its declarations and of their registration made, which `create` creates it under without those checks. */ + static prepare() { + const contents = BrowserVocabularyDeclarations.contentsOf(BrowserModule.#implementationsOf(new Behaviors(), new MutationObservers())); + + return DispatchTable.prepare([{ name: BrowserVocabularyDeclarations.moduleName, contents }]); + } + + /** The module's implementations, by the key each declaration is carried out under. */ + static #implementationsOf(behaviors, mutationObservers) { + return { ...BrowserVocabularyImplementations.implementations, ...BrowserExecutionImplementations.implementationsWith({ mutationObservers }), ...BrowserObservationImplementations.implementationsWith({ mutationObservers }), // The state the behaviors of a name offer on the target, which each instance's start, update, move and end tells, and its own notify. observeBehavior: ({ request: { target, arguments: { behavior } }, notify }) => behaviors.observe(behavior, target, notify), - }); + }; } } diff --git a/src/dom/BrowserVocabularyDeclarations.mjs b/src/dom/BrowserVocabularyDeclarations.mjs index 39b11c2..a8188f0 100644 --- a/src/dom/BrowserVocabularyDeclarations.mjs +++ b/src/dom/BrowserVocabularyDeclarations.mjs @@ -122,10 +122,10 @@ export class BrowserVocabularyDeclarations { static moduleName = 'Domql'; /** - * DOMQL's module, made as every module DOMQL carries out is, through its dispatch table: its declarations, each carrying the implementation given for it where one is. + * The contents of DOMQL's module, as its dispatch table takes them: its declarations, each carrying the implementation given for it where one is. * @param {Record} [implementations] The implementations, by the key each declaration is carried out under. */ - static createModule(implementations = {}) { + static contentsOf(implementations = {}) { // A declaration takes the implementation given under its key, and none where none is given, which leaves it resolved against and never invoked. const implementing = (key, declaration) => (implementations[key] === undefined ? declaration : { ...declaration, impl: implementations[key] }); const observationType = (name, contract, key, rest = {}) => implementing(key, { name, contract, ...rest }); @@ -153,7 +153,7 @@ export class BrowserVocabularyDeclarations { requestKind: 'subscription', }); - return DispatchTable.createModule(BrowserVocabularyDeclarations.moduleName, { + return { // A bound value's type: the kind of node it is, or the window. A text or a comment node is none, and is refused as a binding. typeOf: value => nodeKindOf(value) ?? (isWindow(value) ? 'Window' : isRange(value) ? 'Range' : null), @@ -476,7 +476,17 @@ export class BrowserVocabularyDeclarations { implementing('document', property('document', 'Document', { updates: updatesOf({ changes: 'constant' }) })), implementing('window', property('window', 'Window', { updates: updatesOf({ changes: 'constant' }) })), ], - }); + }; + } + + /** + * DOMQL's module, made as every module DOMQL carries out is, through its dispatch table: its declarations, each carrying the implementation given for it where one is, created under the module manifest given + * without the checks it records of the same contents. + * @param {Record} [implementations] The implementations, by the key each declaration is carried out under. + * @param {{ moduleManifest?: object | null }} [options] The manifest the dispatch table's `prepare` made of the module, or null. + */ + static createModule(implementations = {}, { moduleManifest = null } = {}) { + return DispatchTable.createModule(BrowserVocabularyDeclarations.moduleName, BrowserVocabularyDeclarations.contentsOf(implementations), undefined, moduleManifest); } /** DOMQL's module as its declarations alone, which is enough to resolve a query and carries nothing out. */ diff --git a/src/dom/DispatchTable.mjs b/src/dom/DispatchTable.mjs index 1036ae8..8fd6d14 100644 --- a/src/dom/DispatchTable.mjs +++ b/src/dom/DispatchTable.mjs @@ -30,16 +30,61 @@ export class DispatchTable { * that is no function are refused with a module error naming the declaration, an unnamed indexer as `[]`, as Nexo names it, the type it stands in where it stands in one, and the key; so is a `behavior` on a * declaration that reaches none, one naming no continuous execution of the module, and an event source of a behavior given an implementation or parameters, which DOMQL carries out. * A member the evaluator invokes declaring a `behavior` reads the state that behavior offers: its implementation receives the instance running for the environment's owner on its receiver, null where none runs. + * Under a manifest `prepare` made of the same contents, Nexo makes none of the checks it records; DOMQL's own checks, those above, are made either way. * @param {string} name The module's name. * @param {object} contents What the module declares. * @param {import('./Behaviors.mjs').Behaviors} [behaviors] The behaviors running, which a member reading a behavior's state finds its instance among. + * @param {object | null} [moduleManifest] A manifest `prepare` made of the module, which Nexo creates it from without the checks it records, or null. */ - static createModule(name, contents, behaviors) { + static createModule(name, contents, behaviors, moduleManifest = null) { // Contents Nexo refuses are left to it, which names what is wrong with them. if (contents === null || typeof contents !== 'object' || Array.isArray(contents)) { return nexo.createModule(name, contents); } + const { declared, memberDescriptors, typeDescriptors, sourcesOf } = DispatchTable.#describe(name, contents, behaviors); + const module = nexo.createModule(name, declared, moduleManifest === null ? undefined : { manifest: moduleManifest }); + + // A module keeps its types, and the members of each, in the order they were declared. + const keep = (declarations, descriptors) => declarations?.forEach((declaration, index) => { + const descriptor = descriptors?.[index]; + + if (descriptor != null) { + DispatchTable.#dispatchDescriptors.set(declaration, descriptor); + + if (descriptor.executionMode === 'continuous') { + DispatchTable.#sources.set(declaration, sourcesOf(declaration.name)); + } + } + }); + + keep(module.members, memberDescriptors); + module.types.forEach((type, index) => keep(type.members, typeDescriptors?.[index])); + + return module; + } + + /** + * The manifest Nexo makes of the modules given, each `{ name, contents }` as `createModule` takes them, in the order they are registered: of the contents Nexo is given for each, every check of each module and its + * registration made, refusing what `createModule` refuses, so a module `createModule` creates from it makes none of the checks it records. + * @param {{ name: string, contents?: object }[]} modules The modules, in the order they are registered. + */ + static prepare(modules) { + // What Nexo refuses is left to it, which names what is wrong with it. + const declaredOf = entry => { + const contents = entry?.contents; + + return contents === null || typeof contents !== 'object' || Array.isArray(contents) ? entry : { ...entry, contents: DispatchTable.#describe(entry.name, contents).declared }; + }; + + return nexo.prepare(Array.isArray(modules) ? modules.map(declaredOf) : modules); + } + + /** + * What the dispatch table keeps of a module's host calls, and the contents Nexo is given without them: each host call's descriptor, by its place among its type's members or the module's, and the event sources + * reaching each behavior, refusing what `createModule` refuses. + */ + static #describe(name, contents, behaviors) { const location = (type, declaration, declarationKey) => ({ module: String(name), ...(type === null ? {} : { type }), declaration: String(declaration), declarationKey }); const fail = (code, message, type, declaration, key) => { throw NexoError.module(code, message, location(type, declaration, key)); @@ -71,32 +116,16 @@ export class DispatchTable { fail('DOMQL4012', `'${unknown.descriptor.behavior}' is no continuous execution the module '${name}' declares, whose running instance a declaration naming it reaches`, unknown.type, unknown.name, 'behavior'); } - const module = nexo.createModule(name, { + const declared = { ...contents, ...(memberDescriptors === null ? {} : { members: declarationsOf(contents.members, memberDescriptors) }), ...(typeDescriptors === null ? {} : { types: contents.types.map((type, index) => (typeDescriptors[index] === null ? type : { ...type, members: declarationsOf(type.members, typeDescriptors[index]) })) }), - }); + }; // The event sources reaching each behavior, which its occurrences are delivered to by name. const sourcesOf = behavior => Object.freeze(new Set(described.filter(({ descriptor }) => descriptor.requestKind === 'subscription' && descriptor.behavior === behavior).map(entry => entry.name))); - // A module keeps its types, and the members of each, in the order they were declared. - const keep = (declarations, descriptors) => declarations?.forEach((declaration, index) => { - const descriptor = descriptors?.[index]; - - if (descriptor != null) { - DispatchTable.#dispatchDescriptors.set(declaration, descriptor); - - if (descriptor.executionMode === 'continuous') { - DispatchTable.#sources.set(declaration, sourcesOf(declaration.name)); - } - } - }); - - keep(module.members, memberDescriptors); - module.types.forEach((type, index) => keep(type.members, typeDescriptors?.[index])); - - return module; + return { declared, memberDescriptors, typeDescriptors, sourcesOf }; } /** A type's local name, as Nexo names it in a location, without the type parameters a declared name writes after it, as `ListExtensions` writes `T`; null for a name that is no string. */ diff --git a/src/dom/ModuleManifest.mjs b/src/dom/ModuleManifest.mjs new file mode 100644 index 0000000..c315a5f --- /dev/null +++ b/src/dom/ModuleManifest.mjs @@ -0,0 +1,5 @@ +/** + * ModuleManifest — the manifest Nexo makes of DOMQL's own module, which DOMQL creates its module and registry under; written by scripts/module-manifest.mjs + */ + +export const ModuleManifest = Object.freeze({"format":2,"implementation":"1.0.0-preview.4","modules":[{"name":"Domql","digest":"4b4aafe680c47b13d688","after":[]}],"scripts":[]}); diff --git a/src/domql.js b/src/domql.js index 6637044..fbec96c 100644 --- a/src/domql.js +++ b/src/domql.js @@ -11,6 +11,7 @@ import { ExecutionHandle } from './dom/ExecutionHandle.mjs'; import { DispatchTable } from './dom/DispatchTable.mjs'; import { FrameSchedule } from './dom/FrameSchedule.mjs'; import { MutationObservers } from './dom/MutationObservers.mjs'; +import { ModuleManifest } from './dom/ModuleManifest.mjs'; import { Observations } from './dom/Observations.mjs'; import { QueryEvaluator } from './dom/QueryEvaluator.mjs'; import { EventListener } from './dom/EventListener.mjs'; @@ -101,8 +102,9 @@ class Domql { /** The mutation observers this instance runs, which a transient measurement drains of the records its own change caused. */ static #mutationObservers = new MutationObservers(); - static #browserModule = BrowserModule.create({ behaviors: Domql.#behaviors, mutationObservers: Domql.#mutationObservers }); - static #moduleRegistry = nexo.createRegistry([Domql.#browserModule]); + // DOMQL's module and its registry, created under the manifest its build made of the module. + static #browserModule = BrowserModule.create({ behaviors: Domql.#behaviors, mutationObservers: Domql.#mutationObservers, moduleManifest: ModuleManifest }); + static #moduleRegistry = nexo.createRegistry([Domql.#browserModule], { manifest: ModuleManifest }); /** The loader of each module loaded on request, by its name, which a load asks where the registry holds no module of that name; kept for the instance's life. @type {Map unknown>} */ static #moduleLoaders = new Map(); diff --git a/tests/dom/BrowserModule.test.js b/tests/dom/BrowserModule.test.js index 0c2e482..2eb8daa 100644 --- a/tests/dom/BrowserModule.test.js +++ b/tests/dom/BrowserModule.test.js @@ -55,4 +55,18 @@ describe('BrowserModule', () => { it('leaves the DOM vocabulary alone declaring, with no implementation to carry anything out', () => { expect(declarationsOf(BrowserVocabularyDeclarations.module).filter(declaration => implementationOf(declaration) !== undefined)).toEqual([]); }); + + it('is created under the manifest its prepare makes as the module it is with every check, carried out alike, and the vocabulary alone is not', async () => { + const { Manifest } = await import('#nexo/language/vocabulary/Manifest.mjs'); + const manifest = BrowserModule.prepare(); + const created = BrowserModule.create({ moduleManifest: manifest }); + const namesOf = declared => declarationsOf(declared).map(declaration => [declaration.name, typeof implementationOf(declaration)]); + + expect(manifest.modules).toEqual([{ name: 'Domql', digest: expect.any(String), after: [] }]); + expect(Manifest.recordOf(created)?.digest).toBe(manifest.modules[0].digest); + expect(Manifest.recordOf(module)).toBeUndefined(); + expect(namesOf(created)).toEqual(namesOf(module)); + // A declaration carrying an implementation digests apart from one carrying none, so the vocabulary alone is created with every check. + expect(Manifest.recordOf(BrowserVocabularyDeclarations.createModule({}, { moduleManifest: manifest }))).toBeUndefined(); + }); }); diff --git a/tests/dom/DispatchTable.test.js b/tests/dom/DispatchTable.test.js index b3a112a..f524739 100644 --- a/tests/dom/DispatchTable.test.js +++ b/tests/dom/DispatchTable.test.js @@ -1,4 +1,6 @@ import { describe, it, expect } from 'vitest'; +import { nexo } from '@formaui-net/nexo'; +import { BrowserVocabularyDeclarations } from '#domql/dom/BrowserVocabularyDeclarations.mjs'; import { DispatchTable } from '#domql/dom/DispatchTable.mjs'; /** The module error creating a module throws: its code, its message, and where its location says it is. */ @@ -120,4 +122,49 @@ describe('DispatchTable', () => { expect(refusalOf({ members: {} })).toEqual({ code: 'NEXO4503', module: 'Desk', declarationKey: 'members', message: expect.stringContaining("A module's members are a list") }); expect(refusalOf({ members: [hostCall({ requestKind: 'execution', executionMode: 'once', result: 'Boolean', updates: { changes: 'constant', reads: 'fresh' } })] })).toEqual({ code: 'NEXO4030', module: 'Desk', declaration: 'mark', declarationKey: 'updates', message: expect.stringContaining('so it declares no updates') }); }); + + describe('a manifest', () => { + const execute = () => true; + const contents = () => ({ types: [elementExtension([hostCall({ requestKind: 'execution', executionMode: 'once', result: 'Boolean', impl: execute })])] }); + + /** The error a call throws: its code, and where its location says it is. */ + const failureOf = call => { + try { + call(); + } catch (error) { + return { code: error.code, ...error.location }; + } + + throw new Error('The call threw nothing'); + }; + + it('is the one Nexo makes of the contents the table gives it, without the keys it keeps, each module in the order given', async () => { + const { Manifest } = await import('#nexo/language/vocabulary/Manifest.mjs'); + const manifest = DispatchTable.prepare([{ name: 'Domql', contents: BrowserVocabularyDeclarations.contentsOf() }, { name: 'Desk', contents: contents() }]); + // Desk as Nexo is given it: its host call without the request kind, the execution mode and the implementation the table keeps. + const declared = { types: [elementExtension([{ name: 'mark', kind: 'function', invokedBy: 'host', parameters: [], result: 'Boolean' }])] }; + + expect(manifest).toMatchObject({ implementation: nexo.info.versions.implementation, scripts: [] }); + expect(manifest.modules.map(({ name, after }) => [name, after.map(before => before.name)])).toEqual([['Domql', []], ['Desk', ['Domql']]]); + expect(manifest.modules[1].digest).toBe(Manifest.digestOf(declared)); + }); + + it('creates a module of the same contents under it with none of Nexo\'s checks it records, keeping each host call as the table keeps it, and one of other contents with every check', async () => { + const { Manifest } = await import('#nexo/language/vocabulary/Manifest.mjs'); + const manifest = DispatchTable.prepare([{ name: 'Domql', contents: BrowserVocabularyDeclarations.contentsOf() }, { name: 'Desk', contents: contents() }]); + const module = DispatchTable.createModule('Desk', contents(), undefined, manifest); + const [declaration] = module.types[0].members; + + expect(Manifest.recordOf(module)?.digest).toBe(manifest.modules[1].digest); + expect(DispatchTable.get(declaration)).toMatchObject({ requestKind: 'execution', executionMode: 'once', implementation: execute, module: 'Desk', type: 'DeskElements' }); + expect(Manifest.recordOf(DispatchTable.createModule('Desk', { members: [] }, undefined, manifest))).toBeUndefined(); + expect(Manifest.recordOf(DispatchTable.createModule('Desk', contents()))).toBeUndefined(); + }); + + it('refuses what creating the module refuses, and leaves what Nexo refuses to Nexo', () => { + expect(failureOf(() => DispatchTable.prepare([{ name: 'Desk', contents: { members: [hostCall()] } }]))).toEqual({ code: 'DOMQL4002', module: 'Desk', declaration: 'mark', declarationKey: 'requestKind' }); + expect(failureOf(() => DispatchTable.prepare('Desk')).code).toBe('NEXO4565'); + expect(failureOf(() => DispatchTable.prepare([{ name: 'Desk', contents: [] }])).code).toBe('NEXO4501'); + }); + }); }); diff --git a/tests/dom/ModuleManifest.test.js b/tests/dom/ModuleManifest.test.js new file mode 100644 index 0000000..8fe9c57 --- /dev/null +++ b/tests/dom/ModuleManifest.test.js @@ -0,0 +1,32 @@ +import { readFile } from 'node:fs/promises'; +import { describe, it, expect, vi } from 'vitest'; +import { nexo } from '@formaui-net/nexo'; +import { moduleManifestPath, moduleManifestText } from '../../scripts/module-manifest.mjs'; +import { ModuleManifest } from '#domql/dom/ModuleManifest.mjs'; + +describe('ModuleManifest', () => { + it('is the manifest Nexo makes of DOMQL\'s own module, as npm run manifest writes it', async () => { + expect(await readFile(moduleManifestPath, 'utf8'), 'The manifest of DOMQL\'s own module is not current: run npm run manifest from the repository root').toBe(moduleManifestText()); + }); + + it('records DOMQL\'s module alone, registered first, as the Nexo DOMQL runs on made it', () => { + expect(ModuleManifest).toMatchObject({ implementation: nexo.info.versions.implementation, scripts: [] }); + expect(ModuleManifest.modules).toEqual([{ name: 'Domql', digest: expect.any(String), after: [] }]); + }); + + it('is the one DOMQL creates its module and its registry under, each finding the module it records', async () => { + vi.resetModules(); + + const { Manifest } = await import('#nexo/language/vocabulary/Manifest.mjs'); + const entryOf = vi.spyOn(Manifest, 'entryOf'); + + try { + await import('#domql/domql.js'); + + expect(entryOf.mock.calls.map(([manifest, name]) => [manifest, name])).toEqual([[ModuleManifest, 'Domql'], [ModuleManifest, 'Domql']]); + expect(entryOf.mock.results.map(({ value }) => value)).toEqual([ModuleManifest.modules[0], ModuleManifest.modules[0]]); + } finally { + entryOf.mockRestore(); + } + }); +}); From 60162e9d233d1f11aa01b3d347494af47fa933a5 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:57:10 +0200 Subject: [PATCH 08/15] feat(domql): prepare a host's modules and queries domql.prepare(modules, { scripts }) answers the manifest Nexo makes of a host's modules, registered after DOMQL's own, and of its queries, each text read with Domql supplied. createModule, registerModule, registerModuleLoader and query take it as manifest, sparing the checks it records: in Chromium, cold, a host's first query took about 5.6 ms where it took 11.6. D116 records it. --- CHANGELOG.md | 1 + VERSION-HISTORY.md | 8 ++ docs/decisions.md | 21 +++ docs/domql-design.md | 2 + docs/features-status.md | 1 + nuget/README.md | 35 +++++ spec/api.md | 9 +- spec/errors.md | 3 +- spec/queries.md | 3 +- spec/vocabulary.md | 28 ++++ src/dom/BrowserModule.mjs | 11 +- src/dom/BrowserVocabularyDeclarations.mjs | 2 +- src/dom/DispatchTable.mjs | 17 +-- src/dom/DomqlQuery.mjs | 8 +- src/domql.d.ts | 67 ++++++++- src/domql.js | 145 ++++++++++++++++---- tests/Domql.test.js | 143 ++++++++++++++++++- tests/PackageReadme.test.js | 1 + tests/_examples/38-prepare-ahead-of-time.js | 24 ++++ tests/_types/usage.ts | 23 +++- tests/dom/DispatchTable.test.js | 4 +- 21 files changed, 494 insertions(+), 62 deletions(-) create mode 100644 tests/_examples/38-prepare-ahead-of-time.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 60112ef..c71f987 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ Each release of DOMQL's packages, newest first. The npm package `@formaui-net/do - Runs on Nexo's language `1.0.0-preview.3`, from Nexo's release `1.0.0-preview.4`, as the [version history](VERSION-HISTORY.md#v1-0-0-preview-2) sets out: a refusal of `root` written where no object expression encloses it, or read other than through its fields, says that a binding named root is read as `~root`. `domql.info.versions.language` reports `1.0.0-preview.3`. - A continuous execution's start, a subscription's start and a once execution find where their call stands only where a failure names it, so one that fails nowhere reads its query's text no second time: in Node, a query's first run took about 0.47 ms where it took 0.58, and its first once execution about 0.51 ms where it took 0.57. - DOMQL's module and its registry are created under the manifest Nexo makes of the module, which DOMQL's sources hold, so a start makes none of the checks it records: in Chromium, cold, DOMQL's import took about 33.5 ms where it took 43, and its first resolution and registrations about 2 ms more. DOMQL on a Nexo other than the one it was built against creates its module with every check, as before. +- A host prepares its modules and queries ahead of time: `domql.prepare(modules, { scripts })` answers Nexo's manifest, and `createModule`, `registerModule`, `registerModuleLoader` and `query` take it as `manifest`, sparing the checks it records. In Chromium, cold, a host's first query took about 5.6 ms where it took 11.6, and its module, a subscription and a run about 3.2 ms where they took 5.4. diff --git a/VERSION-HISTORY.md b/VERSION-HISTORY.md index 49c87b9..b52f2cb 100644 --- a/VERSION-HISTORY.md +++ b/VERSION-HISTORY.md @@ -39,6 +39,13 @@ domql.query('box.size', { box }).watch({ acceptPartialObservation: true }); // t const destination = await deliver('destinations', request); // the first subscription's answer, as String?; undefined before, whatever its handler returned ``` +```js +const manifest = domql.prepare([{ name: 'Charts', contents }], { scripts: [{ script: 'import Charts\npanel:palette', types: { panel: 'Domql.Element' } }] }); // Charts and its query checked once; a TypeError before, no such function + +domql.registerModule(domql.createModule('Charts', contents, { manifest }), { manifest }); // created and registered without the checks the manifest records; each option left unread before +domql.query('import Charts\npanel:palette', { panel }, { manifest }); // read from the manifest, neither parsed nor resolved; NEXO2048 before, an option the bindings take none of +``` + DOMQL moves to Nexo's language `1.0.0-preview.3`, by way of `1.0.0-preview.2`, which Nexo's release `1.0.0-preview.4` carries, as [D114](docs/decisions.md#d114) records. Nexo's [language history](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/LANGUAGE-HISTORY.md#v1-0-0-preview-3) sets out its own changes by version; the one below is the one a query meets. **Vocabulary** @@ -54,6 +61,7 @@ DOMQL moves to Nexo's language `1.0.0-preview.3`, by way of `1.0.0-preview.2`, w **Modules** - [An event source is answered](spec/behaviors.md#behaviors-answers) where it declares `answers`, the type of the answer: each subscription's handler answers an occurrence with what it returns, or what its promise fulfils with, and `deliver`'s promise fulfils with the first subscription's answer, captured as that type, where it fulfilled with undefined. An answer the type refuses rejects with `DOMQL5025`, and `answers` declared by anything but an event source is refused with `DOMQL4016`, as [D113](docs/decisions.md#d113) records. +- [Modules and queries are prepared ahead of time](spec/vocabulary.md#extension-modules-manifests): `domql.prepare(modules, { scripts })` checks modules, as `domql.createModule` takes them, registered after DOMQL's own, and resolves queries, as `domql.query` takes them, answering Nexo's manifest. `domql.createModule`, `domql.registerModule`, `domql.registerModuleLoader` and `domql.query` take it as `manifest`, and an operation run directly beside `types`, each sparing the checks it records, as [D116](docs/decisions.md#d116) records. A query given to `prepare` with `imports` of its own is refused with `DOMQL2021`, and a loader's options that are no object with `DOMQL2013`. **Breaking:** diff --git a/docs/decisions.md b/docs/decisions.md index 9582c9d..e1e7405 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -1783,3 +1783,24 @@ Each entry is one of three kinds: - **Declined:** - Writing the manifest as the bundle is built. The npm package ships the sources, which must hold it. - Preparing the module at import. It makes the very checks it would save. + + + +## D116 — A host prepares its modules and queries ahead of time + +*November 30, 2026* + +- **Kind:** Contract; a feature Forma's scripts need, approved with the start-up DOMQL's modules and queries prepare ahead of time. +- **Decision:** + - `domql.prepare(modules, options)` answers the manifest Nexo makes of the modules given, as `domql.createModule` takes them, registered after DOMQL's own, and of the queries `options.scripts` gives, as `domql.query` takes them, each text read with `Domql` supplied. + - `domql.createModule`, `domql.registerModule` and `domql.registerModuleLoader` take Nexo's options, `manifest`, and give them to Nexo as they are. + - `domql.query` takes `manifest` beside `types`, reads its text from it and its resolutions, and every query `with` makes keeps it. An operation run directly takes it beside `types`. + - A query given to `prepare` with `imports` of its own is refused with `DOMQL2021`, since `domql.query` supplies `Domql` and reads none. `prepare` refuses a module declaring observation targets with `DOMQL4008`, as `registerModule` does. +- **Why:** + - Forma's scripts start on every page, and replacing them asks DOMQL to start as fast. Once DOMQL's own module is prepared ([D115](#d115)), a host's modules and its first queries are most of what a start checks. + - In Chromium, cold, over four alternating rounds of 11 runs, a host's first query took about 5.6 ms where it took 11.6, and its module, a subscription and a run about 3.2 ms where they took 5.4: 8.8 ms after DOMQL's import, where it was 17. + - The manifest is Nexo's, under Nexo's name, so a host reads one contract. DOMQL adds only what it supplies: its own module first, and the import `Domql`. +- **Declined:** + - DOMQL keeping the manifests it is given, so a query names none. A page holding several libraries' manifests would leave DOMQL to choose among them. + - Naming the option `moduleManifest`, as DOMQL's own module's is named. DOMQL gives the option to Nexo as it is, under Nexo's name. + - Compiling prepared queries to JavaScript. That waits for a measured need, as the start-up's direction set. diff --git a/docs/domql-design.md b/docs/domql-design.md index e51a246..e347958 100644 --- a/docs/domql-design.md +++ b/docs/domql-design.md @@ -35,6 +35,8 @@ The DOM enters as late as it can. Making and resolving a query read no DOM, so t DOMQL creates its module, and the registry it registers it in, as it is imported, under `ModuleManifest`, the manifest Nexo makes of the module, so neither makes the checks of its declarations and their registration that the manifest records, as [Nexo's preparing modules](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/modules.md#modules-preparing) sets out. DOMQL's own checks of its host calls are made either way. `npm run manifest`, from the repository root, runs `scripts/module-manifest.mjs`, which writes the manifest as the dispatch table gives Nexo the module's contents. A test fails while the manifest the sources hold differs from the one the declarations give. Nexo reads a manifest another implementation made as holding no module, so DOMQL on a Nexo other than the one it was built against, as a host may install beside DOMQL's npm package, creates its module with every check. In Chromium, cold, the import took about 33.5 ms where it took 43, and the first query's resolution and the first registrations about 2 ms more, as Nexo resolves the module's notations as they are first read. [D115](decisions.md#d115) records the measurement. +A host's manifest, which `domql.prepare` answers, is the one Nexo makes of DOMQL's module, the host's modules after it, and the host's queries, each text read with `Domql` supplied, so it holds DOMQL's module at the digest DOMQL's own manifest gives it. DOMQL gives `manifest` to Nexo as each operation takes it: `createModule`, `registerModule` and a loader's registration pass their options on, and a query keeps its manifest beside its types, gives it to `nexo.parse` as it reads its text, and to `registry.resolve` as it resolves, binding its values without it. The resolutions a query keeps for its definition are kept alike, whether Nexo read them from a manifest or resolved them. [D116](decisions.md#d116) records the measurement. + DOMQL's `typeOf` and its types' `isInstance` recognize a node by its `nodeType` and a window by its being its own `window`, never by a global's prototype, so a node of another window is recognized as one of the window a query runs in is. A node holds functions, which data never does, so data that names a `nodeType` is never taken for a node. ## Resolution diff --git a/docs/features-status.md b/docs/features-status.md index 2ee03f4..81ee0e9 100644 --- a/docs/features-status.md +++ b/docs/features-status.md @@ -96,6 +96,7 @@ Each feature, the contract that states it, its state in the implementation, and | Queries from text or a definition, `with`, `select` and `resolve` | [Queries](../spec/queries.md) | Implemented | [Before `alpha.275`](../VERSION-HISTORY.md#before-1-0-0-alpha-275) | | Imports, `Domql` supplied to every query | [Its imports](../spec/queries.md#making-a-query-imports) | Implemented | [`alpha.278`](../VERSION-HISTORY.md#v1-0-0-alpha-278) | | A query run directly, in one call, `domql.executeAsync(text, bindings, options)` and each operation of a query object alike | [Two ways to run a query](../spec/api.md#api-two-ways-to-run-a-query) | Implemented, as [D89](decisions.md#d89) records | [`preview.1`](../VERSION-HISTORY.md#v1-0-0-preview-1) | +| Modules and queries prepared ahead of time, `domql.prepare` and the `manifest` each operation takes | [Preparing ahead of time](../spec/vocabulary.md#extension-modules-manifests) | Implemented, as [D116](decisions.md#d116) records | [`preview.2`](../VERSION-HISTORY.md#v1-0-0-preview-2) | | Bindings of the types a query declares, `domql.query(text, bindings, { types })` | [Declared types](../spec/queries.md#making-a-query-declared-types) | Implemented, as [D82](decisions.md#d82) records | [`preview.1`](../VERSION-HISTORY.md#v1-0-0-preview-1) | | Evaluating once, and waiting for maintained members | [Evaluation](../spec/evaluation.md) | Implemented | [Before `alpha.275`](../VERSION-HISTORY.md#before-1-0-0-alpha-275) | | Watches, their dependencies and partial observation | [Watches](../spec/watches.md) | Implemented | [Before `alpha.275`](../VERSION-HISTORY.md#before-1-0-0-alpha-275) | diff --git a/nuget/README.md b/nuget/README.md index 1cbbaa2..35d8ac8 100644 --- a/nuget/README.md +++ b/nuget/README.md @@ -1077,6 +1077,41 @@ unread.evaluate(); `loadModulesAsync` takes a query, a definition, a text or a list of module names. It loads only the modules the instance doesn't hold yet, and shares a load that is already under way, so call it before every query that may need one. A query that imports a module whose loader hasn't run yet is refused with `DOMQL3007`. Load first even for `run`, which starts its execution before it returns. +### Prepare ahead of time + +Creating and registering a module checks its declarations, and a query's text is read and resolved, each time a page starts. Your build can make those checks once, with `domql.prepare`, and give the page what it recorded, a manifest, which spares it the checks: + +```js +const badges = { + types: [{ + name: 'BadgeElements', + kind: 'extension', + target: 'Domql.Element', + members: [{ + name: 'badge', + kind: 'property', + result: 'String?', + updates: { changes: 'observable', reads: 'fresh', observations: [{ type: 'mutation', of: 'receiver', attributes: ['data-badge'] }] }, + impl: ({ receiver: element }) => element.getAttribute('data-badge') + }] + }] +}; + +// At build time: the module and the query, checked once, as a manifest kept as JSON. +const manifest = domql.prepare([{ name: 'Badges', contents: badges }], { + scripts: [{ script: 'import Badges\npanel:badge ?? "none"', types: { panel: 'Domql.Element' } }] +}); + +// At the page's start: the same module and query, from the manifest. +domql.registerModule(domql.createModule('Badges', badges, { manifest }), { manifest }); +domql.query('import Badges\npanel:badge ?? "none"', { panel }, { manifest }).evaluate(); +// 'none' +``` + +- **A binding given a type and no value** stands for every value of that type, so `types: { panel: 'Domql.Element' }` prepares the query for any element. A `String` or a `Boolean` binding is given its value, since its value decides what a member reads. +- **Pass the manifest** to `createModule`, `registerModule`, `registerModuleLoader` and `query`, or beside `types` to an operation run directly. Anything the manifest doesn't hold is checked and resolved as usual. +- **Prepare again with each release.** A manifest another version of Nexo made holds nothing, so everything is checked again until your build makes it anew. + ## Execute once and run continuously ### Change the page with a built-in execution diff --git a/spec/api.md b/spec/api.md index 4b384df..a1e6ed0 100644 --- a/spec/api.md +++ b/spec/api.md @@ -69,7 +69,7 @@ Each entry point and operation is listed here with what it takes, and the sectio | Entry point or operation | Meaning | | --- | --- | -| `domql.query(text, bindings?, options?)`, `domql.query(definition, bindings?, options?)` | Makes a query object, binding its parameters, each of the type `options.types` [declares](queries.md#making-a-query-declared-types) for it, as [making a query](queries.md#making-a-query) sets out | +| `domql.query(text, bindings?, options?)`, `domql.query(definition, bindings?, options?)` | Makes a query object, binding its parameters, each of the type `options.types` [declares](queries.md#making-a-query-declared-types) for it, read from the manifest `options.manifest` gives, as [making a query](queries.md#making-a-query) sets out | | `domql.evaluate(text, bindings?, options?)`, and `domql.evaluateAsync`, `domql.watch`, `domql.executeAsync` and `domql.run` alike; `domql.subscribe(text, bindings, handler, options?)` | Runs a query directly, in one call, as the query object `domql.query(text, bindings)` makes runs it, as [two ways to run a query](#api-two-ways-to-run-a-query) sets out; each takes a definition in place of the text too | | `query.definition` | The query's immutable definition, without its bindings | | `query.with(bindings)` | A new query with the same definition, bound to these bindings, of the types the query declares | @@ -82,9 +82,10 @@ Each entry point and operation is listed here with what it takes, and the sectio | `query.executeAsync(options?)` | Carries out a once execution, answering a promise of its result, as [executing once](executions.md#executions-executing-once) sets out | | `query.run(options?)` | Starts a continuous execution, answering a `DomqlExecutionHandle`, as [running continuously](executions.md#executions-running-continuously) sets out | | `domql.format(source)` | The canonical text of a text, a definition or a query object, as [formatting](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/definition.md#definition-canonical-text) sets out | -| `domql.createModule(name, contents)` | Creates a module from its declarations, each that runs code carrying its implementation, as [extension modules](vocabulary.md#extension-modules) set out | -| `domql.registerModule(module)` | Registers a module's declarations in the instance's registry, as [extension modules](vocabulary.md#extension-modules) set out | -| `domql.registerModuleLoader(name, load)` | Registers the loader of a module loaded on request, as [loading a module on request](vocabulary.md#extension-modules-loading) sets out | +| `domql.prepare(modules, options?)` | Checks modules and queries ahead of time, answering the manifest a host gives back as `manifest`, as [preparing ahead of time](vocabulary.md#extension-modules-manifests) sets out | +| `domql.createModule(name, contents, options?)` | Creates a module from its declarations, each that runs code carrying its implementation, as [extension modules](vocabulary.md#extension-modules) set out, under the manifest `options.manifest` gives | +| `domql.registerModule(module, options?)` | Registers a module's declarations in the instance's registry, as [extension modules](vocabulary.md#extension-modules) set out, under the manifest `options.manifest` gives | +| `domql.registerModuleLoader(name, load, options?)` | Registers the loader of a module loaded on request, as [loading a module on request](vocabulary.md#extension-modules-loading) sets out, its module registered with the options given | | `domql.loadModulesAsync(modules)` | Loads and registers every module named that the instance doesn't hold yet, answering a promise, as [loading a module on request](vocabulary.md#extension-modules-loading) sets out | | `domql.info` | Which build this is and what it follows, in `versions`: `runtime`, the runtime release version, which the package and the bundle carry, its sources reporting the same; `specification`, the version of DOMQL's specification it follows; and `language`, the language specification version the Nexo runtime it runs on follows, its `nexo.info.versions.language` | diff --git a/spec/errors.md b/spec/errors.md index 947bb69..44797dc 100644 --- a/spec/errors.md +++ b/spec/errors.md @@ -37,7 +37,7 @@ A caller's use of the API, refused where it is made. | `DOMQL2010` | `env.observe` given a request without a type or a target, or a `notify` that is no function | | `DOMQL2011` | `env.frame` given a callback that is no function or a phase neither `write` nor `read`, or in a window without animation frames | | `DOMQL2012` | `env.measureUnder` given an element that is none, a class that is no one token, or a `read` that is no function | -| `DOMQL2013` | `domql.registerModuleLoader` given a name that is no module's, a `load` that is no function, or a name a loader is registered for already | +| `DOMQL2013` | `domql.registerModuleLoader` given a name that is no module's, a `load` that is no function, options that are no object, or a name a loader is registered for already | | `DOMQL2014` | `domql.loadModulesAsync` given neither a query object, a definition, a text nor a list of module names | | `DOMQL2015` | A subscription's `reactions` given anything but a list of query objects of the instance | | `DOMQL2016` | A watch's `sourceOf` given a path that ends at no list's item | @@ -45,6 +45,7 @@ A caller's use of the API, refused where it is made. | `DOMQL2018` | A subscription given both `throttle` and `reactions` | | `DOMQL2019` | A watch's `delay` that is no number above 0, given to a schedule other than `delayed`, or missing from one that is | | `DOMQL2020` | A watch's `reportOn` that is no list of paths | +| `DOMQL2021` | A query `domql.prepare` is given that gives `imports` of its own, since DOMQL reads its text with `Domql` supplied | diff --git a/spec/queries.md b/spec/queries.md index fb90fca..49eceb7 100644 --- a/spec/queries.md +++ b/spec/queries.md @@ -115,7 +115,8 @@ const routed = domql.query("import Forma\nForma.firstKey(routes)", { routes: [{ - **Data is captured as the type:** a structure keeps its data shape, a property the data leaves out is null where its type is nullable, a map binds as a dictionary and a set as a list. Data the type doesn't admit refuses the binding (NEXO2045). - **A reference type holds to its contract:** the value belongs to the type, or is null where it is nullable. - **Every binding made from the query keeps the types:** `with`'s, an execution's update and a reaction's. The query keeps a copy of them, so a change its caller makes afterwards reaches none. -- **The options are the bindings':** a declared type that is no string is refused (NEXO2044), and so is an option the bindings take none of (NEXO2048). +- **A manifest.** `options.manifest` gives a manifest [prepared ahead of time](vocabulary.md#extension-modules-manifests): the text is read from the definition it holds, and the query's resolutions from it, where it holds them. Every query made from the query keeps it, as it keeps the types. A manifest of another shape is refused with Nexo's `NEXO4566`. +- **The options are the bindings', and the manifest:** a declared type that is no string is refused (NEXO2044), and so is an option neither takes (NEXO2048). With the first bindings, the result is the following: an object expression following the null `panel` is null, and `ids` is the empty list. diff --git a/spec/vocabulary.md b/spec/vocabulary.md index aba41e0..a20fe9b 100644 --- a/spec/vocabulary.md +++ b/spec/vocabulary.md @@ -1668,6 +1668,34 @@ chart.evaluate(); - **A module that names another's types** is registered after it, so its loader loads that one first, `await domql.loadModulesAsync(["Gestures"])`, before answering its own. - **Not loaded yet.** A request importing a module that has a loader, and is not registered yet, is refused as it is resolved with `DOMQL3007`, located at the import, rather than Nexo's refusal of a module it doesn't know. No operation loads a module itself: an execution would lose the order and the activation of the call that carries it out. + + +### Preparing modules and queries ahead of time + +Each time a page starts, creating and registering a module checks its declarations, and making and resolving a query reads its text and resolves it. A host's build can make those checks once, ahead of time, and give the page what they recorded, a **manifest**, as Nexo's [preparing modules](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/modules.md#modules-preparing) and [preparing scripts](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/runtime/resolution.md#runtime-preparing-scripts) set out. + +```js +// At build time: the modules a page registers and the queries it makes, checked once. +const manifest = domql.prepare([{ name: "Charts", contents: charts }], { + scripts: [{ script: "import Charts\npanel:palette", types: { panel: "Domql.Element" } }] +}); + +// At the page's start, from the manifest the build kept as JSON. +domql.registerModule(domql.createModule("Charts", charts, { manifest }), { manifest }); +domql.query("import Charts\npanel:palette", { panel }, { manifest }).evaluate(); +``` + +- **`domql.prepare(modules, options?)`** creates each module given, `{ name, contents }` as `domql.createModule` takes it, and registers it with every check, in the order given, after DOMQL's own. It refuses what `domql.createModule` and `domql.registerModule` refuse, and what is no list of modules with Nexo's `NEXO4565`. +- **Its queries.** It resolves each query `options.scripts` gives, `{ script, bindings, types }`, against those modules, as `domql.query(script, bindings, { types })` resolves it, its text read with `Domql` supplied. It refuses what that refuses, and a query that gives `imports` of its own with `DOMQL2021`, since `domql.query` reads none. It answers the manifest, plain data the host keeps as JSON. +- **A binding given a type and no value** stands for any value of its type that decides nothing, as an element does, so `types: { panel: "Domql.Element" }` prepares the query for every element. A `String` or a `Boolean` decides what a member reads by its value, so one is given its value, and a query bound to another value is resolved as it is carried out. +- **`manifest` gives it back** to these operations: + - `domql.createModule(name, contents, { manifest })` creates a module of the same contents without the checks the manifest records. + - `domql.registerModule(module, { manifest })` registers such a module without them, beside the modules registered before it in the manifest. + - `domql.registerModuleLoader(name, load, { manifest })` registers the module its loader answers so. Options that are no object are refused with `DOMQL2013`. + - `domql.query(text, bindings, { types, manifest })` reads the text from the definition the manifest holds, and each resolution it holds for the bindings, as [making a query](queries.md#making-a-query-declared-types) sets out. An operation run directly takes it beside `types`. +- **What it holds none of** is checked and resolved as it is without one. DOMQL's own checks of a module's host calls are made either way. +- **A manifest belongs to its implementation.** One another version of Nexo made holds no module and no query, so everything given it is checked and resolved. A host prepares again at each release of DOMQL, or of Nexo beside it, that it takes. + ### Host calls DOMQL carries out diff --git a/src/dom/BrowserModule.mjs b/src/dom/BrowserModule.mjs index c9ce218..6587ce2 100644 --- a/src/dom/BrowserModule.mjs +++ b/src/dom/BrowserModule.mjs @@ -21,11 +21,16 @@ export class BrowserModule { return BrowserVocabularyDeclarations.createModule(BrowserModule.#implementationsOf(behaviors, mutationObservers), { moduleManifest }); } - /** The manifest Nexo makes of the DOM module, every check of its declarations and of their registration made, which `create` creates it under without those checks. */ - static prepare() { + /** + * The manifest Nexo makes of the DOM module, every check of its declarations and of their registration made, which `create` creates it under without those checks; and of the modules given after it, each + * `{ name, contents }` as the dispatch table's `createModule` takes them, and the scripts the options give, as the dispatch table's `prepare` makes it of them. What is no list of modules is left to Nexo. + * @param {{ name: string, contents?: object }[]} [modules] The modules registered after it, in order. + * @param {{ scripts?: object[] }} [options] The options Nexo's `prepare` takes. + */ + static prepare(modules = [], options = undefined) { const contents = BrowserVocabularyDeclarations.contentsOf(BrowserModule.#implementationsOf(new Behaviors(), new MutationObservers())); - return DispatchTable.prepare([{ name: BrowserVocabularyDeclarations.moduleName, contents }]); + return DispatchTable.prepare(Array.isArray(modules) ? [{ name: BrowserVocabularyDeclarations.moduleName, contents }, ...modules] : modules, options); } /** The module's implementations, by the key each declaration is carried out under. */ diff --git a/src/dom/BrowserVocabularyDeclarations.mjs b/src/dom/BrowserVocabularyDeclarations.mjs index a8188f0..a533e3e 100644 --- a/src/dom/BrowserVocabularyDeclarations.mjs +++ b/src/dom/BrowserVocabularyDeclarations.mjs @@ -486,7 +486,7 @@ export class BrowserVocabularyDeclarations { * @param {{ moduleManifest?: object | null }} [options] The manifest the dispatch table's `prepare` made of the module, or null. */ static createModule(implementations = {}, { moduleManifest = null } = {}) { - return DispatchTable.createModule(BrowserVocabularyDeclarations.moduleName, BrowserVocabularyDeclarations.contentsOf(implementations), undefined, moduleManifest); + return DispatchTable.createModule(BrowserVocabularyDeclarations.moduleName, BrowserVocabularyDeclarations.contentsOf(implementations), undefined, moduleManifest === null ? undefined : { manifest: moduleManifest }); } /** DOMQL's module as its declarations alone, which is enough to resolve a query and carries nothing out. */ diff --git a/src/dom/DispatchTable.mjs b/src/dom/DispatchTable.mjs index 8fd6d14..ff04381 100644 --- a/src/dom/DispatchTable.mjs +++ b/src/dom/DispatchTable.mjs @@ -30,20 +30,20 @@ export class DispatchTable { * that is no function are refused with a module error naming the declaration, an unnamed indexer as `[]`, as Nexo names it, the type it stands in where it stands in one, and the key; so is a `behavior` on a * declaration that reaches none, one naming no continuous execution of the module, and an event source of a behavior given an implementation or parameters, which DOMQL carries out. * A member the evaluator invokes declaring a `behavior` reads the state that behavior offers: its implementation receives the instance running for the environment's owner on its receiver, null where none runs. - * Under a manifest `prepare` made of the same contents, Nexo makes none of the checks it records; DOMQL's own checks, those above, are made either way. + * Under a manifest `prepare` made of the same contents, which the options give as Nexo's `createModule` takes them, Nexo makes none of the checks it records; DOMQL's own checks, those above, are made either way. * @param {string} name The module's name. * @param {object} contents What the module declares. * @param {import('./Behaviors.mjs').Behaviors} [behaviors] The behaviors running, which a member reading a behavior's state finds its instance among. - * @param {object | null} [moduleManifest] A manifest `prepare` made of the module, which Nexo creates it from without the checks it records, or null. + * @param {{ manifest?: object | null }} [options] The options Nexo's `createModule` takes, its manifest among them. */ - static createModule(name, contents, behaviors, moduleManifest = null) { + static createModule(name, contents, behaviors, options = undefined) { // Contents Nexo refuses are left to it, which names what is wrong with them. if (contents === null || typeof contents !== 'object' || Array.isArray(contents)) { - return nexo.createModule(name, contents); + return nexo.createModule(name, contents, options); } const { declared, memberDescriptors, typeDescriptors, sourcesOf } = DispatchTable.#describe(name, contents, behaviors); - const module = nexo.createModule(name, declared, moduleManifest === null ? undefined : { manifest: moduleManifest }); + const module = nexo.createModule(name, declared, options); // A module keeps its types, and the members of each, in the order they were declared. const keep = (declarations, descriptors) => declarations?.forEach((declaration, index) => { @@ -66,10 +66,11 @@ export class DispatchTable { /** * The manifest Nexo makes of the modules given, each `{ name, contents }` as `createModule` takes them, in the order they are registered: of the contents Nexo is given for each, every check of each module and its - * registration made, refusing what `createModule` refuses, so a module `createModule` creates from it makes none of the checks it records. + * registration made, refusing what `createModule` refuses, so a module `createModule` creates from it makes none of the checks it records; and of the scripts the options give, as Nexo's `prepare` takes them. * @param {{ name: string, contents?: object }[]} modules The modules, in the order they are registered. + * @param {{ scripts?: object[] }} [options] The options Nexo's `prepare` takes. */ - static prepare(modules) { + static prepare(modules, options = undefined) { // What Nexo refuses is left to it, which names what is wrong with it. const declaredOf = entry => { const contents = entry?.contents; @@ -77,7 +78,7 @@ export class DispatchTable { return contents === null || typeof contents !== 'object' || Array.isArray(contents) ? entry : { ...entry, contents: DispatchTable.#describe(entry.name, contents).declared }; }; - return nexo.prepare(Array.isArray(modules) ? modules.map(declaredOf) : modules); + return nexo.prepare(Array.isArray(modules) ? modules.map(declaredOf) : modules, options); } /** diff --git a/src/dom/DomqlQuery.mjs b/src/dom/DomqlQuery.mjs index 78f2e89..e6b1c3f 100644 --- a/src/dom/DomqlQuery.mjs +++ b/src/dom/DomqlQuery.mjs @@ -29,7 +29,8 @@ export class DomqlQuery { * @param {object} bindings The values its parameters are bound to, as the registry it is resolved against binds them. * @param {QueryOperations} operations What carries its operations out. * @param {Record} values The values given by parameter name, which `bindings` binds. - * @param {{ types?: Record }} [options] The bindings' options, the types they declare among them, which every binding of this query and of the queries `with` makes from it keeps. + * @param {{ types?: Record, manifest?: object | null }} [options] The bindings' options, the types they declare among them, which every binding of this query and of the queries `with` makes from it + * keeps, and the manifest the query is resolved from where it holds its resolutions. */ constructor(definition, bindings, operations, values, options) { this.#definition = definition; @@ -49,6 +50,11 @@ export class DomqlQuery { return query.#bindings; } + /** The options the query was made with, its manifest among them, which DOMQL resolves it with; no part of a query object's API. */ + static optionsOf(query) { + return query.#options; + } + /** Whether the value is a query object itself, as this instance made it, rather than another instance's or anything standing in for one. */ static isQuery(value) { return value !== null && typeof value === 'object' && #values in value; diff --git a/src/domql.d.ts b/src/domql.d.ts index fb147c1..3b003b3 100644 --- a/src/domql.d.ts +++ b/src/domql.d.ts @@ -284,13 +284,15 @@ export interface DomqlBindings { [name: string]: unknown; } -/** The options a query's bindings take, as Nexo's `createBindings` takes them. */ +/** The options a query takes: those its bindings take, as Nexo's `createBindings` takes them, and the manifest it is read from. */ export interface DomqlQueryOptions { /** * The type of each top-level binding it names, by its notation, a module's type qualified where another of its name would hide it, as `{ routes: 'List' }`. Data is captured as that type, a map as a * dictionary and a set as a list, and a reference holds to the type's contract. Every binding of the query keeps the types, `with`'s, an update's and a reaction's among them. */ readonly types?: Readonly>; + /** A manifest `domql.prepare` made, which the query's text is read from and its resolutions read from where it holds them, or null; every query `with` makes keeps it. */ + readonly manifest?: NexoManifest | null; } /** @@ -717,6 +719,52 @@ export interface DomqlModule { readonly observationTargets: readonly DomqlObservationTargetDeclaration[]; } +/** + * What `domql.prepare` answers, Nexo's manifest: plain data a host keeps as JSON and gives back as `manifest`. One that another implementation of Nexo made holds no module and no script, so every module created and + * registered under it is checked, and every query resolved. + */ +export interface NexoManifest { + /** The form of the manifest. */ + readonly format: number; + /** The version of the Nexo implementation that made it. */ + readonly implementation: string; + /** Each module it checked, in the order it registered them: its name, the digest of its contents, and the modules registered before it, by name and digest. */ + readonly modules: readonly { readonly name: string; readonly digest: string; readonly after: readonly { readonly name: string; readonly digest: string }[] }[]; + /** Each query it resolved, with its definition and its resolutions, as data. */ + readonly scripts: readonly object[]; +} + +/** The options of an operation that takes a manifest, as Nexo's takes them. */ +export interface DomqlManifestOptions { + /** A manifest `domql.prepare` made, whose checks the operation makes no more where it holds what is given, or null. */ + readonly manifest?: NexoManifest | null; +} + +/** A module `domql.prepare` checks, as `createModule` takes it. */ +export interface DomqlModuleToPrepare { + readonly name: string; + readonly contents: DomqlModuleContents; +} + +/** A query `domql.prepare` resolves, as `domql.query` takes it, its text read with `Domql` supplied. */ +export interface DomqlQueryToPrepare { + /** Its text or its definition. */ + readonly script: string | DomqlDefinition; + /** The values it is bound to. */ + readonly bindings?: DomqlBindings; + /** + * The type declared for a binding, by its name, as a notation: one given a value types it, as `domql.query`'s `types` declares one, and one given none stands for any value of its type, as `Domql.Element` stands for every + * element; a `String` and a `Boolean` decide by their value, so a binding of either is given its value. + */ + readonly types?: Readonly>; +} + +/** The options of `domql.prepare`. */ +export interface DomqlPrepareOptions { + /** The queries it resolves against the modules. */ + readonly scripts?: readonly DomqlQueryToPrepare[]; +} + /** The versions DOMQL reports, which change apart. */ export interface DomqlVersions { /** The DOMQL runtime release version, which the package and the bundle carry. */ @@ -756,12 +804,17 @@ export interface Domql { run(source: string | DomqlDefinition, bindings?: DomqlBindings, options?: DomqlQueryOptions & DomqlOperationOptions): DomqlExecutionHandle; /** The canonical text of a request, given as its text, its definition or a query object: it parses and checks the structure, writes every import the definition records but `Domql`, which DOMQL supplies, needs no bindings, and formatting what it gives gives that again. */ format(source: string | DomqlDefinition | DomqlQuery): string; - /** Creates a module from the vocabulary it declares, each declaration that runs code carrying its implementation. */ - createModule(name: string, contents: DomqlModuleContents): DomqlModule; - /** Registers a module's vocabulary, which every request resolved afterwards may use. */ - registerModule(module: DomqlModule): void; - /** Registers the loader of a module loaded on request, by the module's name: `load` answers the module, or a promise of it, and registers nothing itself. */ - registerModuleLoader(name: string, load: () => DomqlModule | Promise): void; + /** + * Checks modules and queries ahead of time, as a host's build does, answering the manifest it keeps as JSON: each module, as `createModule` takes it, created and registered after DOMQL's own with every check, and + * each query resolved against them as `domql.query` resolves it, refusing what those refuse. Given back as `manifest`, it spares each operation the checks it records. + */ + prepare(modules: readonly DomqlModuleToPrepare[], options?: DomqlPrepareOptions): NexoManifest; + /** Creates a module from the vocabulary it declares, each declaration that runs code carrying its implementation; under the manifest `domql.prepare` made of the same contents, without the checks it records. */ + createModule(name: string, contents: DomqlModuleContents, options?: DomqlManifestOptions): DomqlModule; + /** Registers a module's vocabulary, which every request resolved afterwards may use; one created under a manifest and registered under it, without the checks it records. */ + registerModule(module: DomqlModule, options?: DomqlManifestOptions): void; + /** Registers the loader of a module loaded on request, by the module's name: `load` answers the module, or a promise of it, and registers nothing itself; the module is registered with the options given. */ + registerModuleLoader(name: string, load: () => DomqlModule | Promise, options?: DomqlManifestOptions): void; /** * Loads every module named that the instance doesn't hold yet, each through its loader, and registers it, settling once each named is registered: those a query object, a definition or a text imports, or those a * list names. A load already under way is shared. diff --git a/src/domql.js b/src/domql.js index fbec96c..1a5da41 100644 --- a/src/domql.js +++ b/src/domql.js @@ -106,7 +106,10 @@ class Domql { static #browserModule = BrowserModule.create({ behaviors: Domql.#behaviors, mutationObservers: Domql.#mutationObservers, moduleManifest: ModuleManifest }); static #moduleRegistry = nexo.createRegistry([Domql.#browserModule], { manifest: ModuleManifest }); - /** The loader of each module loaded on request, by its name, which a load asks where the registry holds no module of that name; kept for the instance's life. @type {Map unknown>} */ + /** + * The loader of each module loaded on request, by its name, with the options its module is registered with, which a load asks where the registry holds no module of that name; kept for the instance's life. + * @type {Map unknown, options: object | undefined }>} + */ static #moduleLoaders = new Map(); /** The load of each module under way, by its name, which every load asking for that module meanwhile shares; released as it settles, so a failed one is asked of its loader again. @type {Map>} */ @@ -148,12 +151,13 @@ class Domql { * A query object of another DOMQL instance is refused, with how to make it here from its definition. * @param {string | object} source The request's text, or its definition. * @param {Record} [bindings] The values supplied by parameter name. - * @param {{ types?: Record }} [options] The bindings' options, as Nexo's `createBindings` takes them: `types` declares a top-level binding's type by its notation, which every binding of the query keeps. + * @param {{ types?: Record, manifest?: object | null }} [options] The bindings' options, as Nexo's `createBindings` takes them: `types` declares a top-level binding's type by its notation, which every binding of the query keeps; + * and `manifest`, a manifest `prepare` made, which the text is read from and the query's resolutions read from where it holds them, every query `with` makes keeping it. * @returns {DomqlQuery} */ static query(source, bindings = {}, options = undefined) { if (typeof source === 'string') { - const definition = nexo.parse(source, { imports: Domql.#imports }); + const definition = nexo.parse(source, { imports: Domql.#imports, manifest: Domql.#manifestOf(options) }); return new DomqlQuery(definition, Domql.#bind(bindings, options), Domql.#operations, bindings, Domql.#keep(options)); } @@ -189,20 +193,65 @@ class Domql { return nexo.format(source, { imports: Domql.#imports }); } + /** + * The manifest Nexo makes, ahead of time, of the modules given, each `{ name, contents }` as `createModule` takes them, registered in order after DOMQL's own, every check of each and of its registration made, + * refusing what `createModule` and `registerModule` refuse; and of each query `options.scripts` gives, `{ script, bindings, types }`, resolved against them as `query(script, bindings, { types })` resolves it, its text + * read with DOMQL's own module supplied. A binding given a type and no value stands for any value of that type that decides nothing. A host keeps the manifest as JSON, and gives it back as `manifest`. + * @param {{ name: string, contents: object }[]} modules The modules, in the order they are registered. + * @param {{ scripts?: { script: string | object, bindings?: Record, types?: Record }[] }} [options] + */ + static prepare(modules, options = undefined) { + if (Array.isArray(modules)) { + modules.forEach(entry => Domql.#refuseObservationTargets(entry?.name, entry?.contents?.observationTargets)); + } + + // No list of modules is left to Nexo, which refuses it; BrowserModule's own prepare, given none, prepares DOMQL's module alone. + return BrowserModule.prepare(modules === undefined ? null : modules, Domql.#withImportsSupplied(options)); + } + + /** + * The options of `prepare`, each script given as text read with DOMQL's own module supplied, as `query` reads it; one that gives imports of its own is refused, since `query` reads none. Options of another shape + * are left to Nexo, which names what is wrong with them. + */ + static #withImportsSupplied(options) { + if (!Array.isArray(options?.scripts)) { + return options; + } + + const scripts = options.scripts.map((entry, index) => { + if (entry === null || typeof entry !== 'object' || typeof entry.script !== 'string') { + return entry; + } + + if (Object.hasOwn(entry, 'imports')) { + throw NexoError.structure('DOMQL2021', `DOMQL reads a query's text with its own module supplied, as domql.query reads it, so a script it prepares gives no imports, and script ${index} gives them`, {}); + } + + return { ...entry, imports: Domql.#imports }; + }); + + return { ...options, scripts }; + } + /** * Creates a module from the vocabulary it declares, each declaration that runs code carrying its implementation, keeping each host call's request kind, execution mode and implementation in DOMQL's dispatch table. + * Under the manifest `prepare` made of the same contents, Nexo makes none of the checks it records. * @param {string} name The module's name. * @param {object} contents What the module declares. + * @param {{ manifest?: object | null }} [options] The options Nexo's `createModule` takes, its manifest among them. */ - static createModule(name, contents) { - return DispatchTable.createModule(name, contents, Domql.#behaviors); + static createModule(name, contents, options = undefined) { + return DispatchTable.createModule(name, contents, Domql.#behaviors, options); } - /** Registers a module's vocabulary, which every request resolved afterwards may use; a module declaring observation targets is refused, since DOMQL resolves its own module's alone. */ - static registerModule(module) { - if (module?.observationTargets?.length > 0) { - throw NexoError.module('DOMQL4008', `DOMQL resolves the observation targets its own module declares alone, and the module '${module.name}' declares one of its own; its observations observe the receiver, an argument of the member, or window, document, root or roots through one of DOMQL's observation types`, { module: module.name, declarationKey: 'observationTargets' }); - } + /** + * Registers a module's vocabulary, which every request resolved afterwards may use; a module declaring observation targets is refused, since DOMQL resolves its own module's alone. A module created under a manifest + * `prepare` made, registered under it beside the modules registered before it there, is registered without the checks it records. + * @param {object} module A module `createModule` made. + * @param {{ manifest?: object | null }} [options] The options Nexo's `registerModule` takes, its manifest among them. + */ + static registerModule(module, options = undefined) { + Domql.#refuseObservationTargets(module?.name, module?.observationTargets); // DOMQL carries a host call out only as its dispatch table keeps it, which a module domql.createModule made holds. const unregistered = Domql.#membersOf(module).find(({ declaration }) => declaration?.invokedBy === 'host' && DispatchTable.get(declaration) === undefined); @@ -213,25 +262,38 @@ class Domql { throw NexoError.module('DOMQL4009', `The module '${module.name}' declares the host call '${declaration.name}' without the request it makes; create the module with domql.createModule, which keeps each host call's request kind, execution mode and implementation`, { module: module.name, ...(type === null ? {} : { type }), declaration: declaration.name, declarationKey: 'requestKind' }); } - Domql.#moduleRegistry.registerModule(module); + Domql.#moduleRegistry.registerModule(module, options); + } + + /** Refuses a module declaring observation targets, which DOMQL resolves for its own module alone. */ + static #refuseObservationTargets(name, targets) { + if (Array.isArray(targets) && targets.length > 0) { + throw NexoError.module('DOMQL4008', `DOMQL resolves the observation targets its own module declares alone, and the module '${name}' declares one of its own; its observations observe the receiver, an argument of the member, or window, document, root or roots through one of DOMQL's observation types`, { module: name, declarationKey: 'observationTargets' }); + } } /** * Registers the loader of the module of the name given, which `loadModulesAsync` asks for it where this instance holds no module of that name: `load()` answers the module, or a promise of it, and registers nothing - * itself. A name that is no module's, a `load` that is no function, and a second loader for one name are refused. + * itself, the module it answers registered with the options given, as `registerModule` takes them. A name that is no module's, a `load` that is no function, options that are no object, and a second loader for one + * name are refused. * @param {string} name The module's name. * @param {() => unknown} load Answers the module. + * @param {{ manifest?: object | null }} [options] The options its module is registered with. */ - static registerModuleLoader(name, load) { + static registerModuleLoader(name, load, options = undefined) { if (typeof name !== 'string' || name === '' || typeof load !== 'function') { throw NexoError.structure('DOMQL2013', 'A module loader is registered by the name of the module it loads, and is the function that answers that module', {}); } + if (options !== undefined && (options === null || typeof options !== 'object' || Array.isArray(options))) { + throw NexoError.structure('DOMQL2013', `The options the module '${name}' is registered with are an object, as domql.registerModule takes them`, {}); + } + if (Domql.#moduleLoaders.has(name)) { throw NexoError.structure('DOMQL2013', `A loader of the module '${name}' is registered already, and a module has one loader`, {}); } - Domql.#moduleLoaders.set(name, load); + Domql.#moduleLoaders.set(name, { load, options }); } /** @@ -288,21 +350,21 @@ class Domql { let loading = Domql.#loadingModules.get(name); if (loading === undefined) { - const load = Domql.#moduleLoaders.get(name); + const loader = Domql.#moduleLoaders.get(name); - if (load === undefined) { + if (loader === undefined) { return Promise.reject(NexoError.module('DOMQL4015', `The module '${name}' is neither registered nor loaded on request; register it, or a loader of it with domql.registerModuleLoader, before a query that imports it is carried out`, { module: name })); } - loading = Domql.#registerLoadedModuleAsync(name, load).finally(() => Domql.#loadingModules.delete(name)); + loading = Domql.#registerLoadedModuleAsync(name, loader).finally(() => Domql.#loadingModules.delete(name)); Domql.#loadingModules.set(name, loading); } return loading; } - /** Asks the loader for its module and registers it, unless this instance came to hold one of its name meanwhile. */ - static async #registerLoadedModuleAsync(name, load) { + /** Asks the loader for its module and registers it with the loader's options, unless this instance came to hold one of its name meanwhile. */ + static async #registerLoadedModuleAsync(name, { load, options }) { let module; try { @@ -316,7 +378,7 @@ class Domql { } if (!Domql.#moduleRegistry.moduleNames.includes(name)) { - Domql.registerModule(module); + Domql.registerModule(module, options); } } @@ -336,11 +398,22 @@ class Domql { return Object.freeze(options.types === undefined ? { ...options } : { ...options, types: Object.freeze({ ...options.types }) }); } - /** Binds the values given by parameter name through DOMQL's registry, which every query resolves against, each binding whose type the options declare captured as that type. */ + /** Binds the values given by parameter name through DOMQL's registry, which every query resolves against, each binding whose type the options declare captured as that type; their manifest is the query's, never the bindings'. */ static #bind(bindings, options) { + if (options !== null && typeof options === 'object' && Object.hasOwn(options, 'manifest')) { + const { manifest, ...bindingOptions } = options; + + return Domql.#moduleRegistry.createBindings(bindings, bindingOptions); + } + return Domql.#moduleRegistry.createBindings(bindings, options); } + /** The manifest a query's options give, undefined where they give none. */ + static #manifestOf(options) { + return options !== null && typeof options === 'object' ? options.manifest : undefined; + } + /** Evaluates the query once, synchronously, answering the part of its result the path reaches. */ static #evaluate(query, path, { window = globalThis.window, owner = null }) { const resolution = Domql.#resolveFor('evaluate', query); @@ -756,7 +829,9 @@ class Domql { // A resolution stays current until a registration may change what it recognizes, which Nexo alone can tell. if (resolution === undefined || !resolution.isCurrent) { try { - resolution = Domql.#moduleRegistry.resolve(query.definition, bindings); + const manifest = Domql.#manifestOf(DomqlQuery.optionsOf(query)); + + resolution = Domql.#moduleRegistry.resolve(query.definition, bindings, manifest === undefined ? undefined : { manifest }); } catch (error) { throw Domql.#unloadedImportOf(query.definition, error) ?? error; } @@ -1021,18 +1096,27 @@ class Domql { } } +/** The options a query takes, which an operation run directly is given beside its own. */ +const QUERY_OPTIONS = ['types', 'manifest']; + /** - * Runs a query directly, in one call, as the query object its text or definition makes with the bindings runs it: the options hold the query's `types` beside the operation's own, which it is given without them, and options that - * are no object reach the operation as they are, which refuses them. + * Runs a query directly, in one call, as the query object its text or definition makes with the bindings runs it: the options hold the query's `types` and `manifest` beside the operation's own, which it is given without + * them, and options that are no object reach the operation as they are, which refuses them. */ const carryOut = (source, bindings, options, operate, handler) => { - if (options === null || typeof options !== 'object' || !Object.hasOwn(options, 'types')) { + if (options === null || typeof options !== 'object' || !QUERY_OPTIONS.some(key => Object.hasOwn(options, key))) { return operate(Domql.query(source, bindings), options, handler); } - const { types, ...operation } = options; + const operation = { ...options }; + const queryOptions = {}; + + for (const key of QUERY_OPTIONS.filter(name => Object.hasOwn(options, name))) { + queryOptions[key] = options[key]; + delete operation[key]; + } - return operate(Domql.query(source, bindings, { types }), operation, handler); + return operate(Domql.query(source, bindings, queryOptions), operation, handler); }; /** The operations that run a query directly, each a query object's own. */ @@ -1058,9 +1142,10 @@ export const domql = Object.freeze({ executeAsync: async (source, bindings, options) => carryOut(source, bindings, options, AT_ONCE.executeAsync), run: (source, bindings, options) => carryOut(source, bindings, options, AT_ONCE.run), format: source => Domql.format(source), - createModule: (name, contents) => Domql.createModule(name, contents), - registerModule: module => Domql.registerModule(module), - registerModuleLoader: (name, load) => Domql.registerModuleLoader(name, load), + prepare: (modules, options) => Domql.prepare(modules, options), + createModule: (name, contents, options) => Domql.createModule(name, contents, options), + registerModule: (module, options) => Domql.registerModule(module, options), + registerModuleLoader: (name, load, options) => Domql.registerModuleLoader(name, load, options), loadModulesAsync: modules => Domql.loadModulesAsync(modules), info: Object.freeze({ versions: Object.freeze({ runtime: Versions.runtime, specification: Versions.specification, language: Versions.language }) }), }); diff --git a/tests/Domql.test.js b/tests/Domql.test.js index c05df6c..248b240 100644 --- a/tests/Domql.test.js +++ b/tests/Domql.test.js @@ -1,8 +1,9 @@ import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest'; import { DomqlQuery } from '#domql/dom/DomqlQuery.mjs'; import { domql } from '#domql/domql.js'; -import { NexoError } from '@formaui-net/nexo'; +import { nexo, NexoError } from '@formaui-net/nexo'; import { ParsedTexts } from '#nexo/language/ParsedTexts.mjs'; +import { ModuleManifest } from '#domql/dom/ModuleManifest.mjs'; /** The error a call throws. */ const getError = call => { @@ -6411,3 +6412,143 @@ describe('domql executions carried out in one task', () => { document.body.innerHTML = ''; }); }); + +describe('domql manifests', () => { + // Each test loads its own copy of domql, with a registry of its own. + let isolated; + let panel; + let Manifest; + let parse; + let resolve; + + /** The instances of the Mark module's continuous execution, `mark(tone)`, in the order they started. */ + const marks = []; + const markContents = () => ({ + types: [elementExtension('MarkElements', [{ + name: 'mark', kind: 'function', invokedBy: 'host', requestKind: 'execution', executionMode: 'continuous', arguments: 'positional', + parameters: [{ name: 'tone', kind: 'value', type: 'String', required: true }], + impl: ({ receiver, args: { tone } }) => { + const instance = { receiver, tone, update: () => {}, dispose: () => {} }; + + marks.push(instance); + + return instance; + }, + }])], + }); + const scripts = [ + { script: 'panel.children.count', types: { panel: 'Domql.Element' } }, + { script: 'import Mark\npanel:mark(tone)', bindings: { tone: 'warm' }, types: { panel: 'Domql.Element' } }, + ]; + + /** The manifest of the Mark module and the scripts, as a host keeps it, as JSON. */ + const prepare = () => JSON.parse(JSON.stringify(isolated.prepare([{ name: 'Mark', contents: markContents() }], { scripts }))); + + beforeEach(async () => { + vi.resetModules(); + ({ domql: isolated } = await import('#domql/domql.js')); + ({ Manifest } = await import('#nexo/language/vocabulary/Manifest.mjs')); + + const { Parser } = await import('#nexo/language/Parser.mjs'); + const { LanguageResolver } = await import('#nexo/language/LanguageResolver.mjs'); + + parse = vi.spyOn(Parser.prototype, 'parse'); + resolve = vi.spyOn(LanguageResolver.prototype, 'resolveDefinition'); + document.body.innerHTML = '
'; + panel = document.getElementById('panel'); + marks.length = 0; + }); + + afterEach(() => { + parse.mockRestore(); + resolve.mockRestore(); + document.body.innerHTML = ''; + }); + + it('prepares the modules given after DOMQL\'s own, and each script as domql.query reads it, its text read with Domql supplied', () => { + const manifest = prepare(); + + expect(manifest).toMatchObject({ implementation: nexo.info.versions.implementation }); + expect(manifest.modules.map(({ name, after }) => [name, after.map(before => before.name)])).toEqual([['Domql', []], ['Mark', ['Domql']]]); + // DOMQL's module stands at the digest its own manifest gives it, which it was created under, so a module after it registers without its checks. + expect(manifest.modules[0].digest).toBe(ModuleManifest.modules[0].digest); + expect(manifest.scripts.map(({ text, imports, resolutions }) => [text, imports, resolutions.map(({ key }) => key)])).toEqual([ + ['panel.children.count', [{ module: 'Domql' }], ['panel:Domql.Element']], + ['import Mark\npanel:mark(tone)', [{ module: 'Domql' }], ['panel:Domql.Element;tone:Nexo.String="warm"']], + ]); + }); + + it('creates and registers a module under its manifest without the checks it records, and reads a query from it, neither parsing its text nor resolving it', () => { + const manifest = prepare(); + + parse.mockClear(); + resolve.mockClear(); + + const module = isolated.createModule('Mark', markContents(), { manifest }); + + isolated.registerModule(module, { manifest }); + + expect(Manifest.recordOf(module)?.digest).toBe(manifest.modules[1].digest); + expect(isolated.query('panel.children.count', { panel }, { manifest }).evaluate()).toBe(2); + isolated.query('import Mark\npanel:mark(tone)', { panel, tone: 'warm' }, { manifest }).run().dispose(); + expect(isolated.evaluate('panel.children.count', { panel: panel.firstElementChild }, { manifest })).toBe(0); + expect(marks.map(({ receiver, tone }) => [receiver, tone])).toEqual([[panel, 'warm']]); + expect(parse).not.toHaveBeenCalled(); + expect(resolve).not.toHaveBeenCalled(); + }); + + it('resolves a query whose bindings the manifest holds no resolution for, and one made without the manifest, as it resolves any', () => { + const manifest = prepare(); + + isolated.registerModule(isolated.createModule('Mark', markContents(), { manifest }), { manifest }); + resolve.mockClear(); + + const marking = isolated.query('import Mark\npanel:mark(tone)', { panel, tone: 'warm' }, { manifest }); + + marking.with({ panel, tone: 'cold' }).run().dispose(); + expect(resolve).toHaveBeenCalledTimes(1); + expect(isolated.query('panel.children.count', { panel }).evaluate()).toBe(2); + expect(marks.map(({ tone }) => tone)).toEqual(['cold']); + }); + + it('registers a module a loader answers under the options it was registered with, and refuses options that are no object', async () => { + const manifest = prepare(); + const entryOf = vi.spyOn(Manifest, 'entryOf'); + + try { + isolated.registerModuleLoader('Mark', () => isolated.createModule('Mark', markContents(), { manifest }), { manifest }); + await isolated.loadModulesAsync(['Mark']); + + expect(entryOf.mock.results.map(({ value }) => value?.name)).toEqual(['Mark', 'Mark']); + } finally { + entryOf.mockRestore(); + } + + expect(getError(() => isolated.registerModuleLoader('Other', () => null, 'manifest'))).toMatchObject({ kind: 'structure', code: 'DOMQL2013', message: expect.stringContaining("The options the module 'Other' is registered with are an object") }); + }); + + it('creates and resolves everything with every check under a manifest of another implementation, which holds nothing', () => { + const manifest = { ...prepare(), implementation: '0.0.0' }; + const module = isolated.createModule('Mark', markContents(), { manifest }); + + isolated.registerModule(module, { manifest }); + resolve.mockClear(); + + expect(Manifest.recordOf(module)).toBeUndefined(); + expect(isolated.query('panel.children.count', { panel }, { manifest }).evaluate()).toBe(2); + expect(resolve).toHaveBeenCalledTimes(1); + }); + + it('refuses a script that gives imports of its own and a module declaring observation targets, and leaves to Nexo what Nexo refuses', () => { + const targets = { observationTargets: [{ name: 'shelf', resolve: () => null }] }; + + expect(getError(() => isolated.prepare([], { scripts: [{ script: 'panel.size', imports: ['Domql'] }] }))).toMatchObject({ kind: 'structure', code: 'DOMQL2021', message: expect.stringContaining('so a script it prepares gives no imports, and script 0 gives them') }); + expect(getError(() => isolated.prepare([{ name: 'Shelf', contents: targets }]))).toMatchObject({ kind: 'module', code: 'DOMQL4008', location: { module: 'Shelf', declarationKey: 'observationTargets' } }); + expect(getError(() => isolated.prepare('Mark'))).toMatchObject({ code: 'NEXO4565' }); + expect(getError(() => isolated.prepare())).toMatchObject({ code: 'NEXO4565' }); + expect(getError(() => isolated.prepare([], { script: [] }))).toMatchObject({ code: 'NEXO2048' }); + expect(getError(() => isolated.createModule('Mark', markContents(), { prepared: {} }))).toMatchObject({ code: 'NEXO2048' }); + expect(getError(() => isolated.query('panel.size', { panel }, { manifest: 'manifest' }))).toMatchObject({ code: 'NEXO4566' }); + expect(getError(() => isolated.query('panel.size', { panel }, { types: { panel: 'Element' }, manifesto: null }))).toMatchObject({ code: 'NEXO2048' }); + }); +}); diff --git a/tests/PackageReadme.test.js b/tests/PackageReadme.test.js index 33f9950..80d7860 100644 --- a/tests/PackageReadme.test.js +++ b/tests/PackageReadme.test.js @@ -70,6 +70,7 @@ const examples = [ { file: '21-module.js', observed: 'reads', answers: [['{ childCount: 3 }']] }, { file: '37-declared-types.js', observed: 'reads', answers: [["'submit'"]] }, { file: '31-load-on-request.js', observed: 'reads', answers: [['7']] }, + { file: '38-prepare-ahead-of-time.js', observed: 'reads', answers: [["'none'"]] }, { file: '22-execute-once.js', observed: 'reads', answers: [['true']] }, { file: '23-run-continuously.js', observed: 'printed', answers: [["'gold'"], ["'teal'"], ['undefined']] }, { file: '36-anchor.js', observed: 'printed', answers: [["'disposed'"]] }, diff --git a/tests/_examples/38-prepare-ahead-of-time.js b/tests/_examples/38-prepare-ahead-of-time.js new file mode 100644 index 0000000..cd37983 --- /dev/null +++ b/tests/_examples/38-prepare-ahead-of-time.js @@ -0,0 +1,24 @@ +const badges = { + types: [{ + name: 'BadgeElements', + kind: 'extension', + target: 'Domql.Element', + members: [{ + name: 'badge', + kind: 'property', + result: 'String?', + updates: { changes: 'observable', reads: 'fresh', observations: [{ type: 'mutation', of: 'receiver', attributes: ['data-badge'] }] }, + impl: ({ receiver: element }) => element.getAttribute('data-badge') + }] + }] +}; + +// At build time: the module and the query, checked once, as a manifest kept as JSON. +const manifest = domql.prepare([{ name: 'Badges', contents: badges }], { + scripts: [{ script: 'import Badges\npanel:badge ?? "none"', types: { panel: 'Domql.Element' } }] +}); + +// At the page's start: the same module and query, from the manifest. +domql.registerModule(domql.createModule('Badges', badges, { manifest }), { manifest }); +domql.query('import Badges\npanel:badge ?? "none"', { panel }, { manifest }).evaluate(); +// 'none' diff --git a/tests/_types/usage.ts b/tests/_types/usage.ts index 38126ff..6332bf5 100644 --- a/tests/_types/usage.ts +++ b/tests/_types/usage.ts @@ -1,6 +1,6 @@ // How a TypeScript caller uses DOMQL, which the declarations must accept; the test compiles this file. import { domql, NexoError } from '../../src/domql.js'; -import type { DomqlEventArgs, DomqlSubscribeOptions, DomqlFrameOptions, DomqlFrameRequest, DomqlHeldObservation, DomqlMeasureOptions, DomqlChangeOperation, DomqlOperatorImplementationInput, DomqlTypeDeclaration, DomqlDefinition, DomqlDefinitionNode, DomqlEvaluateAsyncOptions, DomqlEventListener, DomqlExecutionHandle, DomqlLiveStateWatch, DomqlLiveStateWatchOptions, DomqlMemberDeclaration, DomqlModule, DomqlModuleContents, DomqlOperationOptions, DomqlQuery, DomqlQueryOptions, DomqlReadOnly, DomqlResolvedDefinition, DomqlResultArgs, DomqlSelectedView, DomqlSelection, DomqlWatch, DomqlWatchOptions } from '../../src/domql.js'; +import type { DomqlEventArgs, DomqlSubscribeOptions, DomqlFrameOptions, DomqlFrameRequest, DomqlHeldObservation, DomqlMeasureOptions, DomqlChangeOperation, DomqlOperatorImplementationInput, DomqlTypeDeclaration, DomqlDefinition, DomqlDefinitionNode, DomqlEvaluateAsyncOptions, DomqlEventListener, DomqlExecutionHandle, DomqlLiveStateWatch, DomqlLiveStateWatchOptions, DomqlManifestOptions, DomqlMemberDeclaration, DomqlModule, DomqlModuleContents, DomqlPrepareOptions, DomqlOperationOptions, DomqlQuery, DomqlQueryOptions, DomqlReadOnly, DomqlResolvedDefinition, DomqlResultArgs, DomqlSelectedView, DomqlSelection, DomqlWatch, DomqlWatchOptions, NexoManifest } from '../../src/domql.js'; const panel = document.createElement('div'); const controller = new AbortController(); @@ -432,8 +432,25 @@ const lamps: DomqlModuleContents = { // @ts-expect-error A module declares its states as members, properties whose result is a Boolean, and no predicates. domql.createModule('Tests', { predicates: [] }); -// @ts-expect-error A module is created from its contents alone, each declaration carrying its implementation. -domql.createModule('Metrics', contents, {}); +// A host's build prepares its modules and its queries, and its start gives the manifest back, sparing the checks it records. +const prepareOptions: DomqlPrepareOptions = { scripts: [{ script: 'import Metrics\npanel.children.count', types: { panel: 'Domql.Element' } }, { script: definition, bindings: { panel } }] }; +const manifest: NexoManifest = domql.prepare([{ name: 'Metrics', contents }], prepareOptions); +const manifestOptions: DomqlManifestOptions = { manifest }; +const fromManifest: DomqlModule = domql.createModule('Metrics', contents, manifestOptions); + +domql.registerModule(fromManifest, { manifest }); +domql.registerModuleLoader('Prepared', () => domql.createModule('Prepared', { types: [] }, { manifest }), { manifest }); +domql.query('import Metrics\npanel.children.count', { panel }, { manifest }).evaluate(); +domql.evaluate('import Metrics\npanel.children.count', { panel }, { manifest, types: { panel: 'Domql.Element' }, owner: 'circuit' }); +domql.query('panel.size', { panel }, { manifest: null }); + +const manifestKept: string = JSON.stringify(manifest); + +// @ts-expect-error A module is created from its contents, under the manifest its options give, which name no other. +domql.createModule('Metrics', contents, { prepared: manifest }); + +// @ts-expect-error A prepared query is read with Domql supplied, as domql.query reads it, and gives no imports. +domql.prepare([], { scripts: [{ script: 'panel.size', imports: ['Domql'] }] }); // @ts-expect-error A reference type says whether a value belongs to it. domql.createModule('Partial', { types: [{ name: 'Lamp', kind: 'reference' }] }); diff --git a/tests/dom/DispatchTable.test.js b/tests/dom/DispatchTable.test.js index f524739..4ad085e 100644 --- a/tests/dom/DispatchTable.test.js +++ b/tests/dom/DispatchTable.test.js @@ -152,12 +152,12 @@ describe('DispatchTable', () => { it('creates a module of the same contents under it with none of Nexo\'s checks it records, keeping each host call as the table keeps it, and one of other contents with every check', async () => { const { Manifest } = await import('#nexo/language/vocabulary/Manifest.mjs'); const manifest = DispatchTable.prepare([{ name: 'Domql', contents: BrowserVocabularyDeclarations.contentsOf() }, { name: 'Desk', contents: contents() }]); - const module = DispatchTable.createModule('Desk', contents(), undefined, manifest); + const module = DispatchTable.createModule('Desk', contents(), undefined, { manifest }); const [declaration] = module.types[0].members; expect(Manifest.recordOf(module)?.digest).toBe(manifest.modules[1].digest); expect(DispatchTable.get(declaration)).toMatchObject({ requestKind: 'execution', executionMode: 'once', implementation: execute, module: 'Desk', type: 'DeskElements' }); - expect(Manifest.recordOf(DispatchTable.createModule('Desk', { members: [] }, undefined, manifest))).toBeUndefined(); + expect(Manifest.recordOf(DispatchTable.createModule('Desk', { members: [] }, undefined, { manifest }))).toBeUndefined(); expect(Manifest.recordOf(DispatchTable.createModule('Desk', contents()))).toBeUndefined(); }); From 4cf51b8205b068d1f435409d79d1236e44e68d29 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:57:15 +0200 Subject: [PATCH 09/15] fix(domql): take every answer a source delivers A module's own event source hands deliver the event alone, so what else it passes takes no subscription's answer away: events.forEach(deliver) passed each index beside its event, and the first event's answer was dropped. --- src/domql.js | 3 ++- tests/dom/Behaviors.test.js | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/domql.js b/src/domql.js index 1a5da41..09bc112 100644 --- a/src/domql.js +++ b/src/domql.js @@ -610,7 +610,8 @@ class Domql { const start = Domql.#implementationOf(call); - return deliver => start({ receiver: call.receiver, args: call.args, env: environment, deliver }); + // A module's own event source hands each event to deliver alone, as deliver(event), so what else it passes, as forEach's index, reaches no subscription. + return deliver => start({ receiver: call.receiver, args: call.args, env: environment, deliver: event => deliver(event) }); }, getLocation: pointer => resolution.getLocation(pointer), observations: Domql.#getObservations(window), diff --git a/tests/dom/Behaviors.test.js b/tests/dom/Behaviors.test.js index 3a1e6c7..e782a53 100644 --- a/tests/dom/Behaviors.test.js +++ b/tests/dom/Behaviors.test.js @@ -796,6 +796,8 @@ describe('Behaviors\' occurrences', () => { const questions = isolated.query('import Questions\nzone:questions()', { zone }).subscribe((sender, args) => args.value * 2); await expect(deliver(21)).resolves.toBe(42); + // What else the source passes beside the event, as forEach's index, reaches no subscription: each answer is taken. + await expect(Promise.all([1, 2].map(deliver))).resolves.toEqual([2, 4]); questions.dispose(); }); }); From 233ad06a4c8b40902906889e9842fce3a0b68907 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:57:20 +0200 Subject: [PATCH 10/15] fix(domql): read a box of no size as no box layoutSize is null for a box of no size, 0 by 0, which a resize observer measures as it measures no box: a watch of an empty element stayed at 0 by 0 after it was hidden or detached, where a new evaluation read null. Read alike, layoutSize stays observable. D117 records it. --- CHANGELOG.md | 2 +- VERSION-HISTORY.md | 2 +- docs/decisions.md | 18 ++++++++++++++- nuget/README.md | 2 +- spec/vocabulary.md | 2 +- src/dom/BrowserVocabularyImplementations.mjs | 4 ++-- tests/dom/LayoutSize.browser.js | 24 ++++++++++++++++++++ 7 files changed, 47 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c71f987..f4280c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ Each release of DOMQL's packages, newest first. The npm package `@formaui-net/do *Unreleased · specification `1.0.0-preview.2` · Nexo language `1.0.0-preview.3` · definition format 38* -- An element's `layoutSize` answers the size layout gives its border box, along its writing mode's axes, `{ inline, block }`, a transform aside, from the browser's resize observer, and a watch follows every change of it. +- An element's `layoutSize` answers the size layout gives its border box, along its writing mode's axes, `{ inline, block }`, a transform aside, from the browser's resize observer, null where the element is laid out as no one box or as one of no size, and a watch follows every change of it. - A watch of an element's `size` is refused unless it accepts partial observation, since a transform changes the box as it is drawn with no observer reporting it. Watch `layoutSize`, or accept partial observation. - A watch of `autofilled` follows an animation the page's style starts on a field as the browser fills or empties it. - An event source declaring `answers` is answered: `deliver` fulfils with its first subscription's answer, the handler's return or its promise's value, captured as the declared type, where it fulfilled with undefined. diff --git a/VERSION-HISTORY.md b/VERSION-HISTORY.md index b52f2cb..343ecc3 100644 --- a/VERSION-HISTORY.md +++ b/VERSION-HISTORY.md @@ -50,7 +50,7 @@ DOMQL moves to Nexo's language `1.0.0-preview.3`, by way of `1.0.0-preview.2`, w **Vocabulary** -- [`layoutSize`](spec/vocabulary.md#property-element-layoutsize) is the size layout gives an element's border box, along the axes of its writing mode, `inline` and `block`, a transform aside, as the browser's resize observation measures it. It reads a maintained observation of its own, [`layoutSize`](spec/vocabulary.md#observations-types), so it is observable, null where the element is laid out as no one box, and pending until the browser first reports it, as [D111](docs/decisions.md#d111) records. +- [`layoutSize`](spec/vocabulary.md#property-element-layoutsize) is the size layout gives an element's border box, along the axes of its writing mode, `inline` and `block`, a transform aside, as the browser's resize observation measures it. It reads a maintained observation of its own, [`layoutSize`](spec/vocabulary.md#observations-types), so it is observable, null where the element is laid out as no one box or as a box of no size, 0 by 0, and pending until the browser first reports it, as [D111](docs/decisions.md#d111) and [D117](docs/decisions.md#d117) record. - [`size`](spec/vocabulary.md#property-element-size) is the box as it is drawn, as it was read, and partly observable: a transform or an animation, its own or an ancestor's, and the size of an inline box are missed, where it was called observable and missed them. - [`autofilled`](spec/vocabulary.md#state-element-autofilled) observes `animationstart` and `animationcancel` on its field too, so a page whose style starts an animation on a field as the browser fills or empties it is followed, as [D112](docs/decisions.md#d112) records. diff --git a/docs/decisions.md b/docs/decisions.md index e1e7405..e72f350 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -1707,7 +1707,7 @@ Each entry is one of three kinds: - **Kind:** Contract, correcting a fault; a feature Forma's scripts need, as [what 1.0 requires](features-status.md#what-1-0-requires) allows. - **Decision:** - `size` stays the border box as it is drawn, transforms applied, as `rect` measures it, and is partly observable. It misses a transform or an animation, its own or an ancestor's, and the size of an inline box. - - `layoutSize`, a new member, is the border box as layout gives it, along the writing mode's axes: `LogicalSize { inline, block }`. It reads a maintained observation of its own, `layoutSize`, which samples the browser's resize observation, so it is observable. It is null where the element is laid out as no one box, and pending until the browser's first report. Chromium, Firefox and WebKit each make one for a box of any size, a hidden or a detached element included, as they lay the page out, so an element of a hidden document waits until the document is shown, as one `intersects` reads does. + - `layoutSize`, a new member, is the border box as layout gives it, along the writing mode's axes: `LogicalSize { inline, block }`. It reads a maintained observation of its own, `layoutSize`, which samples the browser's resize observation, so it is observable. It is null where the element is laid out as no one box, or, as [D117](#d117) records, as a box of no size, and pending until the browser's first report. Chromium, Firefox and WebKit each make one for a box of any size, a hidden or a detached element included, as they lay the page out, so an element of a hidden document waits until the document is shown, as one `intersects` reads does. - **Why:** - `size` read `getClientRects()`, the box as drawn, but its one observation was the resize observer, which reports the box as laid out. A transform changed `size` with nothing observing it, while the specification called it observable. In Chromium, a watch of `size` stayed at 200×50 after `scale(0.5)`, where a refresh read 100×25. - Forma's stepper reads a box's size from C# to decide whether its steps' names fit. It needs the size layout gives the box, along its writing mode, which no member answered. @@ -1804,3 +1804,19 @@ Each entry is one of three kinds: - DOMQL keeping the manifests it is given, so a query names none. A page holding several libraries' manifests would leave DOMQL to choose among them. - Naming the option `moduleManifest`, as DOMQL's own module's is named. DOMQL gives the option to Nexo as it is, under Nexo's name. - Compiling prepared queries to JavaScript. That waits for a measured need, as the start-up's direction set. + + + +## D117 — A box of no size has no `layoutSize` + +*November 30, 2026* + +- **Kind:** Contract, correcting a fault in [D111](#d111) before its release. +- **Decision:** `layoutSize` is null for a box of no size, 0 by 0, as it is where the element is laid out as no one box. +- **Why:** + - A resize observer reports a change of size alone, and measures a box of no size as it measures no box. A box of no size that is hidden, detached, made inline, or shown again resizes nothing it reports. + - In Chromium, a watch of an empty, absolutely positioned element stayed at `{ inline: 0, block: 0 }` after `display: none` and after it was detached, where a new evaluation read null. + - Read alike, the two are no change, so `layoutSize` stays observable, as D111 needs it to be. +- **Declined:** + - Partly observable `layoutSize`. Every watch of it would have to accept partial observation, which is what D111 made it to spare. + - Observing styles and attachment beside the resize observer. A stylesheet's rule hides a box with no observer reporting it, and observing every mutation of the tree would cost every watch of a size. diff --git a/nuget/README.md b/nuget/README.md index 35d8ac8..e67aab6 100644 --- a/nuget/README.md +++ b/nuget/README.md @@ -798,7 +798,7 @@ panel.scroll { } ``` -`rect` and `size` measure the box as it is drawn, its transforms and its ancestors' applied. `layoutSize` is the size layout gives the box, along its writing mode's axes, `inline` and `block`, with any transform left aside, as the browser's resize observer measures it. It is pending until the browser first reports the box, as it lays the page out: `evaluate` fails on it, so read it with `evaluateAsync` or a watch, whose first snapshot waits for that report. +`rect` and `size` measure the box as it is drawn, its transforms and its ancestors' applied. `layoutSize` is the size layout gives the box, along its writing mode's axes, `inline` and `block`, with any transform left aside, as the browser's resize observer measures it, and null for an element that isn't laid out as one box, or whose box has no size. It is pending until the browser first reports the box, as it lays the page out: `evaluate` fails on it, so read it with `evaluateAsync` or a watch, whose first snapshot waits for that report. `scrollContainer()` finds the nearest ancestor the user can scroll, across shadow roots and slots, and is null where the window scrolls the element. `sizeLimits` reads the `min-width`, `max-width`, `min-height` and `max-height` a box is kept within, in pixels, each null where it is no length. A watch compares each measurement within a twentieth of a pixel, so a box settling by less reports no change. diff --git a/spec/vocabulary.md b/spec/vocabulary.md index a20fe9b..82956c6 100644 --- a/spec/vocabulary.md +++ b/spec/vocabulary.md @@ -270,7 +270,7 @@ A property exposes a value, read by property access, and takes no argument. Each **Result.** The size layout gives its border box, along the axes of its writing mode, `inline` and `block`, as the browser's resize observation measures it: a transform, its own or an ancestor's, changes how the box is drawn, which [`size`](#property-element-size) answers, and not its layout, which this answers. A box in a vertical writing mode, 40 pixels wide and 300 high, is 300 along its inline axis and 40 along its block axis. -It is null where the element is laid out as no one box: while it has no layout box, as [measurements and layout](#vocabulary-measurements-and-layout) set out, and while it is an inline box of text and elements, `display: inline` on an element its own content doesn't replace, which flows as fragments no resize observer measures. An element replaced by what it shows, as an image, a video or a form control, is one box whatever its display, and so is an SVG element, which the resize observation measures by its bounding box. It is pending until the browser first reports the element, which it does as it lays the page out, so not while the document is hidden: `evaluate` fails on it, as on any [maintained member](evaluation.md#waiting-for-maintained-members), and `evaluateAsync` and a watch's first snapshot wait for that report. So the first snapshot holds the size as laid out, never a size the box was drawn at before it. +It is null where the element is laid out as no one box: while it has no layout box, as [measurements and layout](#vocabulary-measurements-and-layout) set out, and while it is an inline box of text and elements, `display: inline` on an element its own content doesn't replace, which flows as fragments no resize observer measures. It is null for a box of no size too, 0 by 0, which a resize observer measures as it measures no box: a box of no size that stops or starts being laid out resizes nothing it reports, so reading both alike keeps every change observed. An element replaced by what it shows, as an image, a video or a form control, is one box whatever its display, and so is an SVG element, which the resize observation measures by its bounding box. It is pending until the browser first reports the element, which it does as it lays the page out, so not while the document is hidden: `evaluate` fails on it, as on any [maintained member](evaluation.md#waiting-for-maintained-members), and `evaluateAsync` and a watch's first snapshot wait for that report. So the first snapshot holds the size as laid out, never a size the box was drawn at before it. **Changes.** Observable diff --git a/src/dom/BrowserVocabularyImplementations.mjs b/src/dom/BrowserVocabularyImplementations.mjs index 07cad4e..672de01 100644 --- a/src/dom/BrowserVocabularyImplementations.mjs +++ b/src/dom/BrowserVocabularyImplementations.mjs @@ -79,8 +79,8 @@ export class BrowserVocabularyImplementations { devicePixelRatio: ({ receiver: window }) => window.devicePixelRatio, // The property reads the rectangle against the layout viewport, and rectRelativeTo against the element it is given. rect: ({ receiver: element, args: { relativeTo = null } }) => BrowserVocabularyImplementations.#rect(element, relativeTo), - // The size layout gives its border box, as the browser's resize observation last measured it, where it is laid out as one box. - layoutSize: ({ receiver: element, env: { window }, samples: [size] }) => (size === null || !BrowserVocabularyImplementations.#isLaidOutAsOneBox(element, window) ? null : size), + // The size layout gives its border box, as the browser's resize observation last measured it, where it is laid out as one box of some size; a box of no size, 0 by 0, is read as none. + layoutSize: ({ receiver: element, env: { window }, samples: [size] }) => (size === null || (size.inline === 0 && size.block === 0) || !BrowserVocabularyImplementations.#isLaidOutAsOneBox(element, window) ? null : size), size: ({ receiver: element }) => { const rect = BrowserVocabularyImplementations.boxOf(element); diff --git a/tests/dom/LayoutSize.browser.js b/tests/dom/LayoutSize.browser.js index d8b7ea4..28b460c 100644 --- a/tests/dom/LayoutSize.browser.js +++ b/tests/dom/LayoutSize.browser.js @@ -66,6 +66,30 @@ describe('layoutSize in a browser', () => { await afterLayout(); }); + it('is null for a box of no size, which a resize observer tells from no box by no report, so a watch follows a box as it stops and starts being laid out', async () => { + const sentinel = add('position: absolute'); + const snapshots = []; + const watch = domql.query('sentinel.layoutSize', { sentinel }).watch({ schedule: 'immediate' }); + + watch.subscribe('change', (sender, args) => snapshots.push(args.value)); + await watch.readyAsync(); + await afterLayout(); + sentinel.style.display = 'none'; + await afterLayout(); + sentinel.style.display = ''; + await afterLayout(); + sentinel.style.width = '30px'; + sentinel.style.height = '10px'; + await afterLayout(); + sentinel.remove(); + await afterLayout(); + watch.dispose(); + + expect(snapshots).toEqual([null, { inline: 30, block: 10 }, null]); + expect(await domql.query('sentinel.layoutSize', { sentinel }).evaluateAsync()).toBeNull(); + await afterLayout(); + }); + it('is watched from the size laid out first, under a transform too, and follows each resize, with no partial observation to accept', async () => { const box = add('width: 200px; height: 50px; transform: scale(0.5)'); const snapshots = []; From e6d55d23583ae9b437c964e6cc50e7bb0716569b Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:57:25 +0200 Subject: [PATCH 11/15] docs(domql): count size as partly observable The specification's example names Element.size among the members whose watch must accept partial observation, as the refusal names it, and the members by their types, Node.all and Element.rect, as it writes them. Its observable member is layoutSize, which a resize observation covers, where it was an element's size. --- spec/examples.md | 2 +- spec/watches.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/spec/examples.md b/spec/examples.md index eccc860..cd602d1 100644 --- a/spec/examples.md +++ b/spec/examples.md @@ -85,7 +85,7 @@ With no item selected, `current` is null. With an empty panel, `items` is an emp `intersects` reads maintained values, so the result comes from an asynchronous evaluation or a watch, which wait for its first samples; a synchronous evaluation of the query fails, since it cannot wait. -Watching the query requires accepting partial observation, since `all`, `style`, `grid`, `rect` and `first` are partly observable, which the refusal names as `node.all`, `element.style`, `element.grid`, `element.rect` and `node.first`, each with the changes it misses; the watch then follows the items the panel holds, each item's height, attributes and intersection, the panel's size and focus, the sentinel's intersection, the media query and the document's visibility. +Watching the query requires accepting partial observation, since `all`, `size`, `style`, `grid`, `rect` and `first` are partly observable, which the refusal names as `Node.all`, `Element.size`, `Element.style`, `Element.grid`, `Element.rect` and `Node.first`, each with the changes it misses; the watch then follows the items the panel holds, each item's height, attributes and intersection, the panel's size and focus, the sentinel's intersection, the media query and the document's visibility. diff --git a/spec/watches.md b/spec/watches.md index 068b8ee..077f7df 100644 --- a/spec/watches.md +++ b/spec/watches.md @@ -74,7 +74,7 @@ Every member declares how its result changes, by the categories [Nexo defines](h | Category | As in DOMQL | In a watch | | --- | --- | --- | | Constant | Whether the browser offers a capability, as `Domql.window.canShare` reads | Allowed; it never invalidates. | -| Observable | A size, which a resize observation covers | Allowed. | +| Observable | The size layout gives a box, `layoutSize`, which a resize observation covers | Allowed. | | Partly observable | A computed style, which a rule outside the element can change unobserved | Allowed when the caller accepts partial observation for that watch; a change the observations miss reaches the watch at its next evaluation, which `refreshAsync` or another observed change causes. | | Unobserved | A member that names no observations | A validation error. | From 6e4c5bfc409b566f6b9dbb81c00ca764a301625e Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:57:30 +0200 Subject: [PATCH 12/15] chore(domql): say what the consumers' folder is The packages script's comment says what its work folder is, outside the repository, where no node_modules of the repository's own is found, rather than why it was put there. --- scripts/Test-Packages.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/Test-Packages.ps1 b/scripts/Test-Packages.ps1 index 7d058ab..5c4faf9 100644 --- a/scripts/Test-Packages.ps1 +++ b/scripts/Test-Packages.ps1 @@ -103,7 +103,7 @@ foreach ($name in $expected.Keys) { Write-Host " $name holds the $($listed.Count) files its list names" } -# Outside the repository, not in .sandbox/: within it, Node and TypeScript would also search the repository's own node_modules, which no consumer has. +# The consumers' work folder, outside the repository and its .sandbox/, where Node and TypeScript find none of the repository's own node_modules, as no consumer does. $work = Join-Path ([System.IO.Path]::GetTempPath()) "domql-packages-$([guid]::NewGuid().ToString('N'))" $previousPackages = $env:NUGET_PACKAGES From 135a440a3393bcca26cbd9fedd520d85f6320326 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:32:24 +0200 Subject: [PATCH 13/15] feat(domql): add the C# half domql.connect carries DOMQL's operations across a boundary as messages: a host's requests in batches, each answered once its task ends, and each task's deliveries together, a watch's paced by its acknowledgment and an event behind nothing. The NuGet package holds the .NET half over it: AddDomql, a DomqlConnection for each browser runtime, owners, watches that keep a copy by change sets, subscriptions, executions and typed results, the operations of one turn crossing in one call. Both appliers pass the change sets' conformance corpus. D118 and D119 record it, D119 replacing D46. --- .editorconfig | 19 + .gitignore | 4 + CHANGELOG.md | 2 + CLAUDE.md | 9 +- CONTRIBUTING.md | 5 +- VERSION-HISTORY.md | 15 + build.ps1 | 9 +- docs/decisions.md | 52 ++ docs/domql-design.md | 62 +-- docs/features-status.md | 42 +- nuget/DomqlChangeSet.cs | 184 +++++++ nuget/DomqlConnection.cs | 462 ++++++++++++++++ nuget/DomqlException.cs | 101 ++++ nuget/DomqlExecution.cs | 182 +++++++ nuget/DomqlHandle.cs | 91 ++++ nuget/DomqlLog.cs | 13 + nuget/DomqlOwner.cs | 152 ++++++ nuget/DomqlQuery.cs | 101 ++++ nuget/DomqlReceiver.cs | 38 ++ nuget/DomqlRequest.cs | 79 +++ nuget/DomqlRoute.cs | 48 ++ nuget/DomqlServiceCollectionExtensions.cs | 23 + nuget/DomqlSubscription.cs | 141 +++++ nuget/DomqlWatch.cs | 359 +++++++++++++ nuget/Forma.DOMQL.csproj | 11 + nuget/Forma.DOMQL.slnx | 2 + nuget/README.md | 33 ++ nuget/global.json | 3 + nuget/scripts/domql.dotnet.js | 33 ++ scripts/bundle.mjs | 6 +- scripts/packages/npm.files | 1 + scripts/packages/nuget.files | 2 + spec/README.md | 8 +- spec/api.md | 1 + spec/connections.md | 110 ++++ spec/dotnet.md | 123 +++++ spec/errors.md | 9 + src/connections/Connection.mjs | 593 +++++++++++++++++++++ src/domql.d.ts | 74 +++ src/domql.js | 14 + tests/DocumentExamples.test.js | 2 + tests/_conformance/change-sets.json | 137 +++++ tests/_types/usage.ts | 22 +- tests/connections/Connection.test.js | 397 ++++++++++++++ tests/connections/DotnetConnection.test.js | 51 ++ tests/dotnet/DomqlChangeSetTests.cs | 43 ++ tests/dotnet/DomqlConnectionTests.cs | 412 ++++++++++++++ tests/dotnet/FakeBrowser.cs | 130 +++++ tests/dotnet/Forma.DOMQL.Tests.csproj | 31 ++ tests/dotnet/TestDispatcher.cs | 64 +++ tests/snapshots/SnapshotPatcher.test.js | 16 + tests/vitest.config.js | 2 + 52 files changed, 4459 insertions(+), 64 deletions(-) create mode 100644 nuget/DomqlChangeSet.cs create mode 100644 nuget/DomqlConnection.cs create mode 100644 nuget/DomqlException.cs create mode 100644 nuget/DomqlExecution.cs create mode 100644 nuget/DomqlHandle.cs create mode 100644 nuget/DomqlLog.cs create mode 100644 nuget/DomqlOwner.cs create mode 100644 nuget/DomqlQuery.cs create mode 100644 nuget/DomqlReceiver.cs create mode 100644 nuget/DomqlRequest.cs create mode 100644 nuget/DomqlRoute.cs create mode 100644 nuget/DomqlServiceCollectionExtensions.cs create mode 100644 nuget/DomqlSubscription.cs create mode 100644 nuget/DomqlWatch.cs create mode 100644 nuget/scripts/domql.dotnet.js create mode 100644 spec/connections.md create mode 100644 spec/dotnet.md create mode 100644 src/connections/Connection.mjs create mode 100644 tests/_conformance/change-sets.json create mode 100644 tests/connections/Connection.test.js create mode 100644 tests/connections/DotnetConnection.test.js create mode 100644 tests/dotnet/DomqlChangeSetTests.cs create mode 100644 tests/dotnet/DomqlConnectionTests.cs create mode 100644 tests/dotnet/FakeBrowser.cs create mode 100644 tests/dotnet/Forma.DOMQL.Tests.csproj create mode 100644 tests/dotnet/TestDispatcher.cs diff --git a/.editorconfig b/.editorconfig index 820423c..6aefb2c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -504,4 +504,23 @@ dotnet_diagnostic.IDE0301.severity = error # Use collection express dotnet_diagnostic.IDE0302.severity = error # Use collection expression for stackalloc dotnet_diagnostic.IDE0305.severity = warning # Use collection expression for fluent + +[{*Tests.cs,*Tests.*.cs}] +# ------------------------------------------------------------ +# Test sources, under tests/dotnet/ +# ------------------------------------------------------------ + +# Disable IDE0017 and IDE0028 - Arrange builds the subject and Act mutates it, so folding the two together is not an improvement. +dotnet_diagnostic.IDE0017.severity = none +dotnet_diagnostic.IDE0028.severity = none + +# Disable CA2007 - xUnit1030 conflicts with ConfigureAwait(false) +dotnet_diagnostic.CA2007.severity = none + +# Disable CA1707 - Identifiers should not contain underscores (test method names) +dotnet_diagnostic.CA1707.severity = none + +# Disable CA1062 - Validate arguments of public methods (test methods don't need null checks) +dotnet_diagnostic.CA1062.severity = none + # End of .editorconfig diff --git a/.gitignore b/.gitignore index e4cb8df..e073609 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,10 @@ nuget/bin/ nuget/obj/ artifacts/ +# The .NET half's tests, as dotnet builds them. +tests/dotnet/bin/ +tests/dotnet/obj/ + # What an IDE builds of the package consumer the full gate copies out of the repository. scripts/packages/*/bin/ scripts/packages/*/obj/ diff --git a/CHANGELOG.md b/CHANGELOG.md index f4280c5..44370b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,8 @@ Each release of DOMQL's packages, newest first. The npm package `@formaui-net/do - Runs on Nexo's language `1.0.0-preview.3`, from Nexo's release `1.0.0-preview.4`, as the [version history](VERSION-HISTORY.md#v1-0-0-preview-2) sets out: a refusal of `root` written where no object expression encloses it, or read other than through its fields, says that a binding named root is read as `~root`. `domql.info.versions.language` reports `1.0.0-preview.3`. - A continuous execution's start, a subscription's start and a once execution find where their call stands only where a failure names it, so one that fails nowhere reads its query's text no second time: in Node, a query's first run took about 0.47 ms where it took 0.58, and its first once execution about 0.51 ms where it took 0.57. - DOMQL's module and its registry are created under the manifest Nexo makes of the module, which DOMQL's sources hold, so a start makes none of the checks it records: in Chromium, cold, DOMQL's import took about 33.5 ms where it took 43, and its first resolution and registrations about 2 ms more. DOMQL on a Nexo other than the one it was built against creates its module with every check, as before. +- `domql.connect(deliver)` carries this instance's operations across a boundary as messages: a host's requests in batches, each answered once its task ends, a watch's first snapshot among the answers, and each task's deliveries together, a watch's paced by its acknowledgment and an event behind nothing. +- The NuGet package holds the .NET half: `services.AddDomql()`, a `DomqlConnection` for each browser runtime, owners whose disposal ends every operation they started in one call, watches whose copies change sets keep current, subscriptions, executions, and results mapped onto types. The operations one turn starts cross in one call. The package references Microsoft.JSInterop, and serves `domql.dotnet.js` beside the bundle. - A host prepares its modules and queries ahead of time: `domql.prepare(modules, { scripts })` answers Nexo's manifest, and `createModule`, `registerModule`, `registerModuleLoader` and `query` take it as `manifest`, sparing the checks it records. In Chromium, cold, a host's first query took about 5.6 ms where it took 11.6, and its module, a subscription and a run about 3.2 ms where they took 5.4. diff --git a/CLAUDE.md b/CLAUDE.md index 01161f9..f1b2a5b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,20 +32,22 @@ Use these sources rather than inventing scope, status or style rules. | `src/domql.js` | Entry point that composes the library's modules | | `src/Versions.mjs` | The versions DOMQL reports: its runtime release, the specification it follows, and the language its Nexo runtime follows | | `src/dom/` | Evaluation, watches, events, executions, observations, sessions and built-in implementations | +| `src/connections/` | A connection: DOMQL's operations carried across a boundary as messages, for a host whose code runs elsewhere | | `src/snapshots/` | Computing, comparing, dispatching and applying snapshot updates using identity metadata; no DOM access | -| `tests/` | Tests mirroring the source folders | +| `tests/` | Tests mirroring the source folders; the .NET half's in `tests/dotnet/`, and the change sets' conformance corpus in `tests/_conformance/` | | `scripts/` | Bundling scripts, the manifest of DOMQL's own module, and the package's file lists and verification | | `spec/` | The specification, one document per subject, indexed by `spec/README.md` | | `docs/` | The design, the status overview and the decisions | | `VERSION-HISTORY.md` | Each DOMQL version and what it changed | | `CHANGELOG.md` | Each release of the packages and what it changed | -| `nuget/` | The package project, which distributes the bundle, and the library guide | +| `nuget/` | The package project: the .NET half's C# sources, the module its connection opens in the browser, the bundle it distributes, and the library guide | | `.sandbox/` | Work that stays out of the repository: experiments, spikes, notes, scratch and temporary files, and benchmark baselines; ignored by Git | Add a folder when a new responsibility needs one. Keep dependencies in this direction: - `dom/` may depend on Nexo and `snapshots/`. - `snapshots/` may depend on Nexo. +- `connections/` may depend on Nexo, and reaches DOMQL through the instance its entry point gives it. The language is Nexo, the package `@formaui-net/nexo`, which DOMQL imports by its name and installs from npm, at the release `package.json` declares as the lowest it works with and its lock installs, so a change reaches DOMQL only when that version moves to a release that holds it; with `NEXO_SOURCE` naming a checkout, `build.ps1` links that checkout's working tree in the package's place instead. A change to the language is made there, and a change DOMQL needs of it in both repositories together, with `NEXO_SOURCE` set, moving the version once Nexo releases it. Link Nexo's documents at the release's tag, as `https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md`, so they move with it; the link test reads them from a checkout of [FormaUI/Nexo](https://github.com/FormaUI/Nexo) beside this one, named `formaui-net.Nexo`. @@ -96,7 +98,8 @@ Tests mirror `src/` under `tests/`. Layout, geometry and browser-managed state b | `npm run test:engines` | `tests/` | The tests of what engines decide differently, in Chromium, Firefox and WebKit | | `npm run bench` | `tests/` | Benchmarks, outside the gate | | `npm run scale` | `tests/` | Chromium workloads timed outside the gate, one file at a time: a watch of 1,000 to 100,000 rows, a drag through owned writes, an edit in a large editor, a behavior's deliveries and owners, and transient measurements beside many observers | -| `./build.ps1` | Repository root | Tests, bundle, package build and format check | +| `dotnet test --solution Forma.DOMQL.slnx` | `nuget/` | The .NET half's tests | +| `./build.ps1` | Repository root | Tests, bundle, package build, the .NET half's tests and format check | | `./build.ps1 -Browser` | Repository root | Gate including browser tests | | `./build.ps1 -Browser -Full` | Repository root | The full gate: the gate including browser tests, then the NuGet package packed and verified as consumers install it | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2492947..cba0e0b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -39,10 +39,11 @@ Run the full build from the repository root: | Location | Contents | | --- | --- | | `src/dom/` | DOM evaluation, observations, watches, events, executions and the dispatch table of host calls | +| `src/connections/` | A connection, which carries DOMQL's operations across a boundary as messages | | `src/snapshots/` | Snapshot comparison and updates | -| `tests/` | Tests arranged to match the source folders | +| `tests/` | Tests arranged to match the source folders; the .NET half's in `tests/dotnet/` | | `scripts/` | Bundling scripts, and the one that writes the manifest of DOMQL's own module, `npm run manifest` | -| `nuget/` | Package project and library guide | +| `nuget/` | Package project, with the .NET half's C# sources, and library guide | | `spec/` | The specification, split by subject, with its index | | `docs/` | The design and the status overview | | `VERSION-HISTORY.md` | Each DOMQL version and what it changed | diff --git a/VERSION-HISTORY.md b/VERSION-HISTORY.md index 343ecc3..5e85c04 100644 --- a/VERSION-HISTORY.md +++ b/VERSION-HISTORY.md @@ -46,6 +46,16 @@ domql.registerModule(domql.createModule('Charts', contents, { manifest }), { man domql.query('import Charts\npanel:palette', { panel }, { manifest }); // read from the manifest, neither parsed nor resolved; NEXO2048 before, an option the bindings take none of ``` +```js +const connection = domql.connect(deliveries => host.receiveAsync(deliveries)); // a connection across a boundary; a TypeError before, no such function + +await connection.requestAsync([{ request: 'watch', handle: 1, owner: 'panel', query: { key: 'n', text: 'panel.children.count' }, bindings: { panel } }]); // [{ snapshot: 3 }] +``` + +```csharp +DomqlWatch watch = owner.Watch(DomqlQuery.Create("panel.children.count"), bindings, count => RenderAsync(count)); // kept current in .NET, by change sets; no .NET half before +``` + DOMQL moves to Nexo's language `1.0.0-preview.3`, by way of `1.0.0-preview.2`, which Nexo's release `1.0.0-preview.4` carries, as [D114](docs/decisions.md#d114) records. Nexo's [language history](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/LANGUAGE-HISTORY.md#v1-0-0-preview-3) sets out its own changes by version; the one below is the one a query meets. **Vocabulary** @@ -63,6 +73,11 @@ DOMQL moves to Nexo's language `1.0.0-preview.3`, by way of `1.0.0-preview.2`, w - [An event source is answered](spec/behaviors.md#behaviors-answers) where it declares `answers`, the type of the answer: each subscription's handler answers an occurrence with what it returns, or what its promise fulfils with, and `deliver`'s promise fulfils with the first subscription's answer, captured as that type, where it fulfilled with undefined. An answer the type refuses rejects with `DOMQL5025`, and `answers` declared by anything but an event source is refused with `DOMQL4016`, as [D113](docs/decisions.md#d113) records. - [Modules and queries are prepared ahead of time](spec/vocabulary.md#extension-modules-manifests): `domql.prepare(modules, { scripts })` checks modules, as `domql.createModule` takes them, registered after DOMQL's own, and resolves queries, as `domql.query` takes them, answering Nexo's manifest. `domql.createModule`, `domql.registerModule`, `domql.registerModuleLoader` and `domql.query` take it as `manifest`, and an operation run directly beside `types`, each sparing the checks it records, as [D116](docs/decisions.md#d116) records. A query given to `prepare` with `imports` of its own is refused with `DOMQL2021`, and a loader's options that are no object with `DOMQL2013`. +**Connections and .NET** + +- [A connection](spec/connections.md), `domql.connect(deliver)`, carries this instance's operations across a boundary as messages. A host's requests cross in batches, each answered once its task ends, and each task's deliveries cross together: a watch's paced by the acknowledgment of the one before it, its change sets joined meanwhile, and an event behind nothing. A query crosses as its text once, and by its key after. `DOMQL2022` to `DOMQL2025` refuse what a connection can't carry out, `DOMQL5026` closes one whose host acknowledges nothing, and `DOMQL5027` answers one that has closed, as [D118](docs/decisions.md#d118) records. +- [The .NET half](spec/dotnet.md) is DOMQL's own host of a connection, in the NuGet package: `AddDomql`, a `DomqlConnection` for each browser runtime, owners, watches that keep a copy by change sets, subscriptions whose handlers answer their events, executions, and results mapped onto types. The operations one turn starts cross in one call. `DOMQL5028` to `DOMQL5030` are its own failures, as [D119](docs/decisions.md#d119) records. + **Breaking:** - A watch of `size` is refused unless it accepts partial observation, DOMQL3003. Watch `layoutSize` where the size as laid out is what it needs, reading `inline` and `block` for `width` and `height` along a horizontal line, or pass `acceptPartialObservation: true` to keep the box as drawn. diff --git a/build.ps1 b/build.ps1 index 8a9afc5..0f95d8c 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,6 +1,6 @@ <# .SYNOPSIS -Runs the script tests, bundles DOMQL, builds the package project, and checks its formatting. +Runs the script tests, bundles DOMQL, builds the package project and its C# tests, runs them, and checks its formatting. .PARAMETER Clean Removes every build output first, so the build starts from nothing. @@ -60,6 +60,7 @@ if ($Clean) { # The package project's bin and obj, its bundle, and the packed artifacts, which dotnet clean alone leaves behind. Write-Host 'Cleaning' Get-ChildItem $nuget -Directory -Recurse -Include 'bin', 'obj', 'wwwroot' | Remove-Item -Recurse -Force + Get-ChildItem (Join-Path $tests 'dotnet') -Directory -Include 'bin', 'obj' | Remove-Item -Recurse -Force if (Test-Path $artifacts) { Remove-Item $artifacts -Recurse -Force } @@ -159,6 +160,12 @@ try { throw 'dotnet build failed.' } + Write-Host 'Testing the C# half' + dotnet test --solution $solution --no-build + if ($LASTEXITCODE -ne 0) { + throw 'The C# tests failed.' + } + Write-Host 'Checking formatting' dotnet format $solution --verify-no-changes if ($LASTEXITCODE -ne 0) { diff --git a/docs/decisions.md b/docs/decisions.md index e72f350..67ad1c9 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -705,6 +705,7 @@ Each entry is one of three kinds: - **Decision:** The C# half (A1) is out of the current work until the owner designs it. The design's section and the status's outline stay as where that design starts. Editor tooling, which is Nexo's, waits for Nexo's design too. - **Why:** The outline names an API and an adapter, but leaves open what a host with a transport of its own takes from it, how a result maps onto records a field discriminates, and how text is checked without a parser in .NET. Those are the owner's to design. - **Declined:** Building it from the outline, which would settle those questions without the owner. +- **Replaced** by [D119](#d119), as the owner directed that DOMQL's transport is the one its hosts use. @@ -1820,3 +1821,54 @@ Each entry is one of three kinds: - **Declined:** - Partly observable `layoutSize`. Every watch of it would have to accept partial observation, which is what D111 made it to spare. - Observing styles and attachment beside the resize observer. A stylesheet's rule hides a box with no observer reporting it, and observing every mutation of the tree would cost every watch of a size. + + + +## D118 — A connection carries DOMQL across a boundary + +*December 1, 2026* + +- **Kind:** Contract, meeting [what 1.0 requires](features-status.md#what-1-0-requires) of the C# half, by the owner's direction that DOMQL's transport is the one its hosts use. +- **Decision:** + - `domql.connect(deliver)` opens a [connection](../spec/connections.md). A host sends requests in batches, and each batch is answered once the task that carried it out has ended. + - A request that settles in that task answers final: a watch with its snapshot, an execution or an evaluation with its value. One still waiting answers pending, and its result is delivered. + - The deliveries of one task cross in one call. A watch's next delivery waits for the acknowledgment of its last, what arises meanwhile joined. An event never waits. + - A query crosses as its text once, and by its key after. Owners are strings, numbers or null, and generations are the host's. + - Where earlier batches have left 4,096 deliveries unacknowledged, the next batch closes the connection with `DOMQL5026`; one task of many deliveries crosses whole. +- **Why:** + - A host that calls once for each operation pays a call for each registration of a render. One batch for a turn pays one, whatever it starts. + - Answering at the task's end carries each watch's first snapshot, and each execution that settles at once, in the batch's own answer, with no call back. + - An event behind an acknowledgment was overtaken by a click ([D69](#d69)). Change sets compose ([D65](#d65)), so a watch that waits loses nothing. + - A host's message holds no object twice, so an owner it can name again is a string or a number. + - A host that acknowledges nothing would otherwise hold every occurrence. Closing fails explicitly, as A5 asks. +- **Declined:** + - A batch answered once every request settles. A slow execution would hold every watch's first snapshot. + - Every result as a delivery. An execution that settles at once would take two calls. + - A reference for each operation, which the host disposes in a call of its own. + + + +## D119 — The .NET half is DOMQL's own host of a connection + +*December 1, 2026* + +- **Kind:** Contract, replacing [D46](#d46) by the owner's direction that DOMQL's transport is the one its hosts use. +- **Decision:** + - [The .NET half](../spec/dotnet.md) ships in the NuGet package. `AddDomql` registers one `DomqlConnection` for each scope, through its `IJSRuntime`. + - Each turn's requests cross in one call, as the turn ends on its synchronization context. + - A watch keeps its copy as JSON, applies each change set by DOMQL's rules before it acknowledges the batch, and calls its handler after, one call at a time, with the latest result. + - An event's handler completes before its batch is acknowledged, and its answer answers the event source. + - A query maps its result onto a type through the serializer: source-generated type information, the serializer's options, or the JSON itself. + - Beyond 16 KB, a batch of deliveries crosses as a stream. `RefreshAsync` refreshes every watch once a host's connection to the browser resumes. +- **Why:** + - D46 left three questions to the owner's design: + - **A host with a transport of its own.** The owner's direction answers it: DOMQL's is the transport. + - **Records a field discriminates.** The serializer's polymorphism reads them, by the field the query names first. + - **Text checked without a parser in .NET.** The browser checks it, as the first request makes it there. A host's build checks its queries ahead of time with `domql.prepare` ([D116](#d116)). + - Acknowledging once a change set is applied keeps a slow handler from holding the next one, and no handler sees a copy partly applied. + - The conformance corpus, `tests/_conformance/change-sets.json`, holds each case's previous result, its change set and the result they give. DOMQL's JavaScript applier and the .NET half's pass all 19. + - A delivery may reach .NET before its request's answer, so a watch holds its deliveries until its answer arrives. +- **Declined:** + - `TryQuery`, checking text in .NET. A second parser would have to agree with Nexo's at every release. + - Acknowledging a watch's change once its handler completes. A slow handler would hold every change after it. + - A reconnection hook in the package. It would tie the package to one way of hosting .NET; `RefreshAsync` is the host's to call. diff --git a/docs/domql-design.md b/docs/domql-design.md index e347958..c4032b8 100644 --- a/docs/domql-design.md +++ b/docs/domql-design.md @@ -125,45 +125,47 @@ An owned write's target is kept by `OwnedWrites`, one for each set of the module ## The C# half -This section outlines the C# half, which waits for its design, as [the decisions](decisions.md#d46) record. +The C# half is DOMQL from a .NET application, as [the .NET half](../spec/dotnet.md) specifies it. It is DOMQL's own host of a [connection](../spec/connections.md), and keeps a copy of each result its watches deliver, as [keeping a copy of a result](../spec/results.md#results-keeping-a-copy) sets out. [D118](decisions.md#d118) records the connection and [D119](decisions.md#d119) the half. -The C# half carries a watch to a .NET application, which starts a watch and receives its results; it is a caller that keeps its own copy of each result, as [keeping a copy of a result](../spec/results.md#results-keeping-a-copy) sets out. Its API follows the JavaScript one: +| Part | What it does | Source | +| --- | --- | --- | +| The connection, in the browser | Carries a host's requests out in batches, answering each once its task ends, and sends the deliveries of each task together, a watch's paced by the acknowledgment of the one before it | `src/connections/Connection.mjs` | +| Its module for .NET | Opens a connection whose deliveries reach .NET, each batch as text within a budget and as a stream beyond it | `nuget/scripts/domql.dotnet.js`, served beside the bundle | +| The connection, in .NET | Queues the requests of one turn and sends them as one call once the connection has opened, routes each answer and delivery to its handle, and names each query by its key once the browser has made it | `DomqlConnection`, `DomqlRequest`, `DomqlReceiver` | +| Owners and handles | Start operations for an owner, end every one of them in one request, and drop what an earlier generation delivered | `DomqlOwner`, `DomqlHandle`, `DomqlWatch`, `DomqlSubscription`, `DomqlExecution` | +| The copy | Applies change sets by DOMQL's rules, and maps the copy onto the query's type | `DomqlChangeSet`, `DomqlQuery` | + +### A turn, a task + +- **.NET's side.** A request is queued as it is made. The first of a turn posts a flush to the synchronization context it was made in, so it runs once the turn ends: every watch, subscription and execution the turn starts crosses in one call. The flush waits for the connection to open, and takes what is queued then, so the requests made while the module imports cross with the first batch. +- **The browser's side.** + - A batch's answers settle once the task that carried its requests out has ended. A message posted to the window's own channel runs after that task's microtasks. + - A watch evaluates first in a microtask, so its snapshot answers its request, and so does an execution that settles at once, as a focus or an instant scroll does. + - Deliveries are queued as they happen, and a microtask sends the task's together. +- **Answers and deliveries race.** The runtime orders no call's result before the calls the browser makes while it runs, so a delivery sent during a request's task may reach .NET before its answer. A watch holds such deliveries, and applies them in order after its answer's snapshot. -| C# | Meaning | -| --- | --- | -| `Domql.Query(text, bindings)`, `Domql.Query(text, bindings)`, and from a definition alike | Makes a query object, binding its parameters, as `domql.query` does | -| `Domql.TryQuery(…)`, `Domql.TryQuery(…)` | Attempts exactly what `Domql.Query` does, answering false with a diagnostic for a syntax or structure failure | -| `query.Definition` | The query's immutable definition, without its bindings | +### Watches and their copies -C# writes text, and names the type its result maps onto, or none: +- **A watch in the browser** watches live state, so each change event carries its change set. Its first result answers its request, or is delivered whole. +- **One delivery in flight.** Each later delivery waits for the acknowledgment of the batch holding the one before it. What arises meanwhile is joined: change sets concatenated, since they compose ([D65](decisions.md#d65)), unless the snapshot whole is shorter; a snapshot whole in place of what waits before it; a failure kept in its place. +- **.NET applies, then acknowledges.** It applies a change set to its copy, a `JsonNode`, and maps it onto the query's type before the batch is acknowledged. The watch's handler is called after, one call at a time, with the latest result. So a slow handler never holds the next change set, and never sees a copy partly applied. +- **An uncertain copy.** A change set that doesn't apply makes the copy uncertain. The watch asks for its snapshot whole, and skips change sets until it arrives. +- **Reconnecting.** A host whose connection to the browser resumes calls `RefreshAsync`, which has every watch deliver its snapshot whole in one request. -```csharp -public sealed record PanelState(double? Width, bool HasFocus); +### Events -DomqlQuery typed = Domql.Query( - """ - panel { - width = it.layoutSize?.inline, - hasFocus = it.focusWithin - } - """, - ("panel", panel)); +- **An event is delivered as it happens.** It is never held behind a watch's acknowledgment, nor joined, as [D69](decisions.md#d69) requires. +- **.NET awaits its handler** before it answers the batch. So the event's acknowledgment in the browser follows the handler, and its answer answers the event source. +- **A limit.** A batch sent while earlier ones have left 4,096 deliveries unacknowledged closes the connection; one task of many deliveries crosses whole, so a refresh of thousands of watches closes nothing. -DomqlQuery untyped = Domql.Query("panel { size = it.layoutSize }", ("panel", panel)); -``` +### Queries and their keys -A `DomqlQuery` answers a `T`, mapped by its declared contract, which matches the result's fields to the constructor parameters of `T` by name regardless of case, so a field `nearend` fills a parameter `NearEnd`, and reports an ambiguity where two fields differ only in case, since DOMQL itself tells them apart; a `DomqlQuery` answers a `DomqlSnapshot` giving structured access to its values. C# has no C# type standing for each vocabulary concept: a module contributes its declarations and implementations, and the text names what the query reads. `Domql.TryQuery` attempts exactly what `Domql.Query` does, making a query and checking the syntax and the structural rules that need no vocabulary, an empty object expression, a duplicate field and a reserved name among them, without resolving its vocabulary or evaluating anything, so a successful return means the query was made, not that it is ready to be carried out: a syntax or structure failure returns false with a diagnostic, and any other failure is thrown, never swallowed. A vocabulary failure, such as an unknown member, arrives when the query is resolved. C# cancels with a `CancellationToken` where JavaScript takes a `signal`. +- **A query's key.** Each query has a key in its connection, by its text and its declared types. Its text crosses with the first request that names it in a batch. Every request after the browser made it names it by its key alone. A query the browser refused crosses with its text again. +- **Many panes, one text.** A page of fifty panes, each watching one query, sends its text once. -Its adapter owns the synchronization: +### Crossings -- **Live state by default.** It watches live state, and takes its baseline from the first ready event's `args.snapshot`. -- **One update at a time.** It queues the immutable changes after the baseline and delivers them in order, sending the next only once the receiving side acknowledges that the one before was applied completely. Acknowledgment follows application alone, never the application's handlers, and a failed delivery stops every further update of that watch. -- **One ordered queue.** Every handle of a connection, its watches' changes and its subscriptions' occurrences alike, sends through one queue, bounded, never coalescing an occurrence, and failing explicitly where it overflows, so the receiving side hears them in the [order](../spec/api.md#api-order-across-handles) the JavaScript side's handlers did. -- **No partial state.** No consumer observes a change set partly applied: access to the C# result during an update follows an explicit rule, a result whose application failed becomes unusable, and the application's handlers are notified once the update is applied. -- **Obsolete watches rejected.** The receiving side rejects a delivery from an obsolete watch before applying it, through a token of its own for the watch it follows. -- **Recovery from uncertainty.** Where applying an update throws, a call rejects, or a call times out leaving its outcome uncertain, the adapter first invalidates the old watch, so its late applications and acknowledgments change neither the replacement result nor the new queue, then disposes it and rebuilds the result from a fresh watch's baseline. Where the connection is lost with the components holding its results, their replacements start watches of their own; where it resumes with them, an update unanswered across the interruption is uncertain and recovered as a timeout is. -- **Handler failures reported, not retried.** An exception from an application handler is reported without restarting synchronization, since the state was already accepted. -- **One way of applying.** Its application of change sets passes a conformance corpus the JavaScript patcher passes too: each case a previous result, a change set and the result they give, reviewed independently of either applier, moves and escaped paths among them. +The calls each operation takes, between .NET and the browser, are [the .NET half's crossings](../spec/dotnet.md#dotnet-crossings). A first operation imports one module, the one the package serves beside the bundle. ## Decisions not taken diff --git a/docs/features-status.md b/docs/features-status.md index 81ee0e9..11fff5a 100644 --- a/docs/features-status.md +++ b/docs/features-status.md @@ -2,7 +2,7 @@ ## Current state -**DOMQL is in its preview, `1.0.0-preview.2`. Its vocabulary, queries, watches, events, executions and behaviors are implemented on Nexo's language `1.0.0-preview.3`, definition version 38. The specification describes DOMQL's `1.0.0-preview.2`, which the implementation follows: the DOM declared as DOMQL's own types, read through the `Domql` module every query imports. Every [planned capability](#planned-capabilities) is implemented or declined but the C# half's, A1 and A5's queue, which wait for its design.** +**DOMQL is in its preview, `1.0.0-preview.2`. Its vocabulary, queries, watches, events, executions and behaviors are implemented on Nexo's language `1.0.0-preview.3`, definition version 38. The specification describes DOMQL's `1.0.0-preview.2`, which the implementation follows: the DOM declared as DOMQL's own types, read through the `Domql` module every query imports. Every [planned capability](#planned-capabilities) is implemented or declined, the C# half's among them.** | Version | Implementation | Specification | | --- | --- | --- | @@ -12,7 +12,7 @@ - **The language DOMQL runs on.** DOMQL follows Nexo's language `1.0.0-preview.3`, which Nexo's release `1.0.0-preview.4` carries, the version of Nexo's npm package DOMQL installs, as [D108](decisions.md#d108), [D109](decisions.md#d109) and [D114](decisions.md#d114) record, and its documents link to [Nexo's documents at that tag](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md), moving with the pin. The language was called Lexica before the [migration](#migration-to-nexo). - **Packages.** The bundle and type declarations are built, with Nexo bundled inside `domql.js`. The npm package holds DOMQL's sources, which import Nexo's package, and the NuGet package the bundle. Both carry the runtime version, and `release.yml` publishes each from a release's tag: the NuGet package from `1.0.0-preview.1`, and the npm package from `1.0.0-preview.2`. -- **The C# half** waits for its design, as [D46](decisions.md#d46) records. +- **The C# half** is implemented: a [connection](../spec/connections.md) carries DOMQL's operations across a boundary, and [the .NET half](../spec/dotnet.md) is DOMQL's own host of one, as [D118](decisions.md#d118) and [D119](decisions.md#d119) record. The [specification](../spec/README.md) defines the contract, and the [design](domql-design.md) explains the architecture. The [version history](../VERSION-HISTORY.md) records what each version changed, and the [changelog](../CHANGELOG.md) each release of the packages. This file tracks DOMQL's implementation and its remaining work. "Implemented" means built and tested in the gate for the current implementation version; it does not imply that later specification changes are implemented. @@ -22,10 +22,10 @@ The [specification](../spec/README.md) defines the contract, and the [design](do | Work | State | | --- | --- | -| [The C# half](#the-c-half) | Waits for its design | -| [Planned capabilities](#planned-capabilities) | The C# half's alone remain, waiting for its design | +| [The C# half](#the-c-half) | Implemented | +| [Planned capabilities](#planned-capabilities) | Each implemented or declined | | [Release](#release) | `1.0.0-preview.3` is released; `1.0.0-preview.4`, on the specification `1.0.0-preview.2`, is unreleased | -| [What 1.0 requires](#what-1-0-requires) | Six requirements, two met | +| [What 1.0 requires](#what-1-0-requires) | Six requirements, three met | - **A specification version collects the changes between two releases.** A change to DOMQL's contract joins the [version history](../VERSION-HISTORY.md)'s newest entry while it reads *Unreleased*, and opens the next version's entry once it is released, as [D79](decisions.md#d79) records. - **A breaking change says how to migrate.** Since the beta, a version's entry in the [version history](../VERSION-HISTORY.md) says how to migrate beside each thing it breaks. @@ -127,13 +127,13 @@ Each feature, the contract that states it, its state in the implementation, and | Change sets that compose by concatenation, which a host coalesces, or replaces with the latest snapshot | [Composing](../spec/results.md#results-composing), [coalescing](../spec/results.md#results-coalescing) | Implemented, as [D65](decisions.md#d65) records | [`alpha.310`](../VERSION-HISTORY.md#v1-0-0-alpha-310) | | A refresh that takes new samples of the maintained members its watch reads, `refreshAsync({ resample: true })`, and a refresh's `signal` | [Resampling](../spec/watches.md#watching-resampling) | Implemented, as [D66](decisions.md#d66) records | [`alpha.311`](../VERSION-HISTORY.md#v1-0-0-alpha-311) | | Modules loaded on request: a loader by a module's name, `domql.registerModuleLoader`, and `domql.loadModulesAsync`, which loads what a query imports | [Loading a module on request](../spec/vocabulary.md#extension-modules-loading) | Implemented, as [D68](decisions.md#d68) records | [`alpha.313`](../VERSION-HISTORY.md#v1-0-0-alpha-313) | -| What DOMQL delivers reaches its handlers in the order it happens, across handles, subscriptions and owners, and calls to several handles take effect in the order they are made | [Order across handles](../spec/api.md#api-order-across-handles) | Implemented, as [D69](decisions.md#d69) records; the C# half's queue waits with it | [`alpha.314`](../VERSION-HISTORY.md#v1-0-0-alpha-314) | +| What DOMQL delivers reaches its handlers in the order it happens, across handles, subscriptions and owners, and calls to several handles take effect in the order they are made | [Order across handles](../spec/api.md#api-order-across-handles) | Implemented, as [D69](decisions.md#d69) records, and carried across a boundary by a connection, as [D118](decisions.md#d118) records | [`alpha.314`](../VERSION-HISTORY.md#v1-0-0-alpha-314) | | Reactions, once executions a subscription carries out inside each event's delivery, bound to the event's value, whose results reach the handler after it | [Reactions](../spec/events.md#events-reactions) | Implemented, as [D71](decisions.md#d71) records | [`alpha.316`](../VERSION-HISTORY.md#v1-0-0-alpha-316) | | The element a watch's list item came from, `watch.sourceOf(...path)`, for a handler in the browser | [`sourceOf`](../spec/watches.md#watching-source-elements) | Implemented, as [D72](decisions.md#d72) records | [`alpha.317`](../VERSION-HISTORY.md#v1-0-0-alpha-317) | | Delivery options: a delayed schedule a refresh flushes, reporting on parts, and a subscription's throttle | [The delayed schedule](../spec/watches.md#watching-delayed), [reporting on parts](../spec/results.md#results-reporting-on-parts), [throttling](../spec/events.md#events-throttling) | Implemented, as [D73](decisions.md#d73) records | [`alpha.318`](../VERSION-HISTORY.md#v1-0-0-alpha-318) | | The beta, its promise and the changelog | [Version history](../VERSION-HISTORY.md#v1-0-0-beta-1), [changelog](../CHANGELOG.md) | Implemented, as [D75](decisions.md#d75) records | [`beta.1`](../VERSION-HISTORY.md#v1-0-0-beta-1) | | The preview, the beta's promise under FormaUI Versioning's name for it | [Stages](https://github.com/FormaUI/Versioning/blob/v1.0.0-preview.1/docs/versions.md#stages) | Implemented, as [D106](decisions.md#d106) records | [`preview.1`](../VERSION-HISTORY.md#v1-0-0-preview-1) | -| The C# half | [Design](domql-design.md#the-c-half) | Waits for its design | — | +| The C# half: a connection, and the .NET half over it, mapping results onto types and keeping a copy of each watch's | [Connections](../spec/connections.md), [the .NET half](../spec/dotnet.md) | Implemented, as [D118](decisions.md#d118) and [D119](decisions.md#d119) record | [`preview.2`](../VERSION-HISTORY.md#v1-0-0-preview-2) | @@ -156,18 +156,14 @@ Contracts: [Queries](../spec/queries.md), [types](../spec/vocabulary.md#vocabula ## The C# half -**Waits for its design.** The C# half is out of the current work until it is designed, as [D46](decisions.md#d46) records; the outline below is where its design starts. +**Implemented.** [D118](decisions.md#d118) and [D119](decisions.md#d119) record it, in place of the outline [D46](decisions.md#d46) waited with. -The C# half follows the migration, so its API is built on the final query text, imports, definition version and result representations, never reworked after them. +- **A connection,** `domql.connect`, carries a host's requests in batches, answered as their task ends, and sends each task's deliveries together, a watch's paced by its acknowledgment and an event behind nothing. +- **The .NET half:** `DomqlConnection`, one for each browser runtime; owners that end every operation they started in one request; watches keeping a copy by change sets; subscriptions whose handlers answer their events; continuous and once executions; and failures carried with their code, kind and location. +- **One way of applying:** the conformance corpus, `tests/_conformance/change-sets.json`, which DOMQL's JavaScript applier and the .NET half's both pass. +- **Its tests** run in the gate: the connection's in Node, and the .NET half's through a browser that answers as the connection does. -- **Its API,** as [the design](domql-design.md#the-c-half) sets out: `Domql.Query` and `Domql.Query` from text or a definition, binding its parameters; `Domql.TryQuery`, answering false with a diagnostic for a syntax or structure failure; and `query.Definition`. A `DomqlQuery` maps a result onto `T` by its declared contract, and a `DomqlQuery` answers a `DomqlSnapshot`. -- **Results:** lists, dictionaries and pairs mapped onto `T` and read through a `DomqlSnapshot` by their exported forms. -- **Imports:** `Domql`, which DOMQL supplies to every query, applied as the JavaScript half applies it. -- **Its adapter's synchronization:** live state with its baseline from the first ready event, one update at a time, no partial state, obsolete watches rejected, recovery from uncertainty, and handler failures reported, not retried. -- **One way of applying:** its application of change sets passes the conformance corpus the JavaScript patcher passes too. -- **Diagnostics:** an error of the language it reports keeps its code. - -**Completion:** the C# half passes the gate, its conformance corpus included. +**Remaining:** a test that drives the .NET half through a real browser and a .NET host, as the full gate drives the packages. Contracts: [The C# half](domql-design.md#the-c-half), [keeping a copy of a result](../spec/results.md#results-keeping-a-copy). @@ -181,7 +177,7 @@ The language's part is Nexo's already, adopted with the [migration](#migration-t **The order of the work:** -1. **The C# half** (A1), with its queue of ordered delivery (A5), once it is designed, as [D46](decisions.md#d46) records. +1. **The C# half** (A1), with its queue of ordered delivery (A5), implemented, as [D118](decisions.md#d118) and [D119](decisions.md#d119) record. @@ -245,7 +241,7 @@ None remains: C1 to C14 are implemented, as [the features](#the-host) show, each ### API and host -Only the C# half's remain, A1 and A5's queue, both waiting for its design ([D46](decisions.md#d46)). A2 to A10 are implemented, as [the features](#the-host) show, or declined where their decisions say why. What their decisions settled: +A1 and A5's queue are implemented, as [D118](decisions.md#d118) and [D119](decisions.md#d119) record. A2 to A10 are implemented, as [the features](#the-host) show, or declined where their decisions say why. What their decisions settled: - Change sets compose by concatenation, so a host coalesces them itself ([D65](decisions.md#d65)). - A refresh takes new samples where it is asked to, and delivering an equal result needs nothing new ([D66](decisions.md#d66)). @@ -259,8 +255,8 @@ Only the C# half's remain, A1 and A5's queue, both waiting for its design ([D46] | | Addition | | --- | --- | -| A1 | **The C# half,** waiting for its design, as [outlined](#the-c-half): typed queries mapped onto records, watches, once and continuous executions and subscriptions, with failures reported, never discarded. Its acknowledgement follows the application of an update, never the application's handlers | -| A5 | **The C# half's queue of ordered delivery:** bounded, never coalesced, failing explicitly on overflow, carrying across the boundary the order the JavaScript side already keeps. It waits with A1 | +| A1 | **The C# half,** implemented, as [the .NET half](../spec/dotnet.md) sets out: typed queries mapped onto records, watches, once and continuous executions and subscriptions, with failures reported, never discarded. Its acknowledgement follows the application of an update, never the application's handlers | +| A5 | **The C# half's queue of ordered delivery:** bounded, never coalesced, failing explicitly on overflow, carrying across the boundary the order the JavaScript side already keeps. Implemented by the [connection](../spec/connections.md#connections-pacing) | @@ -308,7 +304,7 @@ Nexo's packages are published from its `1.0.0-preview.1`, as its [release](https - The documents and the module API were audited, and the behavior of a cast inside an optional enclosed access was settled. - The specification and the runtime both took `1.0.0-beta.1`. The contract is that of `1.0.0-alpha.318`, unchanged. -- No breaking redesign is planned. The C# half (A1) and A5's queue wait for their design, as [D46](decisions.md#d46) records. The [deferred work](#deferred) and the design's [decisions not taken](domql-design.md#decisions-not-taken) document the other limitations. +- No breaking redesign is planned. The [deferred work](#deferred) and the design's [decisions not taken](domql-design.md#decisions-not-taken) document the other limitations. - A break from here on says how to migrate, beside it, in the [version history](../VERSION-HISTORY.md), and a change a caller can notice is listed in the [changelog](../CHANGELOG.md). @@ -321,7 +317,7 @@ Nexo's packages are published from its `1.0.0-preview.1`, as its [release](https | --- | --- | --- | | **Nexo's 1.0.** DOMQL runs on Nexo's 1.0, from its published packages. | DOMQL's contract holds the language its queries are written in, so it promises no more than Nexo does. | Nexo is in its preview, at `1.0.0-preview.4`, as [what Nexo's 1.0 requires](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/features-status.md#what-1-0-requires) sets out. | | **Contracts settled.** No decision is open, and each [deferred](#deferred) item and [decision not taken](domql-design.md#decisions-not-taken) is shown to land without a break. | What may still change after 1.0 must be able to change compatibly. | Holds: no decision is open, and each [deferred](#deferred) item and [decision not taken](domql-design.md#decisions-not-taken) lands as an addition or within the implementation. A watch's promise to evaluate its whole query each time was the one that would have made evaluating less a break; [what an evaluation gives](../spec/watches.md#watching-what-an-evaluation-gives) now leaves it to DOMQL. | -| **The C# half decided.** It is designed, or decided to follow 1.0 as an addition. | It waits for the owner's design, as [D46](decisions.md#d46) records, and a .NET application may need it to drive DOMQL. | Waits for its design. | +| **The C# half decided.** It is designed, or decided to follow 1.0 as an addition. | A .NET application may need it to drive DOMQL. | Holds: the connection and the .NET half are implemented, as [D118](decisions.md#d118) and [D119](decisions.md#d119) record. | | **Published.** DOMQL's packages are on npm and NuGet, tested as consumers install them. | A caller pins a release it can install. | Holds: the NuGet package is published from `1.0.0-preview.1` and the npm package from `1.0.0-preview.2`, each verified as consumers install it before its release. | | **Used for real.** Forma's own scripts run as DOMQL queries, watches, subscriptions and executions on a published release. | The [planned capabilities](#planned-capabilities) came from reading those scripts, and only running them settles the contract. | Planned. | | **A release candidate that breaks nothing.** `1.0.0-rc.1` is released once the rest hold, and Forma takes it with no change but its version. `1.0.0` is its contract, unchanged. | It is the last check that nothing still needs to break. | Waits for the rest. | diff --git a/nuget/DomqlChangeSet.cs b/nuget/DomqlChangeSet.cs new file mode 100644 index 0000000..6f8dba0 --- /dev/null +++ b/nuget/DomqlChangeSet.cs @@ -0,0 +1,184 @@ +namespace Domql; + +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Nodes; + +/// +/// Applies a change set to a copy of a result, by DOMQL's rules: a JSON Patch document of replace, add, remove and move, each operation applied after the one before it, its paths +/// JSON Pointers into the result as that operation finds it. One that names no place in the copy fails with DOMQL5029. +/// +internal static class DomqlChangeSet +{ + /// The copy the change set gives, changed in place where it can be, and replaced where an operation replaces the root. + public static JsonNode? Apply(JsonNode? copy, JsonElement changes) + { + if (changes.ValueKind != JsonValueKind.Array) + { + throw Unapplied("it is no list of operations"); + } + + foreach (var operation in changes.EnumerateArray()) + { + var kind = operation.TryGetProperty("op", out var op) && op.ValueKind == JsonValueKind.String ? op.GetString() : null; + + copy = kind switch + { + "replace" => Put(copy, PathOf(operation, "path"), ValueOf(operation), isReplacing: true), + "add" => Put(copy, PathOf(operation, "path"), ValueOf(operation), isReplacing: false), + "remove" => Take(copy, PathOf(operation, "path"), out _), + "move" => Move(copy, PathOf(operation, "from"), PathOf(operation, "path")), + _ => throw Unapplied($"its operation {kind ?? "with no op"} is none of replace, add, remove and move"), + }; + } + + return copy; + } + + private static JsonNode? Move(JsonNode? copy, string[] from, string[] path) + { + copy = Take(copy, from, out var moved); + + return Put(copy, path, moved, isReplacing: false); + } + + /// Puts a value at a path: replacing what stands there, or adding it, a list's item inserted before the index or appended at -. + private static JsonNode? Put(JsonNode? copy, string[] path, JsonNode? value, bool isReplacing) + { + if (path.Length == 0) + { + return value; + } + + var parent = Navigate(copy, path.AsSpan(0, path.Length - 1)); + var token = path[^1]; + + switch (parent) + { + case JsonObject members: + if (isReplacing && !members.ContainsKey(token)) + { + throw Unapplied($"it replaces '{token}', which the object doesn't hold"); + } + + members[token] = value; + + break; + case JsonArray items: + if (!isReplacing && token == "-") + { + items.Add(value); + } + else + { + var index = IndexOf(token, isReplacing ? items.Count - 1 : items.Count); + + if (isReplacing) + { + items[index] = value; + } + else + { + items.Insert(index, value); + } + } + + break; + default: + throw Unapplied($"it puts a value inside {Describe(parent)}"); + } + + return copy; + } + + /// Takes the value at a path out of the copy. + private static JsonNode? Take(JsonNode? copy, string[] path, out JsonNode? taken) + { + if (path.Length == 0) + { + throw Unapplied("it takes the whole result out, which no change set does"); + } + + var parent = Navigate(copy, path.AsSpan(0, path.Length - 1)); + var token = path[^1]; + + switch (parent) + { + case JsonObject members when members.TryGetPropertyValue(token, out taken): + members.Remove(token); + + return copy; + case JsonArray items: + var index = IndexOf(token, items.Count - 1); + + taken = items[index]; + items.RemoveAt(index); + + return copy; + default: + throw Unapplied($"it takes '{token}' out of {Describe(parent)}, which doesn't hold it"); + } + } + + private static JsonNode? Navigate(JsonNode? node, ReadOnlySpan tokens) + { + foreach (var token in tokens) + { + node = node switch + { + JsonObject members when members.TryGetPropertyValue(token, out var member) => member, + JsonArray items => items[IndexOf(token, items.Count - 1)], + _ => throw Unapplied($"its path reaches '{token}' in {Describe(node)}, which doesn't hold it"), + }; + } + + return node; + } + + /// A list index a token names: a whole number of no leading zero, at most the largest given. + private static int IndexOf(string token, int largest) + { + if (token.Length == 0 || token.Length > 1 && token[0] == '0' || !token.All(char.IsAsciiDigit) || !int.TryParse(token, NumberStyles.None, CultureInfo.InvariantCulture, out var index) || index > largest) + { + throw Unapplied($"its index '{token}' names no item of a list of {largest + 1}"); + } + + return index; + } + + /// A JSON Pointer's reference tokens, unescaped: ~1 as /, then ~0 as ~. + private static string[] PathOf(JsonElement operation, string name) + { + if (!operation.TryGetProperty(name, out var path) || path.ValueKind != JsonValueKind.String) + { + throw Unapplied($"an operation gives no {name}"); + } + + var pointer = path.GetString()!; + + if (pointer.Length == 0) + { + return []; + } + + if (pointer[0] != '/') + { + throw Unapplied($"its path '{pointer}' is no JSON Pointer"); + } + + return [.. pointer[1..].Split('/').Select(token => token.Replace("~1", "/", StringComparison.Ordinal).Replace("~0", "~", StringComparison.Ordinal))]; + } + + private static JsonNode? ValueOf(JsonElement operation) => + operation.TryGetProperty("value", out var value) ? JsonNode.Parse(value.GetRawText()) : throw Unapplied("an operation that puts a value gives none"); + + private static string Describe(JsonNode? node) => node switch + { + null => "null", + JsonObject => "an object", + JsonArray => "a list", + _ => "a value", + }; + + private static DomqlException Unapplied(string reason) => new("DOMQL5029", "evaluation", $"A change set doesn't apply to the watch's copy: {reason}"); +} diff --git a/nuget/DomqlConnection.cs b/nuget/DomqlConnection.cs new file mode 100644 index 0000000..cb7cfa3 --- /dev/null +++ b/nuget/DomqlConnection.cs @@ -0,0 +1,462 @@ +namespace Domql; + +using System.Text; +using System.Text.Json; + +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.JSInterop; + +/// +/// DOMQL in one browser runtime, as a .NET application reaches it. Every request one turn of the application makes crosses as one call, its answers return in that call's answer, and the deliveries of one +/// browser task cross back as one call. A connection belongs to one JavaScript runtime and is used from one synchronization context, the one its runtime's callbacks run on. +/// +public sealed class DomqlConnection : IAsyncDisposable +{ + private readonly IJSRuntime _jsRuntime; + private readonly DomqlConnectionOptions _options; + private readonly ILogger _logger; + private readonly Lock _gate = new(); + private readonly Dictionary _handles = []; + private readonly Dictionary _queryKeys = [with(StringComparer.Ordinal)]; + private readonly HashSet _madeQueries = []; + private readonly HashSet _ownerNames = [with(StringComparer.Ordinal)]; + private List _pending = []; + private bool _isFlushScheduled; + private Task? _opened; + private DotNetObjectReference? _receiver; + private long _lastHandle; + private long _lastQuery; + private long _lastOwner; + private bool _isDisposed; + private bool _isRefreshingUnread; + + /// A connection through the JavaScript runtime given, which opens as its first request crosses. + /// The runtime of the browser it reaches. + /// Where it finds DOMQL, and how much it reads of a delivery. + /// What it reports a handler's failure to, which reaches no other caller. + public DomqlConnection(IJSRuntime jsRuntime, DomqlConnectionOptions? options = null, ILogger? logger = null) + { + ArgumentNullException.ThrowIfNull(jsRuntime); + + _jsRuntime = jsRuntime; + _options = options ?? new DomqlConnectionOptions(); + _logger = logger ?? NullLogger.Instance; + } + + /// + /// An owner: who carries out the operations it starts, which their implementations in the browser receive, and whose disposal ends every one of them in one request. + /// + /// Its name in the browser, unique among the connection's owners until it is disposed; one of its own where none is given. A name in use is refused. + public DomqlOwner CreateOwner(string? name = null) + { + lock (_gate) + { + ObjectDisposedException.ThrowIf(_isDisposed, this); + + if (name is not null && !_ownerNames.Add(name)) + { + throw new ArgumentException($"An owner named '{name}' is in use, and a release names one owner alone; give each owner a name of its own", nameof(name)); + } + + while (name is null) + { + var generated = $"owner-{++_lastOwner}"; + + if (_ownerNames.Add(generated)) + { + name = generated; + } + } + + return new DomqlOwner(this, name); + } + } + + /// + /// Evaluates every watch the connection runs and delivers each one's snapshot whole, changed or not, as a host does once its connection to the browser has resumed and a delivery may have been lost on the way. + /// + public Task RefreshAsync() => SendAsync(new DomqlRequest("refresh")); + + /// Ends every operation the connection started, in the browser and here, and releases what it holds of the runtime. + public async ValueTask DisposeAsync() + { + IDomqlRoute[] handles; + + lock (_gate) + { + if (_isDisposed) + { + return; + } + + _isDisposed = true; + handles = [.. _handles.Values]; + _handles.Clear(); + } + + foreach (var handle in handles) + { + handle.End(); + } + + // An opening under way is awaited, so what it opens is closed; a request after disposal opens nothing. + if (_opened is { } opened) + { + try + { + var connection = await opened.ConfigureAwait(false); + + await connection.InvokeVoidAsync("close").ConfigureAwait(false); + await connection.DisposeAsync().ConfigureAwait(false); + } + catch (Exception error) when (error is not OutOfMemoryException) + { + // A runtime that is gone, or an opening that failed, holds nothing of the connection's. + } + } + + _receiver?.Dispose(); + } + + /// Frees an owner's name once its release is queued, which crosses before any request of an owner that takes it again. + internal void ReleaseOwnerName(string name) + { + lock (_gate) + { + _ownerNames.Remove(name); + } + } + + /// The next handle's id, unique within the connection. + internal long CreateHandleId() => Interlocked.Increment(ref _lastHandle); + + /// Registers a handle, whose answers and deliveries reach it until it ends. + internal void Register(IDomqlRoute handle) + { + lock (_gate) + { + ObjectDisposedException.ThrowIf(_isDisposed, this); + _handles.Add(handle.Id, handle); + } + } + + /// Stops routing to a handle that has ended. + internal void Unregister(IDomqlRoute handle) + { + lock (_gate) + { + _handles.Remove(handle.Id); + } + } + + /// Every handle of an owner, which its release ends. + internal IDomqlRoute[] HandlesOf(DomqlOwner owner) + { + lock (_gate) + { + return [.. _handles.Values.Where(handle => handle.Owner == owner)]; + } + } + + /// The key a query's text and declared types go by in this connection, which every request after the first that crosses with its text names it by. + internal long QueryKeyOf(DomqlQuery query) + { + lock (_gate) + { + if (!_queryKeys.TryGetValue(query.Identity, out var key)) + { + key = ++_lastQuery; + _queryKeys.Add(query.Identity, key); + } + + return key; + } + } + + /// + /// Queues a request, which crosses with every other the same turn makes, once the turn ends, and answers a task of its answer. A request the connection can't carry fails its task with the reason. + /// + internal Task SendAsync(DomqlRequest request) + { + lock (_gate) + { + if (_isDisposed) + { + return Task.FromException(new ObjectDisposedException(nameof(DomqlConnection))); + } + + _pending.Add(request); + + if (!_isFlushScheduled) + { + _isFlushScheduled = true; + ScheduleFlush(); + } + } + + return request.Answer; + } + + /// + /// The deliveries of one browser task, applied in the order they happened, each answered: a subscription's event with its handler's answer, anything else with null. A delivery to a handle that has ended is + /// answered with null and goes no further. + /// + internal async Task ReceiveAsync(DomqlTransfer transfer) + { + JsonDocument? read = null; + JsonElement deliveries; + + try + { + if (transfer.Deliveries is { } given) + { + deliveries = given; + } + else + { + read = JsonDocument.Parse(await ReadAsync(transfer.Stream).ConfigureAwait(true)); + deliveries = read.RootElement; + } + + if (deliveries.ValueKind != JsonValueKind.Array) + { + throw new DomqlException("DOMQL5030", "evaluation", "A batch of deliveries crossed as something other than a list"); + } + } + catch (Exception error) when (error is not OutOfMemoryException) + { + read?.Dispose(); + + // A batch that can't be read leaves every copy uncertain, so each watch delivers its snapshot whole; the batch is acknowledged, answering nothing. One refresh at a time: a batch that can't be + // read while one is under way, as a snapshot past the size the connection reads is, refreshes nothing more until a batch is read. + DomqlLog.BatchUnread(_logger, error); + + if (!_isRefreshingUnread) + { + _isRefreshingUnread = true; + _ = RefreshQuietlyAsync(); + } + + return []; + } + + _isRefreshingUnread = false; + + using var reading = read; + + var answers = new object?[deliveries.GetArrayLength()]; + var index = 0; + + foreach (var delivery in deliveries.EnumerateArray()) + { + IDomqlRoute? handle = null; + + if (delivery.TryGetProperty("handle", out var id) && id.TryGetInt64(out var handleId)) + { + lock (_gate) + { + _handles.TryGetValue(handleId, out handle); + } + } + + if (handle is not null) + { + try + { + answers[index] = await handle.DeliverAsync(delivery.Clone()).ConfigureAwait(true); + } + catch (Exception error) when (error is not OutOfMemoryException) + { + // A handler's failure stays its own: the batch is acknowledged, and the deliveries after it applied. + DomqlLog.HandlerFailed(_logger, handle.Id, error); + } + } + + index++; + } + + return answers; + } + + /// Refreshes every watch, as a batch that can't be read asks, where the connection can still carry the request. + internal async Task RefreshQuietlyAsync() + { + try + { + await RefreshAsync().ConfigureAwait(true); + } + catch (Exception error) when (error is DomqlException or ObjectDisposedException) + { + // A connection that can't carry it has no watch left to refresh. + } + } + + /// Reports a handler's failure, which reaches no caller of its own. + internal void ReportHandlerFailure(long handle, Exception error) => DomqlLog.HandlerFailed(_logger, handle, error); + + /// Sends the requests queued once the turn that queued them ends: posted to the synchronization context they were made in, or, without one, run once the caller yields. + private void ScheduleFlush() + { + var context = SynchronizationContext.Current; + + if (context is not null) + { + context.Post(static state => _ = ((DomqlConnection)state!).FlushAsync(), this); + } + else + { + _ = Task.Run(FlushAsync); + } + } + + /// + /// Sends the requests queued, in order, as one call, once the connection has opened, so those made while it opened cross with them; and hands each its answer. A call that fails fails every request it + /// carried, and an opening that fails every request queued. + /// + private async Task FlushAsync() + { + List batch; + IJSObjectReference connection; + + try + { + ObjectDisposedException.ThrowIf(_isDisposed, this); + connection = await OpenAsync().ConfigureAwait(true); + ObjectDisposedException.ThrowIf(_isDisposed, this); + } + catch (Exception error) when (error is not OutOfMemoryException) + { + lock (_gate) + { + batch = _pending; + _pending = []; + _isFlushScheduled = false; + } + + Fail(batch, error); + + return; + } + + lock (_gate) + { + batch = _pending; + _pending = []; + _isFlushScheduled = false; + } + + if (batch.Count == 0) + { + return; + } + + try + { + var crossing = new HashSet(); + var requests = new object[batch.Count]; + + lock (_gate) + { + // A query's text crosses with the first request of the batch that names a query the browser hasn't made, and every later one names it by its key. + for (var index = 0; index < batch.Count; index++) + { + requests[index] = batch[index].Write(key => _madeQueries.Contains(key) || !crossing.Add(key)); + } + } + + var answers = await connection.InvokeAsync("requestAsync", [requests]).ConfigureAwait(true); + + lock (_gate) + { + // A query the browser made, answered with no error by the request its text crossed with, is named by its key alone from here on; one it refused crosses with its text again. + for (var index = 0; index < batch.Count && index < answers.Length; index++) + { + if (batch[index].CarriedQuery is { } key && !answers[index].TryGetProperty("error", out _)) + { + _madeQueries.Add(key); + } + } + } + + for (var index = 0; index < batch.Count; index++) + { + batch[index].Complete(index < answers.Length ? answers[index] : default); + } + } + catch (Exception error) when (error is not OutOfMemoryException) + { + Fail(batch, error); + } + } + + /// Fails every request of a batch with what kept it from crossing. + private static void Fail(List batch, Exception error) + { + var failure = error as DomqlException ?? DomqlException.Unsent(error); + + foreach (var request in batch) + { + request.Fail(failure); + } + } + + /// Imports the module a connection opens, and opens it, once; a failed opening is tried again by the next request. + private Task OpenAsync() + { + lock (_gate) + { + ObjectDisposedException.ThrowIf(_isDisposed, this); + + if (_opened is null || _opened.IsFaulted || _opened.IsCanceled) + { + _opened = OpenOnceAsync(); + } + + return _opened; + } + } + + private async Task OpenOnceAsync() + { + _receiver ??= DotNetObjectReference.Create(new DomqlReceiver(this)); + + var module = await _jsRuntime.InvokeAsync("import", _options.ModulePath).ConfigureAwait(true); + + // The module's reference is released once it has opened the connection, which lives on in the browser on its own. + await using (module.ConfigureAwait(true)) + { + return await module.InvokeAsync("connect", _receiver, new Dictionary { ["textBudget"] = _options.TextBudget }).ConfigureAwait(true); + } + } + + /// The text of a delivery that crossed as a stream, read up to the size the options accept. + private async Task ReadAsync(IJSStreamReference? stream) + { + if (stream is null) + { + throw new DomqlException("DOMQL5030", "evaluation", "A delivery crossed with neither its text nor a stream of it"); + } + + try + { + if (stream.Length > _options.MaximumDeliverySize) + { + throw new DomqlException("DOMQL5030", "evaluation", $"A delivery of {stream.Length} bytes is larger than the {_options.MaximumDeliverySize} the connection reads"); + } + + var content = await stream.OpenReadStreamAsync(_options.MaximumDeliverySize).ConfigureAwait(true); + + await using (content.ConfigureAwait(true)) + { + using var reader = new StreamReader(content, Encoding.UTF8); + + return await reader.ReadToEndAsync().ConfigureAwait(true); + } + } + finally + { + await stream.DisposeAsync().ConfigureAwait(true); + } + } +} diff --git a/nuget/DomqlException.cs b/nuget/DomqlException.cs new file mode 100644 index 0000000..c00a012 --- /dev/null +++ b/nuget/DomqlException.cs @@ -0,0 +1,101 @@ +namespace Domql; + +using System.Text.Json; + +/// +/// A failure DOMQL or Nexo reported in the browser, as it crossed: its code, its kind and where it stands; or a failure of the connection's own, a code of DOMQL's naming it. +/// +/// The code of the condition that failed. +/// The stage it failed in. +/// What failed. +/// Where it stands; nowhere where none is given. +/// What caused it, where something did. +public sealed class DomqlException(string code, string kind, string message, DomqlLocation? location = null, Exception? innerException = null) : Exception(message, innerException) +{ + /// A failure with no code of its own. + public DomqlException() + : this("DOMQL5030", "evaluation", "The connection failed") + { + } + + /// A failure with no code of its own, of the message given. + public DomqlException(string message) + : this("DOMQL5030", "evaluation", message) + { + } + + /// A failure with no code of its own, of the message and the cause given. + public DomqlException(string message, Exception innerException) + : this("DOMQL5030", "evaluation", message, null, innerException) + { + } + + /// The code of the condition that failed: NEXO and four digits for Nexo's, DOMQL and four digits for DOMQL's, as their errors catalog them. + public string Code { get; } = code; + + /// The stage it failed in: syntax, structure, validation, module or evaluation. + public string Kind { get; } = kind; + + /// Where it stands: in the query's text, in its definition, or in a module's declarations. + public DomqlLocation Location { get; } = location ?? DomqlLocation.None; + + /// A failure as the browser wrote it: { code, kind, message, location }, or a message alone for one that DOMQL didn't make. + internal static DomqlException FromJson(JsonElement error) + { + var code = error.TryGetProperty("code", out var codeValue) && codeValue.ValueKind == JsonValueKind.String ? codeValue.GetString()! : "DOMQL5030"; + var kind = error.TryGetProperty("kind", out var kindValue) && kindValue.ValueKind == JsonValueKind.String ? kindValue.GetString()! : "evaluation"; + var message = error.TryGetProperty("message", out var messageValue) && messageValue.ValueKind == JsonValueKind.String ? messageValue.GetString()! : "The browser reported a failure without a message"; + var location = error.TryGetProperty("location", out var locationValue) ? DomqlLocation.FromJson(locationValue) : DomqlLocation.None; + + return new DomqlException(code, kind, message, location); + } + + /// A batch that could not cross, or whose answer could not be read, as the runtime's failure gives it. + internal static DomqlException Unsent(Exception error) => + new("DOMQL5030", "evaluation", $"The connection failed to carry its requests: {error.Message}", null, error); + + /// A result the query's type can't hold. + internal static DomqlException Unmapped(Type type, Exception error) => + new("DOMQL5028", "evaluation", $"The query's result maps onto no {type.Name}: {error.Message}", null, error); +} + +/// Where a failure stands, as Nexo and DOMQL locate it; each part is null where the failure names none. +/// The JSON Pointer of the definition's node it stands at. +/// Its line in the query's text, from 1. +/// Its column in the line, from 1. +/// Its offset in the text, from 0. +/// The binding it concerns. +/// The module it stands in. +/// The type of the module it stands in. +/// The declaration it stands at. +/// The key of the declaration it concerns. +public sealed record DomqlLocation(string? Node, int? Line, int? Column, int? Offset, string? Binding, string? Module, string? Type, string? Declaration, string? DeclarationKey) +{ + /// No location. + public static DomqlLocation None { get; } = new(null, null, null, null, null, null, null, null, null); + + internal static DomqlLocation FromJson(JsonElement location) + { + if (location.ValueKind != JsonValueKind.Object) + { + return None; + } + + return new DomqlLocation( + TextOf(location, "pointer"), + NumberOf(location, "line"), + NumberOf(location, "column"), + NumberOf(location, "offset"), + TextOf(location, "binding"), + TextOf(location, "module"), + TextOf(location, "type"), + TextOf(location, "declaration"), + TextOf(location, "declarationKey")); + } + + private static string? TextOf(JsonElement location, string name) => + location.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null; + + private static int? NumberOf(JsonElement location, string name) => + location.TryGetProperty(name, out var value) && value.TryGetInt32(out var number) ? number : null; +} diff --git a/nuget/DomqlExecution.cs b/nuget/DomqlExecution.cs new file mode 100644 index 0000000..b610ee0 --- /dev/null +++ b/nuget/DomqlExecution.cs @@ -0,0 +1,182 @@ +namespace Domql; + +using System.Text.Json; + +/// A continuous execution running in the browser for its owner: it runs from its request until it is disposed, and reports each failure it meets as it runs. +public sealed class DomqlExecution : DomqlHandle +{ + private readonly DomqlExecutionOptions _options; + + internal DomqlExecution(DomqlOwner owner, DomqlQuery query, IReadOnlyDictionary? bindings, DomqlExecutionOptions options) + : base(owner) + { + _options = options; + owner.Connection.Register(this); + + _ = ObserveAsync(owner.Connection.SendAsync(CreateRequest("run", query, bindings, Answered))); + } + + /// The failure that refused the execution, or the latest it reported; null where there is none. + public DomqlException? Error { get; private set; } + + /// Runs with other bindings, replacing them whole; a failure leaves the execution running as it was, and fails the task with it. + public async Task UpdateAsync(IReadOnlyDictionary? bindings) + { + ObjectDisposedException.ThrowIf(IsDisposed, this); + + var answer = await Owner.Connection.SendAsync(CreateRequest("update", null, bindings ?? new Dictionary(), _ => { })).ConfigureAwait(true); + + if (ErrorOf(answer) is { } error) + { + throw error; + } + } + + internal override async ValueTask DeliverAsync(JsonElement delivery) + { + if (ErrorOf(delivery) is { } error) + { + await FailAsync(error).ConfigureAwait(true); + } + + return null; + } + + private void Answered(JsonElement answer) + { + if (ErrorOf(answer) is { } error && !IsDisposed) + { + End(); + _ = FailAsync(error); + } + } + + /// A request that failed to cross fails the execution, on the context it was made in, and the execution ends. + private async Task ObserveAsync(Task sent) + { + try + { + await sent.ConfigureAwait(true); + } + catch (DomqlException error) when (!IsDisposed) + { + // The request may have run in the browser before its answer was lost, so the execution is disposed there too. + await DisposeAsync().ConfigureAwait(true); + await FailAsync(error).ConfigureAwait(true); + } + catch (Exception error) when (error is DomqlException or ObjectDisposedException) + { + // An execution that has ended, or a connection that is disposed, has nothing left to tell. + } + } + + private async Task FailAsync(DomqlException error) + { + Error = error; + + if (_options.Failed is not { } failed) + { + Owner.Connection.ReportHandlerFailure(Id, error); + + return; + } + + try + { + await failed(error).ConfigureAwait(true); + } + catch (Exception handlerError) when (handlerError is not OutOfMemoryException) + { + Owner.Connection.ReportHandlerFailure(Id, handlerError); + } + } +} + +/// A once execution or an evaluation: answered with its request where the browser settled it in the request's task, and delivered once it settles otherwise. +internal sealed class DomqlResult : IDomqlRoute +{ + private readonly DomqlQuery _query; + private readonly TaskCompletionSource _result = new(TaskCreationOptions.RunContinuationsAsynchronously); + private bool _isEnded; + + public DomqlResult(DomqlOwner owner, string kind, DomqlQuery query, IReadOnlyDictionary? bindings) + { + _query = query; + Owner = owner; + Id = owner.Connection.CreateHandleId(); + owner.Connection.Register(this); + + _ = ObserveAsync(owner.Connection.SendAsync(DomqlRouting.CreateRequest(this, 0, kind, query, bindings, Settle))); + } + + public long Id { get; } + + public DomqlOwner Owner { get; } + + /// Waits for the result; cancelling stops the wait alone. + public Task WaitAsync(CancellationToken cancellationToken) => _result.Task.WaitAsync(cancellationToken); + + public ValueTask DeliverAsync(JsonElement delivery) + { + Settle(delivery); + + return ValueTask.FromResult(null); + } + + public void End() + { + if (!_isEnded) + { + _isEnded = true; + Owner.Connection.Unregister(this); + _result.TrySetCanceled(); + } + } + + /// A request that failed to cross fails the result, its failure set before ending cancels what waits. + private async Task ObserveAsync(Task sent) + { + try + { + await sent.ConfigureAwait(true); + } + catch (Exception error) when (error is DomqlException or ObjectDisposedException) + { + _result.TrySetException(error); + End(); + } + } + + /// Settles with the value or the failure an answer or a delivery holds; one that is pending waits for its delivery. + private void Settle(JsonElement outcome) + { + if (outcome.ValueKind != JsonValueKind.Object || outcome.TryGetProperty("pending", out _)) + { + if (outcome.ValueKind != JsonValueKind.Object) + { + _result.TrySetException(new DomqlException("DOMQL5030", "evaluation", "The browser answered the request with nothing it reads")); + End(); + } + + return; + } + + if (DomqlRouting.ErrorOf(outcome) is { } error) + { + _result.TrySetException(error); + } + else if (outcome.TryGetProperty("value", out var value)) + { + try + { + _result.TrySetResult(_query.Map(value)); + } + catch (DomqlException mappingError) + { + _result.TrySetException(mappingError); + } + } + + End(); + } +} diff --git a/nuget/DomqlHandle.cs b/nuget/DomqlHandle.cs new file mode 100644 index 0000000..44565de --- /dev/null +++ b/nuget/DomqlHandle.cs @@ -0,0 +1,91 @@ +namespace Domql; + +using System.Text.Json; + +/// +/// An operation a connection started in the browser for an owner: a watch, a subscription or a continuous execution. It hears its answers and its deliveries until it ends, by its disposal, its owner's, +/// the connection's, or a refusal of the request that started it. +/// +public abstract class DomqlHandle : IAsyncDisposable, IDomqlRoute +{ + private protected DomqlHandle(DomqlOwner owner) + { + Owner = owner; + Id = owner.Connection.CreateHandleId(); + } + + /// Who carries the operation out. + public DomqlOwner Owner { get; } + + /// Whether the operation has ended. + public bool IsDisposed { get; private set; } + + /// The handle's id in the connection. + internal long Id { get; } + + long IDomqlRoute.Id => Id; + + /// The generation its requests are at: raised by each update, and a delivery of an earlier one is dropped. + internal int Generation { get; private protected set; } + + /// Ends the operation in the browser and here; disposing again does nothing. A connection that is gone has ended it already. + public async ValueTask DisposeAsync() + { + GC.SuppressFinalize(this); + + if (IsDisposed) + { + return; + } + + End(); + + var request = new DomqlRequest("dispose"); + + request.Fields["handle"] = Id; + + try + { + await Owner.Connection.SendAsync(request).ConfigureAwait(true); + } + catch (Exception error) when (error is DomqlException or ObjectDisposedException) + { + // A connection that can't carry the request has no operation left to end. + } + } + + ValueTask IDomqlRoute.DeliverAsync(JsonElement delivery) => DeliverAsync(delivery); + + /// Applies a delivery of the handle, answering what the browser is answered with. + internal abstract ValueTask DeliverAsync(JsonElement delivery); + + /// Ends the handle here alone: it hears nothing more, and what waits on it is told. + internal void End() + { + if (IsDisposed) + { + return; + } + + IsDisposed = true; + Owner.Connection.Unregister(this); + Ended(); + } + + void IDomqlRoute.End() => End(); + + /// What the handle tells what waits on it as it ends. + private protected virtual void Ended() + { + } + + /// Whether a delivery is of the handle's current generation, or of none, and so applies. + private protected bool IsCurrent(JsonElement delivery) => DomqlRouting.IsCurrent(delivery, Generation); + + /// A request of the handle, its id and generation among its fields, which hands its answer to the function given. + private protected DomqlRequest CreateRequest(string kind, DomqlQuery? query, IReadOnlyDictionary? bindings, Action answered) => + DomqlRouting.CreateRequest(this, Generation, kind, query, bindings, answered); + + /// The failure an answer or a delivery holds, null where it holds none. + private protected static DomqlException? ErrorOf(JsonElement element) => DomqlRouting.ErrorOf(element); +} diff --git a/nuget/DomqlLog.cs b/nuget/DomqlLog.cs new file mode 100644 index 0000000..db02eac --- /dev/null +++ b/nuget/DomqlLog.cs @@ -0,0 +1,13 @@ +namespace Domql; + +using Microsoft.Extensions.Logging; + +/// What a connection reports to its logger: the failures that reach no caller of their own. +internal static partial class DomqlLog +{ + [LoggerMessage(Level = LogLevel.Error, Message = "The handler of DOMQL's operation {Handle} failed, or the operation reported a failure no handler heard.")] + public static partial void HandlerFailed(ILogger logger, long handle, Exception error); + + [LoggerMessage(Level = LogLevel.Error, Message = "A batch of DOMQL's deliveries could not be read, so every watch delivers its snapshot whole.")] + public static partial void BatchUnread(ILogger logger, Exception error); +} diff --git a/nuget/DomqlOwner.cs b/nuget/DomqlOwner.cs new file mode 100644 index 0000000..e369706 --- /dev/null +++ b/nuget/DomqlOwner.cs @@ -0,0 +1,152 @@ +namespace Domql; + +/// +/// Who carries operations out, as a component that starts them: the browser gives each implementation an operation reaches its name, as env.owner, and a command reaches the behavior running for it. +/// Disposing it ends every operation it started, in one request. +/// +public sealed class DomqlOwner : IAsyncDisposable +{ + private bool _isDisposed; + + internal DomqlOwner(DomqlConnection connection, string name) + { + Connection = connection; + Name = name; + } + + /// Its name in the browser. + public string Name { get; } + + internal DomqlConnection Connection { get; } + + /// + /// Watches a query: its first snapshot arrives with its request's answer, as waits for, and each change after it is applied to the watch's copy, the next one sent only + /// once the browser has heard it applied. is called with each result once it is applied, one call at a time, with the latest where several arrived meanwhile. + /// + public DomqlWatch Watch(DomqlQuery query, IReadOnlyDictionary? bindings = null, Func? changed = null, DomqlWatchOptions? options = null) + { + ArgumentNullException.ThrowIfNull(query); + ObjectDisposedException.ThrowIf(_isDisposed, this); + + return new DomqlWatch(this, query, bindings, changed, options ?? new DomqlWatchOptions()); + } + + /// Subscribes to a subscription: each event is mapped onto and handed to as it arrives, in the order the browser heard them. + public DomqlSubscription Subscribe(DomqlQuery query, IReadOnlyDictionary? bindings, Func handler, DomqlSubscribeOptions? options = null) + { + ArgumentNullException.ThrowIfNull(query); + ArgumentNullException.ThrowIfNull(handler); + ObjectDisposedException.ThrowIf(_isDisposed, this); + + return new DomqlSubscription(this, query, bindings, async value => + { + await handler(value).ConfigureAwait(true); + + return null; + }, options ?? new DomqlSubscribeOptions()); + } + + /// + /// Subscribes to a subscription whose event source declares answers: each event is handed to , and what it answers answers the event in the browser, as the source's + /// declared type captures it. + /// + public DomqlSubscription Subscribe(DomqlQuery query, IReadOnlyDictionary? bindings, Func> handler, DomqlSubscribeOptions? options = null) + { + ArgumentNullException.ThrowIfNull(query); + ArgumentNullException.ThrowIfNull(handler); + ObjectDisposedException.ThrowIf(_isDisposed, this); + + return new DomqlSubscription(this, query, bindings, async value => await handler(value).ConfigureAwait(true), options ?? new DomqlSubscribeOptions()); + } + + /// Runs the continuous execution a query ends in, until its handle, or this owner, is disposed. + public DomqlExecution Run(DomqlQuery query, IReadOnlyDictionary? bindings = null, DomqlExecutionOptions? options = null) + { + ArgumentNullException.ThrowIfNull(query); + ObjectDisposedException.ThrowIf(_isDisposed, this); + + return new DomqlExecution(this, query, bindings, options ?? new DomqlExecutionOptions()); + } + + /// Carries out the once execution a query ends in, answering its result, mapped onto . Cancelling stops the wait alone: the execution has started in the browser. + public Task ExecuteAsync(DomqlQuery query, IReadOnlyDictionary? bindings = null, CancellationToken cancellationToken = default) => + StartResult("execute", query, bindings, cancellationToken); + + /// Evaluates a query once, waiting for its maintained members, answering its result, mapped onto . + public Task EvaluateAsync(DomqlQuery query, IReadOnlyDictionary? bindings = null, CancellationToken cancellationToken = default) => + StartResult("evaluate", query, bindings, cancellationToken); + + /// Ends every operation the owner started, in the browser in one request and here; disposing again does nothing. + public async ValueTask DisposeAsync() + { + if (_isDisposed) + { + return; + } + + _isDisposed = true; + + foreach (var handle in Connection.HandlesOf(this)) + { + handle.End(); + } + + var request = new DomqlRequest("release"); + + request.Fields["owner"] = Name; + + var released = Connection.SendAsync(request); + + Connection.ReleaseOwnerName(Name); + + try + { + await released.ConfigureAwait(true); + } + catch (Exception error) when (error is DomqlException or ObjectDisposedException) + { + // A connection that can't carry the request has no operation left to end. + } + } + + private Task StartResult(string kind, DomqlQuery query, IReadOnlyDictionary? bindings, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(query); + ObjectDisposedException.ThrowIf(_isDisposed, this); + + return new DomqlResult(this, kind, query, bindings).WaitAsync(cancellationToken); + } +} + +/// How a watch evaluates, as query.watch's options say. +public sealed record DomqlWatchOptions +{ + /// When it evaluates after a change: frame, the default, at the next animation frame; immediate, at once; or delayed, once has passed without another. + public string? Schedule { get; init; } + + /// The time a delayed schedule waits. + public TimeSpan? Delay { get; init; } + + /// Whether it accepts members whose observations miss some changes. + public bool AcceptPartialObservation { get; init; } + + /// Hears each failure of an evaluation, and of a result its type can't hold; the connection's logger hears them where none is given. + public Func? Failed { get; init; } +} + +/// How a subscription hears its events. +public sealed record DomqlSubscribeOptions +{ + /// The least time between two events it hears, the latest heard after it; none where it hears every one. + public TimeSpan? Throttle { get; init; } + + /// Hears each failure of an event; the connection's logger hears them where none is given. + public Func? Failed { get; init; } +} + +/// How a continuous execution reports. +public sealed record DomqlExecutionOptions +{ + /// Hears each failure the execution reports while it runs; the connection's logger hears them where none is given. + public Func? Failed { get; init; } +} diff --git a/nuget/DomqlQuery.cs b/nuget/DomqlQuery.cs new file mode 100644 index 0000000..7553f53 --- /dev/null +++ b/nuget/DomqlQuery.cs @@ -0,0 +1,101 @@ +namespace Domql; + +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization.Metadata; + +/// +/// A query's text, as the browser reads it with Domql supplied, and the types it declares for its bindings. It is checked in the browser, by the first request that makes it there, which a failure answers. +/// +public abstract class DomqlQuery +{ + private protected DomqlQuery(string text, IReadOnlyDictionary? types) + { + ArgumentException.ThrowIfNullOrWhiteSpace(text); + + Text = text; + Types = types; + Identity = types is null ? text : $"{text}\0{string.Join('\0', types.OrderBy(pair => pair.Key, StringComparer.Ordinal).Select(pair => $"{pair.Key}={pair.Value}"))}"; + } + + /// The query's text. + public string Text { get; } + + /// The type of each top-level binding it declares, by its notation, as domql.query's types declares it; null where it declares none. + public IReadOnlyDictionary? Types { get; } + + /// What tells two queries apart in a connection: their text and their declared types. + internal string Identity { get; } + + /// A query whose result maps onto through the type information given, as source-generated serialization gives it. + public static DomqlQuery Create(string text, JsonTypeInfo type, IReadOnlyDictionary? types = null) + { + ArgumentNullException.ThrowIfNull(type); + + return new DomqlQuery(text, types, node => node.Deserialize(type)!, element => element.Deserialize(type)!); + } + + /// A query whose result maps onto through the serializer's options, the web's defaults where none are given. + [RequiresUnreferencedCode("Maps a result onto T by reflection; give a JsonTypeInfo to map it in a trimmed application.")] + [RequiresDynamicCode("Maps a result onto T by reflection; give a JsonTypeInfo to map it in a native application.")] + public static DomqlQuery Create(string text, JsonSerializerOptions? options = null, IReadOnlyDictionary? types = null) + { + var serializer = options ?? JsonSerializerOptions.Web; + + return new DomqlQuery(text, types, node => node.Deserialize(serializer)!, element => element.Deserialize(serializer)!); + } + + /// A query whose result is its JSON, as the browser gave it. + public static DomqlQuery Create(string text, IReadOnlyDictionary? types = null) => + new(text, types, ElementOf, element => element.Clone()); + + /// A copy's JSON as an element of its own. + private static JsonElement ElementOf(JsonNode? node) + { + using var document = JsonDocument.Parse(node?.ToJsonString() ?? "null"); + + return document.RootElement.Clone(); + } +} + +/// A query whose result maps onto : its fields onto the properties and constructor parameters of , as the serializer it was made with maps them. +/// What its result maps onto. +public sealed class DomqlQuery : DomqlQuery +{ + private readonly Func _mapNode; + private readonly Func _mapElement; + + internal DomqlQuery(string text, IReadOnlyDictionary? types, Func mapNode, Func mapElement) + : base(text, types) + { + _mapNode = mapNode; + _mapElement = mapElement; + } + + /// The result a copy holds, mapped; a result the type can't hold fails with DOMQL5028. + internal T Map(JsonNode? copy) + { + try + { + return _mapNode(copy); + } + catch (Exception error) when (error is JsonException or NotSupportedException or InvalidOperationException) + { + throw DomqlException.Unmapped(typeof(T), error); + } + } + + /// A value the browser delivered, mapped; one the type can't hold fails with DOMQL5028. + internal T Map(JsonElement value) + { + try + { + return _mapElement(value); + } + catch (Exception error) when (error is JsonException or NotSupportedException or InvalidOperationException) + { + throw DomqlException.Unmapped(typeof(T), error); + } + } +} diff --git a/nuget/DomqlReceiver.cs b/nuget/DomqlReceiver.cs new file mode 100644 index 0000000..ccc52b8 --- /dev/null +++ b/nuget/DomqlReceiver.cs @@ -0,0 +1,38 @@ +namespace Domql; + +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; + +using Microsoft.JSInterop; + +/// What the browser delivers to: each batch of a connection's deliveries, as one call. +internal sealed class DomqlReceiver(DomqlConnection connection) +{ + /// Applies a batch of deliveries, answering one answer for each. + [JSInvokable] + public Task ReceiveAsync(DomqlTransfer transfer) => connection.ReceiveAsync(transfer); +} + +/// A batch of deliveries as it crossed: the deliveries, or, beyond the browser's budget, a stream of their JSON. +[SuppressMessage("Performance", "CA1812", Justification = "Microsoft.JSInterop creates it as it reads the argument of ReceiveAsync.")] +internal sealed class DomqlTransfer +{ + /// The deliveries, where they crossed as data. + public JsonElement? Deliveries { get; set; } + + /// A stream of the batch's JSON, as UTF-8, where it crossed as one. + public IJSStreamReference? Stream { get; set; } +} + +/// Where a connection finds DOMQL in the browser, and how much it reads of a delivery. +public sealed class DomqlConnectionOptions +{ + /// The module a connection imports and opens, as the package serves it. + public string ModulePath { get; set; } = "./_content/domql/domql.dotnet.js"; + + /// The most a batch of deliveries crosses as data, in UTF-8 bytes, measured as a server's transport writes it, its JSON escaped once more; a larger one crosses as a stream. + public int TextBudget { get; set; } = 16 * 1024; + + /// The most bytes a connection reads of a batch that crossed as a stream; a larger one fails with DOMQL5030. + public long MaximumDeliverySize { get; set; } = 16 * 1024 * 1024; +} diff --git a/nuget/DomqlRequest.cs b/nuget/DomqlRequest.cs new file mode 100644 index 0000000..4441509 --- /dev/null +++ b/nuget/DomqlRequest.cs @@ -0,0 +1,79 @@ +namespace Domql; + +using System.Text.Json; + +/// +/// One request a connection carries to the browser: what it asks for, its fields, the query it names, and the task its answer settles. A request is written as it crosses, so the query's text crosses only +/// with the first request that needs it. +/// +internal sealed class DomqlRequest(string kind) +{ + private readonly TaskCompletionSource _answer = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly Action? _answered; + + /// A request that hands its answer to the function given as it arrives, before its task settles. + public DomqlRequest(string kind, Action answered) + : this(kind) + { + _answered = answered; + } + + /// The request's fields beside its kind and its query, as the browser reads them. + public Dictionary Fields { get; } = []; + + /// The query it names, with the key the connection gave it; none for a request that names none. + public (DomqlQuery Query, long Key)? Query { get; init; } + + /// The key of the query whose text crossed with this request, as it was written; null where none did. + public long? CarriedQuery { get; private set; } + + /// Settles with the request's answer, or fails with what kept it from crossing. + public Task Answer => _answer.Task; + + /// + /// The request as it crosses: its kind, its fields, and its query by its key, with its text and its declared types where the browser has not made it yet. + /// + /// Whether the browser has made the query of the key, or will have as an earlier request of the batch makes it. + public Dictionary Write(Func isMade) + { + var written = new Dictionary { ["request"] = kind }; + + foreach (var (name, value) in Fields) + { + written[name] = value; + } + + if (Query is var (query, key)) + { + if (isMade(key)) + { + written["query"] = key; + } + else + { + CarriedQuery = key; + // Dictionaries, which a trimmed application keeps, rather than anonymous types, which it may not. + var crossing = new Dictionary { ["key"] = key, ["text"] = query.Text }; + + if (query.Types is not null) + { + crossing["types"] = query.Types; + } + + written["query"] = crossing; + } + } + + return written; + } + + /// Hands the answer to the request's own receiver, then settles its task. + public void Complete(JsonElement answer) + { + _answered?.Invoke(answer); + _answer.TrySetResult(answer); + } + + /// Fails the request with what kept it from crossing. + public void Fail(DomqlException error) => _answer.TrySetException(error); +} diff --git a/nuget/DomqlRoute.cs b/nuget/DomqlRoute.cs new file mode 100644 index 0000000..7f4df6e --- /dev/null +++ b/nuget/DomqlRoute.cs @@ -0,0 +1,48 @@ +namespace Domql; + +using System.Text.Json; + +/// What a connection routes its answers and deliveries to: an operation it started, by its id, until it ends. +internal interface IDomqlRoute +{ + /// Its id in the connection. + long Id { get; } + + /// Who carries it out. + DomqlOwner Owner { get; } + + /// Applies a delivery of it, answering what the browser is answered with. + ValueTask DeliverAsync(JsonElement delivery); + + /// Ends it here alone: it hears nothing more, and what waits on it is told. + void End(); +} + +/// What every operation's requests and deliveries share: the fields a request names it by, and what an answer or a delivery holds. +internal static class DomqlRouting +{ + /// A request of an operation, its id, owner and generation among its fields, which hands its answer to the function given. + public static DomqlRequest CreateRequest(IDomqlRoute route, int generation, string kind, DomqlQuery? query, IReadOnlyDictionary? bindings, Action answered) + { + var request = new DomqlRequest(kind, answered) { Query = query is null ? null : (query, route.Owner.Connection.QueryKeyOf(query)) }; + + request.Fields["handle"] = route.Id; + request.Fields["owner"] = route.Owner.Name; + request.Fields["generation"] = generation; + + if (bindings is not null) + { + request.Fields["bindings"] = bindings; + } + + return request; + } + + /// Whether a delivery is of the generation given or a later one, or of none, and so applies. + public static bool IsCurrent(JsonElement delivery, int generation) => + !delivery.TryGetProperty("generation", out var given) || !given.TryGetInt32(out var value) || value >= generation; + + /// The failure an answer or a delivery holds, null where it holds none. + public static DomqlException? ErrorOf(JsonElement element) => + element.ValueKind == JsonValueKind.Object && element.TryGetProperty("error", out var error) ? DomqlException.FromJson(error) : null; +} diff --git a/nuget/DomqlServiceCollectionExtensions.cs b/nuget/DomqlServiceCollectionExtensions.cs new file mode 100644 index 0000000..436810e --- /dev/null +++ b/nuget/DomqlServiceCollectionExtensions.cs @@ -0,0 +1,23 @@ +namespace Domql; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; +using Microsoft.JSInterop; + +/// Registers DOMQL's connection. +public static class DomqlServiceCollectionExtensions +{ + /// Registers one for each scope, through the scope's JavaScript runtime, as each browser runtime has one. + public static IServiceCollection AddDomql(this IServiceCollection services, Action? configure = null) + { + ArgumentNullException.ThrowIfNull(services); + + var options = new DomqlConnectionOptions(); + + configure?.Invoke(options); + services.TryAddScoped(provider => new DomqlConnection(provider.GetRequiredService(), options, provider.GetService>())); + + return services; + } +} diff --git a/nuget/DomqlSubscription.cs b/nuget/DomqlSubscription.cs new file mode 100644 index 0000000..c203944 --- /dev/null +++ b/nuget/DomqlSubscription.cs @@ -0,0 +1,141 @@ +namespace Domql; + +using System.Text.Json; + +/// +/// A subscription to an event source: each event the browser delivers is mapped onto and handed to its handler as it arrives, never behind another's acknowledgment; the event is +/// acknowledged in the browser once the handler has completed, with what it answers where the source declares answers. +/// +/// What each event maps onto. +public sealed class DomqlSubscription : DomqlHandle +{ + private readonly DomqlQuery _query; + private readonly Func> _handler; + private readonly DomqlSubscribeOptions _options; + + internal DomqlSubscription(DomqlOwner owner, DomqlQuery query, IReadOnlyDictionary? bindings, Func> handler, DomqlSubscribeOptions options) + : base(owner) + { + _query = query; + _handler = handler; + _options = options; + owner.Connection.Register(this); + + var request = CreateRequest("subscribe", query, bindings, Answered); + + if (options.Throttle is { } throttle) + { + request.Fields["options"] = new Dictionary { ["throttle"] = throttle.TotalMilliseconds }; + } + + _ = ObserveAsync(owner.Connection.SendAsync(request)); + } + + /// The failure that refused the subscription, or the latest of its events; null where there is none. + public DomqlException? Error { get; private set; } + + /// Subscribes with other bindings, replacing them whole; an event of the old ones that arrives after it is dropped. + public Task UpdateAsync(IReadOnlyDictionary? bindings) + { + ObjectDisposedException.ThrowIf(IsDisposed, this); + + Generation++; + + var sent = Owner.Connection.SendAsync(CreateRequest("update", null, bindings ?? new Dictionary(), Answered)); + + _ = ObserveAsync(sent); + + return sent; + } + + internal override async ValueTask DeliverAsync(JsonElement delivery) + { + if (!IsCurrent(delivery)) + { + return null; + } + + if (delivery.TryGetProperty("event", out var value)) + { + T mapped; + + try + { + mapped = _query.Map(value); + } + catch (DomqlException error) + { + await FailAsync(error).ConfigureAwait(true); + + return null; + } + + return await _handler(mapped).ConfigureAwait(true); + } + + if (ErrorOf(delivery) is { } failure) + { + await FailAsync(failure).ConfigureAwait(true); + } + + return null; + } + + /// A refusal of the request that started the subscription ends it; one of an update ends the subscription it would have replaced, which still runs in the browser, by disposing it. + private void Answered(JsonElement answer) + { + if (ErrorOf(answer) is { } error && !IsDisposed) + { + if (Generation == 0) + { + End(); + } + else + { + _ = DisposeAsync().AsTask(); + } + + _ = FailAsync(error); + } + } + + private async Task FailAsync(DomqlException error) + { + Error = error; + + if (_options.Failed is not { } failed) + { + Owner.Connection.ReportHandlerFailure(Id, error); + + return; + } + + try + { + await failed(error).ConfigureAwait(true); + } + catch (Exception handlerError) when (handlerError is not OutOfMemoryException) + { + Owner.Connection.ReportHandlerFailure(Id, handlerError); + } + } + + /// A request that failed to cross fails the subscription, on the context it was made in, and the subscription ends. + private async Task ObserveAsync(Task sent) + { + try + { + await sent.ConfigureAwait(true); + } + catch (DomqlException error) when (!IsDisposed) + { + // The request may have run in the browser before its answer was lost, so the subscription is disposed there too. + await DisposeAsync().ConfigureAwait(true); + await FailAsync(error).ConfigureAwait(true); + } + catch (Exception error) when (error is DomqlException or ObjectDisposedException) + { + // A subscription that has ended, or a connection that is disposed, has nothing left to tell. + } + } +} diff --git a/nuget/DomqlWatch.cs b/nuget/DomqlWatch.cs new file mode 100644 index 0000000..eec3f65 --- /dev/null +++ b/nuget/DomqlWatch.cs @@ -0,0 +1,359 @@ +namespace Domql; + +using System.Text.Json; +using System.Text.Json.Nodes; + +/// Where a watch stands. +public enum DomqlWatchStatus +{ + /// It has no result yet. + Pending, + + /// It holds a current result. + Ready, + + /// Its last evaluation failed, or its result maps onto no value of its type; a later success makes it ready again. + Failed, + + /// It has ended. + Disposed, +} + +/// +/// A query kept current: a copy of its result, brought up to date by each change set the browser delivers, in order, and mapped onto as each is applied. Its first snapshot arrives +/// with its request's answer; a delivery that overtakes that answer waits for it. A change set that doesn't apply to the copy makes the copy uncertain, and the watch asks for its snapshot whole. +/// +/// What its result maps onto. +public sealed class DomqlWatch : DomqlHandle +{ + private readonly DomqlQuery _query; + private readonly Func? _changed; + private readonly DomqlWatchOptions _options; + private readonly List _early = []; + private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously); + private JsonNode? _copy; + private bool _isAnswered; + private bool _isUncertain; + private int _version; + private int _notified; + private bool _isNotifying; + + internal DomqlWatch(DomqlOwner owner, DomqlQuery query, IReadOnlyDictionary? bindings, Func? changed, DomqlWatchOptions options) + : base(owner) + { + _query = query; + _changed = changed; + _options = options; + owner.Connection.Register(this); + + var request = CreateRequest("watch", query, bindings, Answered); + + request.Fields["options"] = OptionsOf(options); + _ = ObserveAsync(owner.Connection.SendAsync(request)); + } + + /// Where the watch stands. + public DomqlWatchStatus Status { get; private set; } = DomqlWatchStatus.Pending; + + /// The latest result applied, mapped; the default before the first. + public T? Current { get; private set; } + + /// Whether the watch has applied a result, so that a result that is null is told apart from none yet. + public bool HasCurrent { get; private set; } + + /// The latest failure, cleared by the next result applied; null where there is none. + public DomqlException? Error { get; private set; } + + /// Waits for the watch's first result, and answers it; it fails where the request that started the watch was refused, and is cancelled where the watch ends first. + public Task ReadyAsync(CancellationToken cancellationToken = default) => _ready.Task.WaitAsync(cancellationToken); + + /// + /// Watches with other bindings, replacing them whole: the next result is the first of the new bindings, its snapshot arriving with the request's answer, and a delivery made with the old ones is dropped. + /// + public Task UpdateAsync(IReadOnlyDictionary? bindings) + { + ObjectDisposedException.ThrowIf(IsDisposed, this); + + Generation++; + _isAnswered = false; + _early.Clear(); + + var request = CreateRequest("update", null, bindings ?? new Dictionary(), Answered); + var sent = Owner.Connection.SendAsync(request); + + _ = ObserveAsync(sent); + + return sent; + } + + /// Evaluates the query now, and has its snapshot delivered whole, changed or not, so a copy that may have missed a change is brought up to date. + public Task RefreshAsync() + { + ObjectDisposedException.ThrowIf(IsDisposed, this); + + var request = CreateRequest("refresh", null, null, _ => { }); + + return Owner.Connection.SendAsync(request); + } + + internal override ValueTask DeliverAsync(JsonElement delivery) + { + if (IsCurrent(delivery)) + { + if (_isAnswered) + { + Apply(delivery); + } + else + { + _early.Add(delivery); + } + } + + return ValueTask.FromResult(null); + } + + private protected override void Ended() + { + Status = DomqlWatchStatus.Disposed; + _early.Clear(); + _ready.TrySetCanceled(); + } + + /// + /// The answer of the request that started the watch, or that bound it anew: its snapshot, or pending, its first evaluation's failure with it where that failed; a refusal ends it. Each delivery that + /// overtook the answer is applied after it, in order. + /// + private void Answered(JsonElement answer) + { + if (IsDisposed) + { + return; + } + + var error = ErrorOf(answer); + var isPending = answer.ValueKind == JsonValueKind.Object && answer.TryGetProperty("pending", out _); + + if (answer.ValueKind != JsonValueKind.Object || error is not null && !isPending) + { + Fail(error ?? new DomqlException("DOMQL5030", "evaluation", "The browser answered the watch's request with nothing it reads")); + _ready.TrySetException(Error!); + + // A refused update leaves the watch it would have replaced running in the browser, which disposing ends; a refused start left none. + if (Generation == 0) + { + End(); + } + else + { + _ = DisposeAsync().AsTask(); + } + + return; + } + + _isAnswered = true; + + if (answer.TryGetProperty("snapshot", out var snapshot)) + { + Replace(snapshot); + } + else if (error is not null) + { + Fail(error); + } + + var early = _early.ToArray(); + + _early.Clear(); + + foreach (var delivery in early) + { + if (IsCurrent(delivery)) + { + Apply(delivery); + } + } + } + + /// A delivery applied to the copy: a snapshot whole replacing it, a change set changing it, or a failure. + private void Apply(JsonElement delivery) + { + if (delivery.TryGetProperty("snapshot", out var snapshot)) + { + Replace(snapshot); + } + else if (delivery.TryGetProperty("changes", out var changes)) + { + // A copy a change set failed to apply to waits for its snapshot whole, which the refresh it asked for brings. + if (_isUncertain) + { + return; + } + + try + { + _copy = DomqlChangeSet.Apply(_copy, changes); + } + catch (DomqlException error) + { + _isUncertain = true; + Fail(error); + _ = RefreshQuietlyAsync(); + + return; + } + + Mapped(); + } + else if (ErrorOf(delivery) is { } error) + { + Fail(error); + } + } + + private void Replace(JsonElement snapshot) + { + _copy = JsonNode.Parse(snapshot.GetRawText()); + _isUncertain = false; + Mapped(); + } + + /// The copy mapped as the current result, the watch ready with it, and its handler told; a result its type can't hold is a failure, the current result standing. + private void Mapped() + { + T value; + + try + { + value = _query.Map(_copy); + } + catch (DomqlException error) + { + Fail(error); + + return; + } + + Current = value; + HasCurrent = true; + Status = DomqlWatchStatus.Ready; + Error = null; + _ready.TrySetResult(value); + _version++; + + if (_changed is not null && !_isNotifying) + { + _isNotifying = true; + _ = NotifyAsync(); + } + } + + /// Calls the handler with the latest result, one call at a time, until it has heard the latest. + private async Task NotifyAsync() + { + try + { + while (_notified < _version && !IsDisposed) + { + _notified = _version; + + try + { + await _changed!(Current!).ConfigureAwait(true); + } + catch (Exception error) when (error is not OutOfMemoryException) + { + Owner.Connection.ReportHandlerFailure(Id, error); + } + } + } + finally + { + _isNotifying = false; + } + } + + private void Fail(DomqlException error) + { + Status = DomqlWatchStatus.Failed; + Error = error; + + if (_options.Failed is { } failed) + { + _ = ReportAsync(failed, error); + } + else + { + Owner.Connection.ReportHandlerFailure(Id, error); + } + } + + private async Task ReportAsync(Func failed, DomqlException error) + { + try + { + await failed(error).ConfigureAwait(true); + } + catch (Exception handlerError) when (handlerError is not OutOfMemoryException) + { + Owner.Connection.ReportHandlerFailure(Id, handlerError); + } + } + + /// A request that failed to cross fails the watch, on the context it was made in, and the watch ends, its result standing where it had one. + private async Task ObserveAsync(Task sent) + { + try + { + await sent.ConfigureAwait(true); + } + catch (DomqlException error) when (!IsDisposed) + { + Fail(error); + _ready.TrySetException(error); + + // The request may have run in the browser before its answer was lost, so the watch is disposed there too. + await DisposeAsync().ConfigureAwait(true); + } + catch (Exception error) when (error is DomqlException or ObjectDisposedException) + { + // A watch that has ended, or a connection that is disposed, has nothing left to tell. + } + } + + /// Asks for the snapshot whole, where the connection can still carry the request. + private async Task RefreshQuietlyAsync() + { + try + { + await RefreshAsync().ConfigureAwait(true); + } + catch (Exception error) when (error is DomqlException or ObjectDisposedException) + { + // A connection that can't carry it has ended the watch. + } + } + + private static Dictionary OptionsOf(DomqlWatchOptions options) + { + var written = new Dictionary(); + + if (options.Schedule is not null) + { + written["schedule"] = options.Schedule; + } + + if (options.Delay is { } delay) + { + written["delay"] = delay.TotalMilliseconds; + } + + if (options.AcceptPartialObservation) + { + written["acceptPartialObservation"] = true; + } + + return written; + } +} diff --git a/nuget/Forma.DOMQL.csproj b/nuget/Forma.DOMQL.csproj index f22f64d..9aea16d 100644 --- a/nuget/Forma.DOMQL.csproj +++ b/nuget/Forma.DOMQL.csproj @@ -29,6 +29,17 @@ true + + + Domql + true + + + + + + + diff --git a/nuget/Forma.DOMQL.slnx b/nuget/Forma.DOMQL.slnx index 1a4a21e..8a563bb 100644 --- a/nuget/Forma.DOMQL.slnx +++ b/nuget/Forma.DOMQL.slnx @@ -1,4 +1,6 @@ + + diff --git a/nuget/README.md b/nuget/README.md index e67aab6..d5fc897 100644 --- a/nuget/README.md +++ b/nuget/README.md @@ -19,6 +19,7 @@ DOMQL is a JavaScript library for querying the DOM, allowing you to read informa - [Environments](#environments) - [Extend the vocabulary](#extend-the-vocabulary) - [Execute once and run continuously](#execute-once-and-run-continuously) +- [Use DOMQL from .NET](#use-domql-from-net) ## Install and load @@ -1579,6 +1580,38 @@ clickFilter.dispose(); filtered.dispose(); ``` +## Use DOMQL from .NET + +The package holds DOMQL's .NET half too. Register its connection, one for each browser your application reaches: + +```csharp +builder.Services.AddDomql(); +``` + +Then write a query's text, name the type its result maps onto, and carry it out for an owner. An owner is a part of your application that starts operations of its own, and disposing it ends all of them in one call: + +```csharp +public sealed record PanelState(double? Width, bool HasFocus); + +static readonly DomqlQuery Panel = DomqlQuery.Create("panel { width = it.layoutSize?.inline, hasFocus = it.focusWithin }"); + +DomqlOwner owner = connection.CreateOwner(); +DomqlWatch watch = owner.Watch(Panel, new Dictionary { ["panel"] = panelElement }, state => RenderAsync(state)); + +PanelState first = await watch.ReadyAsync(); // Arrives with the watch's own request. +bool focused = await owner.ExecuteAsync(DomqlQuery.Create("field.focus()"), new Dictionary { ["field"] = fieldElement }); + +await owner.DisposeAsync(); +``` + +- **One call for one turn.** Every operation your code starts before it yields crosses to the browser in one call, and the answer brings back each watch's first result. +- **A watch keeps a copy.** Each change arrives as a change set, applied to the watch's copy before the browser sends the next. `changed` hears the latest result, one call at a time. +- **Events arrive as they happen.** A subscription's handler can answer an event, with `Subscribe`, where its event source declares `answers`. +- **Typed results.** Pass source-generated type information, as `DomqlQuery.Create(text, AppJsonContext.Default.PanelState)`, in a trimmed or native application. +- **After a lost connection,** call `connection.RefreshAsync()` once it resumes, and every watch delivers its result whole. + +[The .NET half](https://github.com/FormaUI/DOMQL/blob/main/spec/dotnet.md) specifies each operation, and [connections](https://github.com/FormaUI/DOMQL/blob/main/spec/connections.md) the messages they cross as. + ## Learn more - [Repository README](https://github.com/FormaUI/DOMQL): what DOMQL is for, what is built, and how to build and test it. diff --git a/nuget/global.json b/nuget/global.json index db8b598..a677f5e 100644 --- a/nuget/global.json +++ b/nuget/global.json @@ -2,5 +2,8 @@ "sdk": { "version": "11.0.100-rc.3.26522.148", "rollForward": "disable" + }, + "test": { + "runner": "Microsoft.Testing.Platform" } } diff --git a/nuget/scripts/domql.dotnet.js b/nuget/scripts/domql.dotnet.js new file mode 100644 index 0000000..3ab0179 --- /dev/null +++ b/nuget/scripts/domql.dotnet.js @@ -0,0 +1,33 @@ +/** + * domql.dotnet — the connection a .NET application's DOMQL connection opens in the browser: DOMQL's own, in the bundle beside it, delivering to the receiver .NET gives it + */ + +import { domql } from './domql.js'; + +/** + * The most a batch of deliveries crosses as data, in UTF-8 bytes, measured as a server's transport writes it: the arguments' JSON, escaped once more as its message carries them as text. Beyond it, the batch + * crosses as a stream of its JSON's UTF-8 bytes. + */ +const TEXT_BUDGET = 16 * 1024; + +const encoder = new TextEncoder(); + +/** + * Opens a connection whose deliveries reach the receiver's `ReceiveAsync`, each batch as `{ deliveries }`, or as `{ stream }` beyond the budget, answering what the receiver answers; and answers the object .NET + * carries its requests through. + * @param {{ invokeMethodAsync: (name: string, ...args: unknown[]) => Promise }} receiver + * @param {{ textBudget?: number }} [options] + */ +export function connect(receiver, { textBudget = TEXT_BUDGET } = {}) { + const connection = domql.connect(deliveries => { + const json = JSON.stringify(deliveries); + const transfer = encoder.encode(JSON.stringify(json)).length <= textBudget ? { deliveries } : { stream: globalThis.DotNet.createJSStreamReference(encoder.encode(json)) }; + + return receiver.invokeMethodAsync('ReceiveAsync', transfer); + }); + + return { + requestAsync: requests => connection.requestAsync(requests), + close: () => connection.close(), + }; +} diff --git a/scripts/bundle.mjs b/scripts/bundle.mjs index 8340ce0..a32405c 100644 --- a/scripts/bundle.mjs +++ b/scripts/bundle.mjs @@ -16,6 +16,9 @@ export const bundlePath = resolve(root, 'nuget', 'wwwroot', 'domql.js'); /** Where the package serves the declarations of the bundle's API from, beside the bundle. */ export const declarationsPath = resolve(root, 'nuget', 'wwwroot', 'domql.d.ts'); +/** Where the package serves the module a .NET application's connection opens, which imports the bundle beside it. */ +export const dotnetConnectionPath = resolve(root, 'nuget', 'wwwroot', 'domql.dotnet.js'); + /** Bundles the entry and every module it imports into one minified ES module, answering its text. */ export async function bundle() { const result = await build({ @@ -38,6 +41,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await mkdir(dirname(bundlePath), { recursive: true }); await writeFile(bundlePath, text); await copyFile(resolve(root, 'src', 'domql.d.ts'), declarationsPath); + await copyFile(resolve(root, 'nuget', 'scripts', 'domql.dotnet.js'), dotnetConnectionPath); - console.log(`Bundled ${Buffer.byteLength(text)} bytes of DOMQL ${Versions.runtime} to ${bundlePath}, with its declarations beside it`); + console.log(`Bundled ${Buffer.byteLength(text)} bytes of DOMQL ${Versions.runtime} to ${bundlePath}, with its declarations and the module a .NET connection opens beside it`); } diff --git a/scripts/packages/npm.files b/scripts/packages/npm.files index 19cd792..fc8672c 100644 --- a/scripts/packages/npm.files +++ b/scripts/packages/npm.files @@ -5,6 +5,7 @@ README.md package.json src/Versions.mjs src/common/ObjectUtils.mjs +src/connections/Connection.mjs src/dom/Behaviors.mjs src/dom/BrowserExecutionImplementations.mjs src/dom/BrowserModule.mjs diff --git a/scripts/packages/nuget.files b/scripts/packages/nuget.files index 4c566ec..42df584 100644 --- a/scripts/packages/nuget.files +++ b/scripts/packages/nuget.files @@ -11,6 +11,8 @@ buildMultiTargeting/formaui-net.DOMQL.targets buildTransitive/formaui-net.DOMQL.targets formaui-net.DOMQL.nuspec lib/net11.0/Forma.DOMQL.dll +lib/net11.0/Forma.DOMQL.xml package/services/metadata/core-properties/nuget.psmdcp staticwebassets/domql.d.ts +staticwebassets/domql.dotnet.js staticwebassets/domql.js diff --git a/spec/README.md b/spec/README.md index 5db1290..0d37ebd 100644 --- a/spec/README.md +++ b/spec/README.md @@ -38,6 +38,8 @@ Start with [queries](queries.md), which shows a query with its parameters and it 8. [Executions](executions.md): executing once and running continuously. 9. [Behaviors](behaviors.md): an operation's owner, a behavior's running instance, the commands that reach it, its occurrences and their acknowledgment, handling inside the native dispatch, and the state it offers. 10. [The API](api.md): every entry point, operation and handle, the events a handle raises, their order across handles, lifetimes and errors. -11. [Errors](errors.md): the codes of DOMQL's own conditions. -12. [Examples](examples.md): a complete query with its document and result, and queries by what they ask. -13. [Terms](terms.md): the glossary. +11. [Connections](connections.md): DOMQL's operations carried across a boundary as messages, the requests a host sends and the deliveries it receives, and how a watch's are paced. +12. [The .NET half](dotnet.md): DOMQL from a .NET application: its connection, its queries and the types their results map onto, its owners, watches, subscriptions and executions, and the calls each takes. +13. [Errors](errors.md): the codes of DOMQL's own conditions. +14. [Examples](examples.md): a complete query with its document and result, and queries by what they ask. +15. [Terms](terms.md): the glossary. diff --git a/spec/api.md b/spec/api.md index a1e6ed0..8ba9f7a 100644 --- a/spec/api.md +++ b/spec/api.md @@ -86,6 +86,7 @@ Each entry point and operation is listed here with what it takes, and the sectio | `domql.createModule(name, contents, options?)` | Creates a module from its declarations, each that runs code carrying its implementation, as [extension modules](vocabulary.md#extension-modules) set out, under the manifest `options.manifest` gives | | `domql.registerModule(module, options?)` | Registers a module's declarations in the instance's registry, as [extension modules](vocabulary.md#extension-modules) set out, under the manifest `options.manifest` gives | | `domql.registerModuleLoader(name, load, options?)` | Registers the loader of a module loaded on request, as [loading a module on request](vocabulary.md#extension-modules-loading) sets out, its module registered with the options given | +| `domql.connect(deliver, options?)` | Opens a connection that carries the instance's operations across a boundary as messages, as [connections](connections.md) set out, which [the .NET half](dotnet.md) opens | | `domql.loadModulesAsync(modules)` | Loads and registers every module named that the instance doesn't hold yet, answering a promise, as [loading a module on request](vocabulary.md#extension-modules-loading) sets out | | `domql.info` | Which build this is and what it follows, in `versions`: `runtime`, the runtime release version, which the package and the bundle carry, its sources reporting the same; `specification`, the version of DOMQL's specification it follows; and `language`, the language specification version the Nexo runtime it runs on follows, its `nexo.info.versions.language` | diff --git a/spec/connections.md b/spec/connections.md new file mode 100644 index 0000000..0252486 --- /dev/null +++ b/spec/connections.md @@ -0,0 +1,110 @@ +# Connections + + + +A **connection** carries DOMQL's operations across a boundary as messages, for a host whose code runs somewhere else, as a .NET application's does. The host sends **requests** in batches, and DOMQL answers each batch. DOMQL sends back **deliveries**: a watch's changes, a subscription's events, a result that settled later, and failures. + +```js +const connection = domql.connect(deliveries => host.receiveAsync(deliveries)); + +const answers = await connection.requestAsync([ + { request: 'watch', handle: 1, owner: 'panel-7', query: { key: 'width', text: '{ width = panel.layoutSize?.inline }' }, bindings: { panel } }, + { request: 'watch', handle: 2, owner: 'panel-8', query: 'width', bindings: { panel: other } }, +]); +// [{ snapshot: { width: 640 } }, { snapshot: { width: 320 } }] +``` + +[The .NET half](dotnet.md) is DOMQL's own host of a connection. + +In this document: + +1. [Opening one](#connections-opening) +2. [Requests and their answers](#connections-requests) +3. [Deliveries](#connections-deliveries) +4. [Pacing](#connections-pacing) +5. [Owners, handles and generations](#connections-handles) +6. [Failures and closing](#connections-failures) + + + +## Opening one + +`domql.connect(deliver, options?)` opens a connection on this instance of DOMQL, its registry and its modules among it. + +- **`deliver(deliveries)`** is the host's receiver. DOMQL calls it with every delivery of one task, in the order they happened. It answers a promise of one answer for each delivery, which settles once the host has applied them all. A `deliver` that is no function is refused with `DOMQL2022`. +- **`options.window`** is the window the connection's operations run in, the global one by default. +- **`connection.close()`** ends every handle the connection started. Each request after it answers `DOMQL5027`. `connection.isClosed` says whether it has closed. + + + +## Requests and their answers + +`connection.requestAsync(requests)` carries out a list of requests in order. It answers a promise of their answers, one for each, in order. The promise settles once the task that carried them out has ended, so whatever that task settled is final: + +- A watch whose first evaluation ran in the task answers with its snapshot. +- An execution or an evaluation that settled in the task answers with its value. +- What still waits answers `{ pending: true }`. Its result arrives as a delivery of its handle. + +| Request | Fields | Answer | +| --- | --- | --- | +| `watch` | `handle`, `owner`, `query`, `bindings`, `options`: `schedule`, `delay`, `reportOn`, `acceptPartialObservation` | `{ snapshot }`; or `{ pending: true }`, the snapshot delivered whole, with `error` where the first evaluation failed | +| `subscribe` | `handle`, `owner`, `query`, `bindings`, `options`: `throttle`, `reactions` | `{}` | +| `run` | `handle`, `owner`, `query`, `bindings` | `{}` | +| `execute` | `handle`, `owner`, `query`, `bindings` | `{ value }` or `{ pending: true }` | +| `evaluate` | `handle`, `owner`, `query`, `bindings` | `{ value }` or `{ pending: true }`, waiting for maintained members as `evaluateAsync` does | +| `load` | `handle`, `modules` | `{ value: null }` or `{ pending: true }`, as `loadModulesAsync` loads them | +| `update` | `handle`, `generation`, `bindings`, `options` | A watch watches anew with the new bindings and answers as a `watch` request does. A subscription subscribes anew, and an execution is updated in place, each answering `{}` | +| `refresh` | `handle`, or none for every watch; `generation`; `resample` | `{}`; each watch's snapshot is delivered whole, changed or not | +| `dispose` | `handle` | `{}` | +| `release` | `owner` | `{}`; every handle of the owner ends | + +- **Each request fails alone.** A request that fails answers `{ error }`, and starts no handle. The others of its batch are carried out. +- **Malformed requests.** One that names no request of the table is refused with `DOMQL2023`. A list of requests that is no list rejects the whole call with `DOMQL2023`. +- **Queries cross once.** A request names its query as `{ key, text }`, or `{ key, definition }`, the first time. It may give `types` and `manifest` beside it, as [`domql.query`](queries.md#making-a-query-declared-types) takes them. Every later request names the query by its key alone. A key no earlier request made is refused with `DOMQL2024`. A query whose making was refused is made by no key, so the host sends its text again. +- **Bindings** are the values the transport carried. An element the transport revives, as a .NET element reference becomes the element it names, binds as an element. +- **Reactions** are given in the connection's own form, each `{ query, bindings }`. + + + +## Deliveries + +Each delivery names the handle it belongs to: + +| Delivery | What it holds | +| --- | --- | +| `{ handle, generation, snapshot }` | A watch's snapshot whole: its first, where its request answered pending; after a refresh; or where it is shorter than the change set | +| `{ handle, generation, changes }` | A watch's [change set](results.md#results-change-sets) from the snapshot delivered before it, change sets concatenated where several arose while one was waiting, as [D65](../docs/decisions.md#d65) records | +| `{ handle, generation, event }` | A subscription's event, its projected value | +| `{ handle, value }` | The result of an execution, an evaluation or a load that answered pending | +| `{ handle, generation, error }` | A failure: a watch's evaluation, a subscription's event, or what a continuous execution reports | + +- **One task, one batch.** The deliveries of one task cross in one call to `deliver`, in the order they happened, across handles. +- **The answers.** `deliver`'s promise answers one answer for each delivery. An event's answer is the host's answer to it. Where the event source declares [`answers`](behaviors.md#behaviors-answers), that answer answers the source. Every other answer is ignored. +- **A host keeps its copy** of a watch's result by applying each delivery in order, as [keeping a copy of a result](results.md#results-keeping-a-copy) sets out. + + + +## Pacing + +- **A watch waits for its acknowledgment.** A watch's next delivery waits until `deliver` has settled the batch holding its last one. Whatever arises meanwhile waits, joined: + - Two change sets join into one, concatenated, unless the snapshot whole is shorter. + - A snapshot whole replaces everything waiting before it. + - A failure keeps its place after what came before it. +- **An event never waits.** It crosses with the task it happened in, behind nothing, and is never joined or dropped, so a host hears events in the order the page did, as [D69](../docs/decisions.md#d69) requires. Its acknowledgment settles once the host has applied it: `deliver`'s promise settles the event's acknowledgment in the browser, so an event source that waits for it waits for the host. +- **A rejected batch.** Where `deliver`'s promise rejects, each event of the batch is rejected in the browser. Each watch of the batch waits until it is refreshed, which delivers its snapshot whole. +- **A limit.** Where earlier batches have left 4,096 deliveries the host has not acknowledged, the next batch closes the connection, reporting `DOMQL5026` to the window, rather than hold every occurrence for a host that answers none. One task of many deliveries crosses whole. + + + +## Owners, handles and generations + +- **Handles.** A request that starts an operation names its handle: a string or a number. A handle that is not a string or a number, or one that still runs, is refused with `DOMQL2025`. +- **Owners.** A request names its owner, which every implementation the operation reaches receives as `env.owner`, as [the owner](api.md#api-the-owner) sets out. It is a string, a number or null, since a host's message holds no object twice. Any other owner is refused with `DOMQL2025`. +- **Generations.** A request may give its handle's generation, a whole number, 0 where none was given. Each delivery of the handle carries the generation it was made at. A host that updated a handle drops a delivery of an earlier generation. +- **Overtaking an answer.** A delivery may reach the host before its request's answer does. A host holds a watch's deliveries until its request is answered, and applies them in order after the snapshot the answer holds. + + + +## Failures and closing + +A failure crosses as `{ code, kind, message, location }`, as the [`NexoError`](api.md#api-errors) DOMQL or Nexo made gives it. A failure of a module's own code crosses as its message alone. The codes this document names are catalogued with DOMQL's others, in [errors](errors.md). diff --git a/spec/dotnet.md b/spec/dotnet.md new file mode 100644 index 0000000..0fb7fd4 --- /dev/null +++ b/spec/dotnet.md @@ -0,0 +1,123 @@ +# The .NET half + + + +The .NET half is DOMQL from a .NET application. It ships in the NuGet package, `formaui-net.DOMQL`, beside the bundle. A .NET application writes a query's text, names the type its result maps onto, and carries it out for an owner. DOMQL runs it in the browser, through a [connection](connections.md), and keeps the application's copy of each result. + +```csharp +public sealed record PanelState(double? Width, bool HasFocus); + +static readonly DomqlQuery Panel = DomqlQuery.Create( + "panel { width = it.layoutSize?.inline, hasFocus = it.focusWithin }", + AppJsonContext.Default.PanelState); + +DomqlOwner owner = connection.CreateOwner(); +DomqlWatch watch = owner.Watch(Panel, new Dictionary { ["panel"] = panelElement }, state => RenderAsync(state)); +PanelState first = await watch.ReadyAsync(); + +await owner.DisposeAsync(); // Ends the watch, and everything else the owner started, in one request. +``` + +In this document: + +1. [The connection](#dotnet-connection) +2. [Queries and their results](#dotnet-queries) +3. [Owners and operations](#dotnet-operations) +4. [Watches](#dotnet-watches) +5. [Subscriptions and executions](#dotnet-subscriptions) +6. [Crossings](#dotnet-crossings) +7. [Failures](#dotnet-failures) + + + +## The connection + +- **One for each browser runtime.** `services.AddDomql()` registers one `DomqlConnection` for each scope, through the scope's `IJSRuntime`: one for each browser a server-hosted application is connected to, one for an application that runs in the browser, and one for each web view. `new DomqlConnection(jsRuntime, options, logger)` makes one directly. +- **It opens as its first request crosses.** It imports `_content/domql/domql.dotnet.js`, which the package serves beside the bundle, and opens a connection there whose deliveries reach .NET. Requests made while it opens cross with the first batch. +- **One synchronization context.** A connection is used from the context its runtime's callbacks run on, as a server-hosted application's dispatcher or the browser's one thread runs them. Its handlers run there. +- **`RefreshAsync()`** has every watch deliver its snapshot whole, changed or not, as a host does once its connection to the browser resumes and a delivery may have been lost. +- **`DisposeAsync()`** closes the browser's side and ends every operation the connection started. +- **`DomqlConnectionOptions`:** + - `ModulePath`, where the module is served. + - `TextBudget`: the most a batch of deliveries crosses as data, 16 KB, in UTF-8 bytes as a server's transport writes it, its JSON escaped once more. A larger one crosses as a stream of its JSON's UTF-8 bytes, so a delivery is never refused for a transport's message size. + - `MaximumDeliverySize`: the most bytes the connection reads of a stream, 16 MiB. + + + +## Queries and their results + +- **`DomqlQuery.Create(text, typeInfo, types?)`** makes a query whose result maps onto `T` through source-generated type information, as a trimmed or native application needs. `DomqlQuery.Create(text, options?, types?)` maps it by reflection, through the serializer's options, the web's defaults by default. `DomqlQuery.Create(text, types?)` keeps the result's JSON, as a `JsonElement`. +- **The text is checked in the browser.** It is read with `Domql` supplied, as `domql.query` reads it, by the first request that makes it there. A syntax or structure failure fails that request. .NET has no parser of its own. +- **`types`** declares the type of a top-level binding by its notation, as [declared types](queries.md#making-a-query-declared-types) do. +- **Mapping.** A result's fields map onto `T`'s properties and constructor parameters as the serializer maps JSON. A result `T` can't hold is a failure, `DOMQL5028`, and a watch's current result stands. +- **Records a field discriminates.** A result that is one of several shapes maps onto a type the serializer reads polymorphically, by a field the query names first, as `[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]` names one. +- **Bindings** are `IReadOnlyDictionary`. Each value crosses as the runtime serializes it, and an element reference the runtime serializes crosses as the element it refers to. + + + +## Owners and operations + +`connection.CreateOwner(name?)` makes a **`DomqlOwner`**, who carries operations out. Its name is its own among the connection's owners until it is disposed: one of its own where none is given, and a name in use is refused with an `ArgumentException`, since a release names one owner alone. Each implementation an operation reaches receives its name as `env.owner`, and a command reaches the behavior running for it, as [behaviors](behaviors.md#behaviors-the-owner) set out. A part of a page that starts operations of its own holds one. + +| Operation | Answers | As in the browser | +| --- | --- | --- | +| `owner.Watch(query, bindings, changed, options)` | A `DomqlWatch` | `query.watch` | +| `owner.Subscribe(query, bindings, handler, options)`, and `Subscribe` for a source that declares `answers` | A `DomqlSubscription` | `query.subscribe` | +| `owner.Run(query, bindings, options)` | A `DomqlExecution` | `query.run` | +| `owner.ExecuteAsync(query, bindings, cancellationToken)` | Its result | `query.executeAsync` | +| `owner.EvaluateAsync(query, bindings, cancellationToken)` | Its result | `query.evaluateAsync` | +| `owner.DisposeAsync()` | — | Ends every operation the owner started, in one request | + +- **Each starts at once.** An operation starts as its call returns. Its request crosses as the turn that made it ends, with every other request of that turn, in one call. +- **Cancelling** an `ExecuteAsync` or an `EvaluateAsync` stops the wait alone. The execution has started in the browser. +- **A handle** is a watch, a subscription or an execution. `DisposeAsync()` ends it in the browser and here. A handle whose connection is gone has ended already. + + + +## Watches + +A **`DomqlWatch`** keeps a copy of its query's result, which each delivery brings up to date. + +- **Its first result** arrives with its request's answer, which `ReadyAsync()` waits for. Where the first evaluation waits for a maintained member, its snapshot is delivered whole once it has one. +- **Each change set** is applied to the copy as it arrives, by DOMQL's rules for [applying change sets](results.md#results-change-sets), and the copy is mapped onto `T`. A delivery that overtakes the request's answer waits for it. +- **The browser's next change set** crosses once this one is applied, so a watch has one delivery in flight. What arises meanwhile is joined, as [pacing](connections.md#connections-pacing) sets out. +- **`changed`** is called with each result once it is applied, one call at a time, with the latest where several arrived meanwhile. A handler that throws is reported to the connection's logger, and the copy stands. +- **`Current`**, **`HasCurrent`**, **`Status`** and **`Error`** read the copy: `Pending`, `Ready`, `Failed` or `Disposed`. A failed evaluation, or a result `T` can't hold, sets `Error` and `Failed`. The current result stands until the next result applied. +- **`UpdateAsync(bindings)`** watches with other bindings. Its next result is the first of the new ones, and a delivery made with the old ones is dropped by its generation. +- **`RefreshAsync()`** has the watch deliver its snapshot whole. +- **An uncertain copy.** A change set that doesn't apply to the copy fails with `DOMQL5029`. The watch asks for its snapshot whole, and skips change sets until it arrives. + + + +## Subscriptions and executions + +- **A `DomqlSubscription`** hands each event to its handler as it arrives, mapped onto `T`, in the order the browser heard them. An event never waits behind a watch's delivery. +- **The event's acknowledgment** in the browser settles once the handler completes. A handler of `Subscribe` answers the event, and its answer answers the event source, as [answers](behaviors.md#behaviors-answers) set out. +- **`UpdateAsync(bindings)`** subscribes with other bindings. An event of the old ones that arrives after it is dropped. +- **A `DomqlExecution`** runs until it, or its owner, is disposed. `UpdateAsync(bindings)` updates it in place, and a refusal fails the task and leaves it running as it was. +- **`Failed`**, in each handle's options, hears each failure an operation reports. The connection's logger hears those no `Failed` is given for. + + + +## Crossings + +| What a .NET application does | Calls between .NET and the browser | +| --- | --- | +| Starts any number of operations in one turn | 1, its answers holding each watch's first result | +| A watch's change | 1, the deliveries of one browser task together | +| A subscription's event | 1, with the other deliveries of its task | +| An execution that settles in its request's task | 1 | +| Ends every operation of an owner | 1 | +| Refreshes every watch, once the connection to the browser resumes | 1, and 1 for the snapshots | + + + +## Failures + +A **`DomqlException`** carries a failure's `Code`, its `Kind` and its `Location`, as DOMQL or Nexo reported it in the browser. `DomqlLocation` gives its `Node`, the JSON Pointer of the definition's node, its `Line`, `Column` and `Offset` in the text, the `Binding` it concerns, and the `Module`, `Type`, `Declaration` and `DeclarationKey` of a module's failure. + +- **A refused request** fails its operation: a watch's `ReadyAsync`, an execution's task, a handle's `Failed`. +- **A batch that can't cross** fails each request it carried with `DOMQL5030`, the runtime's failure its inner exception. +- **A batch of deliveries that can't be read** is logged, and every watch delivers its snapshot whole, once: a batch that can't be read while that refresh is under way, as a snapshot past `MaximumDeliverySize` is, refreshes nothing more until a batch is read. A handler's failure stays its own: the batch is acknowledged, and the deliveries after it are applied. +- **A refused update** fails its handle, which ends in the browser too. So does a request whose batch could not cross, since the browser may have run it before its answer was lost. +- **The .NET half's own codes:** `DOMQL5028`, a result its type can't hold; `DOMQL5029`, a change set that doesn't apply to the copy; and `DOMQL5030`, a batch that could not cross or be read. [Errors](errors.md) catalogue them with the rest. diff --git a/spec/errors.md b/spec/errors.md index 44797dc..928cde1 100644 --- a/spec/errors.md +++ b/spec/errors.md @@ -46,6 +46,10 @@ A caller's use of the API, refused where it is made. | `DOMQL2019` | A watch's `delay` that is no number above 0, given to a schedule other than `delayed`, or missing from one that is | | `DOMQL2020` | A watch's `reportOn` that is no list of paths | | `DOMQL2021` | A query `domql.prepare` is given that gives `imports` of its own, since DOMQL reads its text with `Domql` supplied | +| `DOMQL2022` | `domql.connect` given a deliver that is no function | +| `DOMQL2023` | A [connection's](connections.md#connections-requests) request that names no request it carries out, or a list of requests that is no list | +| `DOMQL2024` | A connection's request naming a query by a key no earlier request made | +| `DOMQL2025` | A connection's request whose handle is no string or number, runs already, or runs no operation of the kind it asks for; or whose owner is no string, number or null | @@ -121,3 +125,8 @@ A failure while a request is carried out, located in the query where it concerns | `DOMQL5023` | A module's loader failing, its failure the error's `cause` | | `DOMQL5024` | An occurrence a throttled subscription dropped for a later one | | `DOMQL5025` | An answer a subscription gave an occurrence that the type its event source declares it answers refuses, or whose notation names no type, the refusal the error's `cause` | +| `DOMQL5026` | A connection whose host left as many deliveries unacknowledged as its [limit](connections.md#connections-pacing) holds, which the next batch closes | +| `DOMQL5027` | A request or a delivery of a connection that has closed | +| `DOMQL5028` | In [the .NET half](dotnet.md#dotnet-queries), a result the type a query maps it onto can't hold | +| `DOMQL5029` | In the .NET half, a change set that doesn't apply to a watch's copy, which then asks for its snapshot whole | +| `DOMQL5030` | In the .NET half, a batch of requests that could not cross, or a delivery that could not be read, the runtime's failure its inner exception | diff --git a/src/connections/Connection.mjs b/src/connections/Connection.mjs new file mode 100644 index 0000000..8313922 --- /dev/null +++ b/src/connections/Connection.mjs @@ -0,0 +1,593 @@ +/** + * Connection — DOMQL's operations carried across a boundary as messages: the requests a host sends in batches, each answered as its batch's task ends, and the deliveries DOMQL sends back, those of one task together, + * each watch's paced by the acknowledgment of the one before it + */ + +import { NexoError } from '@formaui-net/nexo'; + +/** The requests a connection carries out, by the name each gives in `request`. */ +const REQUESTS = new Set(['evaluate', 'execute', 'watch', 'subscribe', 'run', 'update', 'refresh', 'dispose', 'release', 'load']); + +/** The requests that start a handle, which names it. */ +const STARTING = new Set(['evaluate', 'execute', 'watch', 'subscribe', 'run', 'load']); + +/** The options a watch request gives its watch; the strategy is the connection's, which keeps the host's copy by change sets. */ +const WATCH_OPTIONS = ['schedule', 'delay', 'reportOn', 'acceptPartialObservation']; + +/** The options a subscription request gives its subscription; its reactions are requests of the connection's own form. */ +const SUBSCRIBE_OPTIONS = ['throttle', 'reactions']; + +/** The deliveries earlier batches may leave unacknowledged; a batch sent while that many wait closes the connection, since a host that acknowledges none would otherwise hold every occurrence. */ +const OUTSTANDING_LIMIT = 4096; + +export class Connection { + /** The DOMQL instance whose operations the connection carries out. */ + #domql; + + /** The host's receiver of deliveries: `deliver(deliveries)` answers a promise of one answer for each delivery, which settles once the host has applied them. */ + #deliver; + + /** The window the connection's operations run in. */ + #window; + + /** Each query a request made, by the key the host gave it, which later requests name it by; kept until the connection closes. @type {Map} */ + #queries = new Map(); + + /** Each handle a request started that has not ended, by the id the host gave it. @type {Map} */ + #handles = new Map(); + + /** The deliveries of the current task, in the order they happened, sent together as it ends. @type {object[]} */ + #queue = []; + + #isFlushScheduled = false; + + /** The deliveries sent whose acknowledgment has not settled. */ + #outstanding = 0; + + #isClosed = false; + + /** + * @param {object} domql The DOMQL instance whose operations it carries out. + * @param {(deliveries: object[]) => Promise} deliver The host's receiver of deliveries. + * @param {{ window?: Window }} [options] + */ + constructor(domql, deliver, { window = globalThis.window } = {}) { + this.#domql = domql; + this.#deliver = deliver; + this.#window = window; + } + + /** Whether the connection has closed: by `close`, or as a host that acknowledged nothing let its deliveries pass their limit. */ + get isClosed() { + return this.#isClosed; + } + + /** + * Carries out the requests given, in order, and answers a promise of their answers, one for each, in order, which settles once the task that carried them out has ended: an answer the task settled is final, and + * one it left waiting answers `{ pending: true }`, its result reaching the host as a delivery of its handle. + * @param {object[]} requests + * @returns {Promise} + */ + requestAsync(requests) { + if (!Array.isArray(requests)) { + return Promise.reject(NexoError.structure('DOMQL2023', 'A connection is sent a list of requests', {})); + } + + const answers = requests.map(request => this.#carryOut(request)); + + // The task's microtasks settle what they settle, which a message posted to the window's own channel runs after; an answer still waiting then is delivered once it settles. + return this.#afterTask().then(() => answers.map(answer => (typeof answer === 'function' ? answer() : answer))); + } + + /** Ends every handle the connection started, and refuses every request after it. Closing again does nothing. */ + close() { + if (this.#isClosed) { + return; + } + + this.#isClosed = true; + + for (const handle of [...this.#handles.values()]) { + this.#end(handle); + } + + const closed = NexoError.evaluation('DOMQL5027', 'The connection is closed, and delivers nothing more', {}); + + this.#queue.splice(0).forEach(({ failed }) => failed(closed)); + } + + /** The answer to one request: final, or a function that answers once the task has ended. */ + #carryOut(request) { + try { + if (this.#isClosed) { + throw NexoError.evaluation('DOMQL5027', 'The connection is closed, and carries out no request', {}); + } + + if (request === null || typeof request !== 'object' || !REQUESTS.has(request.request)) { + throw NexoError.structure('DOMQL2023', `A request names what it asks for, as request: 'watch', and this one names ${JSON.stringify(request?.request ?? null)}`, {}); + } + + if (STARTING.has(request.request)) { + this.#refuseHandleId(request.handle); + } + + switch (request.request) { + case 'evaluate': { + const query = this.#queryOf(request); + const owner = this.#ownerOf(request); + + return this.#settleLater(request.handle, owner, () => query.evaluateAsync({ owner, window: this.#window })); + } + case 'execute': { + const query = this.#queryOf(request); + const owner = this.#ownerOf(request); + + return this.#settleLater(request.handle, owner, () => query.executeAsync({ owner, window: this.#window })); + } + case 'load': + return this.#settleLater(request.handle, this.#ownerOf(request), () => this.#domql.loadModulesAsync(request.modules)); + case 'watch': + return this.#watch(request); + case 'subscribe': + return this.#subscribe(request); + case 'run': + return this.#run(request); + case 'update': + return this.#update(request); + case 'refresh': + return this.#refresh(request); + case 'dispose': + return this.#dispose(request); + default: + return this.#release(request); + } + } catch (error) { + return { error: Connection.#errorOf(error) }; + } + } + + /** Starts a handle of the owner whose operation answers a promise, answered by its value where the task settles it, and otherwise pending, its result delivered once it settles. */ + #settleLater(id, owner, operate) { + const handle = { id, kind: 'settling', owner, generation: 0 }; + let outcome = null; + + this.#handles.set(id, handle); + + Promise.resolve().then(operate).then(value => { outcome = { value: value ?? null }; }, error => { outcome = { error: Connection.#errorOf(error) }; }).then(() => { + if (this.#handles.get(id) !== handle) { + return; + } + + if (handle.isAnswered) { + this.#enqueue({ handle: id, ...outcome }); + } + + this.#handles.delete(id); + }); + + return () => { + handle.isAnswered = true; + + return outcome ?? { pending: true }; + }; + } + + /** Starts a watch of live state, whose first snapshot answers the request where the task gave it one, and whose every later change is delivered, paced by the acknowledgment of the one before it. */ + #watch(request) { + const handle = { id: request.handle, kind: 'watch', owner: this.#ownerOf(request), generation: Connection.#generationOf(request), request, watch: null, isAnswered: false, isWholeNext: false, isSuspended: false, unacknowledged: 0, waiting: [] }; + + this.#startWatch(handle, request); + this.#handles.set(handle.id, handle); + + return () => this.#baselineOf(handle); + } + + /** Starts the handle's watch with the request's query, bindings and options, listening to its changes. */ + #startWatch(handle, request) { + const options = Connection.#pick(request.options, WATCH_OPTIONS); + const watch = this.#queryOf(request).watch({ ...options, updateStrategy: 'liveState', owner: handle.owner, window: this.#window }); + + handle.watch = watch; + handle.isAnswered = false; + watch.subscribe('change', (sender, args) => this.#changed(handle, watch, args)); + } + + /** + * The answer a watch request or update is given as its task ends: the snapshot it has; or pending, its first snapshot delivered whole, with the failure of its first evaluation where that failed, since the watch + * runs on and a later evaluation may succeed. A request refused answers `{ error }` alone, and starts no handle. + */ + #baselineOf(handle) { + handle.isAnswered = true; + handle.waiting = []; + + if (handle.watch.status === 'ready') { + return { snapshot: handle.watch.snapshot }; + } + + handle.isWholeNext = true; + + return handle.watch.status === 'failed' ? { pending: true, error: Connection.#errorOf(handle.watch.error) } : { pending: true }; + } + + /** A watch's change or failure: nothing before its request is answered, whose answer holds the snapshot then current, and afterwards a delivery, joined to the one waiting where one waits. */ + #changed(handle, watch, args) { + if (handle.watch !== watch || !handle.isAnswered) { + return; + } + + if (args.status === 'failed') { + this.#paced(handle, { error: Connection.#errorOf(args.error) }); + + return; + } + + if (handle.isWholeNext) { + handle.isWholeNext = false; + this.#paced(handle, { snapshot: args.snapshot }); + + return; + } + + if (args.changes.length > 0) { + this.#paced(handle, { changes: args.changes, snapshot: args.snapshot }); + } + } + + /** + * Sends a watch's delivery where none of its own is unacknowledged, and otherwise keeps it waiting, joined to those waiting already: a change set to the one before it, concatenated, as change sets compose, unless + * the snapshot whole is shorter; a snapshot whole in place of all that waits, which it brings the host's copy past; and a failure after what came before it, in place of a failure waiting last. So the host hears a + * watch's deliveries in the order they happened, every one it waits for joined in one batch. A watch whose delivery the host rejected waits until it is refreshed. + */ + #paced(handle, delivery) { + const { waiting } = handle; + const last = waiting.at(-1); + + if (delivery.snapshot !== undefined && delivery.changes === undefined) { + waiting.splice(0, waiting.length, delivery); + } else if (delivery.error !== undefined && last?.error !== undefined) { + waiting[waiting.length - 1] = delivery; + } else if (delivery.changes !== undefined && last?.changes !== undefined) { + const changes = [...last.changes, ...delivery.changes]; + + waiting[waiting.length - 1] = JSON.stringify(changes).length > JSON.stringify(delivery.snapshot).length ? { snapshot: delivery.snapshot } : { changes, snapshot: delivery.snapshot }; + } else { + waiting.push(delivery); + } + + if (handle.unacknowledged === 0 && !handle.isSuspended) { + this.#sendWaiting(handle); + } + } + + /** Queues every delivery waiting of a watch, in order, each holding its change set, its snapshot or its failure, and the watch's own unacknowledged until the host settles them. */ + #sendWaiting(handle) { + const deliveries = handle.waiting.splice(0); + + handle.unacknowledged += deliveries.length; + + for (const { changes, snapshot, error } of deliveries) { + const sent = { handle: handle.id, generation: handle.generation, ...(changes !== undefined ? { changes } : error !== undefined ? { error } : { snapshot }) }; + + this.#enqueue(sent, () => this.#acknowledged(handle), () => { + handle.isSuspended = true; + this.#acknowledged(handle); + }); + } + } + + /** One of a watch's deliveries settled; once the last has, what waited since is sent, unless the host rejected one, or the watch has ended. */ + #acknowledged(handle) { + handle.unacknowledged -= 1; + + if (handle.unacknowledged === 0 && !handle.isSuspended && handle.waiting.length > 0 && this.#handles.get(handle.id) === handle) { + this.#sendWaiting(handle); + } + } + + /** Subscribes to an event source, each event delivered as it happens, never waiting for another, and answered with what the host answers it. */ + #subscribe(request) { + const handle = { id: request.handle, kind: 'subscription', owner: this.#ownerOf(request), generation: Connection.#generationOf(request), request, listener: null }; + + this.#startSubscription(handle, request); + this.#handles.set(handle.id, handle); + + return {}; + } + + /** Starts the handle's subscription with the request's query, bindings and options, its reactions made as the connection makes a query. */ + #startSubscription(handle, request) { + const { reactions, ...options } = Connection.#pick(request.options, SUBSCRIBE_OPTIONS); + const made = reactions === undefined ? {} : { reactions: Array.isArray(reactions) ? reactions.map(reaction => this.#queryOf(reaction)) : reactions }; + + handle.listener = this.#queryOf(request).subscribe((sender, args) => this.#occurred(handle, args), { ...options, ...made, owner: handle.owner, window: this.#window }); + } + + /** An event of a subscription, or its failure: delivered at once, and answered with the host's answer, which settles the event's acknowledgment. */ + #occurred(handle, args) { + const delivery = args.status === 'ready' ? { handle: handle.id, generation: handle.generation, event: args.value } : { handle: handle.id, generation: handle.generation, error: Connection.#errorOf(args.error) }; + + return new Promise((resolve, reject) => this.#enqueue(delivery, answer => resolve(answer ?? undefined), reject)); + } + + /** Runs a continuous execution, each failure it reports delivered as it happens. */ + #run(request) { + const handle = { id: request.handle, kind: 'execution', owner: this.#ownerOf(request), generation: Connection.#generationOf(request), execution: null }; + + handle.execution = this.#queryOf(request).run({ owner: handle.owner, window: this.#window }); + handle.execution.subscribe('error', (sender, { error }) => this.#enqueue({ handle: handle.id, generation: handle.generation, error: Connection.#errorOf(error) })); + this.#handles.set(handle.id, handle); + + return {}; + } + + /** + * Binds a handle anew, at the generation the request gives: an execution updated in place; a watch started again with the new bindings, its answer as a watch request's; and a subscription started again. Deliveries + * the handle made before carry the generation before it. + */ + #update(request) { + const handle = this.#getHandle(request.handle, ['watch', 'subscription', 'execution']); + + if (handle.kind === 'execution') { + handle.execution.update(this.#bindingsOf(request)); + handle.generation = Connection.#generationOf(request, handle.generation); + + return {}; + } + + const next = { ...handle.request, query: handle.request.query, bindings: request.bindings ?? {}, ...(request.options === undefined ? {} : { options: request.options }) }; + + if (handle.kind === 'subscription') { + const listener = handle.listener; + + this.#startSubscription(handle, next); + listener.dispose(); + handle.request = next; + handle.generation = Connection.#generationOf(request, handle.generation); + + return {}; + } + + const watch = handle.watch; + + this.#startWatch(handle, next); + watch.dispose(); + handle.isSuspended = false; + handle.request = next; + handle.generation = Connection.#generationOf(request, handle.generation); + handle.waiting = []; + + return () => this.#baselineOf(handle); + } + + /** + * Evaluates a watch now, or every watch the connection runs where the request names none, and delivers its snapshot whole once it has, changed or not, so a host that lost track of its copy has it again. A watch whose + * delivery the host rejected delivers again from it. + */ + #refresh(request) { + const watches = request.handle === undefined ? [...this.#handles.values()].filter(handle => handle.kind === 'watch') : [this.#getHandle(request.handle, ['watch'])]; + + for (const handle of watches) { + const { watch } = handle; + + if (request.handle !== undefined) { + handle.generation = Connection.#generationOf(request, handle.generation); + } + + handle.isWholeNext = true; + handle.isSuspended = false; + handle.waiting = []; + watch.refreshAsync({ resample: request.resample === true }).then(() => { + // A refresh whose result is unchanged raises no change, so the snapshot it settled on is delivered whole. + if (handle.watch === watch && handle.isWholeNext && watch.status === 'ready') { + handle.isWholeNext = false; + this.#paced(handle, { snapshot: watch.snapshot }); + } + }, error => { + // A failed evaluation raises its change, which delivered the failure already; a refresh that failed otherwise delivers its own. + if (handle.watch === watch && !(watch.status === 'failed' && watch.error === error)) { + this.#paced(handle, { error: Connection.#errorOf(error) }); + } + }); + } + + return {}; + } + + /** Ends a handle; one already ended, or never started, is ended already. */ + #dispose(request) { + const handle = this.#handles.get(request.handle); + + if (handle !== undefined) { + this.#end(handle); + } + + return {}; + } + + /** Ends every handle of the owner the request names. */ + #release(request) { + const owner = this.#ownerOf(request); + + for (const handle of [...this.#handles.values()].filter(candidate => candidate.owner === owner)) { + this.#end(handle); + } + + return {}; + } + + /** Ends a handle: its watch, subscription or execution disposed, and nothing more delivered of it. */ + #end(handle) { + this.#handles.delete(handle.id); + handle.waiting = []; + handle.watch?.dispose(); + handle.listener?.dispose(); + handle.execution?.dispose(); + } + + /** Queues a delivery of the current task, sent with the others of the task as it ends; `settled` hears the host's answer to it, and `failed` its rejection. */ + #enqueue(delivery, settled = () => {}, failed = () => {}) { + if (this.#isClosed) { + failed(NexoError.evaluation('DOMQL5027', 'The connection is closed, and delivers nothing more', {})); + + return; + } + + this.#queue.push({ delivery, settled, failed }); + + if (!this.#isFlushScheduled) { + this.#isFlushScheduled = true; + queueMicrotask(() => this.#flush()); + } + } + + /** Sends the task's deliveries to the host, together, in the order they happened. */ + #flush() { + this.#isFlushScheduled = false; + + const entries = this.#queue.splice(0); + + if (entries.length === 0 || this.#isClosed) { + return; + } + + if (this.#outstanding >= OUTSTANDING_LIMIT) { + const error = NexoError.evaluation('DOMQL5026', `The host has acknowledged none of the last ${OUTSTANDING_LIMIT} deliveries, so the connection closes rather than hold more`, {}); + + entries.forEach(({ failed }) => failed(error)); + this.close(); + this.#reportError(error); + + return; + } + + this.#outstanding += entries.length; + + let answered; + + try { + answered = Promise.resolve(this.#deliver(entries.map(({ delivery }) => delivery))); + } catch (error) { + answered = Promise.reject(error); + } + + answered.then(answers => { + this.#outstanding -= entries.length; + entries.forEach(({ settled }, index) => settled(Array.isArray(answers) ? answers[index] : undefined)); + }, error => { + this.#outstanding -= entries.length; + entries.forEach(({ failed }) => failed(error)); + }); + } + + /** Reports a failure that belongs to no handle to the window. */ + #reportError(error) { + try { + (this.#window?.reportError ?? (failure => console.error(failure)))(error); + } catch { + // A reporter failure ends nowhere else. + } + } + + /** Settles once the current task has ended, a message posted to a channel running after its microtasks; without a channel, a timer does. */ + #afterTask() { + const Channel = this.#window?.MessageChannel ?? globalThis.MessageChannel; + + if (Channel === undefined) { + return new Promise(resolve => setTimeout(resolve, 0)); + } + + return new Promise(resolve => { + const channel = new Channel(); + + channel.port1.onmessage = () => { + channel.port1.close(); + resolve(); + }; + channel.port2.postMessage(null); + }); + } + + /** The query a request names, bound to its bindings: one its key names, made by an earlier request, or one it makes from its text or its definition and keeps by its key. */ + #queryOf(request) { + const { query } = request; + let made; + + if (typeof query === 'string' || typeof query === 'number') { + made = this.#queries.get(query); + + if (made === undefined) { + throw NexoError.structure('DOMQL2024', `No request of this connection made the query ${JSON.stringify(query)}; the first request of a query gives its text or its definition beside its key`, {}); + } + } else if (query !== null && typeof query === 'object' && (typeof query.key === 'string' || typeof query.key === 'number')) { + made = this.#queries.get(query.key); + + if (made === undefined) { + const options = Connection.#pick(query, ['types', 'manifest']); + + made = this.#domql.query(query.text ?? query.definition, {}, options); + this.#queries.set(query.key, made); + } + } else { + throw NexoError.structure('DOMQL2024', 'A request names its query by the key an earlier request gave it, or gives it as { key, text } or { key, definition }', {}); + } + + return made.with(this.#bindingsOf(request)); + } + + /** The bindings a request gives, none where it gives none. */ + #bindingsOf(request) { + return request.bindings ?? {}; + } + + /** The owner a request names: a string, a number or null, which a release names again; any other is refused, since a host's message holds no object twice. */ + #ownerOf(request) { + const owner = request.owner ?? null; + + if (owner !== null && typeof owner !== 'string' && typeof owner !== 'number') { + throw NexoError.structure('DOMQL2025', 'A request names its owner as a string, a number or null, which a release names again', {}); + } + + return owner; + } + + /** Refuses a handle id that is no string or number, or that names a handle still running. */ + #refuseHandleId(id) { + if (typeof id !== 'string' && typeof id !== 'number') { + throw NexoError.structure('DOMQL2025', 'A request that starts a handle names it, as handle: 1, by a string or a number', {}); + } + + if (this.#handles.has(id)) { + throw NexoError.structure('DOMQL2025', `The handle ${JSON.stringify(id)} runs already; a request names a new handle by an id of its own`, {}); + } + } + + /** The handle a request names, of one of the kinds given; one that isn't running is refused. */ + #getHandle(id, kinds) { + const handle = this.#handles.get(id); + + if (handle === undefined || !kinds.includes(handle.kind)) { + throw NexoError.structure('DOMQL2025', `No ${kinds.join(' or ')} of this connection runs as the handle ${JSON.stringify(id ?? null)}`, {}); + } + + return handle; + } + + /** The generation a request gives, a whole number; the one the handle had where it gives none. */ + static #generationOf(request, current = 0) { + return Number.isInteger(request.generation) ? request.generation : current; + } + + /** The keys given of an object, those it holds alone. */ + static #pick(source, keys) { + return source === null || typeof source !== 'object' ? {} : Object.fromEntries(keys.filter(key => Object.hasOwn(source, key)).map(key => [key, source[key]])); + } + + /** A failure as a host reads it: its code, kind, message and location where DOMQL or Nexo made it, its message alone otherwise. */ + static #errorOf(error) { + if (error instanceof NexoError) { + return { code: error.code, kind: error.kind, message: error.message, location: error.location ?? {} }; + } + + return { message: error?.message ?? String(error) }; + } +} diff --git a/src/domql.d.ts b/src/domql.d.ts index 3b003b3..beb1aea 100644 --- a/src/domql.d.ts +++ b/src/domql.d.ts @@ -765,6 +765,75 @@ export interface DomqlPrepareOptions { readonly scripts?: readonly DomqlQueryToPrepare[]; } +/** A query a connection's request names: by the key an earlier request gave it, or as its text or its definition beside the key it goes by from then on. */ +export type DomqlConnectionQuery = + | string + | number + | { readonly key: string | number; readonly text: string; readonly types?: Readonly>; readonly manifest?: NexoManifest | null } + | { readonly key: string | number; readonly definition: DomqlDefinition; readonly types?: Readonly>; readonly manifest?: NexoManifest | null }; + +/** What every request that names a handle gives: the handle, its owner, and the generation it is at. */ +interface DomqlHandleRequest { + /** The handle's id, a string or a number unique among the connection's running handles. */ + readonly handle: string | number; + /** Who carries it out: a string, a number or null, which a release names again. */ + readonly owner?: string | number | null; + /** The generation its deliveries carry, which a host drops a delivery of an earlier one by. */ + readonly generation?: number; +} + +/** A request a host sends a connection, in a batch. */ +export type DomqlConnectionRequest = + | (DomqlHandleRequest & { readonly request: 'evaluate' | 'execute'; readonly query: DomqlConnectionQuery; readonly bindings?: DomqlBindings }) + | (DomqlHandleRequest & { readonly request: 'watch'; readonly query: DomqlConnectionQuery; readonly bindings?: DomqlBindings; readonly options?: { readonly schedule?: 'frame' | 'immediate' | 'delayed'; readonly delay?: number; readonly reportOn?: readonly (readonly DomqlPathItem[])[]; readonly acceptPartialObservation?: boolean } }) + | (DomqlHandleRequest & { readonly request: 'subscribe'; readonly query: DomqlConnectionQuery; readonly bindings?: DomqlBindings; readonly options?: { readonly throttle?: number; readonly reactions?: readonly { readonly query: DomqlConnectionQuery; readonly bindings?: DomqlBindings }[] } }) + | (DomqlHandleRequest & { readonly request: 'run'; readonly query: DomqlConnectionQuery; readonly bindings?: DomqlBindings }) + | (DomqlHandleRequest & { readonly request: 'load'; readonly modules: readonly string[] }) + | (DomqlHandleRequest & { readonly request: 'update'; readonly bindings?: DomqlBindings; readonly options?: object }) + | { readonly request: 'refresh'; readonly handle?: string | number; readonly generation?: number; readonly resample?: boolean } + | { readonly request: 'dispose'; readonly handle: string | number } + | { readonly request: 'release'; readonly owner: string | number | null }; + +/** A failure as a connection carries it: the code, kind, message and location of one DOMQL or Nexo made, the message alone of any other. */ +export interface DomqlConnectionError { + readonly code?: string; + readonly kind?: string; + readonly message: string; + readonly location?: NexoLocation; +} + +/** + * A request's answer, as its batch's task ends: a watch's snapshot; an evaluation's or an execution's value; pending, its result delivered once it settles, with the failure of a watch's first evaluation + * where that failed; a refusal, which starts no handle; or nothing more to say. + */ +export type DomqlConnectionAnswer = + | { readonly snapshot: unknown } + | { readonly value: unknown } + | { readonly pending: true; readonly error?: DomqlConnectionError } + | { readonly error: DomqlConnectionError } + | Record; + +/** + * A delivery a connection sends its host, of one handle: a watch's snapshot whole, or the change set from the one before it; a subscription's event; the value an answer left pending; or a failure. A watch's + * deliveries carry the generation they were made at. + */ +export type DomqlConnectionDelivery = + | { readonly handle: string | number; readonly generation: number; readonly snapshot: unknown } + | { readonly handle: string | number; readonly generation: number; readonly changes: readonly DomqlChangeOperation[] } + | { readonly handle: string | number; readonly generation: number; readonly event: unknown } + | { readonly handle: string | number; readonly value: unknown } + | { readonly handle: string | number; readonly generation?: number; readonly error: DomqlConnectionError }; + +/** A connection: this instance's operations carried across a boundary as messages, for a host whose code runs elsewhere. */ +export interface DomqlConnection { + /** Whether it has closed, by `close`, or as its host acknowledged none of the deliveries its limit holds. */ + readonly isClosed: boolean; + /** Carries out the requests in order, and answers a promise of their answers, in order, once the task that carried them out has ended. */ + requestAsync(requests: readonly DomqlConnectionRequest[]): Promise; + /** Ends every handle it started, and refuses every request after it. */ + close(): void; +} + /** The versions DOMQL reports, which change apart. */ export interface DomqlVersions { /** The DOMQL runtime release version, which the package and the bundle carry. */ @@ -820,6 +889,11 @@ export interface Domql { * list names. A load already under way is shared. */ loadModulesAsync(modules: DomqlQuery | DomqlDefinition | string | readonly string[]): Promise; + /** + * Opens a connection that carries this instance's operations across a boundary as messages: the requests a host sends, in batches, and the deliveries `deliver` receives, those of one task together, whose + * promise answers one answer for each, an event's the host's answer to it, and settles once the host has applied them. A watch's next delivery waits for that; an event never waits. + */ + connect(deliver: (deliveries: readonly DomqlConnectionDelivery[]) => Promise, options?: { readonly window?: Window }): DomqlConnection; } export declare const domql: Domql; diff --git a/src/domql.js b/src/domql.js index 09bc112..ff00b54 100644 --- a/src/domql.js +++ b/src/domql.js @@ -5,6 +5,7 @@ import { SnapshotComparer } from './snapshots/SnapshotComparer.mjs'; import { Behaviors } from './dom/Behaviors.mjs'; +import { Connection } from './connections/Connection.mjs'; import { BrowserModule } from './dom/BrowserModule.mjs'; import { DomqlQuery } from './dom/DomqlQuery.mjs'; import { ExecutionHandle } from './dom/ExecutionHandle.mjs'; @@ -1097,6 +1098,18 @@ class Domql { } } +/** + * Opens a connection that carries this instance's operations across a boundary as messages: the requests a host sends, and the deliveries `deliver` receives, each batch's promise settling once the host has applied it. + * A `deliver` that is no function is refused. + */ +const connect = (deliver, options) => { + if (typeof deliver !== 'function') { + throw NexoError.structure('DOMQL2022', 'A connection delivers through the function it is given, deliver(deliveries), which answers a promise that settles once the host has applied them', {}); + } + + return new Connection(domql, deliver, options ?? undefined); +}; + /** The options a query takes, which an operation run directly is given beside its own. */ const QUERY_OPTIONS = ['types', 'manifest']; @@ -1148,6 +1161,7 @@ export const domql = Object.freeze({ registerModule: (module, options) => Domql.registerModule(module, options), registerModuleLoader: (name, load, options) => Domql.registerModuleLoader(name, load, options), loadModulesAsync: modules => Domql.loadModulesAsync(modules), + connect: (deliver, options) => connect(deliver, options), info: Object.freeze({ versions: Object.freeze({ runtime: Versions.runtime, specification: Versions.specification, language: Versions.language }) }), }); diff --git a/tests/DocumentExamples.test.js b/tests/DocumentExamples.test.js index b10b8cb..a0234d1 100644 --- a/tests/DocumentExamples.test.js +++ b/tests/DocumentExamples.test.js @@ -115,6 +115,8 @@ const DOCUMENTS = { 'spec/executions.md': [], 'spec/behaviors.md': [], 'spec/api.md': [], + 'spec/connections.md': [], + 'spec/dotnet.md': [], 'spec/examples.md': [ { about: 'a complete query' }, ], diff --git a/tests/_conformance/change-sets.json b/tests/_conformance/change-sets.json new file mode 100644 index 0000000..c970053 --- /dev/null +++ b/tests/_conformance/change-sets.json @@ -0,0 +1,137 @@ +[ + { + "name": "replaces a field", + "previous": { "count": 1, "label": "a" }, + "changes": [{ "op": "replace", "path": "/count", "value": 2 }], + "result": { "count": 2, "label": "a" } + }, + { + "name": "replaces the whole result", + "previous": { "count": 1 }, + "changes": [{ "op": "replace", "path": "", "value": { "count": 2, "label": "b" } }], + "result": { "count": 2, "label": "b" } + }, + { + "name": "replaces a nested field with null", + "previous": { "panel": { "size": { "inline": 640, "block": 480 }, "hasFocus": false } }, + "changes": [{ "op": "replace", "path": "/panel/size", "value": null }], + "result": { "panel": { "size": null, "hasFocus": false } } + }, + { + "name": "replaces a null with an object", + "previous": { "panel": { "size": null } }, + "changes": [{ "op": "replace", "path": "/panel/size", "value": { "inline": 10, "block": 20 } }], + "result": { "panel": { "size": { "inline": 10, "block": 20 } } } + }, + { + "name": "adds an item inside a list", + "previous": { "items": [{ "key": "a1" }, { "key": "a3" }] }, + "changes": [{ "op": "add", "path": "/items/1", "value": { "key": "a2" } }], + "result": { "items": [{ "key": "a1" }, { "key": "a2" }, { "key": "a3" }] } + }, + { + "name": "adds an item at a list's end, by its length", + "previous": { "items": [{ "key": "a1" }] }, + "changes": [{ "op": "add", "path": "/items/1", "value": { "key": "a2" } }], + "result": { "items": [{ "key": "a1" }, { "key": "a2" }] } + }, + { + "name": "adds an item to an empty list", + "previous": { "items": [] }, + "changes": [{ "op": "add", "path": "/items/0", "value": 7 }], + "result": { "items": [7] } + }, + { + "name": "removes an item", + "previous": { "items": [{ "key": "a1" }, { "key": "a2" }, { "key": "a3" }] }, + "changes": [{ "op": "remove", "path": "/items/0" }], + "result": { "items": [{ "key": "a2" }, { "key": "a3" }] } + }, + { + "name": "moves an item forward, its path read once the item has left", + "previous": { "items": [{ "key": "a1" }, { "key": "a2" }, { "key": "a3" }] }, + "changes": [{ "op": "move", "from": "/items/0", "path": "/items/2" }], + "result": { "items": [{ "key": "a2" }, { "key": "a3" }, { "key": "a1" }] } + }, + { + "name": "moves an item back", + "previous": { "items": [{ "key": "a1" }, { "key": "a2" }, { "key": "a3" }] }, + "changes": [{ "op": "move", "from": "/items/2", "path": "/items/0" }], + "result": { "items": [{ "key": "a3" }, { "key": "a1" }, { "key": "a2" }] } + }, + { + "name": "changes inside an item where a move left it", + "previous": { "items": [{ "key": "a1", "selected": false }, { "key": "a2", "selected": false }] }, + "changes": [ + { "op": "move", "from": "/items/0", "path": "/items/1" }, + { "op": "replace", "path": "/items/1/selected", "value": true } + ], + "result": { "items": [{ "key": "a2", "selected": false }, { "key": "a1", "selected": true }] } + }, + { + "name": "removes, adds and moves in one change set, each where the one before left the list", + "previous": { "items": [{ "key": "a" }, { "key": "b" }, { "key": "c" }, { "key": "d" }] }, + "changes": [ + { "op": "remove", "path": "/items/1" }, + { "op": "add", "path": "/items/0", "value": { "key": "e" } }, + { "op": "move", "from": "/items/3", "path": "/items/1" } + ], + "result": { "items": [{ "key": "e" }, { "key": "d" }, { "key": "a" }, { "key": "c" }] } + }, + { + "name": "reads escaped tokens, ~1 as / and ~0 as ~", + "previous": { "a/b": { "m~n": 1 } }, + "changes": [{ "op": "replace", "path": "/a~1b/m~0n", "value": 2 }], + "result": { "a/b": { "m~n": 2 } } + }, + { + "name": "reads ~01 as ~1, unescaping ~1 first", + "previous": { "~1": 1 }, + "changes": [{ "op": "replace", "path": "/~01", "value": 2 }], + "result": { "~1": 2 } + }, + { + "name": "replaces an item of a list of lists", + "previous": { "rows": [[1, 2], [3, 4]] }, + "changes": [{ "op": "replace", "path": "/rows/1/0", "value": 5 }], + "result": { "rows": [[1, 2], [5, 4]] } + }, + { + "name": "replaces a list whole", + "previous": { "items": [1, 2, 3] }, + "changes": [{ "op": "replace", "path": "/items", "value": [4] }], + "result": { "items": [4] } + }, + { + "name": "changes a result that is a list", + "previous": [{ "key": "a1" }, { "key": "a2" }], + "changes": [ + { "op": "remove", "path": "/0" }, + { "op": "add", "path": "/1", "value": { "key": "a3" } } + ], + "result": [{ "key": "a2" }, { "key": "a3" }] + }, + { + "name": "applies two change sets concatenated, as a host joins those of consecutive events", + "previous": { "items": [{ "key": "a1" }, { "key": "a2" }], "count": 2 }, + "changes": [ + { "op": "add", "path": "/items/2", "value": { "key": "a3" } }, + { "op": "replace", "path": "/count", "value": 3 }, + { "op": "move", "from": "/items/2", "path": "/items/0" }, + { "op": "remove", "path": "/items/2" }, + { "op": "replace", "path": "/count", "value": 2 } + ], + "result": { "items": [{ "key": "a3" }, { "key": "a1" }], "count": 2 } + }, + { + "name": "keeps numbers, Booleans, strings and nulls as they are", + "previous": { "values": [0, false, "", null] }, + "changes": [ + { "op": "replace", "path": "/values/0", "value": -1.5 }, + { "op": "replace", "path": "/values/1", "value": true }, + { "op": "replace", "path": "/values/2", "value": "é ☃" }, + { "op": "replace", "path": "/values/3", "value": { "nested": [null] } } + ], + "result": { "values": [-1.5, true, "é ☃", { "nested": [null] }] } + } +] diff --git a/tests/_types/usage.ts b/tests/_types/usage.ts index 6332bf5..a0ec59b 100644 --- a/tests/_types/usage.ts +++ b/tests/_types/usage.ts @@ -1,6 +1,6 @@ // How a TypeScript caller uses DOMQL, which the declarations must accept; the test compiles this file. import { domql, NexoError } from '../../src/domql.js'; -import type { DomqlEventArgs, DomqlSubscribeOptions, DomqlFrameOptions, DomqlFrameRequest, DomqlHeldObservation, DomqlMeasureOptions, DomqlChangeOperation, DomqlOperatorImplementationInput, DomqlTypeDeclaration, DomqlDefinition, DomqlDefinitionNode, DomqlEvaluateAsyncOptions, DomqlEventListener, DomqlExecutionHandle, DomqlLiveStateWatch, DomqlLiveStateWatchOptions, DomqlManifestOptions, DomqlMemberDeclaration, DomqlModule, DomqlModuleContents, DomqlPrepareOptions, DomqlOperationOptions, DomqlQuery, DomqlQueryOptions, DomqlReadOnly, DomqlResolvedDefinition, DomqlResultArgs, DomqlSelectedView, DomqlSelection, DomqlWatch, DomqlWatchOptions, NexoManifest } from '../../src/domql.js'; +import type { DomqlEventArgs, DomqlSubscribeOptions, DomqlFrameOptions, DomqlFrameRequest, DomqlHeldObservation, DomqlMeasureOptions, DomqlChangeOperation, DomqlOperatorImplementationInput, DomqlTypeDeclaration, DomqlDefinition, DomqlDefinitionNode, DomqlEvaluateAsyncOptions, DomqlEventListener, DomqlExecutionHandle, DomqlLiveStateWatch, DomqlLiveStateWatchOptions, DomqlManifestOptions, DomqlMemberDeclaration, DomqlModule, DomqlModuleContents, DomqlPrepareOptions, DomqlOperationOptions, DomqlQuery, DomqlQueryOptions, DomqlReadOnly, DomqlResolvedDefinition, DomqlResultArgs, DomqlSelectedView, DomqlSelection, DomqlWatch, DomqlWatchOptions, NexoManifest, DomqlConnection, DomqlConnectionAnswer, DomqlConnectionDelivery, DomqlConnectionRequest } from '../../src/domql.js'; const panel = document.createElement('div'); const controller = new AbortController(); @@ -538,3 +538,23 @@ const last: DomqlDefinitionNode = { kind: 'indexerAccess', receiver: { kind: 'lo const imported: DomqlDefinition = { version: 38, imports: [{ module: 'Domql' }], expression: { kind: 'memberAccess', receiver: { kind: 'namespace', name: 'Domql' }, name: 'document' } }; export { routing, following, painting, styled, trapped, counting, drops, destinations, dropZone, release, owned, released, ownedCount, ownedWatch, bound, version, specificationVersion, languageVersion, formatted, formattedText, kind, typeText, count, anything, waited, shorthand, selected, selectedAsync, selectedWatch, key, listening, status, snapshot, failure, ready, refreshed, viewed, viewStatus, viewReady, smaller, held, livingSnapshot, livingReady, livingRefreshed, watchedAgain, keptAgain, clicking, source, moved, stepped, trapping, reported }; + +// A host across a boundary connects, sends its requests in batches, and applies each batch of deliveries, answering an event with its own answer. +const connection: DomqlConnection = domql.connect(async (deliveries: readonly DomqlConnectionDelivery[]) => deliveries.map(delivery => ('event' in delivery ? 'answered' : null))); +const requests: DomqlConnectionRequest[] = [ + { request: 'watch', handle: 1, owner: 'panel', query: { key: 'size', text: 'panel.layoutSize' }, bindings: { panel }, options: { schedule: 'immediate' } }, + { request: 'subscribe', handle: 2, owner: 'panel', query: { key: 'clicks', text: 'panel.on("click")' }, bindings: { panel }, options: { throttle: 16 } }, + { request: 'update', handle: 1, generation: 1, bindings: { panel: document.body } }, + { request: 'refresh' }, + { request: 'release', owner: 'panel' }, +]; +const connectionAnswers: Promise = connection.requestAsync(requests); +const isClosed: boolean = connection.isClosed; + +connection.close(); + +// @ts-expect-error A request names what it asks for, among those a connection carries out. +connection.requestAsync([{ request: 'copy', handle: 3 }]); + +// @ts-expect-error A connection delivers through a function. +domql.connect('deliver'); diff --git a/tests/connections/Connection.test.js b/tests/connections/Connection.test.js new file mode 100644 index 0000000..8f07dd6 --- /dev/null +++ b/tests/connections/Connection.test.js @@ -0,0 +1,397 @@ +import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest'; + +/** The error a call throws. */ +const getError = call => { + try { + call(); + } catch (error) { + return error; + } + + throw new Error('The call threw nothing'); +}; + +/** Settles once the current task and those it queued at once have run: a mutation observed, a watch evaluated, its delivery flushed. */ +const nextTask = () => new Promise(resolve => setTimeout(resolve, 0)); + +describe('a connection', () => { + // Each test loads its own copy of DOMQL, with a registry of its own. + let isolated; + let panel; + let presses; + let finish; + let marks; + let host; + + /** + * A module of an event source answered with a String?, `presses()`, whose deliver the tests keep; a property, `fragile`, that fails while its element is marked broken; a once execution, `later()`, that settles as the tests finish it; and a continuous execution, `mark(tone)`, + * whose instances the tests keep. + */ + const deskModule = () => isolated.createModule('Desk', { + types: [{ + name: 'DeskElements', kind: 'extension', target: 'Domql.Element', + members: [ + { + name: 'presses', kind: 'function', invokedBy: 'host', requestKind: 'subscription', result: 'Number', answers: 'String?', + impl: ({ deliver }) => { + presses = deliver; + + return { stop: () => { presses = null; } }; + }, + }, + { + name: 'fragile', kind: 'property', result: 'Number', + updates: { changes: 'observable', reads: 'fresh', observations: [{ type: 'mutation', of: 'receiver', attributes: ['data-broken'] }] }, + impl: ({ receiver }) => { + if (receiver.hasAttribute('data-broken')) { + throw new Error('broken'); + } + + return 1; + }, + }, + { name: 'later', kind: 'function', invokedBy: 'host', requestKind: 'execution', executionMode: 'once', result: 'Number', impl: () => new Promise(resolve => { finish = resolve; }) }, + { + name: 'mark', kind: 'function', invokedBy: 'host', requestKind: 'execution', executionMode: 'continuous', arguments: 'positional', + parameters: [{ name: 'tone', kind: 'value', type: 'String', required: true }], + impl: ({ args: { tone }, env, reportError }) => { + const instance = { tone, owner: env.owner, isDisposed: false, reportError, update: (receiver, next) => { instance.tone = next.tone; }, dispose: () => { instance.isDisposed = true; } }; + + marks.push(instance); + + return instance; + }, + }, + ], + }], + }); + + /** + * A host: the connection it opened, the batches of deliveries it received, in order, and what settles each, its answers given or one null for each delivery; a batch it rejects rejects its promise. + */ + const openHost = () => { + const batches = []; + const settlers = []; + const connection = isolated.connect(deliveries => new Promise((resolve, reject) => { + batches.push(deliveries); + settlers.push({ resolve: answers => resolve(answers ?? deliveries.map(() => null)), reject }); + }), { window }); + + return { connection, batches, settle: (index, answers) => settlers[index].resolve(answers), reject: (index, error) => settlers[index].reject(error) }; + }; + + const count = { key: 'count', text: '{ count = panel.children.count }' }; + const immediately = { schedule: 'immediate' }; + + beforeEach(async () => { + vi.resetModules(); + ({ domql: isolated } = await import('#domql/domql.js')); + document.body.innerHTML = '
'; + panel = document.getElementById('panel'); + presses = null; + finish = null; + marks = []; + isolated.registerModule(deskModule()); + host = openHost(); + }); + + afterEach(() => { + host.connection.close(); + document.body.innerHTML = ''; + }); + + it('is refused a deliver that is no function', () => { + expect(getError(() => isolated.connect('deliver'))).toMatchObject({ kind: 'structure', code: 'DOMQL2022' }); + }); + + it('answers a batch\'s requests in order once its task has ended: a watch with its snapshot, an execution and an evaluation with their values, each malformed request with its own failure', async () => { + const answers = await host.connection.requestAsync([ + { request: 'watch', handle: 1, owner: 'a', query: count, bindings: { panel }, options: immediately }, + { request: 'watch', handle: 2, owner: 'a', query: 'count', bindings: { panel }, options: immediately }, + { request: 'execute', handle: 3, owner: 'a', query: { key: 'focus', text: 'panel.focus()' }, bindings: { panel } }, + { request: 'evaluate', handle: 4, query: { key: 'n', text: 'panel.children.count' }, bindings: { panel } }, + { request: 'watch', handle: 5, query: 'unknown' }, + { request: 'copy', handle: 6 }, + { request: 'watch', handle: 1, query: 'count', bindings: { panel } }, + { request: 'watch', handle: 7, owner: { name: 'a' }, query: 'count', bindings: { panel } }, + { request: 'watch', handle: 8, query: { key: 'broken', text: 'panel {' } }, + ]); + + expect(answers.slice(0, 4)).toEqual([{ snapshot: { count: 1 } }, { snapshot: { count: 1 } }, { value: true }, { value: 1 }]); + expect(answers.slice(4).map(({ error }) => [error.code, error.kind])).toEqual([['DOMQL2024', 'structure'], ['DOMQL2023', 'structure'], ['DOMQL2025', 'structure'], ['DOMQL2025', 'structure'], ['NEXO1051', 'syntax']]); + expect(answers[8].error.location).toMatchObject({ line: 1 }); + }); + + it('sends the deliveries of one task together, in the order they happened, each watch\'s change set from the snapshot before it', async () => { + await host.connection.requestAsync([ + { request: 'watch', handle: 1, query: count, bindings: { panel }, options: immediately }, + { request: 'watch', handle: 2, query: 'count', bindings: { panel }, options: immediately }, + ]); + + panel.append(document.createElement('i')); + await nextTask(); + + expect(host.batches).toEqual([[ + { handle: 1, generation: 0, changes: [{ op: 'replace', path: '/count', value: 2 }] }, + { handle: 2, generation: 0, changes: [{ op: 'replace', path: '/count', value: 2 }] }, + ]]); + }); + + it('holds a watch\'s next delivery until the host has applied the one before it, joining the change sets meanwhile into one, or into its snapshot whole where that is shorter', async () => { + await host.connection.requestAsync([{ request: 'watch', handle: 1, query: count, bindings: { panel }, options: immediately }]); + + panel.append(document.createElement('i')); + await nextTask(); + panel.append(document.createElement('u')); + await nextTask(); + panel.append(document.createElement('s')); + await nextTask(); + + expect(host.batches).toHaveLength(1); + + host.settle(0); + await nextTask(); + + // Two replacements of the count are longer than the snapshot that holds the latest. + expect(host.batches[1]).toEqual([{ handle: 1, generation: 0, snapshot: { count: 4 } }]); + }); + + it('delivers a subscription\'s events as they happen, never behind a watch\'s, each answered with the host\'s answer, which answers the source', async () => { + await host.connection.requestAsync([ + { request: 'watch', handle: 1, query: count, bindings: { panel }, options: immediately }, + { request: 'subscribe', handle: 2, owner: 'a', query: { key: 'presses', text: 'import Desk\npanel:presses()' }, bindings: { panel } }, + ]); + + panel.append(document.createElement('i')); + await nextTask(); + + const first = presses(1); + const second = presses(2); + + await nextTask(); + + expect(host.batches.map(batch => batch.map(({ handle, event, changes }) => (event ?? changes?.length) && [handle, event ?? 'changes']))).toEqual([[[1, 'changes']], [[2, 1], [2, 2]]]); + + host.settle(1, ['one', 'two']); + + expect(await Promise.all([first, second])).toEqual(['one', 'two']); + }); + + it('answers an execution still waiting as its task ends as pending, and delivers its value once it settles', async () => { + const [answer] = await host.connection.requestAsync([{ request: 'execute', handle: 1, query: { key: 'later', text: 'import Desk\npanel:later()' }, bindings: { panel } }]); + + expect(answer).toEqual({ pending: true }); + + finish(7); + await nextTask(); + + expect(host.batches).toEqual([[{ handle: 1, value: 7 }]]); + }); + + it('answers a watch whose first evaluation fails as pending with that failure, and delivers its first success whole', async () => { + panel.setAttribute('data-broken', ''); + + const [answer] = await host.connection.requestAsync([{ request: 'watch', handle: 1, query: { key: 'fragile', text: 'import Desk\n{ value = panel:fragile }' }, bindings: { panel }, options: immediately }]); + + expect(answer).toEqual({ pending: true, error: expect.objectContaining({ kind: 'evaluation', message: expect.stringContaining('broken') }) }); + + panel.removeAttribute('data-broken'); + await nextTask(); + + expect(host.batches).toEqual([[{ handle: 1, generation: 0, snapshot: { value: 1 } }]]); + }); + + it('runs a continuous execution for its owner, updates it in place, delivers what it reports, and ends it as it is disposed', async () => { + const mark = { key: 'mark', text: 'import Desk\npanel:mark(tone)' }; + + expect(await host.connection.requestAsync([{ request: 'run', handle: 1, owner: 'a', query: mark, bindings: { panel, tone: 'warm' } }])).toEqual([{}]); + expect(marks.map(({ tone, owner }) => [tone, owner])).toEqual([['warm', 'a']]); + expect(await host.connection.requestAsync([{ request: 'update', handle: 1, generation: 1, bindings: { panel, tone: 'cold' } }])).toEqual([{}]); + expect(marks.map(({ tone }) => tone)).toEqual(['cold']); + + marks[0].reportError(new Error('out of ink')); + await nextTask(); + + // A failure the execution reports is its own, so it crosses as its message alone. + expect(host.batches).toEqual([[{ handle: 1, generation: 1, error: { message: 'out of ink' } }]]); + expect(await host.connection.requestAsync([{ request: 'dispose', handle: 1 }])).toEqual([{}]); + expect(marks[0].isDisposed).toBe(true); + }); + + it('watches anew with an update\'s bindings, its snapshot the answer and its deliveries at the update\'s generation', async () => { + const other = document.createElement('div'); + + other.append(document.createElement('b'), document.createElement('b')); + document.body.append(other); + await host.connection.requestAsync([{ request: 'watch', handle: 1, query: count, bindings: { panel }, options: immediately }]); + + expect(await host.connection.requestAsync([{ request: 'update', handle: 1, generation: 1, bindings: { panel: other } }])).toEqual([{ snapshot: { count: 2 } }]); + + panel.append(document.createElement('i')); + other.append(document.createElement('i')); + await nextTask(); + + expect(host.batches).toEqual([[{ handle: 1, generation: 1, changes: [{ op: 'replace', path: '/count', value: 3 }] }]]); + }); + + it('delivers a watch\'s snapshot whole as it is refreshed, changed or not, and resumes one whose delivery the host rejected', async () => { + await host.connection.requestAsync([{ request: 'watch', handle: 1, query: count, bindings: { panel }, options: immediately }]); + + panel.append(document.createElement('i')); + await nextTask(); + host.reject(0, new Error('the host lost the delivery')); + await nextTask(); + panel.append(document.createElement('u')); + await nextTask(); + + expect(host.batches).toHaveLength(1); + + await host.connection.requestAsync([{ request: 'refresh' }]); + await nextTask(); + + expect(host.batches[1]).toEqual([{ handle: 1, generation: 0, snapshot: { count: 3 } }]); + }); + + it('ends every handle of an owner as it is released, and every handle as it closes, answering each request after it with DOMQL5027', async () => { + await host.connection.requestAsync([ + { request: 'watch', handle: 1, owner: 'a', query: count, bindings: { panel }, options: immediately }, + { request: 'run', handle: 2, owner: 'a', query: { key: 'mark', text: 'import Desk\npanel:mark(tone)' }, bindings: { panel, tone: 'warm' } }, + { request: 'subscribe', handle: 3, owner: 'b', query: { key: 'presses', text: 'import Desk\npanel:presses()' }, bindings: { panel } }, + ]); + + expect(await host.connection.requestAsync([{ request: 'release', owner: 'a' }])).toEqual([{}]); + + panel.append(document.createElement('i')); + await nextTask(); + + expect(marks[0].isDisposed).toBe(true); + expect(host.batches).toEqual([]); + expect(presses).not.toBeNull(); + + host.connection.close(); + + expect(presses).toBeNull(); + expect(host.connection.isClosed).toBe(true); + expect((await host.connection.requestAsync([{ request: 'watch', handle: 4, query: count }]))[0].error).toMatchObject({ code: 'DOMQL5027' }); + }); + + it('makes an execution\'s query as its request is carried out, so a later request of the batch names it by its key', async () => { + const answers = await host.connection.requestAsync([ + { request: 'evaluate', handle: 1, query: count, bindings: { panel } }, + { request: 'watch', handle: 2, query: 'count', bindings: { panel }, options: immediately }, + ]); + + expect(answers).toEqual([{ value: { count: 1 } }, { snapshot: { count: 1 } }]); + }); + + it('delivers nothing of a result that settles after its handle ended, and leaves a handle that took its id alone', async () => { + const later = { key: 'later', text: 'import Desk\npanel:later()' }; + + expect(await host.connection.requestAsync([{ request: 'execute', handle: 1, query: later, bindings: { panel } }])).toEqual([{ pending: true }]); + await host.connection.requestAsync([{ request: 'dispose', handle: 1 }, { request: 'watch', handle: 1, query: count, bindings: { panel }, options: immediately }]); + + finish(7); + await nextTask(); + panel.append(document.createElement('i')); + await nextTask(); + + expect(host.batches).toEqual([[{ handle: 1, generation: 0, changes: [{ op: 'replace', path: '/count', value: 2 }] }]]); + expect(await host.connection.requestAsync([{ request: 'refresh', handle: 1 }])).toEqual([{}]); + }); + + it('fails each delivery it drops as it closes, so an event\'s acknowledgment settles', async () => { + await host.connection.requestAsync([{ request: 'subscribe', handle: 1, query: { key: 'presses', text: 'import Desk\npanel:presses()' }, bindings: { panel } }]); + + const pressed = presses(1); + + host.connection.close(); + + // Closing ends the subscription first, which rejects the acknowledgment it hadn't settled. + await expect(pressed).rejects.toMatchObject({ kind: 'evaluation', code: 'DOMQL5017' }); + expect(host.batches).toEqual([]); + }); + + it('sends one task\'s deliveries whole, however many, where earlier batches left none unacknowledged', async () => { + await host.connection.requestAsync([{ request: 'subscribe', handle: 1, query: { key: 'presses', text: 'import Desk\npanel:presses()' }, bindings: { panel } }]); + + for (let index = 0; index < 5000; index++) { + presses(index); + } + + await nextTask(); + + expect(host.batches.map(batch => batch.length)).toEqual([5000]); + expect(host.connection.isClosed).toBe(false); + }); + + it('ends an owner\'s pending execution as the owner is released, and no other owner\'s', async () => { + const later = { key: 'later', text: 'import Desk\npanel:later()' }; + + await host.connection.requestAsync([{ request: 'execute', handle: 1, owner: 'a', query: later, bindings: { panel } }]); + await host.connection.requestAsync([{ request: 'release', owner: null }]); + await host.connection.requestAsync([{ request: 'release', owner: 'a' }]); + + finish(1); + await nextTask(); + + expect(host.batches).toEqual([]); + expect(await host.connection.requestAsync([{ request: 'watch', handle: 1, query: count, bindings: { panel }, options: immediately }])).toEqual([{ snapshot: { count: 1 } }]); + }); + + it('delivers again a watch whose delivery the host rejected once it is updated, and a refresh\'s failure once', async () => { + await host.connection.requestAsync([{ request: 'watch', handle: 1, query: { key: 'fragile', text: 'import Desk\n{ value = panel:fragile, count = panel.children.count }' }, bindings: { panel }, options: immediately }]); + + panel.append(document.createElement('i')); + await nextTask(); + host.reject(0, new Error('the host lost the delivery')); + await nextTask(); + await host.connection.requestAsync([{ request: 'update', handle: 1, generation: 1, bindings: { panel } }]); + panel.append(document.createElement('u')); + await nextTask(); + + expect(host.batches[1]).toEqual([{ handle: 1, generation: 1, changes: [{ op: 'replace', path: '/count', value: 3 }] }]); + + host.settle(1); + panel.setAttribute('data-broken', ''); + await nextTask(); + host.settle(2); + await nextTask(); + + // The attribute's change failed the evaluation once; the refresh evaluates again, and its failure is delivered once, as its change, not again as its rejection. + const before = host.batches.length; + + await host.connection.requestAsync([{ request: 'refresh', handle: 1 }]); + await nextTask(); + host.batches.slice(before).forEach((_, index) => host.settle(before + index)); + await nextTask(); + + expect(host.batches.slice(before).flat().filter(delivery => delivery.error !== undefined)).toHaveLength(1); + }); + + it('opens with options of null as with none', () => { + const connection = isolated.connect(() => Promise.resolve([]), null); + + expect(connection.isClosed).toBe(false); + connection.close(); + }); + + it('closes rather than hold more deliveries than its limit while the host acknowledges none, reporting DOMQL5026 to the window', async () => { + const reported = []; + + window.reportError = error => reported.push(error.code); + await host.connection.requestAsync([{ request: 'subscribe', handle: 1, query: { key: 'presses', text: 'import Desk\npanel:presses()' }, bindings: { panel } }]); + + for (let index = 0; index < 4097; index++) { + presses(index); + await Promise.resolve(); + } + + await nextTask(); + delete window.reportError; + + // The window hears it from the connection, and from the subscription whose event it refused. + expect(reported.length).toBeGreaterThan(0); + expect(reported.every(code => code === 'DOMQL5026')).toBe(true); + expect(host.connection.isClosed).toBe(true); + }); +}); diff --git a/tests/connections/DotnetConnection.test.js b/tests/connections/DotnetConnection.test.js new file mode 100644 index 0000000..4ce09f3 --- /dev/null +++ b/tests/connections/DotnetConnection.test.js @@ -0,0 +1,51 @@ +import { afterEach, beforeEach, describe, it, expect } from 'vitest'; +import { connect } from '../../nuget/scripts/domql.dotnet.js'; + +/** Settles once the current task and those it queued at once have run. */ +const nextTask = () => new Promise(resolve => setTimeout(resolve, 0)); + +describe('the connection a .NET application opens', () => { + let calls; + let connection; + let panel; + + beforeEach(() => { + calls = []; + document.body.innerHTML = '
'; + panel = document.getElementById('panel'); + globalThis.DotNet = { createJSStreamReference: bytes => ({ utf8: new TextDecoder().decode(bytes) }) }; + + const receiver = { + invokeMethodAsync: (name, transfer) => { + calls.push([name, transfer]); + + return Promise.resolve([null]); + }, + }; + + connection = connect(receiver, { textBudget: 120 }); + }); + + afterEach(() => { + connection.close(); + delete globalThis.DotNet; + document.body.innerHTML = ''; + }); + + it('carries .NET\'s requests, and hands each batch of deliveries to the receiver\'s ReceiveAsync as data within the budget and as a stream of its UTF-8 bytes beyond it', async () => { + const query = { key: 'count', text: '{ count = panel.children.count }' }; + + expect(await connection.requestAsync([{ request: 'watch', handle: 1, query, bindings: { panel }, options: { schedule: 'immediate' } }])).toEqual([{ snapshot: { count: 0 } }]); + + panel.append(document.createElement('b')); + await nextTask(); + + expect(calls).toEqual([['ReceiveAsync', { deliveries: [{ handle: 1, generation: 0, changes: [{ op: 'replace', path: '/count', value: 1 }] }] }]]); + + await connection.requestAsync([{ request: 'watch', handle: 2, query: { key: 'label', text: '{ label = panel["data-label"] }' }, bindings: { panel }, options: { schedule: 'immediate' } }]); + panel.setAttribute('data-label', 'x'.repeat(200)); + await nextTask(); + + expect(calls[1]).toEqual(['ReceiveAsync', { stream: { utf8: `[{"handle":2,"generation":0,"changes":[{"op":"replace","path":"/label","value":"${'x'.repeat(200)}"}]}]` } }]); + }); +}); diff --git a/tests/dotnet/DomqlChangeSetTests.cs b/tests/dotnet/DomqlChangeSetTests.cs new file mode 100644 index 0000000..f46b86c --- /dev/null +++ b/tests/dotnet/DomqlChangeSetTests.cs @@ -0,0 +1,43 @@ +namespace Domql.Tests; + +using System.Text.Json; +using System.Text.Json.Nodes; + +using Xunit; + +public sealed class DomqlChangeSetTests +{ + /// The conformance corpus: each case a previous result, a change set and the result they give, which DOMQL's JavaScript applier passes too. + public static TheoryData Cases { get; } = [.. Corpus().Select(entry => (string)entry!["name"]!)]; + + [Theory] + [MemberData(nameof(Cases))] + public void Should_give_the_result_the_corpus_gives(string name) + { + var entry = Corpus().Single(candidate => (string)candidate!["name"]! == name)!; + var changes = JsonDocument.Parse(entry["changes"]!.ToJsonString()).RootElement; + var result = DomqlChangeSet.Apply(entry["previous"]!.DeepClone(), changes); + + Assert.True(JsonNode.DeepEquals(entry["result"], result), $"{name}: {result?.ToJsonString()}"); + } + + [Theory] + [InlineData("""[{"op":"replace","path":"/missing","value":1}]""", "it replaces 'missing'")] + [InlineData("""[{"op":"remove","path":"/rows/2"}]""", "its index '2' names no item")] + [InlineData("""[{"op":"add","path":"/rows/3","value":1}]""", "its index '3' names no item")] + [InlineData("""[{"op":"add","path":"/rows/01","value":1}]""", "its index '01' names no item")] + [InlineData("""[{"op":"remove","path":""}]""", "it takes the whole result out")] + [InlineData("""[{"op":"copy","from":"/rows/0","path":"/rows/1"}]""", "its operation copy is none of")] + [InlineData("""[{"op":"replace","path":"rows","value":1}]""", "is no JSON Pointer")] + [InlineData("""{"op":"replace"}""", "it is no list of operations")] + public void Should_refuse_a_change_set_that_names_no_place_in_the_copy(string changes, string reason) + { + var copy = JsonNode.Parse("""{"rows":[{"k":"a"},{"k":"b"}]}"""); + var error = Assert.Throws(() => DomqlChangeSet.Apply(copy, JsonDocument.Parse(changes).RootElement)); + + Assert.Equal("DOMQL5029", error.Code); + Assert.Contains(reason, error.Message, StringComparison.Ordinal); + } + + private static JsonArray Corpus() => JsonNode.Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "change-sets.json")))!.AsArray(); +} diff --git a/tests/dotnet/DomqlConnectionTests.cs b/tests/dotnet/DomqlConnectionTests.cs new file mode 100644 index 0000000..a1123a6 --- /dev/null +++ b/tests/dotnet/DomqlConnectionTests.cs @@ -0,0 +1,412 @@ +namespace Domql.Tests; + +using System.Text.Json; +using System.Text.Json.Nodes; + +using Xunit; + +public sealed class DomqlConnectionTests : IAsyncDisposable +{ + private readonly TestDispatcher _dispatcher = new(); + private readonly FakeBrowser _browser = new(); + private readonly DomqlConnection _connection; + private readonly DomqlOwner _owner; + + public DomqlConnectionTests() + { + _connection = new DomqlConnection(_browser); + _owner = _connection.CreateOwner("panel"); + } + + public sealed record Counted(int Count); + + private static readonly DomqlQuery CountQuery = DomqlQuery.Create("{ count = panel.children.count }"); + + public async ValueTask DisposeAsync() + { + // The connection first, so the owner's release has no request left to wait on. + await _connection.DisposeAsync(); + await _owner.DisposeAsync(); + _dispatcher.Dispose(); + } + + [Fact] + public Task Should_carry_the_requests_of_one_turn_as_one_call_its_query_text_crossing_once() => _dispatcher.RunAsync(async () => + { + _ = _owner.Watch(CountQuery, Bindings("first")); + _ = _owner.Watch(CountQuery, Bindings("second")); + _ = _owner.Watch(DomqlQuery.Create("panel.children.count"), Bindings("third")); + + var batch = await _browser.NextBatchAsync(); + + Assert.Equal(["./_content/domql/domql.dotnet.js"], _browser.Imports); + Assert.Equal(3, batch.Requests.Count); + Assert.Equal("""{"key":1,"text":"{ count = panel.children.count }"}""", batch.Requests[0]!["query"]!.ToJsonString()); + Assert.Equal("1", batch.Requests[1]!["query"]!.ToJsonString()); + Assert.Equal("""{"key":2,"text":"panel.children.count"}""", batch.Requests[2]!["query"]!.ToJsonString()); + Assert.Equal(["watch", "watch", "watch"], batch.Requests.Select(request => (string)request!["request"]!)); + Assert.Equal(["panel", "panel", "panel"], batch.Requests.Select(request => (string)request!["owner"]!)); + Assert.Equal(["first", "second", "third"], batch.Requests.Select(request => (string)request!["bindings"]!["panel"]!)); + Assert.False(_browser.HasBatch); + }); + + [Fact] + public Task Should_name_a_query_by_its_key_once_the_browser_made_it_and_by_its_text_again_once_it_refused_it() => _dispatcher.RunAsync(async () => + { + var refused = DomqlQuery.Create("panel {"); + + var made = _owner.Watch(CountQuery); + _ = _owner.Watch(refused); + (await _browser.NextBatchAsync()).Answer("""{"snapshot":{"count":0}}""", """{"error":{"code":"NEXO1051","kind":"syntax","message":"unclosed"}}"""); + + // A request made before the answer arrives crosses with the text again, which the browser reads as the query it made; one made after names it by its key. + await made.ReadyAsync(Token); + _ = _owner.Watch(CountQuery); + _ = _owner.Watch(refused); + + var later = await _browser.NextBatchAsync(); + + Assert.Equal("1", later.Requests[0]!["query"]!.ToJsonString()); + Assert.Equal("""{"key":2,"text":"panel {"}""", later.Requests[1]!["query"]!.ToJsonString()); + }); + + [Fact] + public Task Should_answer_a_watch_with_its_first_snapshot_and_apply_each_change_set_its_handler_hearing_each_result() => _dispatcher.RunAsync(async () => + { + var heard = new List(); + var watch = _owner.Watch(CountQuery, Bindings("panel"), counted => + { + heard.Add(counted.Count); + + return Task.CompletedTask; + }); + var batch = await _browser.NextBatchAsync(); + + batch.Answer("""{"snapshot":{"count":2}}"""); + + Assert.Equal(new Counted(2), await watch.ReadyAsync(Token)); + + var id = (long)batch.Requests[0]!["handle"]!; + + await _browser.DeliverAsync($$"""[{"handle":{{id}},"generation":0,"changes":[{"op":"replace","path":"/count","value":3}]}]"""); + + Assert.Equal(new Counted(3), watch.Current); + Assert.Equal(DomqlWatchStatus.Ready, watch.Status); + await WaitUntilAsync(() => heard.Count == 2); + Assert.Equal([2, 3], heard); + }); + + [Fact] + public Task Should_hold_a_delivery_that_overtakes_its_request_s_answer_and_apply_it_after_the_answer() => _dispatcher.RunAsync(async () => + { + var watch = _owner.Watch(CountQuery); + var batch = await _browser.NextBatchAsync(); + var id = (long)batch.Requests[0]!["handle"]!; + + await _browser.DeliverAsync($$"""[{"handle":{{id}},"generation":0,"changes":[{"op":"replace","path":"/count","value":5}]}]"""); + + Assert.False(watch.HasCurrent); + + batch.Answer("""{"snapshot":{"count":4}}"""); + await watch.ReadyAsync(Token); + + Assert.Equal(new Counted(5), watch.Current); + }); + + [Fact] + public Task Should_watch_with_new_bindings_dropping_what_the_old_ones_delivered() => _dispatcher.RunAsync(async () => + { + var watch = _owner.Watch(CountQuery, Bindings("old")); + var first = await _browser.NextBatchAsync(); + var id = (long)first.Requests[0]!["handle"]!; + + first.Answer("""{"snapshot":{"count":1}}"""); + await watch.ReadyAsync(Token); + + var updated = watch.UpdateAsync(new Dictionary { ["panel"] = "new" }); + var update = await _browser.NextBatchAsync(); + + Assert.Equal("""{"request":"update","handle":1,"owner":"panel","generation":1,"bindings":{"panel":"new"}}""".Replace("\"handle\":1", $"\"handle\":{id}", StringComparison.Ordinal), update.Requests[0]!.ToJsonString()); + + update.Answer("""{"snapshot":{"count":7}}"""); + await updated; + await _browser.DeliverAsync($$"""[{"handle":{{id}},"generation":0,"changes":[{"op":"replace","path":"/count","value":2}]}]"""); + + Assert.Equal(new Counted(7), watch.Current); + }); + + [Fact] + public Task Should_ask_for_the_snapshot_whole_where_a_change_set_does_not_apply_and_skip_change_sets_until_it_arrives() => _dispatcher.RunAsync(async () => + { + var failures = new List(); + var watch = _owner.Watch(CountQuery, options: new DomqlWatchOptions { Failed = error => { failures.Add(error.Code); return Task.CompletedTask; } }); + var batch = await _browser.NextBatchAsync(); + var id = (long)batch.Requests[0]!["handle"]!; + + batch.Answer("""{"snapshot":{"count":1}}"""); + await watch.ReadyAsync(Token); + await _browser.DeliverAsync($$"""[{"handle":{{id}},"generation":0,"changes":[{"op":"replace","path":"/missing","value":2}]}]"""); + + var refresh = await _browser.NextBatchAsync(); + + Assert.Equal("refresh", (string)refresh.Requests[0]!["request"]!); + Assert.Equal(["DOMQL5029"], failures); + Assert.Equal(DomqlWatchStatus.Failed, watch.Status); + + await _browser.DeliverAsync($$$"""[{"handle":{{{id}}},"generation":0,"changes":[{"op":"replace","path":"/count","value":9}]},{"handle":{{{id}}},"generation":0,"snapshot":{"count":3}}]"""); + + Assert.Equal(new Counted(3), watch.Current); + Assert.Equal(DomqlWatchStatus.Ready, watch.Status); + }); + + [Fact] + public Task Should_fail_a_refused_watch_with_the_browser_s_code_kind_and_location() => _dispatcher.RunAsync(async () => + { + var watch = _owner.Watch(CountQuery); + + (await _browser.NextBatchAsync()).Answer("""{"error":{"code":"DOMQL3003","kind":"validation","message":"partly observable","location":{"pointer":"/expression","line":1,"column":3,"offset":2,"binding":"panel"}}}"""); + + var error = await Assert.ThrowsAsync(() => watch.ReadyAsync(Token)); + + Assert.Equal(("DOMQL3003", "validation", "partly observable"), (error.Code, error.Kind, error.Message)); + Assert.Equal(new DomqlLocation("/expression", 1, 3, 2, "panel", null, null, null, null), error.Location); + Assert.True(watch.IsDisposed); + }); + + [Fact] + public Task Should_answer_an_event_with_its_handler_s_answer_once_the_handler_completes() => _dispatcher.RunAsync(async () => + { + var events = new List(); + var subscription = _owner.Subscribe(DomqlQuery.Create("import Culture\nDomql.document:destinations()"), null, async (string destination) => + { + events.Add(destination); + await Task.Yield(); + + return $"/{destination}/"; + }); + var batch = await _browser.NextBatchAsync(); + var id = (long)batch.Requests[0]!["handle"]!; + + batch.Answer("{}"); + + var answers = await _browser.DeliverAsync($$"""[{"handle":{{id}},"generation":0,"event":"fr"},{"handle":{{id}},"generation":0,"event":"de"},{"handle":999,"event":"nobody"}]"""); + + Assert.Equal(["fr", "de"], events); + Assert.Equal("""["/fr/","/de/",null]""", answers.ToJsonString()); + Assert.False(subscription.IsDisposed); + }); + + [Fact] + public Task Should_settle_an_execution_with_its_answer_or_with_its_delivery_where_it_was_pending() => _dispatcher.RunAsync(async () => + { + var focused = _owner.ExecuteAsync(DomqlQuery.Create("field.focus()"), Bindings("field"), Token); + var scrolled = _owner.ExecuteAsync(DomqlQuery.Create("""panel.scrollTo({ block = 300, behavior = "smooth" })"""), Bindings("panel"), Token); + var batch = await _browser.NextBatchAsync(); + var scrolling = (long)batch.Requests[1]!["handle"]!; + + Assert.Equal(["execute", "execute"], batch.Requests.Select(request => (string)request!["request"]!)); + + batch.Answer("""{"value":true}""", """{"pending":true}"""); + + Assert.True(await focused); + Assert.False(scrolled.IsCompleted); + + await _browser.DeliverAsync($$"""[{"handle":{{scrolling}},"value":true}]"""); + + Assert.True(await scrolled); + }); + + [Fact] + public Task Should_end_every_operation_of_an_owner_in_one_request() => _dispatcher.RunAsync(async () => + { + var watch = _owner.Watch(CountQuery); + var execution = _owner.Run(DomqlQuery.Create("""panel.ownClass({ name = "dragging" })"""), Bindings("panel")); + + (await _browser.NextBatchAsync()).Answer("""{"snapshot":{"count":1}}""", "{}"); + await watch.ReadyAsync(Token); + + var released = _owner.DisposeAsync(); + var release = await _browser.NextBatchAsync(); + + release.Answer("{}"); + await released; + + Assert.Equal("""[{"request":"release","owner":"panel"}]""", release.Requests.ToJsonString()); + Assert.True(watch.IsDisposed); + Assert.True(execution.IsDisposed); + Assert.Equal(DomqlWatchStatus.Disposed, watch.Status); + }); + + [Fact] + public Task Should_read_a_batch_that_crossed_as_a_stream() => _dispatcher.RunAsync(async () => + { + var watch = _owner.Watch(CountQuery); + var batch = await _browser.NextBatchAsync(); + var id = (long)batch.Requests[0]!["handle"]!; + + batch.Answer("""{"pending":true}"""); + await _browser.DeliverAsync($$$"""[{"handle":{{{id}}},"generation":0,"snapshot":{"count":11}}]""", asStream: true); + + Assert.Equal(new Counted(11), await watch.ReadyAsync(Token)); + }); + + [Fact] + public Task Should_fail_each_request_of_a_batch_that_could_not_cross() => _dispatcher.RunAsync(async () => + { + var watch = _owner.Watch(CountQuery); + var executed = _owner.ExecuteAsync(DomqlQuery.Create("field.focus()"), cancellationToken: Token); + + (await _browser.NextBatchAsync()).Fail(new InvalidOperationException("The circuit is gone")); + + Assert.Equal("DOMQL5030", (await Assert.ThrowsAsync(() => watch.ReadyAsync(Token))).Code); + Assert.Equal("DOMQL5030", (await Assert.ThrowsAsync(() => executed)).Code); + }); + + [Fact] + public Task Should_map_a_result_its_type_can_t_hold_as_a_failure_its_current_result_standing() => _dispatcher.RunAsync(async () => + { + var failures = new List(); + var watch = _owner.Watch(CountQuery, options: new DomqlWatchOptions { Failed = error => { failures.Add(error); return Task.CompletedTask; } }); + var batch = await _browser.NextBatchAsync(); + var id = (long)batch.Requests[0]!["handle"]!; + + batch.Answer("""{"snapshot":{"count":1}}"""); + await watch.ReadyAsync(Token); + await _browser.DeliverAsync($$"""[{"handle":{{id}},"generation":0,"changes":[{"op":"replace","path":"/count","value":"many"}]}]"""); + + Assert.Equal("DOMQL5028", Assert.Single(failures).Code); + Assert.Equal(new Counted(1), watch.Current); + }); + + [Fact] + public Task Should_close_the_browser_side_and_end_every_operation_as_the_connection_is_disposed() => _dispatcher.RunAsync(async () => + { + var watch = _owner.Watch(CountQuery); + + (await _browser.NextBatchAsync()).Answer("""{"snapshot":{"count":1}}"""); + await watch.ReadyAsync(Token); + await _connection.DisposeAsync(); + + Assert.True(_browser.IsClosed); + Assert.True(watch.IsDisposed); + }); + + [Fact] + public Task Should_keep_a_handler_s_failure_its_own_applying_the_deliveries_after_it() => _dispatcher.RunAsync(async () => + { + var watch = _owner.Watch(CountQuery); + var subscription = _owner.Subscribe(DomqlQuery.Create("panel:presses()"), null, (int _) => throw new TaskCanceledException("The request timed out")); + var batch = await _browser.NextBatchAsync(); + var watching = (long)batch.Requests[0]!["handle"]!; + var subscribed = (long)batch.Requests[1]!["handle"]!; + + batch.Answer("""{"snapshot":{"count":1}}""", "{}"); + await watch.ReadyAsync(Token); + + var answers = await _browser.DeliverAsync($$"""[{"handle":{{subscribed}},"generation":0,"event":1},{"handle":{{watching}},"generation":0,"changes":[{"op":"replace","path":"/count","value":2}]}]"""); + + Assert.Equal("[null,null]", answers.ToJsonString()); + Assert.Equal(new Counted(2), watch.Current); + Assert.False(subscription.IsDisposed); + }); + + [Fact] + public Task Should_refresh_every_watch_once_where_a_batch_can_t_be_read_answering_nothing_until_a_batch_reads_again() => _dispatcher.RunAsync(async () => + { + var watch = _owner.Watch(CountQuery); + var batch = await _browser.NextBatchAsync(); + var id = (long)batch.Requests[0]!["handle"]!; + + batch.Answer("""{"snapshot":{"count":1}}"""); + await watch.ReadyAsync(Token); + + var answers = await _browser.DeliverAsync("[{\"handle\":", asStream: true); + var refresh = await _browser.NextBatchAsync(); + + Assert.Equal("[]", answers.ToJsonString()); + Assert.Equal("""[{"request":"refresh"}]""", refresh.Requests.ToJsonString()); + + // A snapshot past what the connection reads fails again, and refreshes nothing more, until a batch reads. + await _browser.DeliverAsync("[{\"handle\":", asStream: true); + await Task.Delay(50, Token); + + Assert.False(_browser.HasBatch); + + await _browser.DeliverAsync($$$"""[{"handle":{{{id}}},"generation":0,"snapshot":{"count":2}}]"""); + await _browser.DeliverAsync("[{\"handle\":", asStream: true); + + Assert.Equal("""[{"request":"refresh"}]""", (await _browser.NextBatchAsync()).Requests.ToJsonString()); + }); + + [Fact] + public Task Should_refuse_an_owner_named_as_one_in_use_until_it_is_disposed() => _dispatcher.RunAsync(async () => + { + var error = Assert.Throws(() => _connection.CreateOwner("panel")); + var generated = _connection.CreateOwner(); + var released = _owner.DisposeAsync(); + + (await _browser.NextBatchAsync()).Answer("{}"); + await released; + + Assert.Contains("An owner named 'panel' is in use", error.Message, StringComparison.Ordinal); + Assert.StartsWith("owner-", generated.Name, StringComparison.Ordinal); + Assert.Equal("panel", _connection.CreateOwner("panel").Name); + }); + + [Fact] + public Task Should_dispose_in_the_browser_a_watch_whose_update_was_refused() => _dispatcher.RunAsync(async () => + { + var watch = _owner.Watch(CountQuery, Bindings("panel")); + var first = await _browser.NextBatchAsync(); + var id = (long)first.Requests[0]!["handle"]!; + + first.Answer("""{"snapshot":{"count":1}}"""); + await watch.ReadyAsync(Token); + + _ = watch.UpdateAsync(new Dictionary { ["panel"] = null }); + (await _browser.NextBatchAsync()).Answer("""{"error":{"code":"NEXO2045","kind":"structure","message":"refused"}}"""); + + var disposal = await _browser.NextBatchAsync(); + + Assert.Equal($$"""[{"request":"dispose","handle":{{id}}}]""", disposal.Requests.ToJsonString()); + Assert.True(watch.IsDisposed); + Assert.Equal("NEXO2045", watch.Error?.Code); + }); + + [Fact] + public Task Should_open_nothing_for_a_connection_disposed_before_its_first_request_crossed() => _dispatcher.RunAsync(async () => + { + var watch = _owner.Watch(CountQuery); + + await _connection.DisposeAsync(); + await Assert.ThrowsAsync(() => watch.ReadyAsync(Token)); + await Task.Yield(); + + Assert.Empty(_browser.Imports); + Assert.False(_browser.HasBatch); + }); + + [Fact] + public Task Should_tell_a_handle_s_failure_on_the_context_its_operation_was_started_in() => _dispatcher.RunAsync(async () => + { + SynchronizationContext? heardOn = null; + var watch = _owner.Watch(CountQuery, options: new DomqlWatchOptions { Failed = _ => { heardOn = SynchronizationContext.Current; return Task.CompletedTask; } }); + + (await _browser.NextBatchAsync()).Fail(new InvalidOperationException("The runtime is gone")); + await Assert.ThrowsAsync(() => watch.ReadyAsync(Token)); + + Assert.Same(_dispatcher, heardOn); + }); + + private static CancellationToken Token => TestContext.Current.CancellationToken; + + private static Dictionary Bindings(string panel) => new() { ["panel"] = panel, ["field"] = panel }; + + private static async Task WaitUntilAsync(Func condition) + { + for (var attempt = 0; !condition() && attempt < 200; attempt++) + { + await Task.Delay(10, Token); + } + } +} diff --git a/tests/dotnet/FakeBrowser.cs b/tests/dotnet/FakeBrowser.cs new file mode 100644 index 0000000..b5d46da --- /dev/null +++ b/tests/dotnet/FakeBrowser.cs @@ -0,0 +1,130 @@ +namespace Domql.Tests; + +using System.Diagnostics.CodeAnalysis; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading.Channels; + +using Microsoft.JSInterop; + +/// +/// A browser a connection reaches: it imports the connection's module, opens it, and keeps each batch of requests the connection sends, which a test answers as DOMQL's connection does; the test delivers +/// to the connection through the receiver it was opened with. +/// +internal sealed class FakeBrowser : IJSRuntime +{ + private readonly Channel _batches = Channel.CreateUnbounded(); + private DotNetObjectReference? _receiver; + + /// The module paths imported, in order. + public List Imports { get; } = []; + + /// Whether the connection closed its browser side. + public bool IsClosed { get; private set; } + + /// The next batch the connection sends, waiting for it where none has arrived. + public async Task NextBatchAsync() + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + + return await _batches.Reader.ReadAsync(timeout.Token).ConfigureAwait(false); + } + + /// Whether a batch arrived that no test has read. + public bool HasBatch => _batches.Reader.TryPeek(out _); + + /// Delivers the deliveries given, as one batch of the browser's task, answering what the connection answers. + public async Task DeliverAsync(string deliveries, bool asStream = false) + { + var receiver = _receiver ?? throw new InvalidOperationException("The connection has not opened"); + var transfer = asStream ? new DomqlTransfer { Stream = new FakeStream(Encoding.UTF8.GetBytes(deliveries)) } : new DomqlTransfer { Deliveries = JsonDocument.Parse(deliveries).RootElement.Clone() }; + var answers = await receiver.Value.ReceiveAsync(transfer).ConfigureAwait(false); + + return JsonSerializer.SerializeToNode(answers, JsonSerializerOptions.Web)!.AsArray(); + } + + public ValueTask InvokeAsync(string identifier, object?[]? args) => InvokeAsync(identifier, CancellationToken.None, args); + + [SuppressMessage("Reliability", "CA2000", Justification = "The connection disposes the references the browser gives it.")] + public ValueTask InvokeAsync(string identifier, CancellationToken cancellationToken, object?[]? args) + { + Imports.Add((string)args![0]!); + + return ValueTask.FromResult((TValue)(object)new Module(this)); + } + + /// A batch of requests, as the connection wrote them, which the test answers. + internal sealed class Batch(JsonArray requests) + { + private readonly TaskCompletionSource _answers = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public JsonArray Requests { get; } = requests; + + public Task Answers => _answers.Task; + + /// Answers the batch, one answer for each request, in order. + public void Answer(params string[] answers) => _answers.SetResult([.. answers.Select(answer => JsonDocument.Parse(answer).RootElement.Clone())]); + + /// Fails the batch, as a runtime that lost the browser does. + public void Fail(Exception error) => _answers.SetException(error); + } + + /// The module the connection imports. + private sealed class Module(FakeBrowser browser) : IJSObjectReference + { + public ValueTask InvokeAsync(string identifier, object?[]? args) => InvokeAsync(identifier, CancellationToken.None, args); + + [SuppressMessage("Reliability", "CA2000", Justification = "The connection disposes the references the browser gives it.")] + public ValueTask InvokeAsync(string identifier, CancellationToken cancellationToken, object?[]? args) + { + browser._receiver = (DotNetObjectReference)args![0]!; + + return ValueTask.FromResult((TValue)(object)new Connection(browser)); + } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + + /// The browser's side of the connection, which hands each batch to the test. + private sealed class Connection(FakeBrowser browser) : IJSObjectReference + { + public ValueTask InvokeAsync(string identifier, object?[]? args) => InvokeAsync(identifier, CancellationToken.None, args); + + public async ValueTask InvokeAsync(string identifier, CancellationToken cancellationToken, object?[]? args) + { + if (identifier == "close") + { + browser.IsClosed = true; + + return default!; + } + + var batch = new Batch(JsonSerializer.SerializeToNode(args![0], JsonSerializerOptions.Web)!.AsArray()); + + await browser._batches.Writer.WriteAsync(batch, cancellationToken).ConfigureAwait(false); + + return (TValue)(object)await batch.Answers.ConfigureAwait(false); + } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + + /// A batch that crossed as a stream. + private sealed class FakeStream(byte[] content) : IJSStreamReference + { + public long Length => content.Length; + + public bool IsDisposed { get; private set; } + + public ValueTask OpenReadStreamAsync(long maxAllowedSize = 512000, CancellationToken cancellationToken = default) => + ValueTask.FromResult(new MemoryStream(content)); + + public ValueTask DisposeAsync() + { + IsDisposed = true; + + return ValueTask.CompletedTask; + } + } +} diff --git a/tests/dotnet/Forma.DOMQL.Tests.csproj b/tests/dotnet/Forma.DOMQL.Tests.csproj new file mode 100644 index 0000000..e33ab24 --- /dev/null +++ b/tests/dotnet/Forma.DOMQL.Tests.csproj @@ -0,0 +1,31 @@ + + + + + net11.0 + enable + enable + latest + Domql.Tests + false + Exe + true + true + + + + + + + + + + + + + + + + + + diff --git a/tests/dotnet/TestDispatcher.cs b/tests/dotnet/TestDispatcher.cs new file mode 100644 index 0000000..cd5f790 --- /dev/null +++ b/tests/dotnet/TestDispatcher.cs @@ -0,0 +1,64 @@ +namespace Domql.Tests; + +using System.Collections.Concurrent; + +/// +/// One thread a test runs on, as a host's dispatcher runs its components: everything posted to it runs in order, after what runs now, so a connection's requests of one turn cross together. +/// +internal sealed class TestDispatcher : SynchronizationContext, IDisposable +{ + private readonly BlockingCollection<(SendOrPostCallback Callback, object? State)> _queue = []; + private readonly Thread _thread; + + public TestDispatcher() + { + _thread = new Thread(Pump) { IsBackground = true, Name = "Test dispatcher" }; + _thread.Start(); + } + + /// Runs the test's body on the dispatcher, and settles as it does. + public Task RunAsync(Func body) + { + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + Post(_ => started.SetResult(body()), null); + + return started.Task.Unwrap().WaitAsync(TimeSpan.FromSeconds(30)); + } + + /// Runs the callback after what runs now; once the dispatcher is disposed, as its test has ended, on the thread pool, as a host with no dispatcher would. + public override void Post(SendOrPostCallback d, object? state) + { + try + { + _queue.Add((d, state)); + + return; + } + catch (Exception error) when (error is InvalidOperationException or ObjectDisposedException) + { + // The test has ended, and what it left posting runs on its own. + } + + ThreadPool.QueueUserWorkItem(_ => d(state)); + } + + public override void Send(SendOrPostCallback d, object? state) => throw new NotSupportedException("A dispatcher runs what is posted to it after what runs now."); + + public void Dispose() + { + _queue.CompleteAdding(); + _thread.Join(); + _queue.Dispose(); + } + + private void Pump() + { + SetSynchronizationContext(this); + + foreach (var (callback, state) in _queue.GetConsumingEnumerable()) + { + callback(state); + } + } +} diff --git a/tests/snapshots/SnapshotPatcher.test.js b/tests/snapshots/SnapshotPatcher.test.js index be2e12f..f949366 100644 --- a/tests/snapshots/SnapshotPatcher.test.js +++ b/tests/snapshots/SnapshotPatcher.test.js @@ -1,3 +1,6 @@ +import { readFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { describe, it, expect } from 'vitest'; import { nexo } from '@formaui-net/nexo'; import { SnapshotPatcher } from '#domql/snapshots/SnapshotPatcher.mjs'; @@ -363,4 +366,17 @@ describe('SnapshotPatcher', () => { expect(() => SnapshotPatcher.applyInPlace(thaw({ rows: [{ k: 'a' }] }), operations)).toThrow(TypeError); }); }); + + describe('the conformance corpus', () => { + // Each case a previous result, a change set and the result they give, which the C# half's applier passes too. + const cases = JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), '..', '_conformance', 'change-sets.json'), 'utf8')); + + it.each(cases.map(entry => [entry.name, entry]))('%s', (name, { previous, changes, result }) => { + const target = structuredClone(previous); + + SnapshotPatcher.applyInPlace(target, changes); + + expect(target).toEqual(result); + }); + }); }); diff --git a/tests/vitest.config.js b/tests/vitest.config.js index fa76e4b..5d4ff36 100644 --- a/tests/vitest.config.js +++ b/tests/vitest.config.js @@ -10,6 +10,8 @@ export default defineConfig({ { find: '#domql/', replacement: resolved('../src/') }, // Nexo's sources, which the integration tests alone reach as `#nexo/`, through the linked checkout and never through the package's exports. { find: '#nexo/', replacement: resolved('../node_modules/@formaui-net/nexo/src/') }, + // The bundle beside the module a .NET connection opens, which its tests read as the sources it is bundled from. + { find: /^\.\/domql\.js$/, replacement: resolved('../src/domql.js') }, ], }, test: { From 673ab5d81bb372fc1cfb1d0637381723bcf9d5c6 Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:57:30 +0200 Subject: [PATCH 14/15] refactor(domql): move the .NET half out The .NET half moves to DOMQL.NET, a project of its own, with its own solution, gate and package. DOMQL keeps the connection, which any host across a boundary speaks, and the change sets' conformance corpus. DOMQL's NuGet package holds the bundle alone again, and its gate runs no C# tests. D120 records it. --- .editorconfig | 19 - .gitignore | 4 - CHANGELOG.md | 1 - CLAUDE.md | 7 +- CONTRIBUTING.md | 4 +- VERSION-HISTORY.md | 7 +- build.ps1 | 9 +- docs/decisions.md | 19 +- docs/domql-design.md | 41 +- docs/features-status.md | 23 +- nuget/DomqlChangeSet.cs | 184 -------- nuget/DomqlConnection.cs | 462 --------------------- nuget/DomqlException.cs | 101 ----- nuget/DomqlExecution.cs | 182 -------- nuget/DomqlHandle.cs | 91 ---- nuget/DomqlLog.cs | 13 - nuget/DomqlOwner.cs | 152 ------- nuget/DomqlQuery.cs | 101 ----- nuget/DomqlReceiver.cs | 38 -- nuget/DomqlRequest.cs | 79 ---- nuget/DomqlRoute.cs | 48 --- nuget/DomqlServiceCollectionExtensions.cs | 23 - nuget/DomqlSubscription.cs | 141 ------- nuget/DomqlWatch.cs | 359 ---------------- nuget/Forma.DOMQL.csproj | 11 - nuget/Forma.DOMQL.slnx | 2 - nuget/README.md | 30 +- nuget/global.json | 3 - nuget/scripts/domql.dotnet.js | 33 -- scripts/bundle.mjs | 6 +- scripts/packages/nuget.files | 2 - spec/README.md | 7 +- spec/api.md | 2 +- spec/connections.md | 2 +- spec/dotnet.md | 123 ------ spec/errors.md | 6 +- tests/DocumentExamples.test.js | 1 - tests/connections/DotnetConnection.test.js | 51 --- tests/dotnet/DomqlChangeSetTests.cs | 43 -- tests/dotnet/DomqlConnectionTests.cs | 412 ------------------ tests/dotnet/FakeBrowser.cs | 130 ------ tests/dotnet/Forma.DOMQL.Tests.csproj | 31 -- tests/dotnet/TestDispatcher.cs | 64 --- tests/snapshots/SnapshotPatcher.test.js | 2 +- tests/vitest.config.js | 2 - 45 files changed, 61 insertions(+), 3010 deletions(-) delete mode 100644 nuget/DomqlChangeSet.cs delete mode 100644 nuget/DomqlConnection.cs delete mode 100644 nuget/DomqlException.cs delete mode 100644 nuget/DomqlExecution.cs delete mode 100644 nuget/DomqlHandle.cs delete mode 100644 nuget/DomqlLog.cs delete mode 100644 nuget/DomqlOwner.cs delete mode 100644 nuget/DomqlQuery.cs delete mode 100644 nuget/DomqlReceiver.cs delete mode 100644 nuget/DomqlRequest.cs delete mode 100644 nuget/DomqlRoute.cs delete mode 100644 nuget/DomqlServiceCollectionExtensions.cs delete mode 100644 nuget/DomqlSubscription.cs delete mode 100644 nuget/DomqlWatch.cs delete mode 100644 nuget/scripts/domql.dotnet.js delete mode 100644 spec/dotnet.md delete mode 100644 tests/connections/DotnetConnection.test.js delete mode 100644 tests/dotnet/DomqlChangeSetTests.cs delete mode 100644 tests/dotnet/DomqlConnectionTests.cs delete mode 100644 tests/dotnet/FakeBrowser.cs delete mode 100644 tests/dotnet/Forma.DOMQL.Tests.csproj delete mode 100644 tests/dotnet/TestDispatcher.cs diff --git a/.editorconfig b/.editorconfig index 6aefb2c..820423c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -504,23 +504,4 @@ dotnet_diagnostic.IDE0301.severity = error # Use collection express dotnet_diagnostic.IDE0302.severity = error # Use collection expression for stackalloc dotnet_diagnostic.IDE0305.severity = warning # Use collection expression for fluent - -[{*Tests.cs,*Tests.*.cs}] -# ------------------------------------------------------------ -# Test sources, under tests/dotnet/ -# ------------------------------------------------------------ - -# Disable IDE0017 and IDE0028 - Arrange builds the subject and Act mutates it, so folding the two together is not an improvement. -dotnet_diagnostic.IDE0017.severity = none -dotnet_diagnostic.IDE0028.severity = none - -# Disable CA2007 - xUnit1030 conflicts with ConfigureAwait(false) -dotnet_diagnostic.CA2007.severity = none - -# Disable CA1707 - Identifiers should not contain underscores (test method names) -dotnet_diagnostic.CA1707.severity = none - -# Disable CA1062 - Validate arguments of public methods (test methods don't need null checks) -dotnet_diagnostic.CA1062.severity = none - # End of .editorconfig diff --git a/.gitignore b/.gitignore index e073609..e4cb8df 100644 --- a/.gitignore +++ b/.gitignore @@ -6,10 +6,6 @@ nuget/bin/ nuget/obj/ artifacts/ -# The .NET half's tests, as dotnet builds them. -tests/dotnet/bin/ -tests/dotnet/obj/ - # What an IDE builds of the package consumer the full gate copies out of the repository. scripts/packages/*/bin/ scripts/packages/*/obj/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 44370b9..d53b474 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,6 @@ Each release of DOMQL's packages, newest first. The npm package `@formaui-net/do - A continuous execution's start, a subscription's start and a once execution find where their call stands only where a failure names it, so one that fails nowhere reads its query's text no second time: in Node, a query's first run took about 0.47 ms where it took 0.58, and its first once execution about 0.51 ms where it took 0.57. - DOMQL's module and its registry are created under the manifest Nexo makes of the module, which DOMQL's sources hold, so a start makes none of the checks it records: in Chromium, cold, DOMQL's import took about 33.5 ms where it took 43, and its first resolution and registrations about 2 ms more. DOMQL on a Nexo other than the one it was built against creates its module with every check, as before. - `domql.connect(deliver)` carries this instance's operations across a boundary as messages: a host's requests in batches, each answered once its task ends, a watch's first snapshot among the answers, and each task's deliveries together, a watch's paced by its acknowledgment and an event behind nothing. -- The NuGet package holds the .NET half: `services.AddDomql()`, a `DomqlConnection` for each browser runtime, owners whose disposal ends every operation they started in one call, watches whose copies change sets keep current, subscriptions, executions, and results mapped onto types. The operations one turn starts cross in one call. The package references Microsoft.JSInterop, and serves `domql.dotnet.js` beside the bundle. - A host prepares its modules and queries ahead of time: `domql.prepare(modules, { scripts })` answers Nexo's manifest, and `createModule`, `registerModule`, `registerModuleLoader` and `query` take it as `manifest`, sparing the checks it records. In Chromium, cold, a host's first query took about 5.6 ms where it took 11.6, and its module, a subscription and a run about 3.2 ms where they took 5.4. diff --git a/CLAUDE.md b/CLAUDE.md index f1b2a5b..d868758 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -34,13 +34,13 @@ Use these sources rather than inventing scope, status or style rules. | `src/dom/` | Evaluation, watches, events, executions, observations, sessions and built-in implementations | | `src/connections/` | A connection: DOMQL's operations carried across a boundary as messages, for a host whose code runs elsewhere | | `src/snapshots/` | Computing, comparing, dispatching and applying snapshot updates using identity metadata; no DOM access | -| `tests/` | Tests mirroring the source folders; the .NET half's in `tests/dotnet/`, and the change sets' conformance corpus in `tests/_conformance/` | +| `tests/` | Tests mirroring the source folders, and the change sets' conformance corpus in `tests/_conformance/`, which DOMQL.NET's tests read too | | `scripts/` | Bundling scripts, the manifest of DOMQL's own module, and the package's file lists and verification | | `spec/` | The specification, one document per subject, indexed by `spec/README.md` | | `docs/` | The design, the status overview and the decisions | | `VERSION-HISTORY.md` | Each DOMQL version and what it changed | | `CHANGELOG.md` | Each release of the packages and what it changed | -| `nuget/` | The package project: the .NET half's C# sources, the module its connection opens in the browser, the bundle it distributes, and the library guide | +| `nuget/` | The package project, which distributes the bundle, and the library guide | | `.sandbox/` | Work that stays out of the repository: experiments, spikes, notes, scratch and temporary files, and benchmark baselines; ignored by Git | Add a folder when a new responsibility needs one. Keep dependencies in this direction: @@ -98,8 +98,7 @@ Tests mirror `src/` under `tests/`. Layout, geometry and browser-managed state b | `npm run test:engines` | `tests/` | The tests of what engines decide differently, in Chromium, Firefox and WebKit | | `npm run bench` | `tests/` | Benchmarks, outside the gate | | `npm run scale` | `tests/` | Chromium workloads timed outside the gate, one file at a time: a watch of 1,000 to 100,000 rows, a drag through owned writes, an edit in a large editor, a behavior's deliveries and owners, and transient measurements beside many observers | -| `dotnet test --solution Forma.DOMQL.slnx` | `nuget/` | The .NET half's tests | -| `./build.ps1` | Repository root | Tests, bundle, package build, the .NET half's tests and format check | +| `./build.ps1` | Repository root | Tests, bundle, package build and format check | | `./build.ps1 -Browser` | Repository root | Gate including browser tests | | `./build.ps1 -Browser -Full` | Repository root | The full gate: the gate including browser tests, then the NuGet package packed and verified as consumers install it | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cba0e0b..de77ee3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -41,9 +41,9 @@ Run the full build from the repository root: | `src/dom/` | DOM evaluation, observations, watches, events, executions and the dispatch table of host calls | | `src/connections/` | A connection, which carries DOMQL's operations across a boundary as messages | | `src/snapshots/` | Snapshot comparison and updates | -| `tests/` | Tests arranged to match the source folders; the .NET half's in `tests/dotnet/` | +| `tests/` | Tests arranged to match the source folders | | `scripts/` | Bundling scripts, and the one that writes the manifest of DOMQL's own module, `npm run manifest` | -| `nuget/` | Package project, with the .NET half's C# sources, and library guide | +| `nuget/` | Package project and library guide | | `spec/` | The specification, split by subject, with its index | | `docs/` | The design and the status overview | | `VERSION-HISTORY.md` | Each DOMQL version and what it changed | diff --git a/VERSION-HISTORY.md b/VERSION-HISTORY.md index 5e85c04..0bb44bc 100644 --- a/VERSION-HISTORY.md +++ b/VERSION-HISTORY.md @@ -52,10 +52,6 @@ const connection = domql.connect(deliveries => host.receiveAsync(deliveries)); / await connection.requestAsync([{ request: 'watch', handle: 1, owner: 'panel', query: { key: 'n', text: 'panel.children.count' }, bindings: { panel } }]); // [{ snapshot: 3 }] ``` -```csharp -DomqlWatch watch = owner.Watch(DomqlQuery.Create("panel.children.count"), bindings, count => RenderAsync(count)); // kept current in .NET, by change sets; no .NET half before -``` - DOMQL moves to Nexo's language `1.0.0-preview.3`, by way of `1.0.0-preview.2`, which Nexo's release `1.0.0-preview.4` carries, as [D114](docs/decisions.md#d114) records. Nexo's [language history](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/LANGUAGE-HISTORY.md#v1-0-0-preview-3) sets out its own changes by version; the one below is the one a query meets. **Vocabulary** @@ -73,10 +69,9 @@ DOMQL moves to Nexo's language `1.0.0-preview.3`, by way of `1.0.0-preview.2`, w - [An event source is answered](spec/behaviors.md#behaviors-answers) where it declares `answers`, the type of the answer: each subscription's handler answers an occurrence with what it returns, or what its promise fulfils with, and `deliver`'s promise fulfils with the first subscription's answer, captured as that type, where it fulfilled with undefined. An answer the type refuses rejects with `DOMQL5025`, and `answers` declared by anything but an event source is refused with `DOMQL4016`, as [D113](docs/decisions.md#d113) records. - [Modules and queries are prepared ahead of time](spec/vocabulary.md#extension-modules-manifests): `domql.prepare(modules, { scripts })` checks modules, as `domql.createModule` takes them, registered after DOMQL's own, and resolves queries, as `domql.query` takes them, answering Nexo's manifest. `domql.createModule`, `domql.registerModule`, `domql.registerModuleLoader` and `domql.query` take it as `manifest`, and an operation run directly beside `types`, each sparing the checks it records, as [D116](docs/decisions.md#d116) records. A query given to `prepare` with `imports` of its own is refused with `DOMQL2021`, and a loader's options that are no object with `DOMQL2013`. -**Connections and .NET** +**Connections** - [A connection](spec/connections.md), `domql.connect(deliver)`, carries this instance's operations across a boundary as messages. A host's requests cross in batches, each answered once its task ends, and each task's deliveries cross together: a watch's paced by the acknowledgment of the one before it, its change sets joined meanwhile, and an event behind nothing. A query crosses as its text once, and by its key after. `DOMQL2022` to `DOMQL2025` refuse what a connection can't carry out, `DOMQL5026` closes one whose host acknowledges nothing, and `DOMQL5027` answers one that has closed, as [D118](docs/decisions.md#d118) records. -- [The .NET half](spec/dotnet.md) is DOMQL's own host of a connection, in the NuGet package: `AddDomql`, a `DomqlConnection` for each browser runtime, owners, watches that keep a copy by change sets, subscriptions whose handlers answer their events, executions, and results mapped onto types. The operations one turn starts cross in one call. `DOMQL5028` to `DOMQL5030` are its own failures, as [D119](docs/decisions.md#d119) records. **Breaking:** diff --git a/build.ps1 b/build.ps1 index 0f95d8c..8a9afc5 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,6 +1,6 @@ <# .SYNOPSIS -Runs the script tests, bundles DOMQL, builds the package project and its C# tests, runs them, and checks its formatting. +Runs the script tests, bundles DOMQL, builds the package project, and checks its formatting. .PARAMETER Clean Removes every build output first, so the build starts from nothing. @@ -60,7 +60,6 @@ if ($Clean) { # The package project's bin and obj, its bundle, and the packed artifacts, which dotnet clean alone leaves behind. Write-Host 'Cleaning' Get-ChildItem $nuget -Directory -Recurse -Include 'bin', 'obj', 'wwwroot' | Remove-Item -Recurse -Force - Get-ChildItem (Join-Path $tests 'dotnet') -Directory -Include 'bin', 'obj' | Remove-Item -Recurse -Force if (Test-Path $artifacts) { Remove-Item $artifacts -Recurse -Force } @@ -160,12 +159,6 @@ try { throw 'dotnet build failed.' } - Write-Host 'Testing the C# half' - dotnet test --solution $solution --no-build - if ($LASTEXITCODE -ne 0) { - throw 'The C# tests failed.' - } - Write-Host 'Checking formatting' dotnet format $solution --verify-no-changes if ($LASTEXITCODE -ne 0) { diff --git a/docs/decisions.md b/docs/decisions.md index 67ad1c9..ea4fe28 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -1852,9 +1852,10 @@ Each entry is one of three kinds: *December 1, 2026* +- **Moved** to [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET), a project of its own, by [D120](#d120), whose records hold it as their D1. - **Kind:** Contract, replacing [D46](#d46) by the owner's direction that DOMQL's transport is the one its hosts use. - **Decision:** - - [The .NET half](../spec/dotnet.md) ships in the NuGet package. `AddDomql` registers one `DomqlConnection` for each scope, through its `IJSRuntime`. + - The .NET half ships in the NuGet package. `AddDomql` registers one `DomqlConnection` for each scope, through its `IJSRuntime`. - Each turn's requests cross in one call, as the turn ends on its synchronization context. - A watch keeps its copy as JSON, applies each change set by DOMQL's rules before it acknowledges the batch, and calls its handler after, one call at a time, with the latest result. - An event's handler completes before its batch is acknowledged, and its answer answers the event source. @@ -1872,3 +1873,19 @@ Each entry is one of three kinds: - `TryQuery`, checking text in .NET. A second parser would have to agree with Nexo's at every release. - Acknowledging a watch's change once its handler completes. A slow handler would hold every change after it. - A reconnection hook in the package. It would tie the package to one way of hosting .NET; `RefreshAsync` is the host's to call. + + + +## D120 — The .NET half is a project of its own + +*December 1, 2026* + +- **Kind:** Process, by the owner's direction. +- **Decision:** + - The .NET half moves to [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET), a repository of its own, with its own solution, workspace, gate, records and package, `formaui-net.DOMQL.NET`. Its types keep the namespace `Domql`. + - DOMQL keeps the [connection](../spec/connections.md), which any host across a boundary speaks, and the change sets' conformance corpus, which is part of its contract and which DOMQL.NET's tests read. + - DOMQL's NuGet package goes back to the bundle alone, with no dependency on Microsoft.JSInterop, and its gate runs no C# tests. The codes the .NET half reports, `DOMQL5028` to `DOMQL5030`, stay reserved for it. +- **Why:** + - DOMQL is a JavaScript library. Its gate, its package and its records had grown a .NET project, a C# test step and a dependency a JavaScript host never uses. + - The .NET half versions apart from DOMQL: a change to its API is no change to DOMQL's contract. +- **Declined:** Moving the connection too. DOMQL would keep no API for a host across a boundary, and DOMQL.NET would reach into DOMQL's internals. diff --git a/docs/domql-design.md b/docs/domql-design.md index c4032b8..331e2dd 100644 --- a/docs/domql-design.md +++ b/docs/domql-design.md @@ -10,7 +10,7 @@ In this document: 4. [Watching](#watching) 5. [Comparing and patching](#comparing-and-patching) 6. [Host calls and their operations](#host-calls-and-their-operations) -7. [The C# half](#the-c-half) +7. [Connections](#connections) 8. [Decisions not taken](#decisions-not-taken) ## Architecture @@ -123,50 +123,39 @@ Nexo keeps a host call's function arguments open until the prepared call is disp An owned write's target is kept by `OwnedWrites`, one for each set of the module's implementations, so one instance of the library, as its registry and its observations are: by the element in a weak map, and by a key naming the target within it, as `attribute tabindex` or `class open`, the holders of each target in the order they began, the value the target held before the first, and the value DOMQL last wrote, which it reads back from the element after writing so the browser's serialization decides it. A holder that keeps its value observes its element's attribute with a mutation observer filtered to it, one for the holding, kept through every update that holds the same target and keeps it still, as [D85](decisions.md#d85) records, the `class` and `style` attributes for a class and a style property, and its child list and their text for its text, and writes its value again among the next animation frame's writes, through the environment's `frame`, rather than in the mutation's own microtask, so a frame watch reads the value kept in the frame it was written in. Having written again, it notes the attribute or the text as the other writer left it, from the target's `written`, and asks two frames more of the schedule. A change before the second runs that restores what it noted is an answer: the writer keeps a value of its own, in a microtask or a frame of its own, so the holder yields to it, writing nothing more until its next update, where two writers that each kept a value would alternate once a frame without end. A change that leaves anything else is a patch, a framework rendering the element again, and is undone as the first was. A text target writes the data of the element's one text node, finding the node again at each read and write, so a framework that rendered it keeps it. -## The C# half + -The C# half is DOMQL from a .NET application, as [the .NET half](../spec/dotnet.md) specifies it. It is DOMQL's own host of a [connection](../spec/connections.md), and keeps a copy of each result its watches deliver, as [keeping a copy of a result](../spec/results.md#results-keeping-a-copy) sets out. [D118](decisions.md#d118) records the connection and [D119](decisions.md#d119) the half. +## Connections + +A host whose code runs elsewhere, as a .NET application's does, reaches DOMQL through a [connection](../spec/connections.md), as [D118](decisions.md#d118) records. [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET), a project of its own, is DOMQL's host of one for .NET applications, as [D120](decisions.md#d120) records. | Part | What it does | Source | | --- | --- | --- | -| The connection, in the browser | Carries a host's requests out in batches, answering each once its task ends, and sends the deliveries of each task together, a watch's paced by the acknowledgment of the one before it | `src/connections/Connection.mjs` | -| Its module for .NET | Opens a connection whose deliveries reach .NET, each batch as text within a budget and as a stream beyond it | `nuget/scripts/domql.dotnet.js`, served beside the bundle | -| The connection, in .NET | Queues the requests of one turn and sends them as one call once the connection has opened, routes each answer and delivery to its handle, and names each query by its key once the browser has made it | `DomqlConnection`, `DomqlRequest`, `DomqlReceiver` | -| Owners and handles | Start operations for an owner, end every one of them in one request, and drop what an earlier generation delivered | `DomqlOwner`, `DomqlHandle`, `DomqlWatch`, `DomqlSubscription`, `DomqlExecution` | -| The copy | Applies change sets by DOMQL's rules, and maps the copy onto the query's type | `DomqlChangeSet`, `DomqlQuery` | +| The connection | Carries a host's requests out in batches, answering each once its task ends, and sends the deliveries of each task together, a watch's paced by the acknowledgment of the one before it | `src/connections/Connection.mjs` | +| The conformance corpus | Each case a previous result, a change set and the result they give, which DOMQL's applier passes, and a host's that keeps a copy of a result | `tests/_conformance/change-sets.json` | -### A turn, a task +### A task's requests and deliveries -- **.NET's side.** A request is queued as it is made. The first of a turn posts a flush to the synchronization context it was made in, so it runs once the turn ends: every watch, subscription and execution the turn starts crosses in one call. The flush waits for the connection to open, and takes what is queued then, so the requests made while the module imports cross with the first batch. -- **The browser's side.** - - A batch's answers settle once the task that carried its requests out has ended. A message posted to the window's own channel runs after that task's microtasks. - - A watch evaluates first in a microtask, so its snapshot answers its request, and so does an execution that settles at once, as a focus or an instant scroll does. - - Deliveries are queued as they happen, and a microtask sends the task's together. -- **Answers and deliveries race.** The runtime orders no call's result before the calls the browser makes while it runs, so a delivery sent during a request's task may reach .NET before its answer. A watch holds such deliveries, and applies them in order after its answer's snapshot. +- **A batch's answers** settle once the task that carried its requests out has ended. A message posted to the window's own channel runs after that task's microtasks. +- **A watch evaluates first in a microtask,** so its snapshot answers its request, and so does an execution that settles at once, as a focus or an instant scroll does. +- **Deliveries are queued as they happen,** and a microtask sends the task's together. +- **Answers and deliveries race.** A transport may deliver a call the browser makes during a request's task before that request's answer, so a host holds a watch's deliveries until its answer arrives. -### Watches and their copies +### Watches - **A watch in the browser** watches live state, so each change event carries its change set. Its first result answers its request, or is delivered whole. - **One delivery in flight.** Each later delivery waits for the acknowledgment of the batch holding the one before it. What arises meanwhile is joined: change sets concatenated, since they compose ([D65](decisions.md#d65)), unless the snapshot whole is shorter; a snapshot whole in place of what waits before it; a failure kept in its place. -- **.NET applies, then acknowledges.** It applies a change set to its copy, a `JsonNode`, and maps it onto the query's type before the batch is acknowledged. The watch's handler is called after, one call at a time, with the latest result. So a slow handler never holds the next change set, and never sees a copy partly applied. -- **An uncertain copy.** A change set that doesn't apply makes the copy uncertain. The watch asks for its snapshot whole, and skips change sets until it arrives. -- **Reconnecting.** A host whose connection to the browser resumes calls `RefreshAsync`, which has every watch deliver its snapshot whole in one request. ### Events -- **An event is delivered as it happens.** It is never held behind a watch's acknowledgment, nor joined, as [D69](decisions.md#d69) requires. -- **.NET awaits its handler** before it answers the batch. So the event's acknowledgment in the browser follows the handler, and its answer answers the event source. +- **An event is delivered as it happens.** It is never held behind a watch's acknowledgment, nor joined, as [D69](decisions.md#d69) requires. Its acknowledgment settles as the host's answer does. - **A limit.** A batch sent while earlier ones have left 4,096 deliveries unacknowledged closes the connection; one task of many deliveries crosses whole, so a refresh of thousands of watches closes nothing. ### Queries and their keys -- **A query's key.** Each query has a key in its connection, by its text and its declared types. Its text crosses with the first request that names it in a batch. Every request after the browser made it names it by its key alone. A query the browser refused crosses with its text again. +- **A query's key.** A host names a query by a key of its own, giving its text with the first request that needs it, and naming it by its key alone after. A query the browser refused is made by no key. - **Many panes, one text.** A page of fifty panes, each watching one query, sends its text once. -### Crossings - -The calls each operation takes, between .NET and the browser, are [the .NET half's crossings](../spec/dotnet.md#dotnet-crossings). A first operation imports one module, the one the package serves beside the bundle. - ## Decisions not taken Each of these was considered, measured where cost decided it, and not adopted. It is reopened only by the need its row names. diff --git a/docs/features-status.md b/docs/features-status.md index 11fff5a..8229170 100644 --- a/docs/features-status.md +++ b/docs/features-status.md @@ -12,7 +12,7 @@ - **The language DOMQL runs on.** DOMQL follows Nexo's language `1.0.0-preview.3`, which Nexo's release `1.0.0-preview.4` carries, the version of Nexo's npm package DOMQL installs, as [D108](decisions.md#d108), [D109](decisions.md#d109) and [D114](decisions.md#d114) record, and its documents link to [Nexo's documents at that tag](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/spec/README.md), moving with the pin. The language was called Lexica before the [migration](#migration-to-nexo). - **Packages.** The bundle and type declarations are built, with Nexo bundled inside `domql.js`. The npm package holds DOMQL's sources, which import Nexo's package, and the NuGet package the bundle. Both carry the runtime version, and `release.yml` publishes each from a release's tag: the NuGet package from `1.0.0-preview.1`, and the npm package from `1.0.0-preview.2`. -- **The C# half** is implemented: a [connection](../spec/connections.md) carries DOMQL's operations across a boundary, and [the .NET half](../spec/dotnet.md) is DOMQL's own host of one, as [D118](decisions.md#d118) and [D119](decisions.md#d119) record. +- **The C# half** is implemented: a [connection](../spec/connections.md) carries DOMQL's operations across a boundary, as [D118](decisions.md#d118) records, and [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET), a project of its own, is DOMQL's host of one for .NET applications, as [D120](decisions.md#d120) records. The [specification](../spec/README.md) defines the contract, and the [design](domql-design.md) explains the architecture. The [version history](../VERSION-HISTORY.md) records what each version changed, and the [changelog](../CHANGELOG.md) each release of the packages. This file tracks DOMQL's implementation and its remaining work. "Implemented" means built and tested in the gate for the current implementation version; it does not imply that later specification changes are implemented. @@ -133,7 +133,7 @@ Each feature, the contract that states it, its state in the implementation, and | Delivery options: a delayed schedule a refresh flushes, reporting on parts, and a subscription's throttle | [The delayed schedule](../spec/watches.md#watching-delayed), [reporting on parts](../spec/results.md#results-reporting-on-parts), [throttling](../spec/events.md#events-throttling) | Implemented, as [D73](decisions.md#d73) records | [`alpha.318`](../VERSION-HISTORY.md#v1-0-0-alpha-318) | | The beta, its promise and the changelog | [Version history](../VERSION-HISTORY.md#v1-0-0-beta-1), [changelog](../CHANGELOG.md) | Implemented, as [D75](decisions.md#d75) records | [`beta.1`](../VERSION-HISTORY.md#v1-0-0-beta-1) | | The preview, the beta's promise under FormaUI Versioning's name for it | [Stages](https://github.com/FormaUI/Versioning/blob/v1.0.0-preview.1/docs/versions.md#stages) | Implemented, as [D106](decisions.md#d106) records | [`preview.1`](../VERSION-HISTORY.md#v1-0-0-preview-1) | -| The C# half: a connection, and the .NET half over it, mapping results onto types and keeping a copy of each watch's | [Connections](../spec/connections.md), [the .NET half](../spec/dotnet.md) | Implemented, as [D118](decisions.md#d118) and [D119](decisions.md#d119) record | [`preview.2`](../VERSION-HISTORY.md#v1-0-0-preview-2) | +| A connection, carrying DOMQL's operations across a boundary as messages, which [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET) hosts for .NET applications | [Connections](../spec/connections.md) | Implemented, as [D118](decisions.md#d118) records | [`preview.2`](../VERSION-HISTORY.md#v1-0-0-preview-2) | @@ -156,16 +156,13 @@ Contracts: [Queries](../spec/queries.md), [types](../spec/vocabulary.md#vocabula ## The C# half -**Implemented.** [D118](decisions.md#d118) and [D119](decisions.md#d119) record it, in place of the outline [D46](decisions.md#d46) waited with. +**Implemented.** [D118](decisions.md#d118) records the connection, in place of the outline [D46](decisions.md#d46) waited with, and [D120](decisions.md#d120) the .NET half's move to a project of its own. - **A connection,** `domql.connect`, carries a host's requests in batches, answered as their task ends, and sends each task's deliveries together, a watch's paced by its acknowledgment and an event behind nothing. -- **The .NET half:** `DomqlConnection`, one for each browser runtime; owners that end every operation they started in one request; watches keeping a copy by change sets; subscriptions whose handlers answer their events; continuous and once executions; and failures carried with their code, kind and location. -- **One way of applying:** the conformance corpus, `tests/_conformance/change-sets.json`, which DOMQL's JavaScript applier and the .NET half's both pass. -- **Its tests** run in the gate: the connection's in Node, and the .NET half's through a browser that answers as the connection does. +- **[DOMQL.NET](https://github.com/FormaUI/DOMQL.NET)** is DOMQL's host of one for .NET applications, with its own specification, status and records. +- **One way of applying:** the conformance corpus, `tests/_conformance/change-sets.json`, which DOMQL's JavaScript applier passes, and DOMQL.NET's tests read and pass. -**Remaining:** a test that drives the .NET half through a real browser and a .NET host, as the full gate drives the packages. - -Contracts: [The C# half](domql-design.md#the-c-half), [keeping a copy of a result](../spec/results.md#results-keeping-a-copy). +Contracts: [Connections](domql-design.md#connections), [keeping a copy of a result](../spec/results.md#results-keeping-a-copy). @@ -177,7 +174,7 @@ The language's part is Nexo's already, adopted with the [migration](#migration-t **The order of the work:** -1. **The C# half** (A1), with its queue of ordered delivery (A5), implemented, as [D118](decisions.md#d118) and [D119](decisions.md#d119) record. +1. **The C# half** (A1), with its queue of ordered delivery (A5), implemented: the connection in DOMQL, as [D118](decisions.md#d118) records, and [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET) over it, as [D120](decisions.md#d120) records. @@ -241,7 +238,7 @@ None remains: C1 to C14 are implemented, as [the features](#the-host) show, each ### API and host -A1 and A5's queue are implemented, as [D118](decisions.md#d118) and [D119](decisions.md#d119) record. A2 to A10 are implemented, as [the features](#the-host) show, or declined where their decisions say why. What their decisions settled: +A1 and A5's queue are implemented, as [D118](decisions.md#d118) and [D120](decisions.md#d120) record. A2 to A10 are implemented, as [the features](#the-host) show, or declined where their decisions say why. What their decisions settled: - Change sets compose by concatenation, so a host coalesces them itself ([D65](decisions.md#d65)). - A refresh takes new samples where it is asked to, and delivering an equal result needs nothing new ([D66](decisions.md#d66)). @@ -255,7 +252,7 @@ A1 and A5's queue are implemented, as [D118](decisions.md#d118) and [D119](decis | | Addition | | --- | --- | -| A1 | **The C# half,** implemented, as [the .NET half](../spec/dotnet.md) sets out: typed queries mapped onto records, watches, once and continuous executions and subscriptions, with failures reported, never discarded. Its acknowledgement follows the application of an update, never the application's handlers | +| A1 | **The C# half,** implemented by [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET), a project of its own: typed queries mapped onto records, watches, once and continuous executions and subscriptions, with failures reported, never discarded. Its acknowledgement follows the application of an update, never the application's handlers | | A5 | **The C# half's queue of ordered delivery:** bounded, never coalesced, failing explicitly on overflow, carrying across the boundary the order the JavaScript side already keeps. Implemented by the [connection](../spec/connections.md#connections-pacing) | @@ -317,7 +314,7 @@ Nexo's packages are published from its `1.0.0-preview.1`, as its [release](https | --- | --- | --- | | **Nexo's 1.0.** DOMQL runs on Nexo's 1.0, from its published packages. | DOMQL's contract holds the language its queries are written in, so it promises no more than Nexo does. | Nexo is in its preview, at `1.0.0-preview.4`, as [what Nexo's 1.0 requires](https://github.com/FormaUI/Nexo/blob/v1.0.0-preview.4/docs/features-status.md#what-1-0-requires) sets out. | | **Contracts settled.** No decision is open, and each [deferred](#deferred) item and [decision not taken](domql-design.md#decisions-not-taken) is shown to land without a break. | What may still change after 1.0 must be able to change compatibly. | Holds: no decision is open, and each [deferred](#deferred) item and [decision not taken](domql-design.md#decisions-not-taken) lands as an addition or within the implementation. A watch's promise to evaluate its whole query each time was the one that would have made evaluating less a break; [what an evaluation gives](../spec/watches.md#watching-what-an-evaluation-gives) now leaves it to DOMQL. | -| **The C# half decided.** It is designed, or decided to follow 1.0 as an addition. | A .NET application may need it to drive DOMQL. | Holds: the connection and the .NET half are implemented, as [D118](decisions.md#d118) and [D119](decisions.md#d119) record. | +| **The C# half decided.** It is designed, or decided to follow 1.0 as an addition. | A .NET application may need it to drive DOMQL. | Holds: the connection is implemented, as [D118](decisions.md#d118) records, and [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET) hosts it for .NET applications, as [D120](decisions.md#d120) records. | | **Published.** DOMQL's packages are on npm and NuGet, tested as consumers install them. | A caller pins a release it can install. | Holds: the NuGet package is published from `1.0.0-preview.1` and the npm package from `1.0.0-preview.2`, each verified as consumers install it before its release. | | **Used for real.** Forma's own scripts run as DOMQL queries, watches, subscriptions and executions on a published release. | The [planned capabilities](#planned-capabilities) came from reading those scripts, and only running them settles the contract. | Planned. | | **A release candidate that breaks nothing.** `1.0.0-rc.1` is released once the rest hold, and Forma takes it with no change but its version. `1.0.0` is its contract, unchanged. | It is the last check that nothing still needs to break. | Waits for the rest. | diff --git a/nuget/DomqlChangeSet.cs b/nuget/DomqlChangeSet.cs deleted file mode 100644 index 6f8dba0..0000000 --- a/nuget/DomqlChangeSet.cs +++ /dev/null @@ -1,184 +0,0 @@ -namespace Domql; - -using System.Globalization; -using System.Text.Json; -using System.Text.Json.Nodes; - -/// -/// Applies a change set to a copy of a result, by DOMQL's rules: a JSON Patch document of replace, add, remove and move, each operation applied after the one before it, its paths -/// JSON Pointers into the result as that operation finds it. One that names no place in the copy fails with DOMQL5029. -/// -internal static class DomqlChangeSet -{ - /// The copy the change set gives, changed in place where it can be, and replaced where an operation replaces the root. - public static JsonNode? Apply(JsonNode? copy, JsonElement changes) - { - if (changes.ValueKind != JsonValueKind.Array) - { - throw Unapplied("it is no list of operations"); - } - - foreach (var operation in changes.EnumerateArray()) - { - var kind = operation.TryGetProperty("op", out var op) && op.ValueKind == JsonValueKind.String ? op.GetString() : null; - - copy = kind switch - { - "replace" => Put(copy, PathOf(operation, "path"), ValueOf(operation), isReplacing: true), - "add" => Put(copy, PathOf(operation, "path"), ValueOf(operation), isReplacing: false), - "remove" => Take(copy, PathOf(operation, "path"), out _), - "move" => Move(copy, PathOf(operation, "from"), PathOf(operation, "path")), - _ => throw Unapplied($"its operation {kind ?? "with no op"} is none of replace, add, remove and move"), - }; - } - - return copy; - } - - private static JsonNode? Move(JsonNode? copy, string[] from, string[] path) - { - copy = Take(copy, from, out var moved); - - return Put(copy, path, moved, isReplacing: false); - } - - /// Puts a value at a path: replacing what stands there, or adding it, a list's item inserted before the index or appended at -. - private static JsonNode? Put(JsonNode? copy, string[] path, JsonNode? value, bool isReplacing) - { - if (path.Length == 0) - { - return value; - } - - var parent = Navigate(copy, path.AsSpan(0, path.Length - 1)); - var token = path[^1]; - - switch (parent) - { - case JsonObject members: - if (isReplacing && !members.ContainsKey(token)) - { - throw Unapplied($"it replaces '{token}', which the object doesn't hold"); - } - - members[token] = value; - - break; - case JsonArray items: - if (!isReplacing && token == "-") - { - items.Add(value); - } - else - { - var index = IndexOf(token, isReplacing ? items.Count - 1 : items.Count); - - if (isReplacing) - { - items[index] = value; - } - else - { - items.Insert(index, value); - } - } - - break; - default: - throw Unapplied($"it puts a value inside {Describe(parent)}"); - } - - return copy; - } - - /// Takes the value at a path out of the copy. - private static JsonNode? Take(JsonNode? copy, string[] path, out JsonNode? taken) - { - if (path.Length == 0) - { - throw Unapplied("it takes the whole result out, which no change set does"); - } - - var parent = Navigate(copy, path.AsSpan(0, path.Length - 1)); - var token = path[^1]; - - switch (parent) - { - case JsonObject members when members.TryGetPropertyValue(token, out taken): - members.Remove(token); - - return copy; - case JsonArray items: - var index = IndexOf(token, items.Count - 1); - - taken = items[index]; - items.RemoveAt(index); - - return copy; - default: - throw Unapplied($"it takes '{token}' out of {Describe(parent)}, which doesn't hold it"); - } - } - - private static JsonNode? Navigate(JsonNode? node, ReadOnlySpan tokens) - { - foreach (var token in tokens) - { - node = node switch - { - JsonObject members when members.TryGetPropertyValue(token, out var member) => member, - JsonArray items => items[IndexOf(token, items.Count - 1)], - _ => throw Unapplied($"its path reaches '{token}' in {Describe(node)}, which doesn't hold it"), - }; - } - - return node; - } - - /// A list index a token names: a whole number of no leading zero, at most the largest given. - private static int IndexOf(string token, int largest) - { - if (token.Length == 0 || token.Length > 1 && token[0] == '0' || !token.All(char.IsAsciiDigit) || !int.TryParse(token, NumberStyles.None, CultureInfo.InvariantCulture, out var index) || index > largest) - { - throw Unapplied($"its index '{token}' names no item of a list of {largest + 1}"); - } - - return index; - } - - /// A JSON Pointer's reference tokens, unescaped: ~1 as /, then ~0 as ~. - private static string[] PathOf(JsonElement operation, string name) - { - if (!operation.TryGetProperty(name, out var path) || path.ValueKind != JsonValueKind.String) - { - throw Unapplied($"an operation gives no {name}"); - } - - var pointer = path.GetString()!; - - if (pointer.Length == 0) - { - return []; - } - - if (pointer[0] != '/') - { - throw Unapplied($"its path '{pointer}' is no JSON Pointer"); - } - - return [.. pointer[1..].Split('/').Select(token => token.Replace("~1", "/", StringComparison.Ordinal).Replace("~0", "~", StringComparison.Ordinal))]; - } - - private static JsonNode? ValueOf(JsonElement operation) => - operation.TryGetProperty("value", out var value) ? JsonNode.Parse(value.GetRawText()) : throw Unapplied("an operation that puts a value gives none"); - - private static string Describe(JsonNode? node) => node switch - { - null => "null", - JsonObject => "an object", - JsonArray => "a list", - _ => "a value", - }; - - private static DomqlException Unapplied(string reason) => new("DOMQL5029", "evaluation", $"A change set doesn't apply to the watch's copy: {reason}"); -} diff --git a/nuget/DomqlConnection.cs b/nuget/DomqlConnection.cs deleted file mode 100644 index cb7cfa3..0000000 --- a/nuget/DomqlConnection.cs +++ /dev/null @@ -1,462 +0,0 @@ -namespace Domql; - -using System.Text; -using System.Text.Json; - -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions; -using Microsoft.JSInterop; - -/// -/// DOMQL in one browser runtime, as a .NET application reaches it. Every request one turn of the application makes crosses as one call, its answers return in that call's answer, and the deliveries of one -/// browser task cross back as one call. A connection belongs to one JavaScript runtime and is used from one synchronization context, the one its runtime's callbacks run on. -/// -public sealed class DomqlConnection : IAsyncDisposable -{ - private readonly IJSRuntime _jsRuntime; - private readonly DomqlConnectionOptions _options; - private readonly ILogger _logger; - private readonly Lock _gate = new(); - private readonly Dictionary _handles = []; - private readonly Dictionary _queryKeys = [with(StringComparer.Ordinal)]; - private readonly HashSet _madeQueries = []; - private readonly HashSet _ownerNames = [with(StringComparer.Ordinal)]; - private List _pending = []; - private bool _isFlushScheduled; - private Task? _opened; - private DotNetObjectReference? _receiver; - private long _lastHandle; - private long _lastQuery; - private long _lastOwner; - private bool _isDisposed; - private bool _isRefreshingUnread; - - /// A connection through the JavaScript runtime given, which opens as its first request crosses. - /// The runtime of the browser it reaches. - /// Where it finds DOMQL, and how much it reads of a delivery. - /// What it reports a handler's failure to, which reaches no other caller. - public DomqlConnection(IJSRuntime jsRuntime, DomqlConnectionOptions? options = null, ILogger? logger = null) - { - ArgumentNullException.ThrowIfNull(jsRuntime); - - _jsRuntime = jsRuntime; - _options = options ?? new DomqlConnectionOptions(); - _logger = logger ?? NullLogger.Instance; - } - - /// - /// An owner: who carries out the operations it starts, which their implementations in the browser receive, and whose disposal ends every one of them in one request. - /// - /// Its name in the browser, unique among the connection's owners until it is disposed; one of its own where none is given. A name in use is refused. - public DomqlOwner CreateOwner(string? name = null) - { - lock (_gate) - { - ObjectDisposedException.ThrowIf(_isDisposed, this); - - if (name is not null && !_ownerNames.Add(name)) - { - throw new ArgumentException($"An owner named '{name}' is in use, and a release names one owner alone; give each owner a name of its own", nameof(name)); - } - - while (name is null) - { - var generated = $"owner-{++_lastOwner}"; - - if (_ownerNames.Add(generated)) - { - name = generated; - } - } - - return new DomqlOwner(this, name); - } - } - - /// - /// Evaluates every watch the connection runs and delivers each one's snapshot whole, changed or not, as a host does once its connection to the browser has resumed and a delivery may have been lost on the way. - /// - public Task RefreshAsync() => SendAsync(new DomqlRequest("refresh")); - - /// Ends every operation the connection started, in the browser and here, and releases what it holds of the runtime. - public async ValueTask DisposeAsync() - { - IDomqlRoute[] handles; - - lock (_gate) - { - if (_isDisposed) - { - return; - } - - _isDisposed = true; - handles = [.. _handles.Values]; - _handles.Clear(); - } - - foreach (var handle in handles) - { - handle.End(); - } - - // An opening under way is awaited, so what it opens is closed; a request after disposal opens nothing. - if (_opened is { } opened) - { - try - { - var connection = await opened.ConfigureAwait(false); - - await connection.InvokeVoidAsync("close").ConfigureAwait(false); - await connection.DisposeAsync().ConfigureAwait(false); - } - catch (Exception error) when (error is not OutOfMemoryException) - { - // A runtime that is gone, or an opening that failed, holds nothing of the connection's. - } - } - - _receiver?.Dispose(); - } - - /// Frees an owner's name once its release is queued, which crosses before any request of an owner that takes it again. - internal void ReleaseOwnerName(string name) - { - lock (_gate) - { - _ownerNames.Remove(name); - } - } - - /// The next handle's id, unique within the connection. - internal long CreateHandleId() => Interlocked.Increment(ref _lastHandle); - - /// Registers a handle, whose answers and deliveries reach it until it ends. - internal void Register(IDomqlRoute handle) - { - lock (_gate) - { - ObjectDisposedException.ThrowIf(_isDisposed, this); - _handles.Add(handle.Id, handle); - } - } - - /// Stops routing to a handle that has ended. - internal void Unregister(IDomqlRoute handle) - { - lock (_gate) - { - _handles.Remove(handle.Id); - } - } - - /// Every handle of an owner, which its release ends. - internal IDomqlRoute[] HandlesOf(DomqlOwner owner) - { - lock (_gate) - { - return [.. _handles.Values.Where(handle => handle.Owner == owner)]; - } - } - - /// The key a query's text and declared types go by in this connection, which every request after the first that crosses with its text names it by. - internal long QueryKeyOf(DomqlQuery query) - { - lock (_gate) - { - if (!_queryKeys.TryGetValue(query.Identity, out var key)) - { - key = ++_lastQuery; - _queryKeys.Add(query.Identity, key); - } - - return key; - } - } - - /// - /// Queues a request, which crosses with every other the same turn makes, once the turn ends, and answers a task of its answer. A request the connection can't carry fails its task with the reason. - /// - internal Task SendAsync(DomqlRequest request) - { - lock (_gate) - { - if (_isDisposed) - { - return Task.FromException(new ObjectDisposedException(nameof(DomqlConnection))); - } - - _pending.Add(request); - - if (!_isFlushScheduled) - { - _isFlushScheduled = true; - ScheduleFlush(); - } - } - - return request.Answer; - } - - /// - /// The deliveries of one browser task, applied in the order they happened, each answered: a subscription's event with its handler's answer, anything else with null. A delivery to a handle that has ended is - /// answered with null and goes no further. - /// - internal async Task ReceiveAsync(DomqlTransfer transfer) - { - JsonDocument? read = null; - JsonElement deliveries; - - try - { - if (transfer.Deliveries is { } given) - { - deliveries = given; - } - else - { - read = JsonDocument.Parse(await ReadAsync(transfer.Stream).ConfigureAwait(true)); - deliveries = read.RootElement; - } - - if (deliveries.ValueKind != JsonValueKind.Array) - { - throw new DomqlException("DOMQL5030", "evaluation", "A batch of deliveries crossed as something other than a list"); - } - } - catch (Exception error) when (error is not OutOfMemoryException) - { - read?.Dispose(); - - // A batch that can't be read leaves every copy uncertain, so each watch delivers its snapshot whole; the batch is acknowledged, answering nothing. One refresh at a time: a batch that can't be - // read while one is under way, as a snapshot past the size the connection reads is, refreshes nothing more until a batch is read. - DomqlLog.BatchUnread(_logger, error); - - if (!_isRefreshingUnread) - { - _isRefreshingUnread = true; - _ = RefreshQuietlyAsync(); - } - - return []; - } - - _isRefreshingUnread = false; - - using var reading = read; - - var answers = new object?[deliveries.GetArrayLength()]; - var index = 0; - - foreach (var delivery in deliveries.EnumerateArray()) - { - IDomqlRoute? handle = null; - - if (delivery.TryGetProperty("handle", out var id) && id.TryGetInt64(out var handleId)) - { - lock (_gate) - { - _handles.TryGetValue(handleId, out handle); - } - } - - if (handle is not null) - { - try - { - answers[index] = await handle.DeliverAsync(delivery.Clone()).ConfigureAwait(true); - } - catch (Exception error) when (error is not OutOfMemoryException) - { - // A handler's failure stays its own: the batch is acknowledged, and the deliveries after it applied. - DomqlLog.HandlerFailed(_logger, handle.Id, error); - } - } - - index++; - } - - return answers; - } - - /// Refreshes every watch, as a batch that can't be read asks, where the connection can still carry the request. - internal async Task RefreshQuietlyAsync() - { - try - { - await RefreshAsync().ConfigureAwait(true); - } - catch (Exception error) when (error is DomqlException or ObjectDisposedException) - { - // A connection that can't carry it has no watch left to refresh. - } - } - - /// Reports a handler's failure, which reaches no caller of its own. - internal void ReportHandlerFailure(long handle, Exception error) => DomqlLog.HandlerFailed(_logger, handle, error); - - /// Sends the requests queued once the turn that queued them ends: posted to the synchronization context they were made in, or, without one, run once the caller yields. - private void ScheduleFlush() - { - var context = SynchronizationContext.Current; - - if (context is not null) - { - context.Post(static state => _ = ((DomqlConnection)state!).FlushAsync(), this); - } - else - { - _ = Task.Run(FlushAsync); - } - } - - /// - /// Sends the requests queued, in order, as one call, once the connection has opened, so those made while it opened cross with them; and hands each its answer. A call that fails fails every request it - /// carried, and an opening that fails every request queued. - /// - private async Task FlushAsync() - { - List batch; - IJSObjectReference connection; - - try - { - ObjectDisposedException.ThrowIf(_isDisposed, this); - connection = await OpenAsync().ConfigureAwait(true); - ObjectDisposedException.ThrowIf(_isDisposed, this); - } - catch (Exception error) when (error is not OutOfMemoryException) - { - lock (_gate) - { - batch = _pending; - _pending = []; - _isFlushScheduled = false; - } - - Fail(batch, error); - - return; - } - - lock (_gate) - { - batch = _pending; - _pending = []; - _isFlushScheduled = false; - } - - if (batch.Count == 0) - { - return; - } - - try - { - var crossing = new HashSet(); - var requests = new object[batch.Count]; - - lock (_gate) - { - // A query's text crosses with the first request of the batch that names a query the browser hasn't made, and every later one names it by its key. - for (var index = 0; index < batch.Count; index++) - { - requests[index] = batch[index].Write(key => _madeQueries.Contains(key) || !crossing.Add(key)); - } - } - - var answers = await connection.InvokeAsync("requestAsync", [requests]).ConfigureAwait(true); - - lock (_gate) - { - // A query the browser made, answered with no error by the request its text crossed with, is named by its key alone from here on; one it refused crosses with its text again. - for (var index = 0; index < batch.Count && index < answers.Length; index++) - { - if (batch[index].CarriedQuery is { } key && !answers[index].TryGetProperty("error", out _)) - { - _madeQueries.Add(key); - } - } - } - - for (var index = 0; index < batch.Count; index++) - { - batch[index].Complete(index < answers.Length ? answers[index] : default); - } - } - catch (Exception error) when (error is not OutOfMemoryException) - { - Fail(batch, error); - } - } - - /// Fails every request of a batch with what kept it from crossing. - private static void Fail(List batch, Exception error) - { - var failure = error as DomqlException ?? DomqlException.Unsent(error); - - foreach (var request in batch) - { - request.Fail(failure); - } - } - - /// Imports the module a connection opens, and opens it, once; a failed opening is tried again by the next request. - private Task OpenAsync() - { - lock (_gate) - { - ObjectDisposedException.ThrowIf(_isDisposed, this); - - if (_opened is null || _opened.IsFaulted || _opened.IsCanceled) - { - _opened = OpenOnceAsync(); - } - - return _opened; - } - } - - private async Task OpenOnceAsync() - { - _receiver ??= DotNetObjectReference.Create(new DomqlReceiver(this)); - - var module = await _jsRuntime.InvokeAsync("import", _options.ModulePath).ConfigureAwait(true); - - // The module's reference is released once it has opened the connection, which lives on in the browser on its own. - await using (module.ConfigureAwait(true)) - { - return await module.InvokeAsync("connect", _receiver, new Dictionary { ["textBudget"] = _options.TextBudget }).ConfigureAwait(true); - } - } - - /// The text of a delivery that crossed as a stream, read up to the size the options accept. - private async Task ReadAsync(IJSStreamReference? stream) - { - if (stream is null) - { - throw new DomqlException("DOMQL5030", "evaluation", "A delivery crossed with neither its text nor a stream of it"); - } - - try - { - if (stream.Length > _options.MaximumDeliverySize) - { - throw new DomqlException("DOMQL5030", "evaluation", $"A delivery of {stream.Length} bytes is larger than the {_options.MaximumDeliverySize} the connection reads"); - } - - var content = await stream.OpenReadStreamAsync(_options.MaximumDeliverySize).ConfigureAwait(true); - - await using (content.ConfigureAwait(true)) - { - using var reader = new StreamReader(content, Encoding.UTF8); - - return await reader.ReadToEndAsync().ConfigureAwait(true); - } - } - finally - { - await stream.DisposeAsync().ConfigureAwait(true); - } - } -} diff --git a/nuget/DomqlException.cs b/nuget/DomqlException.cs deleted file mode 100644 index c00a012..0000000 --- a/nuget/DomqlException.cs +++ /dev/null @@ -1,101 +0,0 @@ -namespace Domql; - -using System.Text.Json; - -/// -/// A failure DOMQL or Nexo reported in the browser, as it crossed: its code, its kind and where it stands; or a failure of the connection's own, a code of DOMQL's naming it. -/// -/// The code of the condition that failed. -/// The stage it failed in. -/// What failed. -/// Where it stands; nowhere where none is given. -/// What caused it, where something did. -public sealed class DomqlException(string code, string kind, string message, DomqlLocation? location = null, Exception? innerException = null) : Exception(message, innerException) -{ - /// A failure with no code of its own. - public DomqlException() - : this("DOMQL5030", "evaluation", "The connection failed") - { - } - - /// A failure with no code of its own, of the message given. - public DomqlException(string message) - : this("DOMQL5030", "evaluation", message) - { - } - - /// A failure with no code of its own, of the message and the cause given. - public DomqlException(string message, Exception innerException) - : this("DOMQL5030", "evaluation", message, null, innerException) - { - } - - /// The code of the condition that failed: NEXO and four digits for Nexo's, DOMQL and four digits for DOMQL's, as their errors catalog them. - public string Code { get; } = code; - - /// The stage it failed in: syntax, structure, validation, module or evaluation. - public string Kind { get; } = kind; - - /// Where it stands: in the query's text, in its definition, or in a module's declarations. - public DomqlLocation Location { get; } = location ?? DomqlLocation.None; - - /// A failure as the browser wrote it: { code, kind, message, location }, or a message alone for one that DOMQL didn't make. - internal static DomqlException FromJson(JsonElement error) - { - var code = error.TryGetProperty("code", out var codeValue) && codeValue.ValueKind == JsonValueKind.String ? codeValue.GetString()! : "DOMQL5030"; - var kind = error.TryGetProperty("kind", out var kindValue) && kindValue.ValueKind == JsonValueKind.String ? kindValue.GetString()! : "evaluation"; - var message = error.TryGetProperty("message", out var messageValue) && messageValue.ValueKind == JsonValueKind.String ? messageValue.GetString()! : "The browser reported a failure without a message"; - var location = error.TryGetProperty("location", out var locationValue) ? DomqlLocation.FromJson(locationValue) : DomqlLocation.None; - - return new DomqlException(code, kind, message, location); - } - - /// A batch that could not cross, or whose answer could not be read, as the runtime's failure gives it. - internal static DomqlException Unsent(Exception error) => - new("DOMQL5030", "evaluation", $"The connection failed to carry its requests: {error.Message}", null, error); - - /// A result the query's type can't hold. - internal static DomqlException Unmapped(Type type, Exception error) => - new("DOMQL5028", "evaluation", $"The query's result maps onto no {type.Name}: {error.Message}", null, error); -} - -/// Where a failure stands, as Nexo and DOMQL locate it; each part is null where the failure names none. -/// The JSON Pointer of the definition's node it stands at. -/// Its line in the query's text, from 1. -/// Its column in the line, from 1. -/// Its offset in the text, from 0. -/// The binding it concerns. -/// The module it stands in. -/// The type of the module it stands in. -/// The declaration it stands at. -/// The key of the declaration it concerns. -public sealed record DomqlLocation(string? Node, int? Line, int? Column, int? Offset, string? Binding, string? Module, string? Type, string? Declaration, string? DeclarationKey) -{ - /// No location. - public static DomqlLocation None { get; } = new(null, null, null, null, null, null, null, null, null); - - internal static DomqlLocation FromJson(JsonElement location) - { - if (location.ValueKind != JsonValueKind.Object) - { - return None; - } - - return new DomqlLocation( - TextOf(location, "pointer"), - NumberOf(location, "line"), - NumberOf(location, "column"), - NumberOf(location, "offset"), - TextOf(location, "binding"), - TextOf(location, "module"), - TextOf(location, "type"), - TextOf(location, "declaration"), - TextOf(location, "declarationKey")); - } - - private static string? TextOf(JsonElement location, string name) => - location.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null; - - private static int? NumberOf(JsonElement location, string name) => - location.TryGetProperty(name, out var value) && value.TryGetInt32(out var number) ? number : null; -} diff --git a/nuget/DomqlExecution.cs b/nuget/DomqlExecution.cs deleted file mode 100644 index b610ee0..0000000 --- a/nuget/DomqlExecution.cs +++ /dev/null @@ -1,182 +0,0 @@ -namespace Domql; - -using System.Text.Json; - -/// A continuous execution running in the browser for its owner: it runs from its request until it is disposed, and reports each failure it meets as it runs. -public sealed class DomqlExecution : DomqlHandle -{ - private readonly DomqlExecutionOptions _options; - - internal DomqlExecution(DomqlOwner owner, DomqlQuery query, IReadOnlyDictionary? bindings, DomqlExecutionOptions options) - : base(owner) - { - _options = options; - owner.Connection.Register(this); - - _ = ObserveAsync(owner.Connection.SendAsync(CreateRequest("run", query, bindings, Answered))); - } - - /// The failure that refused the execution, or the latest it reported; null where there is none. - public DomqlException? Error { get; private set; } - - /// Runs with other bindings, replacing them whole; a failure leaves the execution running as it was, and fails the task with it. - public async Task UpdateAsync(IReadOnlyDictionary? bindings) - { - ObjectDisposedException.ThrowIf(IsDisposed, this); - - var answer = await Owner.Connection.SendAsync(CreateRequest("update", null, bindings ?? new Dictionary(), _ => { })).ConfigureAwait(true); - - if (ErrorOf(answer) is { } error) - { - throw error; - } - } - - internal override async ValueTask DeliverAsync(JsonElement delivery) - { - if (ErrorOf(delivery) is { } error) - { - await FailAsync(error).ConfigureAwait(true); - } - - return null; - } - - private void Answered(JsonElement answer) - { - if (ErrorOf(answer) is { } error && !IsDisposed) - { - End(); - _ = FailAsync(error); - } - } - - /// A request that failed to cross fails the execution, on the context it was made in, and the execution ends. - private async Task ObserveAsync(Task sent) - { - try - { - await sent.ConfigureAwait(true); - } - catch (DomqlException error) when (!IsDisposed) - { - // The request may have run in the browser before its answer was lost, so the execution is disposed there too. - await DisposeAsync().ConfigureAwait(true); - await FailAsync(error).ConfigureAwait(true); - } - catch (Exception error) when (error is DomqlException or ObjectDisposedException) - { - // An execution that has ended, or a connection that is disposed, has nothing left to tell. - } - } - - private async Task FailAsync(DomqlException error) - { - Error = error; - - if (_options.Failed is not { } failed) - { - Owner.Connection.ReportHandlerFailure(Id, error); - - return; - } - - try - { - await failed(error).ConfigureAwait(true); - } - catch (Exception handlerError) when (handlerError is not OutOfMemoryException) - { - Owner.Connection.ReportHandlerFailure(Id, handlerError); - } - } -} - -/// A once execution or an evaluation: answered with its request where the browser settled it in the request's task, and delivered once it settles otherwise. -internal sealed class DomqlResult : IDomqlRoute -{ - private readonly DomqlQuery _query; - private readonly TaskCompletionSource _result = new(TaskCreationOptions.RunContinuationsAsynchronously); - private bool _isEnded; - - public DomqlResult(DomqlOwner owner, string kind, DomqlQuery query, IReadOnlyDictionary? bindings) - { - _query = query; - Owner = owner; - Id = owner.Connection.CreateHandleId(); - owner.Connection.Register(this); - - _ = ObserveAsync(owner.Connection.SendAsync(DomqlRouting.CreateRequest(this, 0, kind, query, bindings, Settle))); - } - - public long Id { get; } - - public DomqlOwner Owner { get; } - - /// Waits for the result; cancelling stops the wait alone. - public Task WaitAsync(CancellationToken cancellationToken) => _result.Task.WaitAsync(cancellationToken); - - public ValueTask DeliverAsync(JsonElement delivery) - { - Settle(delivery); - - return ValueTask.FromResult(null); - } - - public void End() - { - if (!_isEnded) - { - _isEnded = true; - Owner.Connection.Unregister(this); - _result.TrySetCanceled(); - } - } - - /// A request that failed to cross fails the result, its failure set before ending cancels what waits. - private async Task ObserveAsync(Task sent) - { - try - { - await sent.ConfigureAwait(true); - } - catch (Exception error) when (error is DomqlException or ObjectDisposedException) - { - _result.TrySetException(error); - End(); - } - } - - /// Settles with the value or the failure an answer or a delivery holds; one that is pending waits for its delivery. - private void Settle(JsonElement outcome) - { - if (outcome.ValueKind != JsonValueKind.Object || outcome.TryGetProperty("pending", out _)) - { - if (outcome.ValueKind != JsonValueKind.Object) - { - _result.TrySetException(new DomqlException("DOMQL5030", "evaluation", "The browser answered the request with nothing it reads")); - End(); - } - - return; - } - - if (DomqlRouting.ErrorOf(outcome) is { } error) - { - _result.TrySetException(error); - } - else if (outcome.TryGetProperty("value", out var value)) - { - try - { - _result.TrySetResult(_query.Map(value)); - } - catch (DomqlException mappingError) - { - _result.TrySetException(mappingError); - } - } - - End(); - } -} diff --git a/nuget/DomqlHandle.cs b/nuget/DomqlHandle.cs deleted file mode 100644 index 44565de..0000000 --- a/nuget/DomqlHandle.cs +++ /dev/null @@ -1,91 +0,0 @@ -namespace Domql; - -using System.Text.Json; - -/// -/// An operation a connection started in the browser for an owner: a watch, a subscription or a continuous execution. It hears its answers and its deliveries until it ends, by its disposal, its owner's, -/// the connection's, or a refusal of the request that started it. -/// -public abstract class DomqlHandle : IAsyncDisposable, IDomqlRoute -{ - private protected DomqlHandle(DomqlOwner owner) - { - Owner = owner; - Id = owner.Connection.CreateHandleId(); - } - - /// Who carries the operation out. - public DomqlOwner Owner { get; } - - /// Whether the operation has ended. - public bool IsDisposed { get; private set; } - - /// The handle's id in the connection. - internal long Id { get; } - - long IDomqlRoute.Id => Id; - - /// The generation its requests are at: raised by each update, and a delivery of an earlier one is dropped. - internal int Generation { get; private protected set; } - - /// Ends the operation in the browser and here; disposing again does nothing. A connection that is gone has ended it already. - public async ValueTask DisposeAsync() - { - GC.SuppressFinalize(this); - - if (IsDisposed) - { - return; - } - - End(); - - var request = new DomqlRequest("dispose"); - - request.Fields["handle"] = Id; - - try - { - await Owner.Connection.SendAsync(request).ConfigureAwait(true); - } - catch (Exception error) when (error is DomqlException or ObjectDisposedException) - { - // A connection that can't carry the request has no operation left to end. - } - } - - ValueTask IDomqlRoute.DeliverAsync(JsonElement delivery) => DeliverAsync(delivery); - - /// Applies a delivery of the handle, answering what the browser is answered with. - internal abstract ValueTask DeliverAsync(JsonElement delivery); - - /// Ends the handle here alone: it hears nothing more, and what waits on it is told. - internal void End() - { - if (IsDisposed) - { - return; - } - - IsDisposed = true; - Owner.Connection.Unregister(this); - Ended(); - } - - void IDomqlRoute.End() => End(); - - /// What the handle tells what waits on it as it ends. - private protected virtual void Ended() - { - } - - /// Whether a delivery is of the handle's current generation, or of none, and so applies. - private protected bool IsCurrent(JsonElement delivery) => DomqlRouting.IsCurrent(delivery, Generation); - - /// A request of the handle, its id and generation among its fields, which hands its answer to the function given. - private protected DomqlRequest CreateRequest(string kind, DomqlQuery? query, IReadOnlyDictionary? bindings, Action answered) => - DomqlRouting.CreateRequest(this, Generation, kind, query, bindings, answered); - - /// The failure an answer or a delivery holds, null where it holds none. - private protected static DomqlException? ErrorOf(JsonElement element) => DomqlRouting.ErrorOf(element); -} diff --git a/nuget/DomqlLog.cs b/nuget/DomqlLog.cs deleted file mode 100644 index db02eac..0000000 --- a/nuget/DomqlLog.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Domql; - -using Microsoft.Extensions.Logging; - -/// What a connection reports to its logger: the failures that reach no caller of their own. -internal static partial class DomqlLog -{ - [LoggerMessage(Level = LogLevel.Error, Message = "The handler of DOMQL's operation {Handle} failed, or the operation reported a failure no handler heard.")] - public static partial void HandlerFailed(ILogger logger, long handle, Exception error); - - [LoggerMessage(Level = LogLevel.Error, Message = "A batch of DOMQL's deliveries could not be read, so every watch delivers its snapshot whole.")] - public static partial void BatchUnread(ILogger logger, Exception error); -} diff --git a/nuget/DomqlOwner.cs b/nuget/DomqlOwner.cs deleted file mode 100644 index e369706..0000000 --- a/nuget/DomqlOwner.cs +++ /dev/null @@ -1,152 +0,0 @@ -namespace Domql; - -/// -/// Who carries operations out, as a component that starts them: the browser gives each implementation an operation reaches its name, as env.owner, and a command reaches the behavior running for it. -/// Disposing it ends every operation it started, in one request. -/// -public sealed class DomqlOwner : IAsyncDisposable -{ - private bool _isDisposed; - - internal DomqlOwner(DomqlConnection connection, string name) - { - Connection = connection; - Name = name; - } - - /// Its name in the browser. - public string Name { get; } - - internal DomqlConnection Connection { get; } - - /// - /// Watches a query: its first snapshot arrives with its request's answer, as waits for, and each change after it is applied to the watch's copy, the next one sent only - /// once the browser has heard it applied. is called with each result once it is applied, one call at a time, with the latest where several arrived meanwhile. - /// - public DomqlWatch Watch(DomqlQuery query, IReadOnlyDictionary? bindings = null, Func? changed = null, DomqlWatchOptions? options = null) - { - ArgumentNullException.ThrowIfNull(query); - ObjectDisposedException.ThrowIf(_isDisposed, this); - - return new DomqlWatch(this, query, bindings, changed, options ?? new DomqlWatchOptions()); - } - - /// Subscribes to a subscription: each event is mapped onto and handed to as it arrives, in the order the browser heard them. - public DomqlSubscription Subscribe(DomqlQuery query, IReadOnlyDictionary? bindings, Func handler, DomqlSubscribeOptions? options = null) - { - ArgumentNullException.ThrowIfNull(query); - ArgumentNullException.ThrowIfNull(handler); - ObjectDisposedException.ThrowIf(_isDisposed, this); - - return new DomqlSubscription(this, query, bindings, async value => - { - await handler(value).ConfigureAwait(true); - - return null; - }, options ?? new DomqlSubscribeOptions()); - } - - /// - /// Subscribes to a subscription whose event source declares answers: each event is handed to , and what it answers answers the event in the browser, as the source's - /// declared type captures it. - /// - public DomqlSubscription Subscribe(DomqlQuery query, IReadOnlyDictionary? bindings, Func> handler, DomqlSubscribeOptions? options = null) - { - ArgumentNullException.ThrowIfNull(query); - ArgumentNullException.ThrowIfNull(handler); - ObjectDisposedException.ThrowIf(_isDisposed, this); - - return new DomqlSubscription(this, query, bindings, async value => await handler(value).ConfigureAwait(true), options ?? new DomqlSubscribeOptions()); - } - - /// Runs the continuous execution a query ends in, until its handle, or this owner, is disposed. - public DomqlExecution Run(DomqlQuery query, IReadOnlyDictionary? bindings = null, DomqlExecutionOptions? options = null) - { - ArgumentNullException.ThrowIfNull(query); - ObjectDisposedException.ThrowIf(_isDisposed, this); - - return new DomqlExecution(this, query, bindings, options ?? new DomqlExecutionOptions()); - } - - /// Carries out the once execution a query ends in, answering its result, mapped onto . Cancelling stops the wait alone: the execution has started in the browser. - public Task ExecuteAsync(DomqlQuery query, IReadOnlyDictionary? bindings = null, CancellationToken cancellationToken = default) => - StartResult("execute", query, bindings, cancellationToken); - - /// Evaluates a query once, waiting for its maintained members, answering its result, mapped onto . - public Task EvaluateAsync(DomqlQuery query, IReadOnlyDictionary? bindings = null, CancellationToken cancellationToken = default) => - StartResult("evaluate", query, bindings, cancellationToken); - - /// Ends every operation the owner started, in the browser in one request and here; disposing again does nothing. - public async ValueTask DisposeAsync() - { - if (_isDisposed) - { - return; - } - - _isDisposed = true; - - foreach (var handle in Connection.HandlesOf(this)) - { - handle.End(); - } - - var request = new DomqlRequest("release"); - - request.Fields["owner"] = Name; - - var released = Connection.SendAsync(request); - - Connection.ReleaseOwnerName(Name); - - try - { - await released.ConfigureAwait(true); - } - catch (Exception error) when (error is DomqlException or ObjectDisposedException) - { - // A connection that can't carry the request has no operation left to end. - } - } - - private Task StartResult(string kind, DomqlQuery query, IReadOnlyDictionary? bindings, CancellationToken cancellationToken) - { - ArgumentNullException.ThrowIfNull(query); - ObjectDisposedException.ThrowIf(_isDisposed, this); - - return new DomqlResult(this, kind, query, bindings).WaitAsync(cancellationToken); - } -} - -/// How a watch evaluates, as query.watch's options say. -public sealed record DomqlWatchOptions -{ - /// When it evaluates after a change: frame, the default, at the next animation frame; immediate, at once; or delayed, once has passed without another. - public string? Schedule { get; init; } - - /// The time a delayed schedule waits. - public TimeSpan? Delay { get; init; } - - /// Whether it accepts members whose observations miss some changes. - public bool AcceptPartialObservation { get; init; } - - /// Hears each failure of an evaluation, and of a result its type can't hold; the connection's logger hears them where none is given. - public Func? Failed { get; init; } -} - -/// How a subscription hears its events. -public sealed record DomqlSubscribeOptions -{ - /// The least time between two events it hears, the latest heard after it; none where it hears every one. - public TimeSpan? Throttle { get; init; } - - /// Hears each failure of an event; the connection's logger hears them where none is given. - public Func? Failed { get; init; } -} - -/// How a continuous execution reports. -public sealed record DomqlExecutionOptions -{ - /// Hears each failure the execution reports while it runs; the connection's logger hears them where none is given. - public Func? Failed { get; init; } -} diff --git a/nuget/DomqlQuery.cs b/nuget/DomqlQuery.cs deleted file mode 100644 index 7553f53..0000000 --- a/nuget/DomqlQuery.cs +++ /dev/null @@ -1,101 +0,0 @@ -namespace Domql; - -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Nodes; -using System.Text.Json.Serialization.Metadata; - -/// -/// A query's text, as the browser reads it with Domql supplied, and the types it declares for its bindings. It is checked in the browser, by the first request that makes it there, which a failure answers. -/// -public abstract class DomqlQuery -{ - private protected DomqlQuery(string text, IReadOnlyDictionary? types) - { - ArgumentException.ThrowIfNullOrWhiteSpace(text); - - Text = text; - Types = types; - Identity = types is null ? text : $"{text}\0{string.Join('\0', types.OrderBy(pair => pair.Key, StringComparer.Ordinal).Select(pair => $"{pair.Key}={pair.Value}"))}"; - } - - /// The query's text. - public string Text { get; } - - /// The type of each top-level binding it declares, by its notation, as domql.query's types declares it; null where it declares none. - public IReadOnlyDictionary? Types { get; } - - /// What tells two queries apart in a connection: their text and their declared types. - internal string Identity { get; } - - /// A query whose result maps onto through the type information given, as source-generated serialization gives it. - public static DomqlQuery Create(string text, JsonTypeInfo type, IReadOnlyDictionary? types = null) - { - ArgumentNullException.ThrowIfNull(type); - - return new DomqlQuery(text, types, node => node.Deserialize(type)!, element => element.Deserialize(type)!); - } - - /// A query whose result maps onto through the serializer's options, the web's defaults where none are given. - [RequiresUnreferencedCode("Maps a result onto T by reflection; give a JsonTypeInfo to map it in a trimmed application.")] - [RequiresDynamicCode("Maps a result onto T by reflection; give a JsonTypeInfo to map it in a native application.")] - public static DomqlQuery Create(string text, JsonSerializerOptions? options = null, IReadOnlyDictionary? types = null) - { - var serializer = options ?? JsonSerializerOptions.Web; - - return new DomqlQuery(text, types, node => node.Deserialize(serializer)!, element => element.Deserialize(serializer)!); - } - - /// A query whose result is its JSON, as the browser gave it. - public static DomqlQuery Create(string text, IReadOnlyDictionary? types = null) => - new(text, types, ElementOf, element => element.Clone()); - - /// A copy's JSON as an element of its own. - private static JsonElement ElementOf(JsonNode? node) - { - using var document = JsonDocument.Parse(node?.ToJsonString() ?? "null"); - - return document.RootElement.Clone(); - } -} - -/// A query whose result maps onto : its fields onto the properties and constructor parameters of , as the serializer it was made with maps them. -/// What its result maps onto. -public sealed class DomqlQuery : DomqlQuery -{ - private readonly Func _mapNode; - private readonly Func _mapElement; - - internal DomqlQuery(string text, IReadOnlyDictionary? types, Func mapNode, Func mapElement) - : base(text, types) - { - _mapNode = mapNode; - _mapElement = mapElement; - } - - /// The result a copy holds, mapped; a result the type can't hold fails with DOMQL5028. - internal T Map(JsonNode? copy) - { - try - { - return _mapNode(copy); - } - catch (Exception error) when (error is JsonException or NotSupportedException or InvalidOperationException) - { - throw DomqlException.Unmapped(typeof(T), error); - } - } - - /// A value the browser delivered, mapped; one the type can't hold fails with DOMQL5028. - internal T Map(JsonElement value) - { - try - { - return _mapElement(value); - } - catch (Exception error) when (error is JsonException or NotSupportedException or InvalidOperationException) - { - throw DomqlException.Unmapped(typeof(T), error); - } - } -} diff --git a/nuget/DomqlReceiver.cs b/nuget/DomqlReceiver.cs deleted file mode 100644 index ccc52b8..0000000 --- a/nuget/DomqlReceiver.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace Domql; - -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; - -using Microsoft.JSInterop; - -/// What the browser delivers to: each batch of a connection's deliveries, as one call. -internal sealed class DomqlReceiver(DomqlConnection connection) -{ - /// Applies a batch of deliveries, answering one answer for each. - [JSInvokable] - public Task ReceiveAsync(DomqlTransfer transfer) => connection.ReceiveAsync(transfer); -} - -/// A batch of deliveries as it crossed: the deliveries, or, beyond the browser's budget, a stream of their JSON. -[SuppressMessage("Performance", "CA1812", Justification = "Microsoft.JSInterop creates it as it reads the argument of ReceiveAsync.")] -internal sealed class DomqlTransfer -{ - /// The deliveries, where they crossed as data. - public JsonElement? Deliveries { get; set; } - - /// A stream of the batch's JSON, as UTF-8, where it crossed as one. - public IJSStreamReference? Stream { get; set; } -} - -/// Where a connection finds DOMQL in the browser, and how much it reads of a delivery. -public sealed class DomqlConnectionOptions -{ - /// The module a connection imports and opens, as the package serves it. - public string ModulePath { get; set; } = "./_content/domql/domql.dotnet.js"; - - /// The most a batch of deliveries crosses as data, in UTF-8 bytes, measured as a server's transport writes it, its JSON escaped once more; a larger one crosses as a stream. - public int TextBudget { get; set; } = 16 * 1024; - - /// The most bytes a connection reads of a batch that crossed as a stream; a larger one fails with DOMQL5030. - public long MaximumDeliverySize { get; set; } = 16 * 1024 * 1024; -} diff --git a/nuget/DomqlRequest.cs b/nuget/DomqlRequest.cs deleted file mode 100644 index 4441509..0000000 --- a/nuget/DomqlRequest.cs +++ /dev/null @@ -1,79 +0,0 @@ -namespace Domql; - -using System.Text.Json; - -/// -/// One request a connection carries to the browser: what it asks for, its fields, the query it names, and the task its answer settles. A request is written as it crosses, so the query's text crosses only -/// with the first request that needs it. -/// -internal sealed class DomqlRequest(string kind) -{ - private readonly TaskCompletionSource _answer = new(TaskCreationOptions.RunContinuationsAsynchronously); - private readonly Action? _answered; - - /// A request that hands its answer to the function given as it arrives, before its task settles. - public DomqlRequest(string kind, Action answered) - : this(kind) - { - _answered = answered; - } - - /// The request's fields beside its kind and its query, as the browser reads them. - public Dictionary Fields { get; } = []; - - /// The query it names, with the key the connection gave it; none for a request that names none. - public (DomqlQuery Query, long Key)? Query { get; init; } - - /// The key of the query whose text crossed with this request, as it was written; null where none did. - public long? CarriedQuery { get; private set; } - - /// Settles with the request's answer, or fails with what kept it from crossing. - public Task Answer => _answer.Task; - - /// - /// The request as it crosses: its kind, its fields, and its query by its key, with its text and its declared types where the browser has not made it yet. - /// - /// Whether the browser has made the query of the key, or will have as an earlier request of the batch makes it. - public Dictionary Write(Func isMade) - { - var written = new Dictionary { ["request"] = kind }; - - foreach (var (name, value) in Fields) - { - written[name] = value; - } - - if (Query is var (query, key)) - { - if (isMade(key)) - { - written["query"] = key; - } - else - { - CarriedQuery = key; - // Dictionaries, which a trimmed application keeps, rather than anonymous types, which it may not. - var crossing = new Dictionary { ["key"] = key, ["text"] = query.Text }; - - if (query.Types is not null) - { - crossing["types"] = query.Types; - } - - written["query"] = crossing; - } - } - - return written; - } - - /// Hands the answer to the request's own receiver, then settles its task. - public void Complete(JsonElement answer) - { - _answered?.Invoke(answer); - _answer.TrySetResult(answer); - } - - /// Fails the request with what kept it from crossing. - public void Fail(DomqlException error) => _answer.TrySetException(error); -} diff --git a/nuget/DomqlRoute.cs b/nuget/DomqlRoute.cs deleted file mode 100644 index 7f4df6e..0000000 --- a/nuget/DomqlRoute.cs +++ /dev/null @@ -1,48 +0,0 @@ -namespace Domql; - -using System.Text.Json; - -/// What a connection routes its answers and deliveries to: an operation it started, by its id, until it ends. -internal interface IDomqlRoute -{ - /// Its id in the connection. - long Id { get; } - - /// Who carries it out. - DomqlOwner Owner { get; } - - /// Applies a delivery of it, answering what the browser is answered with. - ValueTask DeliverAsync(JsonElement delivery); - - /// Ends it here alone: it hears nothing more, and what waits on it is told. - void End(); -} - -/// What every operation's requests and deliveries share: the fields a request names it by, and what an answer or a delivery holds. -internal static class DomqlRouting -{ - /// A request of an operation, its id, owner and generation among its fields, which hands its answer to the function given. - public static DomqlRequest CreateRequest(IDomqlRoute route, int generation, string kind, DomqlQuery? query, IReadOnlyDictionary? bindings, Action answered) - { - var request = new DomqlRequest(kind, answered) { Query = query is null ? null : (query, route.Owner.Connection.QueryKeyOf(query)) }; - - request.Fields["handle"] = route.Id; - request.Fields["owner"] = route.Owner.Name; - request.Fields["generation"] = generation; - - if (bindings is not null) - { - request.Fields["bindings"] = bindings; - } - - return request; - } - - /// Whether a delivery is of the generation given or a later one, or of none, and so applies. - public static bool IsCurrent(JsonElement delivery, int generation) => - !delivery.TryGetProperty("generation", out var given) || !given.TryGetInt32(out var value) || value >= generation; - - /// The failure an answer or a delivery holds, null where it holds none. - public static DomqlException? ErrorOf(JsonElement element) => - element.ValueKind == JsonValueKind.Object && element.TryGetProperty("error", out var error) ? DomqlException.FromJson(error) : null; -} diff --git a/nuget/DomqlServiceCollectionExtensions.cs b/nuget/DomqlServiceCollectionExtensions.cs deleted file mode 100644 index 436810e..0000000 --- a/nuget/DomqlServiceCollectionExtensions.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace Domql; - -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Logging; -using Microsoft.JSInterop; - -/// Registers DOMQL's connection. -public static class DomqlServiceCollectionExtensions -{ - /// Registers one for each scope, through the scope's JavaScript runtime, as each browser runtime has one. - public static IServiceCollection AddDomql(this IServiceCollection services, Action? configure = null) - { - ArgumentNullException.ThrowIfNull(services); - - var options = new DomqlConnectionOptions(); - - configure?.Invoke(options); - services.TryAddScoped(provider => new DomqlConnection(provider.GetRequiredService(), options, provider.GetService>())); - - return services; - } -} diff --git a/nuget/DomqlSubscription.cs b/nuget/DomqlSubscription.cs deleted file mode 100644 index c203944..0000000 --- a/nuget/DomqlSubscription.cs +++ /dev/null @@ -1,141 +0,0 @@ -namespace Domql; - -using System.Text.Json; - -/// -/// A subscription to an event source: each event the browser delivers is mapped onto and handed to its handler as it arrives, never behind another's acknowledgment; the event is -/// acknowledged in the browser once the handler has completed, with what it answers where the source declares answers. -/// -/// What each event maps onto. -public sealed class DomqlSubscription : DomqlHandle -{ - private readonly DomqlQuery _query; - private readonly Func> _handler; - private readonly DomqlSubscribeOptions _options; - - internal DomqlSubscription(DomqlOwner owner, DomqlQuery query, IReadOnlyDictionary? bindings, Func> handler, DomqlSubscribeOptions options) - : base(owner) - { - _query = query; - _handler = handler; - _options = options; - owner.Connection.Register(this); - - var request = CreateRequest("subscribe", query, bindings, Answered); - - if (options.Throttle is { } throttle) - { - request.Fields["options"] = new Dictionary { ["throttle"] = throttle.TotalMilliseconds }; - } - - _ = ObserveAsync(owner.Connection.SendAsync(request)); - } - - /// The failure that refused the subscription, or the latest of its events; null where there is none. - public DomqlException? Error { get; private set; } - - /// Subscribes with other bindings, replacing them whole; an event of the old ones that arrives after it is dropped. - public Task UpdateAsync(IReadOnlyDictionary? bindings) - { - ObjectDisposedException.ThrowIf(IsDisposed, this); - - Generation++; - - var sent = Owner.Connection.SendAsync(CreateRequest("update", null, bindings ?? new Dictionary(), Answered)); - - _ = ObserveAsync(sent); - - return sent; - } - - internal override async ValueTask DeliverAsync(JsonElement delivery) - { - if (!IsCurrent(delivery)) - { - return null; - } - - if (delivery.TryGetProperty("event", out var value)) - { - T mapped; - - try - { - mapped = _query.Map(value); - } - catch (DomqlException error) - { - await FailAsync(error).ConfigureAwait(true); - - return null; - } - - return await _handler(mapped).ConfigureAwait(true); - } - - if (ErrorOf(delivery) is { } failure) - { - await FailAsync(failure).ConfigureAwait(true); - } - - return null; - } - - /// A refusal of the request that started the subscription ends it; one of an update ends the subscription it would have replaced, which still runs in the browser, by disposing it. - private void Answered(JsonElement answer) - { - if (ErrorOf(answer) is { } error && !IsDisposed) - { - if (Generation == 0) - { - End(); - } - else - { - _ = DisposeAsync().AsTask(); - } - - _ = FailAsync(error); - } - } - - private async Task FailAsync(DomqlException error) - { - Error = error; - - if (_options.Failed is not { } failed) - { - Owner.Connection.ReportHandlerFailure(Id, error); - - return; - } - - try - { - await failed(error).ConfigureAwait(true); - } - catch (Exception handlerError) when (handlerError is not OutOfMemoryException) - { - Owner.Connection.ReportHandlerFailure(Id, handlerError); - } - } - - /// A request that failed to cross fails the subscription, on the context it was made in, and the subscription ends. - private async Task ObserveAsync(Task sent) - { - try - { - await sent.ConfigureAwait(true); - } - catch (DomqlException error) when (!IsDisposed) - { - // The request may have run in the browser before its answer was lost, so the subscription is disposed there too. - await DisposeAsync().ConfigureAwait(true); - await FailAsync(error).ConfigureAwait(true); - } - catch (Exception error) when (error is DomqlException or ObjectDisposedException) - { - // A subscription that has ended, or a connection that is disposed, has nothing left to tell. - } - } -} diff --git a/nuget/DomqlWatch.cs b/nuget/DomqlWatch.cs deleted file mode 100644 index eec3f65..0000000 --- a/nuget/DomqlWatch.cs +++ /dev/null @@ -1,359 +0,0 @@ -namespace Domql; - -using System.Text.Json; -using System.Text.Json.Nodes; - -/// Where a watch stands. -public enum DomqlWatchStatus -{ - /// It has no result yet. - Pending, - - /// It holds a current result. - Ready, - - /// Its last evaluation failed, or its result maps onto no value of its type; a later success makes it ready again. - Failed, - - /// It has ended. - Disposed, -} - -/// -/// A query kept current: a copy of its result, brought up to date by each change set the browser delivers, in order, and mapped onto as each is applied. Its first snapshot arrives -/// with its request's answer; a delivery that overtakes that answer waits for it. A change set that doesn't apply to the copy makes the copy uncertain, and the watch asks for its snapshot whole. -/// -/// What its result maps onto. -public sealed class DomqlWatch : DomqlHandle -{ - private readonly DomqlQuery _query; - private readonly Func? _changed; - private readonly DomqlWatchOptions _options; - private readonly List _early = []; - private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously); - private JsonNode? _copy; - private bool _isAnswered; - private bool _isUncertain; - private int _version; - private int _notified; - private bool _isNotifying; - - internal DomqlWatch(DomqlOwner owner, DomqlQuery query, IReadOnlyDictionary? bindings, Func? changed, DomqlWatchOptions options) - : base(owner) - { - _query = query; - _changed = changed; - _options = options; - owner.Connection.Register(this); - - var request = CreateRequest("watch", query, bindings, Answered); - - request.Fields["options"] = OptionsOf(options); - _ = ObserveAsync(owner.Connection.SendAsync(request)); - } - - /// Where the watch stands. - public DomqlWatchStatus Status { get; private set; } = DomqlWatchStatus.Pending; - - /// The latest result applied, mapped; the default before the first. - public T? Current { get; private set; } - - /// Whether the watch has applied a result, so that a result that is null is told apart from none yet. - public bool HasCurrent { get; private set; } - - /// The latest failure, cleared by the next result applied; null where there is none. - public DomqlException? Error { get; private set; } - - /// Waits for the watch's first result, and answers it; it fails where the request that started the watch was refused, and is cancelled where the watch ends first. - public Task ReadyAsync(CancellationToken cancellationToken = default) => _ready.Task.WaitAsync(cancellationToken); - - /// - /// Watches with other bindings, replacing them whole: the next result is the first of the new bindings, its snapshot arriving with the request's answer, and a delivery made with the old ones is dropped. - /// - public Task UpdateAsync(IReadOnlyDictionary? bindings) - { - ObjectDisposedException.ThrowIf(IsDisposed, this); - - Generation++; - _isAnswered = false; - _early.Clear(); - - var request = CreateRequest("update", null, bindings ?? new Dictionary(), Answered); - var sent = Owner.Connection.SendAsync(request); - - _ = ObserveAsync(sent); - - return sent; - } - - /// Evaluates the query now, and has its snapshot delivered whole, changed or not, so a copy that may have missed a change is brought up to date. - public Task RefreshAsync() - { - ObjectDisposedException.ThrowIf(IsDisposed, this); - - var request = CreateRequest("refresh", null, null, _ => { }); - - return Owner.Connection.SendAsync(request); - } - - internal override ValueTask DeliverAsync(JsonElement delivery) - { - if (IsCurrent(delivery)) - { - if (_isAnswered) - { - Apply(delivery); - } - else - { - _early.Add(delivery); - } - } - - return ValueTask.FromResult(null); - } - - private protected override void Ended() - { - Status = DomqlWatchStatus.Disposed; - _early.Clear(); - _ready.TrySetCanceled(); - } - - /// - /// The answer of the request that started the watch, or that bound it anew: its snapshot, or pending, its first evaluation's failure with it where that failed; a refusal ends it. Each delivery that - /// overtook the answer is applied after it, in order. - /// - private void Answered(JsonElement answer) - { - if (IsDisposed) - { - return; - } - - var error = ErrorOf(answer); - var isPending = answer.ValueKind == JsonValueKind.Object && answer.TryGetProperty("pending", out _); - - if (answer.ValueKind != JsonValueKind.Object || error is not null && !isPending) - { - Fail(error ?? new DomqlException("DOMQL5030", "evaluation", "The browser answered the watch's request with nothing it reads")); - _ready.TrySetException(Error!); - - // A refused update leaves the watch it would have replaced running in the browser, which disposing ends; a refused start left none. - if (Generation == 0) - { - End(); - } - else - { - _ = DisposeAsync().AsTask(); - } - - return; - } - - _isAnswered = true; - - if (answer.TryGetProperty("snapshot", out var snapshot)) - { - Replace(snapshot); - } - else if (error is not null) - { - Fail(error); - } - - var early = _early.ToArray(); - - _early.Clear(); - - foreach (var delivery in early) - { - if (IsCurrent(delivery)) - { - Apply(delivery); - } - } - } - - /// A delivery applied to the copy: a snapshot whole replacing it, a change set changing it, or a failure. - private void Apply(JsonElement delivery) - { - if (delivery.TryGetProperty("snapshot", out var snapshot)) - { - Replace(snapshot); - } - else if (delivery.TryGetProperty("changes", out var changes)) - { - // A copy a change set failed to apply to waits for its snapshot whole, which the refresh it asked for brings. - if (_isUncertain) - { - return; - } - - try - { - _copy = DomqlChangeSet.Apply(_copy, changes); - } - catch (DomqlException error) - { - _isUncertain = true; - Fail(error); - _ = RefreshQuietlyAsync(); - - return; - } - - Mapped(); - } - else if (ErrorOf(delivery) is { } error) - { - Fail(error); - } - } - - private void Replace(JsonElement snapshot) - { - _copy = JsonNode.Parse(snapshot.GetRawText()); - _isUncertain = false; - Mapped(); - } - - /// The copy mapped as the current result, the watch ready with it, and its handler told; a result its type can't hold is a failure, the current result standing. - private void Mapped() - { - T value; - - try - { - value = _query.Map(_copy); - } - catch (DomqlException error) - { - Fail(error); - - return; - } - - Current = value; - HasCurrent = true; - Status = DomqlWatchStatus.Ready; - Error = null; - _ready.TrySetResult(value); - _version++; - - if (_changed is not null && !_isNotifying) - { - _isNotifying = true; - _ = NotifyAsync(); - } - } - - /// Calls the handler with the latest result, one call at a time, until it has heard the latest. - private async Task NotifyAsync() - { - try - { - while (_notified < _version && !IsDisposed) - { - _notified = _version; - - try - { - await _changed!(Current!).ConfigureAwait(true); - } - catch (Exception error) when (error is not OutOfMemoryException) - { - Owner.Connection.ReportHandlerFailure(Id, error); - } - } - } - finally - { - _isNotifying = false; - } - } - - private void Fail(DomqlException error) - { - Status = DomqlWatchStatus.Failed; - Error = error; - - if (_options.Failed is { } failed) - { - _ = ReportAsync(failed, error); - } - else - { - Owner.Connection.ReportHandlerFailure(Id, error); - } - } - - private async Task ReportAsync(Func failed, DomqlException error) - { - try - { - await failed(error).ConfigureAwait(true); - } - catch (Exception handlerError) when (handlerError is not OutOfMemoryException) - { - Owner.Connection.ReportHandlerFailure(Id, handlerError); - } - } - - /// A request that failed to cross fails the watch, on the context it was made in, and the watch ends, its result standing where it had one. - private async Task ObserveAsync(Task sent) - { - try - { - await sent.ConfigureAwait(true); - } - catch (DomqlException error) when (!IsDisposed) - { - Fail(error); - _ready.TrySetException(error); - - // The request may have run in the browser before its answer was lost, so the watch is disposed there too. - await DisposeAsync().ConfigureAwait(true); - } - catch (Exception error) when (error is DomqlException or ObjectDisposedException) - { - // A watch that has ended, or a connection that is disposed, has nothing left to tell. - } - } - - /// Asks for the snapshot whole, where the connection can still carry the request. - private async Task RefreshQuietlyAsync() - { - try - { - await RefreshAsync().ConfigureAwait(true); - } - catch (Exception error) when (error is DomqlException or ObjectDisposedException) - { - // A connection that can't carry it has ended the watch. - } - } - - private static Dictionary OptionsOf(DomqlWatchOptions options) - { - var written = new Dictionary(); - - if (options.Schedule is not null) - { - written["schedule"] = options.Schedule; - } - - if (options.Delay is { } delay) - { - written["delay"] = delay.TotalMilliseconds; - } - - if (options.AcceptPartialObservation) - { - written["acceptPartialObservation"] = true; - } - - return written; - } -} diff --git a/nuget/Forma.DOMQL.csproj b/nuget/Forma.DOMQL.csproj index 9aea16d..f22f64d 100644 --- a/nuget/Forma.DOMQL.csproj +++ b/nuget/Forma.DOMQL.csproj @@ -29,17 +29,6 @@ true - - - Domql - true - - - - - - - diff --git a/nuget/Forma.DOMQL.slnx b/nuget/Forma.DOMQL.slnx index 8a563bb..1a4a21e 100644 --- a/nuget/Forma.DOMQL.slnx +++ b/nuget/Forma.DOMQL.slnx @@ -1,6 +1,4 @@ - - diff --git a/nuget/README.md b/nuget/README.md index d5fc897..eb91bc3 100644 --- a/nuget/README.md +++ b/nuget/README.md @@ -1582,35 +1582,7 @@ filtered.dispose(); ## Use DOMQL from .NET -The package holds DOMQL's .NET half too. Register its connection, one for each browser your application reaches: - -```csharp -builder.Services.AddDomql(); -``` - -Then write a query's text, name the type its result maps onto, and carry it out for an owner. An owner is a part of your application that starts operations of its own, and disposing it ends all of them in one call: - -```csharp -public sealed record PanelState(double? Width, bool HasFocus); - -static readonly DomqlQuery Panel = DomqlQuery.Create("panel { width = it.layoutSize?.inline, hasFocus = it.focusWithin }"); - -DomqlOwner owner = connection.CreateOwner(); -DomqlWatch watch = owner.Watch(Panel, new Dictionary { ["panel"] = panelElement }, state => RenderAsync(state)); - -PanelState first = await watch.ReadyAsync(); // Arrives with the watch's own request. -bool focused = await owner.ExecuteAsync(DomqlQuery.Create("field.focus()"), new Dictionary { ["field"] = fieldElement }); - -await owner.DisposeAsync(); -``` - -- **One call for one turn.** Every operation your code starts before it yields crosses to the browser in one call, and the answer brings back each watch's first result. -- **A watch keeps a copy.** Each change arrives as a change set, applied to the watch's copy before the browser sends the next. `changed` hears the latest result, one call at a time. -- **Events arrive as they happen.** A subscription's handler can answer an event, with `Subscribe`, where its event source declares `answers`. -- **Typed results.** Pass source-generated type information, as `DomqlQuery.Create(text, AppJsonContext.Default.PanelState)`, in a trimmed or native application. -- **After a lost connection,** call `connection.RefreshAsync()` once it resumes, and every watch delivers its result whole. - -[The .NET half](https://github.com/FormaUI/DOMQL/blob/main/spec/dotnet.md) specifies each operation, and [connections](https://github.com/FormaUI/DOMQL/blob/main/spec/connections.md) the messages they cross as. +To run DOMQL from .NET code, with typed results and watches kept current in .NET, use [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET), which runs over DOMQL's [connection](https://github.com/FormaUI/DOMQL/blob/main/spec/connections.md). ## Learn more diff --git a/nuget/global.json b/nuget/global.json index a677f5e..db8b598 100644 --- a/nuget/global.json +++ b/nuget/global.json @@ -2,8 +2,5 @@ "sdk": { "version": "11.0.100-rc.3.26522.148", "rollForward": "disable" - }, - "test": { - "runner": "Microsoft.Testing.Platform" } } diff --git a/nuget/scripts/domql.dotnet.js b/nuget/scripts/domql.dotnet.js deleted file mode 100644 index 3ab0179..0000000 --- a/nuget/scripts/domql.dotnet.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * domql.dotnet — the connection a .NET application's DOMQL connection opens in the browser: DOMQL's own, in the bundle beside it, delivering to the receiver .NET gives it - */ - -import { domql } from './domql.js'; - -/** - * The most a batch of deliveries crosses as data, in UTF-8 bytes, measured as a server's transport writes it: the arguments' JSON, escaped once more as its message carries them as text. Beyond it, the batch - * crosses as a stream of its JSON's UTF-8 bytes. - */ -const TEXT_BUDGET = 16 * 1024; - -const encoder = new TextEncoder(); - -/** - * Opens a connection whose deliveries reach the receiver's `ReceiveAsync`, each batch as `{ deliveries }`, or as `{ stream }` beyond the budget, answering what the receiver answers; and answers the object .NET - * carries its requests through. - * @param {{ invokeMethodAsync: (name: string, ...args: unknown[]) => Promise }} receiver - * @param {{ textBudget?: number }} [options] - */ -export function connect(receiver, { textBudget = TEXT_BUDGET } = {}) { - const connection = domql.connect(deliveries => { - const json = JSON.stringify(deliveries); - const transfer = encoder.encode(JSON.stringify(json)).length <= textBudget ? { deliveries } : { stream: globalThis.DotNet.createJSStreamReference(encoder.encode(json)) }; - - return receiver.invokeMethodAsync('ReceiveAsync', transfer); - }); - - return { - requestAsync: requests => connection.requestAsync(requests), - close: () => connection.close(), - }; -} diff --git a/scripts/bundle.mjs b/scripts/bundle.mjs index a32405c..8340ce0 100644 --- a/scripts/bundle.mjs +++ b/scripts/bundle.mjs @@ -16,9 +16,6 @@ export const bundlePath = resolve(root, 'nuget', 'wwwroot', 'domql.js'); /** Where the package serves the declarations of the bundle's API from, beside the bundle. */ export const declarationsPath = resolve(root, 'nuget', 'wwwroot', 'domql.d.ts'); -/** Where the package serves the module a .NET application's connection opens, which imports the bundle beside it. */ -export const dotnetConnectionPath = resolve(root, 'nuget', 'wwwroot', 'domql.dotnet.js'); - /** Bundles the entry and every module it imports into one minified ES module, answering its text. */ export async function bundle() { const result = await build({ @@ -41,7 +38,6 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await mkdir(dirname(bundlePath), { recursive: true }); await writeFile(bundlePath, text); await copyFile(resolve(root, 'src', 'domql.d.ts'), declarationsPath); - await copyFile(resolve(root, 'nuget', 'scripts', 'domql.dotnet.js'), dotnetConnectionPath); - console.log(`Bundled ${Buffer.byteLength(text)} bytes of DOMQL ${Versions.runtime} to ${bundlePath}, with its declarations and the module a .NET connection opens beside it`); + console.log(`Bundled ${Buffer.byteLength(text)} bytes of DOMQL ${Versions.runtime} to ${bundlePath}, with its declarations beside it`); } diff --git a/scripts/packages/nuget.files b/scripts/packages/nuget.files index 42df584..4c566ec 100644 --- a/scripts/packages/nuget.files +++ b/scripts/packages/nuget.files @@ -11,8 +11,6 @@ buildMultiTargeting/formaui-net.DOMQL.targets buildTransitive/formaui-net.DOMQL.targets formaui-net.DOMQL.nuspec lib/net11.0/Forma.DOMQL.dll -lib/net11.0/Forma.DOMQL.xml package/services/metadata/core-properties/nuget.psmdcp staticwebassets/domql.d.ts -staticwebassets/domql.dotnet.js staticwebassets/domql.js diff --git a/spec/README.md b/spec/README.md index 0d37ebd..8886ea4 100644 --- a/spec/README.md +++ b/spec/README.md @@ -39,7 +39,6 @@ Start with [queries](queries.md), which shows a query with its parameters and it 9. [Behaviors](behaviors.md): an operation's owner, a behavior's running instance, the commands that reach it, its occurrences and their acknowledgment, handling inside the native dispatch, and the state it offers. 10. [The API](api.md): every entry point, operation and handle, the events a handle raises, their order across handles, lifetimes and errors. 11. [Connections](connections.md): DOMQL's operations carried across a boundary as messages, the requests a host sends and the deliveries it receives, and how a watch's are paced. -12. [The .NET half](dotnet.md): DOMQL from a .NET application: its connection, its queries and the types their results map onto, its owners, watches, subscriptions and executions, and the calls each takes. -13. [Errors](errors.md): the codes of DOMQL's own conditions. -14. [Examples](examples.md): a complete query with its document and result, and queries by what they ask. -15. [Terms](terms.md): the glossary. +12. [Errors](errors.md): the codes of DOMQL's own conditions. +13. [Examples](examples.md): a complete query with its document and result, and queries by what they ask. +14. [Terms](terms.md): the glossary. diff --git a/spec/api.md b/spec/api.md index 8ba9f7a..f340f41 100644 --- a/spec/api.md +++ b/spec/api.md @@ -86,7 +86,7 @@ Each entry point and operation is listed here with what it takes, and the sectio | `domql.createModule(name, contents, options?)` | Creates a module from its declarations, each that runs code carrying its implementation, as [extension modules](vocabulary.md#extension-modules) set out, under the manifest `options.manifest` gives | | `domql.registerModule(module, options?)` | Registers a module's declarations in the instance's registry, as [extension modules](vocabulary.md#extension-modules) set out, under the manifest `options.manifest` gives | | `domql.registerModuleLoader(name, load, options?)` | Registers the loader of a module loaded on request, as [loading a module on request](vocabulary.md#extension-modules-loading) sets out, its module registered with the options given | -| `domql.connect(deliver, options?)` | Opens a connection that carries the instance's operations across a boundary as messages, as [connections](connections.md) set out, which [the .NET half](dotnet.md) opens | +| `domql.connect(deliver, options?)` | Opens a connection that carries the instance's operations across a boundary as messages, as [connections](connections.md) set out, which [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET) opens | | `domql.loadModulesAsync(modules)` | Loads and registers every module named that the instance doesn't hold yet, answering a promise, as [loading a module on request](vocabulary.md#extension-modules-loading) sets out | | `domql.info` | Which build this is and what it follows, in `versions`: `runtime`, the runtime release version, which the package and the bundle carry, its sources reporting the same; `specification`, the version of DOMQL's specification it follows; and `language`, the language specification version the Nexo runtime it runs on follows, its `nexo.info.versions.language` | diff --git a/spec/connections.md b/spec/connections.md index 0252486..0fd996b 100644 --- a/spec/connections.md +++ b/spec/connections.md @@ -14,7 +14,7 @@ const answers = await connection.requestAsync([ // [{ snapshot: { width: 640 } }, { snapshot: { width: 320 } }] ``` -[The .NET half](dotnet.md) is DOMQL's own host of a connection. +[DOMQL.NET](https://github.com/FormaUI/DOMQL.NET) is DOMQL's own host of a connection, for .NET applications. In this document: diff --git a/spec/dotnet.md b/spec/dotnet.md deleted file mode 100644 index 0fb7fd4..0000000 --- a/spec/dotnet.md +++ /dev/null @@ -1,123 +0,0 @@ -# The .NET half - - - -The .NET half is DOMQL from a .NET application. It ships in the NuGet package, `formaui-net.DOMQL`, beside the bundle. A .NET application writes a query's text, names the type its result maps onto, and carries it out for an owner. DOMQL runs it in the browser, through a [connection](connections.md), and keeps the application's copy of each result. - -```csharp -public sealed record PanelState(double? Width, bool HasFocus); - -static readonly DomqlQuery Panel = DomqlQuery.Create( - "panel { width = it.layoutSize?.inline, hasFocus = it.focusWithin }", - AppJsonContext.Default.PanelState); - -DomqlOwner owner = connection.CreateOwner(); -DomqlWatch watch = owner.Watch(Panel, new Dictionary { ["panel"] = panelElement }, state => RenderAsync(state)); -PanelState first = await watch.ReadyAsync(); - -await owner.DisposeAsync(); // Ends the watch, and everything else the owner started, in one request. -``` - -In this document: - -1. [The connection](#dotnet-connection) -2. [Queries and their results](#dotnet-queries) -3. [Owners and operations](#dotnet-operations) -4. [Watches](#dotnet-watches) -5. [Subscriptions and executions](#dotnet-subscriptions) -6. [Crossings](#dotnet-crossings) -7. [Failures](#dotnet-failures) - - - -## The connection - -- **One for each browser runtime.** `services.AddDomql()` registers one `DomqlConnection` for each scope, through the scope's `IJSRuntime`: one for each browser a server-hosted application is connected to, one for an application that runs in the browser, and one for each web view. `new DomqlConnection(jsRuntime, options, logger)` makes one directly. -- **It opens as its first request crosses.** It imports `_content/domql/domql.dotnet.js`, which the package serves beside the bundle, and opens a connection there whose deliveries reach .NET. Requests made while it opens cross with the first batch. -- **One synchronization context.** A connection is used from the context its runtime's callbacks run on, as a server-hosted application's dispatcher or the browser's one thread runs them. Its handlers run there. -- **`RefreshAsync()`** has every watch deliver its snapshot whole, changed or not, as a host does once its connection to the browser resumes and a delivery may have been lost. -- **`DisposeAsync()`** closes the browser's side and ends every operation the connection started. -- **`DomqlConnectionOptions`:** - - `ModulePath`, where the module is served. - - `TextBudget`: the most a batch of deliveries crosses as data, 16 KB, in UTF-8 bytes as a server's transport writes it, its JSON escaped once more. A larger one crosses as a stream of its JSON's UTF-8 bytes, so a delivery is never refused for a transport's message size. - - `MaximumDeliverySize`: the most bytes the connection reads of a stream, 16 MiB. - - - -## Queries and their results - -- **`DomqlQuery.Create(text, typeInfo, types?)`** makes a query whose result maps onto `T` through source-generated type information, as a trimmed or native application needs. `DomqlQuery.Create(text, options?, types?)` maps it by reflection, through the serializer's options, the web's defaults by default. `DomqlQuery.Create(text, types?)` keeps the result's JSON, as a `JsonElement`. -- **The text is checked in the browser.** It is read with `Domql` supplied, as `domql.query` reads it, by the first request that makes it there. A syntax or structure failure fails that request. .NET has no parser of its own. -- **`types`** declares the type of a top-level binding by its notation, as [declared types](queries.md#making-a-query-declared-types) do. -- **Mapping.** A result's fields map onto `T`'s properties and constructor parameters as the serializer maps JSON. A result `T` can't hold is a failure, `DOMQL5028`, and a watch's current result stands. -- **Records a field discriminates.** A result that is one of several shapes maps onto a type the serializer reads polymorphically, by a field the query names first, as `[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]` names one. -- **Bindings** are `IReadOnlyDictionary`. Each value crosses as the runtime serializes it, and an element reference the runtime serializes crosses as the element it refers to. - - - -## Owners and operations - -`connection.CreateOwner(name?)` makes a **`DomqlOwner`**, who carries operations out. Its name is its own among the connection's owners until it is disposed: one of its own where none is given, and a name in use is refused with an `ArgumentException`, since a release names one owner alone. Each implementation an operation reaches receives its name as `env.owner`, and a command reaches the behavior running for it, as [behaviors](behaviors.md#behaviors-the-owner) set out. A part of a page that starts operations of its own holds one. - -| Operation | Answers | As in the browser | -| --- | --- | --- | -| `owner.Watch(query, bindings, changed, options)` | A `DomqlWatch` | `query.watch` | -| `owner.Subscribe(query, bindings, handler, options)`, and `Subscribe` for a source that declares `answers` | A `DomqlSubscription` | `query.subscribe` | -| `owner.Run(query, bindings, options)` | A `DomqlExecution` | `query.run` | -| `owner.ExecuteAsync(query, bindings, cancellationToken)` | Its result | `query.executeAsync` | -| `owner.EvaluateAsync(query, bindings, cancellationToken)` | Its result | `query.evaluateAsync` | -| `owner.DisposeAsync()` | — | Ends every operation the owner started, in one request | - -- **Each starts at once.** An operation starts as its call returns. Its request crosses as the turn that made it ends, with every other request of that turn, in one call. -- **Cancelling** an `ExecuteAsync` or an `EvaluateAsync` stops the wait alone. The execution has started in the browser. -- **A handle** is a watch, a subscription or an execution. `DisposeAsync()` ends it in the browser and here. A handle whose connection is gone has ended already. - - - -## Watches - -A **`DomqlWatch`** keeps a copy of its query's result, which each delivery brings up to date. - -- **Its first result** arrives with its request's answer, which `ReadyAsync()` waits for. Where the first evaluation waits for a maintained member, its snapshot is delivered whole once it has one. -- **Each change set** is applied to the copy as it arrives, by DOMQL's rules for [applying change sets](results.md#results-change-sets), and the copy is mapped onto `T`. A delivery that overtakes the request's answer waits for it. -- **The browser's next change set** crosses once this one is applied, so a watch has one delivery in flight. What arises meanwhile is joined, as [pacing](connections.md#connections-pacing) sets out. -- **`changed`** is called with each result once it is applied, one call at a time, with the latest where several arrived meanwhile. A handler that throws is reported to the connection's logger, and the copy stands. -- **`Current`**, **`HasCurrent`**, **`Status`** and **`Error`** read the copy: `Pending`, `Ready`, `Failed` or `Disposed`. A failed evaluation, or a result `T` can't hold, sets `Error` and `Failed`. The current result stands until the next result applied. -- **`UpdateAsync(bindings)`** watches with other bindings. Its next result is the first of the new ones, and a delivery made with the old ones is dropped by its generation. -- **`RefreshAsync()`** has the watch deliver its snapshot whole. -- **An uncertain copy.** A change set that doesn't apply to the copy fails with `DOMQL5029`. The watch asks for its snapshot whole, and skips change sets until it arrives. - - - -## Subscriptions and executions - -- **A `DomqlSubscription`** hands each event to its handler as it arrives, mapped onto `T`, in the order the browser heard them. An event never waits behind a watch's delivery. -- **The event's acknowledgment** in the browser settles once the handler completes. A handler of `Subscribe` answers the event, and its answer answers the event source, as [answers](behaviors.md#behaviors-answers) set out. -- **`UpdateAsync(bindings)`** subscribes with other bindings. An event of the old ones that arrives after it is dropped. -- **A `DomqlExecution`** runs until it, or its owner, is disposed. `UpdateAsync(bindings)` updates it in place, and a refusal fails the task and leaves it running as it was. -- **`Failed`**, in each handle's options, hears each failure an operation reports. The connection's logger hears those no `Failed` is given for. - - - -## Crossings - -| What a .NET application does | Calls between .NET and the browser | -| --- | --- | -| Starts any number of operations in one turn | 1, its answers holding each watch's first result | -| A watch's change | 1, the deliveries of one browser task together | -| A subscription's event | 1, with the other deliveries of its task | -| An execution that settles in its request's task | 1 | -| Ends every operation of an owner | 1 | -| Refreshes every watch, once the connection to the browser resumes | 1, and 1 for the snapshots | - - - -## Failures - -A **`DomqlException`** carries a failure's `Code`, its `Kind` and its `Location`, as DOMQL or Nexo reported it in the browser. `DomqlLocation` gives its `Node`, the JSON Pointer of the definition's node, its `Line`, `Column` and `Offset` in the text, the `Binding` it concerns, and the `Module`, `Type`, `Declaration` and `DeclarationKey` of a module's failure. - -- **A refused request** fails its operation: a watch's `ReadyAsync`, an execution's task, a handle's `Failed`. -- **A batch that can't cross** fails each request it carried with `DOMQL5030`, the runtime's failure its inner exception. -- **A batch of deliveries that can't be read** is logged, and every watch delivers its snapshot whole, once: a batch that can't be read while that refresh is under way, as a snapshot past `MaximumDeliverySize` is, refreshes nothing more until a batch is read. A handler's failure stays its own: the batch is acknowledged, and the deliveries after it are applied. -- **A refused update** fails its handle, which ends in the browser too. So does a request whose batch could not cross, since the browser may have run it before its answer was lost. -- **The .NET half's own codes:** `DOMQL5028`, a result its type can't hold; `DOMQL5029`, a change set that doesn't apply to the copy; and `DOMQL5030`, a batch that could not cross or be read. [Errors](errors.md) catalogue them with the rest. diff --git a/spec/errors.md b/spec/errors.md index 928cde1..3a7d510 100644 --- a/spec/errors.md +++ b/spec/errors.md @@ -127,6 +127,6 @@ A failure while a request is carried out, located in the query where it concerns | `DOMQL5025` | An answer a subscription gave an occurrence that the type its event source declares it answers refuses, or whose notation names no type, the refusal the error's `cause` | | `DOMQL5026` | A connection whose host left as many deliveries unacknowledged as its [limit](connections.md#connections-pacing) holds, which the next batch closes | | `DOMQL5027` | A request or a delivery of a connection that has closed | -| `DOMQL5028` | In [the .NET half](dotnet.md#dotnet-queries), a result the type a query maps it onto can't hold | -| `DOMQL5029` | In the .NET half, a change set that doesn't apply to a watch's copy, which then asks for its snapshot whole | -| `DOMQL5030` | In the .NET half, a batch of requests that could not cross, or a delivery that could not be read, the runtime's failure its inner exception | +| `DOMQL5028` | Reserved for [DOMQL.NET](https://github.com/FormaUI/DOMQL.NET): a result the type a query maps it onto can't hold | +| `DOMQL5029` | Reserved for DOMQL.NET: a change set that doesn't apply to a watch's copy, which then asks for its snapshot whole | +| `DOMQL5030` | Reserved for DOMQL.NET: a batch of requests that could not cross, or a delivery that could not be read | diff --git a/tests/DocumentExamples.test.js b/tests/DocumentExamples.test.js index a0234d1..4c90258 100644 --- a/tests/DocumentExamples.test.js +++ b/tests/DocumentExamples.test.js @@ -116,7 +116,6 @@ const DOCUMENTS = { 'spec/behaviors.md': [], 'spec/api.md': [], 'spec/connections.md': [], - 'spec/dotnet.md': [], 'spec/examples.md': [ { about: 'a complete query' }, ], diff --git a/tests/connections/DotnetConnection.test.js b/tests/connections/DotnetConnection.test.js deleted file mode 100644 index 4ce09f3..0000000 --- a/tests/connections/DotnetConnection.test.js +++ /dev/null @@ -1,51 +0,0 @@ -import { afterEach, beforeEach, describe, it, expect } from 'vitest'; -import { connect } from '../../nuget/scripts/domql.dotnet.js'; - -/** Settles once the current task and those it queued at once have run. */ -const nextTask = () => new Promise(resolve => setTimeout(resolve, 0)); - -describe('the connection a .NET application opens', () => { - let calls; - let connection; - let panel; - - beforeEach(() => { - calls = []; - document.body.innerHTML = '
'; - panel = document.getElementById('panel'); - globalThis.DotNet = { createJSStreamReference: bytes => ({ utf8: new TextDecoder().decode(bytes) }) }; - - const receiver = { - invokeMethodAsync: (name, transfer) => { - calls.push([name, transfer]); - - return Promise.resolve([null]); - }, - }; - - connection = connect(receiver, { textBudget: 120 }); - }); - - afterEach(() => { - connection.close(); - delete globalThis.DotNet; - document.body.innerHTML = ''; - }); - - it('carries .NET\'s requests, and hands each batch of deliveries to the receiver\'s ReceiveAsync as data within the budget and as a stream of its UTF-8 bytes beyond it', async () => { - const query = { key: 'count', text: '{ count = panel.children.count }' }; - - expect(await connection.requestAsync([{ request: 'watch', handle: 1, query, bindings: { panel }, options: { schedule: 'immediate' } }])).toEqual([{ snapshot: { count: 0 } }]); - - panel.append(document.createElement('b')); - await nextTask(); - - expect(calls).toEqual([['ReceiveAsync', { deliveries: [{ handle: 1, generation: 0, changes: [{ op: 'replace', path: '/count', value: 1 }] }] }]]); - - await connection.requestAsync([{ request: 'watch', handle: 2, query: { key: 'label', text: '{ label = panel["data-label"] }' }, bindings: { panel }, options: { schedule: 'immediate' } }]); - panel.setAttribute('data-label', 'x'.repeat(200)); - await nextTask(); - - expect(calls[1]).toEqual(['ReceiveAsync', { stream: { utf8: `[{"handle":2,"generation":0,"changes":[{"op":"replace","path":"/label","value":"${'x'.repeat(200)}"}]}]` } }]); - }); -}); diff --git a/tests/dotnet/DomqlChangeSetTests.cs b/tests/dotnet/DomqlChangeSetTests.cs deleted file mode 100644 index f46b86c..0000000 --- a/tests/dotnet/DomqlChangeSetTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace Domql.Tests; - -using System.Text.Json; -using System.Text.Json.Nodes; - -using Xunit; - -public sealed class DomqlChangeSetTests -{ - /// The conformance corpus: each case a previous result, a change set and the result they give, which DOMQL's JavaScript applier passes too. - public static TheoryData Cases { get; } = [.. Corpus().Select(entry => (string)entry!["name"]!)]; - - [Theory] - [MemberData(nameof(Cases))] - public void Should_give_the_result_the_corpus_gives(string name) - { - var entry = Corpus().Single(candidate => (string)candidate!["name"]! == name)!; - var changes = JsonDocument.Parse(entry["changes"]!.ToJsonString()).RootElement; - var result = DomqlChangeSet.Apply(entry["previous"]!.DeepClone(), changes); - - Assert.True(JsonNode.DeepEquals(entry["result"], result), $"{name}: {result?.ToJsonString()}"); - } - - [Theory] - [InlineData("""[{"op":"replace","path":"/missing","value":1}]""", "it replaces 'missing'")] - [InlineData("""[{"op":"remove","path":"/rows/2"}]""", "its index '2' names no item")] - [InlineData("""[{"op":"add","path":"/rows/3","value":1}]""", "its index '3' names no item")] - [InlineData("""[{"op":"add","path":"/rows/01","value":1}]""", "its index '01' names no item")] - [InlineData("""[{"op":"remove","path":""}]""", "it takes the whole result out")] - [InlineData("""[{"op":"copy","from":"/rows/0","path":"/rows/1"}]""", "its operation copy is none of")] - [InlineData("""[{"op":"replace","path":"rows","value":1}]""", "is no JSON Pointer")] - [InlineData("""{"op":"replace"}""", "it is no list of operations")] - public void Should_refuse_a_change_set_that_names_no_place_in_the_copy(string changes, string reason) - { - var copy = JsonNode.Parse("""{"rows":[{"k":"a"},{"k":"b"}]}"""); - var error = Assert.Throws(() => DomqlChangeSet.Apply(copy, JsonDocument.Parse(changes).RootElement)); - - Assert.Equal("DOMQL5029", error.Code); - Assert.Contains(reason, error.Message, StringComparison.Ordinal); - } - - private static JsonArray Corpus() => JsonNode.Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "change-sets.json")))!.AsArray(); -} diff --git a/tests/dotnet/DomqlConnectionTests.cs b/tests/dotnet/DomqlConnectionTests.cs deleted file mode 100644 index a1123a6..0000000 --- a/tests/dotnet/DomqlConnectionTests.cs +++ /dev/null @@ -1,412 +0,0 @@ -namespace Domql.Tests; - -using System.Text.Json; -using System.Text.Json.Nodes; - -using Xunit; - -public sealed class DomqlConnectionTests : IAsyncDisposable -{ - private readonly TestDispatcher _dispatcher = new(); - private readonly FakeBrowser _browser = new(); - private readonly DomqlConnection _connection; - private readonly DomqlOwner _owner; - - public DomqlConnectionTests() - { - _connection = new DomqlConnection(_browser); - _owner = _connection.CreateOwner("panel"); - } - - public sealed record Counted(int Count); - - private static readonly DomqlQuery CountQuery = DomqlQuery.Create("{ count = panel.children.count }"); - - public async ValueTask DisposeAsync() - { - // The connection first, so the owner's release has no request left to wait on. - await _connection.DisposeAsync(); - await _owner.DisposeAsync(); - _dispatcher.Dispose(); - } - - [Fact] - public Task Should_carry_the_requests_of_one_turn_as_one_call_its_query_text_crossing_once() => _dispatcher.RunAsync(async () => - { - _ = _owner.Watch(CountQuery, Bindings("first")); - _ = _owner.Watch(CountQuery, Bindings("second")); - _ = _owner.Watch(DomqlQuery.Create("panel.children.count"), Bindings("third")); - - var batch = await _browser.NextBatchAsync(); - - Assert.Equal(["./_content/domql/domql.dotnet.js"], _browser.Imports); - Assert.Equal(3, batch.Requests.Count); - Assert.Equal("""{"key":1,"text":"{ count = panel.children.count }"}""", batch.Requests[0]!["query"]!.ToJsonString()); - Assert.Equal("1", batch.Requests[1]!["query"]!.ToJsonString()); - Assert.Equal("""{"key":2,"text":"panel.children.count"}""", batch.Requests[2]!["query"]!.ToJsonString()); - Assert.Equal(["watch", "watch", "watch"], batch.Requests.Select(request => (string)request!["request"]!)); - Assert.Equal(["panel", "panel", "panel"], batch.Requests.Select(request => (string)request!["owner"]!)); - Assert.Equal(["first", "second", "third"], batch.Requests.Select(request => (string)request!["bindings"]!["panel"]!)); - Assert.False(_browser.HasBatch); - }); - - [Fact] - public Task Should_name_a_query_by_its_key_once_the_browser_made_it_and_by_its_text_again_once_it_refused_it() => _dispatcher.RunAsync(async () => - { - var refused = DomqlQuery.Create("panel {"); - - var made = _owner.Watch(CountQuery); - _ = _owner.Watch(refused); - (await _browser.NextBatchAsync()).Answer("""{"snapshot":{"count":0}}""", """{"error":{"code":"NEXO1051","kind":"syntax","message":"unclosed"}}"""); - - // A request made before the answer arrives crosses with the text again, which the browser reads as the query it made; one made after names it by its key. - await made.ReadyAsync(Token); - _ = _owner.Watch(CountQuery); - _ = _owner.Watch(refused); - - var later = await _browser.NextBatchAsync(); - - Assert.Equal("1", later.Requests[0]!["query"]!.ToJsonString()); - Assert.Equal("""{"key":2,"text":"panel {"}""", later.Requests[1]!["query"]!.ToJsonString()); - }); - - [Fact] - public Task Should_answer_a_watch_with_its_first_snapshot_and_apply_each_change_set_its_handler_hearing_each_result() => _dispatcher.RunAsync(async () => - { - var heard = new List(); - var watch = _owner.Watch(CountQuery, Bindings("panel"), counted => - { - heard.Add(counted.Count); - - return Task.CompletedTask; - }); - var batch = await _browser.NextBatchAsync(); - - batch.Answer("""{"snapshot":{"count":2}}"""); - - Assert.Equal(new Counted(2), await watch.ReadyAsync(Token)); - - var id = (long)batch.Requests[0]!["handle"]!; - - await _browser.DeliverAsync($$"""[{"handle":{{id}},"generation":0,"changes":[{"op":"replace","path":"/count","value":3}]}]"""); - - Assert.Equal(new Counted(3), watch.Current); - Assert.Equal(DomqlWatchStatus.Ready, watch.Status); - await WaitUntilAsync(() => heard.Count == 2); - Assert.Equal([2, 3], heard); - }); - - [Fact] - public Task Should_hold_a_delivery_that_overtakes_its_request_s_answer_and_apply_it_after_the_answer() => _dispatcher.RunAsync(async () => - { - var watch = _owner.Watch(CountQuery); - var batch = await _browser.NextBatchAsync(); - var id = (long)batch.Requests[0]!["handle"]!; - - await _browser.DeliverAsync($$"""[{"handle":{{id}},"generation":0,"changes":[{"op":"replace","path":"/count","value":5}]}]"""); - - Assert.False(watch.HasCurrent); - - batch.Answer("""{"snapshot":{"count":4}}"""); - await watch.ReadyAsync(Token); - - Assert.Equal(new Counted(5), watch.Current); - }); - - [Fact] - public Task Should_watch_with_new_bindings_dropping_what_the_old_ones_delivered() => _dispatcher.RunAsync(async () => - { - var watch = _owner.Watch(CountQuery, Bindings("old")); - var first = await _browser.NextBatchAsync(); - var id = (long)first.Requests[0]!["handle"]!; - - first.Answer("""{"snapshot":{"count":1}}"""); - await watch.ReadyAsync(Token); - - var updated = watch.UpdateAsync(new Dictionary { ["panel"] = "new" }); - var update = await _browser.NextBatchAsync(); - - Assert.Equal("""{"request":"update","handle":1,"owner":"panel","generation":1,"bindings":{"panel":"new"}}""".Replace("\"handle\":1", $"\"handle\":{id}", StringComparison.Ordinal), update.Requests[0]!.ToJsonString()); - - update.Answer("""{"snapshot":{"count":7}}"""); - await updated; - await _browser.DeliverAsync($$"""[{"handle":{{id}},"generation":0,"changes":[{"op":"replace","path":"/count","value":2}]}]"""); - - Assert.Equal(new Counted(7), watch.Current); - }); - - [Fact] - public Task Should_ask_for_the_snapshot_whole_where_a_change_set_does_not_apply_and_skip_change_sets_until_it_arrives() => _dispatcher.RunAsync(async () => - { - var failures = new List(); - var watch = _owner.Watch(CountQuery, options: new DomqlWatchOptions { Failed = error => { failures.Add(error.Code); return Task.CompletedTask; } }); - var batch = await _browser.NextBatchAsync(); - var id = (long)batch.Requests[0]!["handle"]!; - - batch.Answer("""{"snapshot":{"count":1}}"""); - await watch.ReadyAsync(Token); - await _browser.DeliverAsync($$"""[{"handle":{{id}},"generation":0,"changes":[{"op":"replace","path":"/missing","value":2}]}]"""); - - var refresh = await _browser.NextBatchAsync(); - - Assert.Equal("refresh", (string)refresh.Requests[0]!["request"]!); - Assert.Equal(["DOMQL5029"], failures); - Assert.Equal(DomqlWatchStatus.Failed, watch.Status); - - await _browser.DeliverAsync($$$"""[{"handle":{{{id}}},"generation":0,"changes":[{"op":"replace","path":"/count","value":9}]},{"handle":{{{id}}},"generation":0,"snapshot":{"count":3}}]"""); - - Assert.Equal(new Counted(3), watch.Current); - Assert.Equal(DomqlWatchStatus.Ready, watch.Status); - }); - - [Fact] - public Task Should_fail_a_refused_watch_with_the_browser_s_code_kind_and_location() => _dispatcher.RunAsync(async () => - { - var watch = _owner.Watch(CountQuery); - - (await _browser.NextBatchAsync()).Answer("""{"error":{"code":"DOMQL3003","kind":"validation","message":"partly observable","location":{"pointer":"/expression","line":1,"column":3,"offset":2,"binding":"panel"}}}"""); - - var error = await Assert.ThrowsAsync(() => watch.ReadyAsync(Token)); - - Assert.Equal(("DOMQL3003", "validation", "partly observable"), (error.Code, error.Kind, error.Message)); - Assert.Equal(new DomqlLocation("/expression", 1, 3, 2, "panel", null, null, null, null), error.Location); - Assert.True(watch.IsDisposed); - }); - - [Fact] - public Task Should_answer_an_event_with_its_handler_s_answer_once_the_handler_completes() => _dispatcher.RunAsync(async () => - { - var events = new List(); - var subscription = _owner.Subscribe(DomqlQuery.Create("import Culture\nDomql.document:destinations()"), null, async (string destination) => - { - events.Add(destination); - await Task.Yield(); - - return $"/{destination}/"; - }); - var batch = await _browser.NextBatchAsync(); - var id = (long)batch.Requests[0]!["handle"]!; - - batch.Answer("{}"); - - var answers = await _browser.DeliverAsync($$"""[{"handle":{{id}},"generation":0,"event":"fr"},{"handle":{{id}},"generation":0,"event":"de"},{"handle":999,"event":"nobody"}]"""); - - Assert.Equal(["fr", "de"], events); - Assert.Equal("""["/fr/","/de/",null]""", answers.ToJsonString()); - Assert.False(subscription.IsDisposed); - }); - - [Fact] - public Task Should_settle_an_execution_with_its_answer_or_with_its_delivery_where_it_was_pending() => _dispatcher.RunAsync(async () => - { - var focused = _owner.ExecuteAsync(DomqlQuery.Create("field.focus()"), Bindings("field"), Token); - var scrolled = _owner.ExecuteAsync(DomqlQuery.Create("""panel.scrollTo({ block = 300, behavior = "smooth" })"""), Bindings("panel"), Token); - var batch = await _browser.NextBatchAsync(); - var scrolling = (long)batch.Requests[1]!["handle"]!; - - Assert.Equal(["execute", "execute"], batch.Requests.Select(request => (string)request!["request"]!)); - - batch.Answer("""{"value":true}""", """{"pending":true}"""); - - Assert.True(await focused); - Assert.False(scrolled.IsCompleted); - - await _browser.DeliverAsync($$"""[{"handle":{{scrolling}},"value":true}]"""); - - Assert.True(await scrolled); - }); - - [Fact] - public Task Should_end_every_operation_of_an_owner_in_one_request() => _dispatcher.RunAsync(async () => - { - var watch = _owner.Watch(CountQuery); - var execution = _owner.Run(DomqlQuery.Create("""panel.ownClass({ name = "dragging" })"""), Bindings("panel")); - - (await _browser.NextBatchAsync()).Answer("""{"snapshot":{"count":1}}""", "{}"); - await watch.ReadyAsync(Token); - - var released = _owner.DisposeAsync(); - var release = await _browser.NextBatchAsync(); - - release.Answer("{}"); - await released; - - Assert.Equal("""[{"request":"release","owner":"panel"}]""", release.Requests.ToJsonString()); - Assert.True(watch.IsDisposed); - Assert.True(execution.IsDisposed); - Assert.Equal(DomqlWatchStatus.Disposed, watch.Status); - }); - - [Fact] - public Task Should_read_a_batch_that_crossed_as_a_stream() => _dispatcher.RunAsync(async () => - { - var watch = _owner.Watch(CountQuery); - var batch = await _browser.NextBatchAsync(); - var id = (long)batch.Requests[0]!["handle"]!; - - batch.Answer("""{"pending":true}"""); - await _browser.DeliverAsync($$$"""[{"handle":{{{id}}},"generation":0,"snapshot":{"count":11}}]""", asStream: true); - - Assert.Equal(new Counted(11), await watch.ReadyAsync(Token)); - }); - - [Fact] - public Task Should_fail_each_request_of_a_batch_that_could_not_cross() => _dispatcher.RunAsync(async () => - { - var watch = _owner.Watch(CountQuery); - var executed = _owner.ExecuteAsync(DomqlQuery.Create("field.focus()"), cancellationToken: Token); - - (await _browser.NextBatchAsync()).Fail(new InvalidOperationException("The circuit is gone")); - - Assert.Equal("DOMQL5030", (await Assert.ThrowsAsync(() => watch.ReadyAsync(Token))).Code); - Assert.Equal("DOMQL5030", (await Assert.ThrowsAsync(() => executed)).Code); - }); - - [Fact] - public Task Should_map_a_result_its_type_can_t_hold_as_a_failure_its_current_result_standing() => _dispatcher.RunAsync(async () => - { - var failures = new List(); - var watch = _owner.Watch(CountQuery, options: new DomqlWatchOptions { Failed = error => { failures.Add(error); return Task.CompletedTask; } }); - var batch = await _browser.NextBatchAsync(); - var id = (long)batch.Requests[0]!["handle"]!; - - batch.Answer("""{"snapshot":{"count":1}}"""); - await watch.ReadyAsync(Token); - await _browser.DeliverAsync($$"""[{"handle":{{id}},"generation":0,"changes":[{"op":"replace","path":"/count","value":"many"}]}]"""); - - Assert.Equal("DOMQL5028", Assert.Single(failures).Code); - Assert.Equal(new Counted(1), watch.Current); - }); - - [Fact] - public Task Should_close_the_browser_side_and_end_every_operation_as_the_connection_is_disposed() => _dispatcher.RunAsync(async () => - { - var watch = _owner.Watch(CountQuery); - - (await _browser.NextBatchAsync()).Answer("""{"snapshot":{"count":1}}"""); - await watch.ReadyAsync(Token); - await _connection.DisposeAsync(); - - Assert.True(_browser.IsClosed); - Assert.True(watch.IsDisposed); - }); - - [Fact] - public Task Should_keep_a_handler_s_failure_its_own_applying_the_deliveries_after_it() => _dispatcher.RunAsync(async () => - { - var watch = _owner.Watch(CountQuery); - var subscription = _owner.Subscribe(DomqlQuery.Create("panel:presses()"), null, (int _) => throw new TaskCanceledException("The request timed out")); - var batch = await _browser.NextBatchAsync(); - var watching = (long)batch.Requests[0]!["handle"]!; - var subscribed = (long)batch.Requests[1]!["handle"]!; - - batch.Answer("""{"snapshot":{"count":1}}""", "{}"); - await watch.ReadyAsync(Token); - - var answers = await _browser.DeliverAsync($$"""[{"handle":{{subscribed}},"generation":0,"event":1},{"handle":{{watching}},"generation":0,"changes":[{"op":"replace","path":"/count","value":2}]}]"""); - - Assert.Equal("[null,null]", answers.ToJsonString()); - Assert.Equal(new Counted(2), watch.Current); - Assert.False(subscription.IsDisposed); - }); - - [Fact] - public Task Should_refresh_every_watch_once_where_a_batch_can_t_be_read_answering_nothing_until_a_batch_reads_again() => _dispatcher.RunAsync(async () => - { - var watch = _owner.Watch(CountQuery); - var batch = await _browser.NextBatchAsync(); - var id = (long)batch.Requests[0]!["handle"]!; - - batch.Answer("""{"snapshot":{"count":1}}"""); - await watch.ReadyAsync(Token); - - var answers = await _browser.DeliverAsync("[{\"handle\":", asStream: true); - var refresh = await _browser.NextBatchAsync(); - - Assert.Equal("[]", answers.ToJsonString()); - Assert.Equal("""[{"request":"refresh"}]""", refresh.Requests.ToJsonString()); - - // A snapshot past what the connection reads fails again, and refreshes nothing more, until a batch reads. - await _browser.DeliverAsync("[{\"handle\":", asStream: true); - await Task.Delay(50, Token); - - Assert.False(_browser.HasBatch); - - await _browser.DeliverAsync($$$"""[{"handle":{{{id}}},"generation":0,"snapshot":{"count":2}}]"""); - await _browser.DeliverAsync("[{\"handle\":", asStream: true); - - Assert.Equal("""[{"request":"refresh"}]""", (await _browser.NextBatchAsync()).Requests.ToJsonString()); - }); - - [Fact] - public Task Should_refuse_an_owner_named_as_one_in_use_until_it_is_disposed() => _dispatcher.RunAsync(async () => - { - var error = Assert.Throws(() => _connection.CreateOwner("panel")); - var generated = _connection.CreateOwner(); - var released = _owner.DisposeAsync(); - - (await _browser.NextBatchAsync()).Answer("{}"); - await released; - - Assert.Contains("An owner named 'panel' is in use", error.Message, StringComparison.Ordinal); - Assert.StartsWith("owner-", generated.Name, StringComparison.Ordinal); - Assert.Equal("panel", _connection.CreateOwner("panel").Name); - }); - - [Fact] - public Task Should_dispose_in_the_browser_a_watch_whose_update_was_refused() => _dispatcher.RunAsync(async () => - { - var watch = _owner.Watch(CountQuery, Bindings("panel")); - var first = await _browser.NextBatchAsync(); - var id = (long)first.Requests[0]!["handle"]!; - - first.Answer("""{"snapshot":{"count":1}}"""); - await watch.ReadyAsync(Token); - - _ = watch.UpdateAsync(new Dictionary { ["panel"] = null }); - (await _browser.NextBatchAsync()).Answer("""{"error":{"code":"NEXO2045","kind":"structure","message":"refused"}}"""); - - var disposal = await _browser.NextBatchAsync(); - - Assert.Equal($$"""[{"request":"dispose","handle":{{id}}}]""", disposal.Requests.ToJsonString()); - Assert.True(watch.IsDisposed); - Assert.Equal("NEXO2045", watch.Error?.Code); - }); - - [Fact] - public Task Should_open_nothing_for_a_connection_disposed_before_its_first_request_crossed() => _dispatcher.RunAsync(async () => - { - var watch = _owner.Watch(CountQuery); - - await _connection.DisposeAsync(); - await Assert.ThrowsAsync(() => watch.ReadyAsync(Token)); - await Task.Yield(); - - Assert.Empty(_browser.Imports); - Assert.False(_browser.HasBatch); - }); - - [Fact] - public Task Should_tell_a_handle_s_failure_on_the_context_its_operation_was_started_in() => _dispatcher.RunAsync(async () => - { - SynchronizationContext? heardOn = null; - var watch = _owner.Watch(CountQuery, options: new DomqlWatchOptions { Failed = _ => { heardOn = SynchronizationContext.Current; return Task.CompletedTask; } }); - - (await _browser.NextBatchAsync()).Fail(new InvalidOperationException("The runtime is gone")); - await Assert.ThrowsAsync(() => watch.ReadyAsync(Token)); - - Assert.Same(_dispatcher, heardOn); - }); - - private static CancellationToken Token => TestContext.Current.CancellationToken; - - private static Dictionary Bindings(string panel) => new() { ["panel"] = panel, ["field"] = panel }; - - private static async Task WaitUntilAsync(Func condition) - { - for (var attempt = 0; !condition() && attempt < 200; attempt++) - { - await Task.Delay(10, Token); - } - } -} diff --git a/tests/dotnet/FakeBrowser.cs b/tests/dotnet/FakeBrowser.cs deleted file mode 100644 index b5d46da..0000000 --- a/tests/dotnet/FakeBrowser.cs +++ /dev/null @@ -1,130 +0,0 @@ -namespace Domql.Tests; - -using System.Diagnostics.CodeAnalysis; -using System.Text; -using System.Text.Json; -using System.Text.Json.Nodes; -using System.Threading.Channels; - -using Microsoft.JSInterop; - -/// -/// A browser a connection reaches: it imports the connection's module, opens it, and keeps each batch of requests the connection sends, which a test answers as DOMQL's connection does; the test delivers -/// to the connection through the receiver it was opened with. -/// -internal sealed class FakeBrowser : IJSRuntime -{ - private readonly Channel _batches = Channel.CreateUnbounded(); - private DotNetObjectReference? _receiver; - - /// The module paths imported, in order. - public List Imports { get; } = []; - - /// Whether the connection closed its browser side. - public bool IsClosed { get; private set; } - - /// The next batch the connection sends, waiting for it where none has arrived. - public async Task NextBatchAsync() - { - using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); - - return await _batches.Reader.ReadAsync(timeout.Token).ConfigureAwait(false); - } - - /// Whether a batch arrived that no test has read. - public bool HasBatch => _batches.Reader.TryPeek(out _); - - /// Delivers the deliveries given, as one batch of the browser's task, answering what the connection answers. - public async Task DeliverAsync(string deliveries, bool asStream = false) - { - var receiver = _receiver ?? throw new InvalidOperationException("The connection has not opened"); - var transfer = asStream ? new DomqlTransfer { Stream = new FakeStream(Encoding.UTF8.GetBytes(deliveries)) } : new DomqlTransfer { Deliveries = JsonDocument.Parse(deliveries).RootElement.Clone() }; - var answers = await receiver.Value.ReceiveAsync(transfer).ConfigureAwait(false); - - return JsonSerializer.SerializeToNode(answers, JsonSerializerOptions.Web)!.AsArray(); - } - - public ValueTask InvokeAsync(string identifier, object?[]? args) => InvokeAsync(identifier, CancellationToken.None, args); - - [SuppressMessage("Reliability", "CA2000", Justification = "The connection disposes the references the browser gives it.")] - public ValueTask InvokeAsync(string identifier, CancellationToken cancellationToken, object?[]? args) - { - Imports.Add((string)args![0]!); - - return ValueTask.FromResult((TValue)(object)new Module(this)); - } - - /// A batch of requests, as the connection wrote them, which the test answers. - internal sealed class Batch(JsonArray requests) - { - private readonly TaskCompletionSource _answers = new(TaskCreationOptions.RunContinuationsAsynchronously); - - public JsonArray Requests { get; } = requests; - - public Task Answers => _answers.Task; - - /// Answers the batch, one answer for each request, in order. - public void Answer(params string[] answers) => _answers.SetResult([.. answers.Select(answer => JsonDocument.Parse(answer).RootElement.Clone())]); - - /// Fails the batch, as a runtime that lost the browser does. - public void Fail(Exception error) => _answers.SetException(error); - } - - /// The module the connection imports. - private sealed class Module(FakeBrowser browser) : IJSObjectReference - { - public ValueTask InvokeAsync(string identifier, object?[]? args) => InvokeAsync(identifier, CancellationToken.None, args); - - [SuppressMessage("Reliability", "CA2000", Justification = "The connection disposes the references the browser gives it.")] - public ValueTask InvokeAsync(string identifier, CancellationToken cancellationToken, object?[]? args) - { - browser._receiver = (DotNetObjectReference)args![0]!; - - return ValueTask.FromResult((TValue)(object)new Connection(browser)); - } - - public ValueTask DisposeAsync() => ValueTask.CompletedTask; - } - - /// The browser's side of the connection, which hands each batch to the test. - private sealed class Connection(FakeBrowser browser) : IJSObjectReference - { - public ValueTask InvokeAsync(string identifier, object?[]? args) => InvokeAsync(identifier, CancellationToken.None, args); - - public async ValueTask InvokeAsync(string identifier, CancellationToken cancellationToken, object?[]? args) - { - if (identifier == "close") - { - browser.IsClosed = true; - - return default!; - } - - var batch = new Batch(JsonSerializer.SerializeToNode(args![0], JsonSerializerOptions.Web)!.AsArray()); - - await browser._batches.Writer.WriteAsync(batch, cancellationToken).ConfigureAwait(false); - - return (TValue)(object)await batch.Answers.ConfigureAwait(false); - } - - public ValueTask DisposeAsync() => ValueTask.CompletedTask; - } - - /// A batch that crossed as a stream. - private sealed class FakeStream(byte[] content) : IJSStreamReference - { - public long Length => content.Length; - - public bool IsDisposed { get; private set; } - - public ValueTask OpenReadStreamAsync(long maxAllowedSize = 512000, CancellationToken cancellationToken = default) => - ValueTask.FromResult(new MemoryStream(content)); - - public ValueTask DisposeAsync() - { - IsDisposed = true; - - return ValueTask.CompletedTask; - } - } -} diff --git a/tests/dotnet/Forma.DOMQL.Tests.csproj b/tests/dotnet/Forma.DOMQL.Tests.csproj deleted file mode 100644 index e33ab24..0000000 --- a/tests/dotnet/Forma.DOMQL.Tests.csproj +++ /dev/null @@ -1,31 +0,0 @@ - - - - - net11.0 - enable - enable - latest - Domql.Tests - false - Exe - true - true - - - - - - - - - - - - - - - - - - diff --git a/tests/dotnet/TestDispatcher.cs b/tests/dotnet/TestDispatcher.cs deleted file mode 100644 index cd5f790..0000000 --- a/tests/dotnet/TestDispatcher.cs +++ /dev/null @@ -1,64 +0,0 @@ -namespace Domql.Tests; - -using System.Collections.Concurrent; - -/// -/// One thread a test runs on, as a host's dispatcher runs its components: everything posted to it runs in order, after what runs now, so a connection's requests of one turn cross together. -/// -internal sealed class TestDispatcher : SynchronizationContext, IDisposable -{ - private readonly BlockingCollection<(SendOrPostCallback Callback, object? State)> _queue = []; - private readonly Thread _thread; - - public TestDispatcher() - { - _thread = new Thread(Pump) { IsBackground = true, Name = "Test dispatcher" }; - _thread.Start(); - } - - /// Runs the test's body on the dispatcher, and settles as it does. - public Task RunAsync(Func body) - { - var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - Post(_ => started.SetResult(body()), null); - - return started.Task.Unwrap().WaitAsync(TimeSpan.FromSeconds(30)); - } - - /// Runs the callback after what runs now; once the dispatcher is disposed, as its test has ended, on the thread pool, as a host with no dispatcher would. - public override void Post(SendOrPostCallback d, object? state) - { - try - { - _queue.Add((d, state)); - - return; - } - catch (Exception error) when (error is InvalidOperationException or ObjectDisposedException) - { - // The test has ended, and what it left posting runs on its own. - } - - ThreadPool.QueueUserWorkItem(_ => d(state)); - } - - public override void Send(SendOrPostCallback d, object? state) => throw new NotSupportedException("A dispatcher runs what is posted to it after what runs now."); - - public void Dispose() - { - _queue.CompleteAdding(); - _thread.Join(); - _queue.Dispose(); - } - - private void Pump() - { - SetSynchronizationContext(this); - - foreach (var (callback, state) in _queue.GetConsumingEnumerable()) - { - callback(state); - } - } -} diff --git a/tests/snapshots/SnapshotPatcher.test.js b/tests/snapshots/SnapshotPatcher.test.js index f949366..f0ae51a 100644 --- a/tests/snapshots/SnapshotPatcher.test.js +++ b/tests/snapshots/SnapshotPatcher.test.js @@ -368,7 +368,7 @@ describe('SnapshotPatcher', () => { }); describe('the conformance corpus', () => { - // Each case a previous result, a change set and the result they give, which the C# half's applier passes too. + // Each case a previous result, a change set and the result they give, which DOMQL.NET's applier passes too. const cases = JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), '..', '_conformance', 'change-sets.json'), 'utf8')); it.each(cases.map(entry => [entry.name, entry]))('%s', (name, { previous, changes, result }) => { diff --git a/tests/vitest.config.js b/tests/vitest.config.js index 5d4ff36..fa76e4b 100644 --- a/tests/vitest.config.js +++ b/tests/vitest.config.js @@ -10,8 +10,6 @@ export default defineConfig({ { find: '#domql/', replacement: resolved('../src/') }, // Nexo's sources, which the integration tests alone reach as `#nexo/`, through the linked checkout and never through the package's exports. { find: '#nexo/', replacement: resolved('../node_modules/@formaui-net/nexo/src/') }, - // The bundle beside the module a .NET connection opens, which its tests read as the sources it is bundled from. - { find: /^\.\/domql\.js$/, replacement: resolved('../src/domql.js') }, ], }, test: { From 69e7d3c508e3bebf5059358178ff39b967157e3b Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:14:56 +0200 Subject: [PATCH 15/15] chore(domql): release 1.0.0-preview.4 The fourth preview, implementing DOMQL's specification 1.0.0-preview.2 on Nexo's language 1.0.0-preview.3, from Nexo's release 1.0.0-preview.4. It dates the changelog's and the version history's entries, and is tagged v1.0.0-preview.4, whose release publishes both packages. --- CHANGELOG.md | 2 +- VERSION-HISTORY.md | 2 +- docs/features-status.md | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d53b474..0892662 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ Each release of DOMQL's packages, newest first. The npm package `@formaui-net/do ## `1.0.0-preview.4` -*Unreleased · specification `1.0.0-preview.2` · Nexo language `1.0.0-preview.3` · definition format 38* +*December 1, 2026 · specification `1.0.0-preview.2` · Nexo language `1.0.0-preview.3` · definition format 38* - An element's `layoutSize` answers the size layout gives its border box, along its writing mode's axes, `{ inline, block }`, a transform aside, from the browser's resize observer, null where the element is laid out as no one box or as one of no size, and a watch follows every change of it. - A watch of an element's `size` is refused unless it accepts partial observation, since a transform changes the box as it is drawn with no observer reporting it. Watch `layoutSize`, or accept partial observation. diff --git a/VERSION-HISTORY.md b/VERSION-HISTORY.md index 0bb44bc..cd253db 100644 --- a/VERSION-HISTORY.md +++ b/VERSION-HISTORY.md @@ -17,7 +17,7 @@ Each entry says what its version breaks: ## `1.0.0-preview.2` -*Unreleased · Nexo language `1.0.0-preview.3` · definition format 38* +*December 1, 2026 · Nexo language `1.0.0-preview.3` · definition format 38* ```domql box.layoutSize?.inline // the size layout gives the box along its line, a transform aside; NEXO3001 before, no such member diff --git a/docs/features-status.md b/docs/features-status.md index 8229170..ccf9e30 100644 --- a/docs/features-status.md +++ b/docs/features-status.md @@ -24,7 +24,7 @@ The [specification](../spec/README.md) defines the contract, and the [design](do | --- | --- | | [The C# half](#the-c-half) | Implemented | | [Planned capabilities](#planned-capabilities) | Each implemented or declined | -| [Release](#release) | `1.0.0-preview.3` is released; `1.0.0-preview.4`, on the specification `1.0.0-preview.2`, is unreleased | +| [Release](#release) | Done: `1.0.0-preview.4`, on the specification `1.0.0-preview.2`, is released | | [What 1.0 requires](#what-1-0-requires) | Six requirements, three met | - **A specification version collects the changes between two releases.** A change to DOMQL's contract joins the [version history](../VERSION-HISTORY.md)'s newest entry while it reads *Unreleased*, and opens the next version's entry once it is released, as [D79](decisions.md#d79) records. @@ -268,7 +268,7 @@ None remains: T1 to T3 are implemented, as [the features](#the-host) show: an im DOMQL releases as [cutting a release](../CONTRIBUTING.md#cut-a-release) sets out, by FormaUI Versioning's path, as [D107](decisions.md#d107) records. Its first release, `1.0.0-preview.1`, is released, tagged `v1.0.0-preview.1`, and `release.yml` publishes its NuGet package, with Nexo inside its bundle, to nuget.org through trusted publishing. nuget.org's policy names `FormaUI/DOMQL`, `release.yml` and the `release` environment. -Its second, `1.0.0-preview.2`, is released, tagged `v1.0.0-preview.2`, and `release.yml` publishes its npm package beside the NuGet package, as [D110](decisions.md#d110) records. npm's trusted publisher names the same repository, workflow and environment, and allows `npm publish`. A deprecated placeholder, `@formaui-net/domql@0.0.0`, holds npm's `latest` dist-tag until 1.0, as Nexo's does, since npm takes a trusted publisher only for a package it holds. Its third, `1.0.0-preview.3`, whose npm package changes only the README it carries, is released, tagged `v1.0.0-preview.3`, and published the same way. +Its second, `1.0.0-preview.2`, is released, tagged `v1.0.0-preview.2`, and `release.yml` publishes its npm package beside the NuGet package, as [D110](decisions.md#d110) records. npm's trusted publisher names the same repository, workflow and environment, and allows `npm publish`. A deprecated placeholder, `@formaui-net/domql@0.0.0`, holds npm's `latest` dist-tag until 1.0, as Nexo's does, since npm takes a trusted publisher only for a package it holds. Its third, `1.0.0-preview.3`, whose npm package changes only the README it carries, is released, tagged `v1.0.0-preview.3`, and published the same way, and so is its fourth, `1.0.0-preview.4`, on the specification `1.0.0-preview.2` and Nexo's `1.0.0-preview.4`.