From c4c4bb95eb358b23e337d1b569115f2dd3ad242f Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 5 Dec 2026 23:38:57 +0100 Subject: [PATCH 1/5] Add webfront/Bridge.hpp, a light header for units that only use the bridge (#766) --- docs/CHANGELOG.md | 1 + docs/adr/ADR-029-en-tete-leger-du-bridge.md | 62 ++++ docs/adr/README.md | 5 +- include/webfront/Bridge.hpp | 366 +++++++++++++++++++ include/webfront/BridgeHost.hpp | 192 ++++++++++ include/webfront/Introspection.hpp | 253 +------------ include/webfront/WebFront.hpp | 128 +------ include/webfront/details/CppFunction.hpp | 143 ++++++++ include/webfront/details/TypescriptNames.hpp | 281 ++++++++++++++ test/cmake/consumer/CMakeLists.txt | 2 +- test/cmake/consumer/main.cpp | 4 + test/cmake/consumer/page.cpp | 19 + test/unit/BridgeLightPage.cpp | 64 ++++ test/unit/BridgeLightPage.hpp | 15 + test/unit/BridgeLightTests.cpp | 159 ++++++++ test/unit/CMakeLists.txt | 4 +- test/web/CMakeLists.txt | 2 +- test/web/JasmineTest.cpp | 4 + test/web/suite/specs/light-bridge-specs.mjs | 33 ++ test/web/suite/specs/webfront-specs.mjs | 1 + 20 files changed, 1364 insertions(+), 374 deletions(-) create mode 100644 docs/adr/ADR-029-en-tete-leger-du-bridge.md create mode 100644 include/webfront/Bridge.hpp create mode 100644 include/webfront/BridgeHost.hpp create mode 100644 include/webfront/details/CppFunction.hpp create mode 100644 include/webfront/details/TypescriptNames.hpp create mode 100644 test/cmake/consumer/page.cpp create mode 100644 test/unit/BridgeLightPage.cpp create mode 100644 test/unit/BridgeLightPage.hpp create mode 100644 test/unit/BridgeLightTests.cpp create mode 100644 test/web/suite/specs/light-bridge-specs.mjs diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index bcc6d773..686811a2 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -19,6 +19,7 @@ these entries stays in the GitHub releases and the Git history. - A type that converts to `std::string_view` without being a string is no longer written as text by `info()`, `fail()` and `checkEqual` (it appears as `{?}` without a `Printer`): specialize `webfront::bdd::isString` (or `Printer`) for it (#739, `docs/BDD.md`). ### Added +- A unit that only registers C++ functions or calls JavaScript can include the light `webfront/Bridge.hpp` and compiles in about a third of the time: pass it `webfront::bridgeFunctions(app)` or `webfront::bridgeUI(ui)` (#766, ADR-029). - Write the SPDX bill of materials of your application with `webfront_write_sbom()` (#762, ADR-028, `docs/DISTRIBUTION.md`). - First measurements of image streams to the page: raw frames, JPEG and WebCodecs availability under CEF and WebKitGTK (#769, `docs/IMAGE_STREAMS.md`). - Open an embedded window maximized, full screen, without a frame or with a minimum size (`WindowOptions`), on WebKitGTK and CEF (#764, `docs/FRONTENDS.md`). diff --git a/docs/adr/ADR-029-en-tete-leger-du-bridge.md b/docs/adr/ADR-029-en-tete-leger-du-bridge.md new file mode 100644 index 00000000..3fc2839f --- /dev/null +++ b/docs/adr/ADR-029-en-tete-leger-du-bridge.md @@ -0,0 +1,62 @@ +# ADR-029 : Un en-tête léger pour les unités qui n'utilisent que le bridge + +## Versions + +| Version | Date | État | Auteur | Évolution | Révision Git | +| --- | --- | --- | --- | --- | --- | +| 1.0 | 2026-12-05 | Proposée | Ambroise Leclerc | `webfront/Bridge.hpp` : frontière à effacement de type entre l'unité qui instancie l'application et les autres (#766). | Branche `766-light-header` | + +## État et chronologie + +**Proposée.** Décision initiale : **2026-12-05** (version 1.0). + +## Contexte + +Une unité qui ne fait qu'enregistrer des fonctions C++ ou appeler JavaScript devait inclure `WebFront.hpp` : le serveur, +le réseau, stdexec et les inspecteurs, soit 15,7 s avec GCC 16 en `-O3` (`BUILD_TIME_STUDY.md`). `UI`, `cppFunction` et +`jsFunction` sont des gabarits sur le type de l'application, qu'aucun réagencement d'inclusions ne retire de ces unités. + +## Décision + +`webfront/Bridge.hpp` donne à ces unités `BridgeUI` et `BridgeFunctions`, sans le type de l'application : + +- la frontière est `detail::BridgeTarget` (un navigateur) et `detail::BridgeRegistrar` (un enregistrement), des + interfaces virtuelles par lesquelles passent des messages binaires entiers ; +- l'encodage et le décodage des valeurs restent des gabarits, instanciés dans l'unité qui connaît les types, avec les + codecs de `weblink/Messages.hpp` : le format du bridge ne change pas ; +- l'unité qui inclut `WebFront.hpp` instancie l'application et donne les objets légers avec `webfront::bridgeUI(ui)` et + `webfront::bridgeFunctions(app)` ; +- `Bridge.hpp` n'inclut ni le serveur, ni le réseau, ni stdexec, ni les watches ; la construction de la seconde unité des + tests le vérifie pour stdexec. + +Une fonction enregistrée ainsi est une fonction de l'application : mêmes noms réservés, mêmes exigences d'appelant, +mêmes comptes et mêmes déclarations TypeScript pour les inspecteurs et `wf bindings`. + +## Options écartées et motifs + +- En-têtes précompilés et `extern template` : mesurés et écartés (`BUILD_TIME_STUDY.md`). +- Faire de `UI` et `cppFunction` eux-mêmes des types effacés : chaque appel de toute application paierait une indirection + et les fonctions différées devraient aussi être effacées. +- `import webfront;` : GCC 16.1 se termine par une erreur interne sur stdexec. + +## Conséquences + +- **Bénéfice :** une unité secondaire ne paie plus le serveur ni stdexec. +- **Coût :** une indirection virtuelle et une copie du message par appel passé par `Bridge.hpp`. +- **Limites :** pas de rappel différé (sender, coroutine, `Stream`), pas de `jsFunctionSender`, pas d'enregistrement sur un + espace (`Space`) ; ces cas restent dans une unité qui inclut `WebFront.hpp`. Un `BridgeUI` ou un `BridgeFunctions` ne + doit pas survivre à son application. Une politique de tampons autre que la politique par défaut s'écrit + `BasicBridgeUI` dans l'unité légère. + +## Prescriptions d'implémentation et de génération de code + +- Ne rien inclure dans `Bridge.hpp` qui tire le réseau ou stdexec ; mesurer avant d'y ajouter un en-tête. +- Garder `BridgeHost` équivalent à `JsFunction` et à l'enregistrement de `cppFunction` : une règle ajoutée à l'un vaut + pour l'autre. +- Ne pas présenter `Bridge.hpp` comme réduisant le coût de l'unité qui instancie l'application. + +## Sources et vérification + +`include/webfront/Bridge.hpp`, `include/webfront/BridgeHost.hpp` ; `test/unit/BridgeLightPage.cpp` et +`BridgeLightTests.cpp`, `test/web/suite/specs/light-bridge-specs.mjs`, `test/cmake/consumer/` ; mesures dans +`docs/BUILD_TIME_STUDY.md`. diff --git a/docs/adr/README.md b/docs/adr/README.md index f099ad50..3e6bc5a6 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -71,6 +71,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-026](ADR-026-configuration-mcp-persistante.md) | Stable MCP client configuration with explicit development security modes | Accepted | 2026-11-22 | 1.2 — 2026-11-22 | | [ADR-027](ADR-027-inspecteurs-de-l-etat-de-l-application.md) | Application state inspectors in the developer environment only: reserved `webfront.inspector.*` functions refused to unproven views unless the application trusts loopback clients, tree nodes on existing bridge types with paged reads and paged differences, observer operations run whole under the application's lock or on its executor, writes only when the application provides them, one `inspector.html` page, shown in a floating window of the page and, for a detached panel only, in the first container that grants access (a native secondary window, else a system-browser tab); an introspectable registry of the registered C++ functions, of the JavaScript functions C++ calls and of the connected browsers, counted with relaxed atomics and timed only while an inspector reads | Accepted through 1.6; 1.7 proposed | 2026-11-25 | 1.7 — 2026-12-04 | | [ADR-028](ADR-028-distribution.md) | Distributing an application without imposing a tool, a key or a server | Proposed | 2026-12-05 | 1.0 — 2026-12-05 | +| [ADR-029](ADR-029-en-tete-leger-du-bridge.md) | A light header for the units that only use the bridge: a type-erased boundary to the unit that instantiates the application | Proposed | 2026-12-05 | 1.0 — 2026-12-05 | Numbering follows the reading topics; milestones and individual file histories provide the chronology, which does not follow the numerical order. @@ -88,7 +89,7 @@ the chronology, which does not follow the numerical order. | Planned work | ADRs to read in addition to the 001/002/012 baseline | | --- | --- | -| Bridge, codecs or new data types | 003, 004, 006, 009 | +| Bridge, codecs or new data types | 003, 004, 006, 009, 029 | | Networking, concurrency, lifetimes or shutdown | 005, 006 | | Files, resources and modules | 009, 010 | | A new engine or changes to window lifecycle | 006, 007, 008 | @@ -117,7 +118,7 @@ Do not replace historical dates with the date of an editorial change to the docu Keep previous rows and update the current version in the index. - Use one `ADR-NNN-description.md` file per decision and one row in this index. The next number - is **ADR-028**. Retain historical numbers and files. + is **ADR-030**. Retain historical numbers and files. - For a new decision that has not been integrated, use **Proposée** (Proposed), its actual proposal date and validation criteria; do not assign an artificial historical commit date. - After integration, record the date and supporting commits, the accepted negative diff --git a/include/webfront/Bridge.hpp b/include/webfront/Bridge.hpp new file mode 100644 index 00000000..13995c2b --- /dev/null +++ b/include/webfront/Bridge.hpp @@ -0,0 +1,366 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-05 +// +// WebFront — core +// Role: The light header of a unit that only registers C++ functions and calls JavaScript ones: BridgeUI and BridgeFunctions (ADR-029). +// Thread: worker-safe | Alloc: unrestricted +// LLM: public API; never include the server, the networking, stdexec or WebFront.hpp here, it is what the header avoids + +#pragma once + +#include "BridgeError.hpp" +#include "Callers.hpp" +#include "details/CppFunction.hpp" +#include "details/TypescriptNames.hpp" +#include "http/BuffersPolicy.hpp" +#include "weblink/Messages.hpp" +#include "weblink/PendingCalls.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront { + +namespace detail { + +/// One browser, seen without the application type. Implemented where the application is instantiated (BridgeHost.hpp). +/// A `message` is a whole bridge message, header first; the implementation writes the call identifier into its header. +class BridgeTarget { +public: + BridgeTarget() = default; + BridgeTarget(const BridgeTarget&) = delete; + BridgeTarget& operator=(const BridgeTarget&) = delete; + virtual ~BridgeTarget() = default; + + /// A call that ignores its result: dropped when the browser is gone. + virtual void send(std::string_view name, std::span message) const = 0; + /// A call with a result. `complete` receives the whole return message and says whether it could be decoded as what the + /// caller expects; `reject` is told the failure. One of the two is called, possibly before call() returns. + virtual void call(std::string_view name, + std::vector message, + std::function)> complete, + std::function reject, + std::chrono::milliseconds delay) const = 0; + + [[nodiscard]] virtual std::chrono::milliseconds callTimeout() const = 0; + virtual void checkCallDelay(std::chrono::milliseconds delay) const = 0; + [[nodiscard]] virtual std::size_t id() const = 0; + [[nodiscard]] virtual bool isEmbeddedView() const = 0; + [[nodiscard]] virtual bool isLocalClient() const = 0; + [[nodiscard]] virtual std::string spacePath() const = 0; +}; + +/// The bytes of a bridge message being encoded: what the encoder appends, copied behind the room left for the header. +template +struct MessageBytes { + std::vector bytes = std::vector(sizeof(Header)); + + void addBuffer(std::span buffer) { + bytes.insert(bytes.end(), buffer.begin(), buffer.end()); + } + /// Writes the header, complete once everything is encoded, and gives the message. + template + [[nodiscard]] std::vector finish(const Message& message) && { + std::memcpy(bytes.data(), message.header().data(), sizeof(Header)); + return std::move(bytes); + } +}; + +/// What a callback answered: the return message, and the failure's text when it is one (for the inspectors' count). +struct BridgeAnswer { + std::vector message; + std::optional failure; +}; + +/// What cppFunction registered through BridgeFunctions, for the application's unit to add. +struct BridgeRegistration { + std::string name{}; + std::source_location location{}; + callers::Requirement requirement{}; + bool takesCaller = false; + + // The TypeScript of the signature, empty in a distribution build. + std::vector parameters{}; // without the calling browser + std::string result{}; + std::vector declaredParameters{}; // as wf bindings writes them (bitsets named) + std::string declaredResult{}; + std::vector structures{}; + + std::function data, std::shared_ptr caller)> invoke{}; +}; + +class BridgeRegistrar { +public: + BridgeRegistrar() = default; + BridgeRegistrar(const BridgeRegistrar&) = delete; + BridgeRegistrar& operator=(const BridgeRegistrar&) = delete; + virtual ~BridgeRegistrar() = default; + virtual bool add(BridgeRegistration registration) = 0; +}; + +/// A callback that answers later returns a sender, a coroutine or a stream: those need the whole application header. +template +concept answers_later = requires { typename R::sender_concept; } || requires { typename R::promise_type; } || requires(R r) { + r.produce; + r.window; +}; + +} // namespace detail + +template +class BasicBridgeJsFunction; + +/** + * @brief One connected browser, without the type of the application: what a unit that includes only this header calls. + * + * Made from the application's UI with `webfront::bridgeUI(ui)` (declared by WebFront.hpp), or received by a function + * registered through BridgeFunctions that takes it as its first parameter. Copies refer to the same connection, with the + * guarantees of UI: once the connection is gone, calls are dropped and typed calls fail. It must not outlive its application. + */ +template +class BasicBridgeUI { +public: + explicit BasicBridgeUI(std::shared_ptr browser) : target(std::move(browser)) { } + + /// As UI::jsFunction: fire-and-forget. + [[nodiscard]] auto jsFunction(std::string_view functionName) const { + return BasicBridgeJsFunction{std::string(functionName), target}; + } + /// As UI::jsFunction: the call returns a std::future. + template + [[nodiscard]] auto jsFunction(std::string_view functionName) const { + return BasicBridgeJsFunction{std::string(functionName), target}; + } + + /// UI::id() + [[nodiscard]] std::size_t id() const { + return target->id(); + } + /// UI::isEmbeddedView() + [[nodiscard]] bool isEmbeddedView() const { + return target->isEmbeddedView(); + } + /// UI::isLocalClient() + [[nodiscard]] bool isLocalClient() const { + return target->isLocalClient(); + } + /// UI::spacePath() + [[nodiscard]] std::string spacePath() const { + return target->spacePath(); + } + +private: + std::shared_ptr target; +}; + +/// The callable of BasicBridgeUI::jsFunction. `Result` is `void*` for the untyped form, which ignores the result. +template +class BasicBridgeJsFunction { + static constexpr bool ignored = std::is_same_v; + +public: + BasicBridgeJsFunction(std::string functionName, std::shared_ptr browser) + : name(std::move(functionName)), target(std::move(browser)), delay(target->callTimeout()) { } + + /// As JsFunction::timeout. + [[nodiscard]] BasicBridgeJsFunction timeout(std::chrono::milliseconds limit) const { + static_assert(!ignored, "A call that ignores its result has no delay: use jsFunction"); + target->checkCallDelay(limit); + auto bounded = *this; + bounded.delay = limit; + return bounded; + } + + auto operator()(auto&&... arguments) const { + msg::FunctionCall command; + detail::MessageBytes> frame; + command.encodeParameter(name, frame); + (command.encodeParameter(std::forward(arguments), frame), ...); + command.setParametersCount(static_cast(1 + sizeof...(arguments))); + auto message = std::move(frame).finish(command); + + if constexpr (ignored) + target->send(name, message); + else { + auto promise = std::make_shared>(); + auto future = promise->get_future(); + target->call( + name, + std::move(message), + [promise](std::span returned) { + try { + const auto& answer = *msg::FunctionReturn::castFromRawData(returned); + if constexpr (std::is_void_v) { + detail::decodeReturn(answer); + promise->set_value(); + } else + promise->set_value(detail::decodeReturn(answer)); + return true; + } catch (...) { + promise->set_exception(std::current_exception()); + return false; + } + }, + [promise](std::exception_ptr failure) { + promise->set_exception(std::move(failure)); + }, + delay); + return future; + } + } + +private: + std::string name; + std::shared_ptr target; + std::chrono::milliseconds delay; +}; + +/** + * @brief Where a unit that includes only this header registers the C++ functions the page calls. + * + * Made by the unit that instantiates the application, with `webfront::bridgeFunctions(app)`. The functions are the + * application's own, as if registered with `app.cppFunction`. A callback answers at once: one that returns a sender, a + * coroutine or a webfront::Stream is registered on the application. It must not outlive its application. + */ +template +class BasicBridgeFunctions { +public: + using UI = BasicBridgeUI; + + explicit BasicBridgeFunctions(std::shared_ptr application) : registrar(std::move(application)) { } + + /// As BasicWF::cppFunction. A first parameter of type UI receives the calling browser. + template + bool cppFunction(std::string functionName, auto&& function, std::source_location location = std::source_location::current()) { + return add(std::move(functionName), std::forward(function), location, {}); + } + template + bool + cppFunction(std::string functionName, auto&& function, callers::Requirement requirement, std::source_location location = std::source_location::current()) { + return add(std::move(functionName), std::forward(function), location, std::move(requirement)); + } + /// The signature deduced from the callable, as BasicWF::cppFunction does. + template + bool cppFunction(std::string functionName, Function&& function, std::source_location location = std::source_location::current()) { + return deduce(std::move(functionName), std::forward(function), location, {}); + } + template + bool cppFunction(std::string functionName, + Function&& function, + callers::Requirement requirement, + std::source_location location = std::source_location::current()) { + return deduce(std::move(functionName), std::forward(function), location, std::move(requirement)); + } + +private: + std::shared_ptr registrar; + + template + bool deduce(std::string name, Function&& function, const std::source_location& location, callers::Requirement requirement) { + using Callable = std::decay_t; + static_assert(detail::has_callable_traits, + "webfront::BridgeFunctions::cppFunction: could not deduce this callable's signature. Give it explicitly: " + "cppFunction(name, callable)."); + if constexpr (detail::has_callable_traits) { + using Traits = detail::callable_traits; + using Args = typename detail::caller_aware_args::type; + return [&](std::type_identity>) { + return add(std::move(name), std::forward(function), location, std::move(requirement)); + }(std::type_identity{}); + } else + return false; + } + + template + bool add(std::string name, auto&& function, const std::source_location& location, callers::Requirement requirement) { + static_assert(!detail::answers_later>, + "webfront::BridgeFunctions registers callbacks that answer at once: register a sender, a coroutine or a stream " + "with app.cppFunction in a unit that includes WebFront.hpp"); + detail::BridgeRegistration registration{.name = std::move(name), .location = location, .requirement = std::move(requirement)}; + if constexpr (detail::takes_caller::value) { + registration.takesCaller = true; + [&](std::type_identity>) { + describe(registration); + bind(registration, detail::adaptCaller(std::forward(function)), std::true_type{}); + }(std::type_identity>{}); + } else { + describe(registration); + bind(registration, std::forward(function), std::false_type{}); + } + return registrar->add(std::move(registration)); + } + + template + static void describe(detail::BridgeRegistration& registration) { + if constexpr (inspect::introspection) { + registration.parameters = {inspect::typescriptType()...}; + registration.result = inspect::typescriptType(); + // The declarations of the page name bitsets apart from containers of bytes. + const inspect::BitsetNaming naming; + registration.declaredParameters = {inspect::typescriptType()...}; + registration.declaredResult = inspect::typescriptType(); + (inspect::detail::declareStructures(registration.structures), ...); + inspect::detail::declareStructures(registration.structures); + } + } + + template + static void bind(detail::BridgeRegistration& registration, Function&& function, std::bool_constant) { + auto decoded = detail::makeCppFunctionHandler...>(std::forward(function)); + registration.invoke = [decoded = std::move(decoded)](std::span data, std::shared_ptr caller) mutable { + using Header = msg::FunctionCallHeader; + // A failure may come from the callback or from encoding its value, which can leave a message partly encoded: + // a failure is sent in a fresh one. + try { + msg::FunctionReturn result; + detail::MessageBytes
frame; + const auto call = [&]() -> R { + if constexpr (Caller) { + UI browser{std::move(caller)}; + return decoded(data, browser); + } else + return decoded(data); + }; + if constexpr (std::is_void_v) + call(); + else { + auto value = call(); + result.encodeParameter(value, frame); + } + return detail::BridgeAnswer{std::move(frame).finish(result), std::nullopt}; + } catch (const std::exception& error) { + return failureOf(error); + } catch (...) { + return failureOf(std::runtime_error{"Unknown C++ exception"}); + } + }; + } + + static detail::BridgeAnswer failureOf(const std::exception& error) { + msg::FunctionReturn result; + detail::MessageBytes> frame; + result.encodeParameter(error, frame); + return {std::move(frame).finish(result), std::string(error.what())}; + } +}; + +using BridgeUI = BasicBridgeUI<>; +using BridgeFunctions = BasicBridgeFunctions<>; + +} // namespace webfront diff --git a/include/webfront/BridgeHost.hpp b/include/webfront/BridgeHost.hpp new file mode 100644 index 00000000..d8658b43 --- /dev/null +++ b/include/webfront/BridgeHost.hpp @@ -0,0 +1,192 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-05 +// +// WebFront — core +// Role: The application's side of Bridge.hpp: bridgeUI() and bridgeFunctions(), instantiated where the application is (ADR-029). +// Thread: worker-safe | Alloc: unrestricted +// LLM: internal; included by WebFront.hpp only, keep a BridgeTarget call equivalent to JsFunction and registerCppFunction + +#pragma once + +#include "Bridge.hpp" +#include "Introspection.hpp" +#include "weblink/WebLink.hpp" + +#include + +namespace webfront { + +namespace detail { + +template +struct BridgeHost { + using Net = typename App::Net; + using Policy = typename App::BufferPolicy; + + class Target final : public BridgeTarget { + public: + Target(App& application, WebLinkId linkId, WebLinkGeneration connectionGeneration) + : app(application), link(linkId), generation(connectionGeneration) { } + + void send(std::string_view name, std::span message) const override { + const auto connection = app.findLink(link, generation); + if (const auto counter = app.jsCallCounter(name)) + counter->called(); + if (connection) + connection->sendFrame(owned(message)); + } + + void call(std::string_view name, + std::vector message, + std::function)> complete, + std::function reject, + std::chrono::milliseconds delay) const override { + const auto connection = app.findLink(link, generation); + const auto counter = app.jsCallCounter(name); + if (counter) + counter->called(); + const auto failed = [counter]() noexcept { + if (counter) + counter->failed(); + }; + if (!connection) { + failed(); + reject(std::make_exception_ptr(disconnectedError())); + return; + } + const auto pending = connection->pendingResults().lock(); + if (!pending) { + failed(); + reject(std::make_exception_ptr(disconnectedError())); + return; + } + msg::CallId id{}; + try { + id = pending->add({.complete = + [complete = std::move(complete), failed](const msg::FunctionReturn& result) { + if (!complete({result.header().data(), result.header().size() + result.payload().size()})) + failed(); + }, + .reject = + [reject, failed](std::exception_ptr error) { + failed(); + reject(std::move(error)); + }}); + } catch (...) { + failed(); + reject(std::current_exception()); + return; + } + setCallId(message, id); + connection->sendFrame(owned(message)); + app.armCallDeadline(connection->pendingResults(), id, delay); + } + + [[nodiscard]] std::chrono::milliseconds callTimeout() const override { + return app.callTimeout(); + } + void checkCallDelay(std::chrono::milliseconds delay) const override { + static_cast(App::checkedCallDelay(delay)); + } + [[nodiscard]] std::size_t id() const override { + return link; + } + [[nodiscard]] bool isEmbeddedView() const override { + return app.isEmbeddedView(link, generation); + } + [[nodiscard]] bool isLocalClient() const override { + return app.isLocalClient(link, generation); + } + [[nodiscard]] std::string spacePath() const override { + return app.spacePathOf(link, generation); + } + + private: + App& app; + WebLinkId link; + WebLinkGeneration generation; + }; + + class Registrar final : public BridgeRegistrar { + public: + explicit Registrar(App& application) : app(application) { } + + bool add(BridgeRegistration registration) override { + using UI = typename App::UI; + App::refuseReservedName(registration.name); + if (app.cppFunctions.contains(registration.name)) + return false; + std::shared_ptr record; + if constexpr (inspect::introspection) { + record = app.functionRegistry->prepare(registration.name, + inspect::typescriptSignature(registration.parameters, registration.result), + registration.takesCaller, + false, + registration.location, + {}); + record->wholeSignature = inspect::typescriptWholeSignature(registration.declaredParameters, registration.declaredResult); + record->structures = std::move(registration.structures); + record->access = registration.requirement.label(); + } + auto handler = app.guarded(registration.name, + std::move(registration.requirement), + [invoke = std::move(registration.invoke), record, application = &app](std::span data, + WebLink& connection, + msg::CallId callId, + UI caller) mutable { + const inspect::CallMeasure measure{record.get()}; // the handler owns the record while it runs + auto answer = invoke(data, std::make_shared(*application, caller.id(), caller.generation)); + if (answer.failure) + measure.failed(*answer.failure); + if (callId == 0) + return; + setCallId(answer.message, callId); + connection.sendFrame(owned(answer.message)); + }); + const bool added = app.cppFunctions.try_emplace(std::move(registration.name), std::move(handler)).second; + if (added) + app.publishFunction(record); + return added; + } + + private: + App& app; + }; + + template + static void setCallId(std::vector& message, msg::CallId id) { + std::memcpy(message.data() + offsetof(msg::FunctionCallHeader, callId), &id, sizeof(id)); + } + + /// A frame that owns its bytes: it outlives the message it was made from. + static websocket::Frame owned(std::span message) { + websocket::Frame frame{message}; + frame.freeze(); + return frame; + } + + static auto browser(const typename App::UI& ui) { + return BasicBridgeUI{std::make_shared(*ui.webFront, ui.webLinkId, ui.generation)}; + } + + static auto functions(App& app) { + return BasicBridgeFunctions{std::make_shared(app)}; + } +}; + +} // namespace detail + +/// The browser of `ui` for a unit that includes only Bridge.hpp. +template +[[nodiscard]] auto bridgeUI(const BasicUI& ui) { + return detail::BridgeHost::browser(ui); +} + +/// Where a unit that includes only Bridge.hpp registers C++ functions of `app`. +template +[[nodiscard]] auto bridgeFunctions(App& app) { + return detail::BridgeHost::functions(app); +} + +} // namespace webfront diff --git a/include/webfront/Introspection.hpp b/include/webfront/Introspection.hpp index d83a339d..d5639b7a 100644 --- a/include/webfront/Introspection.hpp +++ b/include/webfront/Introspection.hpp @@ -9,6 +9,7 @@ #pragma once +#include "details/TypescriptNames.hpp" #include "Watches.hpp" #include "weblink/Messages.hpp" @@ -39,13 +40,6 @@ namespace webfront::inspect { -/// False in a distribution build (WEBFRONT_DISTRIBUTION): nothing is recorded there, and no call is counted. -#if defined(WEBFRONT_DISTRIBUTION) && WEBFRONT_DISTRIBUTION -inline constexpr bool introspection = false; -#else -inline constexpr bool introspection = true; -#endif - /// A signature is written in at most this many bytes; a longer one ends with "…". inline constexpr std::size_t maxSignatureBytes = 512; /// The names of the JavaScript functions that C++ calls are counted one by one up to this many; the calls of the names @@ -54,251 +48,6 @@ inline constexpr std::size_t maxJsFunctionNames = 1024; /// A duration is measured while an inspector read the functions less than this long ago. inline constexpr std::chrono::seconds timingWindow{5}; -// --- TypeScript names ------------------------------------------------------------------------------------------ - -namespace detail { -template -struct typescript_tuple : std::false_type { }; - -template -[[nodiscard]] std::string typescriptName(); - -template -struct typescript_tuple> : std::true_type { - static std::string write() { - std::string text = "["; - static_cast(((text += (text.size() > 1 ? ", " : "") + typescriptName()), ...)); - return text + "]"; - } -}; -template -struct typescript_tuple> : typescript_tuple> { }; - -template -[[nodiscard]] constexpr std::string_view typedArrayName() noexcept { - using E = std::remove_cv_t; - if constexpr (std::is_same_v) - return "Float32Array"; - else if constexpr (std::is_same_v) - return "Float64Array"; - else if constexpr (sizeof(E) == 1) - return std::is_signed_v ? "Int8Array" : "Uint8Array"; - else if constexpr (sizeof(E) == 2) - return std::is_signed_v ? "Int16Array" : "Uint16Array"; - else if constexpr (sizeof(E) == 4) - return std::is_signed_v ? "Int32Array" : "Uint32Array"; - else - return std::is_signed_v ? "BigInt64Array" : "BigUint64Array"; -} - -/// `text` as a TypeScript string literal. -[[nodiscard]] inline std::string quoted(std::string_view text) { - std::string literal = "\""; - for (const char character : text) { - const auto byte = static_cast(character); - if (character == '"' || character == '\\') - literal += std::string{'\\', character}; - else if (byte < 0x20 || byte == 0x7f) - literal += std::format("\\x{:02x}", byte); - else - literal += character; - } - return literal + '"'; -} - -/// Set while the types of the page's declarations are written: they tell a std::bitset from a container of bytes. -inline thread_local bool namingBitsets = false; - -/// The members of a union, in parentheses when it is the element of an array. -[[nodiscard]] inline std::string parenthesized(std::string type) { - return type.find('|') == std::string::npos ? type : '(' + std::move(type) + ')'; -} - -template -struct typescript_variant : std::false_type { }; -template -struct typescript_variant> : std::true_type { - /// A discriminated union: `[0, A] | [1, B]`, the index of the alternative first. - static std::string write() { - std::string text; - std::size_t index = 0; - static_cast(((text += (index == 0 ? "" : " | ") + ("[" + std::to_string(index) + ", " + typescriptName() + "]"), ++index), ...)); - return text; - } -}; - -template -[[nodiscard]] std::string typescriptName() { - using U = std::remove_cvref_t; - if constexpr (std::is_void_v) - return "void"; - else if constexpr (std::is_same_v) - return "null"; - else if constexpr (std::is_same_v) - return "boolean"; - else if constexpr (std::is_arithmetic_v) - return "number"; - else if constexpr (std::is_convertible_v) - return "string"; - else if constexpr (msg::is_bitset_v) - return namingBitsets ? "WebFrontBitset" : "Uint8Array"; - else if constexpr (bridge::described) - return std::string{bridge::structName()}; - else if constexpr (msg::is_optional_v) - return typescriptName() + " | null"; - else if constexpr (typescript_variant::value) - return typescript_variant::write(); - else if constexpr (msg::is_expected_v) - return "[true, " + (std::is_void_v ? std::string{"null"} : typescriptName()) + "] | [false, " - + typescriptName() + "]"; - else if constexpr (typescript_tuple::value) - return typescript_tuple::write(); - else if constexpr (msg::container_adaptor) - return typescriptName(); - else if constexpr (msg::mdspan_like) - return "[" + std::string{typedArrayName()} + ", Uint32Array]"; - else if constexpr (msg::bridge_range) { - using Element = msg::bridge_range_element_t; - if constexpr (msg::is_numeric_array_element_v) - return std::string{typedArrayName()}; - else if constexpr (msg::is_pair_v) - // The entries of a map: the key is not constant for the page. - return "[" + typescriptName() + ", " + typescriptName() + "][]"; - else - return parenthesized(typescriptName()) + "[]"; - } else - return "unknown"; -} -} // namespace detail - -/// While alive, on this thread, a std::bitset is written `WebFrontBitset`: what wf bindings declares. -class BitsetNaming { -public: - BitsetNaming() noexcept : previous(detail::namingBitsets) { - detail::namingBitsets = true; - } - BitsetNaming(const BitsetNaming&) = delete; - BitsetNaming& operator=(const BitsetNaming&) = delete; - ~BitsetNaming() { - detail::namingBitsets = previous; - } - -private: - bool previous; -}; - -/** - * The TypeScript type that JavaScript gives or receives for the C++ type T on the bridge: `boolean`, `number`, `string`, - * the typed array of a container of numbers (`Uint8Array` for a `std::bitset`, packed), `[A, B]` for a tuple or a pair, - * `T[]` for a container of anything else (`[K, V][]` for a map), `T | null` for a `std::optional`, `[0, A] | [1, B]` for a - * `std::variant`, `[true, T] | [false, E]` for a `std::expected`, `void`, and `unknown` for a type the bridge does not carry. - */ -template -[[nodiscard]] std::string typescriptType() { - return detail::typescriptName(); -} - -/// The TypeScript declaration of one described structure, as a function that carries it needs it. -struct StructureDeclaration { - std::string name; - std::type_index type; - std::string text; // "/** bounds */\ntype Name = [...];\n", without `export` -}; - -namespace detail { -/// Appends the declarations of the described structures that T is or holds, each type once and after those it names. -template -void declareStructures(std::vector& declared) { - using U = std::remove_cvref_t; - if constexpr (bridge::described) { - const std::string name{bridge::structName()}; - const std::type_index type{typeid(U)}; - for (const auto& known : declared) - if (known.type == type) - return; - // Marked before its members, which may hold the structure again (a node and its children); written after them. - declared.push_back({name, type, {}}); - std::string fields, bounds; - bridge::forEachMember([&](const auto& member) { - using Value = std::remove_cvref_t().*(member.pointer))>; - declareStructures(declared); - fields += (fields.empty() ? "" : ", ") + std::string(member.name) + ": " + typescriptName(); - if constexpr (std::remove_cvref_t::bounded) - bounds += (bounds.empty() ? "" : "; ") + std::string(member.name) + ": " + std::format("{} to {}", member.min, member.max); - }); - std::erase_if(declared, [&](const auto& known) { - return known.type == type; - }); - declared.push_back({name, type, (bounds.empty() ? std::string{} : "/** " + bounds + " */\n") + "type " + name + " = [" + fields + "];\n"}); - } else if constexpr (msg::is_variant_v) { - [&](std::index_sequence) { - (declareStructures>(declared), ...); - }(std::make_index_sequence>{}); - } else if constexpr (msg::is_expected_v) { - if constexpr (!std::is_void_v) - declareStructures(declared); - declareStructures(declared); - } else if constexpr (requires { typename U::value_type; }) { - if constexpr (!std::same_as, U>) - declareStructures(declared); - } else if constexpr (requires { std::tuple_size::value; }) { - [&](std::index_sequence) { - (declareStructures>(declared), ...); - }(std::make_index_sequence>{}); - } -} - -/// Refuses two structures of different types under one name. -inline void requireDistinctNames(const std::vector& declared) { - std::map names; - for (const auto& structure : declared) - if (names.try_emplace(structure.name, structure.type).first->second != structure.type) - throw std::logic_error("Two described structures are named " + structure.name + ": give each its own name"); -} -} // namespace detail - -/** - * The TypeScript declarations of the described structures given and of those they hold: a labelled tuple each, since a - * structure crosses the bridge as the tuple of its fields. The bounds of numeric fields are written in the comment. - * Name every structure of a .d.ts file in one call, so that a shared one is declared once. - * - * // speed: 1 to 10 - * export type Settings = [speed: number, title: string]; - */ -template - requires(bridge::described && ...) -[[nodiscard]] std::string typescriptDeclaration() { - std::vector declared; - (detail::declareStructures(declared), ...); - detail::requireDistinctNames(declared); - std::string text; - for (const auto& structure : declared) { - // After the comment of the bounds, when there is one. - const auto line = structure.text.starts_with("/**") ? structure.text.find('\n') + 1 : 0; - text += structure.text.substr(0, line) + "export " + structure.text.substr(line); - } - return text; -} - -/// The signature of a function as a page declares it: `(a: number, b: string) => Promise`. A call from JavaScript -/// always returns a Promise, also for a function that returns nothing; a `streamed` one is read with cppStream, whose call -/// gives the iterable itself. -[[nodiscard]] inline std::string typescriptWholeSignature(const std::vector& parameters, std::string_view result, bool streamed = false) { - std::string text = "("; - for (std::size_t i = 0; i < parameters.size(); ++i) { - if (i != 0) - text += ", "; - // a, b, ... z, then a1, b1, ...: a name the declaration needs and the C++ signature does not give - text += static_cast('a' + i % 26); - if (i >= 26) - text += std::to_string(i / 26); - text += ": " + parameters[i]; - } - if (streamed) - return text + ") => AsyncIterable<" + std::string(result) + ">"; - return text + ") => Promise<" + std::string(result) + ">"; -} - /// typescriptWholeSignature(), cut to what the inspectors show. [[nodiscard]] inline std::string typescriptSignature(const std::vector& parameters, std::string_view result, bool streamed = false) { return boundedText(typescriptWholeSignature(parameters, result, streamed), maxSignatureBytes); diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index b6cc7468..4e455276 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -13,6 +13,7 @@ #include "Broadcast.hpp" #include "Callers.hpp" #include "DeferredCalls.hpp" +#include "details/CppFunction.hpp" #include "details/SpaceState.hpp" #include "dom/Document.hpp" #include "frontend/Frontend.hpp" @@ -66,6 +67,11 @@ struct PageRegistration; template class BasicSpace; +namespace detail { +template +struct BridgeHost; +} // namespace detail + inline constexpr std::string_view version = "1.3.0"; namespace testing { @@ -135,6 +141,8 @@ class BasicUI { private: template friend class dom::Document; + template + friend struct detail::BridgeHost; [[nodiscard]] auto domState() const { return webFront->domState(webLinkId, generation); } @@ -276,35 +284,6 @@ inline int ensureFrontendInitialized() { return 0; } -/// Decodes Args from the call data and invokes the callable with them, preceded by 'caller' (the -/// calling UI, for callables that take it as their first parameter, or nothing). -template -auto makeCppFunctionHandler(Function&& function) { - using StoredFunction = std::decay_t; - auto callable = std::make_shared(std::forward(function)); - - return [callable = std::move(callable)](std::span data, auto&&... caller) -> R { - std::tuple parameters; - auto deserializeAndCall = [&](std::tuple& tuple, std::index_sequence) -> R { - // Arguments that cannot be decoded as the callback declared them reject with the `webfront.malformed` code. - try { - (msg::FunctionCall::decodeParameter(std::get(tuple), data), ...); - if (!data.empty()) - throw std::runtime_error("Function call contains trailing parameter data"); - } catch (const std::exception& error) { - throw detail::makeBridgeError(bridge_code::malformed, error.what()); - } - if constexpr (std::is_void_v) { - std::invoke(*callable, caller..., std::get(tuple)...); - return; - } else - return std::invoke(*callable, caller..., std::get(tuple)...); - }; - - return deserializeAndCall(parameters, std::index_sequence_for()); - }; -} - /// Like makeCppFunctionHandler for a callback that answers later: it returns the sender of the callback, which owns the decoded /// arguments and the calling UI (they live in its operation state). A callback that takes them by reference, a coroutine for instance, can thus /// use them until it completes, long after this handler returned. @@ -352,93 +331,6 @@ auto makeDeferredHandler(Function&& function) { }; } -// --- Callable signature inference for cppFunction(name, callable), without explicit --- - -// Primary template intentionally has no Return/DecayedArgs members: has_callable_traits below -// treats their absence as "inference unsupported", so unmatched T (generic lambdas, functors with -// an overloaded or templated operator(), non-callables) fail detection instead of a specialization. -template -struct callable_traits_impl { }; - -template -struct callable_traits_impl { - using Return = R; - using DecayedArgs = std::tuple...>; - using RawArgs = std::tuple; -}; -template -struct callable_traits_impl : callable_traits_impl { }; - -template -struct callable_traits_impl> { - using Return = R; - using DecayedArgs = std::tuple...>; - using RawArgs = std::tuple; -}; - -template -struct callable_traits_impl { - using Return = R; - using DecayedArgs = std::tuple...>; - using RawArgs = std::tuple; -}; -template -struct callable_traits_impl : callable_traits_impl { }; -template -struct callable_traits_impl : callable_traits_impl { }; -template -struct callable_traits_impl : callable_traits_impl { }; - -// A generic lambda or a functor with an overloaded operator() has no single &T::operator() (taking -// its address, or picking an overload, is ill-formed without explicit template arguments), so this -// correctly evaluates to false for exactly the callables that need explicit cppFunction. -template -struct has_call_operator : std::false_type { }; -template -struct has_call_operator> : std::true_type { }; - -// Function pointers and std::function have no operator() member, so their traits apply directly; -// lambdas/functors route through their (single, non-overloaded, non-template) operator() member. -template ::value> -struct callable_traits : callable_traits_impl { }; -template -struct callable_traits : callable_traits_impl { }; - -template -struct has_callable_traits_impl : std::false_type { }; -template -struct has_callable_traits_impl::Return, typename callable_traits::DecayedArgs>> : std::true_type { }; - -template -concept has_callable_traits = has_callable_traits_impl::value; - -/// Passes the calling UI, received as an lvalue, as the callable's declared first parameter type -/// Caller (UI, const UI&, UI& or UI&&), followed by the decoded parameters. -template -auto adaptCaller(Function&& function) { - return [function = std::forward(function)](auto& caller, auto&&... args) mutable -> decltype(auto) { - return std::invoke(function, static_cast(caller), std::forward(args)...); - }; -} - -/// True when a callable's first parameter is the application's UI: the calling browser is then -/// passed to it instead of being read from the call data. -template -struct takes_caller : std::false_type { }; -template -struct takes_caller : std::is_same, UI> { }; - -/// The deduced parameters to register: the decayed ones, except a caller UI, which keeps its declared -/// type so that adaptCaller can pass it as a mutable or rvalue reference. -template -struct caller_aware_args { - using type = DecayedArgs; -}; -template -struct caller_aware_args, std::tuple> { - using type = std::conditional_t, std::tuple, std::tuple>; -}; - // Bridges a deduced > pair back to the explicit-template cppFunction // overload, so the deduced and explicit registration paths share one dispatch/response implementation. template @@ -829,6 +721,8 @@ template class BasicWF { + template + friend struct detail::BridgeHost; template friend class BasicSpace; @@ -2955,3 +2849,5 @@ using EmbeddedWebFront = WebFrontWithFrontend; #include "DeveloperApp.hpp" // Spaces use the callable traits above; BasicWF only names BasicSpace. #include "Space.hpp" +// bridgeUI() and bridgeFunctions(), for the units that include only Bridge.hpp. +#include "BridgeHost.hpp" diff --git a/include/webfront/details/CppFunction.hpp b/include/webfront/details/CppFunction.hpp new file mode 100644 index 00000000..06b540bb --- /dev/null +++ b/include/webfront/details/CppFunction.hpp @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-05 +// +// WebFront — core +// Role: Signature deduction of a callback given to cppFunction, and the decoding of its arguments. +// Thread: worker-safe | Alloc: unrestricted +// LLM: internal; shared by WebFront.hpp and the light Bridge.hpp, keep it free of the server and the senders + +#pragma once + +#include "../BridgeError.hpp" +#include "../http/BuffersPolicy.hpp" +#include "../weblink/Messages.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::detail { + +/// Decodes Args from the call data and invokes the callable with them, preceded by 'caller' (the +/// calling UI, for callables that take it as their first parameter, or nothing). +template +auto makeCppFunctionHandler(Function&& function) { + using StoredFunction = std::decay_t; + auto callable = std::make_shared(std::forward(function)); + + return [callable = std::move(callable)](std::span data, auto&&... caller) -> R { + std::tuple parameters; + auto deserializeAndCall = [&](std::tuple& tuple, std::index_sequence) -> R { + // Arguments that cannot be decoded as the callback declared them reject with the `webfront.malformed` code. + try { + (msg::FunctionCall::decodeParameter(std::get(tuple), data), ...); + if (!data.empty()) + throw std::runtime_error("Function call contains trailing parameter data"); + } catch (const std::exception& error) { + throw detail::makeBridgeError(bridge_code::malformed, error.what()); + } + if constexpr (std::is_void_v) { + std::invoke(*callable, caller..., std::get(tuple)...); + return; + } else + return std::invoke(*callable, caller..., std::get(tuple)...); + }; + + return deserializeAndCall(parameters, std::index_sequence_for()); + }; +} + +// --- Callable signature inference for cppFunction(name, callable), without explicit --- + +// Primary template intentionally has no Return/DecayedArgs members: has_callable_traits below +// treats their absence as "inference unsupported", so unmatched T (generic lambdas, functors with +// an overloaded or templated operator(), non-callables) fail detection instead of a specialization. +template +struct callable_traits_impl { }; + +template +struct callable_traits_impl { + using Return = R; + using DecayedArgs = std::tuple...>; + using RawArgs = std::tuple; +}; +template +struct callable_traits_impl : callable_traits_impl { }; + +template +struct callable_traits_impl> { + using Return = R; + using DecayedArgs = std::tuple...>; + using RawArgs = std::tuple; +}; + +template +struct callable_traits_impl { + using Return = R; + using DecayedArgs = std::tuple...>; + using RawArgs = std::tuple; +}; +template +struct callable_traits_impl : callable_traits_impl { }; +template +struct callable_traits_impl : callable_traits_impl { }; +template +struct callable_traits_impl : callable_traits_impl { }; + +// A generic lambda or a functor with an overloaded operator() has no single &T::operator() (taking +// its address, or picking an overload, is ill-formed without explicit template arguments), so this +// correctly evaluates to false for exactly the callables that need explicit cppFunction. +template +struct has_call_operator : std::false_type { }; +template +struct has_call_operator> : std::true_type { }; + +// Function pointers and std::function have no operator() member, so their traits apply directly; +// lambdas/functors route through their (single, non-overloaded, non-template) operator() member. +template ::value> +struct callable_traits : callable_traits_impl { }; +template +struct callable_traits : callable_traits_impl { }; + +template +struct has_callable_traits_impl : std::false_type { }; +template +struct has_callable_traits_impl::Return, typename callable_traits::DecayedArgs>> : std::true_type { }; + +template +concept has_callable_traits = has_callable_traits_impl::value; + +/// Passes the calling UI, received as an lvalue, as the callable's declared first parameter type +/// Caller (UI, const UI&, UI& or UI&&), followed by the decoded parameters. +template +auto adaptCaller(Function&& function) { + return [function = std::forward(function)](auto& caller, auto&&... args) mutable -> decltype(auto) { + return std::invoke(function, static_cast(caller), std::forward(args)...); + }; +} + +/// True when a callable's first parameter is the application's UI: the calling browser is then +/// passed to it instead of being read from the call data. +template +struct takes_caller : std::false_type { }; +template +struct takes_caller : std::is_same, UI> { }; + +/// The deduced parameters to register: the decayed ones, except a caller UI, which keeps its declared +/// type so that adaptCaller can pass it as a mutable or rvalue reference. +template +struct caller_aware_args { + using type = DecayedArgs; +}; +template +struct caller_aware_args, std::tuple> { + using type = std::conditional_t, std::tuple, std::tuple>; +}; + +} // namespace webfront::detail diff --git a/include/webfront/details/TypescriptNames.hpp b/include/webfront/details/TypescriptNames.hpp new file mode 100644 index 00000000..16d6b6d9 --- /dev/null +++ b/include/webfront/details/TypescriptNames.hpp @@ -0,0 +1,281 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-05 +// +// WebFront — core +// Role: The TypeScript names and declarations of the types the bridge carries (wf bindings). +// Thread: worker-safe | Alloc: unrestricted +// LLM: internal; included by the light Bridge.hpp, keep it free of the server, the senders and the watches + +#pragma once + +#include "../weblink/Messages.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::inspect { + +/// False in a distribution build (WEBFRONT_DISTRIBUTION): nothing is recorded there, and no call is counted. +#if defined(WEBFRONT_DISTRIBUTION) && WEBFRONT_DISTRIBUTION +inline constexpr bool introspection = false; +#else +inline constexpr bool introspection = true; +#endif + +// --- TypeScript names ------------------------------------------------------------------------------------------ + +namespace detail { +template +struct typescript_tuple : std::false_type { }; + +template +[[nodiscard]] std::string typescriptName(); + +template +struct typescript_tuple> : std::true_type { + static std::string write() { + std::string text = "["; + static_cast(((text += (text.size() > 1 ? ", " : "") + typescriptName()), ...)); + return text + "]"; + } +}; +template +struct typescript_tuple> : typescript_tuple> { }; + +template +[[nodiscard]] constexpr std::string_view typedArrayName() noexcept { + using E = std::remove_cv_t; + if constexpr (std::is_same_v) + return "Float32Array"; + else if constexpr (std::is_same_v) + return "Float64Array"; + else if constexpr (sizeof(E) == 1) + return std::is_signed_v ? "Int8Array" : "Uint8Array"; + else if constexpr (sizeof(E) == 2) + return std::is_signed_v ? "Int16Array" : "Uint16Array"; + else if constexpr (sizeof(E) == 4) + return std::is_signed_v ? "Int32Array" : "Uint32Array"; + else + return std::is_signed_v ? "BigInt64Array" : "BigUint64Array"; +} + +/// `text` as a TypeScript string literal. +[[nodiscard]] inline std::string quoted(std::string_view text) { + std::string literal = "\""; + for (const char character : text) { + const auto byte = static_cast(character); + if (character == '"' || character == '\\') + literal += std::string{'\\', character}; + else if (byte < 0x20 || byte == 0x7f) + literal += std::format("\\x{:02x}", byte); + else + literal += character; + } + return literal + '"'; +} + +/// Set while the types of the page's declarations are written: they tell a std::bitset from a container of bytes. +inline thread_local bool namingBitsets = false; + +/// The members of a union, in parentheses when it is the element of an array. +[[nodiscard]] inline std::string parenthesized(std::string type) { + return type.find('|') == std::string::npos ? type : '(' + std::move(type) + ')'; +} + +template +struct typescript_variant : std::false_type { }; +template +struct typescript_variant> : std::true_type { + /// A discriminated union: `[0, A] | [1, B]`, the index of the alternative first. + static std::string write() { + std::string text; + std::size_t index = 0; + static_cast(((text += (index == 0 ? "" : " | ") + ("[" + std::to_string(index) + ", " + typescriptName() + "]"), ++index), ...)); + return text; + } +}; + +template +[[nodiscard]] std::string typescriptName() { + using U = std::remove_cvref_t; + if constexpr (std::is_void_v) + return "void"; + else if constexpr (std::is_same_v) + return "null"; + else if constexpr (std::is_same_v) + return "boolean"; + else if constexpr (std::is_arithmetic_v) + return "number"; + else if constexpr (std::is_convertible_v) + return "string"; + else if constexpr (msg::is_bitset_v) + return namingBitsets ? "WebFrontBitset" : "Uint8Array"; + else if constexpr (bridge::described) + return std::string{bridge::structName()}; + else if constexpr (msg::is_optional_v) + return typescriptName() + " | null"; + else if constexpr (typescript_variant::value) + return typescript_variant::write(); + else if constexpr (msg::is_expected_v) + return "[true, " + (std::is_void_v ? std::string{"null"} : typescriptName()) + "] | [false, " + + typescriptName() + "]"; + else if constexpr (typescript_tuple::value) + return typescript_tuple::write(); + else if constexpr (msg::container_adaptor) + return typescriptName(); + else if constexpr (msg::mdspan_like) + return "[" + std::string{typedArrayName()} + ", Uint32Array]"; + else if constexpr (msg::bridge_range) { + using Element = msg::bridge_range_element_t; + if constexpr (msg::is_numeric_array_element_v) + return std::string{typedArrayName()}; + else if constexpr (msg::is_pair_v) + // The entries of a map: the key is not constant for the page. + return "[" + typescriptName() + ", " + typescriptName() + "][]"; + else + return parenthesized(typescriptName()) + "[]"; + } else + return "unknown"; +} +} // namespace detail + +/// While alive, on this thread, a std::bitset is written `WebFrontBitset`: what wf bindings declares. +class BitsetNaming { +public: + BitsetNaming() noexcept : previous(detail::namingBitsets) { + detail::namingBitsets = true; + } + BitsetNaming(const BitsetNaming&) = delete; + BitsetNaming& operator=(const BitsetNaming&) = delete; + ~BitsetNaming() { + detail::namingBitsets = previous; + } + +private: + bool previous; +}; + +/** + * The TypeScript type that JavaScript gives or receives for the C++ type T on the bridge: `boolean`, `number`, `string`, + * the typed array of a container of numbers (`Uint8Array` for a `std::bitset`, packed), `[A, B]` for a tuple or a pair, + * `T[]` for a container of anything else (`[K, V][]` for a map), `T | null` for a `std::optional`, `[0, A] | [1, B]` for a + * `std::variant`, `[true, T] | [false, E]` for a `std::expected`, `void`, and `unknown` for a type the bridge does not carry. + */ +template +[[nodiscard]] std::string typescriptType() { + return detail::typescriptName(); +} + +/// The TypeScript declaration of one described structure, as a function that carries it needs it. +struct StructureDeclaration { + std::string name; + std::type_index type; + std::string text; // "/** bounds */\ntype Name = [...];\n", without `export` +}; + +namespace detail { +/// Appends the declarations of the described structures that T is or holds, each type once and after those it names. +template +void declareStructures(std::vector& declared) { + using U = std::remove_cvref_t; + if constexpr (bridge::described) { + const std::string name{bridge::structName()}; + const std::type_index type{typeid(U)}; + for (const auto& known : declared) + if (known.type == type) + return; + // Marked before its members, which may hold the structure again (a node and its children); written after them. + declared.push_back({name, type, {}}); + std::string fields, bounds; + bridge::forEachMember([&](const auto& member) { + using Value = std::remove_cvref_t().*(member.pointer))>; + declareStructures(declared); + fields += (fields.empty() ? "" : ", ") + std::string(member.name) + ": " + typescriptName(); + if constexpr (std::remove_cvref_t::bounded) + bounds += (bounds.empty() ? "" : "; ") + std::string(member.name) + ": " + std::format("{} to {}", member.min, member.max); + }); + std::erase_if(declared, [&](const auto& known) { + return known.type == type; + }); + declared.push_back({name, type, (bounds.empty() ? std::string{} : "/** " + bounds + " */\n") + "type " + name + " = [" + fields + "];\n"}); + } else if constexpr (msg::is_variant_v) { + [&](std::index_sequence) { + (declareStructures>(declared), ...); + }(std::make_index_sequence>{}); + } else if constexpr (msg::is_expected_v) { + if constexpr (!std::is_void_v) + declareStructures(declared); + declareStructures(declared); + } else if constexpr (requires { typename U::value_type; }) { + if constexpr (!std::same_as, U>) + declareStructures(declared); + } else if constexpr (requires { std::tuple_size::value; }) { + [&](std::index_sequence) { + (declareStructures>(declared), ...); + }(std::make_index_sequence>{}); + } +} + +/// Refuses two structures of different types under one name. +inline void requireDistinctNames(const std::vector& declared) { + std::map names; + for (const auto& structure : declared) + if (names.try_emplace(structure.name, structure.type).first->second != structure.type) + throw std::logic_error("Two described structures are named " + structure.name + ": give each its own name"); +} +} // namespace detail + +/** + * The TypeScript declarations of the described structures given and of those they hold: a labelled tuple each, since a + * structure crosses the bridge as the tuple of its fields. The bounds of numeric fields are written in the comment. + * Name every structure of a .d.ts file in one call, so that a shared one is declared once. + * + * // speed: 1 to 10 + * export type Settings = [speed: number, title: string]; + */ +template + requires(bridge::described && ...) +[[nodiscard]] std::string typescriptDeclaration() { + std::vector declared; + (detail::declareStructures(declared), ...); + detail::requireDistinctNames(declared); + std::string text; + for (const auto& structure : declared) { + // After the comment of the bounds, when there is one. + const auto line = structure.text.starts_with("/**") ? structure.text.find('\n') + 1 : 0; + text += structure.text.substr(0, line) + "export " + structure.text.substr(line); + } + return text; +} + +/// The signature of a function as a page declares it: `(a: number, b: string) => Promise`. A call from JavaScript +/// always returns a Promise, also for a function that returns nothing; a `streamed` one is read with cppStream, whose call +/// gives the iterable itself. +[[nodiscard]] inline std::string typescriptWholeSignature(const std::vector& parameters, std::string_view result, bool streamed = false) { + std::string text = "("; + for (std::size_t i = 0; i < parameters.size(); ++i) { + if (i != 0) + text += ", "; + // a, b, ... z, then a1, b1, ...: a name the declaration needs and the C++ signature does not give + text += static_cast('a' + i % 26); + if (i >= 26) + text += std::to_string(i / 26); + text += ": " + parameters[i]; + } + if (streamed) + return text + ") => AsyncIterable<" + std::string(result) + ">"; + return text + ") => Promise<" + std::string(result) + ">"; +} + +} // namespace webfront::inspect diff --git a/test/cmake/consumer/CMakeLists.txt b/test/cmake/consumer/CMakeLists.txt index 7dd57732..c857e5ae 100644 --- a/test/cmake/consumer/CMakeLists.txt +++ b/test/cmake/consumer/CMakeLists.txt @@ -13,7 +13,7 @@ if(CPM_MODULE) endif() add_subdirectory("${WEBFRONT_SOURCE_DIR}" webfront) -add_executable(consumer main.cpp) +add_executable(consumer main.cpp page.cpp) target_link_libraries(consumer PRIVATE WebFront::WebFront) webfront_use_native_window(consumer) if(EXPECT_NATIVE) diff --git a/test/cmake/consumer/main.cpp b/test/cmake/consumer/main.cpp index f0c3977a..73d5b08f 100644 --- a/test/cmake/consumer/main.cpp +++ b/test/cmake/consumer/main.cpp @@ -33,10 +33,14 @@ using ConsumerApp = webfront::WebFrontWithFrontend 1) { // never taken by the smoke test: it only proves that the library compiles and links ConsumerApp app; webfront::testing::JasmineTest tests{app}; + auto functions = webfront::bridgeFunctions(app); + registerConsumerPage(functions); app.show(); } return 0; diff --git a/test/cmake/consumer/page.cpp b/test/cmake/consumer/page.cpp new file mode 100644 index 00000000..1a7180a9 --- /dev/null +++ b/test/cmake/consumer/page.cpp @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-05 +// +// WebFront — tests/cmake +// Role: The second unit of the consumer project: C++ functions and JavaScript calls through webfront/Bridge.hpp alone. +// Thread: bridge-io | Alloc: unrestricted +// LLM: consumer fixture of the portability tier; never include WebFront.hpp here + +#include + +#include + +void registerConsumerPage(webfront::BridgeFunctions& functions) { + functions.cppFunction("greet", [](webfront::BridgeUI browser, const std::string& name) { + browser.jsFunction("print")("hello " + name); + return name.size(); + }); +} diff --git a/test/unit/BridgeLightPage.cpp b/test/unit/BridgeLightPage.cpp new file mode 100644 index 00000000..80639a70 --- /dev/null +++ b/test/unit/BridgeLightPage.cpp @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-05 +// +// WebFront — tests/unit +// Role: A unit that includes only Bridge.hpp: C++ functions called by the page and calls to JavaScript (ADR-029). +// Thread: bridge-io | Alloc: unrestricted +// LLM: the build of this unit is the test that Bridge.hpp stays light; shared with webtest + +#include "BridgeLightPage.hpp" + +#if defined(STDEXEC_ASSERT) || defined(STDEXEC_CONSTEXPR_CXX23) + #error "webfront/Bridge.hpp must not include stdexec" +#endif + +#include +#include +#include +#include + +namespace { +std::future askedName; // the server thread only +} // namespace + +bool registerLightPage(webfront::BridgeFunctions& functions) { + bool added = functions.cppFunction("light.add", [](int a, int b) { + return a + b; + }); + added &= functions.cppFunction("light.echo", [](const std::string& text) { + return "echo:" + text; + }); + added &= functions.cppFunction, std::vector>("light.doubles", [](std::vector values) { + for (auto& value : values) + value *= 2; + return values; + }); + added &= functions.cppFunction("light.fail", [](bool) -> bool { + throw webfront::BridgeError("light:refused", "the light function refused"); + }); + added &= functions.cppFunction("light.notify", [](webfront::BridgeUI browser, const std::string& text) { + browser.jsFunction("lightPrint")(text, browser.id()); + }); + added &= functions.cppFunction("light.ask", [](const webfront::BridgeUI& browser) { + askedName = browser.jsFunction("lightName")("who"); + }); + added &= functions.cppFunction("light.answer", []() -> std::string { + if (!askedName.valid()) + return "nothing asked"; + if (askedName.wait_for(std::chrono::seconds(0)) != std::future_status::ready) + return "pending"; + try { + return "answered:" + askedName.get(); + } catch (const webfront::BridgeError& error) { + return "failed:" + error.code(); + } + }); + added &= functions.cppFunction( + "light.local", + [] { + return std::string("local only"); + }, + webfront::callers::localView); + return added; +} diff --git a/test/unit/BridgeLightPage.hpp b/test/unit/BridgeLightPage.hpp new file mode 100644 index 00000000..0b2b7e33 --- /dev/null +++ b/test/unit/BridgeLightPage.hpp @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-05 +// +// WebFront — tests/unit +// Role: The second unit of the light header's tests: C++ functions registered by a unit that includes only Bridge.hpp. +// Thread: bridge-io | Alloc: unrestricted +// LLM: shared by the unit tests and webtest; never include WebFront.hpp here + +#pragma once + +#include + +/// Registers the `light.*` functions. A second registration reports false for each name. +bool registerLightPage(webfront::BridgeFunctions& functions); diff --git a/test/unit/BridgeLightTests.cpp b/test/unit/BridgeLightTests.cpp new file mode 100644 index 00000000..53c3368f --- /dev/null +++ b/test/unit/BridgeLightTests.cpp @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-05 +// +// WebFront — tests/unit +// Role: An application and a unit that includes only Bridge.hpp: registration, answers, calls to JavaScript. +// Thread: bridge-io | Alloc: unrestricted +// LLM: uses an injectable networking mock; the second unit is BridgeLightPage.cpp + +#include "BridgeLightPage.hpp" +#include "InjectableNetworking.hpp" +#include +#include +#include + +#include +#include +#include +#include +#include + +using namespace webfront::bdd; +using namespace webfront; + +namespace { + +using LightSocket = webfront::testing::InjectableSocket; + +struct LightNet : webfront::testing::InjectableNetworking { + static inline bool accepted{}; + static auto Accept(Acceptor&) { + return networking::ex::then(networking::ex::just(), []() -> LightSocket { + if (std::exchange(accepted, true)) + throw std::system_error(std::make_error_code(std::errc::operation_canceled)); + return LightSocket{}; + }); + } +}; + +using LightApp = BasicWF; + +struct LightBrowser { + struct Fresh { + Fresh() { + LightSocket::reset(); + LightNet::accepted = false; + } + } fresh; + LightApp app{WebFrontConfig{.port = "0"}}; + + void connect() { + const std::string upgrade = "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"; + LightSocket::receive(std::as_bytes(std::span(upgrade))); + msg::Handshake handshake; + LightSocket::receive( + webfront::testing::clientFrame(std::span(reinterpret_cast(handshake.header().data()), handshake.header().size()))); + } + template + static void send(msg::CallId callId, const Arguments&... arguments) { + Message message; + message.setCallId(callId); + websocket::Frame frame{std::span(reinterpret_cast(message.header().data()), message.header().size())}; + (message.encodeParameter(arguments, frame), ...); + message.setParametersCount(static_cast(sizeof...(arguments))); + frame.freeze(); + LightSocket::receive(webfront::testing::clientFrame(webfront::testing::messagePayload(frame))); + } + template + static void call(const std::string& name, msg::CallId callId, const Arguments&... arguments) { + send>(callId, name, arguments...); + } + ~LightBrowser() { + app.shutdown(); + LightSocket::reset(); + } +}; + +} // namespace + +const Scenario lightRegistration{"A unit that includes only Bridge.hpp registers the application's functions", {"bridge-light"}, [] { + LightBrowser browser; + auto functions = bridgeFunctions(browser.app); + require(registerLightPage(functions)); + require(!registerLightPage(functions)); + require(!browser.app.cppFunction("light.add", [] { })); + requireThrows([&] { + functions.cppFunction("webfront.inspector.x", [] { }); + }); + if constexpr (inspect::introspection) { + bool described = false; + for (const auto& function : browser.app.registeredFunctions()) + described |= function.name == "light.add" && function.signature == "(a: number, b: number) => Promise"; + require(described); + } + }}; + +const Scenario lightAnswers{"A function of the light unit answers with its value or its failure", {"bridge-light"}, [] { + LightBrowser browser; + auto functions = bridgeFunctions(browser.app); + require(registerLightPage(functions)); + browser.connect(); + LightBrowser::call("light.echo", 3, std::string("hello")); + require(LightSocket::wrote("echo:hello")); + LightBrowser::call("light.fail", 4, true); + require(LightSocket::wrote("light:refused")); + require(LightSocket::wrote("the light function refused")); + LightBrowser::call("light.echo", 5, 1.0); + require(LightSocket::wrote(std::string(bridge_code::malformed))); + LightBrowser::call("light.local", 6); + require(LightSocket::wrote(std::string(bridge_code::denied))); + require(!LightSocket::wrote("local only")); + }}; + +const Scenario lightCalls{"The light unit calls JavaScript and reads its answer", {"bridge-light"}, [] { + LightBrowser browser; + auto functions = bridgeFunctions(browser.app); + require(registerLightPage(functions)); + browser.connect(); + LightBrowser::call("light.notify", 0, std::string("printed text")); + require(LightSocket::wrote("lightPrint")); + require(LightSocket::wrote("printed text")); + LightBrowser::call("light.ask", 0); + require(LightSocket::wrote("lightName")); + LightBrowser::call("light.answer", 7); + require(LightSocket::wrote("pending")); + when("the browser returns the result of the first typed call", [&] { + LightBrowser::send>(1, std::string("Ada")); + LightBrowser::call("light.answer", 8); + then("the future of the light unit holds it", [&] { + require(LightSocket::wrote("answered:Ada")); + }); + }); + }}; + +const Scenario lightGone{"A typed call of the light unit fails as disconnected when the browser leaves", {"bridge-light"}, [] { + LightBrowser browser; + std::optional page; + browser.app.onUIStarted([&](LightApp::UI ui) { + page.emplace(bridgeUI(ui)); + }); + browser.connect(); + require(page.has_value()); + auto pending = page->jsFunction("never").timeout(std::chrono::milliseconds::zero())(); + LightSocket::fail(std::make_error_code(std::errc::connection_reset)); + const auto code = [](std::future& result) { + try { + static_cast(result.get()); + } catch (const BridgeError& error) { + return error.code(); + } + return std::string{}; + }; + require(code(pending) == bridge_code::disconnected); + auto after = page->jsFunction("never")(); + require(code(after) == bridge_code::disconnected); + page->jsFunction("dropped")(1); + require(!LightSocket::wrote("dropped")); + }}; diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 6a7d80f7..aa177cc4 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -81,7 +81,7 @@ list(APPEND TESTS_LIST FormsTests.cpp ReactStoreTests.cpp DomDocumentTests.cpp D list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp DownloadsTests.cpp StorageTests.cpp NativeStorageTests.cpp PtyTests.cpp) list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp ProfileLeaseTests.cpp SafePathTests.cpp UISubscribersTests.cpp) list(APPEND TESTS_LIST ReadBindingTests.cpp ViewAssociationTests.cpp WatchTests.cpp WatchTreeTests.cpp WatchContainersTests.cpp WatchPassTests.cpp WatchWriteTests.cpp IntrospectionTests.cpp BridgeStateTests.cpp BroadcastTests.cpp SpaceTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) -list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationDiscoveryTests.cpp AutomationMcpHttpTests.cpp AutomationStateTests.cpp JasmineConsumerTests.cpp HostTests.cpp LifeTests.cpp HostLoopTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp DeferredCallTests.cpp) +list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationDiscoveryTests.cpp AutomationMcpHttpTests.cpp AutomationStateTests.cpp JasmineConsumerTests.cpp HostTests.cpp LifeTests.cpp HostLoopTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp DeferredCallTests.cpp BridgeLightTests.cpp BridgeLightPage.cpp) list(APPEND TESTS_LIST Main.cpp ScenarioIsolation.cpp FrontendUrlTests.cpp ApplicationUrlTests.cpp FrontendContractTests.cpp UIExecutorTests.cpp NativeWindowTests.cpp WindowRegistryTests.cpp CommandsTests.cpp EmbeddedCoreAssetsTests.cpp) if(WEBFRONT_USE_MDDLOG) list(APPEND TESTS_LIST MddlogLoggerTests.cpp MddlogTransportTests.cpp) @@ -119,7 +119,7 @@ target_compile_definitions(tests PRIVATE WEBFRONT_PTY_PROBE="$cppFunction("deepEcho", [](const vector::type>& value) { return value; }); diff --git a/test/web/suite/specs/light-bridge-specs.mjs b/test/web/suite/specs/light-bridge-specs.mjs new file mode 100644 index 00000000..4fd1f68e --- /dev/null +++ b/test/web/suite/specs/light-bridge-specs.mjs @@ -0,0 +1,33 @@ +// The C++ functions registered by a unit that includes only webfront/Bridge.hpp (test/unit/BridgeLightPage.cpp). +const call = name => webFront.cppFunction(name); + +describe('Functions of a unit that includes only Bridge.hpp', () => { + it('answer with numbers, texts and typed arrays', async () => { + expect(await call('light.add')(2, 3)).toBe(5); + expect(await call('light.echo')('hello')).toBe('echo:hello'); + const doubled = await call('light.doubles')(new Float64Array([1.5, -2])); + expect(Array.from(doubled)).toEqual([3, -4]); + }); + it('reject with the code of their failure, and with webfront.malformed for arguments they did not declare', async () => { + await expectAsync(call('light.fail')(true)).toBeRejectedWith(jasmine.objectContaining({code: 'light:refused'})); + await expectAsync(call('light.echo')(1)).toBeRejectedWith(jasmine.objectContaining({code: 'webfront.malformed'})); + }); + it('call JavaScript, with and without a result', async () => { + let printed; + globalThis.lightPrint = text => { printed = text; }; + globalThis.lightName = question => `${question}:Ada`; + try { + await call('light.notify')('printed text'); + await call('light.ask')(); + const deadline = performance.now() + 5000; + let answer = await call('light.answer')(); + while (answer === 'pending' && performance.now() < deadline) + answer = await call('light.answer')(); + expect(answer).toBe('answered:who:Ada'); + expect(printed).toBe('printed text'); + } finally { + delete globalThis.lightPrint; + delete globalThis.lightName; + } + }); +}); diff --git a/test/web/suite/specs/webfront-specs.mjs b/test/web/suite/specs/webfront-specs.mjs index 8a1c723c..02c4b6f4 100644 --- a/test/web/suite/specs/webfront-specs.mjs +++ b/test/web/suite/specs/webfront-specs.mjs @@ -12,6 +12,7 @@ import './dom-specs.mjs'; import './spaces-specs.mjs'; import './inspector-specs.mjs'; import './bridge-state-specs.mjs'; +import './light-bridge-specs.mjs'; import { importedValue } from './module-fixture.mjs'; import './async-diagnostics.js'; From 2a09274d46613bb611358e745f9a6b8640b421a4 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:16:45 +0100 Subject: [PATCH 2/5] Copy the encoder's buffers once the light bridge has encoded the whole message (#766) --- include/webfront/Bridge.hpp | 47 +++++++++++++++++----------------- test/unit/BridgeLightTests.cpp | 14 ++++++++++ 2 files changed, 38 insertions(+), 23 deletions(-) diff --git a/include/webfront/Bridge.hpp b/include/webfront/Bridge.hpp index 13995c2b..c8703582 100644 --- a/include/webfront/Bridge.hpp +++ b/include/webfront/Bridge.hpp @@ -19,7 +19,6 @@ #include #include -#include #include #include #include @@ -66,19 +65,21 @@ class BridgeTarget { [[nodiscard]] virtual std::string spacePath() const = 0; }; -/// The bytes of a bridge message being encoded: what the encoder appends, copied behind the room left for the header. -template +/// A bridge message being encoded. As with a websocket frame, the encoder lends its buffers, some before it has written +/// them: finish() copies them, while the encoding object and the encoded values still live. struct MessageBytes { - std::vector bytes = std::vector(sizeof(Header)); + std::vector> buffers; void addBuffer(std::span buffer) { - bytes.insert(bytes.end(), buffer.begin(), buffer.end()); + buffers.push_back(buffer); } - /// Writes the header, complete once everything is encoded, and gives the message. + /// The whole message, header first. template - [[nodiscard]] std::vector finish(const Message& message) && { - std::memcpy(bytes.data(), message.header().data(), sizeof(Header)); - return std::move(bytes); + [[nodiscard]] std::vector finish(const Message& message) const { + std::vector bytes(message.header().begin(), message.header().end()); + for (const auto buffer : buffers) + bytes.insert(bytes.end(), buffer.begin(), buffer.end()); + return bytes; } }; @@ -188,12 +189,12 @@ class BasicBridgeJsFunction { } auto operator()(auto&&... arguments) const { - msg::FunctionCall command; - detail::MessageBytes> frame; + msg::FunctionCall command; + detail::MessageBytes frame; command.encodeParameter(name, frame); (command.encodeParameter(std::forward(arguments), frame), ...); command.setParametersCount(static_cast(1 + sizeof...(arguments))); - auto message = std::move(frame).finish(command); + auto message = frame.finish(command); if constexpr (ignored) target->send(name, message); @@ -324,26 +325,26 @@ class BasicBridgeFunctions { static void bind(detail::BridgeRegistration& registration, Function&& function, std::bool_constant) { auto decoded = detail::makeCppFunctionHandler...>(std::forward(function)); registration.invoke = [decoded = std::move(decoded)](std::span data, std::shared_ptr caller) mutable { - using Header = msg::FunctionCallHeader; // A failure may come from the callback or from encoding its value, which can leave a message partly encoded: // a failure is sent in a fresh one. try { - msg::FunctionReturn result; - detail::MessageBytes
frame; - const auto call = [&]() -> R { + msg::FunctionReturn result; + detail::MessageBytes frame; + const auto call = [&]() -> R { if constexpr (Caller) { UI browser{std::move(caller)}; return decoded(data, browser); } else return decoded(data); }; - if constexpr (std::is_void_v) + if constexpr (std::is_void_v) { call(); - else { - auto value = call(); + return detail::BridgeAnswer{frame.finish(result), std::nullopt}; + } else { + auto value = call(); // lives until finish(): the frame borrows from it result.encodeParameter(value, frame); + return detail::BridgeAnswer{frame.finish(result), std::nullopt}; } - return detail::BridgeAnswer{std::move(frame).finish(result), std::nullopt}; } catch (const std::exception& error) { return failureOf(error); } catch (...) { @@ -353,10 +354,10 @@ class BasicBridgeFunctions { } static detail::BridgeAnswer failureOf(const std::exception& error) { - msg::FunctionReturn result; - detail::MessageBytes> frame; + msg::FunctionReturn result; + detail::MessageBytes frame; result.encodeParameter(error, frame); - return {std::move(frame).finish(result), std::string(error.what())}; + return {frame.finish(result), std::string(error.what())}; } }; diff --git a/test/unit/BridgeLightTests.cpp b/test/unit/BridgeLightTests.cpp index 53c3368f..2a35952d 100644 --- a/test/unit/BridgeLightTests.cpp +++ b/test/unit/BridgeLightTests.cpp @@ -100,6 +100,20 @@ const Scenario lightAnswers{"A function of the light unit answers with its value auto functions = bridgeFunctions(browser.app); require(registerLightPage(functions)); browser.connect(); + // The whole payload, number included: the encoder lends some buffers before it writes them. + const auto encoded = [](const auto& value) { + msg::FunctionReturn<> message; + websocket::Frame frame{ + std::span(reinterpret_cast(message.header().data()), message.header().size())}; + message.encodeParameter(value, frame); + frame.freeze(); + const auto payload = webfront::testing::messagePayload(frame); + return std::string(reinterpret_cast(payload.data()) + 12, payload.size() - 12); + }; + LightBrowser::call("light.add", 2, 2.0, 40.0); + require(LightSocket::wrote(encoded(42))); + LightBrowser::call("light.doubles", 9, std::vector{1.5, -2.0}); + require(LightSocket::wrote(encoded(std::vector{3.0, -4.0}))); LightBrowser::call("light.echo", 3, std::string("hello")); require(LightSocket::wrote("echo:hello")); LightBrowser::call("light.fail", 4, true); From ee8b1c91da3e6f82fe05779f1a67332d22857eec Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:25:13 +0100 Subject: [PATCH 3/5] Record the cost of a unit that includes Bridge.hpp and document how to use it (#766) --- AGENTS.md | 2 +- README.md | 14 ++++++++++++++ docs/BUILD_TIME_STUDY.md | 42 ++++++++++++++++++++++++++++++++-------- 3 files changed, 49 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 803739b4..0df64048 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ The README introduces WebFront through the Game of Life walkthrough, demonstrati ## Repository map -- `include/webfront/`: public header-only library, included as ``. `WebFront.hpp` is the main orchestration API; `Commands.hpp` adds an application's C++ commands to the developer environment's terminal. +- `include/webfront/`: public header-only library, included as ``. `WebFront.hpp` is the main orchestration API; `Bridge.hpp` is the light header of the units that only use the bridge (ADR-029: never include the server, the networking or stdexec from it; `BridgeHost.hpp` stays equivalent to `JsFunction` and to `cppFunction`'s registration); `Commands.hpp` adds an application's C++ commands to the developer environment's terminal. - `include/webfront/components/react/`: optional C++ snapshot stores coalesced per browser; the React adapter is installed separately with `wf` and documented in `docs/REACT.md`. - `include/webfront/components/forms/`: optional type descriptors (C++23), forms, inspectors and TypeScript declarations generated from them, and an optional C++26 reflection layer (`Reflection.hpp`, GCC 16 only) documented in `docs/FORMS.md`. - `include/webfront/http/`: HTTP and WebSocket protocol implementation. diff --git a/README.md b/README.md index be54c8f6..3ffbcdda 100644 --- a/README.md +++ b/README.md @@ -464,6 +464,20 @@ target_link_libraries(MyApp PRIVATE WebFront::WebFront) As a subproject, examples and tests are off by default and compiler settings do not leak into your targets. `WEBFRONT_BUILD_EXAMPLES=OFF` disables examples in a standalone build too. +`WebFront.hpp` is slow to compile. A unit that only registers C++ functions or calls JavaScript can include the light `webfront/Bridge.hpp` instead, and receives `webfront::bridgeFunctions(app)` or `webfront::bridgeUI(ui)` from the unit that creates the application ([ADR-029](docs/adr/ADR-029-en-tete-leger-du-bridge.md), [measurements](docs/BUILD_TIME_STUDY.md)): + +```cpp +#include + +void registerFunctions(webfront::BridgeFunctions& functions) { + functions.cppFunction("greet", [](webfront::BridgeUI browser, const std::string& name) { + browser.jsFunction("print")("hello " + name); + }); +} +``` + +Its callbacks answer at once: register senders, coroutines and streams on the application. +
GCC 16 and C++ module scanning diff --git a/docs/BUILD_TIME_STUDY.md b/docs/BUILD_TIME_STUDY.md index e426b46f..553df758 100644 --- a/docs/BUILD_TIME_STUDY.md +++ b/docs/BUILD_TIME_STUDY.md @@ -76,14 +76,40 @@ The rows overlap: they cannot be added. - **``** was included by `HTTPServer.hpp` and used nowhere. The include is removed; the effect on `HelloWorld.cpp` is within the noise (32.9 s and 33.5 s). - **The development components** (inspectors, introspection) do not change the cost measurably in a minimal application. -- **A lighter header** is not delivered. A second unit under 5 s would have to avoid `WebLink.hpp` (5.1 s for the front end - alone), which `UI`, `cppFunction` and `jsFunction` are templates over: it needs a type-erased boundary between an - application unit and the units that use it, a change of the public design rather than of the includes. -- **`import webfront;`** (a module whose global module fragment includes `WebFront.hpp`) is not adopted: GCC 16.1 stops - with an internal compiler error (segmentation fault, `stdexec/__detail/__query.hpp`). Clang and MSVC were not tried; a - module is not worth offering until the three compilers of the CI build it. - -No MSVC figure was taken for this study: the target of 30 % less on `HelloWorld.cpp` with MSVC remains open. +- **A lighter header** is delivered: `webfront/Bridge.hpp`, below. +- **`import webfront;`** (a module whose global module fragment includes `WebFront.hpp`) is not adopted. Tried again with + the light header: GCC 16.1 still ends with an internal compiler error (`stdexec/__detail/__query.hpp`), and Clang 22 + precompiles a module whose import then fails to compile in stdexec (`no matching function for call` from + `__detail/__storage.hpp`). MSVC was not tried. + +## The light header (#766, ADR-029) + +A unit that only registers C++ functions or calls JavaScript includes `webfront/Bridge.hpp` and takes a +`webfront::BridgeFunctions` or a `webfront::BridgeUI`; the unit that includes `WebFront.hpp` makes them with +`webfront::bridgeFunctions(app)` and `webfront::bridgeUI(ui)`. + +Same machine, GCC 16.1, medians of three runs, no compiler cache, while the machine had some other load (average 4 to 12 +on 24 threads). + +| What is compiled | `-O3 -DNDEBUG` | `-O0` | Peak memory (`-O3`) | +| --- | --- | --- | --- | +| A second unit that calls `ui.jsFunction`, with `WebFront.hpp` | 17.8 s | 11.8 s | 1.1 GB | +| The same with `Bridge.hpp` | 2.3 s | 1.9 s | 0.33 GB | +| `test/unit/BridgeLightPage.cpp`: eight functions, two JavaScript calls | 5.4 s | 3.2 s | 0.42 GB | +| `Bridge.hpp` alone, `-fsyntax-only` | 1.8 s | | 0.29 GB | +| `HelloWorld.cpp` before the change | 35.6 s | | 1.4 GB | +| `HelloWorld.cpp` after the change | 32.8 s | | 1.4 GB | + +- The target of a secondary application unit under 5 s with GCC is met for a unit that calls JavaScript. A unit pays for + each signature it instantiates: eight registrations are at 5.4 s with optimisation. +- **`HelloWorld.cpp` does not get cheaper**: the difference above is within the noise. It instantiates the application, + which `Bridge.hpp` does not touch. The target of 30 % less on `HelloWorld.cpp` is **not met**, and no MSVC figure was + taken (no MSVC on the machine that made these measurements). +- Clang 22 `-ftime-trace` on `HelloWorld.cpp` (38 s): 17.5 s front end and 20.4 s back end. The largest instantiations, + which overlap, are `webfront::BasicWF` (12.5 s) and `webfront::http::Server` (8.5 s), then the senders of stdexec. + Reducing it means instantiating less of the server and the application, or compiling them once, which a header-only + core does not do (ADR-001). +- `` is no longer included anywhere under `include/`: nothing is left to rewrite by hand. ## Run time From ba4bd51354f8e54c31e5f0dadb7c4e2d0f907339 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:43:44 +0100 Subject: [PATCH 4/5] Fix the MSVC warnings of the light bridge header (#766) --- include/webfront/Bridge.hpp | 5 +++-- include/webfront/BridgeHost.hpp | 4 ++-- test/unit/BridgeLightPage.cpp | 6 ++++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/include/webfront/Bridge.hpp b/include/webfront/Bridge.hpp index c8703582..0cde2f90 100644 --- a/include/webfront/Bridge.hpp +++ b/include/webfront/Bridge.hpp @@ -308,7 +308,7 @@ class BasicBridgeFunctions { } template - static void describe(detail::BridgeRegistration& registration) { + static void describe([[maybe_unused]] detail::BridgeRegistration& registration) { // unused in a distribution build if constexpr (inspect::introspection) { registration.parameters = {inspect::typescriptType()...}; registration.result = inspect::typescriptType(); @@ -324,7 +324,8 @@ class BasicBridgeFunctions { template static void bind(detail::BridgeRegistration& registration, Function&& function, std::bool_constant) { auto decoded = detail::makeCppFunctionHandler...>(std::forward(function)); - registration.invoke = [decoded = std::move(decoded)](std::span data, std::shared_ptr caller) mutable { + registration.invoke = [decoded = std::move(decoded)](std::span data, + [[maybe_unused]] std::shared_ptr caller) mutable { // A failure may come from the callback or from encoding its value, which can leave a message partly encoded: // a failure is sent in a fresh one. try { diff --git a/include/webfront/BridgeHost.hpp b/include/webfront/BridgeHost.hpp index d8658b43..c0d77dd3 100644 --- a/include/webfront/BridgeHost.hpp +++ b/include/webfront/BridgeHost.hpp @@ -113,7 +113,7 @@ struct BridgeHost { explicit Registrar(App& application) : app(application) { } bool add(BridgeRegistration registration) override { - using UI = typename App::UI; + using Browser = typename App::UI; // not "UI": MSVC C4459, webfront::UI App::refuseReservedName(registration.name); if (app.cppFunctions.contains(registration.name)) return false; @@ -134,7 +134,7 @@ struct BridgeHost { [invoke = std::move(registration.invoke), record, application = &app](std::span data, WebLink& connection, msg::CallId callId, - UI caller) mutable { + Browser caller) mutable { const inspect::CallMeasure measure{record.get()}; // the handler owns the record while it runs auto answer = invoke(data, std::make_shared(*application, caller.id(), caller.generation)); if (answer.failure) diff --git a/test/unit/BridgeLightPage.cpp b/test/unit/BridgeLightPage.cpp index 80639a70..4d72a264 100644 --- a/test/unit/BridgeLightPage.cpp +++ b/test/unit/BridgeLightPage.cpp @@ -34,8 +34,10 @@ bool registerLightPage(webfront::BridgeFunctions& functions) { value *= 2; return values; }); - added &= functions.cppFunction("light.fail", [](bool) -> bool { - throw webfront::BridgeError("light:refused", "the light function refused"); + added &= functions.cppFunction("light.fail", [](bool refuse) -> bool { + if (refuse) // MSVC C4702: a callback that always throws leaves the encoding of its value unreachable + throw webfront::BridgeError("light:refused", "the light function refused"); + return refuse; }); added &= functions.cppFunction("light.notify", [](webfront::BridgeUI browser, const std::string& text) { browser.jsFunction("lightPrint")(text, browser.id()); From 1223ed438af853df3a3bc35d514d0e7139bc04cd Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:40:29 +0100 Subject: [PATCH 5/5] Link the light bridge page into the HTTPS browser tests --- test/web/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index 477bb6a4..522dfa9e 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -312,7 +312,7 @@ if(_browser_tests_available) file(STRINGS "${_tls_fixture}/spki.txt" _tls_spki LIMIT_COUNT 1) webfront_add_test_program(webtest_tls JasmineTest.cpp WITH_WEBTEST DEFINITIONS WEBFRONT_TEST_TLS_FIXTURE="${_tls_fixture}" WEBFRONT_TEST_MEDIA_FILE="${CMAKE_CURRENT_SOURCE_DIR}/fixtures/media/seek.webm") - target_sources(webtest_tls PRIVATE RestartableServer.cpp) + target_sources(webtest_tls PRIVATE RestartableServer.cpp ../unit/BridgeLightPage.cpp) target_link_libraries(webtest_tls PRIVATE WebFront_boing) endif() else()