Packages and dependencies

Dependencies make names visible, module roots define public boundaries and packages provide stable named surfaces. Moth keeps those jobs separate.

Unlike languages that expose any reachable filesystem path, Moth resolves source dependencies from the owning module root and stops at each module facade. Project-local support packages share code without opening private paths.

The packages and builders progress matrix records current package and project-builder support.

Choose the explanation level: Dependency paths

Dependency paths

Dependencies make names visible. A source dependency path resolves from the binding file's owning module root, not its directory.

  • @card render_card at the start of a statement is a dependency clause. It binds render_card.
  • @settings site_name inside an expression reads one value without binding it.
  • @docs/intro.mtf is a file value that produces a String.

Module-root-relative paths

@card render_card
@markdown render

title = @settings site_name
intro = @docs/intro.mtf

@card resolves under the owning module root. @markdown can name an accessible scoped support package. A .moth file has no file value.

Root filenames such as @mod.moth and @entry.moth cannot be dependency targets. Cross-module imports see only names marked by $export in the applicable facade.

See Dependency paths.

Dependency paths resolve declaration surfaces, not file bytes. Every source dependency clause resolves from the declaring file's owning module root, not the file's physical directory.

A dependency path has three distinct roles:

  • @module symbol in expression position is a qualified expression reference. It selects one symbol as an operand.
  • @module symbol, other in statement position is an ordinary dependency clause. It binds the selected names for later statements.
  • @file.ext is a file value. It evaluates to a String.

The spelling and provider rules are shared, but the roles never convert into each other. A clause never becomes a file value, and a file value never exposes a provider namespace. See File paths and Template scope.

Qualified expression references

A PATH token followed by exactly one SYMBOL token on the same physical line forms one expression primary:

name = @settings site_name
color = @settings palette.background
value = @math square(12)

A newline ends the selection. Spaces and tabs may separate the two tokens, a newline may not. The selected symbol creates no visible local binding, so it never collides with a local name or with another provider's selection. Ordinary expression suffixes still apply after the selected symbol.

The same form works inside template heads in .moth templates and inside the synthetic .mtf body:

# Welcome to [@settings site_name]

A qualified reference creates an early provider-dependency fact, not a dependency clause. The provider must expose the selected symbol under the consuming source's access rules. An unassigned top-level @math square(12) is rejected: a top-level path starts a dependency clause, and a call is not a valid selection list. Bind the name with a clause and call it there.

Path families

  • Module-root-relative: dependency clauses resolve from the declaring file's owning module root. Example: inside internal/deep/renderer.moth, @accounts Account resolves to accounts.moth, not internal/deep/accounts.moth.
  • Child module: reaching a child normal module exposes only its @mod.moth facade. Dependency clauses cannot bypass that facade with paths such as @child/internal.
  • Support package: scoped @package.moth packages are depended on by package name. Consumers never encode ancestor paths. A support-only child remains importable only by eligible consumers through its support surface.
  • Entry-only child module: an entry-only directory has no importable normal interface. A dependency that requests one receives a missing-surface diagnostic. The entry is never activated.
  • Core binding-backed package: @core/math, @core/text and current peers are registered by the builder.
  • Core source-backed package: @core/html and @core/css are compiler-provided Moth source packages and the fixed template prelude providers. Each publishes through a directly contained @package.moth.
  • Builder source-backed package: @builder/web/site belongs to the HTML builder and publishes through a directly contained @package.moth.
  • Builder binding-backed package: @builder/web/canvas is a builder-owned runtime package with no source facade.
  • JavaScript file: project-local annotated JavaScript files require .js and a builder external import provider. The .js extension is kept.

