Skip to content

Latest commit

 

History

History
897 lines (515 loc) · 27.6 KB

File metadata and controls

897 lines (515 loc) · 27.6 KB

API documentation

Note

The long term goal for LLRT is to become WinterTC compliant. Not every API from Node.js will be supported.

Node.js API

assert

ok

async_hooks

Static methods

createHook

currentId

executionAsyncId

triggerAsyncId

Class: AsyncHook

enable

disable

Hook callbacks

init

before

after

destroy

promiseResolve

buffer

Static methods

alloc

allocUnsafe

allocUnsafeSlow

byteLength

concat

from

isBuffer

isEncoding

Prototype methods

copy

readBigInt64BE

readBigInt64LE

readDoubleBE

readDoubleLE

readFloatBE

readFloatLE

readInt8

readInt16BE

readInt16LE

readInt32BE

readInt32LE

readUInt8

readUInt16BE

readUInt16LE

readUInt32BE

readUInt32LE

subarray

toString

write

writeBigInt64BE

writeBigInt64LE

writeDoubleBE

writeDoubleLE

writeFloatBE

writeFloatLE

writeInt8

writeInt16BE

writeInt16LE

writeInt32BE

writeInt32LE

writeUInt8

writeUInt16BE

writeUInt16LE

writeUInt32BE

writeUInt32LE

Constants

constants.MAX_LENGTH

constants.MAX_STRING_LENGTH

Everything else inherited from Uint8Array

child_process

Warning

spawn uses native streams that is not 100% compatible with the Node.js Streams API.

spawn

console

Console

crypto

createHash

createHmac

getRandomValues

randomBytes

randomFill

randomFillSync

randomInt

randomUUID

webcrypto

LLRT specific hash classes

Lightweight and fast hash classes for LLRT.

  • Md5
  • Sha1
  • Sha256
  • Sha384
  • Sha512
  • Crc32
  • Crc32c

crypto.subtle

subtle.decrypt

subtle.deriveBits

subtle.digest

subtle.encrypt

subtle.exportKey

subtle.generateKey

subtle.importKey

subtle.sign

subtle.verify

dgram

createSocket

Class: dgram.Socket

address

bind

close

ref

send

unref

dns

lookup

events

EventEmitter

fs

accessSync

constants

lstatSync

mkdirSync

mkdtempSync

readdirSync

readFileSync

rmdirSync

rmSync

statSync

writeFileSync

chmodSync

renameSync

symlinkSync

fs/promises

access

constants

lstat

mkdir

mkdtemp

open

readdir

readFile

rm

rmdir

stat

writeFile

chmod

rename

symlink

https

Agent

module

builtinModules

createRequire

Note

require is available from esm modules natively. This function is just for compatibility

isBuiltin

registerHooks

net

Warning

These APIs uses native streams that is not 100% compatible with the Node.js Streams API. Server APIs like createSever provides limited functionality useful for testing purposes. Serverless applications typically don't expose servers. Some server options are not supported: highWaterMark, pauseOnConnect, keepAlive, noDelay, keepAliveInitialDelay

connect

createConnection

createServer

os

arch

availableParallelism

cpus

devNull

endianness

EOL

freemem

getPriority

homedir

hostname

loadavg

machine

networkInterfaces

platform

release

setPriority

tmpdir

totalmem

type

uptime

userInfo

version

path

basename

delimiter

dirname

extname

format

isAbsolute

join

normalize

parse

relative

resolve

perf_hooks

performance is available globally

performance.now

process

process is available globally

arch

argv

argv0

cwd

env

exit

exitCode

getegid

geteuid

getgid

getuid

hrtime

id

kill

platform

release

setegid

seteuid

setgid

setuid

version

versions

stream

Duplex

PassThrough

Readable

Stream

Transform

Writable

finished

pipeline

stream/promises

finished

pipeline

string_decoder

StringDecoder

timers

Also available globally

clearImmediate

clearInterval

clearTimeout

setImmediate

setInterval

setTimeout

tty

isatty

url

Class

URL

URLSearchParams

Prototype methods

domainToASCII

domainToUnicode

fileURLToPath

format

pathToFileURL

urlToHttpOptions

util

Important

Supported encodings: hex, base64, utf-8, utf-16le, windows-1252 and their aliases.

format

inherits

TextDecoder

TextEncoder

zlib

Convenience methods

deflate

deflateSync

deflateRaw

deflateRawSync

gzip

gzipSync

inflate

inflateSync

inflateRaw

inflateRawSync

gunzip

gunzipSync

brotliCompress

brotliCompressSync

brotliDecompress

brotliDecompressSync

zstdCompress

zstdCompressSync

zstdDecompress

zstdDecompressSync

LLRT API

llrt:hex

export function encode(
  value: string | Array | ArrayBuffer | Uint8Array
): string;
export function decode(value: string): Uint8Array;

llrt:timezone

Lightweight timezone support for LLRT. Provides timezone offset calculations and a minimal Intl.DateTimeFormat implementation for dayjs and similar library compatibility.

interface Timezone {
  /**
   * Get the UTC offset in minutes for a timezone at a given time.
   * Returns a positive value for timezones ahead of UTC (e.g., 540 for Asia/Tokyo)
   * and a negative value for timezones behind UTC (e.g., -420 for America/Denver).
   * Automatically handles DST transitions.
   */
  getOffset(timezone: string, epochMs: number): number;

  /**
   * List all available IANA timezone names.
   */
  list(): string[];
}

declare var Timezone: Timezone;

export { Timezone };

Example

import { Timezone } from "llrt:timezone";

