js

js bindings for builtins/web/node/deno/bun (browser APIs split to mizchi/js_browser)

js
node
dom
deno
bun
moon add mizchi/js@0.12.2
Download zip
Author
Version
0.12.2
License
MIT
Last updated
15 hours ago
Downloads
34K

Dependencies

README

#mizchi/js

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

#Package Layout

Starting in v0.11.0, environment-specific bindings live in their own MoonBit modules under the mizchi/js_* namespace. The core mizchi/js module covers JavaScript built-ins, Web Standard APIs, and Node.js — pull in the additional modules only for the runtimes you target.

ModuleScopeSource
mizchi/jsCore FFI, JS built-ins, Web Standard APIs, Node.jssrc/
mizchi/js_browserBrowser-only APIs (DOM, canvas, IndexedDB, storage, navigation, service worker, …)modules/js_browser/
mizchi/js_denoDeno runtime APIsmodules/js_deno/
mizchi/js_bunBun runtime APIsmodules/js_bun/
mizchi/js_webextensionsWebExtensions (chrome.* / browser.*)modules/js_webextensions/
mizchi/npm_typedNPM package bindings (React, Hono, Zod, AI SDK, …)separate repo
mizchi/cloudflare.mbtCloudflare Workers bindingsseparate repo

See docs/package-split.md for the migration steps and the multi-module layout.

#Version Requirements

v0.10.0+ requires MoonBit nightly 2025-12-09 or later for ESM #module directive support:

moon 0.1.20251209 (8d6e473 2025-12-09) moonc v0.6.34+7262739a4-nightly (2025-12-09) moonrun 0.1.20251209 (8d6e473 2025-12-09)

If you need stable toolchain compatibility, use v0.8.x.

#Installation

$ moon add mizchi/js # Pull in additional runtimes as needed: $ moon add mizchi/js_browser $ moon add mizchi/js_deno $ moon add mizchi/js_bun $ moon add mizchi/js_webextensions

Add to your moon.pkg.json:

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

#📚 API Documentation by Platform

PlatformDocumentationExamplesStatus
Core JavaScriptsrc/README.mdjs_examples.mbt.md🧪 Tested
Browsermodules/js_browser/src/README.mdbrowser_examples.mbt.md🧪 Tested
Node.jssrc/node/README.mdnode_examples.mbt.md🧪 Tested
Denosrc/deno/README.md-🧪 Tested
Reactmizchi/npm_typedSee npm_typed repo📦 Moved

#📖 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
  • obj["key"], obj["key"] = value - Property access (or _get(key), _set(key, value))
  • 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, setTimeout etc.
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
DataViewmizchi/js/builtins/arraybuffer🧪 TestedBuffer views
memory | | Pattern & Reflection | | RegExp | mizchi/js/builtins/regexp | 🧪 Tested | Regular expressions | | Reflect | mizchi/js/builtins/reflect | 🧪 Tested | Reflection API | | Proxy | mizchi/js/builtins/proxy | 🤖 AI Generated | Proxy API | | Iteration & Async | | Iterator | mizchi/js/builtins/iterator | 🧪 Tested | JsIterator protocol | | AsyncIterator | mizchi/js/builtins/iterator | 🧪 Tested | Async iteration | | Concurrency | | Atomics | mizchi/js/builtins/atomics | 🧪 Tested | Atomic operations | | Resource Management | | DisposableStack | mizchi/js/builtins/disposable | 🧪 Tested | Disposable 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

Browser, Deno, Bun, and WebExtensions APIs ship as separate mizchi/js_* modules — add each one to your moon.mod.json deps only if you target that runtime.

