diff --git a/CMakeLists.txt b/CMakeLists.txt index 301e2c5..39e05e1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -180,6 +180,22 @@ if(BUILD_TESTING) LABELS "tools;windows;rc" TIMEOUT 30) endif() + # Synthetic checked provider peers exercise loading and ownership without + # a browser engine or signed-in desktop. Never packaged into the SDK. + add_library(nil_webview_fixture_good SHARED tests/webview_provider_fixture.cpp) + add_library(nil_webview_fixture_bad SHARED tests/webview_provider_fixture.cpp) + target_compile_definitions(nil_webview_fixture_bad PRIVATE NILWV_FIXTURE_BAD_ABI=1) + foreach(fixture IN ITEMS nil_webview_fixture_good nil_webview_fixture_bad) + target_compile_features(${fixture} PRIVATE cxx_std_17) + endforeach() + add_executable(nil_webview_runtime_tests tests/webview_runtime_tests.cpp) + target_link_libraries(nil_webview_runtime_tests PRIVATE nilruntime nil_webview_fixture_good Threads::Threads) + target_include_directories(nil_webview_runtime_tests PRIVATE nilcompiler/src) + add_dependencies(nil_webview_runtime_tests nil_webview_fixture_bad) + add_test(NAME nil.webview-runtime COMMAND $ + $ $) + set_tests_properties(nil.webview-runtime PROPERTIES TIMEOUT 20) + add_executable(nil_rooted_file_snapshot_tests tests/rooted_file_snapshot_tests.cpp) target_link_libraries(nil_rooted_file_snapshot_tests PRIVATE nilruntime) target_include_directories(nil_rooted_file_snapshot_tests PRIVATE nilcompiler/src) @@ -838,6 +854,11 @@ if(BUILD_TESTING) --lifecycle-test $ --llvm "${NIL_ENABLE_LLVM}" ${NIL_UI_DISPLAY_APPKIT_ARGS}) set_tests_properties(nil.ui-display PROPERTIES LABELS "ui;routes" SKIP_RETURN_CODE 77 TIMEOUT "${NIL_UI_DISPLAY_TIMEOUT}") + add_test(NAME nil.webview-intrinsic-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/webview_intrinsic_contract.py" + --compiler $ --interpreter $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.webview-intrinsic-contract PROPERTIES LABELS "webview;routes" TIMEOUT 180) add_test(NAME nil.ui-intrinsic-contract COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/ui_intrinsic_contract.py" --compiler $ --interpreter $ diff --git a/common/webview_json_v1.hpp b/common/webview_json_v1.hpp new file mode 100644 index 0000000..b57a68c --- /dev/null +++ b/common/webview_json_v1.hpp @@ -0,0 +1,127 @@ +// Copyright (C) 2026 Execute Software. SPDX-License-Identifier: MIT +#pragma once +#include +#include +#include + +// WebView v1 JSON text grammar. This validates without decoding or normalizing +// JSON.stringify output, including escaped lone UTF-16 surrogates. A configuration +// parser with duplicate-key/scalar restrictions is not interchangeable with it. +// The provider and framework carry identical copies of this versioned grammar. +namespace nilwebview::json_v1 { +namespace detail { +class Parser { +public: + explicit Parser(const std::string &source) : source_(source) {} + bool parse() noexcept { whitespace(); return value(0) && (whitespace(), offset_ == source_.size()); } +private: + void whitespace() noexcept { + while (offset_ < source_.size() && (source_[offset_] == ' ' || source_[offset_] == '\t' || + source_[offset_] == '\r' || source_[offset_] == '\n')) ++offset_; + } + bool take(char expected) noexcept { + if (offset_ == source_.size() || source_[offset_] != expected) return false; + ++offset_; return true; + } + bool literal(const char *text) noexcept { + const auto size = std::strlen(text); + if (source_.compare(offset_, size, text) != 0) return false; + offset_ += size; return true; + } + bool string() noexcept { + if (!take('"')) return false; + while (offset_ < source_.size()) { + const auto c = static_cast(source_[offset_++]); + if (c == '"') return true; + if (c < 0x20) return false; + if (c != '\\') continue; + if (offset_ == source_.size()) return false; + const auto escape = source_[offset_++]; + if (escape == 'u') { + for (int index = 0; index < 4; ++index) { + if (offset_ == source_.size()) return false; + const auto digit = source_[offset_++]; + if (!((digit >= '0' && digit <= '9') || (digit >= 'a' && digit <= 'f') || + (digit >= 'A' && digit <= 'F'))) return false; + } + } else if (!std::strchr("\"\\/bfnrt", escape)) return false; + } + return false; + } + bool number() noexcept { + take('-'); + if (!take('0')) { + if (offset_ == source_.size() || source_[offset_] < '1' || source_[offset_] > '9') return false; + do { ++offset_; } while (offset_ < source_.size() && source_[offset_] >= '0' && source_[offset_] <= '9'); + } + if (take('.')) { + const auto first = offset_; + while (offset_ < source_.size() && source_[offset_] >= '0' && source_[offset_] <= '9') ++offset_; + if (offset_ == first) return false; + } + if (take('e') || take('E')) { + if (!take('+')) take('-'); + const auto first = offset_; + while (offset_ < source_.size() && source_[offset_] >= '0' && source_[offset_] <= '9') ++offset_; + if (offset_ == first) return false; + } + return true; + } + bool value(unsigned depth) noexcept { + if (depth > 64 || offset_ == source_.size()) return false; + switch (source_[offset_]) { + case '"': return string(); + case 't': return literal("true"); + case 'f': return literal("false"); + case 'n': return literal("null"); + case '[': { + ++offset_; whitespace(); + if (take(']')) return true; + do { whitespace(); if (!value(depth + 1)) return false; whitespace(); } while (take(',')); + return take(']'); + } + case '{': { + ++offset_; whitespace(); + if (take('}')) return true; + do { + whitespace(); if (!string()) return false; + whitespace(); if (!take(':')) return false; + whitespace(); if (!value(depth + 1)) return false; + whitespace(); + } while (take(',')); + return take('}'); + } + default: return number(); + } + } + const std::string &source_; + std::size_t offset_ = 0; +}; +} // namespace detail + +inline bool valid_utf8(const std::string &text) noexcept { + for (std::size_t index = 0; index < text.size();) { + const auto first = static_cast(text[index++]); + if (!first) return false; + if (first < 0x80) continue; + unsigned count = 0; + std::uint32_t code = 0, minimum = 0; + if (first >= 0xc2 && first <= 0xdf) { count = 1; code = first & 0x1f; minimum = 0x80; } + else if (first >= 0xe0 && first <= 0xef) { count = 2; code = first & 0x0f; minimum = 0x800; } + else if (first >= 0xf0 && first <= 0xf4) { count = 3; code = first & 7; minimum = 0x10000; } + else return false; + if (text.size() - index < count) return false; + while (count--) { + const auto byte = static_cast(text[index++]); + if ((byte & 0xc0) != 0x80) return false; + code = (code << 6) | (byte & 0x3f); + } + if (code < minimum || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return false; + } + return true; +} + +inline bool valid_json(const std::string &text) noexcept { + return text.size() <= 1048576 && valid_utf8(text) && detail::Parser(text).parse(); +} +} // namespace nilwebview::json_v1 diff --git a/common/webview_provider_v1.h b/common/webview_provider_v1.h new file mode 100644 index 0000000..216964e --- /dev/null +++ b/common/webview_provider_v1.h @@ -0,0 +1,191 @@ +/* Checked WebView provider ABI, version 1. + * Copyright (C) 2026 Execute Software. SPDX-License-Identifier: MIT + */ +#ifndef NILWEBVIEW_PROVIDER_V1_H +#define NILWEBVIEW_PROVIDER_V1_H +#include + +#if defined(_WIN32) +#define NILWV_CALL __cdecl +#else +#define NILWV_CALL +#endif +#if defined(_WIN32) && defined(NILWEBVIEW_PROVIDER_BUILD) +#define NILWV_EXPORT __declspec(dllexport) +#elif defined(__GNUC__) && defined(NILWEBVIEW_PROVIDER_BUILD) +#define NILWV_EXPORT __attribute__((visibility("default"))) +#else +#define NILWV_EXPORT +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define NILWV_ABI_V1 UINT32_C(1) +#define NILWV_MAX_TEXT_BYTES UINT64_C(1048576) +#define NILWV_MAX_QUEUED_BYTES UINT64_C(8388608) +#define NILWV_MAX_EVENTS UINT32_C(256) +#define NILWV_MAX_WINDOWS UINT32_C(16) +#define NILWV_OPERATION_TIMEOUT_MS UINT32_C(30000) + +/* Capability bits describe native sender metadata, never page assertions. + * A valid GTK6 provider may advertise zero. These bits do not prove that a + * display or browser runtime can initialize, or apply to every URL scheme. */ +#define NILWV_CAP_MESSAGE_URL UINT64_C(1) +#define NILWV_CAP_MESSAGE_ORIGIN UINT64_C(2) +#define NILWV_CAP_MESSAGE_FRAME UINT64_C(4) +#define NILWV_CAP_KNOWN_MASK UINT64_C(7) + +typedef struct nilwv_context_v1 nilwv_context_v1; +typedef struct nilwv_text_v1 { + const char *data; + uint64_t size; +} nilwv_text_v1; + +/* Fields are fixed-width; C enums below name values but never cross the ABI. + * UTF-8 is validated, with no embedded NUL. {NULL,0} is the empty string. + * Inputs are borrowed for the call; asynchronous operations copy them. + * Every returned text view is provider-owned until the next call using this + * context, or context destruction. The framework must copy it immediately. + * Error text uses the same rule; probe/create errors survive the next call + * on their owner thread. No allocator or C++ type crosses this boundary. */ +typedef struct nilwv_result_v1 { + uint32_t size; /* caller initializes to sizeof(result) */ + int32_t code; /* 0 success; negative error code */ + int64_t number; /* numeric result; zero when unused */ + nilwv_text_v1 text; /* text result, or diagnostic if code < 0 */ +} nilwv_result_v1; + +enum nilwv_error_code_v1 { + NILWV_E_UNAVAILABLE = -1, + NILWV_E_ARGUMENT = -2, + NILWV_E_HANDLE = -3, + NILWV_E_THREAD = -4, + NILWV_E_NOT_READY = -5, + NILWV_E_BUSY = -6, + NILWV_E_LIMIT = -7, + NILWV_E_NATIVE = -8, + NILWV_E_TIMEOUT = -9, + NILWV_E_PROTOCOL = -10, + NILWV_E_QUEUE_OVERFLOW = -11 +}; + +enum nilwv_event_kind_v1 { + NILWV_EVENT_READY = 1, + NILWV_EVENT_INITIALIZATION_FAILED = 2, + NILWV_EVENT_NAVIGATION_COMPLETED = 3, + NILWV_EVENT_NAVIGATION_FAILED = 4, + NILWV_EVENT_SCRIPT_COMPLETED = 5, + NILWV_EVENT_SCRIPT_FAILED = 6, + NILWV_EVENT_PAGE_MESSAGE = 7, + NILWV_EVENT_NAVIGATION_REQUESTED = 8, + NILWV_EVENT_CLOSE_REQUESTED = 9, + NILWV_EVENT_PROVIDER_FAILED = 10 +}; +enum nilwv_value_kind_v1 { + NILWV_VALUE_NONE = 0, NILWV_VALUE_JSON = 1, NILWV_VALUE_UNDEFINED = 2 +}; +enum nilwv_source_kind_v1 { + NILWV_SOURCE_UNKNOWN = 0, + NILWV_SOURCE_NATIVE_URL = 1, + NILWV_SOURCE_NATIVE_ORIGIN = 2 +}; +enum nilwv_frame_kind_v1 { + NILWV_FRAME_UNKNOWN = 0, NILWV_FRAME_MAIN = 1, NILWV_FRAME_CHILD = 2 +}; +enum nilwv_failure_kind_v1 { + NILWV_FAILURE_NONE = 0, + NILWV_FAILURE_NATIVE = 1, + NILWV_FAILURE_SCRIPT_EXCEPTION = 2, + NILWV_FAILURE_SERIALIZATION = 3, + NILWV_FAILURE_ASYNC_RESULT = 4, + NILWV_FAILURE_PAYLOAD_LIMIT = 5, + NILWV_FAILURE_TIMEOUT = 6, + NILWV_FAILURE_CANCELLED = 7 +}; + +/* One context per framework execution context, owned by its platform UI + * thread: the process main thread on macOS/Linux, the creating STA thread on + * Windows. All methods, including release and destruction, use that thread. + * Public numeric handles are positive, process-unique, never reused, <=INT64_MAX, + * and validated against context, resource kind and lifetime on every call. + * No callback from a provider enters Matrix or the VM. + * + * probe: no window/display initialization; result.number=1 on success. + * create: returns a context or NULL on error; profile state is provider-owned + * and isolated from personal browser profiles. Neither probe nor create starts + * a global event loop. window: returns a pending hidden window, then poll emits + * exactly one Ready/InitializationFailed unless explicitly closed first. + * + * show/close/release_event: number=1. navigate/load_html/evaluate_function: + * positive operation ID, then one matching completion/failure event. Reject + * overlapping navigation/script operations with BUSY; do not queue another. + * navigate authorizes one initial URL request. HTTP redirects and uninitiated + * navigations (including page actions/new windows) are cancelled and reported + * as NavigationRequested; a cancelled active navigation completes as failed. + * After that completion the application may explicitly follow a requested URL. + * load_html has no base URI; evaluate_function accepts a synchronous function + * body with explicit return, JSON.stringify result semantics, distinct undefined, + * and explicit failure for thenables or unsuccessful serialization. + * + * poll pumps a bounded batch (up to 64 native dispatch iterations, 2ms soft budget) and returns an + * owned immutable event snapshot ID, or 0 for empty. Retained snapshots count + * toward queue limits. The framework copies all fields then releases on every + * path. Overflow latches QUEUE_OVERFLOW; operations fail until context teardown. + * No messages or completion events are silently dropped to recover capacity. + * + * event_number names: window, kind, sequence, operation, value_kind, + * source_kind, frame_kind, failure_kind. operation=0 means no initiating call. + * event_text names: payload_json, source_url, source_origin, detail. + * source_url/origin are empty when unavailable; browser current URL and + * JavaScript-supplied URL/origin values must not be represented as sender proof. + * source_origin is only a native engine-reported origin, not parsed from a URL. + * Unknown event property names are ARGUMENT errors, not empty/zero results. + * + * close invalidates the window, its queued/retained events and pending operations. + * Closing again is HANDLE error. Teardown invalidates all context resources. + * Outstanding engine callbacks retain only independent cancelled state, never + * a raw freed context/window pointer. Late callbacks cannot publish new events. + * Browser processes may finish asynchronously after object closure; the provider + * remains responsible for its own isolated profile/cleanup state. No claim is + * made that cancelling a script stops executing JavaScript. + */ +typedef struct nilwv_api_v1 { + uint32_t abi_version; + uint32_t size; + uint64_t capabilities; + const char *provider_name; /* static NUL-terminated UTF-8 */ + const char *provider_build; /* static NUL-terminated UTF-8 */ + + void (NILWV_CALL *probe)(nilwv_result_v1 *); + void (NILWV_CALL *context_create)(nilwv_context_v1 **, nilwv_result_v1 *); + void (NILWV_CALL *context_destroy)(nilwv_context_v1 *); + void (NILWV_CALL *window)(nilwv_context_v1 *, nilwv_text_v1, int64_t, int64_t, nilwv_result_v1 *); + void (NILWV_CALL *show)(nilwv_context_v1 *, int64_t, nilwv_result_v1 *); + void (NILWV_CALL *navigate)(nilwv_context_v1 *, int64_t, nilwv_text_v1, nilwv_result_v1 *); + void (NILWV_CALL *load_html)(nilwv_context_v1 *, int64_t, nilwv_text_v1, nilwv_result_v1 *); + void (NILWV_CALL *evaluate_function)(nilwv_context_v1 *, int64_t, nilwv_text_v1, nilwv_result_v1 *); + void (NILWV_CALL *poll)(nilwv_context_v1 *, int64_t, nilwv_result_v1 *); + void (NILWV_CALL *event_number)(nilwv_context_v1 *, int64_t, nilwv_text_v1, nilwv_result_v1 *); + void (NILWV_CALL *event_text)(nilwv_context_v1 *, int64_t, nilwv_text_v1, nilwv_result_v1 *); + void (NILWV_CALL *release_event)(nilwv_context_v1 *, int64_t, nilwv_result_v1 *); + void (NILWV_CALL *close)(nilwv_context_v1 *, int64_t, nilwv_result_v1 *); +} nilwv_api_v1; + +typedef const nilwv_api_v1 *(NILWV_CALL *nilwv_get_api_v1_fn)(uint32_t, uint32_t); + +/* Exactly this exported C name; NULL rejects unsupported ABI/table size. + * The table and function pointers remain stable for process lifetime. + * Runtime loads only a caller-selected absolute provider path, validates every + * mandatory pointer and the exact ABI, calls probe, then creates its context. + * The runtime never unloads or hot-reloads a successfully loaded provider. + * No provider call may allow a C++ exception to cross this boundary. + */ +NILWV_EXPORT const nilwv_api_v1 *NILWV_CALL +nilwebview_provider_v1_get_api(uint32_t requested_version, uint32_t minimum_table_size); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/nilcompiler/CMakeLists.txt b/nilcompiler/CMakeLists.txt index b29a9cd..dec1beb 100644 --- a/nilcompiler/CMakeLists.txt +++ b/nilcompiler/CMakeLists.txt @@ -69,6 +69,7 @@ add_library(nilruntime_objects OBJECT src/owned_runtime.cpp src/secure_file_io.cpp src/database_runtime.cpp + src/webview_runtime.cpp ${NIL_UI_PROVIDER_SOURCE} src/pattern_engine.cpp src/nildata.cpp diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index bde58c9..dd7851d 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -7128,7 +7128,8 @@ codegen::assemble_module(const ast_program &program, std::string ret_type_str = "void"; if (intrinsic_name.rfind("regex.", 0) == 0 || intrinsic_name.rfind("nildata.", 0) == 0 || - intrinsic_name.rfind("ui.v1.", 0) == 0) { + intrinsic_name.rfind("ui.v1.", 0) == 0 || + intrinsic_name.rfind("webview.v1.", 0) == 0) { ret_type_str = canonical_nil_type_name(fn.return_type); } else if (is_declared_enum_type(*this, fn.return_type)) { ret_type_str = canonical_nil_type_name(fn.return_type); diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index 36d29a0..47a3eb2 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -7,6 +7,7 @@ #include "diagnostics.hpp" #include "dynamic_type.hpp" #include "ui_intrinsic.hpp" +#include "webview_intrinsic.hpp" #include "executable_context.hpp" #include "native_runtime.hpp" #include "ordinary_io_intrinsic.hpp" @@ -2944,10 +2945,13 @@ bool NativeCodegen::generateModule(const nil_module &mod) { impl_->builder->CreateRet(value); } annotation_handled = true; - } else if (dispatch_name == "@intrinsic" && dispatch_provider.rfind("ui.v1.", 0) == 0) { - const auto contract = ui::intrinsic(dispatch_provider); + } else if (dispatch_name == "@intrinsic" && + (dispatch_provider.rfind("ui.v1.", 0) == 0 || dispatch_provider.rfind("webview.v1.", 0) == 0)) { + const bool is_webview = dispatch_provider.rfind("webview.v1.", 0) == 0; + const auto contract = is_webview ? webview::intrinsic(dispatch_provider) : ui::intrinsic(dispatch_provider); + const std::string family = is_webview ? "WebView" : "UI"; if (!contract) { - std::cerr << "[NativeCodegen] unknown UI intrinsic '" << dispatch_provider << "'\n"; + std::cerr << "[NativeCodegen] unknown " << family << " intrinsic '" << dispatch_provider << "'\n"; return false; } std::vector parameter_types; @@ -2969,7 +2973,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { valid = valid && schemas == 1; } if (!valid) { - std::cerr << "[NativeCodegen] " << dispatch_provider << " requires the exact UI ABI " + std::cerr << "[NativeCodegen] " << dispatch_provider << " requires the exact " << family << " ABI " << ui::signature(*contract) << " and the standard Result schema\n"; return false; } @@ -2989,7 +2993,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { std::vector types; for (auto *argument : arguments) types.push_back(argument->getType()); auto *runtime_type = llvm::FunctionType::get(capability ? word_type : llvm::Type::getInt32Ty(ctx), types, false); - auto runtime = impl_->module->getOrInsertFunction("nyrt_ui_v1_" + contract->operation, runtime_type); + auto runtime = impl_->module->getOrInsertFunction(std::string(is_webview ? "nyrt_webview_v1_" : "nyrt_ui_v1_") + contract->operation, runtime_type); auto *status = impl_->builder->CreateCall(runtime_type, runtime.getCallee(), arguments); if (capability) { impl_->builder->CreateRet(impl_->builder->CreateIntCast(status, impl_->current_function->getReturnType(), false)); @@ -9395,6 +9399,17 @@ int NativeCodegen::executeJIT(const std::vector &program_args) { llvm::orc::ExecutorSymbolDef(llvm::orc::ExecutorAddr::fromPtr(address), llvm::JITSymbolFlags::Exported); }; + expose_runtime_symbol("nyrt_webview_v1_configure", &nyrt_webview_v1_configure); + expose_runtime_symbol("nyrt_webview_v1_window", &nyrt_webview_v1_window); + expose_runtime_symbol("nyrt_webview_v1_show", &nyrt_webview_v1_show); + expose_runtime_symbol("nyrt_webview_v1_poll", &nyrt_webview_v1_poll); + expose_runtime_symbol("nyrt_webview_v1_release_event", &nyrt_webview_v1_release_event); + expose_runtime_symbol("nyrt_webview_v1_close", &nyrt_webview_v1_close); + expose_runtime_symbol("nyrt_webview_v1_navigate", &nyrt_webview_v1_navigate); + expose_runtime_symbol("nyrt_webview_v1_load_html", &nyrt_webview_v1_load_html); + expose_runtime_symbol("nyrt_webview_v1_evaluate_function", &nyrt_webview_v1_evaluate_function); + expose_runtime_symbol("nyrt_webview_v1_event_number", &nyrt_webview_v1_event_number); + expose_runtime_symbol("nyrt_webview_v1_event_text", &nyrt_webview_v1_event_text); expose_runtime_symbol("nyrt_ui_v1_available", &nyrt_ui_v1_available); expose_runtime_symbol("nyrt_ui_v1_window", &nyrt_ui_v1_window); expose_runtime_symbol("nyrt_ui_v1_widget", &nyrt_ui_v1_widget); diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index 7c20629..4d2a789 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -7,6 +7,7 @@ #include "dynamic_type.hpp" #include "database_runtime.hpp" #include "ui_runtime.hpp" +#include "webview_runtime.hpp" #include "integer_conversion.hpp" #include "memory_profile.hpp" #include "pattern_engine.hpp" @@ -97,6 +98,7 @@ struct runtime_context { ny::memory_profile::Session profile; ny::database::Context databases; ny::ui::Context ui; + ny::webview::Context webview; struct file { std::unique_ptr stream; bool readable = false; @@ -647,10 +649,77 @@ const char *ui_text_argument(const char *text) { if (!text) throw std::invalid_argument("ui: expected text argument"); return text; } +template +std::int32_t webview_number_result(std::int64_t *value, const char **error, + Invoke invoke) noexcept { + if (!value || !error) return 0; + *value = 0; *error = nullptr; + try { + auto result = invoke(); + if (!result) { set_error(error, result.error); return 0; } + *value = result.number; + return 1; + } catch (const std::invalid_argument &invalid) { set_error(error, invalid.what()); return 0; } + catch (...) { *error = "webview: host allocation failed"; return 0; } +} +template +std::int32_t webview_text_result(const char **value, const char **error, + Invoke invoke) noexcept { + if (!value || !error) return 0; + *value = nullptr; *error = nullptr; + try { + auto result = invoke(); + if (!result) { set_error(error, result.error); return 0; } + // The snapshot may be released immediately after this call. Never return + // provider storage, even when its lifetime presently spans the caller. + *value = own_string(result.text); + if (!*value) { *error = "webview: host allocation failed"; return 0; } + return 1; + } catch (const std::invalid_argument &invalid) { set_error(error, invalid.what()); return 0; } + catch (...) { *error = "webview: host allocation failed"; return 0; } +} +const char *webview_text_argument(const char *text) { + if (!text) throw std::invalid_argument("webview: expected text argument"); + return text; +} } // namespace extern "C" { +std::int32_t nyrt_webview_v1_configure(const char *path, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.configure(webview_text_argument(path)); }); +} +std::int32_t nyrt_webview_v1_window(const char *title, std::int64_t width, std::int64_t height, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.window(webview_text_argument(title), width, height); }); +} +std::int32_t nyrt_webview_v1_show(std::int64_t handle, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.show(handle); }); +} +std::int32_t nyrt_webview_v1_poll(std::int64_t handle, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.poll(handle); }); +} +std::int32_t nyrt_webview_v1_release_event(std::int64_t handle, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.release_event(handle); }); +} +std::int32_t nyrt_webview_v1_close(std::int64_t handle, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.close(handle); }); +} +std::int32_t nyrt_webview_v1_navigate(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.navigate(handle, webview_text_argument(text)); }); +} +std::int32_t nyrt_webview_v1_load_html(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.load_html(handle, webview_text_argument(text)); }); +} +std::int32_t nyrt_webview_v1_evaluate_function(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.evaluate_function(handle, webview_text_argument(text)); }); +} +std::int32_t nyrt_webview_v1_event_number(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.event_number(handle, webview_text_argument(text)); }); +} +std::int32_t nyrt_webview_v1_event_text(std::int64_t handle, const char *text, const char **value, const char **error) noexcept { + return webview_text_result(value, error, [&] { return context.webview.event_text(handle, webview_text_argument(text)); }); +} + std::int64_t nyrt_ui_v1_available() noexcept { return ny::ui::available() ? 1 : 0; } std::int32_t nyrt_ui_v1_window(const char *title, std::int64_t width, std::int64_t height, std::int64_t *value, const char **error) noexcept { @@ -869,6 +938,7 @@ void nyrt_context_end() noexcept { nyrt_fail("NIL native runtime error: memory capture failed\n"); context.databases.clear(); context.ui.clear(); + context.webview.clear(); context.files.clear(); nyrt_owned_v1_unwind(0); context.pending_fault.reset(); @@ -891,6 +961,7 @@ void nyrt_profile_site(const char *file, const char *function, [[noreturn]] void nyrt_fail(const char *message) noexcept { context.ui.clear(); + context.webview.clear(); (void)context.profile.finish("failed", false); if (message != nullptr) std::fputs(message, stderr); diff --git a/nilcompiler/src/native_runtime.hpp b/nilcompiler/src/native_runtime.hpp index 5435df5..306d5e0 100644 --- a/nilcompiler/src/native_runtime.hpp +++ b/nilcompiler/src/native_runtime.hpp @@ -53,6 +53,19 @@ std::int32_t nyrt_ui_v1_destroy_widget(std::int64_t handle, std::int32_t nyrt_ui_v1_close(std::int64_t window, std::int64_t *value, const char **error) noexcept; +// Checked WebView provider bridge. All text is copied into managed storage. +std::int32_t nyrt_webview_v1_configure(const char *path, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_window(const char *title, std::int64_t width, std::int64_t height, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_show(std::int64_t handle, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_poll(std::int64_t handle, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_release_event(std::int64_t handle, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_close(std::int64_t handle, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_navigate(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_load_html(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_evaluate_function(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_event_number(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_event_text(std::int64_t handle, const char *text, const char **value, const char **error) noexcept; + // Additive database ABI. Success is 1, failure 0; outputs are context-owned. std::int64_t nyrt_db2_available(const char *driver) noexcept; std::int32_t nyrt_db2_open(const char *driver, const char *address, diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index 6f293a3..59eed7c 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -7,6 +7,7 @@ #include "diagnostics.hpp" #include "dynamic_type.hpp" #include "ui_intrinsic.hpp" +#include "webview_intrinsic.hpp" #include "nil_contract.hpp" #include "numeric_literal.hpp" #include "scalar_text.hpp" @@ -3309,10 +3310,12 @@ void type_checker::visit(ast_function_decl &p) { const auto &arguments = annotation.typed_arguments ? *annotation.typed_arguments : parsed.arguments; if (arguments.size() != 1 || arguments.front().name || arguments.front().kind != "text") continue; const auto &provider = arguments.front().value; - if (provider.rfind("ui.v1.", 0) != 0) continue; - const auto contract = ui::intrinsic(provider); + const bool is_webview = provider.rfind("webview.v1.", 0) == 0; + if (!is_webview && provider.rfind("ui.v1.", 0) != 0) continue; + const auto contract = is_webview ? webview::intrinsic(provider) : ui::intrinsic(provider); + const std::string family = is_webview ? "WebView" : "UI"; if (!contract) { - add_error(p.line, "Unknown UI intrinsic '" + provider + "'"); + add_error(p.line, "Unknown " + family + " intrinsic '" + provider + "'"); continue; } // Core Result may remain a short built-in name after ordinary import @@ -3334,7 +3337,7 @@ void type_checker::visit(ast_function_decl &p) { ordinary = ordinary && !parameter.is_ref && !parameter.is_variadic && !parameter.default_value; } if (!ordinary || !ui::signature_matches(*contract, parameters, p.return_type.value_or("void"))) - add_error(p.line, provider + " requires the exact UI ABI " + ui::signature(*contract) + + add_error(p.line, provider + " requires the exact " + family + " ABI " + ui::signature(*contract) + "; use a module-level, non-generic function without reference, variadic, or default parameters and import nil.std.core.result"); } diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index 50c7620..22df6b6 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -10,6 +10,7 @@ #include "nil_contract.hpp" #include "dynamic_type.hpp" #include "ui_intrinsic.hpp" +#include "webview_intrinsic.hpp" #include "numeric_literal.hpp" #include "scalar_text.hpp" #include "integer_conversion.hpp" @@ -738,6 +739,7 @@ bool VM::finishMemoryProfile(const char *status, bool completed) noexcept { // This hook runs at every invocation terminal, even without profiling. // Paused debugger steps retain their UI until completion/reset. ui_.clear(); + webview_.clear(); closeOpenSockets(); if (!memory_profile_started_ || memory_profile_finished_) return true; @@ -5548,6 +5550,57 @@ void VM::executeInstruction(const Instruction &instr) { return; } + if (lib_name == "intrinsic" && fn_name.rfind("webview.v1.", 0) == 0) { + const auto contract = webview::intrinsic(fn_name); + if (!contract) throw std::runtime_error("webview: unknown intrinsic '" + fn_name + "'"); + const auto declared = call_stack_.empty() ? functions_.end() + : functions_.find(call_stack_.back().fn_name); + if (declared == functions_.end() || + !webview::signature_matches(*contract, declared->second.parameter_types, + declared->second.return_type) || + instr.args.size() != 4 || webview::abi_type(instr.args[3]) != contract->return_type() || + args.size() != contract->parameters.size()) + throw std::runtime_error(fn_name + " requires the exact WebView ABI " + webview::signature(*contract)); + if (contract->output != webview::Output::capability) { + std::size_t schemas = 0; + if (class_metadata_) + for (const auto &definition : class_metadata_->enums) + if (webview::result_schema_matches(*contract, definition)) ++schemas; + if (schemas != 1) + throw std::runtime_error(fn_name + " requires the standard Result schema with exact Ok and Error payloads"); + } + for (std::size_t index = 0; index < args.size(); ++index) { + const bool valid = contract->parameters[index] == "text" + ? std::holds_alternative(args[index]) + : std::holds_alternative(args[index]); + if (!valid) throw std::runtime_error(fn_name + " argument " + + std::to_string(index + 1) + " requires " + contract->parameters[index]); + } + auto text_arg = [&](std::size_t index) -> const std::string & { + return std::get(args[index]); + }; + auto word_arg = [&](std::size_t index) { return std::get(args[index]); }; + webview::Result result; + const auto &op = contract->operation; + if (op == "configure") result = webview_.configure(text_arg(0)); + else if (op == "window") result = webview_.window(text_arg(0), word_arg(1), word_arg(2)); + else if (op == "show") result = webview_.show(word_arg(0)); + else if (op == "navigate") result = webview_.navigate(word_arg(0), text_arg(1)); + else if (op == "load_html") result = webview_.load_html(word_arg(0), text_arg(1)); + else if (op == "evaluate_function") result = webview_.evaluate_function(word_arg(0), text_arg(1)); + else if (op == "poll") result = webview_.poll(word_arg(0)); + else if (op == "event_number") result = webview_.event_number(word_arg(0), text_arg(1)); + else if (op == "event_text") result = webview_.event_text(word_arg(0), text_arg(1)); + else if (op == "release_event") result = webview_.release_event(word_arg(0)); + else if (op == "close") result = webview_.close(word_arg(0)); + EnumValue value; + value.variant_name = result ? "Result::Ok" : "Result::Error"; + if (!result) value.payloads.push_back(std::move(result.error)); + else if (contract->output == webview::Output::text) value.payloads.push_back(std::move(result.text)); + else value.payloads.push_back(result.number); + pushStack(std::move(value)); + return; + } if (lib_name == "intrinsic" && fn_name.rfind("ui.v1.", 0) == 0) { const auto contract = ui::intrinsic(fn_name); if (!contract) throw std::runtime_error("ui: unknown intrinsic '" + fn_name + "'"); diff --git a/nilcompiler/src/vm.hpp b/nilcompiler/src/vm.hpp index 2f7db71..e041981 100644 --- a/nilcompiler/src/vm.hpp +++ b/nilcompiler/src/vm.hpp @@ -17,6 +17,7 @@ #include "source_debug.hpp" #include "database_runtime.hpp" #include "ui_runtime.hpp" +#include "webview_runtime.hpp" #include "memory_profile.hpp" namespace ny { @@ -561,6 +562,7 @@ class VM { // Heap management for manual memory (unsafe mode) and GC (safe mode) database::Context databases_; ui::Context ui_; + webview::Context webview_; struct HeapBlock { std::string type_name; // Logical element metadata for type_name == "array". Textual and binary diff --git a/nilcompiler/src/webview_intrinsic.hpp b/nilcompiler/src/webview_intrinsic.hpp new file mode 100644 index 0000000..744663d --- /dev/null +++ b/nilcompiler/src/webview_intrinsic.hpp @@ -0,0 +1,28 @@ +/* Copyright (C) 2026 Execute Software. SPDX-License-Identifier: MIT */ +#pragma once +#include "ui_intrinsic.hpp" + +namespace ny::webview { +using Intrinsic = ui::Intrinsic; +using Output = ui::Output; +using ui::abi_type; +using ui::signature; +using ui::signature_matches; +using ui::result_schema_matches; + +inline std::optional intrinsic(const std::string &name) { + if (name.rfind("webview.v1.", 0) != 0) return std::nullopt; + Intrinsic value; + value.operation = name.substr(11); + const auto &op = value.operation; + if (op == "configure") value.parameters = {"text"}; + else if (op == "window") value.parameters = {"text", "i64", "i64"}; + else if (op == "navigate" || op == "load_html" || op == "evaluate_function" || op == "event_number") + value.parameters = {"i64", "text"}; + else if (op == "event_text") { value.parameters = {"i64", "text"}; value.output = Output::text; } + else if (op == "show" || op == "poll" || op == "release_event" || op == "close") + value.parameters = {"i64"}; + else return std::nullopt; + return value; +} +} // namespace ny::webview diff --git a/nilcompiler/src/webview_runtime.cpp b/nilcompiler/src/webview_runtime.cpp new file mode 100644 index 0000000..5820cbe --- /dev/null +++ b/nilcompiler/src/webview_runtime.cpp @@ -0,0 +1,299 @@ +/* Copyright (C) 2026 Execute Software. SPDX-License-Identifier: MIT */ +#include "webview_runtime.hpp" +#include "../../common/webview_provider_v1.h" +#include "../../common/webview_json_v1.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif + +namespace ny::webview { +namespace { +Result failure(const std::string &message) { return {0, {}, "webview: " + message}; } +Result success(std::int64_t value = 1) { return {value, {}, {}}; } +bool valid_text(const std::string &value) { + if (value.size() > NILWV_MAX_TEXT_BYTES || value.find('\0') != std::string::npos) return false; + return nilwebview::json_v1::valid_utf8(value); +} +nilwv_text_v1 view(const std::string &value) { return {value.data(), value.size()}; } +std::atomic next_handle{1}; +std::int64_t fresh_handle() { + auto value = next_handle.load(std::memory_order_relaxed); + for (;;) { + if (value <= 0 || value == std::numeric_limits::max()) return 0; + if (next_handle.compare_exchange_weak(value, value + 1, std::memory_order_relaxed)) return value; + } +} +struct Library { + const nilwv_api_v1 *api; + void *module; // Intentionally never unloaded, even after a rejected handshake. +}; +// Process-lifetime registry: asynchronous engine callbacks can outlive a +// window/context. Do not let static destructor ordering unload their code. +struct Registry { std::mutex mutex; std::map libraries; }; +Registry ®istry() { static auto *value = new Registry; return *value; } +const nilwv_api_v1 *load_provider(const std::string &path) { + auto &cache = registry(); + std::lock_guard lock(cache.mutex); + auto found = cache.libraries.find(path); + if (found != cache.libraries.end()) return found->second.api; + if (cache.libraries.size() >= 16) return nullptr; + void *module = nullptr; + nilwv_get_api_v1_fn get_api = nullptr; +#ifdef _WIN32 + auto wide = std::filesystem::u8path(path).wstring(); + auto handle = LoadLibraryExW(wide.c_str(), nullptr, + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + module = handle; + if (handle) get_api = reinterpret_cast(GetProcAddress(handle, "nilwebview_provider_v1_get_api")); +#else + module = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (module) get_api = reinterpret_cast(dlsym(module, "nilwebview_provider_v1_get_api")); +#endif + if (!module) return nullptr; + // Insert before calling foreign code so allocation/validation failure cannot + // make a loaded library eligible for an accidental later unload. + auto &entry = cache.libraries.emplace(path, Library{nullptr, module}).first->second; + const nilwv_api_v1 *api = nullptr; + try { if (get_api) api = get_api(NILWV_ABI_V1, sizeof(nilwv_api_v1)); } catch (...) { return nullptr; } + if (!api || api->abi_version != NILWV_ABI_V1 || api->size < sizeof(nilwv_api_v1) || + (api->capabilities & ~NILWV_CAP_KNOWN_MASK) || + !api->probe || !api->context_create || !api->context_destroy || + !api->window || !api->show || !api->navigate || !api->load_html || + !api->evaluate_function || !api->poll || !api->event_number || + !api->event_text || !api->release_event || !api->close) return nullptr; + entry.api = api; + return api; +} +constexpr std::array number_fields{ + "window", "kind", "sequence", "operation", "value_kind", "source_kind", "frame_kind", "failure_kind"}; +constexpr std::array text_fields{"payload_json", "source_url", "source_origin", "detail"}; +template std::size_t field_index(const Array &fields, const std::string &key) { + return static_cast(std::find(fields.begin(), fields.end(), key) - fields.begin()); +} +} // namespace + +struct Context::Impl { + const std::thread::id thread = std::this_thread::get_id(); + const nilwv_api_v1 *api = nullptr; + nilwv_context_v1 *context = nullptr; + std::string path, fault; + std::map windows; + struct Event { std::array numbers{}; std::array texts; std::size_t bytes = 0; }; + std::map events; + std::size_t event_bytes = 0; + + Result check(bool configured = true) const { + if (thread != std::this_thread::get_id()) return failure("context belongs to another thread"); + if (!fault.empty()) return failure(fault); + if (configured && (!api || !context)) return failure("configure an explicit provider first"); + return success(); + } + Result protocol() { fault = "provider contract violation; close the execution context"; return failure(fault); } + template Result call(Invoke invoke) { + nilwv_result_v1 result{}; + result.size = sizeof(result); + try { invoke(&result); } catch (...) { return protocol(); } + if (result.size != sizeof(result) || result.code > 0 || + result.text.size > NILWV_MAX_TEXT_BYTES || (!result.text.data && result.text.size)) return protocol(); + std::string text; + if (result.text.size) text.assign(result.text.data, static_cast(result.text.size)); + if (!valid_text(text)) return protocol(); + if (result.code < 0) return failure(text.empty() ? "provider reported an unspecified failure" : text); + return {result.number, std::move(text), {}}; + } + std::int64_t native_window(std::int64_t window) const { + auto item = windows.find(window); return item == windows.end() ? 0 : item->second; + } + template Result window_call(std::int64_t window, Invoke invoke, bool operation = false) { + if (auto state = check(); !state) return state; + const auto native = native_window(window); + if (!native) return failure("invalid or closed window handle"); + auto result = call([&](auto *out) { invoke(native, out); }); + if (result && (operation ? result.number <= 0 : result.number != 1)) return protocol(); + return result; + } +}; + +Context::Context() : impl_(std::make_unique()) {} +Context::~Context() { clear(); } +void Context::clear() noexcept { + if (!impl_) return; + // Context ownership cannot be transferred. A foreign-thread teardown must + // not enter a toolkit on the wrong thread; retained provider state remains + // pinned, rather than risking callbacks into freed objects. + if (impl_->thread != std::this_thread::get_id()) return; + try { if (impl_->context && impl_->api) impl_->api->context_destroy(impl_->context); } catch (...) {} + impl_->context = nullptr; impl_->api = nullptr; + impl_->windows.clear(); impl_->events.clear(); impl_->event_bytes = 0; + impl_->fault.clear(); impl_->path.clear(); +} +Result Context::configure(const std::string &path) { + if (auto state = impl_->check(false); !state) return state; + if (!valid_text(path) || path.empty() || !std::filesystem::u8path(path).is_absolute()) + return failure("provider path must be absolute UTF-8 without NUL"); + if (impl_->context) + return path == impl_->path ? success(static_cast(impl_->api->capabilities)) + : failure("this execution already selected a provider"); + const auto *api = load_provider(path); + if (!api) return failure("provider could not be loaded or has an incompatible ABI"); + auto probe = impl_->call([&](auto *out) { api->probe(out); }); + if (!probe) return probe; + if (probe.number != 1) return impl_->protocol(); + nilwv_context_v1 *context = nullptr; + auto created = impl_->call([&](auto *out) { api->context_create(&context, out); }); + if (!created || !context || created.number != 1) { + try { if (context) api->context_destroy(context); } catch (...) {} + return !created ? created : impl_->protocol(); + } + impl_->api = api; impl_->context = context; impl_->path = path; + return success(static_cast(api->capabilities)); +} +Result Context::window(const std::string &title, std::int64_t width, std::int64_t height) { + if (auto state = impl_->check(); !state) return state; + if (!valid_text(title) || width < 1 || width > 16384 || height < 1 || height > 16384) + return failure("window requires valid text and dimensions from 1 to 16384"); + if (impl_->windows.size() >= NILWV_MAX_WINDOWS) return failure("window limit reached"); + auto result = impl_->call([&](auto *out) { impl_->api->window(impl_->context, view(title), width, height, out); }); + if (!result) return result; + if (result.number <= 0 || std::any_of(impl_->windows.begin(), impl_->windows.end(), + [&](const auto &entry) { return entry.second == result.number; })) return impl_->protocol(); + const auto handle = fresh_handle(); + if (!handle) { impl_->call([&](auto *out) { impl_->api->close(impl_->context, result.number, out); }); return failure("handle space exhausted"); } + try { impl_->windows.emplace(handle, result.number); } + catch (...) { impl_->call([&](auto *out) { impl_->api->close(impl_->context, result.number, out); }); throw; } + return success(handle); +} +Result Context::show(std::int64_t window) { + return impl_->window_call(window, [&](auto native, auto *out) { impl_->api->show(impl_->context, native, out); }); +} +#define NILWV_TEXT_OPERATION(name) \ +Result Context::name(std::int64_t window, const std::string &text) { \ + if (!valid_text(text)) return failure("text must be UTF-8 without NUL, at most 1048576 bytes"); \ + return impl_->window_call(window, [&](auto native, auto *out) { impl_->api->name(impl_->context, native, view(text), out); }, true); \ +} +NILWV_TEXT_OPERATION(navigate) +NILWV_TEXT_OPERATION(load_html) +NILWV_TEXT_OPERATION(evaluate_function) +#undef NILWV_TEXT_OPERATION + +Result Context::poll(std::int64_t window) { + if (auto state = impl_->check(); !state) return state; + const auto native = impl_->native_window(window); + if (!native) return failure("invalid or closed window handle"); + if (impl_->events.size() >= NILWV_MAX_EVENTS) return failure("release retained event snapshots before polling"); + auto polled = impl_->call([&](auto *out) { impl_->api->poll(impl_->context, native, out); }); + if (!polled || polled.number == 0) return polled; + if (polled.number < 0) return impl_->protocol(); + struct Release { + Impl *state; std::int64_t handle; bool active = true; + Result run() { active = false; return state->call([&](auto *out) { state->api->release_event(state->context, handle, out); }); } + ~Release() { if (active) { try { run(); } catch (...) {} } } + } release{impl_.get(), polled.number}; + Impl::Event event; + for (std::size_t i = 0; i < number_fields.size(); ++i) { + const std::string key = number_fields[i]; + auto field = impl_->call([&](auto *out) { impl_->api->event_number(impl_->context, polled.number, view(key), out); }); + if (!field) return field; + event.numbers[i] = field.number; + } + for (std::size_t i = 0; i < text_fields.size(); ++i) { + const std::string key = text_fields[i]; + auto field = impl_->call([&](auto *out) { impl_->api->event_text(impl_->context, polled.number, view(key), out); }); + if (!field) return field; + event.bytes += field.text.size(); event.texts[i] = std::move(field.text); + } + const auto &n = event.numbers; + if (n[0] != native || n[1] < NILWV_EVENT_READY || n[1] > NILWV_EVENT_PROVIDER_FAILED || + n[2] <= 0 || n[3] < 0 || n[4] < 0 || n[4] > NILWV_VALUE_UNDEFINED || + n[5] < 0 || n[5] > NILWV_SOURCE_NATIVE_ORIGIN || n[6] < 0 || n[6] > NILWV_FRAME_CHILD || + n[7] < 0 || n[7] > NILWV_FAILURE_CANCELLED) return impl_->protocol(); + const auto caps = impl_->api->capabilities; + if ((n[5] == NILWV_SOURCE_UNKNOWN && (!event.texts[1].empty() || !event.texts[2].empty())) || + (n[5] == NILWV_SOURCE_NATIVE_URL && (event.texts[1].empty() || !event.texts[2].empty() || !(caps & NILWV_CAP_MESSAGE_URL))) || + (n[5] == NILWV_SOURCE_NATIVE_ORIGIN && (event.texts[2].empty() || !(caps & NILWV_CAP_MESSAGE_ORIGIN))) || + (!event.texts[1].empty() && !(caps & NILWV_CAP_MESSAGE_URL)) || + (!event.texts[2].empty() && !(caps & NILWV_CAP_MESSAGE_ORIGIN)) || + (n[6] != NILWV_FRAME_UNKNOWN && !(caps & NILWV_CAP_MESSAGE_FRAME))) return impl_->protocol(); + if (n[4] == NILWV_VALUE_JSON) { + if (!nilwebview::json_v1::valid_json(event.texts[0])) return impl_->protocol(); + } else if (!event.texts[0].empty()) return impl_->protocol(); + const auto kind = n[1]; + const bool completion = kind >= NILWV_EVENT_NAVIGATION_COMPLETED && kind <= NILWV_EVENT_SCRIPT_FAILED; + const bool failed = kind == NILWV_EVENT_INITIALIZATION_FAILED || kind == NILWV_EVENT_NAVIGATION_FAILED || + kind == NILWV_EVENT_SCRIPT_FAILED || kind == NILWV_EVENT_PROVIDER_FAILED; + if ((completion ? n[3] <= 0 : n[3] != 0) || (failed ? n[7] == 0 : n[7] != 0) || + (kind != NILWV_EVENT_PAGE_MESSAGE && (n[5] != NILWV_SOURCE_UNKNOWN || n[6] != NILWV_FRAME_UNKNOWN))) + return impl_->protocol(); + if (kind == NILWV_EVENT_PAGE_MESSAGE || kind == NILWV_EVENT_NAVIGATION_COMPLETED || kind == NILWV_EVENT_NAVIGATION_REQUESTED) { + if (n[4] != NILWV_VALUE_JSON) return impl_->protocol(); + } else if (kind == NILWV_EVENT_SCRIPT_COMPLETED) { + if (n[4] != NILWV_VALUE_JSON && n[4] != NILWV_VALUE_UNDEFINED) return impl_->protocol(); + } else if (kind == NILWV_EVENT_NAVIGATION_FAILED) { + if (n[4] == NILWV_VALUE_UNDEFINED) return impl_->protocol(); + } else if (n[4] != NILWV_VALUE_NONE) return impl_->protocol(); + if ((kind == NILWV_EVENT_NAVIGATION_COMPLETED || kind == NILWV_EVENT_NAVIGATION_REQUESTED || + kind == NILWV_EVENT_NAVIGATION_FAILED) && n[4] == NILWV_VALUE_JSON) { + const auto first = event.texts[0].find_first_not_of(" \t\n\r"); + if (first == std::string::npos || event.texts[0][first] != '"') return impl_->protocol(); + } + auto released = release.run(); + if (!released || released.number != 1) return impl_->protocol(); + if (event.bytes > NILWV_MAX_QUEUED_BYTES - impl_->event_bytes) { + impl_->fault = "retained event byte limit exceeded; close the execution context"; + return failure(impl_->fault); + } + event.numbers[0] = window; + const auto handle = fresh_handle(); + if (!handle) return failure("handle space exhausted"); + const auto bytes = event.bytes; + impl_->events.emplace(handle, std::move(event)); impl_->event_bytes += bytes; + return success(handle); +} +Result Context::event_number(std::int64_t snapshot, const std::string &field) { + if (auto state = impl_->check(); !state) return state; + const auto event = impl_->events.find(snapshot); + const auto index = field_index(number_fields, field); + if (event == impl_->events.end()) return failure("invalid or released event handle"); + if (index == number_fields.size()) return failure("unknown numeric event field"); + return success(event->second.numbers[index]); +} +Result Context::event_text(std::int64_t snapshot, const std::string &field) { + if (auto state = impl_->check(); !state) return state; + const auto event = impl_->events.find(snapshot); + const auto index = field_index(text_fields, field); + if (event == impl_->events.end()) return failure("invalid or released event handle"); + if (index == text_fields.size()) return failure("unknown text event field"); + return {0, event->second.texts[index], {}}; +} +Result Context::release_event(std::int64_t snapshot) { + if (auto state = impl_->check(); !state) return state; + const auto event = impl_->events.find(snapshot); + if (event == impl_->events.end()) return failure("invalid or released event handle"); + impl_->event_bytes -= event->second.bytes; impl_->events.erase(event); + return success(); +} +Result Context::close(std::int64_t window) { + auto result = impl_->window_call(window, [&](auto native, auto *out) { impl_->api->close(impl_->context, native, out); }); + if (!result) return result; + impl_->windows.erase(window); + for (auto it = impl_->events.begin(); it != impl_->events.end();) { + if (it->second.numbers[0] == window) { impl_->event_bytes -= it->second.bytes; it = impl_->events.erase(it); } + else ++it; + } + return success(); +} +} // namespace ny::webview diff --git a/nilcompiler/src/webview_runtime.hpp b/nilcompiler/src/webview_runtime.hpp new file mode 100644 index 0000000..67d661a --- /dev/null +++ b/nilcompiler/src/webview_runtime.hpp @@ -0,0 +1,40 @@ +/* Copyright (C) 2026 Execute Software. SPDX-License-Identifier: MIT */ +#pragma once +#include +#include +#include + +namespace ny::webview { +struct Result { + std::int64_t number = 0; + std::string text, error; + explicit operator bool() const noexcept { return error.empty(); } +}; + +// Each execution owns a context on the UI thread. The explicit absolute path +// selects trusted native code; the loader is not a sandbox for untrusted DLLs. +// Loaded libraries stay pinned for process lifetime, including late browser +// callbacks. Context handles and copied events never expose native addresses. +class Context { +public: + Context(); + ~Context(); + Context(const Context &) = delete; + Context &operator=(const Context &) = delete; + void clear() noexcept; + Result configure(const std::string &absolute_provider_path); + Result window(const std::string &title, std::int64_t width, std::int64_t height); + Result show(std::int64_t window); + Result navigate(std::int64_t window, const std::string &url); + Result load_html(std::int64_t window, const std::string &html); + Result evaluate_function(std::int64_t window, const std::string &body); + Result poll(std::int64_t window); + Result event_number(std::int64_t snapshot, const std::string &field); + Result event_text(std::int64_t snapshot, const std::string &field); + Result release_event(std::int64_t snapshot); + Result close(std::int64_t window); +private: + struct Impl; + std::unique_ptr impl_; +}; +} // namespace ny::webview diff --git a/notebook/2026-11-12-matrix-webview.md b/notebook/2026-11-12-matrix-webview.md new file mode 100644 index 0000000..f816430 --- /dev/null +++ b/notebook/2026-11-12-matrix-webview.md @@ -0,0 +1,80 @@ +# Matrix WebView provider boundary — 2026-11-12 + +## Status and question + +The archived Ny WebView project has been left untouched. Its modern replacement +is being built as `exec-nil-framework-webview`, with Matrix-facing library code +and separate WebView2, GTK4/WebKitGTK 6 and AppKit/WKWebView providers. Actual +browser qualification remains separate from the framework bridge tests below. + +The question is how a Matrix application can observe a browser's asynchronous +work consistently through interpreted NIL and LLVM AOT/JIT, without reviving the +old unchecked generic interop layer. + +## Decision + +The versioned `webview.v1.*` intrinsic family uses the standard nominal +`Result` and `Result` schemas. The frontend, loaded-NIL +interpreter and native backend each validate the declarations. A provider is +selected by an explicit absolute path to a trusted native library. The C ABI +contains fixed-width fields and borrowed text views; no toolkit object, callback +into Matrix, allocator or C++ container crosses it. Loaded modules remain pinned +for process lifetime because engine callbacks may outlive a closed window. + +Each execution owns its context on the UI thread. Runtime window and event +handles are process-unique and checked against that context. A poll copies all +event fields before releasing the provider's snapshot, including on malformed +output. Closing a window invalidates its retained runtime snapshots. Independent +contexts remain unaffected. Neither browser state nor these external handles is +part of the interpreter's pure same-process checkpoint profile. + +Creation yields a pending window and an eventual Ready or InitializationFailed +event. Navigation and synchronous function evaluation yield operation identities +with explicit completion or failure. Only one such operation is pending per +window; deadlines make a timed-out window unusable until closed and recreated. +Cancelling a request does not claim that executing JavaScript was forcibly stopped. + +The initial common navigation profile authorizes one URL request. Redirects and +page-initiated navigation are reported for explicit application approval instead +of being followed automatically. This avoids making different promises on macOS +15, whose public navigation-action API does not identify HTTP redirects the way +the other engines do. Popups, downloads and native host commands are outside this +profile. The migration document tracks legacy features separately rather than +advertising unimplemented cross-platform aliases. + +## Message and JSON identity + +A message's sender metadata must come from the native engine or remain Unknown. +WebKitGTK 6's public message callback does not expose authenticated sender frame +metadata. A JavaScript field or the browser's current URL cannot fill that gap. +Capability bits distinguish browser-reported URLs, security origins and frames. +An event cannot claim metadata that its provider did not advertise. + +Script results retain JSON.stringify's serialized text, with distinct Undefined, +script exception, serialization failure and unsupported Promise/thenable cases. +An independent review caught a real boundary mismatch: the framework's strict +configuration JSON parser rejected escaped lone surrogates and nesting levels +accepted by the provider. Both sides now use byte-identical WebView JSON grammar +headers: bounded UTF-8 JSON text, depth 64, no decoding of escaped UTF-16 units. +This preserves a legitimate `JSON.stringify` result without turning it into an +invalid UTF-8 scalar string. Depth 65 is rejected explicitly. + +For future AI tooling, operation identity and copied events provide an observable +boundary for browser actions. They do not grant page messages authority to invoke +host operations, and they do not automatically log page content or credentials. + +## Evidence and next qualification + +- 57 framework host checks cover provider ABI rejection, context/thread and + handle ownership, event release, provenance combinations and JSON boundaries. +- 28 intrinsic contract checks cover malformed declarations, disabled source + checking, typed failures and execution routes; the existing 40-check UI + intrinsic contract also passes after sharing native lowering code. +- The Matrix consumer contract passed text NIL, binary NIL, LLVM AOT and JIT + using a synthetic provider, including records retained after event/window + teardown. This is interface proof, not browser proof. +- Shared provider logic passed 196 native controls with sanitizers and 36 checks + of the generated JavaScript transport. Real browser builds and desktop tests + on Windows, Linux and both Mac architectures remain the next required gate. + +No accepted SDK, installer or release deployment is changed by this work. diff --git a/notebook/README.md b/notebook/README.md index d874eb0..e48741c 100644 --- a/notebook/README.md +++ b/notebook/README.md @@ -13,6 +13,8 @@ and explicit about evidence, uncertainty, and implementation status. - [`2026-11-13-formatted-markup-handoff.md`](2026-11-13-formatted-markup-handoff.md) — multiline text and structured markup completion review, route checks and SDK handoff. +- [`2026-11-12-matrix-webview.md`](2026-11-12-matrix-webview.md) — checked + browser providers, asynchronous operation identity and honest message provenance. - [`2026-11-12-web-server-boundaries.md`](2026-11-12-web-server-boundaries.md) — application-driven file snapshots, protocol boundaries, binary values and the checked provider boundary needed by the planned WebView rewrite. diff --git a/tests/tools/webview_intrinsic_contract.py b/tests/tools/webview_intrinsic_contract.py new file mode 100644 index 0000000..6134193 --- /dev/null +++ b/tests/tools/webview_intrinsic_contract.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Reject forged WebView declarations before loading any native provider.""" +import argparse +import os +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', required=True, type=Path) + parser.add_argument('--interpreter', required=True, type=Path) + parser.add_argument('--llvm', required=True, choices=('ON', 'OFF')) + args = parser.parse_args() + compiler, interpreter = args.compiler.resolve(), args.interpreter.resolve() + environment = {k: v for k, v in os.environ.items() if not k.startswith(('NIL_', 'NY_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-webview-abi-') as directory: + work = Path(directory) + base = [compiler, '--quiet', '--sdk-path', ROOT/'nilstd/src'] + + def run(command, status=0): + nonlocal checks + result = subprocess.run(list(map(str, command)), cwd=work, env=environment, + stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=60) + assert result.returncode == status, (result.returncode, result.stdout, result.stderr) + checks += 1 + return result + + imported = 'import nil.std.core.result\n' + entry = 'fn main() -> i32\n return 0\nend fn\n' + invalid = { + 'unknown': ('@intrinsic("webview.v1.unknown")\nfn provider() -> bool\n', 'Unknown WebView intrinsic'), + 'arity': (imported+'@intrinsic("webview.v1.configure")\nfn provider() -> Result\n', 'exact WebView ABI'), + 'width': (imported+'@intrinsic("webview.v1.show")\nfn provider(handle:i32) -> Result\n', 'exact WebView ABI'), + 'number-result': (imported+'@intrinsic("webview.v1.poll")\nfn provider(handle:i64) -> Result\n', 'exact WebView ABI'), + 'text-result': (imported+'@intrinsic("webview.v1.event_text")\nfn provider(handle:i64,field:text) -> Result\n', 'exact WebView ABI'), + 'error-payload': (imported+'@intrinsic("webview.v1.show")\nfn provider(handle:i64) -> Result\n', 'exact WebView ABI'), + 'reference': (imported+'@intrinsic("webview.v1.show")\nfn provider(ref handle:i64) -> Result\n', 'exact WebView ABI'), + 'default': (imported+'@intrinsic("webview.v1.show")\nfn provider(handle:i64=0) -> Result\n', 'exact WebView ABI'), + 'variadic': (imported+'@intrinsic("webview.v1.show")\nfn provider(..handles:i64) -> Result\n', 'exact WebView ABI'), + 'generic': (imported+'@intrinsic("webview.v1.show")\nfn provider(handle:i64) -> Result\n', 'exact WebView ABI'), + 'impostor': ('''module impostor +enum Result + Ok(T) + Error(E) +end enum +@intrinsic("webview.v1.show") +fn provider(handle:i64) -> Result +''', 'exact WebView ABI'), + } + for name, (declaration, diagnostic) in invalid.items(): + source, output = work/(name+'.ny'), work/(name+'.nil') + source.write_text(declaration+entry, newline='\n') + output.write_bytes(b'previous artifact') + result = run([*base, '--no-bundle', '-o', output, source], 1) + assert diagnostic in result.stderr + assert output.read_bytes() == b'previous artifact' + + for name, declaration, expression in ( + ('arity', imported+'@intrinsic("webview.v1.configure")\nfn provider() -> Result\n', 'provider()'), + ('return', '@intrinsic("webview.v1.poll")\nfn provider(handle:i64) -> i64\n', 'provider(0)'), + ): + source, output = work/('unchecked-'+name+'.ny'), work/('unchecked-'+name+'.nil') + source.write_text(declaration+'fn main() -> i32\n let value = '+expression+'\n return 0\nend fn\n', newline='\n') + run([*base, '--no-typecheck', '--no-bundle', '-o', output, source]) + result = run([interpreter, '--no-ai', output], 1) + assert 'WebView ABI' in result.stderr + if args.llvm == 'ON': + for flags in ([], ['--jit']): + output.write_bytes(b'previous artifact') + result = run([*base, '--no-typecheck', '--native', *flags, '-o', output, source], 1) + assert 'WebView ABI' in result.stderr + assert output.read_bytes() == b'previous artifact' + + source = work/'checked.ny' + source.write_text(imported+'''@intrinsic("webview.v1.configure") +fn configure(path:text) -> Result +@intrinsic("webview.v1.event_text") +fn event_text(snapshot:i64,field:text) -> Result +fn main() -> i32 + match configure("relative-provider") + Result.Ok(value) -> return 8 + Result.Error(message) -> println("checked WebView configuration failure") + end match + match event_text(0,"payload_json") + Result.Ok(value) -> return 9 + Result.Error(message) -> println("checked WebView event failure") + end match + return 0 +end fn +''', newline='\n') + for route in ['text', 'binary', 'bundle'] + (['native', 'jit'] if args.llvm == 'ON' else []): + output = work/('checked-'+route) + flags = (['--native', '--jit'] if route == 'jit' else ['--native'] if route == 'native' + else [] if route == 'bundle' else ['--no-bundle']) + if route == 'binary': flags += ['--emit-binary-nil'] + result = run([*base, *flags, '-o', output, source]) + if route != 'jit': + executable = output.with_suffix('.exe') if os.name == 'nt' and route in ('native', 'bundle') else output + command = [interpreter, '--no-ai', output] if route in ('text', 'binary') else [executable] + result = run(command) + assert result.stdout == 'checked WebView configuration failure\nchecked WebView event failure\n' + assert not result.stderr + print(f'WebView intrinsic ABI: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/webview_provider_fixture.cpp b/tests/webview_provider_fixture.cpp new file mode 100644 index 0000000..7aadf46 --- /dev/null +++ b/tests/webview_provider_fixture.cpp @@ -0,0 +1,89 @@ +/* Synthetic ABI peer, never a browser provider. SPDX-License-Identifier: MIT */ +#define NILWEBVIEW_PROVIDER_BUILD +#include "../common/webview_provider_v1.h" +#include +#include +#include + +struct nilwv_context_v1 { + bool open = false, event = false; + std::int64_t kind = NILWV_EVENT_READY, operation = 0; + std::string payload, detail, control; +}; +namespace { +std::atomic contexts{0}, releases{0}; +void ok(nilwv_result_v1 *r, std::int64_t value = 1) { *r = {sizeof(*r), 0, value, {nullptr, 0}}; } +void bad(nilwv_result_v1 *r) { static const char text[] = "synthetic invalid handle"; *r = {sizeof(*r), NILWV_E_HANDLE, 0, {text, sizeof(text)-1}}; } +void probe(nilwv_result_v1 *r) { ok(r); } +void create(nilwv_context_v1 **c, nilwv_result_v1 *r) { *c = new nilwv_context_v1; ++contexts; ok(r); } +void destroy(nilwv_context_v1 *c) { delete c; --contexts; } +void window(nilwv_context_v1 *c, nilwv_text_v1, std::int64_t, std::int64_t, nilwv_result_v1 *r) { + if (c->open) { bad(r); return; } + c->open = c->event = true; c->kind = NILWV_EVENT_READY; ok(r, 17); +} +void show(nilwv_context_v1 *c, std::int64_t w, nilwv_result_v1 *r) { if (c->open && w == 17) ok(r); else bad(r); } +void navigate(nilwv_context_v1 *c, std::int64_t w, nilwv_text_v1, nilwv_result_v1 *r) { + if (!c->open || w != 17) { bad(r); return; } + c->event = true; c->kind = NILWV_EVENT_NAVIGATION_COMPLETED; c->operation = 31; c->payload = "\"about:blank\""; ok(r, 31); +} +void script(nilwv_context_v1 *c, std::int64_t w, nilwv_text_v1 body, nilwv_result_v1 *r) { + if (!c->open || w != 17) { bad(r); return; } + c->event = true; c->kind = NILWV_EVENT_SCRIPT_COMPLETED; c->operation = 32; + const std::string value(body.data, body.size); + c->control = value; + c->payload = value == "bad-json" ? "{invalid" : "{\"answer\":42}"; + if (value == "surrogate") c->payload = "\"\\ud800\""; + if (value == "deep33" || value == "deep64" || value == "deep65") { + const auto depth = value == "deep33" ? 33 : value == "deep64" ? 64 : 65; + c->payload = std::string(depth, '[') + "0" + std::string(depth, ']'); + } + if (value == "bad-message") { c->kind = NILWV_EVENT_PAGE_MESSAGE; c->operation = 0; c->payload.clear(); } + c->detail = value == "bad-text" ? std::string("\xc0\xaf", 2) : ""; + ok(r, 32); +} +void poll(nilwv_context_v1 *c, std::int64_t w, nilwv_result_v1 *r) { + if (!c->open || w != 17) { bad(r); return; } ok(r, c->event ? 19 : 0); +} +void number(nilwv_context_v1 *c, std::int64_t e, nilwv_text_v1 property, nilwv_result_v1 *r) { + if (!c->event || e != 19) { bad(r); return; } + const std::string field(property.data, property.size); + if (field == "window") ok(r,17); + else if (field == "kind") ok(r,c->kind); + else if (field == "sequence") ok(r,1); + else if (field == "operation") ok(r,c->operation); + else if (field == "value_kind") ok(r,c->payload.empty() ? NILWV_VALUE_NONE : NILWV_VALUE_JSON); + else if (field == "source_kind") ok(r,c->control == "bad-origin" ? NILWV_SOURCE_NATIVE_ORIGIN : c->control == "bad-url" ? NILWV_SOURCE_NATIVE_URL : 0); + else if (field == "frame_kind") ok(r,c->control == "bad-frame" ? NILWV_FRAME_MAIN : 0); + else if (field == "failure_kind") ok(r,0); + else bad(r); +} +void text(nilwv_context_v1 *c, std::int64_t e, nilwv_text_v1 property, nilwv_result_v1 *r) { + if (!c->event || e != 19) { bad(r); return; } + const std::string field(property.data, property.size); + ok(r,0); + if (field == "payload_json") r->text = {c->payload.data(), c->payload.size()}; + else if (field == "detail") r->text = {c->detail.data(), c->detail.size()}; + else if (field != "source_url" && field != "source_origin") bad(r); +} +void release(nilwv_context_v1 *c, std::int64_t e, nilwv_result_v1 *r) { + if (!c->event || e != 19) { bad(r); return; } + c->event = false; c->payload.assign("released storage"); c->detail.assign("released storage"); ++releases; ok(r); +} +void close(nilwv_context_v1 *c, std::int64_t w, nilwv_result_v1 *r) { + if (!c->open || w != 17) { bad(r); return; } c->open = c->event = false; ok(r); +} +const nilwv_api_v1 api{ +#ifdef NILWV_FIXTURE_BAD_ABI + 2, +#else + NILWV_ABI_V1, +#endif + sizeof(nilwv_api_v1), 0, "synthetic", "test-only", probe, create, destroy, + window, show, navigate, navigate, script, poll, number, text, release, close}; +} +extern "C" NILWV_EXPORT const nilwv_api_v1 *NILWV_CALL +nilwebview_provider_v1_get_api(std::uint32_t version, std::uint32_t size) { + return version == NILWV_ABI_V1 && size <= sizeof(api) ? &api : nullptr; +} +extern "C" NILWV_EXPORT std::int64_t nilwebview_fixture_live_contexts() { return contexts; } +extern "C" NILWV_EXPORT std::int64_t nilwebview_fixture_releases() { return releases; } diff --git a/tests/webview_runtime_tests.cpp b/tests/webview_runtime_tests.cpp new file mode 100644 index 0000000..73aef30 --- /dev/null +++ b/tests/webview_runtime_tests.cpp @@ -0,0 +1,97 @@ +/* Checked provider ownership/ABI controls, no desktop. SPDX-License-Identifier: MIT */ +#include "webview_runtime.hpp" +#include +#include +#include +#include +extern "C" std::int64_t nilwebview_fixture_live_contexts(); +extern "C" std::int64_t nilwebview_fixture_releases(); +namespace { +int checks = 0; +void require(bool condition, const char *label) { + ++checks; + if (!condition) { std::cerr << "FAIL: " << label << '\n'; std::exit(1); } +} +} +int main(int argc, char **argv) { + if (argc != 3) return 2; + using ny::webview::Context; + { + Context a, b; + require(!a.window("unset", 640, 480), "unconfigured context"); + require(!a.configure("relative-provider"), "relative provider refused"); + require(!a.configure(argv[2]), "incompatible ABI refused"); + auto configured = a.configure(argv[1]); + require(configured && configured.number == 0, "zero capabilities is successful configuration"); + require(bool(a.configure(argv[1])), "same provider configuration is idempotent"); + require(!a.configure(argv[2]), "cannot switch an active provider"); + require(bool(b.configure(argv[1])), "independent context"); + require(nilwebview_fixture_live_contexts() == 2, "exact live contexts"); + require(!a.window("bad",0,480), "zero dimension rejected"); + require(!a.window(std::string("x\0y",3),640,480), "NUL title rejected"); + require(!a.window(std::string("\xc0\xaf",2),640,480), "invalid UTF-8 title rejected"); + auto wa = a.window("first",640,480), wb = b.window("second",640,480); + require(wa && wb && wa.number != wb.number, "context handles distinct despite repeated native handles"); + require(!a.show(wb.number) && !b.show(wa.number), "cross-context window handles refused"); + bool wrong_thread = false; + std::thread other([&] { wrong_thread = !a.show(wa.number); }); other.join(); + require(wrong_thread, "foreign thread rejected"); + require(bool(a.show(wa.number)), "same-thread operation"); + auto ready = a.poll(wa.number); + require(ready && ready.number > 0, "ready copied"); + require(a.event_number(ready.number,"window").number == wa.number, "native window translated"); + require(a.event_number(ready.number,"kind").number == 1, "event kind preserved"); + require(!a.event_number(ready.number,"unknown"), "unknown number field refused"); + require(!a.event_text(ready.number,"unknown"), "unknown text field refused"); + require(!b.event_number(ready.number,"kind"), "cross-context event handle refused"); + require(nilwebview_fixture_releases() == 1, "provider event released after copy"); + require(a.poll(wa.number).number == 0, "empty event queue"); + require(bool(a.release_event(ready.number)), "copied event released"); + require(!a.release_event(ready.number), "event cannot be released twice"); + require(!a.navigate(wa.number,std::string("x\0y",3)), "NUL operation input rejected"); + auto script = a.evaluate_function(wa.number,"return 42;"); + require(script && script.number == 32, "accepted operation identity"); + auto completed = a.poll(wa.number); + require(completed && completed.number > 0, "script event copied"); + require(a.event_number(completed.number,"operation").number == script.number, "completion identity preserved"); + require(a.event_text(completed.number,"payload_json").text == "{\"answer\":42}", "snapshot survives provider storage mutation"); + require(bool(a.close(wa.number)), "window closed"); + require(!a.event_text(completed.number,"payload_json"), "close invalidates retained snapshots"); + require(!a.close(wa.number) && !a.show(wa.number), "stale window refused"); + require(bool(b.show(wb.number)), "unrelated context remains live"); + a.clear(); b.clear(); + require(nilwebview_fixture_live_contexts() == 0, "explicit context teardown"); + require(bool(a.configure(argv[1])), "context can be reused after terminal cleanup"); + auto w = a.window("invalid-result",640,480); + auto first = a.poll(w.number); a.release_event(first.number); + require(bool(a.evaluate_function(w.number,"bad-json")), "synthetic malformed result accepted asynchronously"); + const auto before = nilwebview_fixture_releases(); + require(!a.poll(w.number), "invalid provider JSON refused"); + require(nilwebview_fixture_releases() == before+1, "malformed event released on error"); + require(!a.show(w.number), "provider protocol fault remains latched"); + a.clear(); + require(bool(a.configure(argv[1])), "teardown resets protocol fault"); + w = a.window("bad-text",640,480); first = a.poll(w.number); a.release_event(first.number); + a.evaluate_function(w.number,"bad-text"); + require(!a.poll(w.number), "invalid provider UTF-8 refused"); + for (const auto *invalid : {"bad-origin", "bad-url", "bad-frame", "bad-message", "deep65"}) { + a.clear(); a.configure(argv[1]); w = a.window("invalid-event",640,480); + first = a.poll(w.number); a.release_event(first.number); + a.evaluate_function(w.number,invalid); + const auto released_before = nilwebview_fixture_releases(); + require(!a.poll(w.number), "inconsistent provenance, event kind or depth refused"); + require(nilwebview_fixture_releases() == released_before+1, "invalid snapshot always released"); + } + for (const auto *valid : {"surrogate", "deep33", "deep64"}) { + a.clear(); a.configure(argv[1]); w = a.window("JSON-stringify-result",640,480); + first = a.poll(w.number); a.release_event(first.number); + a.evaluate_function(w.number,valid); + auto found = a.poll(w.number); + require(found && found.number > 0, "bounded JSON.stringify text preserved"); + if (std::string(valid) == "surrogate") + require(a.event_text(found.number,"payload_json").text == "\"\\ud800\"", "escaped lone surrogate remains serialized text"); + } + } + require(nilwebview_fixture_live_contexts() == 0, "destructor cleanup"); + std::cout << checks << " WebView runtime checks passed\n"; +}