Resolution rules

  • @./... has no supported meaning.
  • @/... absolute-root paths are invalid, and so is bare @/. Dependency resolution starts at the owning module root, so no absolute root is meaningful here. In expression position bare @/ is instead the site-root URL. See File paths.
  • Parent components and .. are invalid.
  • Paths may traverse ordinary unrooted directories owned by the same module.
  • .moth, .mtf and .md source dependency paths are extensionless.
  • Direct .js dependency clauses keep the .js extension.
  • Scoped support packages are injected by package name, not physical ancestor paths.
  • Core and builder runtime packages use their registered package path. The exact @core and @builder roots are not package targets.
  • Specific symbol bindings use flat direct selections. Direct symbol paths such as @core/math/sin remain invalid.
  • Direct dependency clauses on @mod.moth, @package.moth, @entry.moth and @config.moth are rejected. Depend on the module directory instead.
  • @@name is invalid. The leading @ starts a dependency path and is not part of the module name.
  • A bare explicit-extension clause requires as or at least one direct selection. An explicit-extension clause with no registered provider gets a targeted diagnostic.
  • A recognised source extension used with an explicit extension gets an extensionless-source diagnostic. @docs/intro.mtf content stays invalid as a clause even though @docs/intro.mtf is a valid file value in expression position.
  • Moth template .mtf and plain Markdown .md content files both expose generated content constants. See Moth template content dependencies and Markdown dependencies.
  • The public surface comes from $export declarations and direct-selection clauses in the applicable facade. See Module visibility.

Same-module dependencies

Files in the same module can bind ordinary sibling source files directly. Same-module dependency clauses bypass the public-surface boundary. Root-local declarations are the exception: a declaration authored directly in @mod.moth, @package.moth or @entry.moth stays in that root file. See Module visibility.

Cross-module dependencies

Dependency clauses that cross into another module boundary can only access what that module's applicable facade makes public. Cross-module dependency clauses cannot bypass the public API. See Module visibility.

Content-file dependencies

Moth template and plain Markdown content files are bound with the same extensionless syntax. Their dependency shape is covered by the Moth template and Plain Markdown pages, not here.

Concepts related to dependency paths

Choose the explanation level: Dependency clauses

Dependency clauses

Direct-selection clauses bring multiple symbols. Namespace clauses bring a whole surface.

Two colliding render symbols

@blog render as render_blog
@docs render as render_docs

Two modules both export render. Aliases keep them apart.

A namespace alias

@core/math as math

result = math.sin(1.0)

math gives you field access to the whole math package.

Direct-selection and namespace dependency clauses provide compact syntax for binding multiple symbols or a whole declaration surface.

Direct symbol dependencies

@core/math sin, cos, PI

@components render as render_component, Button as UiButton, Card

Each direct selection binds one symbol into the file. as creates a file-local alias. One authored clause keeps one shell identity and resolves one provider surface. Selected names do not become independent provider clauses.

Direct-selection termination

The path and the first direct selection must start on the same physical line. A comma explicitly continues the list across a following newline:

@core/math sin, -- the comma keeps the clause open
    cos

Without a comma, a newline ends the dependency clause:

@core/math sin
next_value = build_value()

The comma always promises another selection, so a trailing comma is invalid:

-- Error
@core/math sin, cos,

The same rules apply when $export marks a direct-selection clause for re-export.

Namespace dependencies

@core/math

angle = math.PI
result = math.sin(angle)

A bare namespace clause brings the whole surface as a field-access-only namespace. Use math.sin(1.0) for values and math.PI for constants, but do not pass the namespace record itself as a value.

Namespace alias

@core/math as math

@vendor/drawing.js as drawing

A clause-level as gives the namespace a local name. This is the standard form for external package namespaces.

Entry aliases

@core/math sin as sine, PI as pi

Each selected entry can have its own alias. A clause-level as is mutually exclusive with direct selections and renames the whole namespace.

Bindable symbol categories

  • functions
  • structs
  • choices
  • type aliases
  • traits
  • compile-time constants

Runtime top-level bindings are not bindable. See Module visibility.

Namespaced access

Source and module namespace clauses are shallow. External package namespaces can expose nested package-local symbols. Use field-access syntax on the namespace record, but do not pass the namespace itself as a first-class value. Source-authored receiver methods are called through receiver-call syntax rather than as namespace fields.

Dependency clauses are compile-time declarations

Dependency clauses are not first-class runtime values. They exist at compile time to make names visible. Dependency bindings are file-local and visible throughout the file independent of clause position.

