JSRealm

API Reference

URL

The URL class provides URL parsing following the WHATWG URL Standard.

Constructor

new URL(url)

new URL(url, base)

Properties

Property Description
href Complete URL string
protocol Protocol with colon (e.g., "https:")
hostname Hostname (e.g., "example.com")
port Port number as string
host Hostname with port
pathname Path (e.g., "/path/to/file")
search Query string with ?
hash Fragment with #
origin Origin (protocol + host)
searchParams URLSearchParams object

Example

const url = new URL("https://example.com:8080/path?key=value#section");

console.log(url.hostname); // "example.com"

console.log(url.searchParams.get("key")); // "value"

URLSearchParams

The URLSearchParams class provides methods for working with URL query strings.

Constructor

new URLSearchParams()

new URLSearchParams(init)

Parameter Description
init Optional query string (with or without ?)

Methods

Method Description
get(name) Get first value for name
set(name, value) Set value (replaces existing)
append(name, value) Append value
delete(name) Delete all values for name
has(name) Check if name exists
forEach(callback) Iterate over entries
toString() Get query string (without ?)

Example

const params = new URLSearchParams("foo=1&bar=2");

params.append("baz", "3");

console.log(params.get("foo")); // "1"

console.log(params.toString()); // "foo=1&bar=2&baz=3"

Headers

The Headers class provides methods for working with HTTP headers following the Fetch API Standard.

Constructor

new Headers()

new Headers(init)

Parameter Description
init Optional object, array of pairs, or Headers instance

Methods

Method Description
get(name) Get header value (merged with ", " for multi-value)
set(name, value) Set header value (replaces existing)
append(name, value) Append header value
delete(name) Delete header by name
has(name) Check if header exists
forEach(callback) Iterate over headers
keys() Iterator over header names
values() Iterator over header values
entries() Iterator over [name, value] pairs

Example

const headers = new Headers({"Content-Type": "application/json"});

headers.append("Accept", "text/html");

headers.append("Accept", "application/json");

console.log(headers.get("Accept")); // "text/html, application/json"

Request

The Request class represents an HTTP request following the Fetch API Standard.

Constructor

new Request(input)

new Request(input, options)

Parameter Description
input URL string or another Request object
options Optional object with method, headers, body, etc.

Properties

Property Description
method HTTP method (GET, POST, etc.)
url Request URL
headers Headers object
bodyUsed Whether body has been read
cache Cache mode
credentials Credentials mode
mode Request mode

Methods

Method Description
text() Read body as text (returns Promise)
json() Read body as JSON (returns Promise)
arrayBuffer() Read body as ArrayBuffer (returns Promise)
clone() Create a copy of the request

Example

const req = new Request("https://api.example.com/data", {

method: "POST",

headers: {"Content-Type": "application/json"},

body: JSON.stringify({key: "value"})

});

console.log(req.method); // "POST"

Response

The Response class represents an HTTP response following the Fetch API Standard.

Constructor

new Response(body)

new Response(body, options)

Parameter Description
body Response body (string, ArrayBuffer, or TypedArray)
options Optional object with status, statusText, headers

Properties

Property Description
status HTTP status code
statusText Status message
ok True if status is 200-299
headers Headers object
bodyUsed Whether body has been read
redirected Always false

Methods

Method Description
text() Read body as text (returns Promise)
json() Read body as JSON (returns Promise)
arrayBuffer() Read body as ArrayBuffer (returns Promise)

Static Methods

Method Description
Response.json(data, init?) Create JSON response with Content-Type header

Example

const res = new Response("Hello", {status: 200});

const json = Response.json({message: "ok"});

fetch

The global fetch() function makes HTTP requests following the Fetch API Standard.

Syntax

fetch(input)

fetch(input, options)

Parameter Description
input URL string or Request object
options Optional object with method, headers, body, etc.

Options

Option Description
method HTTP method (GET, POST, etc.)
headers Request headers (object or Headers)
body Request body
target Override connection address (proxy support)
host Override Host header
timeout Request timeout in milliseconds (default: 30000)
maxBodySize Max response body size (default: 1MB)
verify Verify TLS certificate (default: true)

Return Value

Returns a Promise that resolves to a Response object.

Example

// Simple GET request

const res = await fetch("https://api.example.com/data");

const data = await res.json();

// POST request with JSON body

const res = await fetch("https://api.example.com/users", {

method: "POST",

headers: {"Content-Type": "application/json"},

body: JSON.stringify({name: "John"})

});

// With timeout and proxy target

const res = await fetch("https://api.example.com/data", {

target: "http://127.0.0.1:8080",

host: "api.example.com",

timeout: 5000

});

// Skip TLS verification (for development)

const res = await fetch("https://localhost:8443/api", {

verify: false

});

Error Handling

try {

const res = await fetch("https://api.example.com/data");

if (!res.ok) {

throw new Error(HTTP error: ${res.status});

}

const data = await res.json();

} catch (e) {

console.log("Fetch failed:", e.message);

}

