External binding packages give you typed functions, constants and opaque types from code written outside Moth. The HTML builder supports annotated JavaScript imports. WIT component imports remain deferred.
Annotated JavaScript
You can import .js files that use @moth.opaque, @moth.sig and @moth.const annotations. The annotations tell the compiler what Moth names and exact types to expose.
@vendor/drawing.js as drawing
JavaScript export names are runtime details. Moth names come from annotations, not from the JavaScript export.
Write each annotation directly above the declaration it describes, and make sure that declaration is exported. An annotation always belongs to the next declaration in the file. If that declaration lacks export, the compiler asks you to add it rather than looking further down the file.
What JavaScript can export
The builder accepts export function name(...) { ... } and block-bodied arrow exports. @moth.sig annotations expose free functions.
A signature may use -> ! when the import never returns. That is a whole contract and cannot mix with ordinary return slots.
Numeric signatures accept I32, I64, U32, U64, F32 and F64. @moth.const exposes a flat U32 name from one unsigned decimal literal:
export const TRIANGLES = 4;
The compiler reads that literal without executing JavaScript. It rejects an out-of-range value rather than wrapping it. This subset doesn't include every Moth numeric type.
What JavaScript can't export
The builder rejects default exports, re-exports, CommonJS, classes, callbacks, async functions, property accessors and multi-success returns. These don't map to Moth's type system.
Values cross by value
Moth values that cross into JavaScript go by value. JavaScript can't hold references into Moth storage. Opaque handles represent foreign identities, not Moth references.
WIT is deferred
Future Wasm component imports will use a value-only WIT profile. WIT resources, callbacks, async and streams remain deferred. See External binding contracts advanced for the full contract and deferred surface.
External binding packages expose typed functions, constants and opaque types implemented outside Moth. The HTML builder currently supports annotated project-local JavaScript files; WIT component imports are deferred.
Annotated JavaScript dependencies
The HTML builder supports annotated single-file .js dependency clauses through @moth.opaque, @moth.sig and @moth.const. @moth.sig declares each exposed function and @moth.const declares each literal-backed constant. @moth.opaque is required only when signatures use foreign opaque handle types. A function-only module may use @moth.sig without @moth.opaque and a constant-only module may use @moth.const on its own. JavaScript export names are runtime implementation details. Moth names come from annotations.
@vendor/drawing.js as drawing
Annotated JavaScript example
export const emphasize = (text) => {
return `**${text}**`;
};
export function joinLabel(prefix, body) {
return `${prefix}: ${body}`;
}
The Moth dependency clause uses the annotation names, not the JavaScript export names:
@vendor/drawing.js emphasize, join_label
Supported JavaScript export forms
export function name(...) { ... }- block-bodied arrow exports
- one
export const NAME = 4; declarator with an unsigned decimal literal for @moth.const
@moth.sig annotations expose free functions and @moth.const annotations expose literal constants. this receiver-style signatures are rejected during registration. Runtime imports from builder-registered modules must be named static imports.
Placing annotations
Each annotation describes the declaration that comes right after its comment block. Only whitespace and other comments may sit between the two. The compiler never skips ahead looking for a declaration that fits, so moving code around can't quietly attach an annotation to the wrong function.
That nearest declaration must be exported. In the following file, the annotation belongs to emphasize, which lacks export. The compiler reports the missing keyword and the line to add it on, rather than binding the annotation to some later export:
function emphasize(text) {
return `**${text}**`;
}
An annotation is also an error when no supported declaration follows it, for example when a statement, an unsupported export or the end of the file comes first.
Exact signature subset
- parameters are positional and typed
- mutable parameters use
name ~Type - signatures have zero or one success return, or the whole Never contract
-> ! - an optional final
Error! channel is allowed on ordinary signatures Error! must be final-> ! is a whole contract and cannot mix with success, optional or error slots- mixed forms such as
-> String, !, -> Error!, ! or -> !! are rejected - numeric slots spell
I32, I64, U32, U64, F32 or F64, alongside Bool, String, Char and opaque handle types - annotations do not support
I8, I16, U8, U16, F16, Byte or Dec - generic signatures are rejected
- option and collection types are rejected
- callbacks are rejected
- multi-success returns are rejected
this receiver-shaped signatures are rejected for external package registration- opaque types must be declared through
@moth.opaque before use where required - JavaScript export names are runtime implementation details
- Moth names come from annotations
Calls to mutable parameters follow ordinary access rules. Pass an existing mutable place as ~place and pass a fresh value or legal copy without ~. External binding calls remain positional-only.
An explicit @moth.sig ... -> ! annotation is the only way an external function is Never. Moth does not inspect the foreign body. Calls follow the standalone-statement rule. Host Never imports are rejected on Wasm at target validation.
export function halt(message) {
throw new Error(message);
}
Exact literal constant subset
@moth.const exposes a flat Moth name and the fixed U32 type. The JavaScript export name may differ:
export const TRIANGLES = 4;
The initializer supplies the value. Compilation reads its authored literal without executing JavaScript and preserves its exact U32 identity through imports and flat direct-selection source re-exports. Builders and physical targets don't retype it.
Each annotation accepts one export const declarator with an unsigned decimal integer literal from 0 through 4294967295. Whitespace and comments may separate tokens. A semicolon may close the declaration, or a newline may end it when the following token doesn't continue the initializer.
Unannotated constants, leading-zero spellings other than 0, numeric separators, alternate radices, signs, fractions, exponents, BigInt suffixes, arithmetic, references, property reads, calls, multiple declarators and non-U32 constant annotations remain rejected. @moth.sig cannot annotate a literal constant and @moth.const cannot annotate a callable export. Duplicate Moth names across functions, constants and opaque types, and duplicate JavaScript export names, also produce diagnostics.
Constant-only dependencies contribute semantic inputs without emitting their JavaScript asset, wrappers or authored runtime imports. A literal change still invalidates its semantic users even when no asset is emitted, so a 4 to 5 edit rebuilds what depends on it. A dependency with reachable functions retains the normal runtime asset once. Nested annotation names and nominal foreign enum domains remain pending.
Rejected JavaScript features
- arbitrary dependency graphs
- default exports
- re-exports
- CommonJS
- classes
- constants outside the exact
@moth.const literal subset - property accessors
- callbacks
- async functions
- collections or options in JS signatures
- generic external type
- receiver methods
- multi-success JS returns
Restricted host-binding profile
Existing Core, Builder and JavaScript-backed bindings follow a restricted host-binding profile:
- ordinary Moth values cross by value
- host code may not retain references into ordinary Moth storage
- opaque handles represent foreign identities rather than Moth reference types
Observable external resources require explicit close or teardown. Host finalisation timing does not define language behaviour.
Compiler-generated runtime error exports
@moth/runtime exposes mothOk and mothErr unchanged alongside five named numeric error exports. The names are MOTH_ERROR_UNSUPPORTED, MOTH_ERROR_HOST_INVALID_ARGUMENT, MOTH_ERROR_HOST_RESOURCE_NOT_FOUND, MOTH_ERROR_HOST_RESOURCE_UNAVAILABLE and MOTH_ERROR_HOST_OPERATION_FAILED. BuiltinErrorCode owns their values and one association generates both the validated exported-name list and the numeric JavaScript declarations. Package assets import them by name and never copy numbers into a second table or static asset.
Numeric signature types
External numeric signatures name exact Moth types independently of their foreign ABI carriers. Core and Builder APIs use explicit I32, U32 and F64 slots where their contracts require them. Already fixed foreign signatures retain their widths. Annotated JavaScript accepts I32, I64, U32, U64, F32 and F64, not every language numeric type. The numeric types reference owns the language inventory and literal defaults.
- I64 crosses annotated JavaScript as a
Number only within the safe-integer range, from -9,007,199,254,740,991 through 9,007,199,254,740,991 inclusive. Values outside that range fail rather than silently losing precision. - U64 inside Moth JavaScript is a
BigInt from 0 through 18446744073709551615. Across the existing Number-based foreign adapter it crosses only from 0 through 9007199254740991. That restriction belongs to the foreign boundary, not the Moth U64 range. - The U64 adapter rejects negative or unsafe values before precision can be lost. It validates one evaluated snapshot, canonicalises
Number -0 to integer 0 and rejects fractions, non-finite values and wrong carrier types. Foreign contract violations throw rather than creating a new implicit-failure or Error code. - U32 crosses annotated JavaScript as a
Number integer from 0 through 4294967295. The wrapper does not coerce or wrap and rejects invalid carriers or ranges. Integer -0 canonicalises to 0 at ingress. Infallible and fallible calls validate successful payloads identically, evaluating each foreign result once. - An F32 parameter must already be an exact finite binary32
Number. The wrapper checks typeof, finiteness and Math.fround equality before the foreign call observes the value. It preserves signed zero and subnormals. Inexact, non-finite or wrong-carrier values throw. - An F32 result rounds once at binary32 with
Math.fround and must stay finite. The wrapper evaluates the foreign value once and preserves signed zero and subnormals. A non-Number fails at the same boundary. A rounded non-finite value throws in an infallible wrapper and becomes builtin Error code 304 through the documented builtin Error! boundary. - F64 results retain binary64 width and undergo the shared finite-result check. A non-finite result uses code
304 through a declared builtin Error! boundary, otherwise the integrity guard halts. - I32 values must be JavaScript Numbers, integral and within -2,147,483,648 through 2,147,483,647. Invalid successful payloads fail at the wrapper boundary in both infallible and fallible calls. Integer ingress converts
-0 to 0, while binary-float ingress preserves signed zero. - Opaque external types retain their package-specific identities and representations; numeric carrier adaptation does not reinterpret them.
Moth-owned finite-value checks, including the shared external binary-float boundary with code 304, are fatal integrity guards, not implicit built-in failure: they halt unless a declared builtin Error! contract returns them. This changes failure delivery, not numeric validity or the foreign signature. See Errors and Progress for the contract and current support.
Validation uses the resolved exact result type and precision for every supported result shape, not a package-name test. Unsupported shapes retain their capability rejection. Validate only successful payloads and preserve a valid returned Error's code, message and identity. Authored safety catch never creates an Error producer or makes a fatal integrity guard recoverable.
Compile-time external constants also retain their declared exact scalar type. Projection validates range and finiteness before publishing a Moth value, so a wider host carrier cannot change the constant's identity or admit an invalid value. Compile-time invalidity produces a diagnostic, not a runtime handler outcome. This registry contract doesn't expand the annotated JavaScript constant subset beyond literal U32.
Exact types don't expand target capabilities. The packages and builders progress matrix records package availability. Constant-only JavaScript dependencies need no runtime asset, while reachable JavaScript-backed functions still need a supported lowering. WIT, collections, options, callbacks and async retain their existing capability limits.
Fallible JavaScript bindings project error.code onto Moth's U32 field. The wrapper reads the foreign code once and accepts JavaScript Number integers from 0 through 4294967295. It normalises integer -0 to 0 and uses code 0 for missing or invalid codes. The existing adapter for declared fallible JavaScript bindings turns exceptions thrown by the export into builtin Error values with code 0. Their message uses a truthy message property or stringifies the thrown value, including null and undefined. Current invalid-wrapper handling remains build-mode-specific; see Progress. Implicit numeric failure adds no automatic recoverable adapter for unexpected foreign throws or other violations of a declared value contract.
Deferred WIT component support
WIT is the standard foreign Wasm/component boundary. It does not encode Moth module or package semantic interfaces. MothSource packages keep their Moth interfaces even when their physical output is Wasm.
The HTML builder does not currently load WIT component imports. Component discovery and projection into binding-backed package metadata are deferred; no WIT component loader contract is delivered here.
Deferred WIT surfaces
No WIT component contract is delivered for resources, callbacks, async operations, futures, streams, shared-memory views, raw pointers, returned aliases or retained Moth references.
Concepts related to external binding contracts