| Title: | Interface for the 'QuickJS-NG' Lightweight 'JavaScript' Engine |
|---|---|
| Description: | An 'R' interface to the 'QuickJS' portable 'JavaScript' engine. The engine and all 'R' to 'JavaScript' interoperability is bundled within the package, requiring no dependencies beyond a 'C' compiler. |
| Authors: | Andrew R. Johnson [aut, cre] (ORCID: <https://orcid.org/0000-0001-7000-8065>), QuickJS Authors [cph] (QuickJS sources and headers), QuickJS-NG Authors [cph] (QuickJS-NG sources and headers) |
| Maintainer: | Andrew R. Johnson <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.11.9000 |
| Built: | 2026-10-11 16:20:44 UTC |
| Source: | https://github.com/andrjohns/QuickJSR |
An interface to the QuickJS lightweight Javascript engine
Maintainer: Andrew R. Johnson [email protected] (ORCID)
Authors:
Andrew R. Johnson [email protected] (ORCID)
Other contributors:
QuickJS Authors (QuickJS sources and headers) [copyright holder]
QuickJS-NG Authors (QuickJS-NG sources and headers) [copyright holder]
Useful links:
Report bugs at https://github.com/andrjohns/QuickJSR/issues
Use the QuickJS C API to convert a JSON string to an R object
from_json(json)from_json(json)
json |
JSON string to convert to an R object |
R object
Transfers a data frame as one JavaScript object whose properties are columns.
This avoids creating one object per row. With typed = TRUE, raw,
integer, and double columns use contiguous typed arrays. Integer columns with
missing values, factors, and date-time columns use ordinary arrays. Double
NA and NaN values become JavaScript NaN in typed columns.
Explicit character row names are included as the _row column.
js_columnar_data_frame(x, typed = TRUE)js_columnar_data_frame(x, typed = TRUE)
x |
A data frame. |
typed |
Use typed arrays for eligible raw, integer, and double columns. |
The data frame marked for column-oriented conversion.
ctx <- JSContext$new() ctx$source(code = "function rows(x) { return x.value.length; }") df <- data.frame(value = 1:4, label = letters[1:4]) ctx$call("rows", js_columnar_data_frame(df))ctx <- JSContext$new() ctx$source(code = "function rows(x) { return x.value.length; }") df <- data.frame(value = 1:4, label = letters[1:4]) ctx$call("rows", js_columnar_data_frame(df))
Transfers an R vector as a branded JavaScript object containing contiguous
values and validity typed arrays. The validity byte is zero for
a missing value and one otherwise.
js_masked_typed_array(x)js_masked_typed_array(x)
x |
A logical, integer, or double vector without factor or date classes. |
Logical values use a Uint8Array, integers use an Int32Array, and
doubles use a Float64Array. Every representation uses a
Uint8Array validity mask and exposes the original length as
length.
R integer and logical NA values have validity zero and a placeholder
value of zero. Double NA is treated the same way, while ordinary
NaN remains a valid Float64 value. This preserves the R distinction
between NA_real_ and NaN.
JavaScript can modify the contents of both typed arrays. Returning the branded object to R reconstructs the original R vector type using the current values and validity bytes. A nonzero validity byte is treated as valid. Removing the brand by constructing a plain object returns the two buffers separately under the ordinary object conversion rules.
The mask uses one byte per element. Use js_typed_array() when a mask is
not required. Factors and dates are rejected because their class semantics
cannot be represented by the numeric values and validity buffers alone.
A lightweight wrapper around the input vector.
ctx <- JSContext$new(profile = "bare") ctx$source(code = paste( "function fillMissing(x) {", " x.values[1] = 20;", " x.validity[1] = 1;", " return x;", "}" )) values <- js_masked_typed_array(c(10L, NA_integer_, 30L)) ctx$call("fillMissing", values)ctx <- JSContext$new(profile = "bare") ctx$source(code = paste( "function fillMissing(x) {", " x.values[1] = 20;", " x.validity[1] = 1;", " return x;", "}" )) values <- js_masked_typed_array(c(10L, NA_integer_, 30L)) ctx$call("fillMissing", values)
Creates a fixed-length array-like JavaScript object whose indexed writes update R-owned vector storage. The wrapper makes one copy when it is created; passing it to JavaScript does not copy or convert the complete vector.
js_mutable_view(x)js_mutable_view(x)
x |
An unclassed raw, logical, integer, double, or character vector. |
JavaScript reads convert elements on demand and writes update
view$value. The caller's original vector is never modified. Multiple
JavaScript views of the same wrapper share its owned storage.
The view has length, indexed access, enumeration, iteration, inherited
Array methods, and toArray(). Its length cannot change, properties
cannot be added, and elements cannot be deleted. Methods such as reverse,
sort, fill, and copyWithin work because they only replace
existing elements.
Assignments are type checked. JavaScript null and undefined
write R missing values except for raw vectors. JavaScript NaN remains an
ordinary R NaN. Factors, dates, and other classed vectors are rejected.
Normal R copy-on-write rules still apply. Replacing or modifying
view$value in R after JavaScript retains the view can detach the R
binding from the retained storage.
A mutable-view wrapper containing an independent copy in value.
ctx <- JSContext$new(profile = "bare") ctx$source(code = "function increment(x) { x[0] += 1; return x; }") values <- js_mutable_view(c(1, 2, 3)) ctx$call("increment", values) values$valuectx <- JSContext$new(profile = "bare") ctx$source(code = "function increment(x) { x[0] += 1; return x; }") values <- js_mutable_view(c(1, 2, 3)) ctx$call("increment", values) values$value
Creates an array-like JavaScript object that reads directly from retained R vector storage. Creating the view does not copy or convert its elements. Elements are converted only when JavaScript accesses them.
js_readonly_view(x)js_readonly_view(x)
x |
A raw, logical, integer, double, or character vector. |
The view has length, indexed access, array iteration, and inherited
non-mutating Array methods. Use view.toArray() or
Array.from(view) when a mutable JavaScript array is required. Attempts
to write or delete indexed values throw an error.
The wrapper does not copy the vector. The view retains the wrapper and vector until JavaScript releases them. Normal R assignment follows R's copy-on-write rules, so modifying an R binding can detach it from the storage retained by an existing view. Returning the view to R recovers the wrapper without materialising a JavaScript array.
Missing values use the ordinary conversion rules: logical, integer, double,
and character NA become JavaScript null; NaN remains
NaN. Factors yield their labels, and dates yield JavaScript dates.
A lightweight wrapper around the input vector.
ctx <- JSContext$new(profile = "bare") ctx$source(code = paste( "function endpoints(x) { return [x[0], x[x.length - 1]]; }", "function total(x) { return x.reduce((a, b) => a + b, 0); }" )) values <- js_readonly_view(as.double(1:1000)) ctx$call("endpoints", values) ctx$call("total", values)ctx <- JSContext$new(profile = "bare") ctx$source(code = paste( "function endpoints(x) { return [x[0], x[x.length - 1]]; }", "function total(x) { return x.reduce((a, b) => a + b, 0); }" )) values <- js_readonly_view(as.double(1:1000)) ctx$call("endpoints", values) ctx$call("total", values)
Creates a zero-copy R view over the storage of a retained JavaScript typed
array. Uint8Array and Uint8ClampedArray produce raw vectors,
Int32Array produces an integer vector, and Float64Array produces
a double vector.
js_ref_to_altrep(ref)js_ref_to_altrep(ref)
ref |
A |
The backing ArrayBuffer is made permanently immutable before its address is exposed to R. This affects every JavaScript alias of that buffer. Indexed JavaScript writes are ignored, while mutating typed-array methods, DataView writes, resizing, and transfer operations throw an error.
The ALTREP object retains the reference and its context while it reads the JavaScript buffer. When R requests writable storage, the values are copied into an ordinary R vector, the R modification affects only that copy, and the JavaScript reference can be released.
Shared, detached, unsupported, and out-of-bounds typed-array buffers are
rejected. An Int32Array value of -2147483648 is R's
NA_integer_ sentinel. Float64 NaN payloads are preserved, including an
R NA_real_ payload originally transferred to JavaScript.
ALTREP-aware R operations can read the buffer without copying. Other R code may request writable or materialised storage and therefore trigger a copy.
An ALTREP raw, integer, or double vector backed by the JavaScript ArrayBuffer.
ctx <- JSContext$new(profile = "bare") ref <- ctx$eval_ref("new Float64Array([1, 2, 3, 4])") values <- js_ref_to_altrep(ref) sum(values) values[1]ctx <- JSContext$new(profile = "bare") ref <- ctx$eval_ref("new Float64Array([1, 2, 3, 4])") values <- js_ref_to_altrep(ref) sum(values) values[1]
Marks a vector for contiguous transfer to JavaScript. Raw vectors become
Uint8Array, integer vectors become Int32Array, and double vectors
become Float64Array. Integer vectors containing NA are rejected.
Double NA and NaN values both become JavaScript NaN.
On return, the JavaScript Int32Array value -2147483648 becomes
R's NA_integer_ sentinel.
js_typed_array(x)js_typed_array(x)
x |
A raw, integer, or double vector. |
The input vector marked for typed-array conversion.
ctx <- JSContext$new() ctx$source(code = "function total(x) { return x.reduce((a, b) => a + b, 0); }") ctx$call("total", js_typed_array(as.double(1:4)))ctx <- JSContext$new() ctx$source(code = "function total(x) { return x.reduce((a, b) => a + b, 0); }") ctx$call("total", js_typed_array(as.double(1:4)))
Compiled scripts avoid parsing source on every execution. The bytecode remains owned by its original context and can be executed repeatedly. The script keeps that context alive.
js_script_run(script) js_script_run_ref(script)js_script_run(script) js_script_run_ref(script)
script |
A script created by |
Compilation does not execute the source. Compiled scripts cannot be passed as
ordinary JavaScript values. For parameterised work, evaluate a JavaScript
function with ctx$eval_ref() and call it repeatedly with
js_ref_call().
js_script_run() converts the result to R. js_script_run_ref()
returns a JSValueRef owned by the script's context.
ctx <- JSContext$new(profile = "bare") ctx$eval("globalThis.value = 0") script <- ctx$compile("value += 1; value") js_script_run(script) js_script_run(script)ctx <- JSContext$new(profile = "bare") ctx$eval("globalThis.value = 0") script <- ctx$compile("value += 1; value") js_script_run(script) js_script_run(script)
An initialised context within which to evaluate Javascript scripts or commands.
JSContextJSContext
A JSContext object containing an initialised JavaScript context for evaluating scripts/commands
Assign a value to a variable in the current context
assign(var_name, value)assign(var_name, value)
var_name |
The name of the variable to assign |
value |
The value to assign to the variable |
No return value, called for side effects
## Not run: ctx <- JSContext$new() ctx$assign("a", 1) ctx$get("a") ## End(Not run)## Not run: ctx <- JSContext$new() ctx$assign("a", 1) ctx$get("a") ## End(Not run)
Call a specified function in the JavaScript context with the provided arguments.
call(function_name, ...)call(function_name, ...)
function_name |
The function to be called |
... |
The arguments to be passed to the function |
The result of calling the specified function
## Not run: ctx <- JSContext$new() ctx$source(code = "function add(a, b) { return a + b; }") ctx$call("add", 1, 2) ## End(Not run)## Not run: ctx <- JSContext$new() ctx$source(code = "function add(a, b) { return a + b; }") ctx$call("add", 1, 2) ## End(Not run)
Evaluates source code in an existing JSContext. Global state remains
available to later evaluations, calls, and compiled scripts. Use
ctx$eval(code) to invoke the method.
eval(code)eval(code)
code |
JavaScript source code to evaluate. |
The evaluation result converted to R.
Get the value of a variable from the current context
get(var_name)get(var_name)
var_name |
The name of the variable to retrieve |
The value of the variable
## Not run: ctx <- JSContext$new() ctx$source(code = "var a = 1;") ctx$get("a") ## End(Not run)## Not run: ctx <- JSContext$new() ctx$source(code = "var a = 1;") ctx$get("a") ## End(Not run)
Evaluate a provided JavaScript file or string within the initialised context.
Note that this method should only be used for initialising functions or values
within the context, no values are returned from this function. See the $call()
method for returning values.
source(file = NULL, code = NULL)source(file = NULL, code = NULL)
file |
A path to the JavaScript file to load |
code |
A single string of JavaScript to evaluate |
No return value, called for side effects
## Not run: ctx <- JSContext$new() ctx$source(file = "path/to/file.js") ctx$source(code = "1 + 2") ## End(Not run)## Not run: ctx <- JSContext$new() ctx$source(file = "path/to/file.js") ctx$source(code = "1 + 2") ## End(Not run)
Checks whether JS code string is valid code in the current context
validate(code_string)validate(code_string)
code_string |
The JS code to check |
A boolean indicating whether code is valid
## Not run: ctx <- JSContext$new() ctx$validate("1 + 2") ## End(Not run)## Not run: ctx <- JSContext$new() ctx$validate("1 + 2") ## End(Not run)
Creates a persistent QuickJS runtime and context.
new_JSContext( stack_size = NULL, profile = c("host", "standard", "bare") )new_JSContext( stack_size = NULL, profile = c("host", "standard", "bare") )
stack_size |
Optional maximum JavaScript stack size in bytes. |
profile |
Context facilities to install. See Details. |
Create contexts through JSContext$new().
The host profile preserves the complete API with std, os,
console helpers, and the global R bridge. The standard profile
installs std, os, and console helpers without the global
R bridge. The bare profile installs only the core JavaScript
runtime. R values can still be passed through context methods in every profile.
A persistent JSContext.
ctx <- JSContext$new(profile = "bare") ctx$source(code = "function add(a, b) { return a + b; }") ctx$call("add", 2, 3)ctx <- JSContext$new(profile = "bare") ctx$source(code = "function add(a, b) { return a + b; }") ctx$call("add", 2, 3)
Evaluate, retrieve, or call JavaScript while retaining the result inside the context instead of eagerly converting it to R.
call_ref(function_name, ...) get_ref(var_name) eval_ref(code)call_ref(function_name, ...) get_ref(var_name) eval_ref(code)
function_name |
The global function or dotted method path to call. |
... |
Arguments passed to the JavaScript function. |
var_name |
The global value or dotted property path to retrieve. |
code |
JavaScript source code to evaluate. |
A JSValueRef owned by the context.
Retain values inside their JavaScript context so chained operations do not convert intermediate values to R. References keep their context alive and can only be passed back to that same context.
js_ref_get(ref, name) js_ref_call(ref, ...) js_ref_to_r(ref)js_ref_get(ref, name) js_ref_call(ref, ...) js_ref_to_r(ref)
ref |
A |
name |
A property name or dotted property path. |
... |
Arguments passed to the referenced JavaScript function. |
js_ref_get() and js_ref_call() return a JSValueRef.
js_ref_to_r() materialises the referenced value as an R object.
ctx <- JSContext$new() ref <- ctx$eval_ref("({ value: 2, add(x) { return this.value + x; } })") result <- js_ref_call(js_ref_get(ref, "add"), 3) js_ref_to_r(result)ctx <- JSContext$new() ref <- ctx$eval_ref("({ value: 2, add(x) { return this.value + x; } })") result <- js_ref_call(js_ref_get(ref, "add"), 3) js_ref_to_r(result)
Evaluate a single Javascript expression.
qjs_eval(eval_string)qjs_eval(eval_string)
eval_string |
A single string of the expression to evaluate |
The result of the provided expression
# Return the sum of two numbers: qjs_eval("1 + 2") # Concatenate strings: qjs_eval("'1' + '2'") # Create lists from objects: qjs_eval("var t = {'a' : 1, 'b' : 2}; t")# Return the sum of two numbers: qjs_eval("1 + 2") # Concatenate strings: qjs_eval("'1' + '2'") # Create lists from objects: qjs_eval("var t = {'a' : 1, 'b' : 2}; t")
Return the flags needed for compiling against the bundled quickjs-ng headers and library
cppflags() ldflags()cppflags() ldflags()
A character string of flags
Get the version of the bundled QuickJS library
quickjs_version()quickjs_version()
Character string of the version of the bundled QuickJS library
Use the QuickJS C API to convert an R object to a JSON string
to_json(arg, auto_unbox = FALSE)to_json(arg, auto_unbox = FALSE)
arg |
Argument to convert to JSON |
auto_unbox |
Automatically unbox single element vectors |
JSON string