docs
Loading...
Searching...
No Matches
Value.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_JSValue.h>
12#include <Ultralight/CAPI/CAPI_String.h>
13#include <Ultralight/detail/Exceptions.h>
14#include <Ultralight/js/Error.h>
15
16#include <cstdint>
17#include <cstdio>
18#include <cstring>
19#include <optional>
20#include <span>
21#include <string>
22#include <string_view>
23#include <type_traits>
24#include <utility>
25#include <vector>
26
27namespace ultralight {
28namespace js {
29
30///
31/// Forward declaration.
32///
33/// @see <Ultralight/js/TypeTraits.h>
34///
35template <typename T, typename = void>
36struct TypeTraits;
37
38///
39/// Tag type for the JavaScript `null` value (see js::null).
40///
41struct NullType {};
42
43///
44/// The JavaScript `null` value.
45///
46/// Use it anywhere a typed value is accepted (eg, `obj["x"] = js::null` or a bound function's
47/// return value).
48///
49inline constexpr NullType null {};
50
51///
52/// Tag type for the JavaScript `undefined` value (see js::undefined).
53///
54struct UndefinedType {};
55
56///
57/// The JavaScript `undefined` value. Use it the same way as js::null.
58///
59inline constexpr UndefinedType undefined {};
60
61///
62/// Attribute flags for a property created by Value::SetProperty() or Value::DefineProperty().
63/// Combine them with `|`:
64///
65/// ```
66/// obj.SetProperty("id", ctx.Make(7.0),
67/// js::PropertyAttributes::ReadOnly | js::PropertyAttributes::DontDelete);
68/// ```
69///
70/// @note SetProperty() only applies the flags when it creates the property. If the object (or
71/// its prototype chain) already has one with that name, SetProperty() assigns the value
72/// and ignores the flags. DefineProperty() always applies them.
73///
74enum class PropertyAttributes : unsigned {
75 None = kULJSPropertyAttributes_None, ///< No flags (a normal property).
76 ReadOnly = kULJSPropertyAttributes_ReadOnly, ///< Script can't change its value.
77 DontEnum = kULJSPropertyAttributes_DontEnum, ///< Hidden from for...in and Object.keys.
78 DontDelete = kULJSPropertyAttributes_DontDelete, ///< The property can't be deleted.
79};
80
81///
82/// Combine property attribute flags.
83///
84/// @return Returns the union of both flag sets.
85///
87 return static_cast<PropertyAttributes>(static_cast<unsigned>(a) | static_cast<unsigned>(b));
88}
89
90///
91/// The type of a JavaScript value.
92///
93/// Later versions may add types, so handle a value you don't know (eg, with a `default` case).
94///
95/// @see Value::type()
96///
97enum class Type : unsigned {
98 Invalid = kULJSType_Invalid, ///< An empty Value, or one whose page is gone.
99 Undefined = kULJSType_Undefined,
100 Null = kULJSType_Null,
101 Boolean = kULJSType_Boolean,
102 Number = kULJSType_Number,
103 String = kULJSType_String,
104 Symbol = kULJSType_Symbol,
105 BigInt = kULJSType_BigInt,
106 Object = kULJSType_Object,
107};
108
109static_assert(kULJSType_Count == 9, "js::Type must list every ULJSType");
110
111///
112/// The kind of a JavaScript object.
113///
114/// Each kind agrees with the matching Value check where one exists: Array with Value::IsArray(),
115/// Promise with Value::IsPromise(), and Function with Value::IsCallable() for anything that isn't
116/// a Proxy.
117///
118/// Later versions may split new kinds out of Other, so test for the kinds you handle (eg, with a
119/// `default` case), never for Other itself.
120///
121/// @see Value::object_kind()
122///
123enum class ObjectKind : unsigned {
124 Invalid = kULJSObjectKind_Invalid, ///< An empty Value, or one whose page is gone.
125 None = kULJSObjectKind_None, ///< Not an object (a primitive like a number or string).
126 Plain = kULJSObjectKind_Plain, ///< An ordinary object (eg, `{}` or an instance of a JS class).
127 Array = kULJSObjectKind_Array,
128 /// A callable object that isn't a Proxy (a native class constructor included, although
129 /// Value::IsFunction() is false for it).
130 Function = kULJSObjectKind_Function,
131 Proxy = kULJSObjectKind_Proxy, ///< A Proxy (callable or not).
132 Date = kULJSObjectKind_Date,
133 RegExp = kULJSObjectKind_RegExp,
134 Map = kULJSObjectKind_Map,
135 Set = kULJSObjectKind_Set,
136 WeakMap = kULJSObjectKind_WeakMap,
137 WeakSet = kULJSObjectKind_WeakSet,
138 Promise = kULJSObjectKind_Promise,
139 Error = kULJSObjectKind_Error,
140 ArrayBuffer = kULJSObjectKind_ArrayBuffer,
141 TypedArray = kULJSObjectKind_TypedArray, ///< Any typed array (eg, a Float32Array).
142 DataView = kULJSObjectKind_DataView,
143 /// Any other object (eg, `window`, a DOM object, `Math`, `arguments`, a primitive wrapper like
144 /// `new Number(1)`, or an instance of a native class).
145 Other = kULJSObjectKind_Other,
146};
147
148static_assert(kULJSObjectKind_Count == 18, "js::ObjectKind must list every ULJSObjectKind");
149
150///
151/// Flags for Value::OwnKeys(). Combine them with `|`.
152///
153enum class OwnKeysFlags : unsigned {
154 None = 0, ///< Enumerable keys only.
155 IncludeNonEnumerable = kULJSOwnKeys_IncludeNonEnumerable, ///< Non-enumerable keys too.
156};
157
158///
159/// Combine own-keys flags.
160///
161/// @return Returns the union of both flag sets.
162///
164 return static_cast<OwnKeysFlags>(static_cast<unsigned>(a) | static_cast<unsigned>(b));
165}
166
167namespace detail {
168
169// An integer type usable as a property index (bool excluded).
170template <typename I>
171concept PropertyIndex = std::is_integral_v<I> && !std::is_same_v<I, bool>;
172
173} // namespace detail
174
175///
176/// A handle to a live JavaScript value.
177///
178/// A Value represents a live JavaScript value on a page. You use it to hold page objects and
179/// functions across calls, interacting with them directly without converting them to C++ types.
180///
181/// This example interacts with an object on the page:
182///
183/// ```
184/// js::Value player = ctx["game"]["player"];
185///
186/// double health = player["health"].Or(0.0); // read (0.0 if anything fails)
187/// player["score"] = 1200; // write
188/// player["respawn"](10, 20); // call a method (`this` is player)
189/// ```
190///
191/// ## Handle States
192///
193/// A handle is always in one of these states:
194///
195/// | State | When | operator bool | Calls |
196/// |-------|--------------------------------------------------|---------------|---------------|
197/// | Valid | On a live page | `true` | Work normally |
198/// | Empty | Default-constructed, moved from, or failed read | `false` | Do nothing |
199/// | Gone | Page navigated, frame removed, or View destroyed | `false` | Do nothing |
200///
201/// An empty Value differs from JavaScript `null` and `undefined`. A missing property reads as a
202/// valid Value holding `undefined`, while an empty handle represents an uninitialized handle or a
203/// failed operation.
204///
205/// Every operation is safe in all three states, allowing property reads and method calls to chain
206/// without checking each step.
207///
208/// This call chains safely even if the HUD object doesn't exist:
209///
210/// ```
211/// ctx["hud"]["showToast"]("Saved"); // does nothing if there's no hud
212/// ```
213///
214/// When an operation returns a failed js::Result, inspect js::Error::is_empty() to check for an
215/// empty handle or js::Error::is_page_gone() to check whether the page navigated away.
216///
217/// A handle whose page is gone never recovers, even when that page is restored from the
218/// back-forward cache.
219///
220/// To interact with the new page, get a new Value from that page's js::Context. Every page-lifetime
221/// handle across the JavaScript API follows these rules.
222///
223/// ## Copies and Lifetimes
224///
225/// Copying a Value creates another reference to the same JavaScript value.
226///
227/// Holding a Value keeps the underlying JavaScript value from being garbage-collected, but it
228/// doesn't keep the page or its View alive.
229///
230/// For ownership cycles between bound instances and JavaScript objects, see js::ClassBuilder.
231///
232/// A `const Value` still lets you change the underlying JavaScript value, matching the behavior of
233/// a `const RefPtr`.
234///
235/// ## Type Conversions
236///
237/// The conversion methods To(), Maybe(), and Or() are strict about the JavaScript type (the string
238/// `"7"` doesn't convert to a number), differing only in how they report a failure.
239///
240/// To convert values using JavaScript's own coercion rules, call ToNumber(), ToString(),
241/// ToBoolean(), or ToJSON() directly on the Value. For the full list of supported types, see
242/// js::TypeTraits.
243///
244/// This example compares strict conversion against JavaScript coercion:
245///
246/// ```
247/// js::Value level = player["level"]; // the string "7"
248///
249/// double strict = level.Or(0.0); // 0.0 (not a number)
250/// double loose = level.ToNumber().value_or(0.0); // 7.0 (JavaScript's rules)
251/// ```
252///
253/// ## Values Across Pages
254///
255/// A Value belongs to the page that created it. You can pass a Value directly only between frames
256/// of the same top-level page that share an exact origin, never across separate View%s.
257///
258/// Using a Value on a page that can't take it fails with a TypeError whose error code is
259/// `ULJS_CROSS_CONTEXT`. To transfer data between separate pages or View%s, copy the data using
260/// JSON or native C++ types.
261///
262/// This example transfers player data to a page in another View using JSON:
263///
264/// ```
265/// js::Context bestiary(bestiary_view.get()); // a page in another View
266///
267/// std::string json = player.ToJSON().value_or("null");
268/// bestiary["player"] = js::OrEmpty(bestiary.MakeFromJSON(json));
269/// ```
270///
271/// @note js::Value and dom::data::Value are unrelated types (dom::data::Value is the value type of
272/// the data-binding API).
273///
274/// @see js::Context, js::Error, js::TypeTraits, js::WeakValue
275///
276class Value {
277 public:
278 ///
279 /// Create an empty Value.
280 ///
281 Value() : handle_(nullptr) {}
282
283 ///
284 /// Copy constructor (adds a reference to the same JavaScript value).
285 ///
286 Value(const Value& other)
287 : handle_(other.handle_ ? ulCreateJSValueRef(other.handle_) : nullptr) {}
288
289 ///
290 /// Move constructor (`other` becomes empty).
291 ///
292 Value(Value&& other) noexcept : handle_(other.handle_) { other.handle_ = nullptr; }
293
294 ///
295 /// Assignment (copies or moves `other` into this Value).
296 ///
297 Value& operator=(Value other) noexcept {
298 std::swap(handle_, other.handle_);
299 return *this;
300 }
301
302 ///
303 /// Destructor (releases this handle).
304 ///
305 ~Value() { ulDestroyJSValue(handle_); }
306
307 ///
308 /// Whether or not this Value is valid (it isn't empty and its page is still alive).
309 ///
310 explicit operator bool() const { return IsAlive(); }
311
312 ///
313 /// Whether or not this Value holds nothing (see "Handle States" above).
314 ///
315 bool IsEmpty() const { return handle_ == nullptr; }
316
317 ///
318 /// Whether or not this Value's page is still alive (the same test as `operator bool`).
319 ///
320 /// @note Safe to call from any thread, but off the Renderer's thread the result may already
321 /// be out of date when you act on it.
322 ///
323 bool IsAlive() const { return handle_ && ulJSValueIsAlive(handle_); }
324
325 ///
326 /// Get the type of the value.
327 ///
328 /// @return Returns the value's type (Type::Invalid for an empty Value or one whose page is
329 /// gone).
330 ///
331 Type type() const { return static_cast<Type>(ulJSValueGetType(handle_)); }
332
333 ///
334 /// Whether or not the value is `undefined`.
335 ///
336 bool IsUndefined() const { return type() == Type::Undefined; }
337
338 ///
339 /// Whether or not the value is `null`.
340 ///
341 bool IsNull() const { return type() == Type::Null; }
342
343 ///
344 /// Whether or not the value is `null` or `undefined`.
345 ///
346 bool IsNullish() const { return IsNull() || IsUndefined(); }
347
348 ///
349 /// Whether or not the value is a boolean.
350 ///
351 bool IsBoolean() const { return type() == Type::Boolean; }
352
353 ///
354 /// Whether or not the value is a number.
355 ///
356 bool IsNumber() const { return type() == Type::Number; }
357
358 ///
359 /// Whether or not the value is a BigInt (eg, `10n`).
360 ///
361 bool IsBigInt() const { return type() == Type::BigInt; }
362
363 ///
364 /// Whether or not the value is a string.
365 ///
366 bool IsString() const { return type() == Type::String; }
367
368 ///
369 /// Whether or not the value is an object.
370 ///
371 /// Arrays and functions are objects too (use IsArray() or IsFunction() to tell them apart).
372 ///
373 bool IsObject() const { return type() == Type::Object; }
374
375 ///
376 /// Whether or not the value is an Array.
377 ///
378 bool IsArray() const { return handle_ && ulJSValueIsArray(handle_); }
379
380 ///
381 /// Whether or not the value can be called (see Call() and Invoke()).
382 ///
383 bool IsCallable() const { return handle_ && ulJSValueIsCallable(handle_); }
384
385 ///
386 /// Whether or not the value is a function.
387 ///
388 /// @note A few callable objects aren't functions (eg, the constructor of a native class). Use
389 /// IsCallable() to check whether you can call a value.
390 ///
391 bool IsFunction() const { return handle_ && ulJSValueIsFunction(handle_); }
392
393 ///
394 /// Whether or not the value is a Promise.
395 ///
396 /// This has no side effects: the promise isn't marked as handled.
397 ///
398 bool IsPromise() const { return handle_ && ulJSValueIsPromise(handle_); }
399
400 ///
401 /// Whether or not the value can be called with `new` (see Construct()).
402 ///
403 bool IsConstructor() const { return handle_ && ulJSValueIsConstructor(handle_); }
404
405 ///
406 /// Get the kind of object the value is (eg, a Map, a Date, or an ordinary object).
407 ///
408 /// This never runs script, so it's safe on any value, a Proxy included.
409 ///
410 /// ```
411 /// if (value.object_kind() == js::ObjectKind::Date)
412 /// ShowDate(value.TimeValue().value_or(0.0));
413 /// ```
414 ///
415 /// @return Returns the kind (ObjectKind::None for a value that isn't an object, and
416 /// ObjectKind::Invalid for an empty Value or one whose page is gone).
417 ///
418 /// @note Later versions may add kinds, so handle a kind you don't know (see ObjectKind).
419 ///
421 return static_cast<ObjectKind>(ulJSValueGetObjectKind(handle_));
422 }
423
424 ///
425 /// Whether or not this value and `other` are strictly equal (like JavaScript's `===`).
426 ///
427 /// Two handles to one object are equal, strings compare by content, `NaN` never equals
428 /// anything, and `+0` equals `-0`. This never runs script.
429 ///
430 /// @param other The value to compare with.
431 ///
432 /// @return Returns whether the values are strictly equal (false if either Value is empty or
433 /// its page is gone).
434 ///
435 bool StrictEquals(const Value& other) const {
436 return handle_ && other.handle_ && ulJSValueIsStrictEqual(handle_, other.handle_);
437 }
438
439 ///
440 /// Get the time value of a Date, in milliseconds since the epoch (like `date.getTime()`).
441 ///
442 /// This reads the Date directly, so it never runs script (a `valueOf()` the page replaced
443 /// isn't called).
444 ///
445 /// @return Returns the time value (NaN for an Invalid Date). Fails with a TypeError if the
446 /// value isn't a Date.
447 ///
448 /// @see Context::MakeDate()
449 ///
450 [[nodiscard]] Result<double> TimeValue() const {
451 if (!handle_)
452 return detail::EmptyHandleError();
453 double ms_since_epoch = 0.0;
454 if (ulJSDateGetTime(handle_, &ms_since_epoch))
455 return ms_since_epoch;
456 if (!IsAlive())
457 return Unexpected<Error>(Error::PageGone());
458 return Unexpected<Error>(Error::TypeError("The value isn't a Date."));
459 }
460
461 ///
462 /// Convert to a boolean using JavaScript's rules (this never runs script).
463 ///
464 /// @return Returns the boolean.
465 ///
466 [[nodiscard]] Result<bool> ToBoolean() const {
467 if (!handle_)
468 return detail::EmptyHandleError();
469 bool result;
470 if (!ulJSValueToBoolean(handle_, &result))
471 return Unexpected<Error>(Error::PageGone());
472 return result;
473 }
474
475 ///
476 /// Convert to a number using JavaScript's rules.
477 ///
478 /// @return Returns the number. Fails with a JavaScript exception if the conversion throws
479 /// (eg, a valueOf() method throws or the value is a Symbol).
480 ///
481 [[nodiscard]] Result<double> ToNumber() const {
482 if (!handle_)
483 return detail::EmptyHandleError();
484 double result;
485 ULJSValue exception = nullptr;
486 if (!ulJSValueToNumber(handle_, &result, &exception)) {
487 if (exception)
488 return Unexpected<Error>(Error::AdoptException(exception));
489 return Unexpected<Error>(Error::PageGone());
490 }
491 return result;
492 }
493
494 ///
495 /// Convert to a UTF-8 string using JavaScript's rules.
496 ///
497 /// @return Returns the string. Fails with a JavaScript exception if the conversion throws
498 /// (eg, a toString() method throws or the value is a Symbol).
499 ///
500 [[nodiscard]] Result<std::string> ToString() const {
501 if (!handle_)
502 return detail::EmptyHandleError();
503 ULJSValue exception = nullptr;
504 if (ulJSValueGetType(handle_) == kULJSType_String) {
505 // Already a string: reading its bytes runs no script, so the capacity retry is safe.
506 char stack_buffer[256];
507 size_t length = 0;
508 if (ulJSValueGetUTF8(handle_, stack_buffer, sizeof(stack_buffer), &length, &exception))
509 return std::string(stack_buffer, length);
510 if (!exception && length > sizeof(stack_buffer)) {
511 std::string heap(length, '\0');
512 if (ulJSValueGetUTF8(handle_, heap.data(), heap.size(), &length, &exception))
513 return heap;
514 }
515 if (exception)
516 return Unexpected<Error>(Error::AdoptException(exception));
517 return Unexpected<Error>(Error::PageGone());
518 }
519 ULString s = ulJSValueToString(handle_, &exception);
520 if (!s) {
521 if (exception)
522 return Unexpected<Error>(Error::AdoptException(exception));
523 return Unexpected<Error>(Error::PageGone());
524 }
525 std::string result(ulStringGetData(s), ulStringGetLength(s));
526 ulDestroyString(s);
527 return result;
528 }
529
530 ///
531 /// Convert to JSON text like `JSON.stringify()` does.
532 ///
533 /// @param indent The number of spaces to indent each level by (0 for compact output, at
534 /// most 10).
535 ///
536 /// @return Returns the JSON text. Fails with a TypeError if the value has no JSON form
537 /// (`undefined`, a function, or a Symbol), or with a JavaScript exception if a
538 /// toJSON() method or a getter throws.
539 ///
540 [[nodiscard]] Result<std::string> ToJSON(unsigned indent = 0) const {
541 if (!handle_)
542 return detail::EmptyHandleError();
543 ULJSValue exception = nullptr;
544 ULString s = ulJSValueToJSON(handle_, indent, &exception);
545 if (!s) {
546 if (exception)
547 return Unexpected<Error>(Error::AdoptException(exception));
548 // JSON.stringify renders some live values as no JSON at all (undefined, functions,
549 // symbols); report that as its own failure, not as a page-gone error.
550 if (ulJSValueIsAlive(handle_))
551 return Unexpected<Error>(Error::TypeError("The value has no JSON representation."));
552 return Unexpected<Error>(Error::PageGone());
553 }
554 std::string result(ulStringGetData(s), ulStringGetLength(s));
555 ulDestroyString(s);
556 return result;
557 }
558
559 ///
560 /// Get a property of this object (own or inherited).
561 ///
562 /// @param name The property name (NULL is treated as "").
563 ///
564 /// @return Returns the property value (`undefined` if there's no such property). Fails with
565 /// a JavaScript exception if a getter throws.
566 ///
567 [[nodiscard]] Result<Value> GetProperty(const char* name) const {
568 if (!handle_)
569 return detail::EmptyHandleError();
570 ULJSValue exception = nullptr;
571 ULJSValue result = ulJSObjectGetProperty(handle_, name ? name : "", &exception);
572 if (!result) {
573 if (exception)
574 return Unexpected<Error>(Error::AdoptException(exception));
575 return Unexpected<Error>(Error::PageGone());
576 }
577 return Adopt(result);
578 }
579
580 ///
581 /// Whether or not this object has a property (own or inherited).
582 ///
583 /// Unlike reading the property, this returns true for a property set to `undefined`. It
584 /// doesn't run JavaScript getters, but on an instance of a bound native class (see
585 /// js::ClassBuilder) the property's native getter does run.
586 ///
587 /// @param name The property name (NULL is treated as "").
588 ///
589 /// @note Any failure returns false. Use HasProperty() if you need the reason.
590 ///
591 bool Has(const char* name) const {
592 detail::SwallowedException swallow;
593 return handle_ && ulJSObjectHasProperty(handle_, name ? name : "", swallow.out());
594 }
595
596 ///
597 /// Whether or not this object has a property (like Has(), but reports failures).
598 ///
599 /// @param name The property name (NULL is treated as "").
600 ///
601 /// @return Returns whether the property exists. Fails with a JavaScript exception if the
602 /// check throws (eg, in a Proxy's `has` handler).
603 ///
604 [[nodiscard]] Result<bool> HasProperty(const char* name) const {
605 if (!handle_)
606 return detail::EmptyHandleError();
607 ULJSValue exception = nullptr;
608 bool present = ulJSObjectHasProperty(handle_, name ? name : "", &exception);
609 return CheckedBool(present, exception);
610 }
611
612 ///
613 /// Set a property of this object.
614 ///
615 /// ```
616 /// obj.SetProperty("id", ctx.Make(7.0),
617 /// js::PropertyAttributes::ReadOnly | js::PropertyAttributes::DontDelete);
618 /// ```
619 ///
620 /// @param name The property name (NULL is treated as "").
621 ///
622 /// @param value The value to assign (an empty Value assigns `undefined`).
623 ///
624 /// @param attributes The flags combined with `|`. They only apply if this creates the
625 /// property (see PropertyAttributes).
626 ///
627 /// @return Returns success. Fails with a JavaScript exception if a setter throws.
628 ///
629 /// @note Like an assignment in non-strict JavaScript, a write the object refuses (a frozen
630 /// object, or a read-only property) is silently ignored and still returns success.
631 ///
633 const char* name, const Value& value,
634 PropertyAttributes attributes = PropertyAttributes::None) const {
635 if (!handle_)
636 return detail::EmptyHandleError();
637 ULJSValue exception = nullptr;
638 if (ulJSObjectSetProperty(handle_, name ? name : "", value.handle_,
639 static_cast<unsigned>(attributes), &exception))
640 return {};
641 if (exception)
642 return Unexpected<Error>(Error::AdoptException(exception));
643 return Unexpected<Error>(Error::PageGone());
644 }
645
646 ///
647 /// Delete a property of this object (like JavaScript's `delete` operator).
648 ///
649 /// ```
650 /// js::Result<bool> deleted = settings.DeleteProperty("cache");
651 /// ```
652 ///
653 /// @param name The property name (NULL is treated as "").
654 ///
655 /// @return Returns the `delete` operator's result: true if the property was deleted or
656 /// didn't exist, false if the object refused (eg, a property created with
657 /// PropertyAttributes::DontDelete, or a frozen object). Fails with a JavaScript
658 /// exception if the delete throws (eg, in a Proxy's `deleteProperty` handler).
659 ///
660 /// @note Unlike SetProperty(), a refusal isn't ignored: it returns false.
661 ///
662 [[nodiscard]] Result<bool> DeleteProperty(const char* name) const {
663 if (!handle_)
664 return detail::EmptyHandleError();
665 ULJSValue exception = nullptr;
666 bool deleted = ulJSObjectDeleteProperty(handle_, name ? name : "", &exception);
667 return CheckedBool(deleted, exception);
668 }
669
670 ///
671 /// Delete an element of this object by index (eg, `arr.DeleteProperty(2)`).
672 ///
673 /// Deleting an array element leaves a hole, so the array's length doesn't change. A negative
674 /// index deletes the property with that name, as JavaScript does (`-1` deletes "-1").
675 ///
676 /// @param index The index (any integer type).
677 ///
678 /// @return Returns the `delete` operator's result and fails the same way as the overload
679 /// above.
680 ///
681 template <detail::PropertyIndex I>
682 [[nodiscard]] Result<bool> DeleteProperty(I index) const {
683 if (!handle_)
684 return detail::EmptyHandleError();
685 ULJSValue exception = nullptr;
686 return CheckedBool(DeleteByKey(ResolveIndex(index), &exception), exception);
687 }
688
689 ///
690 /// Delete a property of this object (like DeleteProperty(), but without the failure reason).
691 ///
692 /// @param name The property name (NULL is treated as "").
693 ///
694 /// @return Returns the `delete` operator's result (see DeleteProperty()).
695 ///
696 /// @note Any failure returns false. Use DeleteProperty() if you need the reason.
697 ///
698 [[nodiscard]] bool Delete(const char* name) const {
699 detail::SwallowedException swallow;
700 return handle_ && ulJSObjectDeleteProperty(handle_, name ? name : "", swallow.out());
701 }
702
703 ///
704 /// Delete an element of this object by index (like Delete(), but taking an index).
705 ///
706 /// @param index The index (any integer type; a negative index deletes the property with
707 /// that name).
708 ///
709 /// @return Returns the `delete` operator's result (see DeleteProperty()).
710 ///
711 /// @note Any failure returns false. Use DeleteProperty() if you need the reason.
712 ///
713 template <detail::PropertyIndex I>
714 [[nodiscard]] bool Delete(I index) const {
715 detail::SwallowedException swallow;
716 return handle_ && DeleteByKey(ResolveIndex(index), swallow.out());
717 }
718
719 ///
720 /// Whether or not this object has an own property (one that isn't inherited, like
721 /// `Object.hasOwn()`).
722 ///
723 /// Like Has(), this doesn't run JavaScript getters, but on an instance of a bound native class
724 /// the property's native getter does run.
725 ///
726 /// @param name The property name (NULL is treated as "").
727 ///
728 /// @note Any failure returns false. Use HasOwnProperty() if you need the reason.
729 ///
730 bool HasOwn(const char* name) const {
731 detail::SwallowedException swallow;
732 return handle_ && ulJSObjectHasOwnProperty(handle_, name ? name : "", swallow.out());
733 }
734
735 ///
736 /// Whether or not this object has an own element at an index (eg, `arr.HasOwn(2)` is false
737 /// for a hole).
738 ///
739 /// @param index The index (any integer type; a negative index checks the property with that
740 /// name).
741 ///
742 /// @note Any failure returns false. Use HasOwnProperty() if you need the reason.
743 ///
744 template <detail::PropertyIndex I>
745 bool HasOwn(I index) const {
746 return HasOwn(IndexName(index).text);
747 }
748
749 ///
750 /// Whether or not this object has an own property (like HasOwn(), but reports failures).
751 ///
752 /// @param name The property name (NULL is treated as "").
753 ///
754 /// @return Returns whether the object has the property itself. Fails with a JavaScript
755 /// exception if the check throws (eg, in a Proxy's `getOwnPropertyDescriptor`
756 /// handler, or in a bound native class's property getter).
757 ///
758 [[nodiscard]] Result<bool> HasOwnProperty(const char* name) const {
759 if (!handle_)
760 return detail::EmptyHandleError();
761 ULJSValue exception = nullptr;
762 bool present = ulJSObjectHasOwnProperty(handle_, name ? name : "", &exception);
763 return CheckedBool(present, exception);
764 }
765
766 ///
767 /// Whether or not this object has an own element at an index (like HasOwn(), but reports
768 /// failures).
769 ///
770 /// @param index The index (any integer type; a negative index checks the property with that
771 /// name).
772 ///
773 /// @return Returns whether the object has the element itself and fails the same way as the
774 /// overload above.
775 ///
776 template <detail::PropertyIndex I>
777 [[nodiscard]] Result<bool> HasOwnProperty(I index) const {
778 return HasOwnProperty(IndexName(index).text);
779 }
780
781 ///
782 /// Get the names of this object's own properties, without reading their values.
783 ///
784 /// The names come in the same order as `Object.getOwnPropertyNames()` (integer keys in
785 /// ascending order, then the rest in the order they were added). Inherited properties and
786 /// Symbol keys aren't listed.
787 ///
788 /// No getter runs, so this is a safe way to walk an object you don't control:
789 ///
790 /// ```
791 /// for (const std::string& key : obj.OwnKeys().value_or({}))
792 /// Log(key);
793 /// ```
794 ///
795 /// @param flags OwnKeysFlags::IncludeNonEnumerable to also list non-enumerable properties
796 /// (eg, an array's `length`).
797 ///
798 /// @return Returns the names. Fails with a JavaScript exception if listing them throws (eg,
799 /// in a Proxy's `ownKeys` handler).
800 ///
801 /// @note An array or typed array lists one name per element, so a large one gives a large
802 /// list.
803 ///
805 OwnKeysFlags flags = OwnKeysFlags::None) const {
806 if (!handle_)
807 return detail::EmptyHandleError();
808 ULJSValue exception = nullptr;
809 ULJSStringList list =
810 ulJSObjectGetOwnKeys(handle_, static_cast<unsigned>(flags), &exception);
811 if (!list) {
812 if (exception)
813 return Unexpected<Error>(Error::AdoptException(exception));
814 if (!IsAlive())
815 return Unexpected<Error>(Error::PageGone());
816 return Unexpected<Error>(Error::TypeError("Unknown OwnKeysFlags bits."));
817 }
818 std::vector<std::string> keys;
819 size_t length = ulJSStringListGetLength(list);
820 keys.reserve(length);
821 for (size_t i = 0; i < length; i++) {
822 if (ULString key = ulJSStringListGetString(list, i)) {
823 keys.emplace_back(ulStringGetData(key), ulStringGetLength(key));
824 ulDestroyString(key);
825 }
826 }
827 ulDestroyJSStringList(list);
828 return keys;
829 }
830
831 ///
832 /// Define a data property of this object (like `Reflect.defineProperty()`).
833 ///
834 /// Unlike SetProperty(), this always applies the flags you give, whether or not the property
835 /// exists already. No flags means a writable, enumerable, deletable property (the opposite of
836 /// `Object.defineProperty()`'s defaults):
837 ///
838 /// ```
839 /// obj.DefineProperty("version", ctx.Make(2.0),
840 /// js::PropertyAttributes::ReadOnly | js::PropertyAttributes::DontDelete);
841 /// ```
842 ///
843 /// @param name The property name (NULL is treated as "").
844 ///
845 /// @param value The value (an empty Value defines `undefined`).
846 ///
847 /// @param attributes The flags combined with `|`.
848 ///
849 /// @return Returns true if the property was defined, or false if the object refused (eg, an
850 /// existing property that can't be deleted, an object that's frozen or can't be
851 /// extended, or a property of a bound native class). Fails with a TypeError if this
852 /// value isn't an object, or with a JavaScript exception if the definition throws
853 /// (eg, in a Proxy's `defineProperty` handler).
854 ///
855 /// @note Defining a data property over an accessor property replaces the accessor.
856 ///
858 const char* name, const Value& value,
859 PropertyAttributes attributes = PropertyAttributes::None) const {
860 if (!handle_)
861 return detail::EmptyHandleError();
862 ULJSValue exception = nullptr;
863 bool defined = ulJSObjectDefineProperty(handle_, name ? name : "", value.handle_,
864 static_cast<unsigned>(attributes), &exception);
865 return CheckedBool(defined, exception);
866 }
867
868 ///
869 /// Define an accessor property of this object, with a getter and a setter function (like
870 /// `Reflect.defineProperty()` with `get` and `set`).
871 ///
872 /// The flags work as for DefineProperty(), except PropertyAttributes::ReadOnly, which doesn't
873 /// apply to an accessor. Pass an empty Value to leave out the getter or the setter:
874 ///
875 /// ```
876 /// js::Value getter = ctx.MakeFunction("level", [] { return GetLevel(); });
877 /// obj.DefineAccessor("level", getter, js::Value()); // no setter
878 /// ```
879 ///
880 /// @param name The property name (NULL is treated as "").
881 ///
882 /// @param getter The getter function (an empty Value for none).
883 ///
884 /// @param setter The setter function (an empty Value for none).
885 ///
886 /// @param attributes The flags combined with `|`.
887 ///
888 /// @return Returns true if the property was defined, or false if the object refused (see
889 /// DefineProperty()). Fails with a TypeError if this value isn't an object, if both
890 /// functions are empty, or if one isn't callable, or with a JavaScript exception if
891 /// the definition throws.
892 ///
893 /// @note Redefining an existing accessor keeps the getter or setter you leave out, so this
894 /// can't remove one. To remove one, delete the property and define it again.
895 ///
897 const char* name, const Value& getter, const Value& setter,
898 PropertyAttributes attributes = PropertyAttributes::None) const {
899 if (!handle_)
900 return detail::EmptyHandleError();
901 ULJSValue exception = nullptr;
902 bool defined =
903 ulJSObjectDefineAccessor(handle_, name ? name : "", getter.handle_, setter.handle_,
904 static_cast<unsigned>(attributes), &exception);
905 return CheckedBool(defined, exception);
906 }
907
908 ///
909 /// Freeze this object (like `Object.freeze()`), so no property can be added, removed, or
910 /// changed afterward.
911 ///
912 /// @return Returns success (a value that isn't an object, or an object that's already
913 /// frozen, succeeds without change). Fails with a TypeError if the object can't be
914 /// frozen (eg, the global object, a Proxy whose handler refuses, or an instance of a
915 /// bound native class), or with a JavaScript exception if a Proxy's handler throws.
916 ///
917 /// @note Unlike DeleteProperty() and DefineProperty(), a refusal here is an error, as it is
918 /// in JavaScript.
919 ///
920 [[nodiscard]] Result<void> Freeze() const {
921 if (!handle_)
922 return detail::EmptyHandleError();
923 ULJSValue exception = nullptr;
924 if (ulJSObjectFreeze(handle_, &exception))
925 return {};
926 if (exception)
927 return Unexpected<Error>(Error::AdoptException(exception));
928 return Unexpected<Error>(Error::PageGone());
929 }
930
931 ///
932 /// Call this value as a function.
933 ///
934 /// @param this_value The `this` value for the call (an empty Value uses the global object).
935 ///
936 /// @param args The arguments (an empty Value passes `undefined`).
937 ///
938 /// @param argc The number of entries in `args`.
939 ///
940 /// @return Returns the function's return value. Fails with a JavaScript exception if the
941 /// call throws or this value can't be called.
942 ///
943 [[nodiscard]] Result<Value> Call(const Value& this_value, const Value* args,
944 size_t argc) const {
945 if (!handle_)
946 return detail::EmptyHandleError();
947 RawArgs raw(args, argc);
948 ULJSValue exception = nullptr;
949 ULJSValue result = ulJSFunctionCall(handle_, this_value.handle_, raw.data, argc, &exception);
950 return AdoptResult(result, exception);
951 }
952
953 ///
954 /// Call this value as a function with the arguments in a range (eg, a
955 /// `std::vector<js::Value>`).
956 ///
957 /// @param this_value The `this` value for the call (an empty Value uses the global object).
958 ///
959 /// @param args The arguments.
960 ///
961 /// @return Returns the function's return value and fails the same way as the overload
962 /// above.
963 ///
964 [[nodiscard]] Result<Value> Call(const Value& this_value,
965 std::span<const Value> args) const {
966 return Call(this_value, args.data(), args.size());
967 }
968
969 ///
970 /// Convert to a C++ type.
971 ///
972 /// This works for every type js::TypeTraits supports: numbers, strings, containers,
973 /// optionals, variants, reflected structs and enums, and your own specializations. The value
974 /// must already have the matching JavaScript type (see "Type Conversions" above).
975 ///
976 /// ```
977 /// js::Result<Settings> s = payload["settings"].To<Settings>();
978 ///
979 /// // To walk an array or an object's entries, convert to a container of js::Value:
980 /// auto items = arr.To<std::vector<js::Value>>().value_or({});
981 /// auto entries = obj.To<std::map<std::string, js::Value>>().value_or({});
982 ///
983 /// // A std::map takes an ordinary object (eg, `{ a: 1 }`), not a Map, Set, or Date:
984 /// auto bad = lookup.To<std::map<std::string, double>>(); // fails on `new Map()`
985 /// ```
986 ///
987 /// An integer type needs a whole number in its range, so `To<int>()` on 3.5 fails instead of
988 /// truncating.
989 ///
990 /// @return Returns the converted value. Fails with a TypeError (code `ULJS_BAD_ARG`) if the
991 /// value doesn't have the requested type. Its message says where and why, like a
992 /// bound function's (eg, "volume: expected number, got 'loud'").
993 ///
994 /// @note Requires `<Ultralight/js/TypeTraits.h>` (or any header that includes it).
995 ///
996 template <typename T>
997 [[nodiscard]] Result<T> To() const;
998
999 ///
1000 /// Convert to a C++ type like To() but without the failure reason.
1001 ///
1002 /// @return Returns the converted value or nullopt on any failure.
1003 ///
1004 template <typename T>
1005 [[nodiscard]] std::optional<T> Maybe() const;
1006
1007 ///
1008 /// Convert to a C++ type like To() but with a fallback.
1009 ///
1010 /// @param fallback The value to return if the conversion fails.
1011 ///
1012 /// @return Returns the converted value or `fallback` on any failure.
1013 ///
1014 /// @note The fallback's type is the type converted to, so pass `0.0` (not `0`) to read a
1015 /// number that can have a fraction: `Or(0)` converts to `int` and fails on 3.5.
1016 ///
1017 template <typename T>
1018 [[nodiscard]] T Or(T fallback) const;
1019
1020 ///
1021 /// Convert to a std::string like To() but with a string-literal fallback.
1022 ///
1023 /// @param fallback The text to return if the conversion fails.
1024 ///
1025 /// @return Returns the converted string or `fallback` on any failure.
1026 ///
1027 [[nodiscard]] std::string Or(const char* fallback) const;
1028
1029 ///
1030 /// Call this value as a function with typed arguments and result.
1031 ///
1032 /// The arguments and the result (when you give R) convert through js::TypeTraits:
1033 ///
1034 /// ```
1035 /// js::Result<double> total = fn.Invoke<double>(3, "x");
1036 /// fn.Invoke(path); // result left as a js::Value
1037 /// ```
1038 ///
1039 /// @param args The arguments to pass to the function.
1040 ///
1041 /// @return Returns the call's result converted to R. Fails with a JavaScript exception if
1042 /// the call throws, or with a TypeError if the result doesn't convert to R.
1043 ///
1044 /// @note The function's `this` is the global object. To call a method on an object, call
1045 /// through operator[] (`obj["m"](x)`) or use InvokeOn().
1046 ///
1047 template <typename R = Value, typename... A>
1048 Result<R> Invoke(A&&... args) const;
1049
1050 ///
1051 /// Call this value as a function with an explicit `this` (otherwise the same as Invoke()).
1052 ///
1053 /// ```
1054 /// js::Result<js::Value> row = fn.InvokeOn(receiver, 42);
1055 /// ```
1056 ///
1057 /// @param this_value The `this` value for the call.
1058 ///
1059 /// @param args The arguments to pass to the function.
1060 ///
1061 /// @return Returns the call's result and fails the same way as Invoke().
1062 ///
1063 template <typename R = Value, typename... A>
1064 Result<R> InvokeOn(const Value& this_value, A&&... args) const;
1065
1066 ///
1067 /// Call this value as a constructor with `new`, with typed arguments and result.
1068 ///
1069 /// The arguments and the result (when you give R) convert through js::TypeTraits, as for
1070 /// Invoke():
1071 ///
1072 /// ```
1073 /// js::Result<js::Value> lookup = ctx["Map"].Construct();
1074 /// js::Result<js::Value> launch = ctx["Date"].Construct(2026, 0, 15);
1075 /// ```
1076 ///
1077 /// @param args The arguments to pass to the constructor.
1078 ///
1079 /// @return Returns the new object converted to R. Fails with a TypeError if this value can't
1080 /// be called with `new` or the result doesn't convert to R, or with a JavaScript
1081 /// exception if the constructor throws.
1082 ///
1083 /// @note A `std::vector<js::Value>` argument passes one Array. To pass a list of arguments
1084 /// you build at run time, wrap it in a `std::span<const js::Value>` (see the overload
1085 /// below).
1086 ///
1087 template <typename R = Value, typename... A>
1088 Result<R> Construct(A&&... args) const;
1089
1090 ///
1091 /// Call this value as a constructor with `new`, with the arguments in a range.
1092 ///
1093 /// ```
1094 /// std::vector<js::Value> args = { ctx.Make(3.0), ctx.Make(4.0) };
1095 /// js::Result<js::Value> point = point_class.Construct(std::span<const js::Value>(args));
1096 /// ```
1097 ///
1098 /// @param args The arguments (an empty Value passes `undefined`).
1099 ///
1100 /// @return Returns the new object and fails the same way as the overload above.
1101 ///
1102 [[nodiscard]] Result<Value> Construct(std::span<const Value> args) const {
1103 if (!handle_)
1104 return detail::EmptyHandleError();
1105 RawArgs raw(args.data(), args.size());
1106 ULJSValue exception = nullptr;
1107 ULJSValue result = ulJSFunctionConstruct(handle_, raw.data, args.size(), &exception);
1108 return AdoptResult(result, exception);
1109 }
1110
1111 ///
1112 /// Call this value as a function: `on_save(path)` is the same as `on_save.Invoke(path)`.
1113 ///
1114 /// @param args The arguments to pass to the function.
1115 ///
1116 /// @return Returns the call's result and fails the same way as Invoke().
1117 ///
1118 template <typename... A>
1119 Result<Value> operator()(A&&... args) const {
1120 return Invoke<Value>(std::forward<A>(args)...);
1121 }
1122
1123 ///
1124 /// Wait for this promise to settle without a coroutine.
1125 ///
1126 /// `on_settled` runs once on the Renderer's thread during a later Renderer::Update(). Its
1127 /// Result holds the promise's value or an Error with the rejection reason. If the page goes
1128 /// away first, it gets a page-gone Error instead, so it always runs.
1129 ///
1130 /// ```
1131 /// // Page: myApp.nativeReady(fetch('/level.json').then(r => r.json()));
1132 /// api["nativeReady"] = [](js::Value promise) {
1133 /// bool waiting = promise.Then([](js::Result<js::Value> r) {
1134 /// if (r)
1135 /// LoadLevel(*r); // fulfilled: r holds the value
1136 /// else if (!r.error().is_page_gone())
1137 /// Log(r.error().message()); // rejected: r.error() holds the reason
1138 /// });
1139 /// if (!waiting)
1140 /// Log("nativeReady expects a Promise");
1141 /// };
1142 /// ```
1143 ///
1144 /// @param on_settled A callable that takes a js::Result<js::Value>.
1145 ///
1146 /// @return Returns true if this value is a Promise and `on_settled` will run. Otherwise it
1147 /// returns false and destroys `on_settled` without running it.
1148 ///
1149 /// \parblock
1150 /// @note A rejection you wait for this way counts as handled, so the page doesn't report it
1151 /// as unhandled.
1152 /// \endparblock
1153 ///
1154 /// \parblock
1155 /// @note In a coroutine, use `co_await js::Await<T>(promise)` instead (see
1156 /// `<Ultralight/js/Task.h>`).
1157 /// \endparblock
1158 ///
1159 template <typename F>
1160 [[nodiscard]] bool Then(F&& on_settled) const {
1161 using Fn = std::decay_t<F>;
1162 static_assert(std::is_invocable_v<Fn&, Result<Value>>,
1163 "js::Value::Then takes a callable invocable with js::Result<js::Value>");
1164 auto* fn = new Fn(std::forward<F>(on_settled));
1165 // On registration failure the library destroys the observer inline, freeing `fn`.
1166 return ulJSPromiseThen(handle_, &ThenThunk<Fn>, fn, &DeleteThenCallable<Fn>);
1167 }
1168
1169 ///
1170 /// Wait for this promise to settle and convert its value to a C++ type.
1171 ///
1172 /// ```
1173 /// bool waiting = promise.Then<std::string>([](js::Result<std::string> r) {
1174 /// if (r)
1175 /// ApplyName(*r);
1176 /// });
1177 /// ```
1178 ///
1179 /// @param on_settled A callable that takes a js::Result<T>.
1180 ///
1181 /// @return Returns true if this value is a Promise and `on_settled` will run (see Then()).
1182 ///
1183 /// @note If the value doesn't convert to T (see To()), `on_settled` gets the TypeError.
1184 ///
1185 template <typename T, typename F>
1186 requires(!std::is_same_v<T, Value>)
1187 [[nodiscard]] bool Then(F&& on_settled) const {
1188 using Fn = std::decay_t<F>;
1189 static_assert(std::is_invocable_v<Fn&, Result<T>>,
1190 "js::Value::Then<T> takes a callable invocable with js::Result<T>");
1191 return Then(TypedSettleAdapter<T, Fn> { std::forward<F>(on_settled) });
1192 }
1193
1194 class Ref;
1195
1196 ///
1197 /// Access a property to read, assign, or call it.
1198 ///
1199 /// ```
1200 /// double volume = settings["volume"].Or(0.0);
1201 /// settings["volume"] = 5.0;
1202 /// settings["nested"]["deep"] = js::null;
1203 /// settings["save"]("slot1"); // method call: `this` = settings
1204 /// ```
1205 ///
1206 /// A read that fails (the Value is empty or its page is gone, it holds `null` or `undefined`,
1207 /// or a getter throws) gives you an empty Value instead of an error, like JavaScript's
1208 /// optional chaining. Use GetProperty() or SetProperty() when you need the reason.
1209 ///
1210 /// @param name The property name.
1211 ///
1212 /// @return Returns a Value::Ref for the property.
1213 ///
1214 /// \parblock
1215 /// @note A missing property reads as a valid `undefined` Value (`operator bool` returns
1216 /// true). Use Has() to check whether a property exists.
1217 /// \endparblock
1218 ///
1219 /// \parblock
1220 /// @note You can also index with any integer type (eg, `arr[2]`). A negative index reads the
1221 /// property with that name as JavaScript does (`arr[-1]` reads "-1").
1222 /// \endparblock
1223 ///
1224 Ref operator[](const char* name) const;
1225 template <detail::PropertyIndex I>
1226 Ref operator[](I index) const;
1227
1228 // --- Interop with the C API (most embedders never touch raw handles) -------------------
1229
1230 ///
1231 /// Take ownership of a handle from the C API without adding a reference.
1232 ///
1233 /// Use this for a handle you'd otherwise destroy with ulDestroyJSValue() (eg, the return value
1234 /// of a C function).
1235 ///
1236 /// @param handle The handle to take ownership of.
1237 ///
1238 /// @return Returns a Value that owns `handle`.
1239 ///
1240 /// @note For a handle the library owns (eg, a callback argument), use FromBorrowed().
1241 ///
1242 static Value Adopt(ULJSValue handle) { return Value(handle); }
1243
1244 ///
1245 /// Add a reference to a handle the library owns (eg, a callback argument) so it can outlive
1246 /// the callback.
1247 ///
1248 /// @param handle The borrowed handle.
1249 ///
1250 /// @return Returns a Value with its own reference to `handle`.
1251 ///
1252 /// @note For a handle you own, use Adopt().
1253 ///
1254 static Value FromBorrowed(ULJSValue handle) {
1255 return Value(handle ? ulCreateJSValueRef(handle) : nullptr);
1256 }
1257
1258 ///
1259 /// Get the C API handle without transferring ownership.
1260 ///
1261 /// @return Returns the handle for use with the `<Ultralight/CAPI/CAPI_JSValue.h>` functions.
1262 ///
1263 ULJSValue raw() const { return handle_; }
1264
1265 ///
1266 /// Give up ownership of the C API handle and return it (like RefPtr::LeakRef()).
1267 ///
1268 /// @return Returns the handle. You must destroy it with ulDestroyJSValue() when finished.
1269 ///
1270 ULJSValue LeakRef() {
1271 ULJSValue handle = handle_;
1272 handle_ = nullptr;
1273 return handle;
1274 }
1275
1276 protected:
1277 explicit Value(ULJSValue handle) : handle_(handle) {}
1278
1279 private:
1280 // Decimal property name for integer indexes JavaScript treats as string keys.
1281 struct IndexKey {
1282 char text[24];
1283 };
1284
1285 static IndexKey MakeIndexKey(long long value) {
1286 IndexKey key;
1287 snprintf(key.text, sizeof(key.text), "%lld", value);
1288 return key;
1289 }
1290
1291 static IndexKey MakeIndexKey(unsigned long long value) {
1292 IndexKey key;
1293 snprintf(key.text, sizeof(key.text), "%llu", value);
1294 return key;
1295 }
1296
1297 template <detail::PropertyIndex I>
1298 static IndexKey IndexName(I index) {
1299 if constexpr (std::is_signed_v<I>)
1300 return MakeIndexKey(static_cast<long long>(index));
1301 else
1302 return MakeIndexKey(static_cast<unsigned long long>(index));
1303 }
1304
1305 // Where an integer index goes: the waist's index form, or the decimal name for an index it
1306 // can't take (negative, or above SIZE_MAX on 32-bit targets).
1307 struct PropertyKey {
1308 bool by_index;
1309 size_t index;
1310 IndexKey name;
1311 };
1312
1313 template <detail::PropertyIndex I>
1314 static PropertyKey ResolveIndex(I index) {
1315 if constexpr (std::is_signed_v<I>) {
1316 if (index < 0)
1317 return { false, 0, IndexName(index) };
1318 }
1319 unsigned long long wide = static_cast<unsigned long long>(index);
1320 if (wide > SIZE_MAX)
1321 return { false, 0, IndexName(index) };
1322 return { true, static_cast<size_t>(wide), {} };
1323 }
1324
1325 bool DeleteByKey(const PropertyKey& key, ULJSValue* exception) const {
1326 if (key.by_index)
1327 return ulJSObjectDeletePropertyAtIndex(handle_, key.index, exception);
1328 return ulJSObjectDeleteProperty(handle_, key.name.text, exception);
1329 }
1330
1331 template <typename I>
1332 Ref MakeIndexRef(I index) const;
1333
1334 // The Result of a waist call whose bool is meaningful on success: an exception wins, then a
1335 // gone page, so a false only reaches the caller from a live page.
1336 Result<bool> CheckedBool(bool value, ULJSValue exception) const {
1337 if (exception)
1338 return Unexpected<Error>(Error::AdoptException(exception));
1339 if (!IsAlive())
1340 return Unexpected<Error>(Error::PageGone());
1341 return value;
1342 }
1343
1344 static Result<Value> AdoptResult(ULJSValue result, ULJSValue exception) {
1345 if (result)
1346 return Adopt(result);
1347 if (exception)
1348 return Unexpected<Error>(Error::AdoptException(exception));
1349 return Unexpected<Error>(Error::PageGone());
1350 }
1351
1352 // The raw handles of a call's arguments: typical calls stay on the stack, rare wide calls
1353 // take one heap allocation.
1354 struct RawArgs {
1355 ULJSValue stack[8];
1356 ULJSValue* data;
1357
1358 RawArgs(const Value* args, size_t argc) : data(argc > 8 ? new ULJSValue[argc] : stack) {
1359 for (size_t i = 0; i < argc; i++)
1360 data[i] = args[i].handle_;
1361 }
1362 ~RawArgs() {
1363 if (data != stack)
1364 delete[] data;
1365 }
1366 RawArgs(const RawArgs&) = delete;
1367 RawArgs& operator=(const RawArgs&) = delete;
1368 };
1369
1370 // Named functor (never a lambda: the MSVC alias-in-lambda discipline) bridging the
1371 // untyped settlement to Then<T>'s typed callback.
1372 template <typename T, typename Fn>
1373 struct TypedSettleAdapter {
1374 Fn fn;
1375 void operator()(Result<Value> settled) {
1376 if (!settled)
1377 fn(Result<T>(Unexpected<Error>(std::move(settled).error())));
1378 else
1379 fn(settled.value().To<T>());
1380 }
1381 };
1382
1383 template <typename Fn>
1384 static void ThenThunk(void* user_data, ULJSContext, ULJSValue result, bool rejected) {
1385 Fn& fn = *static_cast<Fn*>(user_data);
1386 // The callback runs inside the library's update: an exception must not unwind into it.
1387 ultralight::detail::CallCatchingExceptions(
1388 [&] {
1389 if (!result)
1390 fn(Result<Value>(Unexpected<Error>(Error::PageGone())));
1391 else if (rejected)
1392 fn(Result<Value>(
1393 Unexpected<Error>(Error::AdoptException(ulCreateJSValueRef(result)))));
1394 else
1396 },
1397 [](const char* what) { detail::LogNativeException("js::Value::Then", what); });
1398 }
1399
1400 template <typename Fn>
1401 static void DeleteThenCallable(void* user_data) {
1402 delete static_cast<Fn*>(user_data);
1403 }
1404
1405 ULJSValue handle_;
1406};
1407
1408///
1409/// A reference to a property of a Value (returned by Value::operator[]).
1410///
1411/// Reading a Ref gives you the property's value, assigning to it sets the property, and calling
1412/// it calls the property as a method of the object. Refs chain (`obj["a"]["b"] = 1`).
1413///
1414/// Use a Ref within one expression. To keep a property's value, read it into a Value.
1415///
1416/// @note A Ref has To(), Maybe(), and Or(). For the other conversions, read the property first
1417/// (eg, `obj["volume"].Get().ToNumber()`).
1418///
1420 public:
1421 ///
1422 /// Read the property.
1423 ///
1424 /// @return Returns the property value (an empty Value if the read fails, see
1425 /// Value::operator[]()).
1426 ///
1427 [[nodiscard]] Value Get() const {
1428 detail::SwallowedException swallow;
1429 if (by_index_)
1430 return Value::Adopt(
1431 object_.raw() ? ulJSObjectGetPropertyAtIndex(object_.raw(), index_, swallow.out())
1432 : nullptr);
1433 return Value::Adopt(
1434 object_.raw() ? ulJSObjectGetProperty(object_.raw(), name_.c_str(), swallow.out())
1435 : nullptr);
1436 }
1437
1438 ///
1439 /// Read the property (the same as Get()).
1440 ///
1441 operator Value() const { return Get(); }
1442
1443 ///
1444 /// Set the property to `value` (converted through js::TypeTraits).
1445 ///
1446 /// @param value The value to assign.
1447 ///
1448 /// @return Returns this Ref.
1449 ///
1450 /// @note Failures are ignored (eg, the page is gone or a setter throws). Use
1451 /// Value::SetProperty() if you need to check.
1452 ///
1453 template <typename T>
1454 Ref& operator=(T&& value);
1455
1456 ///
1457 /// Read this property and access a property of its value.
1458 ///
1459 /// @param name The property name.
1460 ///
1461 /// @return Returns a Ref for the nested property.
1462 ///
1463 Ref operator[](const char* name) const {
1464 Value value = Get();
1465 return Chained(value, value[name]);
1466 }
1467 template <detail::PropertyIndex I>
1468 Ref operator[](I index) const {
1469 Value value = Get();
1470 return Chained(value, value[index]);
1471 }
1472
1473 ///
1474 /// Call the property as a method of its object (otherwise the same as Value::Invoke()).
1475 ///
1476 /// ```
1477 /// global["JSON"]["stringify"](payload);
1478 /// js::Result<double> total = cart["total"].Invoke<double>();
1479 /// ```
1480 ///
1481 /// @param args The arguments to pass to the method.
1482 ///
1483 /// @return Returns the call's result converted to R and fails the same way as
1484 /// Value::Invoke().
1485 ///
1486 template <typename R = Value, typename... A>
1487 Result<R> Invoke(A&&... args) const;
1488
1489 ///
1490 /// Read the property and call it as a constructor with `new` (otherwise the same as
1491 /// Value::Construct()).
1492 ///
1493 /// ```
1494 /// js::Result<js::Value> lookup = ctx["Map"].Construct();
1495 /// ```
1496 ///
1497 /// @param args The arguments to pass to the constructor.
1498 ///
1499 /// @return Returns the new object converted to R and fails the same way as
1500 /// Value::Construct().
1501 ///
1502 template <typename R = Value, typename... A>
1503 Result<R> Construct(A&&... args) const;
1504
1505 ///
1506 /// Call the property as a method: `obj["save"](path)` is the same as `obj["save"].Invoke(path)`.
1507 ///
1508 /// @param args The arguments to pass to the method.
1509 ///
1510 /// @return Returns the call's result and fails the same way as Invoke().
1511 ///
1512 template <typename... A>
1513 Result<Value> operator()(A&&... args) const {
1514 return Invoke<Value>(std::forward<A>(args)...);
1515 }
1516
1517 ///
1518 /// Read the property and convert it to a C++ type (see Value::To()).
1519 ///
1520 /// @return Returns the converted value and fails the same way as Value::To().
1521 ///
1522 template <typename T>
1523 [[nodiscard]] Result<T> To() const;
1524
1525 ///
1526 /// Read the property and convert it to a C++ type like To() but without the failure reason.
1527 ///
1528 /// @return Returns the converted value or nullopt on any failure.
1529 ///
1530 template <typename T>
1531 [[nodiscard]] std::optional<T> Maybe() const;
1532
1533 ///
1534 /// Read the property and convert it to a C++ type with a fallback.
1535 ///
1536 /// @param fallback The value to return if the read or the conversion fails.
1537 ///
1538 /// @return Returns the converted value or `fallback` on any failure.
1539 ///
1540 template <typename T>
1541 [[nodiscard]] T Or(T fallback) const;
1542
1543 ///
1544 /// Read the property and convert it to a std::string with a string-literal fallback.
1545 ///
1546 /// @param fallback The text to return if the read or the conversion fails.
1547 ///
1548 /// @return Returns the converted string or `fallback` on any failure.
1549 ///
1550 [[nodiscard]] std::string Or(const char* fallback) const { return Get().Or(fallback); }
1551
1552 ///
1553 /// Copy constructor (refers to the same property).
1554 ///
1555 Ref(const Ref&) = default;
1556
1557 ///
1558 /// Set this property to the value of another Ref's property.
1559 ///
1560 /// @param other The Ref to read the value from.
1561 ///
1562 /// @return Returns this Ref.
1563 ///
1564 /// @note A Ref always refers to the same property: assigning to it sets the property's value
1565 /// and never changes which property it refers to (like std::map's operator[]).
1566 ///
1567 Ref& operator=(const Ref& other) { return (*this) = other.Get(); }
1568
1569 private:
1570 friend class Value;
1571 friend class Context;
1572 Ref(Value object, const char* name)
1573 : object_(std::move(object)), name_(name ? name : ""), by_index_(false), index_(0) {}
1574 Ref(Value object, size_t index)
1575 : object_(std::move(object)), by_index_(true), index_(index) {}
1576
1577 // Whether a failed read here is because the page is gone: this Ref's object belongs to a page
1578 // that's gone, or the chain it came from started at one.
1579 bool SourceGone() const { return source_gone_ || (object_.raw() && !object_.IsAlive()); }
1580
1581 // A chain continued through a failed read keeps reporting a gone page as page-gone, not as an
1582 // empty handle.
1583 Ref Chained(const Value& value, Ref next) const {
1584 next.source_gone_ = value.IsEmpty() && SourceGone();
1585 return next;
1586 }
1587
1588 Value object_;
1589 std::string name_;
1590 bool by_index_;
1591 size_t index_;
1592 bool source_gone_ = false;
1593};
1594
1595inline Value::Ref Value::operator[](const char* name) const {
1596 return Ref(*this, name);
1597}
1598
1599template <typename I>
1600Value::Ref Value::MakeIndexRef(I index) const {
1601 PropertyKey key = ResolveIndex(index);
1602 if (key.by_index)
1603 return Ref(*this, key.index);
1604 return Ref(*this, key.name.text);
1605}
1606
1607template <detail::PropertyIndex I>
1609 return MakeIndexRef(index);
1610}
1611
1612///
1613/// Compare against the JavaScript `null` literal: `if (v == js::null)`.
1614///
1615/// @return Returns whether the value is JavaScript `null`.
1616///
1617inline bool operator==(const Value& value, NullType) {
1618 return value.IsNull();
1619}
1620
1621///
1622/// Compare against the JavaScript `undefined` literal: `if (v == js::undefined)`.
1623///
1624/// @return Returns whether the value is JavaScript `undefined`.
1625///
1626inline bool operator==(const Value& value, UndefinedType) {
1627 return value.IsUndefined();
1628}
1629
1630///
1631/// An argument passed to a bound function.
1632///
1633/// An Arg is only valid during the callback that received it (it adds no reference, so reading
1634/// it is cheap). Call ToValue() to keep the argument after the callback returns.
1635///
1636/// An Arg has To(), Maybe(), and Or(). Other conversions need a Value first (eg,
1637/// `arg.ToValue().ToNumber()`).
1638///
1639/// @see CallInfo::arg()
1640///
1641class Arg {
1642 public:
1643 ///
1644 /// Wrap a borrowed handle.
1645 ///
1646 /// @param borrowed The handle (valid only during the callback).
1647 ///
1648 /// @note You normally get an Arg from CallInfo::arg() instead of creating one.
1649 ///
1650 explicit Arg(ULJSValue borrowed) : borrowed_(borrowed) {}
1651
1652 ///
1653 /// Whether or not the argument is absent (the call passed fewer arguments than the index
1654 /// given to CallInfo::arg()).
1655 ///
1656 /// @note An absent argument converts only to an optional type (as an empty optional). Any
1657 /// other To() fails with a TypeError, and ToValue() returns an empty Value.
1658 ///
1659 bool IsEmpty() const { return borrowed_ == nullptr; }
1660
1661 ///
1662 /// Get the argument's type (Type::Invalid if the argument is absent).
1663 ///
1664 Type type() const { return static_cast<Type>(ulJSValueGetType(borrowed_)); }
1665
1666 ///
1667 /// Convert to a C++ type (see Value::To()).
1668 ///
1669 /// @return Returns the converted value and fails the same way as Value::To().
1670 ///
1671 /// @note Requires `<Ultralight/js/TypeTraits.h>` (or any header that includes it).
1672 ///
1673 template <typename T>
1674 [[nodiscard]] Result<T> To() const;
1675
1676 ///
1677 /// Convert to a C++ type like To() but without the failure reason.
1678 ///
1679 /// @return Returns the converted value or nullopt on any failure.
1680 ///
1681 template <typename T>
1682 [[nodiscard]] std::optional<T> Maybe() const;
1683
1684 ///
1685 /// Convert to a C++ type like To() but with a fallback.
1686 ///
1687 /// @param fallback The value to return if the conversion fails.
1688 ///
1689 /// @return Returns the converted value or `fallback` on any failure.
1690 ///
1691 template <typename T>
1692 [[nodiscard]] T Or(T fallback) const;
1693
1694 ///
1695 /// Convert to a std::string like To() but with a string-literal fallback.
1696 ///
1697 /// @param fallback The text to return if the conversion fails.
1698 ///
1699 /// @return Returns the converted string or `fallback` on any failure.
1700 ///
1701 [[nodiscard]] std::string Or(const char* fallback) const;
1702
1703 ///
1704 /// Get a Value that keeps the argument after the callback returns.
1705 ///
1706 /// @return Returns the new Value.
1707 ///
1708 Value ToValue() const { return Value::FromBorrowed(borrowed_); }
1709
1710 ///
1711 /// Get the C API handle.
1712 ///
1713 /// @return Returns the handle (valid only during the callback).
1714 ///
1715 ULJSValue raw() const { return borrowed_; }
1716
1717 private:
1718 ULJSValue borrowed_;
1719};
1720
1721///
1722/// Convert a value to a C++ type with a fallback (the free-function form of Value::Or()).
1723///
1724/// This takes a Value, a Value::Ref, a js::Arg, or the Result of a call. The value must already
1725/// have the requested JavaScript type (see Value::To()). Any failure returns `fallback` (eg, a
1726/// missing property or a failed call):
1727///
1728/// ```
1729/// double score = js::Or(ctx["score"], 0.0);
1730/// double total = js::Or(ctx["computeTotal"](3, 4), 0.0);
1731/// std::string name = js::Or(ctx["playerName"](), "guest");
1732/// ```
1733///
1734/// @param value The value to convert.
1735///
1736/// @param fallback The value to return if the conversion fails.
1737///
1738/// @return Returns the converted value or `fallback` on any failure.
1739///
1740/// @note Requires `<Ultralight/js/TypeTraits.h>` (or any header that includes it).
1741///
1742template <typename T>
1743[[nodiscard]] T Or(const Value& value, T fallback) {
1744 return value.Or(std::move(fallback));
1745}
1746
1747///
1748/// Convert a value to a std::string with a string-literal fallback.
1749///
1750/// @param value The value to convert.
1751///
1752/// @param fallback The text to return if the conversion fails.
1753///
1754/// @return Returns the converted string or `fallback` on any failure.
1755///
1756[[nodiscard]] inline std::string Or(const Value& value, const char* fallback) {
1757 return value.Or(fallback);
1758}
1759
1760///
1761/// Convert a callback argument to a C++ type with a fallback.
1762///
1763/// @param arg The argument to convert.
1764///
1765/// @param fallback The value to return if the conversion fails.
1766///
1767/// @return Returns the converted value or `fallback` on any failure.
1768///
1769template <typename T>
1770[[nodiscard]] T Or(const Arg& arg, T fallback) {
1771 return arg.Or(std::move(fallback));
1772}
1773
1774///
1775/// Convert a callback argument to a std::string with a string-literal fallback.
1776///
1777/// @param arg The argument to convert.
1778///
1779/// @param fallback The text to return if the conversion fails.
1780///
1781/// @return Returns the converted string or `fallback` on any failure.
1782///
1783[[nodiscard]] inline std::string Or(const Arg& arg, const char* fallback) {
1784 return arg.Or(fallback);
1785}
1786
1787///
1788/// Convert the value a call returned to a C++ type with a fallback.
1789///
1790/// @param result The call's result.
1791///
1792/// @param fallback The value to return if the call or the conversion failed.
1793///
1794/// @return Returns the converted value or `fallback` on any failure.
1795///
1796template <typename R, typename T>
1797 requires std::is_same_v<std::remove_cvref_t<R>, Result<Value>>
1798[[nodiscard]] T Or(const R& result, T fallback) {
1799 return result ? result.value().Or(std::move(fallback)) : fallback;
1800}
1801
1802///
1803/// Convert the value a call returned to a std::string with a string-literal fallback.
1804///
1805/// @param result The call's result.
1806///
1807/// @param fallback The text to return if the call or the conversion failed.
1808///
1809/// @return Returns the converted string or `fallback` on any failure.
1810///
1811template <typename R>
1812 requires std::is_same_v<std::remove_cvref_t<R>, Result<Value>>
1813[[nodiscard]] std::string Or(const R& result, const char* fallback) {
1814 return result ? result.value().Or(fallback) : std::string(fallback ? fallback : "");
1815}
1816
1817///
1818/// Get a typed Result's value or `fallback` if it holds an error.
1819///
1820/// This is the same as `result.value_or(fallback)` and lets a typed call read like an untyped
1821/// one: `js::Or(fn.Invoke<double>(3, 4), 0.0)`.
1822///
1823/// @param result The typed result.
1824///
1825/// @param fallback The value to return if the result holds an error.
1826///
1827/// @return Returns the result's value or `fallback`.
1828///
1829template <typename T, typename U>
1830 requires(!std::is_same_v<T, Value>)
1831[[nodiscard]] T Or(const Result<T>& result, U&& fallback) {
1832 return result.value_or(std::forward<U>(fallback));
1833}
1834
1835///
1836/// Get the value a JavaScript exception threw, to keep it or pass it back to the page.
1837///
1838/// ```
1839/// js::Result<js::Value> r = ctx.Evaluate("JSON.parse('{')");
1840/// if (!r && r.error().is_exception())
1841/// ctx["lastError"] = js::ExceptionValue(r.error());
1842/// ```
1843///
1844/// @param error The error.
1845///
1846/// @return Returns the thrown value (an empty Value if `error` doesn't hold a JavaScript
1847/// exception).
1848///
1849inline Value ExceptionValue(const Error& error) {
1850 return Value::FromBorrowed(error.exception());
1851}
1852
1853} // namespace js
1854} // namespace ultralight
1855
1856#pragma pop_macro("None")
struct C_JSContext * ULJSContext
Opaque handle to a JavaScript execution context (one page's script world in one View).
Definition View.h:25
Unicode string container with conversions for UTF-8, UTF-16, and UTF-32.
Definition String.h:31
An argument passed to a bound function.
Definition Value.h:1641
std::string Or(const char *fallback) const
Convert to a std::string like To() but with a string-literal fallback.
T Or(T fallback) const
Convert to a C++ type like To() but with a fallback.
bool IsEmpty() const
Whether or not the argument is absent (the call passed fewer arguments than the index given to CallIn...
Definition Value.h:1659
Result< T > To() const
Convert to a C++ type (see Value::To()).
std::optional< T > Maybe() const
Convert to a C++ type like To() but without the failure reason.
Type type() const
Get the argument's type (Type::Invalid if the argument is absent).
Definition Value.h:1664
Arg(ULJSValue borrowed)
Wrap a borrowed handle.
Definition Value.h:1650
Value ToValue() const
Get a Value that keeps the argument after the callback returns.
Definition Value.h:1708
ULJSValue raw() const
Get the C API handle.
Definition Value.h:1715
Handle to a JavaScript ArrayBuffer for sharing raw binary memory with the page.
Definition Buffer.h:88
An error from a JavaScript operation.
Definition Error.h:115
static Error AdoptException(ULJSValue exception)
Create an error from a JavaScript exception, taking ownership of the handle.
Definition Error.h:131
static Error TypeError(std::string message)
Create a native TypeError.
Definition Error.h:144
static Error PageGone()
Create a page-gone error (is_page_gone() returns true).
Definition Error.h:122
ULJSValue exception() const
Get the JavaScript exception (NULL if is_exception() is false).
Definition Error.h:268
Handle to a JavaScript typed array on a page.
Definition Buffer.h:203
A reference to a property of a Value (returned by Value::operator[]).
Definition Value.h:1419
Ref operator[](const char *name) const
Read this property and access a property of its value.
Definition Value.h:1463
Ref & operator=(const Ref &other)
Set this property to the value of another Ref's property.
Definition Value.h:1567
Ref(const Ref &)=default
Copy constructor (refers to the same property).
std::string Or(const char *fallback) const
Read the property and convert it to a std::string with a string-literal fallback.
Definition Value.h:1550
T Or(T fallback) const
Read the property and convert it to a C++ type with a fallback.
Ref & operator=(T &&value)
Set the property to value (converted through js::TypeTraits).
Value Get() const
Read the property.
Definition Value.h:1427
Result< R > Invoke(A &&... args) const
Call the property as a method of its object (otherwise the same as Value::Invoke()).
Result< Value > operator()(A &&... args) const
Call the property as a method: obj["save"](path) is the same as obj["save"].Invoke(path).
Definition Value.h:1513
Result< T > To() const
Read the property and convert it to a C++ type (see Value::To()).
Result< R > Construct(A &&... args) const
Read the property and call it as a constructor with new (otherwise the same as Value::Construct()).
friend class Context
Definition Value.h:1571
std::optional< T > Maybe() const
Read the property and convert it to a C++ type like To() but without the failure reason.
Ref operator[](I index) const
Definition Value.h:1468
friend class Value
Definition Value.h:1570
A handle to a live JavaScript value.
Definition Value.h:276
bool Has(const char *name) const
Whether or not this object has a property (own or inherited).
Definition Value.h:591
Ref operator[](const char *name) const
Access a property to read, assign, or call it.
Definition Value.h:1595
Value(Value &&other) noexcept
Move constructor (other becomes empty).
Definition Value.h:292
Value & operator=(Value other) noexcept
Assignment (copies or moves other into this Value).
Definition Value.h:297
std::string Or(const char *fallback) const
Convert to a std::string like To() but with a string-literal fallback.
static Value Adopt(ULJSValue handle)
Take ownership of a handle from the C API without adding a reference.
Definition Value.h:1242
bool IsCallable() const
Whether or not the value can be called (see Call() and Invoke()).
Definition Value.h:383
static Value FromBorrowed(ULJSValue handle)
Add a reference to a handle the library owns (eg, a callback argument) so it can outlive the callback...
Definition Value.h:1254
Result< double > ToNumber() const
Convert to a number using JavaScript's rules.
Definition Value.h:481
Result< std::string > ToString() const
Convert to a UTF-8 string using JavaScript's rules.
Definition Value.h:500
Result< void > Freeze() const
Freeze this object (like Object.freeze()), so no property can be added, removed, or changed afterward...
Definition Value.h:920
ULJSValue LeakRef()
Give up ownership of the C API handle and return it (like RefPtr::LeakRef()).
Definition Value.h:1270
T Or(T fallback) const
Convert to a C++ type like To() but with a fallback.
Result< bool > DeleteProperty(I index) const
Delete an element of this object by index (eg, arr.DeleteProperty(2)).
Definition Value.h:682
Value(const Value &other)
Copy constructor (adds a reference to the same JavaScript value).
Definition Value.h:286
Result< R > InvokeOn(const Value &this_value, A &&... args) const
Call this value as a function with an explicit this (otherwise the same as Invoke()).
Result< bool > HasProperty(const char *name) const
Whether or not this object has a property (like Has(), but reports failures).
Definition Value.h:604
Result< bool > DefineProperty(const char *name, const Value &value, PropertyAttributes attributes=PropertyAttributes::None) const
Define a data property of this object (like Reflect.defineProperty()).
Definition Value.h:857
bool Delete(I index) const
Delete an element of this object by index (like Delete(), but taking an index).
Definition Value.h:714
bool HasOwn(const char *name) const
Whether or not this object has an own property (one that isn't inherited, like Object....
Definition Value.h:730
bool StrictEquals(const Value &other) const
Whether or not this value and other are strictly equal (like JavaScript's ===).
Definition Value.h:435
bool IsNumber() const
Whether or not the value is a number.
Definition Value.h:356
Result< double > TimeValue() const
Get the time value of a Date, in milliseconds since the epoch (like date.getTime()).
Definition Value.h:450
Result< bool > ToBoolean() const
Convert to a boolean using JavaScript's rules (this never runs script).
Definition Value.h:466
Result< bool > HasOwnProperty(const char *name) const
Whether or not this object has an own property (like HasOwn(), but reports failures).
Definition Value.h:758
bool IsObject() const
Whether or not the value is an object.
Definition Value.h:373
bool IsPromise() const
Whether or not the value is a Promise.
Definition Value.h:398
Result< std::vector< std::string > > OwnKeys(OwnKeysFlags flags=OwnKeysFlags::None) const
Get the names of this object's own properties, without reading their values.
Definition Value.h:804
bool IsString() const
Whether or not the value is a string.
Definition Value.h:366
Result< bool > HasOwnProperty(I index) const
Whether or not this object has an own element at an index (like HasOwn(), but reports failures).
Definition Value.h:777
bool Then(F &&on_settled) const
Wait for this promise to settle and convert its value to a C++ type.
Definition Value.h:1187
bool IsEmpty() const
Whether or not this Value holds nothing (see "Handle States" above).
Definition Value.h:315
bool IsAlive() const
Whether or not this Value's page is still alive (the same test as operator bool).
Definition Value.h:323
bool Delete(const char *name) const
Delete a property of this object (like DeleteProperty(), but without the failure reason).
Definition Value.h:698
~Value()
Destructor (releases this handle).
Definition Value.h:305
Result< bool > DefineAccessor(const char *name, const Value &getter, const Value &setter, PropertyAttributes attributes=PropertyAttributes::None) const
Define an accessor property of this object, with a getter and a setter function (like Reflect....
Definition Value.h:896
Result< std::string > ToJSON(unsigned indent=0) const
Convert to JSON text like JSON.stringify() does.
Definition Value.h:540
Result< R > Invoke(A &&... args) const
Call this value as a function with typed arguments and result.
Result< Value > operator()(A &&... args) const
Call this value as a function: on_save(path) is the same as on_save.Invoke(path).
Definition Value.h:1119
bool IsConstructor() const
Whether or not the value can be called with new (see Construct()).
Definition Value.h:403
Result< Value > GetProperty(const char *name) const
Get a property of this object (own or inherited).
Definition Value.h:567
Result< T > To() const
Convert to a C++ type.
Result< R > Construct(A &&... args) const
Call this value as a constructor with new, with typed arguments and result.
Value(ULJSValue handle)
Definition Value.h:1277
bool IsNullish() const
Whether or not the value is null or undefined.
Definition Value.h:346
Value()
Create an empty Value.
Definition Value.h:281
Result< void > SetProperty(const char *name, const Value &value, PropertyAttributes attributes=PropertyAttributes::None) const
Set a property of this object.
Definition Value.h:632
bool IsBigInt() const
Whether or not the value is a BigInt (eg, 10n).
Definition Value.h:361
Result< Value > Construct(std::span< const Value > args) const
Call this value as a constructor with new, with the arguments in a range.
Definition Value.h:1102
bool IsNull() const
Whether or not the value is null.
Definition Value.h:341
bool IsBoolean() const
Whether or not the value is a boolean.
Definition Value.h:351
Result< Value > Call(const Value &this_value, std::span< const Value > args) const
Call this value as a function with the arguments in a range (eg, a std::vector<js::Value>).
Definition Value.h:964
ObjectKind object_kind() const
Get the kind of object the value is (eg, a Map, a Date, or an ordinary object).
Definition Value.h:420
std::optional< T > Maybe() const
Convert to a C++ type like To() but without the failure reason.
bool HasOwn(I index) const
Whether or not this object has an own element at an index (eg, arr.HasOwn(2) is false for a hole).
Definition Value.h:745
Type type() const
Get the type of the value.
Definition Value.h:331
Result< bool > DeleteProperty(const char *name) const
Delete a property of this object (like JavaScript's delete operator).
Definition Value.h:662
bool IsUndefined() const
Whether or not the value is undefined.
Definition Value.h:336
bool Then(F &&on_settled) const
Wait for this promise to settle without a coroutine.
Definition Value.h:1160
Result< Value > Call(const Value &this_value, const Value *args, size_t argc) const
Call this value as a function.
Definition Value.h:943
bool IsFunction() const
Whether or not the value is a function.
Definition Value.h:391
bool IsArray() const
Whether or not the value is an Array.
Definition Value.h:378
ULJSValue raw() const
Get the C API handle without transferring ownership.
Definition Value.h:1263
Definition StringSTL.h:166
Type-checked JavaScript bridge between C++ and web pages.
Definition JSInterop.h:141
constexpr UndefinedType undefined
The JavaScript undefined value.
Definition Value.h:59
T Or(const Value &value, T fallback)
Convert a value to a C++ type with a fallback (the free-function form of Value::Or()).
Definition Value.h:1743
Type
The type of a JavaScript value.
Definition Value.h:97
@ Symbol
Definition Value.h:104
@ String
Definition Value.h:103
@ Boolean
Definition Value.h:101
@ Object
Definition Value.h:106
@ Invalid
An empty Value, or one whose page is gone.
Definition Value.h:98
@ BigInt
Definition Value.h:105
@ Number
Definition Value.h:102
@ Null
Definition Value.h:100
@ Undefined
Definition Value.h:99
ObjectKind
The kind of a JavaScript object.
Definition Value.h:123
@ WeakSet
Definition Value.h:137
@ Array
Definition Value.h:127
@ Date
Definition Value.h:132
@ Map
Definition Value.h:134
@ Plain
An ordinary object (eg, {} or an instance of a JS class).
Definition Value.h:126
@ Set
Definition Value.h:135
@ WeakMap
Definition Value.h:136
@ Function
A callable object that isn't a Proxy (a native class constructor included, although Value::IsFunction...
Definition Value.h:130
@ DataView
Definition Value.h:142
@ Promise
Definition Value.h:138
@ RegExp
Definition Value.h:133
@ Proxy
A Proxy (callable or not).
Definition Value.h:131
constexpr NullType null
The JavaScript null value.
Definition Value.h:49
Value ExceptionValue(const Error &error)
Get the value a JavaScript exception threw, to keep it or pass it back to the page.
Definition Value.h:1849
constexpr AttachFlags operator|(AttachFlags a, AttachFlags b)
Combine attach flags.
Definition API.h:57
PropertyAttributes
Attribute flags for a property created by Value::SetProperty() or Value::DefineProperty().
Definition Value.h:74
@ DontDelete
The property can't be deleted.
Definition Value.h:78
@ ReadOnly
Script can't change its value.
Definition Value.h:76
@ DontEnum
Hidden from for...in and Object.keys.
Definition Value.h:77
@ None
No flags (a normal property).
Definition Value.h:75
OwnKeysFlags
Flags for Value::OwnKeys().
Definition Value.h:153
@ IncludeNonEnumerable
Non-enumerable keys too.
Definition Value.h:155
@ None
Enumerable keys only.
Definition Value.h:154
bool operator==(const Value &value, NullType)
Compare against the JavaScript null literal: if (v == js::null).
Definition Value.h:1617
Expected< T, Error > Result
The result of a JavaScript operation that can fail: a T or a js::Error.
Definition Error.h:520
Root namespace for every public Ultralight type, function, and enumeration.
@ Other
A focused element that is not a text-editing target (eg, a select).
Definition Editor.h:98
@ None
Definition Anchor.h:36
Tag type for the JavaScript null value (see js::null).
Definition Value.h:41
Type conversions between C++ and JavaScript across the bridge.
Definition TypeTraits.h:244
Tag type for the JavaScript undefined value (see js::undefined).
Definition Value.h:54