Sign in

    js

    bindings for js/node/browser/deno/cloudflare/react etc

    js
    node
    react
    preact
    dom
    async
    http
    cloudflare
    deno
    Download zip
    Author
    Version
    0.8.2
    License
    MIT
    Last updated
    10 months ago
    Downloads
    42K

    #mizchi/js

    Comprehensive JavaScript/ FFI bindings for MoonBit, supporting multiple runtimes and platforms.

    #Installation

    $ moon add mizchi/js

    Add to your moon.pkg.json:

    { "import": ["mizchi/js"] }

    ⚠️ Future Plans: Platform-specific APIs (Node.js, Browser, Deno, Cloudflare Workers) will be split into separate packages in the future. The core mizchi/js package will focus on JavaScript built-ins and Web Standard APIs.

    #📚 API Documentation by Platform

    PlatformDocumentationExamplesStatus
    Core JavaScriptsrc/README.mdjs_examples.mbt.md🧪 Tested
    Browsersrc/browser/README.mdbrowser_examples.mbt.md🧪 Tested
    Node.jssrc/node/README.mdnode_examples.mbt.md🧪 Tested
    Denosrc/deno/README.md-🧪 Tested
    Cloudflare Workerssrc/cloudflare/README.mdcfw/🧪 Tested
    Reactsrc/npm/react/react_app/🧪 Tested

    #📖 Learning Resources

    #Supported Modules

    #Status Legend

    • 🧪 Tested: Comprehensive test coverage, production ready
    • 🚧 Partially: Core functionality implemented, tests incomplete
    • 🤖 AI Generated: FFI bindings created, needs testing
    • 📅 Planned: Scheduled for future implementation
    • ❌ Not Supported: Technical limitations

    #Core JavaScript APIs

    #mizchi/js/core - Core FFI Package

    The mizchi/js/core package provides the foundation for JavaScript interoperability in MoonBit:

    Type System
    • Any - Opaque type for JavaScript values
    • Nullable[T] - Represents null | T
    • Nullish[T] - Represents null | undefined | T
    • Union2[A,B] ~ Union5[A,B,C,D,E] - TypeScript union types (A | B)
    • Promise[T] - JavaScript Promise wrapper

    FFI Operations (zero-cost conversions)
    • identity[A,B](value: A) -> B - Type casting using %identity
    • any[T](value: T) -> Any - Convert to Any
    • Any::cast[T](self) -> T - Cast from Any
    • Any::_get(key), Any::_set(key, value) - Property access
    • Any::_call(method, args), Any::_invoke(args) - Method calls

    Object & JSON
    • new_object(), new_array() - Create JS objects/arrays
    • object_keys(), object_values(), object_assign(), object_has_own()
    • json_stringify(), json_parse(), json_stringify_pretty()

    Async/Promise Support
    • run_async(f) - Execute async functions (MoonBit builtin %async.run)
    • suspend(f) - Await promises (MoonBit builtin %async.suspend)
    • promisify0 ~ promisify3 - Convert callbacks to promises
    • Promise utilities: resolve, reject, all, race, any, withResolvers

    Error Handling
    • JsError - Generic JS error type
    • ThrowError - Wrapper for thrown errors
    • try_sync(op) - Safe wrapper converting JS exceptions to MoonBit errors
    • throwable(f) - Convert JS exceptions to ThrowError
    • export_sync(op) - Convert MoonBit errors to JS exceptions
    • throw_error(msg) - Throw JS Error

    Type Checking
    • is_object(), is_array(), is_null(), is_undefined(), is_nullish()

    Nullish Utilities
    • Nullish::to_option(), Nullable::to_option() - Convert to MoonBit Option
    • nullable(opt) - Convert Option to JS nullable
    • as_any(opt) - Convert Option[Any] to Any

    #API Summary

    CategoryPackageStatusNote
    Core FFI & Objects
    Core FFImizchi/js/core🧪 Testedget, set, call, etc.
    Objectmizchi/js/builtins/object🧪 TestedObject manipulation
    Functionmizchi/js/builtins/function🧪 TestedFunction operations
    Promisemizchi/js/core🧪 TestedAsync/Promise API
    Errormizchi/js/builtins/error🧪 TestedError handling
    JSONmizchi/js/builtins/json🧪 TestedJSON parse/stringify
    Iteratormizchi/js/builtins/iterator🧪 TestedJS Iterator protocol
    AsyncIteratormizchi/js/builtins/iterator🧪 TestedAsync iteration
    WeakMap/Set/Refmizchi/js/builtins/weak🧪 TestedWeak references
    Async Helpers
    run_asyncmizchi/js/core🧪 TestedAsync execution
    suspendmizchi/js/core🧪 TestedPromise suspension
    sleepmizchi/js/core🧪 TestedDelay execution
    promisifymizchi/js/core🧪 TestedCallback → Promise

    #JavaScript Built-ins

    All JavaScript built-in objects are exported from mizchi/js:

    CategoryPackageStatusNote
    Global Functions
    Globalmizchi/js/builtins/global🧪 TestedglobalThis, parseInt, parseFloat, etc.
    Timersmizchi/js/builtins/global🧪 TestedsetTimeout, setInterval, queueMicrotask
    Encodingmizchi/js/builtins/global🧪 Testedatob, btoa, encodeURI, decodeURI
    Cloningmizchi/js/builtins/global🧪 TestedstructuredClone
    Core Types
    Objectmizchi/js/builtins/object🧪 TestedObject manipulation
    Functionmizchi/js/builtins/function🧪 TestedFunction operations
    Symbolmizchi/js/builtins/symbol🧪 TestedSymbol primitive
    Errormizchi/js/builtins/error🧪 TestedError types (TypeError, RangeError, etc.)
    Primitives & Data
    Stringmizchi/js/builtins/string🧪 TestedJsString (String methods)
    Arraymizchi/js/builtins/array🧪 TestedJsArray (Array methods)
    BigIntmizchi/js/builtins/bigint🧪 TestedJsBigInt (arbitrary precision)
    JSONmizchi/js/builtins/json🧪 TestedJSON parse/stringify
    Date & Math
    Datemizchi/js/builtins/date🧪 TestedDate/time operations
    Mathmizchi/js/builtins/math🧪 TestedMath operations
    Collections
    Map/Setmizchi/js/builtins/collection🧪 TestedJsMap, JsSet
    WeakMap/Set/Refmizchi/js/builtins/weak🧪 TestedWeakMap, WeakSet, WeakRef, FinalizationRegistry
    Binary Data
    ArrayBuffermizchi/js/builtins/arraybuffer🧪 TestedBinary buffers
    TypedArraysmizchi/js/builtins/arraybuffer🧪 TestedUint8Array, Int32Array, etc.
    DataViewmizchi/js/builtins/arraybuffer🧪 TestedBuffer views
    SharedArrayBuffermizchi/js/builtins/arraybuffer🤖 AI GeneratedShared memory
    Pattern & Reflection
    RegExpmizchi/js/builtins/regexp🧪 TestedRegular expressions
    Reflectmizchi/js/builtins/reflect🤖 AI GeneratedReflection API
    Proxymizchi/js/builtins/proxy🤖 AI GeneratedProxy API
    Iteration & Async
    Iteratormizchi/js/builtins/iterator🧪 TestedJsIterator protocol
    AsyncIteratormizchi/js/builtins/iterator🧪 TestedAsync iteration
    Concurrency
    Atomicsmizchi/js/builtins/atomics🤖 AI GeneratedAtomic operations
    Resource Management
    DisposableStackmizchi/js/builtins/disposable🤖 AI GeneratedDisposable resources

    #Web Standard APIs

    Platform-independent Web Standard APIs (browsers, Node.js, Deno, edge runtimes):

    See mizchi/js/web for detailed Web APIs documentation

    CategoryPackageStatusNote
    Consolemizchi/js/web/console🧪 Testedconsole.log, console.error, etc.
    fetchmizchi/js/web/http🧪 TestedHTTP requests
    Requestmizchi/js/web/http🧪 TestedRequest objects
    Responsemizchi/js/web/http🧪 TestedResponse objects
    Headersmizchi/js/web/http🧪 TestedHTTP headers
    FormDatamizchi/js/web/http🧪 TestedForm data
    URLmizchi/js/web/url🧪 TestedURL parsing
    URLSearchParamsmizchi/js/web/url🧪 TestedQuery strings
    URLPatternmizchi/js/web/url🧪 TestedURL pattern matching
    Blobmizchi/js/web/blob🧪 TestedBinary data
    ReadableStreammizchi/js/web/streams🧪 TestedStream reading
    WritableStreammizchi/js/web/streams🧪 TestedStream writing
    TransformStreammizchi/js/web/streams🧪 TestedStream transformation
    CompressionStreammizchi/js/web/streams🧪 TestedGZIP/Deflate compression
    DecompressionStreammizchi/js/web/streams🧪 TestedGZIP/Deflate decompression
    TextEncodermizchi/js/web/encoding🧪 TestedString to Uint8Array
    TextDecodermizchi/js/web/encoding🧪 TestedUint8Array to String
    Eventmizchi/js/web/event🧪 TestedEvent objects
    CustomEventmizchi/js/web/event🧪 TestedCustom events
    MessageEventmizchi/js/web/event🧪 TestedMessage events
    Cryptomizchi/js/web/crypto🧪 TestedWeb Crypto API
    WebSocketmizchi/js/web/websocket🧪 TestedWebSocket API
    Workermizchi/js/web/worker🧪 TestedWeb Workers
    MessageChannelmizchi/js/web/message🧪 TestedMessage passing
    MessagePortmizchi/js/web/message🧪 TestedMessage ports
    WebAssemblymizchi/js/web/webassembly🤖 AI GeneratedWASM integration
    Performancemizchi/js/web/performance🤖 AI GeneratedPerformance API

    #Runtime-Specific APIs

    PlatformPackageStatusDocumentation
    Node.jsmizchi/js/node/*🧪 TestedNode.js README
    Browser APImizchi/js/browser/*🧪 TestedBrowser README
    Denomizchi/js/deno🧪 TestedDeno README
    Cloudflare Workersmizchi/js/cloudflare🧪 TestedCloudflare README

    #NPM Package Bindings

    See src/npm/README.md for full npm package documentation

    CategoryPackagesStatus
    UI FrameworksReact, React DOM, React Router, Preact, Ink🧪 Tested
    Web FrameworksHono, better-auth🧪 Tested
    AI / LLMVercel AI SDK, MCP SDK, Claude Code SDK🧪 Tested
    Cloud Services@aws-sdk/client-s3 (S3, R2, GCS, MinIO)🧪 Tested
    DatabasePGlite, DuckDB, Drizzle, pg🧪 Tested
    ValidationZod, AJV🧪 Tested
    Build ToolsTerser, Vite, Unplugin, Lighthouse🧪 Tested
    Utilitiesdate-fns, semver, chalk, dotenv, chokidar, yargs, debug🧪 Tested
    TestingTesting Library, Puppeteer, Playwright, Vitest, JSDOM, MSW🧪 Tested
    Parsinghtmlparser2, js-yaml🧪 Tested
    Othersimple-git, ignore, memfs, source-map, comlink🧪 Tested

    #Limited Support APIs

    FeatureStatusNote
    eval()❌ Not SupportedSecurity and type safety concerns
    new Function()❌ Not SupportedSecurity and type safety concerns
    DisposableStack⚠️ LimitedAPI available, but no using keyword syntax
    AsyncDisposableStack⚠️ LimitedAPI available, but no await using keyword syntax

    #Project Status

    • ✅ React SPA - Full support with SSR/CSR
    • ✅ Node.js Core APIs - fs, path, process, child_process, etc.
    • ✅ Cloudflare Workers - KV, D1, R2, Durable Objects
    • ✅ Deno Runtime - File system, permissions, testing
    • ✅ DOM APIs - Full browser DOM manipulation
    • 🤖 AI-Generated Bindings - Many APIs generated from TypeScript definitions

    #Goals

    • Provide comprehensive JavaScript bindings for MoonBit
    • Platform Coverage
      • ✅ Browser + React for frontend development
      • ✅ Node.js/Deno support to replace TypeScript
      • ✅ Cloudflare Workers for edge computing
      • ✅ MCP server/client support

    #Quick Start

    #Basic FFI Operations

    // Create JavaScript objects
    let obj = @js.from_map({ "name": @core.any("Alice"), "age": @core.any(30) })

    // Get property
    let name = obj._get("name")

    // Set property
    obj.set("age", 31)

    // Call method
    let result = obj._call("toString", [])

    // Type casting
    let age: Int = obj._get("age").cast()

    #LICENSE

    MIT

    #mizchi/js - Core Package

    Core JavaScript FFI bindings package. This is the foundation package that provides:

    • Core FFI operations (get, set, call, cast, etc.)
    • JavaScript built-in types (Object, Array, Promise, Function, Error, etc.)
    • Async helpers (run_async, suspend, sleep, promisify)
    • Type conversion utilities

    #Installation

    moon add mizchi/js

    Add to your moon.pkg.json:

    { "import": ["mizchi/js"] }

    #Basic Usage

    #Core FFI Operations

    // Create objects
    let obj = @core.Object::new()
    obj["name"] = "Alice" |> @js.any
    obj["agen"] = 25 |> @js.any

    // Get properties
    let name: String = obj["name"].cast() // Returns @js.Any
    let age: Int = obj["age"].cast() // Manual casting

    // Call methods
    let has_name: Bool = obj._call("hasOwnProperty", ["name"]).cast()

    // Create from map
    let obj2 = @js.from_map({ "x": @core.any(10), "y": @core.any(20) })

    #Type Casting

    // Using cast() method (recommended)
    let value: Int = js_value.cast()
    let str: String = js_value.cast()

    // Using identity() for low-level FFI
    let value: Int = @js.identity(js_value)

    // Optional types
    let nullable: Int? = @js.identity_option(js_value)

    #Promises and Async

    // Create and use promises
    let promise = @js.Promise::resolve(42)
    promise.then_(fn(value) {
    @console.log(value)
    })

    // Async/await
    async fn example() -> Int {
    let promise = @js.Promise::resolve(42)
    let value = promise.wait()
    value
    }

    // Run async code
    @js.run_async(async fn() {
    let value = some_promise.wait()
    @console.log(value)
    })

    #Async Helpers

    // Sleep
    async fn delayed() -> Unit {
    @js.sleep(1000) // Sleep for 1 second
    @console.log("Delayed!")
    }

    // Promisify callbacks
    let async_fn = async fn(x: Int) -> String {
    @js.sleep(100)
    x.to_string()
    }
    let promise_fn = @js.promisify1(async_fn)
    let promise = promise_fn(42) // Returns Promise[String]

    #Arrays

    // Create arrays
    let arr = @js.JsArray::new()
    arr.push(1)
    arr.push(2)
    arr.push(3)

    // Array operations
    let length = arr.length()
    let first = arr._get(0)
    arr.set(1, 42)

    // From MoonBit Array
    let mbt_arr = [1, 2, 3]
    let js_arr = @js.JsArray::from_array(mbt_arr)

    #Error Handling

    // Create errors
    let err = @js.Error::new("Something went wrong")

    // Throw errors (use in FFI functions marked with `raise`)
    fn example() -> Int raise {
    fail("Error message")
    }

    // Catch errors in async
    async fn safe_operation() -> Unit {
    try {
    let result = risky_operation().wait()
    @console.log(result)
    } catch {
    e => @console.error("Error: " + e.to_string())
    }
    }

    #JSON Operations

    // Parse JSON
    let json_str = "{\"name\":\"Alice\",\"age\":30}"
    let obj = @js.JSON::parse(json_str)

    // Stringify
    let obj = @js.from_map({ "name": @core.any("Alice"), "age": @core.any(30) })
    let json_str = @js.JSON::stringify(obj)

    // With formatting
    let pretty = @js.JSON::stringify_with_indent(obj, 2)

    #Nullish Handling

    // Nullish[T] handles both null and undefined
    let nullish: @js.Nullish[Int] = @js.null()

    match nullish.to_option() {
    Some(value) => @console.log(value)
    None => @console.log("null or undefined")
    }

    // Nullable[T] only handles null
    let nullable: @js.Nullable[Int] = @js.Nullable::null()

    #Iterators

    // JavaScript iterator
    let iter = js_array.values()
    loop {
    let next = iter.next()
    if next.done {
    break
    }
    @console.log(next.value)
    }

    // Async iterator
    async fn iterate_async(iter: @js.AsyncIterator) -> Unit {
    loop {
    let next = iter.next().wait()
    if next.done {
    break
    }
    @console.log(next.value)
    }
    }

    #Understanding Core FFI Types

    When reading test code or using this library, you'll encounter several core types and functions for bridging MoonBit and JavaScript. This section explains what they are and when to use them.

    #@core.Any - The Universal JavaScript Type

    @core.Any represents any JavaScript value (similar to TypeScript's any). It's the foundation type for all JavaScript interop.

    // @core.Any can hold any JavaScript value
    let num : @core.Any = @core.any(42) // number
    let str : @core.Any = @core.any("hello") // string
    let obj : @core.Any = @core.Object::new() // object

    When you see @core.Any in code: This value came from JavaScript and its type is unknown at compile time.

    #@core.any() - Converting MoonBit Values to JavaScript

    @core.any() converts MoonBit values that implement JsImpl trait to @core.Any.

    // Convert MoonBit values to JavaScript
    let js_int = @core.any(42) // Int → @core.Any
    let js_str = @core.any("hello") // String → @core.Any
    let js_bool = @core.any(true) // Bool → @core.Any
    let js_arr = @core.any([1, 2, 3]) // Array → @core.Any

    When to use: When passing MoonBit values to JavaScript APIs that expect dynamic types.

    #@js.identity() - Unsafe Type Casting

    @js.identity() performs an unsafe cast between any two types. It's used to convert @core.Any back to typed MoonBit values.

    // Cast @core.Any to specific types (unsafe!)
    let js_value : @core.Any = obj._get("count")
    let count : Int = @js.identity(js_value)

    // Common pattern: inline casting
    let name : String = @js.identity(obj._get("name"))

    Warning: @js.identity() does no runtime checking. If the JavaScript value isn't the expected type, you'll get undefined behavior.

    Alternative: Use .cast() method which is equivalent but more readable:
    let count : Int = obj._get("count").cast()

    #JsImpl Trait - Types That Can Interop with JavaScript

    JsImpl is a trait for types that can be safely converted to JavaScript values. All JavaScript wrapper types and MoonBit primitives implement this trait.

    // These types implement JsImpl:
    // - @core.Any, @js.Object, @js.JsArray, @js.Promise[T], etc.
    // - MoonBit primitives: String, Int, Double, Bool, etc.
    // - Array[T] where T : JsImpl

    // JsImpl provides these methods:
    trait JsImpl {
    as_any(Self) -> Any // Convert to @core.Any
    get(Self, key) -> Any // JS: self[key]
    set(Self, key, val) -> Unit // JS: self[key] = val
    call(Self, key, args) -> Any // JS: self[key](...args)
    // ... and more
    }

    When you see &JsImpl in function signatures: The function accepts any type that can be converted to JavaScript.

    #Common Patterns in Test Code

    #Pattern 1: Getting typed values from JavaScript objects

    // JavaScript: const name = obj.name
    let name : String = @js.identity(obj._get("name"))

    // Alternative using cast()
    let age : Int = obj._get("age").cast()

    #Pattern 2: Creating JavaScript objects with MoonBit values

    // Using from_map (recommended)
    let obj = @js.from_map({
    "name": @core.any("Alice"),
    "age": @core.any(30)
    })

    // Manual construction
    let obj = @core.Object::new()
    obj.set("name", "Alice") // String implements JsImpl
    obj.set("age", 30) // Int implements JsImpl

    #Pattern 3: Handling nullable/optional values

    // JavaScript null/undefined → MoonBit Option
    let maybe_value : Int? = @js.identity_option(obj._get("optional_field"))

    // MoonBit Option → JavaScript null
    let js_value = @js.from_option(Some(42)) // → 42
    let js_null = @js.from_option(None) // → null

    #Pattern 4: Calling JavaScript methods

    // No arguments: obj.method()
    let result = obj.call0("method")

    // With arguments: obj.method(arg1, arg2)
    let result = obj._call("method", [arg1, arg2])

    // With type casting
    let str_result : String = obj.call0("toString").cast()

    #Summary Table

    Function/TypePurposeExample
    @core.AnyUniversal JS value typelet v : @core.Any = ...
    @core.any(x)MoonBit → JS conversion@core.any(42)
    @js.identity(x)Unsafe type castlet n : Int = @js.identity(v)
    .cast()Same as identity (method)v.cast()
    JsImplTrait for JS-compatible typesfn foo(x : &JsImpl)
    .as_any()Convert to @core.Anyobj.as_any()
    ._get(key)Property accessobj._get("name")
    .set(key, val)Property assignmentobj.set("age", 30)

    #Advanced Patterns

    #Escape Hatch Pattern

    When you need to access JavaScript APIs not yet wrapped in this library:

    // Define external FFI function
    extern "js" fn ffi_my_custom_api(arg: @core.Any) -> @core.Any =
    #|arg => {
    #| // JavaScript code here
    #| return arg.customMethod();
    #|}

    // Wrap it in a type-safe function
    pub fn my_custom_api(value: String) -> String {
    let result = ffi_my_custom_api(value)
    result.cast()
    }

    See escape_hatch.mbt.md for more patterns.

    #Type Reference

    #Core Types

    • @core.Any - Universal JavaScript value type (was @js.Js before v0.5.0)
    • @js.Object - JavaScript object
    • @js.JsArray - JavaScript array
    • @js.Promise[T] - JavaScript Promise
    • @js.Function - JavaScript function
    • @js.Error - JavaScript Error

    #Nullish Types

    • @js.Nullish[T] - Handles both null and undefined (converts to Option[T])
    • @js.Nullable[T] - Handles only null
    • @js.Undefinedable[T] - Handles only undefined

    #Binary Data

    See mizchi/js/builtins/arraybuffer package.

    This core package is used by:

    • mizchi/js/web/* - Web Standard APIs
    • mizchi/js/browser/* - Browser DOM APIs
    • mizchi/js/node/* - Node.js runtime APIs
    • mizchi/js/cloudflare/* - Cloudflare Workers APIs
    • mizchi/js/npm/* - NPM package bindings

    See the main project README for the complete package list.

    #Migration from v0.4.0

    #Breaking Changes in v0.5.0

    // Type rename: @js.Js → @core.Any
    let value: @core.Any = obj._get("key")

    // Method rename: to_js() → as_any()
    let any = obj.as_any()

    // Function rename: @js.js() → @core.any()
    let converted = @core.any(value)

    // Casting: unsafe_cast() → identity() or cast()
    let typed: Int = value.cast()

    #Contributing

    See the main project documentation for contribution guidelines.

    AbortController

    @see https://developer.mozilla.org/en-US/docs/Web/API/AbortController

    AbortSignal

    @see https://developer.mozilla.org/en-US/docs/Web/API/AbortController

    AggregateError

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

    Any

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

    ArrayBuffer

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer

    AsyncDisposableStack

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DisposableStack

    AsyncIterator

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols

    AtomicsWaitResult

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics

    DataView

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer

    Date

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

    DisposableStack

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DisposableStack

    EvalError

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

    FinalizationRegistry

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry

    Function

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function

    JSON

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON

    JsArray

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

    JsBigInt

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

    JsError

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

    JsIterator

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols

    JsMap

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

    JsSet

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

    JsString

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

    Math

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math

    Nullable

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

    Nullish

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

    Object

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

    Promise

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

    PromiseResolvers

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

    Proxy

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

    RangeError

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

    ReferenceError

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

    RegExp

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

    RegExpMatchArray

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

    RegExpResult

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

    SharedArrayBuffer

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer

    Symbol

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol

    SyntaxError

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

    ThrowError

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

    Timer

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

    TypeError

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

    TypedArray

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer

    URIError

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

    WeakMap

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry

    WeakRef

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry

    WeakSet

    @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry

    any

    fn[T] any(value : T) ->
    Any

    apply

    fn apply(target :
    Any
    , this_argument :
    Any
    , arguments_list : Array[
    Any
    ]) ->
    Any

    JS: Reflect.apply(target, thisArgument, argumentsList) Calls a target function with arguments as specified

    atob

    fn atob(encoded_data : String) -> String raise

    JS: atob(encodedData)

    Decodes a string of data which has been encoded using Base64 encoding.

    btoa

    fn btoa(data : String) -> String raise

    JS: btoa(data)

    Creates a Base64-encoded ASCII string from a binary string.

    clearInterval

    fn clearInterval(timer :
    Timer
    ) -> Unit

    JS: clearInterval(timer)

    Cancels an interval previously established by calling setInterval().

    clearTimeout

    fn clearTimeout(timer :
    Timer
    ) -> Unit

    JS: clearTimeout(timer)

    Cancels a timeout previously established by calling setTimeout().

    construct

    fn construct(target :
    Any
    , arguments_list : Array[
    Any
    ], new_target :
    Any
    ?) ->
    Any

    JS: Reflect.construct(target, argumentsList, newTarget?) Acts like the new operator as a function

    decodeURI

    fn decodeURI(encoded_uri : String) -> String

    JS: decodeURI(encodedURI)

    decodeURIComponent

    fn decodeURIComponent(encoded_str : String) -> String

    JS: decodeURIComponent(encodedStr)

    defineProperty

    fn defineProperty(target :
    Any
    , property_key :
    Any
    , attributes :
    Any
    ) -> Bool

    JS: Reflect.defineProperty(target, propertyKey, attributes) Similar to Object.defineProperty but returns a Boolean

    deleteProperty

    fn deleteProperty(target :
    Any
    , property_key :
    Any
    ) -> Bool

    JS: Reflect.deleteProperty(target, propertyKey) Deletes a property from an object

    dynamic_import

    fn dynamic_import(module_name : String) ->
    Any

    Dynamic import (ES modules) Note: Returns a Promise

    encodeURI

    fn encodeURI(uri : String) -> String

    JS: encodeURI(uri)

    encodeURIComponent

    fn encodeURIComponent(str : String) -> String

    JS: encodeURIComponent(str)

    from_fn0

    fn[A] from_fn0(f : () -> A) ->
    Any

    Wrap MoonBit function as JS function (0 args)

    from_fn1

    fn[A, B] from_fn1(f : (A) -> B) ->
    Any

    Wrap MoonBit function as JS function (1 arg)

    from_fn2

    fn[A, B, C] from_fn2(f : (A, B) -> C) ->
    Any

    Wrap MoonBit function as JS function (2 args)

    from_fn3

    fn[A, B, C, D] from_fn3(f : (A, B, C) -> D) ->
    Any

    Wrap MoonBit function as JS function (3 args)

    get

    JS: Reflect._get(target, propertyKey, receiver?) Gets a property value from an object

    getOwnPropertyDescriptor

    fn getOwnPropertyDescriptor(target :
    Any
    , property_key :
    Any
    ) ->
    Any

    JS: Reflect.getOwnPropertyDescriptor(target, propertyKey) Gets the property descriptor of an own property

    getPrototypeOf

    fn getPrototypeOf(target :
    Any
    ) ->
    Any

    JS: Reflect.getPrototypeOf(target) Gets the prototype of an object

    globalThis

    fn globalThis() ->
    Any

    JS: globalThis

    has

    fn has(target :
    Any
    , property_key :
    Any
    ) -> Bool

    JS: Reflect.has(target, propertyKey) Checks if an object has a property

    identity

    fn[A, B] identity(value : A) -> B

    isExtensible

    fn isExtensible(target :
    Any
    ) -> Bool

    JS: Reflect.isExtensible(target) Checks if an object is extensible

    isFinite

    fn isFinite(v : Double) -> Bool

    JS: isFinite(v)

    isNaN

    fn isNaN(v :
    Any
    ) -> Bool

    JS: isNaN(v)

    log

    fn log(message :
    Any
    ) -> Unit

    new

    JS: new cls(...args)

    new_array

    fn new_array() ->
    Any

    new_object

    fn new_object() ->
    Any

    ownKeys

    JS: Reflect.ownKeys(target)

    Returns an array of the target object's own property keys. Note: The returned array is a snapshot and should be treated as immutable.

    parseFloat

    fn parseFloat(string : String) -> Double?

    JS: parseFloat(string)

    Parse a string and return a floating point number. Returns None if the string cannot be parsed as a number.

    parseInt

    fn parseInt(string : String, radix? : Int) -> Int?

    JS: parseInt(string, radix)

    Parse a string and return an integer. If radix is not provided, it defaults to 10 (or 16 if string starts with "0x").

    preventExtensions

    fn preventExtensions(target :
    Any
    ) -> Bool

    JS: Reflect.preventExtensions(target) Prevents new properties from being added to an object

    promisify0

    fn[R] promisify0(f : async () -> R) -> (() ->
    Promise
    [R])

    promisify1

    fn[A, R] promisify1(f : async (A) -> R) -> ((A) ->
    Promise
    [R])

    Moonbit Async Function to JS Promise Function

    promisify2

    fn[A, B, R] promisify2(f : async (A, B) -> R) -> ((A, B) ->
    Promise
    [R])

    Moonbit Async Function to JS Promise Function

    promisify3

    fn[A, B, C, R] promisify3(f : async (A, B, C) -> R) -> ((A, B, C) ->
    Promise
    [R])

    Moonbit Async Function to JS Promise Function

    queueMicrotask

    fn queueMicrotask(callback : () -> Unit) -> Unit

    JS: queueMicrotask(callback)

    Queue a microtask to be executed after the current task finishes. Microtasks are executed before the next task in the event loop.

    run_async

    fn run_async(f : async () -> Unit noraise) -> Unit

    MoonBit builtin %async.run

    set

    fn set(target :
    Any
    , property_key :
    Any
    , value :
    Any
    , receiver :
    Any
    ?) -> Bool

    JS: Reflect.set(target, propertyKey, value, receiver?) Sets a property value on an object

    setInterval

    fn setInterval(f : () -> Unit, duration : Int) ->
    Timer

    JS: setInterval(f, duration)

    Repeatedly calls a function with a fixed time delay between each call. Returns a Timer that can be used to cancel the interval.

    setPrototypeOf

    fn setPrototypeOf(target :
    Any
    , prototype :
    Any
    ) -> Bool

    JS: Reflect.setPrototypeOf(target, prototype) Sets the prototype of an object

    setTimeout

    fn setTimeout(f : () -> Unit, duration : Int) ->
    Timer

    JS: setTimeout(f, duration)

    Schedules a function to be called after a specified delay (in milliseconds). Returns a Timer that can be used to cancel the scheduled execution.

    structuredClone

    fn structuredClone(value :
    Any
    ) ->
    Any

    JS: structuredClone(value)

    Creates a deep clone of a value using the structured clone algorithm. This can clone complex objects including nested objects, arrays, dates, etc.

    suspend

    async fn[T, E : Error] suspend(f : ((T) -> Unit, (E) -> Unit) -> Unit) -> T raise E

    MoonBit builtin %async.suspend

    symbol

    fn symbol(name : String) ->
    Symbol

    JS: Symbol(name)

    throwable

    fn[T] throwable(f : () -> T raise?) -> T raise
    ThrowError

    Wraps a synchronous function call, converting any thrown JS errors into ThrowError
    let result = throwable(() => undefined()._invoke([]))

    typeof_

    fn typeof_(v :
    Any
    ) -> String

    JS: typeof v

    undefined

    fn undefined() ->
    Any

    JS: undefined

    Source Files