Direct-selection rules

  • Empty selection lists are unrepresentable.
  • A leading @ inside a selection list is invalid.
  • Selections are flat identifiers and cannot contain child paths or nested selection syntax.
  • Duplicate selected names and duplicate local names are diagnosed.
  • A direct-selection clause binds selected declarations from the one resolved provider surface.
  • Clause-level as and direct selections are mutually exclusive.
  • An invalid inferred namespace stem requires as.
  • Receiver methods remain attached to their receiver types and cannot be selected separately.

Collision and no-shadowing policy

  • Ordinary dependency aliases are file-local.
  • A dependency alias cannot hide an existing visible name.
  • If render is already declared in the file, @other render is an error. Pick a different local name.
  • Leading-case mismatches warn. For example, binding a struct with a lowercase alias or a function with an uppercase alias triggers a warning.

Provider clauses

Explicit-extension paths select a registered provider:

@drawing.js draw
@drawing.js as drawing

A bare explicit-extension clause requires as or at least one same-line direct selection. An explicit-extension clause with no registered provider gets a targeted diagnostic. A namespace has one provider origin. Consumer-created mixed-origin namespace aggregation is outside scope.

A bare explicit-extension path in expression position is a file value, not a provider. @drawing.js as drawing binds the provider's namespace; url = @drawing.js is the file itself, as a resource String. @drawing.js draw(...) is a qualified provider reference: the path selects the provider and draw selects one of its declarations. A clause never becomes a file value, and a bare file value never exposes a provider namespace. See File paths.

Concepts related to dependency clauses

Choose the explanation level: Module visibility

Module visibility

Module boundaries expose only names marked with $export in the appropriate facade.

Shared helpers

-- components/utils.moth
internal_value #= 42
-- components/@mod.moth
$export
@utils internal_value

A parent module may now bind @components internal_value. It cannot bypass the child facade with @components/utils.

Separate root scopes

Declarations authored in @mod.moth, @package.moth or @entry.moth remain local to that root. Shared code belongs in ordinary helper files.

@mod.moth publishes the normal API and @package.moth publishes the support API. @entry.moth publishes none. Resolution never falls back from one facade to another.

See Module visibility and Project-local packages.

Module visibility determines which declarations can cross a module boundary. Shared helper declarations are available within their owning module. Other modules can see only the names published by the applicable @mod.moth or @package.moth facade using $export.

Shared helpers and public facades

A rooted directory is one module. Its ordinary .moth files, including files in unrooted subdirectories, share declarations through dependency clauses.

@entry.moth
components/
├── @mod.moth
└── utils.moth
-- components/utils.moth
internal_value #= 42
-- components/@mod.moth
$export
@utils internal_value

The facade imports and publishes internal_value. Another module can now use:

@components internal_value

Without $export, the same @utils dependency would be private to the facade. Other modules cannot bypass the child facade using @components/utils.

Root-local declarations

Declarations authored directly in @mod.moth, @package.moth or @entry.moth belong to that root's own scope. They are not shared with other roots or ordinary helpers. A facade can publish its own declarations, but a sibling root cannot import or re-export them.

Shared code belongs in ordinary helper files. Each root may depend on those helpers through normal dependency clauses. Same-spelling declarations in separate roots are independent unless an imported helper introduces a name collision.

Direct dependency paths to root filenames or @config.moth are invalid. Depend on the module directory or a shared source file instead. See Module roots.

Separate public surfaces

@mod.moth publishes the normal module API. @package.moth publishes a scoped support package API or the external project package API at the project root. @entry.moth has no importable public surface and only its selected entry executes.

A dependency selects the surface appropriate to its consumer. It cannot fall back to the other facade. A child with only @entry.moth has no normal public API. Support packages have additional scoped consumer restrictions, described in Project-local packages.

A facade with no $export declarations or clauses has an empty public API. A cross-module import of a private name is rejected regardless of the path used.

Methods and public contracts

