docs
Loading...
Searching...
No Matches
API.h
Go to the documentation of this file.
1///
2/// Copyright (C) 2026 Ultralight, Inc. All rights reserved.
3/// A license is required for commercial use. https://ultralig.ht
4///
5#pragma once
6// X11's headers define None as a macro, which would break the None enumerators.
7#pragma push_macro("None")
8#undef None
9
10#include <Ultralight/CAPI/CAPI_JSAPI.h>
11#include <Ultralight/CAPI/CAPI_String.h>
14#include <Ultralight/RefPtr.h>
15#include <Ultralight/View.h>
16#include <Ultralight/detail/InjectionFilter.h>
18#include <Ultralight/js/Error.h>
21#include <Ultralight/js/Value.h>
22#include <Ultralight/js/detail/Binding.h>
23#include <Ultralight/js/detail/Json.h>
24#include <Ultralight/js/detail/Schema.h>
25
26#include <cstdint>
27#include <initializer_list>
28#include <optional>
29#include <string>
30#include <string_view>
31#include <tuple>
32#include <type_traits>
33#include <utility>
34
35namespace ultralight {
36namespace js {
37
38template <typename T>
39class ClassBuilder;
40
41///
42/// The flags for API::AttachTo() (the C++ form of ULJSAPIAttachFlags).
43///
44enum class AttachFlags : unsigned {
45 None = 0, ///< Main frame only, with frozen namespace objects.
46 AllFrames = 1u << 1, ///< Also add the bindings to subframes.
47 Mutable = 1u << 2, ///< Don't freeze the namespace objects, so page script (or
48 ///< Value::DeleteProperty()) can change or delete bindings (constants
49 ///< stay read-only and can't be deleted).
50};
51
52///
53/// Combine attach flags.
54///
55/// @return Returns the union of both flag sets.
56///
58 return static_cast<AttachFlags>(static_cast<unsigned>(a) | static_cast<unsigned>(b));
59}
60
61///
62/// Add attach flags to `a`.
63///
64/// @return Returns `a`.
65///
67 return a = a | b;
68}
69
70///
71/// Shorthand for AttachFlags::AllFrames.
72///
74
75///
76/// Shorthand for AttachFlags::Mutable.
77///
79
80static_assert(static_cast<unsigned>(AttachFlags::AllFrames) == kULJSAPIAttachFlags_AllFrames
81 && static_cast<unsigned>(AttachFlags::Mutable) == kULJSAPIAttachFlags_Mutable,
82 "js::AttachFlags must mirror ULJSAPIAttachFlags");
83
84///
85/// Options for API::AttachTo().
86///
87/// ```
88/// api.AttachTo(view.get(), { .flags = js::AllFrames,
89/// .origin_rules = { "https://*.mygame.com" } });
90/// ```
91///
93 ///
94 /// The attach flags (see AttachFlags).
95 ///
97
98 ///
99 /// The origin rules for the pages that get the bindings. Leave it empty for the default
100 /// policy (your application's own content). See ultralight::OriginRules.
101 ///
103};
104
105///
106/// The diagnostics levels for an API.
107///
108/// Diagnostics are development warnings, written to the native logger and to the page's
109/// console. Each level does everything the level below it does.
110///
111/// **Warn** reports mistakes that still run:
112///
113/// - **Typos**: reading a missing property of the API's namespace objects logs the closest
114/// existing name (`myApp.addd is not defined; did you mean add?`).
115/// - **Unknown events**: subscribing to or emitting an event the API never declared (checked
116/// once the API declares at least one event, see DefineEvent()).
117/// - **Lossy numbers**: a fractional or out-of-range argument truncated to an integer
118/// parameter, or a 64-bit integer return value that a JavaScript number can't hold exactly.
119/// - **Withheld bindings**: a page that the origin rules or the View's filter kept the
120/// bindings from.
121/// - **Reserved member names**: a member named `then`, `toJSON`, `constructor`, or
122/// `__proto__`, which changes how JavaScript treats the object.
123///
124/// **Strict** also turns two caller mistakes into TypeErrors:
125///
126/// - **A lossy numeric argument** (error code `ULJS_LOSSY`).
127/// - **More arguments than the binding declares** (error code `ULJS_EXTRA_ARGS`). A callable
128/// that takes a CallInfo is exempt, since it reads the raw argument list.
129///
130/// A lossy return value still only warns, since the page can't fix a native return type.
131///
132/// **Auto** (the default) uses the JavaScript level in Config::diagnostics, which is Warn in
133/// developer mode and Off otherwise (see DiagnosticsConfig).
134///
135/// Two warnings follow the Config's JavaScript level instead: an operation on a handle whose
136/// page is gone, and a JavaScript exception that nothing read. Mistakes found once at
137/// registration (an invalid or reserved root path, an invalid binding path, a missing callback)
138/// always warn, whatever the level.
139///
140/// \parblock
141/// @note Warn and Strict make property reads on the API's namespace objects slower, and
142/// attaching the API to a View also attaches the library's `ul.diagnostics` API.
143/// \endparblock
144///
145/// \parblock
146/// @note The UL_JS_DIAGNOSTICS environment variable ("off", "warn", or "strict", any case,
147/// read once per process) overrides the level of every API while developer mode is on,
148/// so you can switch diagnostics without recompiling.
149/// \endparblock
150///
152
153///
154/// Options for creating an API.
155///
156/// ```
157/// js::API api("myApp", { .diagnostics = js::Diagnostics::Strict });
158/// ```
159///
161 ///
162 /// The diagnostics level.
163 ///
164 /// Diagnostics::Auto uses the JavaScript level in Config::diagnostics, so you can switch
165 /// every API from one place.
166 ///
167 Diagnostics diagnostics = Diagnostics::Auto;
168};
169
170///
171/// A parameter name for a registration (shown in API::schema() and in error messages).
172///
173/// API::Bind(), API::DefineEvent(), ClassBuilder::Method(), and ClassBuilder::StaticMethod()
174/// accept these after the callable. Name every parameter (except a CallInfo or js::Resolver) or
175/// none. The text is read during the call, so it doesn't need to outlive it.
176///
177/// ```
178/// api.Bind("setConfig", [](double volume, bool muted) { ... },
179/// js::Param("volume"), js::Param("muted"));
180/// ```
181///
182/// A wrong call from the page then reports the names:
183///
184/// ```
185/// myApp.setConfig('loud', true);
186/// // TypeError: myApp.setConfig(volume: number, muted: boolean): argument 1 (volume):
187/// // expected number, got 'loud'
188/// ```
189///
190/// \parblock
191/// @note The assignment form (`api["x"] = fn`) takes no annotations. Use Bind() to add them.
192/// \endparblock
193///
194/// \parblock
195/// @note Don't confuse this with js::Arg, which is an argument value a callback reads.
196/// \endparblock
197///
198/// @see js::Doc
199///
200struct Param {
201 ///
202 /// The parameter name.
203 ///
204 const char* name;
205
206 ///
207 /// Create a parameter name annotation.
208 ///
209 /// @param declared_name The parameter name (NULL becomes an empty name).
210 ///
211 constexpr explicit Param(const char* declared_name)
212 : name(declared_name ? declared_name : "") {}
213};
214
215///
216/// A documentation string for a registration (shown in API::schema()).
217///
218/// The text becomes the entry's `doc` field in API::schema(). Pass at most one, to the same calls
219/// that take js::Param. The text is read during the call, so it doesn't need to outlive it.
220///
221/// ```
222/// api.Bind("save", &SaveGame, js::Doc("Saves the current session to disk."));
223/// ```
224///
225struct Doc {
226 ///
227 /// The documentation text.
228 ///
229 const char* text;
230
231 ///
232 /// Create a documentation annotation.
233 ///
234 /// @param doc_text The documentation text.
235 ///
236 constexpr explicit Doc(const char* doc_text) : text(doc_text) {}
237};
238
239namespace detail {
240
241// The trailing annotation pack accepted by the explicit registration forms. A concept
242// (rather than accepting anything) keeps receiver overloads unambiguous.
243template <typename A>
244concept Annotation = std::is_same_v<std::remove_cvref_t<A>, Param>
245 || std::is_same_v<std::remove_cvref_t<A>, Doc>;
246
247template <typename... Anns>
248inline constexpr size_t kArgAnnotationCount
249 = ((std::is_same_v<std::remove_cvref_t<Anns>, Param> ? size_t { 1 } : size_t { 0 }) + ...
250 + size_t { 0 });
251
252template <typename... Anns>
253inline constexpr size_t kDocAnnotationCount
254 = ((std::is_same_v<std::remove_cvref_t<Anns>, Doc> ? size_t { 1 } : size_t { 0 }) + ...
255 + size_t { 0 });
256
257inline void CollectAnnotation(AnnotationSet& set, const Param& annotation) {
258 if (set.name_count < AnnotationSet::kMaxNames)
259 set.names[set.name_count++] = annotation.name;
260}
261
262inline void CollectAnnotation(AnnotationSet& set, const Doc& annotation) {
263 set.doc = annotation.text;
264}
265
266template <typename... Anns>
267AnnotationSet CollectAnnotations(const Anns&... annotations) {
268 AnnotationSet set;
269 (CollectAnnotation(set, annotations), ...);
270 return set;
271}
272
273} // namespace detail
274
275///
276/// A global JavaScript namespace for native functions and data.
277///
278/// A js::API gives page scripts access to your application's functions and data, much like browsers
279/// add built-in Web APIs such as `console` and `document` on top of core JavaScript.
280///
281/// Once attached to a View, the API provides its global namespace to your pages.
282///
283/// Define an API with a constant and a function, attach it to a View, and load a page:
284///
285/// ```
286/// js::API app("app");
287/// app["version"] = "2.1.0";
288/// app["add"] = [](double a, double b) { return a + b; };
289///
290/// if (app.AttachTo(view.get()))
291/// view->LoadURL("file:///app.html");
292/// ```
293///
294/// Page script accesses the namespace on `window`:
295///
296/// ```js
297/// console.log(app.version); // "2.1.0"
298/// app.add(2, 3); // 5
299/// ```
300///
301/// ## Binding Functions and Values
302///
303/// The C++ type you bind decides what the page gets:
304///
305/// | Binding | What the Page Gets |
306/// |-------------------|--------------------------------|
307/// | Callable | Function |
308/// | Plain value | Read-only constant |
309/// | Getter and setter | Live property |
310/// | Async callable | Function returning a Promise |
311/// | Bound class | Class constructible with `new` |
312///
313/// A dot in a path string (such as `"fs.readFile"`) creates a child namespace object on the page.
314///
315/// Bind nested paths using dot notation and live properties using getters and setters:
316///
317/// ```
318/// app["fs.readFile"] = [](std::string path) { return ReadFile(path); };
319/// app.BindProperty("volume", [] { return g_volume; },
320/// [](double v) { g_volume = v; });
321/// ```
322///
323/// ## Attaching to a View
324///
325/// Call AttachTo() with a View before loading content. Every page the View loads from then on gets
326/// the API automatically, so you don't need to attach again after a navigation.
327///
328/// If you add, replace, or remove bindings after a page is loaded, that page keeps its current
329/// bindings until its next navigation. To adjust frame scope or mutability, pass AttachOptions to
330/// AttachTo() (see AttachFlags).
331///
332/// ## Allowed Pages and Origin Rules
333///
334/// By default, only local `file://` pages and content loaded with View::LoadHTML() get the API.
335///
336/// Passing origin rules replaces the default policy completely. Only pages matching your rules get
337/// the API, so you must include `"file://*"` if you want local pages to retain access (see
338/// ultralight::OriginRules). For decisions origin rules can't express (such as checking a user
339/// setting at runtime), set a callback with js::SetInjectionFilter() to allow or withhold the API
340/// per page.
341///
342/// Specify origin rules in AttachOptions to allow a local development server alongside local pages:
343///
344/// ```
345/// // A local development server, plus your local pages:
346/// if (app.AttachTo(view.get(),
347/// { .origin_rules = { "http://localhost:*", "file://*" } }))
348/// view->LoadURL("http://localhost:5173/");
349/// ```
350///
351/// ## Emitting Events
352///
353/// Native code can push events to attached pages without polling. Events are delivered on the
354/// Renderer's thread during a later Renderer::Update().
355///
356/// Call Emit() from any thread with an event name and payload arguments:
357///
358/// ```
359/// app.Emit("saved", std::string("slot1.dat"));
360/// ```
361///
362/// Subscribe on the page using on() or once(), and remove listeners with off():
363///
364/// ```js
365/// app.on("saved", (path) => refreshList(path));
366/// ```
367///
368/// ## Managing API Lifetime
369///
370/// A View keeps an API attached only while the js::API instance exists. Destroying the js::API
371/// detaches it from every View. Events stop reaching pages, and any calls to bound functions or
372/// class constructors that a page still holds throw a TypeError with code `ULJS_DETACHED`.
373///
374/// Hold the API as a class member to tie its lifetime to an owner and bind member functions with
375/// js::Bind():
376///
377/// ```
378/// class Game {
379/// public:
380/// explicit Game(View* view) {
381/// api_["showMenu"] = js::Bind(this, &Game::ShowMenu);
382/// if (api_.AttachTo(view))
383/// view->LoadURL("file:///app.html");
384/// }
385///
386/// void ShowMenu();
387///
388/// private:
389/// js::API api_{"app"}; // detaches from every View when the Game goes away
390/// };
391/// ```
392///
393/// @note Once an API is attached to a View, you must bind and unbind only on the Renderer's
394/// thread.
395///
396/// @see ultralight::OriginRules, js::SetInjectionFilter(), js::BindingGuard, js::ClassBuilder,
397/// js::TypeTraits, js::Diagnostics
398///
399class API {
400 public:
401 ///
402 /// Create an API rooted at a global namespace path.
403 ///
404 /// @param root_path The dot-separated namespace path (eg, "myApp" or "myApp.native"). Every
405 /// segment must be non-empty. The roots `ul` and `ultralight` (and every
406 /// path under them) are reserved for the library.
407 ///
408 /// @param options The creation options (see APIOptions).
409 ///
410 /// @note An invalid or reserved `root_path` creates an empty API (`operator bool` returns
411 /// false) and logs a warning saying why.
412 ///
413 explicit API(const char* root_path, const APIOptions& options = {})
414 : root_(root_path ? root_path : ""), api_(ulCreateJSAPI(root_path)) {
415 if (api_ && options.diagnostics != Diagnostics::Auto)
416 ulJSAPISetDiagnostics(api_, static_cast<ULJSDiagnosticsLevel>(options.diagnostics));
417 }
418
419 ///
420 /// Destructor (releases this handle).
421 ///
422 /// @note Destroying the API detaches it from every View (see Managing API Lifetime in the class
423 /// overview), unless it came from FromBorrowed() or another owning handle to it exists.
424 ///
425 ~API() { ulDestroyJSAPI(api_); }
426
427 ///
428 /// Move constructor (`other` becomes empty).
429 ///
430 API(API&& other) noexcept : root_(std::move(other.root_)), api_(other.api_) {
431 other.api_ = nullptr;
432 }
433
434 ///
435 /// Move assignment (releases the current handle, and `other` becomes empty).
436 ///
437 API& operator=(API&& other) noexcept {
438 if (this != &other) {
439 ulDestroyJSAPI(api_);
440 root_ = std::move(other.root_);
441 api_ = other.api_;
442 other.api_ = nullptr;
443 }
444 return *this;
445 }
446 API(const API&) = delete;
447 API& operator=(const API&) = delete;
448
449 // --- Interop with the C API (most embedders never touch raw handles) -------------------
450
451 ///
452 /// Wrap a handle you own from the C API, taking ownership of it (eg, the result of
453 /// ulCreateJSAPI()).
454 ///
455 /// @param api The handle to take ownership of.
456 ///
457 /// @return Returns an API that owns `api`.
458 ///
459 /// @note For a handle someone else owns, use FromBorrowed().
460 ///
461 static API Adopt(ULJSAPI api) { return API(api); }
462
463 ///
464 /// Wrap a handle someone else owns, without owning the API (eg, the `api` member of a
465 /// js::InjectionRequest).
466 ///
467 /// The result works like any API, but destroying it never detaches the API, and it doesn't
468 /// keep the API attached once its owners are gone.
469 ///
470 /// @param api The borrowed handle.
471 ///
472 /// @return Returns an API with its own (non-owning) reference to `api`. Its raw() is a
473 /// different handle than `api`.
474 ///
475 /// @note For a handle you own, use Adopt().
476 ///
477 static API FromBorrowed(ULJSAPI api) { return API(ulCreateJSAPIBorrowedRef(api)); }
478
479 ///
480 /// Whether or not this API holds a handle (false if the root path was invalid or reserved, and
481 /// after a move or LeakRef()).
482 ///
483 explicit operator bool() const { return api_ != nullptr; }
484
485 ///
486 /// The assignable path that operator[] returns (see Binding Functions and Values in the class
487 /// overview).
488 ///
489 /// @warning Use a Binder only in the expression that created it (`api["path"] = ...`). It
490 /// can't be copied, and a named Binder can't bind, since the API could move or be
491 /// destroyed while you hold it. Keep the path string instead.
492 ///
493 class Binder {
494 public:
495 Binder(const Binder&) = delete;
496 Binder& operator=(const Binder&) = delete;
497
498 ///
499 /// Bind a callable or value at this path (the type of `rhs` decides what's bound, see Binding
500 /// Functions and Values in the API class overview).
501 ///
502 /// @param rhs The callable or value to bind.
503 ///
504 /// @return Returns this Binder.
505 ///
506 template <typename T>
507 Binder& operator=(T&& rhs) && {
508 using U = std::decay_t<T>;
509 if constexpr (detail::IsIntrospectableCallable<U>::value) {
510 api_->Bind(path_.c_str(), std::forward<T>(rhs));
511 } else if constexpr (Holder<U>) {
512 // A holder of a bound class exposes the INSTANCE: a read-only live property whose
513 // every read returns the instance's wrapper (one wrapper per page, so `===` holds).
515 "an exclusive holder cannot back a live instance binding (every page "
516 "read needs its own stake): bind a shared holder such as RefPtr<T>, "
517 "std::shared_ptr<T>, or js::Eternal<T>");
518 static_assert(Marshalable<U>,
519 "bind the class first: include <Ultralight/js/Class.h> and call "
520 "DefineClass<T>() before exposing an instance of it");
521 api_->BindProperty(path_.c_str(), [value = U(std::forward<T>(rhs))] { return value; });
522 } else if constexpr (LockableHolder<U>) {
523 static_assert(detail::kAlwaysFalse<U>,
524 "a weak holder cannot back a live instance binding (every page read "
525 "needs a strong ownership stake): bind a shared holder such as "
526 "RefPtr<T>, or bind a method with js::Bind(weak, &T::Method)");
527 } else if constexpr (std::is_null_pointer_v<U>) {
528 static_assert(detail::kAlwaysFalse<U>,
529 "nullptr is not a JavaScript value: use js::null for a JavaScript null");
530 } else if constexpr (detail::kIsJsonConstant<U>
531 || std::is_convertible_v<U, std::string_view>) {
532 api_->SetConstant(path_.c_str(), std::forward<T>(rhs));
533 } else if constexpr (Marshalable<U>) {
534 static_assert(detail::kAlwaysFalse<U>,
535 "this type cannot be a constant: constants are serialized to JSON "
536 "once at registration (no live context exists yet), and JSON cannot "
537 "represent it. Bind a function or property instead (js::undefined "
538 "has no JSON form; use js::null)");
539 } else {
540 static_assert(detail::kAlwaysFalse<U>,
541 "this value can be neither bound nor stored as a constant. Callables "
542 "must have exactly one non-template operator() (generic lambdas with "
543 "'auto' parameters cannot be introspected); constants must be one of "
544 "the JSON-serializable types (see API::SetConstant())");
545 }
546 return *this;
547 }
548
549 ///
550 /// Get the Binder for a child path (`api["fs"]["readFile"]` is `api["fs.readFile"]`).
551 ///
552 /// @param segment The child path segment.
553 ///
554 /// @return Returns the Binder for the combined path.
555 ///
556 Binder operator[](const char* segment) && {
557 return Binder(api_, path_ + "." + (segment ? segment : ""));
558 }
559
560 ///
561 /// Bind a property with a getter (and optional setter) at this path (see
562 /// API::BindProperty()):
563 ///
564 /// ```
565 /// api["player"]["health"].BindProperty([&] { return player.health; });
566 /// ```
567 ///
568 /// @param get The getter, called on every JavaScript read.
569 ///
570 /// @param set The setter, or nullptr for a read-only property.
571 ///
572 /// @note Assigning a callable always binds a function the page calls with parentheses,
573 /// even one that takes no arguments. Use this to bind a property instead.
574 ///
575 template <typename Getter, typename Setter = std::nullptr_t>
576 void BindProperty(Getter&& get, Setter&& set = nullptr) && {
577 api_->BindProperty(path_.c_str(), std::forward<Getter>(get),
578 std::forward<Setter>(set));
579 }
580
581 private:
582 friend class API;
583 Binder(API* api, std::string path) : api_(api), path_(std::move(path)) {}
584 API* api_;
585 std::string path_;
586 };
587
588 ///
589 /// Get the Binder for a path relative to the root (see Binder).
590 ///
591 /// @param path The dot-separated path (eg, "greet" or "fs.readFile").
592 ///
593 /// @return Returns the Binder for `path`.
594 ///
595 Binder operator[](const char* path) { return Binder(this, path ? path : ""); }
596
597 ///
598 /// Bind a callable at a path (the explicit form of `api[path] = fn`, which also takes
599 /// annotations).
600 ///
601 /// @param path The dot-separated path relative to the root (eg, "fs.readFile").
602 ///
603 /// @param fn The callable to bind (see Binding Functions and Values in the class
604 /// overview).
605 ///
606 /// @param annotations Optional js::Param names (one per parameter, or none) and at most one
607 /// js::Doc.
608 ///
609 /// @note Binding a path that's already bound replaces the old binding and removes the path's
610 /// metadata (so call SetMetadata() after binding).
611 ///
612 template <typename Fn, typename... Anns>
613 requires(detail::Annotation<Anns> && ...)
614 void Bind(const char* path, Fn&& fn, const Anns&... annotations) {
615 using F = std::decay_t<Fn>;
616 using Traits = detail::CallableTraits<F>;
617 using Shape = detail::ParamShape<typename Traits::Params>;
618 using R = typename Traits::Return;
619
620 [&]<size_t... Is>(std::index_sequence<Is...>) {
621 (detail::ValidateParam<std::tuple_element_t<Is, typename Shape::Converted>>(), ...);
622 }(std::make_index_sequence<Shape::kCount> {});
623 constexpr size_t kNames = detail::kArgAnnotationCount<Anns...>;
624 static_assert(kNames == 0 || kNames == Shape::kCount,
625 "js::Param annotations must name every payload parameter or none (one "
626 "Param per converted parameter; CallInfo and Resolver take no name)");
627 static_assert(detail::kDocAnnotationCount<Anns...> <= 1,
628 "at most one js::Doc annotation per registration");
629
630 detail::AnnotationSet set = detail::CollectAnnotations(annotations...);
631 auto* bound
632 = new detail::BoundCallable<F> { std::forward<Fn>(fn), FullPath(path), {}, {} };
633 bound->display
634 = bound->path + detail::RenderSignature<typename Shape::Converted>(set);
635 bound->names.assign(set.names, set.names + set.name_count);
636 if constexpr (detail::HasSettableBoundPath<F>)
637 bound->fn.SetBoundPath(bound->path);
638 bool bound_ok;
639 if constexpr (Shape::kHasResolver || detail::kIsAsyncReturn<R>) {
640 bound_ok = ulJSAPIBindAsyncFunction(api_, path, &detail::AsyncTrampoline<F>, bound,
641 &detail::DestroyBoundCallable<F>);
642 } else {
643 bound_ok = ulJSAPIBindFunction(api_, path, &detail::SyncTrampoline<F>, bound,
644 &detail::DestroyBoundCallable<F>);
645 }
646 if (!bound_ok)
647 return;
648
649 detail::SchemaShapes shapes;
650 std::string fragment
651 = detail::BuildCallableFragment<typename Shape::Converted, R, Shape::kHasResolver>(
652 shapes, set);
653 ulJSAPISetMetadata(api_, path, fragment.c_str());
654 detail::EmitSchemaShapes(api_, shapes);
655 }
656
657 ///
658 /// Bind a member function of an object at a path (the same as binding
659 /// `js::Bind(receiver, method)`):
660 ///
661 /// ```
662 /// api.Bind("save", this, &App::OnSave);
663 /// ```
664 ///
665 /// @param path The dot-separated path relative to the root (eg, "fs.readFile").
666 ///
667 /// @param receiver The object to call `method` on. It must outlive every call through the
668 /// binding.
669 ///
670 /// @param method The member function pointer.
671 ///
672 /// @param annotations Optional js::Param names (one per parameter, or none) and at most one
673 /// js::Doc.
674 ///
675 /// @note To have the binding keep the object alive, bind `js::Bind(holder, method)` with a
676 /// shared holder instead.
677 ///
678 template <typename T, typename M, typename... Anns>
679 requires(std::is_member_function_pointer_v<M> && (detail::Annotation<Anns> && ...))
680 void Bind(const char* path, T* receiver, M method, const Anns&... annotations) {
681 Bind(path, detail::MakeBoundMethod(receiver, method, detail::MemberFnTraits<M> {}),
682 annotations...);
683 }
684
685 ///
686 /// Set a constant at a path (the explicit form of `api[path] = value`).
687 ///
688 /// The value is copied when you call this, and every page gets that copy. Changing your C++
689 /// value later doesn't change the constant (use BindProperty() for a live value). Page script
690 /// can't modify a constant, and objects and arrays in it are frozen too.
691 ///
692 /// @param path The dot-separated path relative to the root.
693 ///
694 /// @param value The value (see the supported types below).
695 ///
696 /// \parblock
697 /// @note Constants support the JSON-serializable types: numbers, booleans, strings, js::null,
698 /// std::optional, std::vector, std::map<std::string, T>, and (when
699 /// ULTRALIGHT_REFLECTION is 1) enums and plain aggregate structs of these.
700 /// js::undefined has no JSON form, so use js::null instead.
701 /// \endparblock
702 ///
703 /// \parblock
704 /// @note Structs convert field by field, so a custom js::TypeTraits specialization doesn't
705 /// apply to a constant. Bind a function or property for a custom conversion.
706 /// \endparblock
707 ///
708 /// \parblock
709 /// @note A null `const char*` binds `null` (and logs a diagnostics warning). For `null` on
710 /// purpose, pass js::null.
711 /// \endparblock
712 ///
713 template <typename T>
714 void SetConstant(const char* path, T&& value) {
715 using U = std::decay_t<T>;
716 if constexpr (std::is_same_v<U, const char*> || std::is_same_v<U, char*>) {
717 if (!value) {
718 ulJSAPISetConstantJSON(api_, path, "null");
719 if (ulJSAPIGetDiagnostics(api_) >= kULJSDiagnostics_Warn) {
720 std::string message = FullPath(path)
721 + ": the constant's string is a null pointer, so it was bound as null.";
722 ulJSAPIEmitDiagnostic(nullptr, message.c_str());
723 }
724 return;
725 }
726 }
727 if constexpr (std::is_null_pointer_v<U>) {
728 static_assert(detail::kAlwaysFalse<U>,
729 "nullptr is not a JavaScript value: use js::null for a JavaScript null");
730 } else if constexpr (std::is_same_v<U, bool>) {
731 ulJSAPISetConstantBoolean(api_, path, value);
732 } else if constexpr (std::is_arithmetic_v<U>) {
733 bool set = ulJSAPISetConstantNumber(api_, path, static_cast<double>(value));
734 // The generated constant entry says "number"; an integral C++ source refines it.
735 if constexpr (std::is_integral_v<U>) {
736 if (set)
737 ulJSAPISetMetadata(api_, path, "{\"type\":\"integer\"}");
738 }
739 } else if constexpr (std::is_convertible_v<U, std::string_view>) {
740 std::string text { std::string_view(value) };
741 ulJSAPISetConstantString(api_, path, text.c_str());
742 } else {
743 std::string json;
744 detail::WriteJson(json, value);
745 bool set = ulJSAPISetConstantJSON(api_, path, json.c_str());
746 // A JSON constant's generated entry carries the parsed value but no type; the typed
747 // layer knows it (js::null stays untyped: "null" is not a schema expression).
748 if constexpr (!std::is_same_v<U, NullType>) {
749 if (!set)
750 return;
751 detail::SchemaShapes shapes;
752 std::string fragment = detail::BuildTypeFragment<U>(shapes);
753 ulJSAPISetMetadata(api_, path, fragment.c_str());
754 detail::EmitSchemaShapes(api_, shapes);
755 }
756 }
757 }
758
759 ///
760 /// Define a native class at a path, so page script can call its methods, read its properties,
761 /// and construct it with `new` (when you declare a constructor).
762 ///
763 /// ```
764 /// api.DefineClass<Database>("Database")
765 /// .Constructor<std::string>()
766 /// .Method("query", &Database::Query);
767 /// ```
768 ///
769 /// @param path The dot-separated path relative to the root. The first DefineClass() for a
770 /// type also takes the JavaScript class name from the last path segment
771 /// ("db.Database" gives a class called "Database").
772 ///
773 /// @return Returns the builder to declare members on. The class is registered when the
774 /// builder goes out of scope (normally at the end of the statement).
775 ///
776 /// @note Requires `<Ultralight/js/Class.h>`. A type binds to one class for the life of the
777 /// process, so a later DefineClass() for the same type reuses that class and its
778 /// members (see ClassBuilder).
779 ///
780 /// @see ClassBuilder
781 ///
782 template <typename T>
783 ClassBuilder<T> DefineClass(const char* path);
784
785 ///
786 /// Bind a property with a getter and an optional setter.
787 ///
788 /// Unlike a constant, the property is live: every JavaScript read calls `get`, and every
789 /// assignment calls `set`.
790 ///
791 /// ```
792 /// api.BindProperty("volume", [] { return g_volume; },
793 /// [](double v) { g_volume = v; });
794 /// // Page: myApp.volume -> calls the getter
795 /// // myApp.volume = 0.5 -> calls the setter
796 /// ```
797 ///
798 /// @param path The dot-separated path relative to the root.
799 ///
800 /// @param get The getter. It takes no parameters and returns a type js::TypeTraits
801 /// converts, or a js::Result<T> to throw an error into the page.
802 ///
803 /// @param set The setter, which takes one parameter of a type js::TypeTraits converts
804 /// (return a js::Result<void> to reject the assignment with an error). Pass
805 /// nullptr for a read-only property: assigning to it then throws in strict-mode
806 /// code and does nothing otherwise.
807 ///
808 /// @note Assigning a value of the wrong type throws the standard TypeError, and the setter
809 /// isn't called.
810 ///
811 template <typename Getter, typename Setter = std::nullptr_t>
812 void BindProperty(const char* path, Getter&& get, Setter&& set = nullptr) {
813 using G = std::decay_t<Getter>;
814 using GTraits = detail::CallableTraits<G>;
815 static_assert(std::tuple_size_v<typename GTraits::Params> == 0,
816 "a property getter takes no parameters");
817 static_assert(!std::is_void_v<typename GTraits::Return>,
818 "a property getter must return a value (a Marshalable type or "
819 "js::Result<T>)");
820 if constexpr (std::is_same_v<std::decay_t<Setter>, std::nullptr_t>) {
821 struct ReadOnly {
822 void operator()() const {}
823 };
824 using Bound = detail::BoundProperty<G, ReadOnly>;
825 auto* bound = new Bound { std::forward<Getter>(get), ReadOnly {}, FullPath(path) };
826 if constexpr (detail::HasSettableBoundPath<G>)
827 bound->get.SetBoundPath(bound->path);
828 if (!ulJSAPIBindProperty(api_, path, &detail::PropertyGetterThunk<Bound>, nullptr, bound,
829 &detail::DestroyBoundProperty<Bound>))
830 return;
831 } else {
832 using S = std::decay_t<Setter>;
833 using Bound = detail::BoundProperty<G, S>;
834 auto* bound = new Bound { std::forward<Getter>(get), std::forward<Setter>(set),
835 FullPath(path) };
836 if constexpr (detail::HasSettableBoundPath<G>)
837 bound->get.SetBoundPath(bound->path);
838 if constexpr (detail::HasSettableBoundPath<S>)
839 bound->set.SetBoundPath(bound->path);
840 if (!ulJSAPIBindProperty(api_, path, &detail::PropertyGetterThunk<Bound>,
841 &detail::PropertySetterThunk<Bound>, bound,
842 &detail::DestroyBoundProperty<Bound>))
843 return;
844 }
845
846 detail::SchemaShapes shapes;
847 std::string fragment = detail::BuildTypeFragment<typename GTraits::Return>(shapes);
848 ulJSAPISetMetadata(api_, path, fragment.c_str());
849 detail::EmitSchemaShapes(api_, shapes);
850 }
851
852 ///
853 /// Emit an event to the page listeners subscribed with `on` or `once` (see Emitting Events in
854 /// the class overview).
855 ///
856 /// ```
857 /// api.Emit("saved", std::string("slot1.dat"));
858 /// // Page: myApp.on('saved', (path) => { ... });
859 /// ```
860 ///
861 /// @param event_path The event path relative to the root (eg, "saved" or "fs.changed").
862 /// A page can subscribe to "fs.changed" on the root with the full path
863 /// (`myApp.on('fs.changed', fn)`), or as `myApp.fs.on('changed', fn)`
864 /// when something is bound under `fs` (only then does `myApp.fs` exist).
865 ///
866 /// @param args Up to 16 argument values of types js::TypeTraits converts.
867 ///
868 /// \parblock
869 /// @note Safe to call from any thread. The arguments are copied here (strings included), so
870 /// nothing you pass needs to outlive the call.
871 /// \endparblock
872 ///
873 /// \parblock
874 /// @note The event is delivered later, on the Renderer's thread: during a later
875 /// Renderer::Update(), the listeners run once in each page that had the bindings when
876 /// you called Emit() (each frame, for an API attached with AllFrames).
877 /// \endparblock
878 ///
879 /// @see dom::Element::dispatchEvent()
880 ///
881 template <typename... Args>
883 void Emit(const char* event_path, Args&&... args) {
884 static_assert(sizeof...(Args) <= 16, "events support at most 16 arguments");
885 static_assert((!detail::kIsClassInstancePointer<Args> && ...),
886 "a raw instance pointer cannot cross a deferred boundary (delivery "
887 "happens later, on the Renderer's thread): capture an owning holder (the "
888 "class's canonical holder) or js::Eternal<T> instead");
889 static_assert((!detail::IsCallScopedView<std::decay_t<Args>>::value && ...),
890 "a std::span cannot cross a deferred boundary (delivery happens later; "
891 "the view would dangle): copy into a std::vector<E> or RefPtr<Buffer>");
892 static_assert((!std::is_base_of_v<Value, std::decay_t<Args>> && ...),
893 "a js::Value cannot be emitted (Emit delivers to every attached page, and "
894 "a value belongs to one page): emit native values instead, such as "
895 "numbers, strings, containers, or structs. A js::ArrayBuffer or "
896 "js::TypedArray from the page can't be emitted either: emit a "
897 "RefPtr<Buffer> or the bytes (eg, a std::vector<uint8_t>)");
898 using Payload = std::tuple<detail::CapturedArg<Args>...>;
899 auto* payload = new Payload(detail::CaptureArg(std::forward<Args>(args))...);
900 ulJSAPIEmitEvent(api_, event_path, &detail::EmitArgsThunk<Payload>, payload,
901 &detail::DeleteEmitPayload<Payload>);
902 }
903
904 ///
905 /// Declare an event and its payload types.
906 ///
907 /// Declared events appear in schema(), and the generated TypeScript declarations give them
908 /// typed `on`, `once`, and `off` overloads. The declaration only describes the event, so Emit()
909 /// doesn't check its arguments against the declared types.
910 ///
911 /// ```
912 /// api.DefineEvent<std::string>("saved", js::Param("path"), js::Doc("A save finished."));
913 /// api.Emit("saved", path); // Page: myApp.on('saved', (path) => ...)
914 /// ```
915 ///
916 /// @param event_path The event path relative to the root, in the form Emit() takes.
917 ///
918 /// @param annotations Optional js::Param names (one per payload type, or none) and at most
919 /// one js::Doc.
920 ///
921 /// \parblock
922 /// @note Once an API declares an event, diagnostics (Warn and Strict) warn about every
923 /// subscription and every Emit() for an event it didn't declare. You should declare
924 /// every event the API emits.
925 /// \endparblock
926 ///
927 /// \parblock
928 /// @note Declaring an event again replaces its payload types. Declarations are permanent
929 /// (Unbind() never removes them).
930 /// \endparblock
931 ///
932 /// \parblock
933 /// @note This follows the registration thread rules (see the class overview).
934 /// \endparblock
935 ///
936 template <typename... Args, typename... Anns>
937 requires(detail::Annotation<Anns> && ...)
938 void DefineEvent(const char* event_path, const Anns&... annotations) {
939 static_assert(sizeof...(Args) <= 16, "events support at most 16 arguments");
940 static_assert((Marshalable<std::remove_cvref_t<Args>> && ...),
941 "an event payload type has no js::TypeTraits: use a supported built-in, "
942 "make it a plain aggregate struct, or specialize js::TypeTraits for it");
943 constexpr size_t kNames = detail::kArgAnnotationCount<Anns...>;
944 static_assert(kNames == 0 || kNames == sizeof...(Args),
945 "js::Param annotations must name every event parameter or none");
946 static_assert(detail::kDocAnnotationCount<Anns...> <= 1,
947 "at most one js::Doc annotation per registration");
948 detail::AnnotationSet set = detail::CollectAnnotations(annotations...);
949 detail::SchemaShapes shapes;
950 std::string fragment = detail::BuildEventFragment<Args...>(shapes, set, event_path);
951 ulJSAPISetMetadata(api_, "", fragment.c_str());
952 detail::EmitSchemaShapes(api_, shapes);
953 }
954
955 ///
956 /// Remove the binding at a path, along with its metadata.
957 ///
958 /// Pages see the removal at their next navigation. A page that's already loaded (or restored
959 /// from the back-forward cache) keeps the binding, and functions the page got from it keep
960 /// working. A js::Task one of them already started finishes normally. The library destroys
961 /// the bound callable once the last of those functions and Tasks is gone (right away if
962 /// there's none).
963 ///
964 /// To also remove the binding from a loaded page attached with js::Mutable, delete the
965 /// property there with Value::DeleteProperty() (this doesn't work for a constant, or on a page
966 /// attached without js::Mutable, since those bindings can't be deleted).
967 ///
968 /// To tie a binding to a C++ object's lifetime instead, see js::BindingGuard.
969 ///
970 /// @param path The binding's path relative to the root, as you bound it.
971 ///
972 /// @return Returns whether a binding or metadata entry was removed (false for an empty path
973 /// or a path with neither). You can ignore it, since removing an absent path is
974 /// harmless.
975 ///
976 /// \parblock
977 /// @note Event declarations and root metadata (the top-level `meta`, `events`, and `types`
978 /// sections) are never removed.
979 /// \endparblock
980 ///
981 /// \parblock
982 /// @note This follows the registration thread rules (see the class overview).
983 /// \endparblock
984 ///
985 bool Unbind(const char* path) { return ulJSAPIUnbind(api_, path); }
986
987 ///
988 /// Get the API's schema as JSON.
989 ///
990 /// The JSON has a `format` ("ul-schema"), an `api` ("js"), and a `version`, then an entry for
991 /// each binding with its parameter and return types, the named types they use, and the
992 /// metadata you added (js::Param, js::Doc, and SetMetadata()).
993 ///
994 /// A reader should ignore keys and types it doesn't know. The `version` changes only for a
995 /// change that would break an existing reader.
996 ///
997 /// @return Returns the JSON text (an empty string for an empty API).
998 ///
999 /// @note Safe to call from any thread.
1000 ///
1001 std::string schema() const {
1002 ULString text = ulJSAPIGetSchema(api_);
1003 std::string result
1004 = text ? std::string(ulStringGetData(text), ulStringGetLength(text)) : std::string();
1005 ulDestroyString(text);
1006 return result;
1007 }
1008
1009 ///
1010 /// Write the JSON from schema() to a file.
1011 ///
1012 /// The library writes the file before this returns. A tool such as `gen-typescript.py` can
1013 /// then read it.
1014 ///
1015 /// @param utf8_path The file's path as a UTF-8 string (on Windows too). An existing file is
1016 /// replaced.
1017 ///
1018 /// @return Returns whether or not the file was written (false for an empty API, or a NULL or
1019 /// empty `utf8_path`). A write that fails also logs a warning with the path.
1020 ///
1021 /// @note Safe to call from any thread.
1022 ///
1023 bool DumpSchema(const char* utf8_path) { return ulJSAPIDumpSchema(api_, utf8_path); }
1024
1025 ///
1026 /// Add schema metadata (eg, documentation) to the entry at a path.
1027 ///
1028 /// schema() merges each fragment over the entry: objects merge field by field, other values
1029 /// replace, and later fragments win.
1030 ///
1031 /// Binding a path again (replacing its binding) removes that path's metadata, so call this
1032 /// after the Bind() it describes.
1033 ///
1034 /// ```
1035 /// api.SetMetadata("add", "{\"doc\": \"Adds two numbers.\"}");
1036 /// ```
1037 ///
1038 /// @param path The dot-separated path relative to the root, or "" for the document
1039 /// root (its top-level `meta`, `events`, and `types` sections). Root
1040 /// `events` entries declare events the way DefineEvent() does.
1041 ///
1042 /// @param metadata_json A JSON object. Anything else is ignored with a logged warning.
1043 ///
1044 /// @note This follows the registration thread rules (see the class overview).
1045 ///
1046 void SetMetadata(const char* path, const char* metadata_json) {
1047 ulJSAPISetMetadata(api_, path, metadata_json);
1048 }
1049
1050 ///
1051 /// Set the diagnostics level (see Diagnostics).
1052 ///
1053 /// Most warnings follow the new level right away. Typo warnings (reads of missing properties)
1054 /// start only on pages that get the bindings after you turn them on, but stop right away when
1055 /// you set Diagnostics::Off.
1056 ///
1057 /// @param level The new level (Diagnostics::Auto goes back to the Config's JavaScript
1058 /// level).
1059 ///
1060 /// \parblock
1061 /// @note You should set the level before attaching the API to a View (or pass it in
1062 /// APIOptions), since attaching at Warn or higher is what also attaches the library's
1063 /// `ul.diagnostics` API. Raising the level afterward doesn't add it.
1064 /// \endparblock
1065 ///
1066 /// \parblock
1067 /// @note The UL_JS_DIAGNOSTICS environment variable overrides this level while developer
1068 /// mode is on (see diagnostics()).
1069 /// \endparblock
1070 ///
1071 /// \parblock
1072 /// @note This follows the registration thread rules (see the class overview).
1073 /// \endparblock
1074 ///
1076 ulJSAPISetDiagnostics(api_, static_cast<ULJSDiagnosticsLevel>(level));
1077 }
1078
1079 ///
1080 /// Get the effective diagnostics level.
1081 ///
1082 /// @return Returns the level in effect: the UL_JS_DIAGNOSTICS environment override when it
1083 /// applies, else the level set on this API, with Diagnostics::Auto replaced by the
1084 /// Config's JavaScript level (this is never Diagnostics::Auto).
1085 ///
1087 return static_cast<Diagnostics>(ulJSAPIGetDiagnostics(api_));
1088 }
1089
1090 ///
1091 /// Attach this API to a View.
1092 ///
1093 /// The bindings are added to the View's current page (if the origin policy allows it) and to
1094 /// every page the View loads afterwards. The View keeps the API attached until you detach it
1095 /// or destroy this API. Attaching again updates the flags and origin rules.
1096 ///
1097 /// ```
1098 /// api.AttachTo(view.get()); // your own content
1099 /// api.AttachTo(view.get(), { .flags = js::AllFrames }); // and subframes
1100 /// api.AttachTo(view.get(), { .origin_rules = { "https://*.mygame.com" } }); // the game's site
1101 /// ```
1102 ///
1103 /// @param view The View to attach to.
1104 ///
1105 /// @param options The attach flags and the origin rules for the pages that get the bindings
1106 /// (see AttachOptions).
1107 ///
1108 /// @return Returns true on success, or false if `view` is nullptr, this API is empty, a flag
1109 /// is unknown, a rule failed to parse, or every owning handle to the API is gone (for
1110 /// an API from FromBorrowed()). Nothing changes then. An unknown flag, a rule that
1111 /// failed to parse, or a destroyed API also logs a warning that says why.
1112 ///
1113 /// \parblock
1114 /// @note Call this on the Renderer's thread.
1115 /// \endparblock
1116 ///
1117 /// \parblock
1118 /// @note APIs that share a namespace prefix (eg, roots `myApp.fs` and `myApp.net`) should all
1119 /// be attached before the page loads. An API attached later can't add to a frozen
1120 /// namespace the page already has, so its bindings appear after the page's next
1121 /// navigation.
1122 /// \endparblock
1123 ///
1124 [[nodiscard]] bool AttachTo(View* view, const AttachOptions& options = {}) {
1125 return view && api_
1126 && view->AttachJSAPI(api_, static_cast<unsigned>(options.flags),
1127 options.origin_rules.data(), options.origin_rules.size());
1128 }
1129
1130 ///
1131 /// Detach this API from a View.
1132 ///
1133 /// Events stop reaching the View's pages right away. The current page keeps the bindings it
1134 /// already has until it navigates (destroying the API instead makes them throw).
1135 ///
1136 /// @param view The View to detach from.
1137 ///
1138 /// @note Call this on the Renderer's thread.
1139 ///
1140 void DetachFrom(View* view) {
1141 if (view && api_)
1142 view->DetachJSAPI(api_);
1143 }
1144
1145 ///
1146 /// Get the underlying handle, for calls into the C API.
1147 ///
1148 /// @return Returns the handle (this API keeps ownership).
1149 ///
1150 ULJSAPI raw() const { return api_; }
1151
1152 ///
1153 /// Give up ownership of the underlying handle without releasing it (this API becomes empty).
1154 ///
1155 /// @return Returns the handle. You must call ulDestroyJSAPI() when finished.
1156 ///
1158 ULJSAPI api = api_;
1159 api_ = nullptr;
1160 return api;
1161 }
1162
1163 private:
1164 // The Adopt / FromBorrowed route: wrap an existing handle and recover its root path so
1165 // path-qualified diagnostics keep working.
1166 explicit API(ULJSAPI adopted) : api_(adopted) {
1167 if (!api_)
1168 return;
1169 ULString root = ulJSAPIGetRootPath(api_);
1170 if (root) {
1171 root_.assign(ulStringGetData(root), ulStringGetLength(root));
1172 ulDestroyString(root);
1173 }
1174 }
1175
1176 std::string FullPath(const char* path) const {
1177 std::string full = root_;
1178 full += '.';
1179 full += path ? path : "";
1180 return full;
1181 }
1182
1183 std::string root_;
1184 ULJSAPI api_;
1185};
1186
1187///
1188/// A binding tied to a C++ object's lifetime.
1189///
1190/// When an armed guard is destroyed, it removes the binding at its path (see API::Unbind()), so
1191/// a feature can keep a binding for exactly as long as its owner lives:
1192///
1193/// ```
1194/// api.Bind("debug.dump", [] { DumpState(); });
1195/// js::BindingGuard dump_guard(api, "debug.dump");
1196/// // ~dump_guard removes debug.dump (pages see the removal at their next navigation).
1197/// ```
1198///
1199/// The guard keeps its own reference to the API, so it stays safe to destroy after the js::API
1200/// that created it. It doesn't own the API, so destroying the js::API still detaches it. The
1201/// guard removes by path: if you bind something else at the path later, the guard removes that.
1202///
1203/// \parblock
1204/// @note Destroying or move-assigning over an armed guard removes the binding, so it follows
1205/// the registration thread rules (see the js::API class overview): once the API is
1206/// attached, do it on the Renderer's thread. To give up a guard on another thread, call
1207/// Release().
1208/// \endparblock
1209///
1210/// \parblock
1211/// @note `operator bool` only says whether the guard is armed. It never reflects whether the
1212/// binding or any page still exists.
1213/// \endparblock
1214///
1215class [[nodiscard]] BindingGuard {
1216 public:
1217 ///
1218 /// Create an unarmed guard (removes nothing).
1219 ///
1220 BindingGuard() = default;
1221
1222 ///
1223 /// Create an armed guard that removes the binding at `path` when destroyed.
1224 ///
1225 /// @param api The API the binding belongs to (an empty API gives an unarmed guard).
1226 ///
1227 /// @param path The binding's path relative to the root, as you bound it.
1228 ///
1229 BindingGuard(const API& api, const char* path)
1230 : api_(ulCreateJSAPIBorrowedRef(api.raw())), path_(path ? path : "") {}
1231
1232 ///
1233 /// Destructor (removes the binding if the guard is armed).
1234 ///
1236 if (api_) {
1237 ulJSAPIUnbind(api_, path_.c_str());
1238 ulDestroyJSAPI(api_);
1239 }
1240 }
1241
1242 ///
1243 /// Move constructor (`other` becomes unarmed).
1244 ///
1245 BindingGuard(BindingGuard&& other) noexcept
1246 : api_(other.api_), path_(std::move(other.path_)) {
1247 other.api_ = nullptr;
1248 }
1249
1250 ///
1251 /// Move assignment (removes the current binding first if armed, and `other` becomes unarmed).
1252 ///
1254 if (this != &other) {
1255 if (api_) {
1256 ulJSAPIUnbind(api_, path_.c_str());
1257 ulDestroyJSAPI(api_);
1258 }
1259 api_ = other.api_;
1260 path_ = std::move(other.path_);
1261 other.api_ = nullptr;
1262 }
1263 return *this;
1264 }
1265 BindingGuard(const BindingGuard&) = delete;
1267
1268 ///
1269 /// Disarm the guard without removing the binding (it stays until you unbind it or the API is
1270 /// destroyed).
1271 ///
1272 /// Safe to call from any thread.
1273 ///
1274 void Release() {
1275 if (api_) {
1276 ulDestroyJSAPI(api_);
1277 api_ = nullptr;
1278 }
1279 path_.clear();
1280 }
1281
1282 ///
1283 /// Whether or not the guard is armed (holds a path to remove).
1284 ///
1285 explicit operator bool() const { return api_ != nullptr; }
1286
1287 private:
1288 ULJSAPI api_ = nullptr;
1289 std::string path_;
1290};
1291
1292///
1293/// The details an API injection filter decides on (see SetInjectionFilter()).
1294///
1295/// New members may be added at the end in later versions, so read the members by name.
1296///
1298 ///
1299 /// The View loading the page (the View you set the filter on).
1300 ///
1302
1303 ///
1304 /// The API being decided on. It's the handle your API's raw() returns, so compare the two to
1305 /// tell your APIs apart. Wrap it with API::FromBorrowed() to use it as an API.
1306 ///
1308
1309 ///
1310 /// The page's security origin, serialized (eg, "https://example.com", or "null" for an opaque
1311 /// origin).
1312 ///
1313 const char* origin;
1314
1315 ///
1316 /// Whether or not the page is in the View's main frame.
1317 ///
1319
1320 ///
1321 /// Whether or not the origin rules allow the page.
1322 ///
1324};
1325
1326} // namespace js
1327
1328/// \cond INTERNAL
1329namespace detail {
1330template <>
1331struct InjectionRequestTraits<ULJSAPIInjectionRequest> {
1332 static js::InjectionRequest ToRequest(View* view, const ULJSAPIInjectionRequest& request) {
1333 return { view, request.api, request.origin, request.is_main_frame, request.rules_allow };
1334 }
1335 static void ReportException(const char* what) {
1336 std::string message = "js::SetInjectionFilter: the filter threw a C++ exception, so the "
1337 "JavaScript API was withheld from the page";
1338 if (what) {
1339 message += ": ";
1340 message += what;
1341 }
1342 ulJSAPIEmitDiagnostic(nullptr, message.c_str());
1343 }
1344};
1345} // namespace detail
1346/// \endcond
1347
1348namespace js {
1349
1350///
1351/// Set a View's API filter with a C++ callable (the typed form of
1352/// View::SetJSAPIInjectionFilter()).
1353///
1354/// The View calls the filter each time it's about to add an attached API's bindings to a page:
1355/// when a page loads, when you attach an API, and when a page returns from the back-forward
1356/// cache. The origin rules run first and their verdict arrives in `rules_allow`. Return true to
1357/// add the bindings or false to withhold them, whatever the rules decided. Use it for decisions
1358/// that origin rules can't express, such as a user setting or allowing a page whose origin is
1359/// opaque.
1360///
1361/// ```
1362/// js::SetInjectionFilter(view.get(), [&](const js::InjectionRequest& request) {
1363/// if (request.api == debug_api.raw())
1364/// return settings.debug_tools_enabled && request.rules_allow;
1365/// return request.rules_allow;
1366/// });
1367/// ```
1368///
1369/// @param view The View to set the filter on (nothing happens if it's nullptr).
1370///
1371/// @param filter A callable invocable as `bool(const js::InjectionRequest&)`. The new filter
1372/// replaces (and destroys) the previous one.
1373///
1374/// \parblock
1375/// @note Call this on the Renderer's thread. The filter runs there too.
1376/// \endparblock
1377///
1378/// \parblock
1379/// @note The filter is called for subframes only for APIs attached with AllFrames. The request
1380/// is valid only during the call.
1381/// \endparblock
1382///
1383/// \parblock
1384/// @note A filter that throws a C++ exception withholds the API from that page (and the
1385/// library logs a warning).
1386/// \endparblock
1387///
1388/// @see ClearInjectionFilter()
1389///
1390template <typename F>
1391void SetInjectionFilter(View* view, F&& filter) {
1392 using Fn = std::decay_t<F>;
1393 static_assert(std::is_invocable_r_v<bool, Fn&, const InjectionRequest&>,
1394 "js::SetInjectionFilter takes a callable invocable as "
1395 "bool(const js::InjectionRequest&)");
1396 if (!view)
1397 return;
1398 using Adapter = ultralight::detail::InjectionFilterAdapter<Fn, ULJSAPIInjectionRequest>;
1399 view->SetJSAPIInjectionFilter(&Adapter::Invoke, new Adapter { std::forward<F>(filter), view },
1400 &Adapter::Destroy);
1401}
1402
1403///
1404/// Remove a View's API filter, so the origin rules alone decide which pages get the bindings.
1405///
1406/// @param view The View to clear the filter on (nothing happens if it's nullptr).
1407///
1408/// @note Call this on the Renderer's thread.
1409///
1410inline void ClearInjectionFilter(View* view) {
1411 if (view)
1412 view->SetJSAPIInjectionFilter(nullptr, nullptr, nullptr);
1413}
1414
1415///
1416/// Bind a member function to an instance without writing a lambda.
1417///
1418/// How you pass the instance decides who keeps it alive:
1419///
1420/// ```
1421/// api["save"] = js::Bind(this, &App::OnSave); // raw pointer: you do
1422/// api["query"] = js::Bind(database_, &Database::Query); // shared holder: the binding does
1423/// api["tick"] = js::Bind(std::weak_ptr(widget_), // weak holder: nobody, and calls
1424/// &Widget::OnTick); // fail safely once it's gone
1425/// ```
1426///
1427/// The result is an ordinary callable that you can bind anywhere a lambda works. A method that
1428/// returns js::Task<T> or takes a trailing js::Resolver binds as an async function in every
1429/// form.
1430///
1431/// @param instance The object to call the method on. It must outlive every call through the
1432/// binding.
1433///
1434/// @param method The member function pointer.
1435///
1436/// @return Returns a callable that calls `method` on `instance`.
1437///
1438template <typename T, typename M>
1439 requires std::is_member_function_pointer_v<M>
1440auto Bind(T* instance, M method) {
1441 return detail::MakeBoundMethod(instance, method, detail::MemberFnTraits<M> {});
1442}
1443
1444///
1445/// Bind a member function to an instance kept by a holder.
1446///
1447/// Any smart pointer with an ultralight::HolderTraits specialization works, built-in or your own:
1448///
1449/// - **A shared holder** (RefPtr, std::shared_ptr, js::Eternal, or your own shared
1450/// specialization) is kept by the binding, so the instance lives as long as the binding.
1451/// - **A weak holder** (WeakPtr, std::weak_ptr, or your own specialization with Lock()) is
1452/// locked for each call and never keeps the instance alive between calls.
1453///
1454/// A method that returns js::Task<T> keeps the instance alive until its Task finishes, in both
1455/// forms (the weak form keeps the locked holder), even if the binding is removed meanwhile. A
1456/// method that takes a trailing js::Resolver binds in both forms too, but the weak form keeps
1457/// the instance only during the call, not until the Resolver settles.
1458///
1459/// @param holder The holder to call the method through (copied into the binding).
1460///
1461/// @param method The member function pointer.
1462///
1463/// @return Returns a callable that calls `method` on the held instance.
1464///
1465/// \parblock
1466/// @note When the instance is gone (an empty shared holder, or a weak holder whose object was
1467/// destroyed), a call throws a TypeError with code `ULJS_DETACHED` into the page instead
1468/// of touching the missing object. An async binding rejects its Promise with that error.
1469/// \endparblock
1470///
1471/// \parblock
1472/// @note std::unique_ptr isn't accepted, since passing one would move ownership into the
1473/// binding. Keep ownership and bind `js::Bind(ptr.get(), &T::Method)` instead.
1474/// \endparblock
1475///
1476template <typename H, typename M>
1477 requires((Holder<H> || LockableHolder<H>) && std::is_member_function_pointer_v<M>)
1478auto Bind(H holder, M method) {
1479 using T = typename HolderTraits<H>::element_type;
1480 static_assert(std::is_base_of_v<typename detail::MemberFnTraits<M>::Class, T>,
1481 "the member pointer must belong to the holder's element type (or a base "
1482 "of it)");
1483 if constexpr (Holder<H> && !LockableHolder<H>) {
1485 "js::Bind does not take exclusive holders: passing a unique_ptr would "
1486 "silently move ownership into the binding. Keep ownership and borrow "
1487 "with js::Bind(ptr.get(), &T::Method), or bind a shared holder");
1488 }
1489 return detail::MakeHolderBoundMethod<H, T>(std::move(holder), method,
1490 detail::MemberFnTraits<M> {});
1491}
1492
1493} // namespace js
1494} // namespace ultralight
1495
1496#pragma pop_macro("None")
struct C_JSAPI * ULJSAPI
Opaque handle to a set of native JavaScript bindings.
Definition View.h:32
struct ULJSAPIInjectionRequest ULJSAPIInjectionRequest
The details an API injection filter decides on.
Definition View.h:60
A list of origin patterns that controls which pages get an attached API.
Definition OriginRules.h:90
Web-page container rendered to an offscreen surface.
Definition View.h:483
virtual bool AttachJSAPI(ULJSAPI api, unsigned flags=0, const char *const *origin_rules=nullptr, size_t num_origin_rules=0)=0
Attach a JavaScript API to this View.
virtual void DetachJSAPI(ULJSAPI api)=0
Detach a JavaScript API from this View.
virtual void SetJSAPIInjectionFilter(JSAPIInjectionFilter filter, void *user_data, void(*destroy_user_data)(void *))=0
Set a filter that decides whether an attached API's bindings are added to a page.
The assignable path that operator[] returns (see Binding Functions and Values in the class overview).
Definition API.h:493
Binder(const Binder &)=delete
Binder & operator=(T &&rhs) &&
Bind a callable or value at this path (the type of rhs decides what's bound, see Binding Functions an...
Definition API.h:507
friend class API
Definition API.h:582
Binder & operator=(const Binder &)=delete
Binder operator[](const char *segment) &&
Get the Binder for a child path (api["fs"]["readFile"] is api["fs.readFile"]).
Definition API.h:556
void BindProperty(Getter &&get, Setter &&set=nullptr) &&
Bind a property with a getter (and optional setter) at this path (see API::BindProperty()):
Definition API.h:576
A global JavaScript namespace for native functions and data.
Definition API.h:399
void BindProperty(const char *path, Getter &&get, Setter &&set=nullptr)
Bind a property with a getter and an optional setter.
Definition API.h:812
void DefineEvent(const char *event_path, const Anns &... annotations)
Declare an event and its payload types.
Definition API.h:938
Diagnostics diagnostics() const
Get the effective diagnostics level.
Definition API.h:1086
API & operator=(API &&other) noexcept
Move assignment (releases the current handle, and other becomes empty).
Definition API.h:437
bool Unbind(const char *path)
Remove the binding at a path, along with its metadata.
Definition API.h:985
API(const char *root_path, const APIOptions &options={})
Create an API rooted at a global namespace path.
Definition API.h:413
void set_diagnostics(Diagnostics level)
Set the diagnostics level (see Diagnostics).
Definition API.h:1075
ULJSAPI raw() const
Get the underlying handle, for calls into the C API.
Definition API.h:1150
static API Adopt(ULJSAPI api)
Wrap a handle you own from the C API, taking ownership of it (eg, the result of ulCreateJSAPI()).
Definition API.h:461
ClassBuilder< T > DefineClass(const char *path)
Define a native class at a path, so page script can call its methods, read its properties,...
Definition Class.h:683
void Bind(const char *path, Fn &&fn, const Anns &... annotations)
Bind a callable at a path (the explicit form of api[path] = fn, which also takes annotations).
Definition API.h:614
~API()
Destructor (releases this handle).
Definition API.h:425
bool AttachTo(View *view, const AttachOptions &options={})
Attach this API to a View.
Definition API.h:1124
void Emit(const char *event_path, Args &&... args)
Emit an event to the page listeners subscribed with on or once (see Emitting Events in the class over...
Definition API.h:883
API(API &&other) noexcept
Move constructor (other becomes empty).
Definition API.h:430
API & operator=(const API &)=delete
bool DumpSchema(const char *utf8_path)
Write the JSON from schema() to a file.
Definition API.h:1023
Binder operator[](const char *path)
Get the Binder for a path relative to the root (see Binder).
Definition API.h:595
void SetConstant(const char *path, T &&value)
Set a constant at a path (the explicit form of api[path] = value).
Definition API.h:714
static API FromBorrowed(ULJSAPI api)
Wrap a handle someone else owns, without owning the API (eg, the api member of a js::InjectionRequest...
Definition API.h:477
API(const API &)=delete
void DetachFrom(View *view)
Detach this API from a View.
Definition API.h:1140
ULJSAPI LeakRef()
Give up ownership of the underlying handle without releasing it (this API becomes empty).
Definition API.h:1157
void SetMetadata(const char *path, const char *metadata_json)
Add schema metadata (eg, documentation) to the entry at a path.
Definition API.h:1046
std::string schema() const
Get the API's schema as JSON.
Definition API.h:1001
BindingGuard(const BindingGuard &)=delete
BindingGuard()=default
Create an unarmed guard (removes nothing).
BindingGuard(BindingGuard &&other) noexcept
Move constructor (other becomes unarmed).
Definition API.h:1245
BindingGuard & operator=(const BindingGuard &)=delete
void Release()
Disarm the guard without removing the binding (it stays until you unbind it or the API is destroyed).
Definition API.h:1274
BindingGuard(const API &api, const char *path)
Create an armed guard that removes the binding at path when destroyed.
Definition API.h:1229
~BindingGuard()
Destructor (removes the binding if the guard is armed).
Definition API.h:1235
BindingGuard & operator=(BindingGuard &&other) noexcept
Move assignment (removes the current binding first if armed, and other becomes unarmed).
Definition API.h:1253
Builder for exposing a C++ class to JavaScript.
Definition Class.h:277
Whether or not H (ignoring const and references) is an owning holder: its ultralight::HolderTraits de...
Definition Holder.h:102
Whether or not H (ignoring const and references) is a weak holder: its ultralight::HolderTraits decla...
Definition Holder.h:113
Whether or not js::TypeTraits can convert T (ignoring const, volatile, and references).
Definition TypeTraits.h:279
Definition StringSTL.h:166
Type-checked JavaScript bridge between C++ and web pages.
Definition JSInterop.h:141
DiagnosticsLevel Diagnostics
The diagnostics levels for an API.
Definition API.h:151
auto Bind(T *instance, M method)
Bind a member function to an instance without writing a lambda.
Definition API.h:1440
void SetInjectionFilter(View *view, F &&filter)
Set a View's API filter with a C++ callable (the typed form of View::SetJSAPIInjectionFilter()).
Definition API.h:1391
constexpr AttachFlags operator|(AttachFlags a, AttachFlags b)
Combine attach flags.
Definition API.h:57
@ ReadOnly
Script can't change its value.
Definition Value.h:76
void ClearInjectionFilter(View *view)
Remove a View's API filter, so the origin rules alone decide which pages get the bindings.
Definition API.h:1410
constexpr AttachFlags & operator|=(AttachFlags &a, AttachFlags b)
Add attach flags to a.
Definition API.h:66
AttachFlags
The flags for API::AttachTo() (the C++ form of ULJSAPIAttachFlags).
Definition API.h:44
@ AllFrames
Also add the bindings to subframes.
Definition API.h:46
@ None
Main frame only, with frozen namespace objects.
Definition API.h:45
@ Mutable
Don't freeze the namespace objects, so page script (or Value::DeleteProperty()) can change or delete ...
Definition API.h:47
constexpr AttachFlags AllFrames
Shorthand for AttachFlags::AllFrames.
Definition API.h:73
constexpr AttachFlags Mutable
Shorthand for AttachFlags::Mutable.
Definition API.h:78
Root namespace for every public Ultralight type, function, and enumeration.
DiagnosticsLevel
How much checking and warning the library does for mistakes made through one of its APIs.
Definition DiagnosticsLevel.h:18
@ None
Definition Anchor.h:36
@ Shared
Copies share ownership (eg, RefPtr), or the instance is never destroyed (js::Eternal).
Definition HolderTraits.h:20
Traits template that lets the library hold objects through custom smart pointers.
Definition HolderTraits.h:156
Options for creating an API.
Definition API.h:160
Diagnostics diagnostics
The diagnostics level.
Definition API.h:167
Options for API::AttachTo().
Definition API.h:92
OriginRules origin_rules
The origin rules for the pages that get the bindings.
Definition API.h:102
AttachFlags flags
The attach flags (see AttachFlags).
Definition API.h:96
const char * text
The documentation text.
Definition API.h:229
constexpr Doc(const char *doc_text)
Create a documentation annotation.
Definition API.h:236
The details an API injection filter decides on (see SetInjectionFilter()).
Definition API.h:1297
const char * origin
The page's security origin, serialized (eg, "https://example.com", or "null" for an opaque origin).
Definition API.h:1313
bool rules_allow
Whether or not the origin rules allow the page.
Definition API.h:1323
bool is_main_frame
Whether or not the page is in the View's main frame.
Definition API.h:1318
ULJSAPI api
The API being decided on.
Definition API.h:1307
View * view
The View loading the page (the View you set the filter on).
Definition API.h:1301
constexpr Param(const char *declared_name)
Create a parameter name annotation.
Definition API.h:211
const char * name
The parameter name.
Definition API.h:204