// Get current offset for Denver (handles DST automatically)
const offset = Timezone.getOffset("America/Denver", Date.now());
// Returns -420 (UTC-7) in winter, -360 (UTC-6) in summer

// Check DST transition
const beforeDst = new Date("2024-03-09T12:00:00Z").getTime();
const afterDst = new Date("2024-03-11T12:00:00Z").getTime();
console.log(Timezone.getOffset("America/Denver", beforeDst)); // -420
console.log(Timezone.getOffset("America/Denver", afterDst)); // -360

// List all available timezones
const zones = Timezone.list();

Intl.DateTimeFormat

LLRT provides a minimal Intl.DateTimeFormat implementation focused on timezone support. This enables libraries like dayjs to work with timezone conversions transparently.

// Create a formatter for a specific timezone
const formatter = new Intl.DateTimeFormat("en-US", {
  timeZone: "America/Denver",
  hour12: false,
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
  hour: "2-digit",
  minute: "2-digit",
  second: "2-digit",
});

// Format a date
const date = new Date("2022-03-02T15:45:34Z");
console.log(formatter.format(date)); // "03/02/2022, 08:45:34"

// Get formatted parts
const parts = formatter.formatToParts(date);
// [{ type: "month", value: "03" }, { type: "literal", value: "/" }, ...]

// Get resolved options
const options = formatter.resolvedOptions();
console.log(options.timeZone); // "America/Denver"

Date.prototype.toLocaleString with timezone

Date.prototype.toLocaleString is enhanced to support the timeZone option:

const date = new Date("2022-03-02T15:45:34Z");

// Convert to Denver time
console.log(date.toLocaleString("en-US", { timeZone: "America/Denver" }));
// "03/02/2022, 8:45:34 AM"

// Convert to Tokyo time
console.log(date.toLocaleString("en-US", { timeZone: "Asia/Tokyo" }));
// "03/03/2022, 12:45:34 AM"

Using with dayjs

The timezone module enables dayjs timezone support without polyfills:

const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
const timezone = require("dayjs/plugin/timezone");

dayjs.extend(utc);
dayjs.extend(timezone);

// Convert between timezones
const date = dayjs("2022-03-02T15:45:34Z");
console.log(date.tz("America/Denver").format()); // "2022-03-02T08:45:34-07:00"
console.log(date.tz("Asia/Tokyo").format()); // "2022-03-03T00:45:34+09:00"

// Get start of day in a specific timezone
const denver = date.tz("America/Denver");
console.log(denver.startOf("day").format()); // "2022-03-02T00:00:00-07:00"

llrt:qjs

interface MemoryInfo {
  malloc_size: number;
  malloc_limit: number;
  memory_used_size: number;
  malloc_count: number;
  memory_used_count: number;
  atom_count: number;
  atom_size: number;
  str_count: number;
  str_size: number;
  obj_count: number;
  obj_size: number;
  prop_count: number;
  prop_size: number;
  shape_count: number;
  shape_size: number;
  js_func_count: number;
  js_func_size: number;
  js_func_code_size: number;
  js_func_pc2line_count: number;
  js_func_pc2line_size: number;
  c_func_count: number;
  array_count: number;
  fast_array_count: number;
  fast_array_elements: number;
  binary_object_count: number;
  binary_object_size: number;
}
export function ComputeMemoryUsage(): MemoryInfo;

llrt:xml

A lightweight and fast XML parser and builder

export class XmlText {
  constructor(text: string);
  toString(): string;
}

export class XmlNode {
  constructor(name: string);
  withName(name: string): this;
  addAttribute(name: string, value: string): this;
  addChildNode(node: XmlNode | XmlText): this;
  removeAttribute(name: string): this;
  toString(): string;
}

type XmlParserOptions = {
    ignoreAttributes?: boolean;
    attributeNamePrefix?: string;
    textNodeName?: string;
    attributeValueProcessor?: (attrName: string, attrValue: string, jpath: string) => unknown;
    tagValueProcessor?: (attrName: string, attrValue: string, jpath: string, hasAttributes: boolean) => unknown;
}
export class XMLParser(options?: XmlParserOptions){
    parse(xml:string):object
}

llrt:util

export function dimensions(): [number, number];
export function load(path: string): any;
export function print(value: any): void;

Web Platform API

CONSOLE

Console

DOM

AbortController

AbortSignal

CustomEvent

Event

EventTarget

ECMASCRIPT

globalThis

ENCODING

TextDecoder

TextEncoder

FETCH

Headers

Request

Response

fetch

Important

There are some differences with the WHATWG standard. Mainly browser specific behavior is removed:

  • keepalive is always true
  • request.body can only be string, Array, ArrayBuffer or Uint8Array
  • response.body returns null. Use response.text(), response.json() etc
  • mode, credentials, referrerPolicy, priority, cache is not available/applicable

FILEAPI

Blob

File

HR-TIME

performance.now

performance.timeOrigin

HTML

atob

btoa

clearInterval

clearTimeout

navigator

queueMicrotask

setInterval

setTimeout

structuredClone

userAgent

STREAMS

ByteLengthQueuingStrategy

CountQueuingStrategy

ReadableByteStreamController

ReadableStream

ReadableStreamBYOBReader

ReadableStreamBYOBRequest

ReadableStreamDefaultController

ReadableStreamDefaultReader

WritableStream

WritableStreamDefaultController

WritableStreamDefaultWriter

URL

URL

URLSearchParams

WEBCRYPTO

Crypto

CryptoKey

SubtleCrypto

WEBIDL

DOMException

XHR

FormData