Receiver methods follow the visibility of their nominal receiver type. A caller with a value of a public receiver type can call its methods without separately importing that type name. Naming the type in a signature, constructor or conformance still requires a suitable type binding. Methods cannot be imported or exported individually.

Public signatures must expose only accessible types and trait evidence. Exported callables without an error slot must handle any escaping implicit built-in failure. The same guarantee applies to exposed methods and re-exports. See Public API.

Dependency ordering

A dependency clause binds names throughout its file, independent of source position. File dependency cycles inside one module are allowed when declarations can be resolved in dependency order. Circular constant dependencies are rejected.

Related references

Choose the explanation level: Public re-exports

Public re-exports

A facade re-exports declarations by marking a direct-selection dependency clause with $export.

$export
@components/card CardData as Card, render_card

Consumers can bind Card and render_card. CardData is not also published unless selected separately.

Without $export, an import stays private to its source file:

@components/card CardData as LocalCard

A re-export needs explicit selected names. Whole namespaces and namespace aliases cannot be exported. See Public re-exports.

A facade can re-export declarations from another source file or package without defining a wrapper. Place $export immediately before a direct-selection dependency clause in @mod.moth or @package.moth.

Direct-selection re-exports

$export
@components/card CardData as Card, render_card

$export
@core/math PI, sin

This publishes Card, render_card, PI and sin through the facade. CardData remains available under its original name only if the facade also selects it without an alias. A leaf as alias is both the local selected name and the public name.

One directive applies to all names on the following clause. An ordinary unmarked dependency clause stays private:

@components/card CardData as LocalCard

LocalCard is now bound in this file, but is not public.

Selection syntax

The provider path and first selected name must begin on the same physical line. A comma continues the list across a newline:

$export
@components/card CardData,
    render_card

Without a comma, a newline ends the clause. A trailing comma is invalid because another selected name is required.

Re-exports require a nonempty list of flat, explicit selections. Whole namespaces, namespace aliases, nested selections, wildcard exports and export lists are unsupported. Receiver methods remain attached to their receiver type and cannot be re-exported as separate selected names.

Public identity and validation

Re-exports preserve the selected declaration's origin, type and callable error contract. They cannot expose an unknown or inaccessible private declaration. Exported names must be unique across direct declarations and re-exported selections in one facade.

A private callable's inferred implicit failure cannot escape through a public callable without an appropriate declared error slot or local handling. See Public API for the public contract.

Related references

Choose the explanation level: Project-local packages

Project-local packages

A scoped support package is a directory containing @package.moth. The directory supplies its package name.

@entry.moth
blog/
├── @package.moth
└── helpers/dates.moth

@blog is visible to the entry root and eligible normal sibling modules.

@blog post_title

Only declarations marked by $export in blog/@package.moth are public. Support roots can re-export selected helpers but do not create pages.

A project-root @package.moth is the external project package surface. Internal project modules cannot import it. Registered source packages use the same @package.moth facade rule, but their names live below the reserved @core or @builder root rather than in project-local scope. See Project-local packages.

Project-local source-backed packages are scoped @package.moth support packages discovered structurally from the project source tree. Structural discovery determines package roots without configuration.

Directory structure

project-root/
├── @config.moth
├── @entry.moth
├── markdown/
│   ├── @package.moth
│   ├── parser/
│   │   └── @mod.moth
│   └── rendering/
│       └── @mod.moth
├── pages/
│   └── @mod.moth
└── @package.moth

The markdown directory contains an @package.moth root, making @markdown a scoped support package visible to the entry root, @pages and their descendants.

Scoped visibility

For a support package S whose nearest ancestor normal-position module is P:

  • S is visible to P
  • S is visible to normal sibling modules of S and their descendants
  • S is not visible above P
  • S is not visible outside P's subtree
  • S is not visible inside its own private implementation subtree
  • another support package in the same owner scope cannot depend on S

A module with @mod.moth or @entry.moth occupies the normal-position owner role. An entry-only module can therefore own support descendants even though it publishes no normal API. A co-located @entry.moth gives no entry privileges to its @package.moth facade.

Public surface