PlatformModuleStatusDocumentation
Node.jsmizchi/js/node/* (bundled with mizchi/js)🧪 TestedNode.js README
Browser APImizchi/js_browser/*🧪 TestedBrowser README
Denomizchi/js_deno🧪 TestedDeno README
Bunmizchi/js_bun🤖 AI Generated-
WebExtensionsmizchi/js_webextensions🤖 AI GeneratedWebExtensions README

#NPM Package Bindings

Moved to separate repository: NPM package bindings are now maintained at mizchi/npm_typed

CategoryPackagesRepository
UI FrameworksReact, React DOM, React Router, Preact, Inkmizchi/npm_typed
Web FrameworksHono, better-authmizchi/npm_typed
AI / LLMVercel AI SDK, MCP SDK, Claude Code SDKmizchi/npm_typed
Cloud Services@aws-sdk/client-s3 (S3, R2, GCS, MinIO)mizchi/npm_typed
DatabasePGlite, DuckDB, Drizzle, pgmizchi/npm_typed
ValidationZod, AJVmizchi/npm_typed
Build ToolsTerser, Vite, Unplugin, Lighthousemizchi/npm_typed
Utilitiesdate-fns, semver, chalk, dotenv, chokidar, yargs, debugmizchi/npm_typed
TestingTesting Library, Puppeteer, Playwright, Vitest, JSDOM, MSWmizchi/npm_typed
Parsinghtmlparser2, js-yamlmizchi/npm_typed
Othersimple-git, ignore, memfs, source-map, comlinkmizchi/npm_typed

#Limited Support APIs

FeatureStatusNote
eval()❌ Not SupportedSecurity and type safety concerns
new Function()❌ Not SupportedSecurity and type safety concerns

#Project Status

  • Core JS / Web Standards (mizchi/js) - built-ins, Web APIs, fetch, URL, Streams, Crypto, WebSocket
  • Node.js Core APIs (mizchi/js/node/*) - fs, path, process, child_process, etc.
  • 📦 Browser / DOM (mizchi/js_browser) - Split out in v0.11.0
  • 📦 Deno Runtime (mizchi/js_deno) - Split out in v0.11.0
  • 📦 Bun Runtime (mizchi/js_bun) - Split out in v0.11.0
  • 📦 WebExtensions (mizchi/js_webextensions) - Split out in v0.11.0
  • 📦 React / NPM Packages - Maintained at mizchi/npm_typed
  • 📦 Cloudflare Workers - Maintained at mizchi/cloudflare.mbt

#Goals

  • Provide comprehensive JavaScript FFI bindings for MoonBit
  • Platform Coverage (split across mizchi/js_* modules)
    • ✅ Browser DOM and Web APIs (mizchi/js_browser)
    • ✅ Node.js (bundled with mizchi/js) / Deno (mizchi/js_deno) / Bun (mizchi/js_bun)
    • ✅ JavaScript built-in objects and Web Standard APIs (mizchi/js)
  • Ecosystem

#Quick Start

#Basic FFI Operations

// Create JavaScript objects
let obj = @js.from_entries([
("name", @js.any("Alice")),
("age", @js.any(30))
])

// Get property
let name = obj["name"]

// Set property
obj["age"] = @js.any(31)

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

// Type casting
let age: Int = obj["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

///|
test {
// Create objects
let obj = @core.new_object()
obj["name"] = @core.any("Alice")
obj["age"] = @core.any(25)

// Get properties
let name : String = obj["name"].cast()
let age : Int = obj["age"].cast()
inspect(name, content="Alice")
inspect(age, content="25")

// Call methods
let has_name : Bool = obj._call("hasOwnProperty", [@core.any("name")]).cast()
inspect(has_name, content="true")

// Create from entries
let obj2 = @core.from_entries([("x", @core.any(10)), ("y", @core.any(20))])
let x : Int = obj2["x"].cast()
inspect(x, content="10")
}

#Type Casting

///|
test {
// Using cast() method (recommended)
let js_value : @core.Any = @core.any(42)
let value : Int = js_value.cast()
inspect(value, content="42")

// Using identity() for low-level FFI
let value2 : Int = @core.identity(js_value)
inspect(value2, content="42")

// Optional types
let nullable : Int? = @core.identity_option(@core.null())
inspect(nullable, content="None")
let some_value : Int? = @core.identity_option(@core.any(100))
inspect(some_value, content="Some(100)")
}

#JSON Operations

///|
test {
// Parse JSON
let json_str = "{\"name\":\"Alice\",\"age\":30}"
let obj = @core.json_parse(json_str)
let name : String = obj["name"].cast()
inspect(name, content="Alice")

// Stringify
let obj2 = @core.from_entries([("x", @core.any(1))])
let json_str2 = @core.json_stringify(obj2)
inspect(json_str2, content="{\"x\":1}")
}

#Nullish Handling

///|
test {
// Check nullish values
let null_val = @core.null()
let undefined_val = @core.undefined()
inspect(@core.is_nullish(null_val), content="true")
inspect(@core.is_nullish(undefined_val), content="true")
inspect(@core.is_nullish(@core.any(42)), content="false")

// identity_option for safe conversion
let maybe_null : Int? = @core.identity_option(null_val)
inspect(maybe_null, content="None")

// from_option for MoonBit Option -> JS
let js_some = @core.from_option(Some(42))
let js_none = @core.from_option((None : Int?))
inspect(@core.is_nullish(js_some), content="false")
inspect(@core.is_nullish(js_none), content="true")
}

#Understanding Core FFI Types

#@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.

///|
test {
// @core.Any can hold any JavaScript value
let num : @core.Any = @core.any(42)
let str : @core.Any = @core.any("hello")
let obj : @core.Any = @core.new_object()
inspect(@core.typeof_(num), content="number")
inspect(@core.typeof_(str), content="string")
inspect(@core.typeof_(obj), content="object")
}

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

@core.any() converts MoonBit values to @core.Any.

///|
test {
// Convert MoonBit values to JavaScript
let js_int = @core.any(42)
let js_str = @core.any("hello")
let js_bool = @core.any(true)
let int_val : Int = js_int.cast()
let str_val : String = js_str.cast()
let bool_val : Bool = js_bool.cast()
inspect(int_val, content="42")
inspect(str_val, content="hello")
inspect(bool_val, content="true")
}

#Common Patterns

#Pattern 1: Getting typed values from JavaScript objects

///|
test {
let obj = @core.from_entries([
("name", @core.any("Alice")),
("age", @core.any(30)),
])

// Using cast()
let name : String = obj["name"].cast()
let age : Int = obj["age"].cast()
inspect(name, content="Alice")
inspect(age, content="30")
}

#Pattern 2: Handling nullable/optional values

///|
test {
let obj = @core.from_entries([("name", @core.any("Alice"))])

// Existing field
let name : String? = @core.identity_option(obj["name"])
inspect(
name,
content=(
#|Some(Alice)

),
)

// Missing field returns undefined
let missing : String? = @core.identity_option(obj["missing"])
inspect(missing, content="None")
}

#Pattern 3: Calling JavaScript methods

///|
test {
let arr = @core.any([1, 2, 3])

// Call method with arguments
let joined : String = arr._call("join", [@core.any("-")]).cast()
inspect(joined, content="1-2-3")

// Get property
let length : Int = arr["length"].cast()
inspect(length, content="3")
}

#TypeOf[T] - JavaScript Constructor Type

TypeOf[T] represents a JavaScript constructor/class, similar to TypeScript's typeof ClassName.

///|
extern "js" fn get_array_constructor() -> @core.TypeOf[Array[Int]] =
#| () => Array

///|
test "TypeOf usage" {
let arr_ctor = get_array_constructor()

// Create instance using constructor
let arr : Array[Int] = @core.new_instance(arr_ctor, [])
inspect(arr.length(), content="0")

// instanceof check
let js_arr = @core.any([1, 2, 3])
inspect(arr_ctor.is_instanceof(js_arr), content="true")
inspect(arr_ctor.is_instanceof(@core.any("not array")), content="false")
}

#Summary Table

Function/TypePurposeExample
@core.AnyUniversal JS value typelet v : @core.Any = ...
@core.any(x)MoonBit -> JS conversion@core.any(42)
@core.identity(x)Unsafe type castlet n : Int = @core.identity(v)
.cast()Same as identity (method)v.cast()
._get(key) / [key]Property accessobj["name"]
._set(key, val) / [key]=Property assignmentobj["age"] = @core.any(30)
._call(method, args)Method callobj._call("toString", [])
TypeOf[T]Constructor typeTypeOf[Date]

This core package is used by:

  • mizchi/js/web/* - Web Standard APIs
  • mizchi/js_browser/* - Browser DOM APIs (separate module)
  • mizchi/js/node/* - Node.js runtime APIs
  • mizchi/npm_typed - NPM package bindings (React, Hono, AI SDK, etc.)

See the main project README for the complete package list.

#
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

using @mizchi/js/core { type 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

#
Atomics

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

#
AtomicsWaitResult

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

#
BigInt64Array

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

#
BigUint64Array

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

#
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

#
Float32Array

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

#
Float64Array

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

#
Function

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

#
Int16Array

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

#
Int32Array

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

#
Int8Array

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

#
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

using @mizchi/js/core { type Nullable }

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

#
Nullish

using @mizchi/js/core { type 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

using @mizchi/js/core { type 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

#
Reflect

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

#
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

#
Uint16Array

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

#
Uint32Array

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

#
Uint8Array

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

#
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

#
atob

fn atob(encoded_data : String) -> String raise
ThrowError

JS: atob(encodedData)

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

#
btoa

fn btoa(data : String) -> String raise
ThrowError

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().

#
decodeURI

fn decodeURI(encoded_uri : String) -> String

JS: decodeURI(encodedURI)

#
decodeURIComponent

fn decodeURIComponent(encoded_str : String) -> String

JS: decodeURIComponent(encodedStr)

#
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_async

fn[A] from_async(f : async () -> A) ->
Promise
[A]

Convert an async function to a Promise.
let p : Promise[Int] = from_async(async fn() {
let result = some_async_operation()
result
})

#
from_entries

fn from_entries(entries : Array[(String,
Any
)]) ->
Any

#
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)

#
globalThis

fn globalThis() ->
Any

JS: globalThis

#
identity

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

#
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

#
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").

#
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

#
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.

#
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

#
undefined

fn undefined() ->
Any

JS: undefined

Source Files