Command line tool and library to generate a Rust crate wrapping JavaScript code into a WebAssembly Component using the QuickJS engine.
ComponentizeJS achieves the same goal of wrapping JavaScript code into a WebAssembly Component, but it does it using a modified version of the SpiderMonkey engine.
Advantages of wasm-rquickjs over ComponentizeJS:
- At the time of writing, there are known bugs in ComponentizeJS (or one of its underlying modules) that prevents it from being used in production.
- Much simpler to develop and debug, as everything exposed for JavaScript is implemented in async Rust using the rquickjs library
- The WIT-JS mapping rules and the set of available JavaScript APIs are well defined
- Smaller WASM binary size
Advantages of ComponentizeJS over wasm-rquickjs:
- Faster runtime (due to the SpiderMonkey engine)
- Faster startup time (it does pre-initialization with Wizer)
- No need for the Rust toolchain for end users
The project is similar to wasmedge-quickjs in using te QuickJS engine compiled to WASM to run JavaScript code, but it is different in the following ways:
- It does not provide support for using the component model from JS (defining imports and exports using WIT)
- The imports the resulting WASM component has are WasmEdge specific
The tool can be used as a command line tool or as a library. The command line tool has two top level commands:
generate-wrapper-crate Generate the wrapper crate for a JavaScript module
generate-dts Generate TypeScript module definitions
This is the primary command that generates the Rust crate embedding the JavaScript code into a WebAssembly Component.
Usage: wasm-rquickjs generate-wrapper-crate --js <JS> --wit <WIT> --output <OUTPUT>
- The
--jsarguments is the path to the JavaScript file to be wrapped. There can be only one JavaScript file, containing an ES6 module exporting the necessary functions and classes as described below. - The
--witargument is the path to the WIT root containing a single world that describes the imports and exports of the component - The
--outputargument is the path to the output directory where the generated Rust crate will be created.
The output directory is going to contain a self-contained Rust crate that can be compiled into a WASM component using the cargo-component tool.
The generated crate has some features that control what imports the component will have beside the ones defined in the user's WIT world:
logging: enables thewasi:loggingimport to be used for the JavaScriptconsoleAPIhttp: enables thewasi:httpimport to be used for the JavaScriptfetchAPI
By default both feature flags are enabled.
The generate-dts command generates TypeScript module definitions for all the exported and imported interfaces:
Usage: wasm-rquickjs generate-dts --wit <WIT> --output <OUTPUT>
- The
--witargument is the path to the WIT root containing a single world that describes the imports and exports of the component. - The
--outputargument is the path to the output directory where the generated TypeScript module definitions (.d.ts) will be created.
wasm-rquickjs is integrated into Golem's command line interface, so it can be directly used
using Golem app templates.
The following WIT code:
package demo:pkg;
world example {
export hello: func() -> string;
}must be implemented in JavaScript as:
export const hello = () => {
return "Hello, world!";
};The this is bound to the module object. The JS function name is always in camelCase.
Exported interfaces has to be exported from JavaScript as objects:
The following WIT example:
package demo:pkg;
interface sample-api {
get-string-length: func(value: string) -> u64;
}
world example {
export sample-api;
}has to be implemented in JavaScript as:
export const sampleApi = {
getStringLength: (value) => {
return value.length;
}
};All names are converted to camelCase. The JavaScript this is bound to object representing the exporter interface, in
the above example it is sampleApi.
Exported resources are implemented as classes in JS:
The following WIT example:
package demo:pkg;
interface iface {
resource example-resource {
constructor(name: string);
get-name: func() -> string;
compare: static func(h1: borrow<example-resource>, h2: borrow<example-resource>) -> s32;
merge: static func(h1: own<example-resource>, h2: own<example-resource>) -> hello;
}
}
world example {
export iface;
}Must be exported from JavaScript in the following way:
class Hello {
constructor(name) {
this.name = name;
}
// async to demonstrate it is possible
async getName() {
return this.name;
}
static compare(h1, h2) {
if (h1.name === h2.name) {
return 0;
} else if h1.name < h2.name) {
return -1;
} else {
return 1;
}
}
static merge(h1, h2) {
return new Hello(`${h1.name} & ${h2.name}`);
}
}
export const iface = {
Hello: Hello,
};The classes have a UpperCamelCase name and their methods are in camelCase. All methods and static methods can be either sync or async.
| Name | WIT | JS | Notes |
|---|---|---|---|
| Character | char |
string |
- |
| String | string |
string |
- |
| Signed 8-bit integer | s8 |
number |
- |
| Unsigned 8-bit integer | u8 |
number |
- |
| Signed 16-bit integer | s16 |
number |
- |
| Unsigned 16-bit integer | u16 |
number |
- |
| Signed 32-bit integer | s32 |
number |
- |
| Unsigned 32-bit integer | u32 |
number |
- |
| Signed 64-bit integer | s64 |
bigint |
- |
| Unsigned 64-bit integer | u64 |
bigint |
- |
| 32-bit float | f32 |
number |
- |
| 64-bit float | f64 |
number |
- |
| Optional type | option<T> |
T | undefined |
Nested options are encoded differently |
| List | list<T> |
T[] |
- |
| Result | result<T, E> |
{ tag: "ok": val: T } | { tag: "err", val: E } |
- |
| Tuple | tuple<A, B, C> |
Array | - |
| Enum | enum { a, b, c} |
"a" | "b" | "c" |
The strings match the WIT enum cases |
| Flags | flags { a, b, c } |
{ a: boolean, b: boolean, c: boolean } |
The object keys are camelCase |
| Record | record { .. } |
Object | Field names are camelCase |
| Variant | variant { .. } |
{ tag: "x", val: X } |
Tag names match the WIT variant case names; val is undefined for unit cases |
- Maximum number of function parameters is 26
- Anonymous interface exports/imports are not supported
- Imported individual functions into the world are not supported (only whole interfaces)
If the logging feature flag is enabled in the generated crate, it depends on wasi:logging, otherwise just on the
core WASI interfaces.
assertclearcountcountResetdebugdirdirXmlerrorgroupgroupCollapsedgroupEndinfologtabletimetimeEndtimeLogtracewarn
Only if the http feature flag is enabled in the generated crate. It depends on wasi:http.
fetchHeadersRequestResponseFormDataBlobFile
URLURLSearchParams
Implemented by https://github.com/MattiasBuelens/web-streams-polyfill
ByteLengthQueuingStrategyCountQueuingStrategyReadableByteStreamControllerReadableStreamReadableStreamBYOBReaderReadableStreamBYOBRequestReadableStreamDefaultControllerReadableStreamDefaultReaderTransformStreamTransformStreamDefaultControllerWritableStreamWritableStreamDefaultController
setTimeoutclearTimeoutsetIntervalclearIntervalsetImmediate
TextEncoderTextDecoderTextDecoderStreamTextEncoderStream
formatdeprecatedebugLoginspectisArrayisBooleanisNullisNullOrUndefinedisNumberisStringisSymbolisUndefinedisRegExpisObjectisDateisErrorisFunctionisPrimitiveisBufferlog_extendpromisifycallbackify
BufferINSPECT_MAX_BYTESkMaxLengthkStringMaxLengthconstantsSlowBuffer
readFilereadFileSyncwriteFilewriteFileSync
argvargv0envcwd
byteLengthtoByteArrayfromByteArray
readwrite
crypto.randomUUIDcrypto.getRandomValues
-
Global:
parseIntparseFloatisNaNisFinitequickMicrotaskdecodeURIdecodeURIComponentencodeURIencodeURIComponentescapeunescapeInfinityNaNundefined[Symbol.toStringTag]
-
Object- static methods and properties:
creategetPrototypeOfsetPrototypeOfdefinePropertydefinePropertiesgetOwnPropertyNamesgetOwnPropertySymbolsgroupBykeysvaluesentriesisExtensiblepreventExtensionsgetOwnPropertyDescriptorgetOwnPropertyDescriptorsisassignsealfreezeisSealedisFrozenfromEntrieshasOwn
- methods and properties:
toStringtoLocaleStringvalueOfhasOwnPropertyisPrototypeOfpropertyIsEnumerable__proto____defineGetter____defineSetter____lookupGetter____lookupSetter__
- static methods and properties:
-
Function- methods and properties:
callapplybindtoString[Symbol.hasInstance]fileNamelineNumbercolumnNumber
- methods and properties:
-
Error- methods and properties:
namemessagetoString
- static methods and properties:
isErrorcaptureStackTracestackTraceLimitprepareStackTrace
- methods and properties:
-
Generator- methods and properties:
nextreturnthrow[Symbol.toStringTag]
- static methods and properties:
from
- methods and properties:
-
Iterator- static methods and properties:
from
- methods and properties:
dropfilterflatMapmaptakeeveryfindforEachsomereducetoArray[Symbol.iterator][Symbol.toStringTag]
- static methods and properties:
-
Array- static methods and properties:
isArrayfromof[Symbol.species]
- methods and properties:
atwithconcateverysomeforEachmapfilterreducereduceRightfillfindfindIndexfindLastfindLastIndexindexOflastIndexOfincludesjointoStringtoLocaleStringpoppushshiftunshiftreversetoReversedsorttoSortedslicesplicetoSplicedcopyWithinflatMapflatvalues[Symbol.iterator]keysentries
- static methods and properties:
-
Number- static methods and properties:
parseIntparseFloatisNaNisFiniteisIntegerisSafeIntegerMAX_VALUEMIN_VALUENaNNEGATIVE_INFINITYPOSITIVE_INFINITYEPSILONMAX_SAFE_INTEGERMIN_SAFE_INTEGER
- methods and properties:
toExponentialtoFixedtoPrecisiontoStringtoLocaleStringvalueOf
- static methods and properties:
-
Boolean- methods and properties:
toStringvalueOf
- methods and properties:
-
String- static methods and properties:
fromCharCodefromCodePointraw
- methods and properties:
lengthatcharCodeAtcharAtconcatcodePointAtisWellFormedtoWellFormedindexOflastIndexOfincludesendsWithstartsWithmatchmatchAllsearchsplitsubstringsubstrslicerepeatreplacereplaceAllpadEndpadStarttrimtrimEndtrimRighttrimStarttrimLefttoStringvalueOflocaleComparenormalizetoLowerCasetoUpperCasetoLocaleLowerCasetoLocaleUpperCase[Symbol.iterator]anchorbigblinkboldfixedfontcolorfontsizeitalicslinksmallstrikesubsup
- static methods and properties:
-
Symbol- static methods and properties:
forkeyFor
- methods and properties:
toStringvalueOfdescription[Symbol.toPrimitive][Symbol.toStringTag]
- static methods and properties:
-
Map- static methods and properties:
groupBy[Symbol.species]
- methods and properties:
setgethasdeleteclearsizeforEachvalueskeysentries[Symbol.iterator][Symbol.toStringTag]
- static methods and properties:
-
Set- static methods and properties:
[Symbol.species]
- methods and properties:
addhasdeleteclearsizeforEachisDisjointFromisSubsetOfisSupersetOfintersectiondifferencesymmetricDifferenceunionvalueskeys[Symbol.iterator]entries[Symbol.toStringTag]
- static methods and properties:
-
WeakMap- methods and properties:
setgethasdelete[Symbol.toStringTag]
- methods and properties:
-
WeakSet- methods and properties:
addhasdelete[Symbol.toStringTag]
- methods and properties:
-
GeneratorFunction- methods and properties:
[Symbol.toStringTag]
- methods and properties:
-
Math- static methods and properties:
minmaxabsfloorceilroundsqrtacosasinatanatan2cosexplogpowsintantruncsigncoshsinhtanhacoshasinhatanhexpm1log1plog2log10cbrthypotrandomf16roundfroundimulclz32sumPrecise[Symbol.toStringTag]ELN10LN2LOG2ELOG10EPISQRT1_2SQRT2
- static methods and properties:
-
Reflect- static methods and properties:
applyconstructdefinePropertydeletePropertygetgetOwnPropertyDescriptorgetPrototypeOfhasisExtensibleownKeyspreventExtensionssetsetPrototypeOf[Symbol.toStringTag]
- static methods and properties:
-
RegExp- static methods and properties:
escape[Symbol.species]
- methods and properties:
flagssourceglobalignoreCasemultilinedotAllunicodeunicodeSetsstickyhasIndicesexeccompiletesttoString[Symbol.replace][Symbol.match][Symbol.matchAll][Symbol.search][Symbol.split]
- static methods and properties:
-
JSON- static methods and properties:
parsestringify[Symbol.toStringTag]
- static methods and properties:
-
Promise- static methods and properties:
resolverejectallallSettledanytryracewithResolvers[Symbol.species]
- methods and properties:
thencatchfinally[Symbol.toStringTag]
- static methods and properties:
-
AsyncFunction- methods and properties:
[Symbol.toStringTag]
- methods and properties:
-
AsyncIterator- methods and properties:
nextreturnthrow
- methods and properties:
-
AsyncGeneratorFunction- methods and properties:
[Symbol.toStringTag]
- methods and properties:
-
AsyncGenerator- methods and properties:
nextreturnthrow[Symbol.toStringTag]
- methods and properties:
-
Date- static methods and properties:
nowparseUTC
- methods and properties:
valueOftoString[Symbol.toPrimitive]toUTCStringtoGMTStringtoISOStringtoDateStringtoTimeStringtoLocaleStringtoLocaleDateStringtoLocaleTimeStringgetTimezoneOffsetgetTimegetYeargetFullYeargetUTCFullYeargetMonthgetUTCMonthgetDategetUTCDategetHoursgetUTCHoursgetMinutesgetUTCMinutesgetSecondsgetUTCSecondsgetMillisecondsgetUTCMillisecondsgetDaygetUTCDaysetTimesetMillisecondssetUTCMillisecondssetSecondssetUTCSecondssetMinutessetUTCMinutessetHourssetUTCHourssetDatesetUTCDatesetMonthsetUTCMonthsetYearsetFullYearsetUTCFullYeartoJSON
- static methods and properties:
-
BigInt- static methods and properties:
asIntNasUintN
- methods and properties:
toStringvalueOf[Symbol.toStringTag]
- static methods and properties:
-
ArrayBuffer- static methods and properties:
isView[Symbol.species
- methods and properties:
byteLengthmaxByteLengthresizeabledetachedresizeslicetransfertransferToFixedLength[Symbol.toStringTag]
- static methods and properties:
-
SharedArrayBuffer- static methods and properties:
[Symbol.species]
- methods and properties:
byteLengthmaxByteLengthgrowablegrowslice[Symbol.toStringTag]
- static methods and properties:
-
Typed arrays (
Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,BigInt64Array,BigUint64Array,Float32Array,Float64Array,Float16Array)- static methods and properties:
fromof[Symbol.species]
- methods and properties:
lengthatwithbufferbyteLengthsetbyteOffsetvalues[Symbol.iterator]keysentries[Symbol.toStringTag]copyWithineverysomeforEachmapfilterreducereduceRightfillfindfindIndexfindLastfindLastIndexreversetoReversedslicesubarraysorttoSortedjointoLocaleStringindexOflastIndexOfincludes
- static methods and properties:
-
DataView- methods and properties:
bufferbyteLengthbyteOffsetgetInt8getUint8getInt16getUint16getInt32getUint32getBigInt64getBigUint64getFloat16getFloat32getFloat64setInt8setUint8setInt16setUint16setInt32setUint32setBigInt64setBigUint64setFloat16setFloat32setFloat64[Symbol.toStringTag]
- methods and properties:
-
Atomics- static methods and properties:
addandorsubxorexchangecompareExchangeloadstoreisLockFreepausewaitnotify[Symbol.toStringTag]
- static methods and properties:
-
Performance- methods and properties:
now
- methods and properties:
-
WeakRef- methods and properties:
deref[Symbol.toStringTag]
- methods and properties:
-
FinalizationRegistry- methods and properties:
registerunregister[Symbol.toStringTag]
- methods and properties:
-
Callsite- methods and properties:
-
isNativegetFileNamegetFunctiongetFunctionNamegetColumnNumbergetLineNumber[Symbol.toStringTag]
- methods and properties:
-
-
Proxy
There are a few important things to keep in mind when working on the project:
-
The
skeletoncrate can be opened and compiled separately when working on the APIs provided for JavaScript. Unfortunately we cannot use theCargo.tomlfile name in it because that breaks Rust packaging - so before working on it, it has to be renamed toCargo.tomland before committing back it has to be renamed back toCargo.toml_. -
If the
skeletoncrate was compiled for testing, and thenwasm-rquickjsis compiled, theinclude_dir!macro is embedding everything from theskeletondirectory including thetargetdirectory, resulting in slow compilation times and huge resulting binaries. Use thecleanup-skeleton.shscript to quickly remove thetargetdirectory from theskeletoncrate.