Consumers see only declarations and direct-selection re-exports marked with $export in the support facade. Internal implementation files remain private unless the facade re-exports selected declarations.

Shared helpers in a paired directory must obey the intersection of imports legal to every root that can consume them.

Private subtrees

The support facade may depend on ordinary files it owns, any descendant module in its private subtree, support packages from a strictly outer scope and registered packages. It may not depend on its parent, normal sibling consumers or same-scope support siblings.

Consumers see only the support facade's $export surface. They cannot address @markdown/parser or another implementation path.

Depended-on package roots do not produce routes

Support roots are API-only. They reject top-level runtime work, direct fragments and builder-slot contributions, export declarations instead and produce no HTML artefact. Only @entry.moth creates a page. Importing a support package never activates an entry in its directory. See HTML routing and artefacts.

Support packages may hold reusable ordinary # constants and expose them through their public surface. They do not need custom project metadata. Project metadata remains the separate @config.moth contract.

Namespace limits and copied packages

Local support packages stay outside the reserved Core and Builder namespaces. An importable local facade, helper or dependency alias cannot claim core or builder, compared case-insensitively. A directory name alone never triggers that rejection: entry-only modules, their private helpers, directories containing only entry modules and plain asset directories remain legal. Unrelated html/, css/, styles/ and web/ folders also stay legal.

A project folder whose full path matches a registered source package path, such as core/html/ or builder/web/site/, collides whichever module owns it, even when it holds no importable surface. An ancestor folder such as core/ alone stays legal. A binding-backed package has no source module, so an asset folder at a registered binding path such as builder/web/canvas/ stays legal.

Copying a source-backed package directory to a non-colliding local path gives an ordinary support package through its own @package.moth. Copying it to a registered source package path, such as core/html/, hits the collision above. Copying a binding-backed asset tree creates no package and registers no symbols. Neither copy inherits the registered package's origin, namespace or capabilities.

Origin and backing are separate

Scoped @package.moth packages are ProjectLocal packages backed by Moth source. Registered MothSource packages also publish through a directly contained @package.moth, while @mod.moth alone is insufficient for registration. @core/html and @core/css are source-backed with Core origin. @core/math and @builder/web/canvas are binding-backed packages with Core and Builder origins respectively. See Package origins and backing.

Concepts related to project-local packages

Choose the explanation level: Package origins and backing

Package origins and backing

Packages can differ in two ways: who provides them and what backs their implementation.

Origin

  • Core packages come from the compiler.
  • Builder packages come from the selected project builder.
  • ProjectLocal packages come from your project.

Backing

  • Source-backed packages contain ordinary Moth modules.
  • Binding-backed packages expose typed functions, constants and opaque types implemented outside Moth.

@core/html and @core/css are source-backed Core packages available under every builder. @core/collections and @core/math are binding-backed Core packages. @builder/web/canvas is a binding-backed Builder package.

Core names live below the reserved @core root, Builder names below @builder. Neither exact root is importable, and a project-local package cannot claim them. Every registered source package publishes through a directly contained @package.moth, and a copied source package becomes an ordinary project-local support package rather than a Core or Builder package.

Every package has two independent classifications: where it comes from and how the compiler obtains its implementation.

Package origin

Origin describes ownership and distribution:

  • Core: compiler-owned packages such as @core/html, @core/css, @core/io and @core/math.
  • Builder: packages selected by a project builder, including @builder/web/site and @builder/web/canvas.
  • ProjectLocal: scoped @package.moth support packages, the project-root package facade and annotated project-local JavaScript files.
  • Dependency: reserved for future package-system support.

Package backing

Backing describes implementation:

  • MothSource: one or more Moth modules resolved through the source package registry.
  • ExternalBinding: typed functions, constants and opaque types implemented outside Moth.

Backing is semantic, not a file-format choice. Precompiling or emitting a MothSource package as Wasm keeps it MothSource. Imported WIT components are ExternalBinding packages.

Package

Origin

Backing

@core/html, @core/css

Core

MothSource

@builder/web/site

Builder

MothSource

