This is the in-depth reference for the WebAssembly Component JS-API. See the component model explainer for an in-depth explanation of WebAssembly Components (hereafter 'components'). See the JS-API explainer for a higher-level introduction to the JS-API.
This is a draft and is not complete. Major details are unresolved, and there are bugs.
- Components can import and use most web and JS APIs
- Components can export an API usable by JS
- Components interact with the web platform in similar ways to JS:
- Components can feature test whether APIs are present
- Components work whether they are importing a web API, or a JS polyfill, or a component polyfill
- Components are tolerant of web API evolution
- Component misuse of a web API results in failure at that call-site, not a link time error
- Components have better web API performance than WebAssembly modules today
- Components importing every kind of web API
- Components exporting any kind of JS API
The gaps ideally will narrow over time after a v1.0 release, but may not ever fully close.
We extend the imperative WebAssembly JS-API interfaces to also allow validation, compilation, and instantiation of components in addition to modules.
[LegacyNamespace=WebAssembly, Exposed=*]
interface Component {
constructor([AllowResizable] AllowSharedBufferSource bytes, optional WebAssemblyCompileOptions options = {});
};
[LegacyNamespace=WebAssembly, Exposed=*]
interface ComponentInstance {
constructor(Component component, optional object importsObject);
readonly attribute object exports;
};
typedef (Component or Module) InstantiateSource;
dictionary WebAssemblyInstantiatedComponentSource {
required Component component;
required ComponentInstance instance;
};
[Exposed=*]
namespace WebAssembly {
// Same as before, but now will detect if the bytes are a component or module and dispatch differently.
boolean validate([AllowResizable] AllowSharedBufferSource bytes, optional WebAssemblyCompileOptions options = {});
Promise<Module or Component> compile([AllowResizable] AllowSharedBufferSource bytes, optional WebAssemblyCompileOptions options = {});
Promise<(WebAssemblyInstantiatedSource or WebAssemblyInstantiatedComponentSource)> instantiate(
[AllowResizable] AllowSharedBufferSource bytes, optional object importObject, optional WebAssemblyCompileOptions options = {});
// Now takes an InstantiateSource instead of just a Module, and returns a
// ComponentInstance for a Component.
Promise<(Instance or ComponentInstance)> instantiate(
InstantiateSource moduleOrComponentObject, optional object importObject);
};We also add an error type for component functions that return result<_, E> to JS:
[LegacyNamespace=WebAssembly, Exposed=*]
interface ComponentError : Error {
constructor(optional DOMString message = "", optional any data);
readonly attribute any data;
};data is the converted E value. See Create the exports object.
Validation and compilation of components defer to the underlying component embedding interface. This reference adds nothing to it.
A component store is defined by the canonical ABI and is analogous to the core wasm store. It contains a set of component instances and tasks. A store is also a unit of failure where a trap can trigger a lockdown which prevents further execution within the store.
In contrast with core wasm, every component instantiated by the JS-API or ESM (i.e. 'top level') is partitioned to its own store. This means that all top-level component interaction is mediated by the JS-API. A component export imported by another component is treated the same as any other JS import.
This ensures that whether an ESM is implemented as a component or with JS is an implementation detail that can change over time. This also means that a failure within a top-level component instance that triggers a lockdown affects only that component instance.
Nested components share a common store and directly link following the normal component rules. This should be sufficient for most cases where you want to directly link components. In the future, we could consider an extension to instantiate two components within the same store.
Every top-level component instance has an instance record with the following fields:
| Field | Value |
|---|---|
| [[Store]] | the component store |
| [[ComponentInstance]] | the component instance from the embedding API |
| [[HostResourceTypes]] | map from abstract type key to host resource type |
| [[GuestResourceClasses]] | map from abstract type key to guest resource class |
A Component JS object has the following slots:
- [[Component]] - the compiled component from the embedding API.
- [[EnabledBuiltins]] - the enabled builtins.
A ComponentInstance JS object has the following slots:
- [[Instance]] - the instance record.
- [[Exports]] - the exports object.
To trap given an instance record |instance|:
- Invoke |instance|.[[Store]].lock_down().
- Throw a
WebAssembly.RuntimeError.
A trapped instance is locked down: every later call into it traps again before running any code.
A call has entered the guest once the canonical ABI has, on the call's behalf, invoked any function of the component instance (such as realloc) or modified one of its handle tables. A conversion that throws after that point leaves guest state the guest never sees, so the instance is locked down as if the call had trapped, while the original exception still propagates. A conversion that throws before that point leaves the instance untouched.
To construct a Component given |bytes| and |options|:
- Let |stableBytes| be a copy of the bytes held by |bytes|.
- Let |enabledBuiltins| be the result of parsing
builtinsfrom |options|. - Let |component| be the result of compiling |stableBytes| as a component, per the embedding interface.
- If compilation fails:
- Throw a
WebAssembly.CompileError.
- Throw a
- Set this.[[Component]] to |component|.
- Set this.[[EnabledBuiltins]] to |enabledBuiltins|.
To construct a ComponentInstance given a Component |component|, and |importsObject|:
- Let |enabledBuiltins| be |component|.[[EnabledBuiltins]].
- Let |result| be ?
instantiate a component from an imports objectgiven |component|.[[Component]], |importsObject|, |enabledBuiltins|. - Set this.[[Instance]] to |result|.[[Instance]].
- Set this.[[Exports]] to |result|.[[Exports]].
The exports getter returns this.[[Exports]].
validate is modified to validate the bytes as a component if the layer field of the binary indicates a component.
compile/instantiate are modified to asynchronously compile/instantiate the bytes as a component if the layer field indicates a component.
Component import/export plainnames contain labels that must be transformed into an identifier for use with JS.
Fully qualified component import/export interfacenames (such as wasi:http/handler@1.0.0) are used as-is when converted to JS strings or as module specifiers.
We define PascalCase(label) and CamelCase(label) below.
label |
PascalCase |
CamelCase |
|---|---|---|
element |
Element |
element |
query-selector |
QuerySelector |
querySelector |
inner-HTML |
InnerHTML |
innerHTML |
XML-http-request |
XMLHttpRequest |
xmlHttpRequest |
URL |
URL |
url |
a1-2-3 |
A123 |
a123 |
Every plainname matches exactly one of the four patterns below, and no interfacename matches any of them. The algorithms in this document dispatch on these patterns and read their named captures. <label> stands for the label production.
| Pattern | Regex | Groups | Example |
|---|---|---|---|
| Plain | ^(<label>)$ |
1: name |
query-selector |
| Property | ^\[(get|set)\](<label>)$ |
1: accessor, 2: name |
[get]inner-HTML |
| Constructor | ^\[constructor\](<label>)$ |
1: resource |
[constructor]element |
| Member | ^\[(method|static)\](\[(get|set)\])?(<label>)\.(<label>)$ |
1: scope, 3: accessor, 4: resource, 5: name |
[method][set]element.inner-HTML |
plainname's are restricted by component strong uniqueness. This helps us statically avoid collisions when building high-level export types (such as guest resource classes) and using the name transformations below.
LabelOf(|name|), where |name| is a plainname, returns the label that names the definition in JS:
- If |name| matches Constructor:
- Return the
resourcecapture.
- Return the
- Return the
namecapture.
Fragments(|label|):
- Return the List of Strings produced by splitting |label| on occurrences of U+002D (-). The hyphens themselves are discarded.
Capitalize(|fragment|):
- If |fragment| is an
acronym:- Return |fragment|.
- Return |fragment| with its first character uppercased.
PascalCase(|label|):
- Let |fragments| be
Fragments(|label|). - Let |result| be the empty String.
- For each |fragment| of |fragments|:
- Set |result| to the string-concatenation of |result| and
Capitalize(|fragment|).
- Set |result| to the string-concatenation of |result| and
- Return |result|.
CamelCase(|label|):
- Let |fragments| be
Fragments(|label|). - Let |result| be |fragments|[0] with every character lowercased.
- For each |fragment| of |fragments| after the first:
- Set |result| to the string-concatenation of |result| and
Capitalize(|fragment|).
- Set |result| to the string-concatenation of |result| and
- Return |result|.
The JS name of an import or export declaration is then:
JSName(|decl|):
- If |decl| has an
external-idattribute that is the Unicode string |id|:- Return |id|.
- If |decl|.Name is an
interfacename:- Return |decl|.Name.
- If |decl| is a type declaration:
- Return
PascalCase(LabelOf(|decl|.Name)).
- Return
- Return
CamelCase(LabelOf(|decl|.Name)).
Components and JS maintain separate type/value systems, so any value crossing the boundary needs a defined translation in both directions.
This section specifies that translation as two abstract operations:
ToJSValue- convert a component value to a JS value.ToComponentValue- convert a JS value to a component value of a given type.
Roundtripping from ToJSValue back through ToComponentValue is designed to be strictly the identity function with the following exceptions:
- A
mapwith duplicate keys keeps only the last pair per key (seeToJSValueMap) - Float NaNs are canonicalized
Every object a conversion creates, including any error it throws, belongs to the component realm. This is the realm of the WebAssembly namespace the component was instantiated through with the JS-API, or the realm the ESM was instantiated in with ESM-integration.
Conversions run within the current call, a Record with the following fields:
| Field | Value |
|---|---|
| [[HostResourceTypes]] | map from abstract type key to host resource type |
| [[GuestResourceClasses]] | map from abstract type key to guest resource class |
| [[Lenders]] | an optional List of guest resource objects lent as a borrow back to the defining component |
To run within a call given |hostResourceTypes|, |guestResourceClasses| and an Abstract Closure |steps|:
- Let |previousCall| be the current call.
- Set the current call to Record { [[HostResourceTypes]]: |hostResourceTypes|, [[GuestResourceClasses]]: |guestResourceClasses|, [[Lenders]]: empty }.
- Let |result| be Completion(|steps|()).
- Set the current call to |previousCall|.
- Return ? |result|.
A trap in |steps| also restores the previous call as it unwinds.
ToJSValue(componentValue, componentValType) converts a component value to a JS value. It is infallible.
Dispatch on componentValType:
bool→ Boolean.- Integer types other than
s64/u64→ Number, an exact integer. s64/u64→ BigInt.f32/f64→ Number, including NaN and infinities.char→ String containing exactly the one Unicode scalar value.string→ String (well formed).list<Scalar>→ Ascalar typed array classover a fresh ArrayBuffer holding the scalars.list<T>→ToJSValueList(the elements, T).list<T, N>→ aslist<T>;lengthisN.tuple<T0, T1, ...>→ aslist, with elementiconverted asT_i.record { f: T, ... }→ToJSValueRecord(|componentValue|, the fields).flags "L"+→ToJSValueFlags(|componentValue|, the labels).enum "L"+→ String, the label verbatim.option<T>not nested within anotheroption→ undefined fornone, elseToJSValue(the payload, T).variant, and nestedoption, andresultoutside return position →ToJSValueVariant(|componentValue|, the cases). In return position aresultis unwrapped instead, into a return value or a thrownComponentError(see Read the imports and Create the exports object).map<K, V>→ToJSValueMap(|componentValue|, K, V).own<R>/borrow<R>→ See Resource types.future<T>→ a Promise (TODO).stream<T>→ anAsyncIterator(TODO).error-context→ TODO.
The scalar typed array class is given by:
| Component type | JS class |
|---|---|
s8 |
Int8Array |
u8 |
Uint8Array |
s16 |
Int16Array |
u16 |
Uint16Array |
s32 |
Int32Array |
u32 |
Uint32Array |
f32 |
Float32Array |
f64 |
Float64Array |
s64 |
BigInt64Array |
u64 |
BigUint64Array |
ToJSValueList(values, T):
- Let |n| be the number of |values|.
- Let |array| be
ArrayCreate(|n|). - For each i in [0, |n|):
- Perform
CreateDataPropertyOrThrow(|array|,ToString(𝔽(i)),ToJSValue(|values|[i], T)).
- Perform
- Return |array|.
ToJSValueRecord(value, fields):
- Let |object| be
OrdinaryObjectCreate(null). - For each field
f: Tof |fields|, in declaration order:- Perform
CreateDataPropertyOrThrow(|object|,CamelCase(f),ToJSValue(|value|'sf, T)).
- Perform
- Return |object|.
ToJSValueFlags(value, labels):
- Let |object| be
OrdinaryObjectCreate(null). - For each label
Lof |labels|:- Perform
CreateDataPropertyOrThrow(|object|,CamelCase(L), |value|'sLbit as a Boolean).
- Perform
- Return |object|.
ToJSValueVariant(value, cases):
- Let |object| be
OrdinaryObjectCreate(null). - Perform
CreateDataPropertyOrThrow(|object|, "kind",CaseLabelOf(|value|, |cases|)). - If that case has a payload of type T:
- Perform
CreateDataPropertyOrThrow(|object|, "value",ToJSValue(PayloadOf(|value|), T)).
- Perform
- Return |object|.
This operation is used for variant, and also cases in the above table where we can't specialize the behavior of option and result.
ToJSValueMap(value, K, V):
- Let |map| be a new ordinary
Mapobject with an empty [[MapData]] and the component realm's%Map.prototype%. - For each pair (k, v) of |value|, in order:
- Let |key| be
ToJSValue(k, K). - Let |mapValue| be
ToJSValue(v, V). - If [[MapData]] has an entry whose key is
SameValueZeroto |key|:- Set that entry's value to |mapValue|.
- Else:
- Append an entry (|key|, |mapValue|) to [[MapData]].
- Let |key| be
- Return |map|.
A map<K, V> is a specialization of list<tuple<K, V>> where the last pair for a key defines its value. So [(a,1),(a,2)] round-trips from a component value to JS and back as [(a,2)].
ToComponentValue(jsValue, targetComponentType) converts a JS value to a component value. It may throw if the JS value doesn't match the component value type.
A component value is a specification device. An implementation lowers the JS value straight into the component's memory and handle tables, so the steps below are interleaved with the canonical ABI's lowering. A final specification would need to be more precise on the ordering of observable actions.
Dispatch on targetComponentType:
bool→ToBoolean(|jsValue|).- Integer types → ?
ToComponentValueInteger(|jsValue|, the type). - Float types → ?
ToComponentValueFloat(|jsValue|, the type). char→ ?ToString(|jsValue|); it must consist of exactly one Unicode scalar value, else throw aTypeError. A lone surrogate is not a scalar value and is therefore aTypeError.string→ ?ToString(|jsValue|), then replace each unpaired surrogate with U+FFFD (matching WebIDLUSVString).list<Scalar>→ ?ToComponentValueScalarList(|scalar|, |jsValue|).list<T>→ ?ToComponentValueList(|jsValue|, T,none).list<T, N>→ ?ToComponentValueList(|jsValue|, T, N).tuple<Types...>→ ?ToComponentValueTuple(|jsValue|, Types...)record { f: T, ... }→ ?ToComponentValueRecord(|jsValue|, the fields).flags "L"+→ ?ToComponentValueFlags(|jsValue|, the labels).enum→ ?ToString(|jsValue|) must be one of the labels, else throw aTypeError.option<T>not nested within anotheroption→ null and undefined both givenone; anything else givessome(ToComponentValue(jsValue, T)).variant, and nestedoption, andresultoutside return position → ?ToComponentValueVariant(|jsValue|, the cases). In return position aresultis unwrapped instead: a JS return value becomesresult.ok, and a thrown exception becomesresult.error(see Read the imports and Create the exports object).map<K, V>→ ?ToComponentValueMap(|jsValue|, K, V).own<R>/borrow<R>→ See Resource types.future<T>→ TODO.stream<T>→ TODO.error-context→ TODO.
ToComponentValueInteger(jsValue, t):
- Return the result of the matching operation below, applied to |jsValue|:
s8→ToInt8u8→ToUint8s16→ToInt16u16→ToUint16s32→ToInt32u32→ToUint32s64→ToBigInt64u64→ToBigUint64
Out-of-range values wrap and NaN and infinities become 0, matching the core JS API's ToWebAssemblyValue. The 64-bit types require a BigInt, so a Number throws a TypeError.
ToComponentValueFloat(jsValue, t):
- Let |num| be ?
ToNumber(|jsValue|). - If |t| is
f32:- Set |num| to |num| rounded to the nearest f32 value (ties to even).
- Return |num|.
NaN and infinities are accepted (matching WebIDL unrestricted float/unrestricted double).
ToComponentValueScalarList(scalar, jsValue):
- If |jsValue| has a [[TypedArrayName]] internal slot whose value is the
scalar typed array classfor |scalar|:- If |jsValue|'s underlying buffer is detached or |jsValue| is out of bounds:
- Throw a
TypeError.
- Throw a
- Return one |scalar| per element of |jsValue|, in order.
- If |jsValue|'s underlying buffer is detached or |jsValue| is out of bounds:
- Return
ToComponentValueList(|jsValue|, |scalar|,none).
A typed array of the matching class is copied directly, since that is what ToJSValue produces. Anything else goes through the iterable path, so other typed arrays and plain Arrays behave like they do in the new TypedArray(iterable) constructor.
IterableToValues(jsValue):
- If |jsValue| is not an Object:
- Return not-iterable.
- Let |method| be ?
GetMethod(|jsValue|,%Symbol.iterator%). - If |method| is undefined:
- Return not-iterable.
- Return ?
IteratorToList(?GetIteratorFromMethod(|jsValue|, |method|)).
%Symbol.iterator% is looked up once, and the iterable is consumed before any element is converted, so that the canonical ABI has the length before calling realloc and converting elements.
ToComponentValueList(jsValue, T, N):
- Let |values| be ?
IterableToValues(|jsValue|). - If |values| is not-iterable:
- Throw a
TypeError.
- Throw a
- Let |valuesLength| be the length of |values|.
- If |N| is not
none:- Let |listLength| be |N|.
- Else:
- Let |listLength| be |valuesLength|.
- Let |list| be an empty component list with length |listLength| of type
T. - For |i| in 0..|listLength|:
- If |i| >= |valuesLength|:
- Let |value| be
undefined.
- Let |value| be
- Else:
- Let |value| be |values|[|i|].
- Set |list|[|i|] to ?
ToComponentValue(|value|,T).
- If |i| >= |valuesLength|:
- Return |list|.
For fixed-length lists, any missing values from the iterable are filled in with undefined.
ToComponentValueTuple(jsValue, Types...):
- Let |values| be ?
IterableToValues(|jsValue|). - If |values| is not-iterable:
- Throw a
TypeError.
- Throw a
- Let |valuesLength| be the length of |values|.
- Let |listLength| be the length of |Types|.
- Let |list| be an empty component tuple with element types |Types|.
- For |i| in 0..|listLength|:
- If |i| >= |valuesLength|:
- Let |value| be
undefined.
- Let |value| be
- Else:
- Let |value| be |values|[|i|].
- Set |list|[|i|] to ?
ToComponentValue(|value|, |Types|[|i|]).
- If |i| >= |valuesLength|:
- Return |list|.
A tuple is treated like a fixed-length list, except the destination type for conversion changes based on the element index.
ToComponentValueRecord(jsValue, fields):
- If |jsValue| is not an Object:
- Throw a
TypeError.
- Throw a
- Let |record| be a new component record value with one field per |fields|.
- For each field
f: Tof |fields|, in declaration order:- Let |m| be ?
Get(|jsValue|,CamelCase(f)). - Set |record|'s
ffield to ?ToComponentValue(|m|, T).
- Let |m| be ?
- Return |record|.
ToComponentValueFlags(jsValue, labels):
- If |jsValue| is not an Object:
- Throw a
TypeError.
- Throw a
- Let |flags| be a new component flags value with every bit initially false.
- For each label
Lof |labels|:- Set |flags|'s
Lbit toToBoolean(?Get(|jsValue|,CamelCase(L))).
- Set |flags|'s
- Return |flags|.
An absent property is therefore false, matching a boolean dictionary member defaulted to false.
ToComponentValueVariant(jsValue, cases):
- If |jsValue| is not an Object:
- Throw a
TypeError.
- Throw a
- Let |kind| be ?
ToString(?Get(|jsValue|, "kind")). - If there is no case of |cases| whose label
LhasLequal to |kind|:- Throw a
TypeError.
- Throw a
- Let |case| be that case.
- If |case| has a payload type T:
- Let |payload| be ?
ToComponentValue(?Get(|jsValue|, "value"), T). - Return a variant value of |case| whose payload is |payload|.
- Let |payload| be ?
- Return a variant value of |case| with no payload.
This operation is used for variant, and also cases in the above table where we can't specialize the behavior of option and result.
ToComponentValueMap(jsValue, K, V):
- If |jsValue| is not an Object:
- Throw a
TypeError.
- Throw a
- Let |map| be a new empty component map value.
- Let |values| be ?
IterableToValues(|jsValue|). - If |values| is a List:
- For each |v| of |values|:
- Append ?
ToComponentValue(|v|,tuple<K, V>) to |map|.
- Append ?
- Return |map|.
- For each |v| of |values|:
- If K is not
string:- Throw a
TypeError.
- Throw a
- Let |keys| be ? |jsValue|.[OwnPropertyKeys].
- For each |key| of |keys|:
- Let |desc| be ? |jsValue|.[GetOwnProperty].
- If |desc| is not undefined and |desc|.[[Enumerable]] is true:
- Let |typedKey| be ?
ToComponentValue(|key|, K). - Let |value| be ?
Get(|jsValue|, |key|). - Let |typedValue| be ?
ToComponentValue(|value|, V). - Append (|typedKey|, |typedValue|) to |map|.
- Let |typedKey| be ?
- Return |map|.
If the value is not iterable, we fall back to converting the object the way WebIDL's record<USVString, V> would, for compatibility.
A component resource type can be defined in a component (i.e. a guest resource), or else as an imported abstract type (i.e. a host resource).
The component JS-API defines:
- How a JS value satisfies a resource type import.
- A spec representation of host resource types and values.
- A JS representation of guest resource types and values.
We sketch two operations here that will be formalized more fully in the embedding interface.
To create a resource type for host given a host function |destructor|:
- Return a fresh component resource type whose representation is host-defined and whose destructor is |destructor|.
To drop a guest resource given a guest resource class |class| and a guest rep |rep| owned by the host:
- Let |resourceType| be |class|.[[ResourceType]].
- Let |instance| be |class|.[[Instance]].
- If |instance|.[[Store]].is_locked_down():
- Perform ?
trapgiven |instance|.
- Perform ?
- Perform the effect of
canon resource.dropon an owning handle holding |resourceType| and |rep|, invoking |resourceType|'s destructor. There is no handle table entry to remove, because the host was holding the rep. - If that traps:
- Perform ?
trapgiven |instance|.
- Perform ?
Imported and exported resource types are either abstract or transparently equivalent to a previous abstract import or export.
(type (component
(import "r1" (type $r1 (sub resource)))
(import "r2" (type (eq $r1)))
(import "r3" (type (sub resource)))
(export "r4" (type $r4 (sub resource)))
(export "r5" (type (eq $r4)))
(export "r6" (type (sub resource)))
(export "r7" (type (eq $r3)))
))
r1, r3, r4, r6 are the abstract types of this component type, while r2, r5, and r7 are transparently equal to one of the abstract types.
Host/guest resource types below are created only for abstract types, and stored in maps on the instance record. The map is keyed by an abstract type key, which is an import/export declaration for an abstract type.
A type import or export declares a resource type if following (eq R) reaches a (sub resource). An abstract type key can be found for any such declaration by following (eq R) until you reach that (sub resource).
Type declarations that do not declare a resource type, such as an exported record, exist only to satisfy external visibility and have no JS representation. The JS-API skips them: a type import is not read from the imports object and a type export is left off the exports object.
A host resource type is what the JS-API creates to satisfy a resource type import. It is a Record with the following fields:
| Field | Value |
|---|---|
| [[ComponentResourceType]] | the component resource type produced by create a resource type for host |
| [[ConstructorObject]] | the JS constructor that satisfied the import |
A host resource value is the rep of a host resource type. It too is a Record:
| Field | Value |
|---|---|
| [[Type]] | the host resource type this is a rep of |
| [[JSValue]] | the JS value, held strongly |
A host resource value just holds a strong reference to the underlying value. %Symbol.dispose% is captured from the constructor's prototype upon instantiation and is invoked when the resource is dropped. Dropping a resource is infallible, so if the destructor fails this results in a trap and lockdown.
One host resource type is created per imported abstract type. Two abstract type imports satisfied by the same JS constructor become distinct component resource types, and a handle for one cannot be passed where the other is expected.
A map from imported abstract type to host resource type is built by read the imports object and stored on the instance record.
A resource type import is satisfied by a constructor. Each time a JS value needs to be converted to a value of that resource type, it is brand checked against the constructor.
To brand check given a JS value |jsValue| and an Object |constructor|:
- If |constructor| is a WebIDL interface object:
- Return true if and only if |jsValue| is a platform object that implements the interface |constructor| is the interface object of.
- Return ?
InstanceofOperator(|jsValue|, |constructor|).
Which case applies is fixed for the lifetime of |constructor|.
The first case is a real brand check. The instanceof fallback only inspects the prototype chain, so a value that was never created by |constructor| can pass it. In the future we may add a way for JS to supply a custom brand check through a Symbol based protocol.
A guest resource class never reaches a brand check, because importing one is a LinkError.
For a resource type R whose abstract type is one of the component's type imports:
ToJSValue(rep, own<R> | borrow<R>):- Let |abstractTypeKey| be the abstract type key of |R|.
- Let |hostType| be the current call's [[HostResourceTypes]][|abstractTypeKey|].
- Assert: |rep| is a host resource value whose [[Type]] is |hostType|.
- Return |rep|.[[JSValue]].
ToComponentValue(jsValue, own<R> | borrow<R>):- Let |abstractTypeKey| be the abstract type key of |R|.
- Let |hostType| be the current call's [[HostResourceTypes]][|abstractTypeKey|].
- Let |matches| be ?
brand checkgiven |jsValue| and |hostType|.[[ConstructorObject]]. - If |matches| is false:
- Throw a
TypeError.
- Throw a
- Return a host resource value whose [[Type]] is |hostType| and whose [[JSValue]] is |jsValue|.
Converting the same JS value to a host resource type yields fresh handle indices. There is no canonicalization of indices.
A component's type may export a resource type that is transparently equal to one of its imported resource types (see abstract types). This currently throws a LinkError at instantiation, but may be relaxed in the future.
An exported resource type that is only privately a re-export of an imported type, i.e. the component's type declares it as a fresh abstract export, will wrap the original host resource type in a new guest resource class. This keeps callers from observing whether an exported resource type is a re-export or defined in the component.
An exported guest resource type may be imported by a separate ComponentInstance through the JS-API. As explained in component store, there is no direct component model linking between top-level instances through the JS-API. However, we do want to ensure that incidental linking of components through the JS-API works well, and there are tricky questions around handling own and borrow. So we temporarily throw a LinkError in this case.
A unique JS guest resource class is created for each exported abstract type. A map from abstract type key to guest resource class is stored on the instance record.
A guest resource class is a built-in function object with the following slots:
- [[ResourceType]] - the guest resource type.
- [[ConstructorFunc]] - the component function that implements
new, or empty. - [[Instance]] - the instance record the class belongs to.
To create a guest resource class given an instance record |instance|, a list of export declarations |exportDecls|, resource type |resourceType|, String |name| and an integer |arity|:
- Let |prototype| be
OrdinaryObjectCreate(%Object.prototype%). - Let |constructor| be a built-in function object with name |name| and length |arity|.
- Set |constructor|.[[ResourceType]] to |resourceType|.
- Set |constructor|.[[ConstructorFunc]] to empty.
- Set |constructor|.[[Instance]] to |instance|.
- Set |constructor|'s [[Call]] behaviour to throw a
TypeError. - Set |constructor|'s [[Construct]] behaviour, given JS arguments |args| and |newTarget|, to perform:
- If |constructor|.[[ConstructorFunc]] is empty:
- Throw a
TypeError.
- Throw a
- Let |proto| be ?
Get(|newTarget|, "prototype"). - If
Type(|proto|) is not Object:- Set |proto| to |prototype|.
- Let |rep| be ?
run within a callgiven |instance|.[[HostResourceTypes]], |instance|.[[GuestResourceClasses]], and the following steps:- Return ?
invoke a component functiongiven |instance|, |constructor|.[[ConstructorFunc]], false, undefined and |args|.
- Return ?
- Return
create an own guest resource objectgiven |constructor|, |rep| and |proto|.
- If |constructor|.[[ConstructorFunc]] is empty:
- Let |disposeFunc| be a built-in function object with name "[Symbol.dispose]" and length 0 that performs
dispose a guest resource objectgiven its this value. - Perform
DefinePropertyOrThrow(|prototype|,%Symbol.dispose%, PropertyDescriptor { [[Value]]: |disposeFunc|, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }). - Perform
DefinePropertyOrThrow(|prototype|,%Symbol.toStringTag%, PropertyDescriptor { [[Value]]: |name|, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }). - Perform
DefinePropertyOrThrow(|prototype|, "constructor", PropertyDescriptor { [[Value]]: |constructor|, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }). - Perform
DefinePropertyOrThrow(|constructor|, "prototype", PropertyDescriptor { [[Value]]: |prototype|, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }). - Let |members| be the function exports of |exportDecls| whose names match Constructor or Member with a
resourcecapture naming |resourceType|. - If some |c| of |members| matches Constructor:
- Assert: there is only one by validation rules.
- Set |constructor|.[[ConstructorFunc]] to |c|.Func.
- For each |e| of |members| matching Member, in declaration order:
- If
JSName(|e|) is inreserved class members:- Continue.
- If |e|.Name's
scopecapture is "method":- Let |target| be |prototype|.
- Let |takesSelf| be true.
- Else:
- Assert: |e|.Name's
scopecapture is "static". - Let |target| be |constructor|.
- Let |takesSelf| be false.
- Assert: |e|.Name's
- If |e|.Name has an
accessorcapture:- Perform
define an accessor for a component functiongiven |instance|, |target|, |e| and false.
- Perform
- Else:
- Let |func| be
create a JS function for a component functiongiven |instance|, |e|.Func,JSName(|e|) and |takesSelf|. - Perform
DefinePropertyOrThrow(|target|,JSName(|e|), PropertyDescriptor { [[Value]]: |func|, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
- Let |func| be
- If
- Return |constructor|.
The following names are reserved class members:
- "proto"
- "constructor"
- "prototype"
- "arguments"
- "caller"
- "name"
- "length"
Defining these on the constructor or prototype may unexpectedly change JS class semantics. They are exported through create the exports object in a generic way alongside all the other exports.
Member exports with an accessor capture become the two halves of one accessor property, on prototype when scope is "method" and on the class itself when it is "static". Validation requires a [set] to be preceded in the same scope by the [get] it pairs with, so the getter is always defined first and the setter only fills in the accessor's [[Set]] field.
A guest resource object has the following slots:
- [[ResourceClass]] - the resource class this object is an instance of.
- [[Rep]] - the rep, or empty once the handle has been detached or dropped.
- [[LendCount]] - how many outstanding
borrows were lent from this object.
It holds the same state a handle table entry does, plus the class it belongs to. A guest resource object always owns a rep.
To create an own guest resource object given a resource class |class|, |rep|, and an optional Object |proto|:
- If |proto| is not present:
- Let |proto| be the value of |class|'s
"prototype"property.
- Let |proto| be the value of |class|'s
- Let |object| be
OrdinaryObjectCreate(|proto|, « [[ResourceClass]], [[Rep]], [[LendCount]] »). - Set |object|.[[ResourceClass]] to |class|.
- Set |object|.[[Rep]] to |rep|.
- Set |object|.[[LendCount]] to 0.
- Register |object| in the guest resource
FinalizationRegistrywith held value a record { [[ResourceClass]]: |class|, [[Rep]]: |rep| } and unregister token |object|. - Return |object|.
To detach a guest resource object given resource object |resourceObject|:
- Assert: |resourceObject|.[[Rep]] is not empty and |resourceObject|.[[LendCount]] is 0.
- Set |resourceObject|.[[Rep]] to empty.
- Unregister |resourceObject| from the guest resource
FinalizationRegistry.
To dispose a guest resource object given |resourceObject|:
- If |resourceObject|.[[Rep]] is empty:
- Assert |resourceObject|.[[LendCount]] is 0.
- Return undefined.
- If |resourceObject|.[[LendCount]] is not 0:
- Throw a
TypeError.
- Throw a
- Let |class| be |resourceObject|.[[ResourceClass]].
- Let |rep| be |resourceObject|.[[Rep]].
- Perform
detach a guest resource objectwith |resourceObject|. - Perform
drop a guest resourcegiven |class| and |rep|. - Return undefined.
The [[LendCount]] check can only fail on the %Symbol.dispose% path, because a lent object is kept alive by the [[Lenders]] of the call it was lent to.
To finalize a guest resource object given |resourceClass| and |resourceRep|:
- If |resourceClass|.[[Instance]].[[Store]].is_locked_down():
- Return.
- Perform ?
drop a guest resourcegiven |resourceClass| and |resourceRep|.
The current call lender list should keep all guest resource object's alive such that they cannot be finalized.
Each guest resource object lowered as a borrow while converting the arguments of a JS-to-component call has its [[LendCount]] incremented and is appended to the current call's [[Lenders]], which protects it from being disposed while lent. When the call resolves (and so the callee has dropped all its borrows) invoke a component function decrements every [[LendCount]] in the list.
For a resource type R whose abstract type is one of the component's type exports:
ToJSValue(rep, own<R>):- Let |abstractTypeKey| be the abstract type key of |R|.
- Let |class| be the current call's [[GuestResourceClasses]][|abstractTypeKey|].
- Return
create an own guest resource objectgiven |class| and |rep|.
ToJSValue(rep, borrow<R>):- Assert: unreachable.
- This can only happen if an exported function returns a borrow, which is not allowed.
ToComponentValue(jsValue, own<R>):- Let |abstractTypeKey| be the abstract type key of |R|.
- Let |class| be the current call's [[GuestResourceClasses]][|abstractTypeKey|].
- If |jsValue| does not have a [[ResourceClass]] internal slot, or |jsValue|.[[ResourceClass]] is not |class|:
- Throw a
TypeError.
- Throw a
- If |jsValue|.[[Rep]] is empty, or |jsValue|.[[LendCount]] is not 0:
- Throw a
TypeError.
- Throw a
- Let |rep| be |jsValue|.[[Rep]].
- Perform
detach a guest resource objectwith |jsValue|. - Return |rep|.
ToComponentValue(jsValue, borrow<R>):- Let |abstractTypeKey| be the abstract type key of |R|.
- Let |class| be the current call's [[GuestResourceClasses]][|abstractTypeKey|].
- If |jsValue| does not have a [[ResourceClass]] internal slot, or |jsValue|.[[ResourceClass]] is not |class|:
- Throw a
TypeError.
- Throw a
- If |jsValue|.[[Rep]] is empty:
- Throw a
TypeError.
- Throw a
- Let |lenders| be the current call's [[Lenders]].
- Assert: |lenders| is not empty.
- Increment |jsValue|.[[LendCount]].
- Append |jsValue| to |lenders|.
- Return |jsValue|.[[Rep]].
There is an unexposed "guest resource FinalizationRegistry" created per-Realm of the WebAssembly namespace object. The callback for it, given a held value |record|, performs finalize a guest resource object given |record|.[[ResourceClass]] and |record|.[[Rep]].
The held value is a record of the objects's class and rep rather than the object itself, because registering an object with itself as the held value would keep it alive forever. The record never goes stale, because the object is unregistered whenever its [[Rep]] is taken.
To instantiate a component given |component|, a list of component definitions |imports|, and |hostResourceTypes|:
- If the type of any function import or export of |component|, including those nested in instance imports and exports, is
async:- Throw a
WebAssembly.LinkError.
- Throw a
- If any type export of |component|'s type, including those nested in instance exports, declares a resource type whose abstract type key is an import declaration:
- Throw a
WebAssembly.LinkError.
- Throw a
- Let |store| be a new component store.
- Let |componentInstance| be the result of instantiating |component| with |imports| in |store|.
- If instantiation traps:
- Throw a
WebAssembly.RuntimeError.
- Throw a
- Let |instance| be a new instance record { [[Store]]: |store|, [[ComponentInstance]]: |componentInstance|, [[HostResourceTypes]]: |hostResourceTypes|, [[GuestResourceClasses]]: a new empty map }.
- Perform
create guest resource classesgiven |instance| and |componentInstance|.Exports. - Let |exportsObject| be ?
create the exports objectgiven |instance| and |componentInstance|.Exports. - Return a Record { [[Instance]]: |instance|, [[Exports]]: |exportsObject| }.
We temporarily reject async function imports/exports until they are specified, and re-exported host resource types until their semantics are settled.
To instantiate a component from an imports object given |component|, |importsObject|, and |enabledBuiltins|:
- Let |imports| and |hostResourceTypes| be ?
read the imports objectgiven |component|, |importsObject|, and |enabledBuiltins|. - Return ?
instantiate a componentgiven |component|, |imports|, and |hostResourceTypes|.
The top-level read the imports object algorithm walks the component's imports and resolves each to a JS value via property lookups on the |importsObject|, mirroring the core JS-API's algorithm of the same name.
The resolved JS values are then handed to the per-sort algorithms (read the function import, read the type import, and the rest) to produce the component definitions used during instantiation.
While walking, the algorithm recognizes the pattern of a resource type import accompanied by Constructor and Member function imports naming it. A resource type import is read first and looks for a constructor (see resource types). Those function imports then read from the constructor and its prototype directly. This allows the common case of importing a class to be satisfied by just passing the constructor.
Passing an exported component definition to a component import via the JS-API/ESM-integration is treated as if the import were a JS value. There is no "direct linking" that bypasses going through JS semantics. See component store for more details.
To read the imports object given |component|, |importsObject|, and |enabledBuiltins|:
- Let |hostResourceTypes| be an empty map from abstract type key to host resource type record.
- If |component| has no imports:
- Return an empty list and |hostResourceTypes|.
- Let |imports| be ?
read a scope of importsgiven |component|.Imports, |importsObject|, |enabledBuiltins|, and |hostResourceTypes|. - Return |imports| and |hostResourceTypes|.
To read a scope of imports given a list of import declarations |importDecls|, |importsObject|, |enabledBuiltins|, and |hostResourceTypes|:
- Let |definitions| be a new empty list.
- For each |importDecl| of |importDecls|, in declaration order:
- If |importDecl|.Sort is type:
- If |importDecl| does not declare a resource type:
- Append the type |importDecl| declares to |definitions|.
- Continue.
- Let |abstractTypeKey| be the abstract type key of |importDecl|.
- If |hostResourceTypes|[|abstractTypeKey|] exists:
- Append |hostResourceTypes|[|abstractTypeKey|].[[ComponentResourceType]] to |definitions|.
- Continue.
- If |importDecl| does not declare a resource type:
- Let |name| be
JSName(|importDecl|). - Let |builtin| be ?
resolve a builtin specifiergiven |name| and |enabledBuiltins|. - If |builtin| is not empty:
- Let |importValue| be |builtin|.
- Else:
- If |importDecl|.Sort is func and |importDecl|.Name matches Constructor or Member:
- Let |abstractTypeKey| be the abstract type key of the type import named by the
resourcecapture. - Assert: |hostResourceTypes|[|abstractTypeKey|] exists. (Validation requires that declaration to precede this one in the same scope)
- Let |constructorFunction| be |hostResourceTypes|[|abstractTypeKey|].[[ConstructorObject]].
- If |importDecl|.Name matches Constructor:
- Let |importValue| be |constructorFunction|.
- Else:
-
If the
scopecapture is "static":- Let |lookupTarget| be |constructorFunction|.
-
Else:
- Let |lookupTarget| be ?
Get(|constructorFunction|, "prototype"). - If
Type(|lookupTarget|) is not Object:- Throw a
WebAssembly.LinkError.
- Throw a
- Let |lookupTarget| be ?
-
If |importDecl|.Name has an
accessorcapture:- Let |importValue| be ?
find an accessorgiven |lookupTarget|, |name| and theaccessorcapture.
- Let |importValue| be ?
-
Else:
- Let |importValue| be ?
Get(|lookupTarget|, |name|).
- Let |importValue| be ?
-
- Let |abstractTypeKey| be the abstract type key of the type import named by the
- Else:
-
If
Type(|importsObject|) is not Object:- Throw a
TypeError.
- Throw a
-
If |importDecl|.Sort is func and |importDecl|.Name matches Property:
- Let |importValue| be ?
find an accessorgiven |importsObject|, |name| and theaccessorcapture.
- Let |importValue| be ?
-
Else:
- Let |importValue| be ?
Get(|importsObject|, |name|).
- Let |importValue| be ?
-
- If |importDecl|.Sort is func and |importDecl|.Name matches Constructor or Member:
- Let |resolved| be ?
read an importgiven |importDecl|, |importValue| and |hostResourceTypes|. - Append |resolved| to |definitions|.
- If |importDecl|.Sort is type:
- Return |definitions|.
To read an import given |importDecl|, |importValue| and |hostResourceTypes|:
- Match |importDecl|.Sort:
- core module: return ?
read the core module importgiven |importDecl|.ModuleType and |importValue|. - func: return ?
read the function importgiven |importDecl|.FuncType, |importValue|, |importDecl|.Name and |hostResourceTypes|. - type: return ?
read the type importgiven |importDecl|, |importValue|, and |hostResourceTypes|. - value: return ?
read the value importgiven |importDecl|.ValType, |importValue| and |hostResourceTypes|. - instance: return ?
read the instance importgiven |importDecl|.InstanceType, |importValue| and |hostResourceTypes|. - component: return ?
read the component importgiven |importDecl|.ComponentType and |importValue|.
- core module: return ?
To read the core module import given |coreModuleType| and |importValue|:
- If |importValue| does not have a [[Module]] internal slot:
- Throw a
WebAssembly.LinkError.
- Throw a
- If the type of |importValue|.[[Module]] is not a subtype of |coreModuleType|:
- Throw a
WebAssembly.LinkError.
- Throw a
- Return |importValue|.[[Module]].
To read the component import given |componentType| and |importValue|:
- If |importValue| does not have a [[Component]] internal slot:
- Throw a
WebAssembly.LinkError.
- Throw a
- If the type of |importValue|.[[Component]] is not a subtype of |componentType|:
- Throw a
WebAssembly.LinkError.
- Throw a
- Return |importValue|.[[Component]].
To read the instance import given |instanceType|, |importValue| and |hostResourceTypes|:
- If
Type(|importValue|) is not Object:- Throw a
WebAssembly.LinkError.
- Throw a
- Let |definitions| be ?
read a scope of importsgiven |instanceType|.Exports, |importValue|, an empty set of enabled builtins, and |hostResourceTypes|. - Return a component instance whose exports are |definitions|.
To read the type import given |importDecl|, |importValue|, and |hostResourceTypes|:
- Let |abstractTypeKey| be the abstract type key of |importDecl|.
- Assert: |hostResourceTypes|[|abstractTypeKey|] does not exist. (
read a scope of importshandles transparent imports) - If
IsCallable(|importValue|) is false:- Throw a
WebAssembly.LinkError.
- Throw a
- If |importValue| has a [[ConstructorFunc]] internal slot:
- Assert: |importValue| is a guest resource class.
- Throw a
WebAssembly.LinkError.
- Let |dispose| be undefined.
- Let |prototype| be ?
Get(|importValue|, "prototype"). - If
Type(|prototype|) is Object:- Set |dispose| to ?
Get(|prototype|, %Symbol.dispose%).
- Set |dispose| to ?
- Let |hasDispose| be
IsCallable(|dispose|). - Let |destructor| be a host function that given a host resource value |self|:
- Let |selfValue| be |self|.[[JSValue]].
- Set |self|.[[JSValue]] to
undefined. - If |hasDispose|:
- Let |result| be
Call(|dispose|, |selfValue|, the empty list). - If |result| is an abrupt completion:
- Trap.
- Let |result| be
- Let |resourceType| be
create a resource type for hostgiven |destructor|. - Let |hostResourceType| be a new host resource type record whose [[ComponentResourceType]] is |resourceType| and [[ConstructorObject]] is |importValue|.
- Set |hostResourceTypes|[|abstractTypeKey|] to |hostResourceType|.
- Return |resourceType|.
%Symbol.dispose% is captured from the constructor's prototype, and called when the resource is dropped. Dropping a resource is infallible, so if it throws an exception, this becomes a trap which results in lockdown.
To find an accessor given an object |target|, a property key |key| and |kind|, which is either "get" or "set":
- Let |object| be |target|.
- Repeat, while |object| is not null:
- Let |desc| be ? |object|.[GetOwnProperty].
- If |desc| is not undefined:
- If
IsAccessorDescriptor(|desc|) is false:- Return undefined.
- If |kind| is "get", return |desc|.[[Get]].
- Return |desc|.[[Set]].
- If
- Set |object| to ? |object|.[GetPrototypeOf].
- Return undefined.
The walk stops at the first own property it finds, as an ordinary property access does. A data property that shadows an accessor further up the chain therefore resolves to undefined and becomes a LinkError.
To read the function import given |componentFuncType|, |importValue|, |importName| and |hostResourceTypes|:
- Let |isConstructor| be true if |importName| matches Constructor, and false otherwise.
- If
IsCallable(|importValue|) is false or (|isConstructor| is true andIsConstructor(|importValue|) is false):- Return a new Abstract Closure with parameters (|onStart|, |onResolve|) that traps when called.
- Let |takesSelf| be true if |importName| matches Member with
scope"method", and false otherwise. - Return
create a component function for a JS functiongiven |componentFuncType|, |importValue|, |isConstructor|, |takesSelf| and |hostResourceTypes|.
To create a component function for a JS function given |componentFuncType|, |callable|, a Boolean |isConstructor|, a Boolean |takesSelf| and |hostResourceTypes|:
- Let |paramTypes| be |componentFuncType|.Params.
- Let |resultType| be |componentFuncType|.Result.
- Let |paramOffset| be 1 if |takesSelf| is true, else 0.
- If |resultType| is a
result:- Let |okType| be its
okpayload type, or empty if it has none. - Let |errorType| be its
errorpayload type, or empty if it has none. - Let |throwing| be true.
- Let |okType| be its
- Else:
- Let |okType| be |resultType|, or empty if |componentFuncType| has no result.
- Let |throwing| be false.
- Return a new Abstract Closure with parameters (|onStart|, |onResolve|) that performs the following steps when called:
- Let |values| be |onStart|().
- Let |results| be
run within a callgiven |hostResourceTypes|, a new empty map, and a new Abstract Closure that performs the following steps when called:- Let |args| be a new empty List.
- For each i in [|paramOffset|, |values|.length):
- Append
ToJSValue(|values|[i], |paramTypes|[i]) to |args|.
- Append
- If |isConstructor| is true:
- Let |completion| be Completion(
Construct(|callable|, |args|)).
- Let |completion| be Completion(
- Else:
- If |takesSelf| is true:
- Let |thisArg| be
ToJSValue(|values|[0], |paramTypes|[0]).
- Let |thisArg| be
- Else:
- Let |thisArg| be undefined.
- Let |completion| be Completion(
Call(|callable|, |thisArg|, |args|)).
- If |takesSelf| is true:
- If |completion| is an abrupt completion:
- If |throwing| is false:
- Trap.
- If |errorType| is empty:
- Return «
result.error».
- Return «
- Let |errorValue| be
ToComponentValue(|completion|.[[Value]], |errorType|). - If that throws:
- Trap.
- Return «
result.error(|errorValue|)».
- If |throwing| is false:
- If |okType| is empty:
- If |throwing| is true:
- Return «
result.ok».
- Return «
- Return « ».
- If |throwing| is true:
- Let |okValue| be
ToComponentValue(|completion|.[[Value]], |okType|). - If that throws:
- Trap.
- If |throwing| is true:
- Return «
result.ok(|okValue|)».
- Return «
- Return « |okValue| ».
- Perform |onResolve|(|results|).
- Let |onCancel| be a new Abstract Closure with no parameters that performs nothing when called.
- Return |onCancel|.
The returned closure is a FuncInst. Since |componentFuncType| is not async, it calls |onStart| and |onResolve| synchronously, and so the caller never needs the returned OnCancel.
To read the value import given |componentValType|, |importValue| and |hostResourceTypes|:
- Return ?
run within a callgiven |hostResourceTypes|, a new empty map, and a new Abstract Closure with no parameters that captures |importValue| and |componentValType| and performs the following steps when called:- Return ?
ToComponentValue(|importValue|, |componentValType|).
- Return ?
The component JS-API can provide builtins to imports just as the core JS-API does.
Builtin imports are opt-in via the builtins field of WebAssemblyCompileOptions when used in the JS-API. ESM-integration enables all builtins by default.
This spec defines one builtin specifier:
| Builtin | Specifiers | Resolves to |
|---|---|---|
js/global |
wasm:js/global, wasm:js/global/* |
the global object |
To resolve a builtin specifier given a String |specifier| and a set of Strings |enabledBuiltins|:
- If |specifier| does not start with "wasm:":
- Return empty.
- Let |name| be the portion of |specifier| after "wasm:".
- If |name| is "js/global" or starts with "js/global/":
- If |enabledBuiltins| does not contain "js/global":
- Return empty.
- Return ?
resolve a js global builtinwith |name|.
- If |enabledBuiltins| does not contain "js/global":
- Return empty.
The normal read the imports object rules are designed so that JS classes can be imported by just providing the constructor object. wasm:js/global/* provides a fine-grained way to get access to globally exposed constructors and other functions. This reduces the amount of glue code needed in the common case.
wasm:js/global resolves to the globalThis of the component realm, and nested paths resolve to a chain of property accessors off of the global (e.g. wasm:js/global/console is globalThis.console).
To resolve a js global builtin with String |name|:
- Let |result| be the component realm's
globalThis. - If |name| is "js/global":
- Return |result|.
- Assert: |name| starts with "js/global/".
- Let |remaining| be the portion of |name| after "js/global/".
- Let |projections| be the result of splitting |remaining| on "/".
- For each |projection| of |projections|:
- Set |result| to ?
Get(|result|, |projection|).
- Set |result| to ?
- Return |result|.
TODO: Handle whitespace? TODO: Within the wasm scheme we're parsing this similar to a general URL, but no using the canonical algorithm. We don't need the general algorithm and it's a nice dependency to avoid. But are there future compatibility or extensibility reasons we should use it?
The create the exports object algorithm walks the component's exports and builds a fresh JS object whose properties are the exports.
Exported resource types become guest resource classes named JSName(|export|), and function exports matching Constructor or Member are mapped onto the class R named by their resource capture, just as in read the imports object:
- Constructor: the function becomes
R's constructor behaviour. Names are strongly-unique, so there can only be one. - Member with
scope"method": the function becomes a method namedJSName(|export|) onR.prototype. - Member with
scope"static": the function becomes a static method namedJSName(|export|) onR. - Member with an
accessorcapture: the "get" and "set" functions become the getter and setter of one accessor property namedJSName(|export|), again onR.prototypeor onR.
A Property export becomes an accessor property on the exports object itself. All other exported component definitions are given JS definitions named JSName(|export|) on the exports object.
To create guest resource classes given an instance record |instance| and a list of export declarations |exportDecls|:
- Let |guestResourceClasses| be |instance|.[[GuestResourceClasses]].
- For each |export| of |exportDecls|, in declaration order:
- If |export|.Sort is instance:
- Perform
create guest resource classesgiven |instance| and the exports of the exported instance. - Continue.
- Perform
- If |export|.Sort is not type, or |export| does not declare a resource type:
- Continue.
- Let |abstractTypeKey| be the abstract type key of |export|.
- Assert: |abstractTypeKey| is not an import declaration, by instantiation.
- If |guestResourceClasses|[|abstractTypeKey|] exists:
- Continue.
- Let |resourceType| be the component resource type |export| refers to.
- Let |arity| be the parameter count of the export of |exportDecls| whose name matches Constructor with a
resourcecapture naming |export|, or 0 if there is none. - Let |class| be
create a guest resource classgiven |instance|, |exportDecls|, |resourceType|,JSName(|export|) and |arity|. - Set |guestResourceClasses|[|abstractTypeKey|] to |class|.
- If |export|.Sort is instance:
To create the exports object given an instance record |instance| and a list of export declarations |exportDecls|:
- Let |exportsObject| be
OrdinaryObjectCreate(null). - For each |export| of |exportDecls|, in declaration order:
- If |export|.Name matches Constructor:
- Continue.
- If |export|.Name matches Member and
JSName(|export|) is not inreserved class members:- Continue.
- If |export|.Name matches Property:
- Perform
define an accessor for a component functiongiven |instance|, |exportsObject|, |export| and true. - Continue.
- Perform
- Let |key| be
JSName(|export|). - Match |export|.Sort:
- core module:
- Let |value| be a new
Modulewhose [[Module]] is |export|.Module.
- Let |value| be a new
- type:
- If |export| does not declare a resource type:
- Continue.
- Let |abstractTypeKey| be the abstract type key of |export|.
- Let |value| be |instance|.[[GuestResourceClasses]][|abstractTypeKey|].
- If |export| does not declare a resource type:
- func:
- Let |value| be
create a JS function for a component functiongiven |instance|, |export|.Func, |key| and false.
- Let |value| be
- value:
- Let |value| be
run within a callgiven |instance|.[[HostResourceTypes]], |instance|.[[GuestResourceClasses]], and a new Abstract Closure that performs the following steps when called:- Return
ToJSValue(|export|.Value, |export|.Type).
- Return
- Let |value| be
- instance:
- Let |value| be ?
create the exports objectgiven |instance| and the exports of the exported instance.
- Let |value| be ?
- component:
- Let |value| be a new
Componentwhose [[Component]] is |export|.Component.
- Let |value| be a new
- core module:
- Perform
CreateDataPropertyOrThrow(|exportsObject|, |key|, |value|).
- If |export|.Name matches Constructor:
- Perform
SetIntegrityLevel(|exportsObject|, "frozen"). - Return |exportsObject|.
TODO: We need a JSName for members that hit the reserved class members list. It needs to concatenate the resource name with the method name somehow.
To create a JS function for a component function given an instance record |instance|, |componentFunc|, |name| and |takesSelf|:
- Let |paramOffset| be 1 if |takesSelf| is true, else 0.
- If |componentFunc|.Result is a
result:- Let |okType| be its
okpayload type, or empty if it has none.
- Let |okType| be its
- Else:
- Let |okType| be |componentFunc|.Result, or empty if |componentFunc| has no result.
- Return a built-in function object with name |name| and length |componentFunc|.Params.length - |paramOffset|, whose behaviour, given a this value |thisValue| and JS arguments |args|, performs:
- Return ?
run within a callgiven |instance|.[[HostResourceTypes]], |instance|.[[GuestResourceClasses]], and a new Abstract Closure that performs the following steps when called:- Let |componentResult| be ?
invoke a component functiongiven |instance|, |componentFunc|, |takesSelf|, |thisValue| and |args|. - If |okType| is empty:
- Return undefined.
- Return
ToJSValue(|componentResult|, |okType|).
- Let |componentResult| be ?
- Return ?
To define an accessor for a component function given an instance record |instance|, an object |target|, a function export |export| and a Boolean |enumerable|:
- Let |key| be
JSName(|export|). - Let |accessor| be the
accessorcapture of |export|.Name. - Let |name| be the string-concatenation of |accessor|, " " and |key|.
- Let |takesSelf| be true if |export|.Name matches Member with
scope"method", and false otherwise. - Let |func| be
create a JS function for a component functiongiven |instance|, |export|.Func, |name| and |takesSelf|. - If |accessor| is "get":
- Perform
DefinePropertyOrThrow(|target|, |key|, PropertyDescriptor { [[Get]]: |func|, [[Set]]: undefined, [[Enumerable]]: |enumerable|, [[Configurable]]: true }).
- Perform
- Else:
- Perform
DefinePropertyOrThrow(|target|, |key|, PropertyDescriptor { [[Set]]: |func| }).
- Perform
The "set" case defines a partial descriptor, so it only replaces the [[Set]] field of the accessor property the matching [get] export already defined. The "get "/"set " prefix on the function name follows how JS names accessor functions.
To invoke a component function given an instance record |instance|, |componentFunc|, a Boolean |takesSelf|, |thisValue| and a List of JS values |args|:
- Let |paramTypes| be |componentFunc|.Params.
- Let |resultType| be |componentFunc|.Result.
- Let |formalParamsOffset| be 1 if |takesSelf| is true, else 0.
- Let |formalParamsCount| be |paramTypes|.length - |formalParamsOffset|.
- If |resultType| is a
result:- Let |okType| be its
okpayload type, or empty if it has none. - Let |errorType| be its
errorpayload type, or empty if it has none. - Let |throwing| be true.
- Let |okType| be its
- Else:
- Let |okType| be |resultType|, or empty if |componentFunc| has no result.
- Let |throwing| be false.
- If
Length(|args|) is less than |formalParamsCount|:- Let |missingFormalArgCount| be |formalParamsCount| -
Length(|args|). - Let |missingFormalArgs| be a List of
undefinedrepeated |missingFormalArgCount| times. - Set |args| to |args| concatenated with |missingFormalArgs|.
- Let |missingFormalArgCount| be |formalParamsCount| -
- If |instance|.[[Store]].is_locked_down():
- Perform ?
trapgiven |instance|.
- Perform ?
- Let |call| be the current call.
- Let |lenders| be a new empty List.
- Let |onStart| be a new Abstract Closure with no parameters that performs the following steps when called:
- Set |call|.[[Lenders]] to |lenders|.
- Once the remaining steps complete, either normally or abruptly, set |call|.[[Lenders]] to empty.
- Let |values| be a new empty List.
- If |formalParamsOffset| is 1:
- Append ?
ToComponentValue(|thisValue|, |paramTypes|[0]) to |values|.
- Append ?
- For each i in [0, |formalParamsCount|): append ?
ToComponentValue(|args|[i], |paramTypes|[i + |formalParamsOffset|]) to |values|. - Return |values|.
- Let |resolved| be false.
- Let |componentResult| be empty.
- Let |onResolve| be a new Abstract Closure with parameters (|results|) that performs the following steps when called:
- Assert: |results| is not None.
- Decrement the [[LendCount]] of every object in |lenders|.
- Set |resolved| to true.
- If |results| is not empty, set |componentResult| to |results|[0].
- Let |completion| be Completion(|instance|.[[Store]].invoke(|componentFunc|, |onStart|, |onResolve|)).
- If the call traps:
- If |resolved| is false, decrement the [[LendCount]] of every object in |lenders|.
- Perform ?
trapgiven |instance|.
- If |completion| is an abrupt completion:
- Decrement the [[LendCount]] of every object in |lenders|.
- If the call has entered the guest:
- Invoke |instance|.[[Store]].lock_down().
- Return ? |completion|.
- Assert: |resolved| is true.
- If |throwing| is true and |componentResult| is
result.error(|e|):- Throw
create a component errorfor |e| and |errorType|.
- Throw
- If |okType| is empty:
- Return empty.
- If |throwing| is true:
- Return the
result.okpayload of |componentResult|.
- Return the
- Else:
- Return |componentResult|.
|componentFunc| is not async (see instantiation), so |onStart| and |onResolve| are called by canon_lift synchronously.
To create a component error for an optional component value |e| and component type |errorType|:
- If |errorType| is empty:
- Let |payload| be undefined.
- Else:
- Let |payload| be
ToJSValue(|e|, |errorType|).
- Let |payload| be
- Return a new
ComponentErrorwhosedatais |payload| and whosemessageis implementation-defined.
ESM-integration extends to components. The module loader branches on the layer field of the binary to decide whether the bytes decode as a module or a component, so a component can be loaded anywhere a module can be today.
Each component import has a module specifier given by JSName(|decl|).
Which binding of the resolved module the component receives depends on the import's type:
| Import type | JS equivalent | Value |
|---|---|---|
| bare type, function, value | import v from "JSName(decl)" |
the default export |
| instance | import { a, b } from "JSName(decl)" |
one named import per export of the instance type whose name is an interfacename or matches Plain, named JSName of that export |
| core module, component | import source M from "JSName(decl)" |
the module source, as a Module or Component |
Reading the imports snapshots the resolved values, and so components cannot participate in cycles: a binding that is still uninitialized when the component is evaluated throws a ReferenceError. This matches how core modules work today with ESM-integration.
Each resolved value is handed to read an import and the resulting definitions are passed to instantiate a component.
A component's exports become the bindings of its module namespace object. There is one binding per JSName(|export|), holding what create the exports object puts under that name, and no default binding. Exports matching Property have no binding, since a binding cannot be an accessor.
- How to dynamically pass a union value? Statically passing a single case of the union works, but not dynamic choice.
- How to import multiple overloads of a function? Can we just use
external-id? - How to support class inheritance and casting?
- Do we support a reference equality protocol?
ToJSValuecreates a fresh resource object per lift, so twoborrows of one component-defined resource are two JS objects that do not compare equal. Reps are opaque and reusable after a drop, so an identity map would need careful invalidation. - Do we let a JS constructor supply its own brand check?
- Should a
[get]/[set]import fall back to aGet/Seton the target when the property is not an accessor? That would let data properties,Proxytraps and module namespace bindings satisfy a property import. - How does a component feature test an import?
- How does a component pass one of its own functions to a JS callback, e.g.
add-event-listener? - Async function types, top-level await, and async start functions.