Base64

Global functions and Base64 object for Base64 encoding/decoding.

Global Functions

Function Description
btoa(string) Encode Latin-1 string to Base64
atob(string) Decode Base64 to string

Base64 Object Methods

Method Description
Base64.encode(data) Encode string or Uint8Array to Base64
Base64.decode(string) Decode Base64 to ArrayBuffer
Base64.encodeUrl(data) Encode to Base64URL (no padding)
Base64.decodeUrl(string) Decode Base64URL to ArrayBuffer

Example

// Web standard btoa/atob

const encoded = btoa("Hello"); // "SGVsbG8="

const decoded = atob("SGVsbG8="); // "Hello"

// Base64 object - works with binary data

const bytes = new Uint8Array([72, 101, 108, 108, 111]);

const b64 = Base64.encode(bytes); // "SGVsbG8="

const buf = Base64.decode(b64); // ArrayBuffer

// Base64URL for JWT/URLs (no padding, URL-safe chars)

const urlSafe = Base64.encodeUrl("Hello"); // "SGVsbG8"

TextEncoder / TextDecoder

Standard Web APIs for encoding and decoding text.

TextEncoder

Encodes strings to UTF-8 bytes.

const encoder = new TextEncoder();

const bytes = encoder.encode("Hello"); // Uint8Array [72, 101, 108, 108, 111]

console.log(encoder.encoding); // "utf-8"

TextDecoder

Decodes UTF-8 bytes to strings.

const decoder = new TextDecoder();

const bytes = new Uint8Array([72, 101, 108, 108, 111]);

const text = decoder.decode(bytes); // "Hello"

console.log(decoder.encoding); // "utf-8"

Crypto

Web Crypto API for cryptographic operations. Requires JS_SSL=1 build flag.

crypto.getRandomValues(typedArray)

Fills a TypedArray with cryptographically secure random values.

const array = new Uint8Array(16);

crypto.getRandomValues(array);

crypto.subtle.digest(algorithm, data)

Computes a hash digest. Supported algorithms: SHA-1, SHA-256, SHA-384, SHA-512.

const hash = crypto.subtle.digest("SHA-256", "hello");

// Returns ArrayBuffer

crypto.subtle.sign(algorithm, key, data)

Creates a digital signature. Supports HMAC and RSA.

// HMAC signing

const sig = crypto.subtle.sign(

{ name: "HMAC", hash: "SHA-256" },

"secret-key",

"message"

);

// RSA signing (requires CryptoKey)

const sig = crypto.subtle.sign(

{ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },

privateKey,

data

);

crypto.subtle.verify(algorithm, key, signature, data)

Verifies an HMAC signature.

const valid = crypto.subtle.verify(

{ name: "HMAC", hash: "SHA-256" },

key, signature, data

);

crypto.subtle.generateKey(algorithm, extractable, keyUsages)

Generates an RSA key pair.

const keyPair = await crypto.subtle.generateKey(

{ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048 },

true,

["sign", "verify"]

);

// Returns { publicKey, privateKey }

crypto.subtle.exportKey(format, key)

Exports a CryptoKey. Formats: jwk, pkcs8 (private), spki (public).

const jwk = await crypto.subtle.exportKey("jwk", privateKey);

const pem = await crypto.subtle.exportKey("pkcs8", privateKey);

crypto.subtle.importKey(format, keyData, algorithm, extractable, keyUsages)

Imports a key from JWK format.

const key = await crypto.subtle.importKey(

"jwk", jwkData,

{ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },

true, ["sign"]

);

crypto.generateCSR(domains, privateKey)

Generates a Certificate Signing Request (CSR) for ACME.

const csr = crypto.generateCSR(

["example.com", "www.example.com"],

keyPair.privateKey

);

// Returns ArrayBuffer (DER format)

Cache

Global cache object for in-memory key-value storage with LRU eviction and TTL support.

cache.set(key, value, options?)

Stores a value in the cache.

Parameter Description
key Cache key (string)
value Value to store (string)
options.ttl Time-to-live in seconds (optional)

cache.set("user:123", "John");

cache.set("session", "abc123", { ttl: 3600 }); // expires in 1 hour

cache.get(key)

Retrieves a value from the cache.

Returns the value as a string, or null if not found or expired.

const value = cache.get("user:123");  // "John" or null

cache.has(key)

Checks if a key exists in the cache.

if (cache.has("user:123")) {

// key exists and not expired

}

cache.delete(key)

Removes a key from the cache. Returns true if the key was deleted, false if not found.

cache.delete("user:123");

Example

var app = new App();

app.get("/cache-demo", (req) => {

// Set with TTL

cache.set("visits", "1", { ttl: 60 });

// Get value

// Update

cache.set("visits", String(parseInt(visits) + 1), { ttl: 60 });

return new Response(Visits: ${visits});

});

export default app;