@core/collections, @core/io, @core/math, @core/text, @core/random, @core/time

Core

ExternalBinding

@builder/web/canvas, @builder/web/graphics, @builder/web/page

Builder

ExternalBinding

Scoped @package.moth support package

ProjectLocal

MothSource

Project-root @package.moth facade

ProjectLocal

MothSource

Annotated project-local .js file

ProjectLocal

ExternalBinding

Origin and backing don't change dependency clause syntax or module visibility. Source-backed packages publish their public surface with $export. Binding-backed packages expose typed external symbols registered by the builder.

Package names and source facades

Core and Builder names sit in reserved namespaces. Core registrations live below @core/. Builder registrations live below @builder/ at an explicit path the builder chooses, such as web/site or game. The exact @core and @builder roots are not importable package surfaces. ProjectLocal and Dependency packages cannot claim either root. Registration compares names case-insensitively, so case-only variants fail along with equal or ancestor/descendant overlaps for every backing.

Every registered MothSource package publishes its public surface through a directly contained @package.moth. @mod.moth alone is insufficient. A co-located @mod.moth may still own a separate internal normal-position scope, while the external package interface always comes from @package.moth. Ordinary project modules keep their optional root combinations. Binding-backed packages carry no source facade because the builder registers their typed symbols directly.

Copying a package directory into a project does not grant Core or Builder identity. A copied source package becomes an ordinary ProjectLocal support package through its own @package.moth. A copied binding package directory registers no symbols and gains no namespace identity.

Prelude is visibility policy

The prelude is implicit dependency policy, not an origin or backing. The ordinary Moth prelude exposes io as an alias to @core/io. The separate .mtf prelude makes public compile-time constants from @core/html and @core/css visible by bare name. Package metadata remains independent of these visibility policies.

Builder-selected availability

Builders provide implementations and additional packages without redefining Core semantics. Official browser and native environments provide the canonical Core catalogue, including its documented host-capability gates. Custom builders may provide a subset or no public Core implementation. Reserved Core identities and the io prelude keep their meaning even when an operation is unavailable. The progress matrix records current implementation gaps separately from this design contract.

The mandatory Core source packages @core/html and @core/css are an exception to builder-selected availability. The common builder surface registers both roots under every builder, including custom SDK builders, because they supply compiler-level template helpers rather than host capabilities. A builder cannot replace either root or register a package under its prefix.

The future official package manager classifies managed Moth-source packages as no-core or Core-dependent over their complete dependency closure. Official certified environments may consume both. Custom builders receive no-core packages only, even when they use Lappet or implement all Core APIs. Certification is a Moth project decision, not inferred from matching signatures.

Compiler-internal helpers and the unused io prelude do not make a package Core-dependent. No-core still requires support for the language features it executes. Managed Builder-dependent and foreign-code packages are deferred. Local and builder-supplied packages retain their normal compiler rules. See Lappet for scope and the package-manager design.

Binding-backed package constraints

Binding-backed packages expose free functions, constants and opaque types. They don't expose source-style receiver methods. Use a source-backed wrapper type for method-style APIs. External calls are positional-only because named arguments and default parameters are source-function features.

The HTML-Wasm mode has a stricter backend surface. A reachable JS-backed package needs a Wasm lowering before that backend can use it.

No package manager yet

There is no remote fetching, lockfile or version resolution yet. Use @package.moth support facades for project-local source-backed packages, builder-provided package dependency clauses for built-in capabilities and annotated .js wrappers for direct browser integration.

Concepts related to package origins and backing

Choose the explanation level: External binding contracts

External binding contracts

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:

/** @moth.const primitive_triangles U32 */
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

/**
 * @moth.sig emphasize |text String| -> String
 */
export const emphasize = (text) => {
    return `**${text}**`;
};


/**
 * @moth.sig join_label |prefix String, body String| -> String
 */
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:

/**
 * @moth.sig emphasize |text String| -> String
 */
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.

/**
 * @moth.sig halt |message String| -> !
 */
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:

/** @moth.const primitive_triangles U32 */
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

Package reference pages