client

package module
v0.6.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 28, 2026 License: MIT Imports: 21 Imported by: 3

README ΒΆ

tinywasm/client

Build-only WebAssembly compilation manager for TinyWASM.

As of v2, client has a single responsibility: compile the WASM binary and serve it at /client.wasm. All JavaScript composition has moved to tinywasm/js.

Responsibilities

βœ… Owns ❌ No longer owns
WASM compilation (Go stdlib / TinyGo) wasm_exec.js embedding
Serving /client.wasm via HTTP Javascript struct / GetSSRClientInitJS
3-mode compiler selection (L/M/S) Generating script.js content
File watcher for web/main.wasm.go WasmExecGoSignatures / WasmExecTinyGoSignatures
VS Code GOOS/GOARCH config ClearJavaScriptCache
Project scaffolding (CreateDefaultWasmFileClientIfNotExist)

CLI Tool

go install github.com/tinywasm/client/cmd/wasmbuild@latest
wasmbuild        # Go stdlib mode (L)  β†’ writes web/public/client.wasm + script.js
wasmbuild -tinygo # TinyGo mode (S)

script.js is now generated via tinywasm/js.PageBootstrap() β€” the embedded wasm_exec.js lives in js/assets/ (single source of truth).

See cmd/wasmbuild for details.

πŸ›  Basic Usage

cfg := client.NewConfig()
cfg.SourceDir = func() string { return "web" }
cfg.OutputDir = func() string { return "web/public" }

twc := client.New(cfg)
twc.SetAppRootDir("/path/to/project")
twc.SetMainInputFile("app.go") // default: "client.go"
twc.SetOutputName("app")       // default: "client"
Mode switching
twc.Change("S") // "L" = Go, "M" = TinyGo debug, "S" = TinyGo prod
HTTP serving
twc.RegisterRoutes(mux) // registers /client.wasm (or /prefix/client.wasm)
ArgumentsForServer
// Returns []string{"-wasmsize_mode=L"} (for subprocess injection)
args := twc.ArgumentsForServer()

Storage modes

Mode Use case
In-Memory (default) Fast dev β€” compiles to buffer, served directly
Disk Static integration β€” compiles to OutputDir, served via http.ServeFile
twc.UseDiskStorage()   // switch to disk
twc.UseMemoryStorage() // switch back to memory

Project Initialization

// Generates web/client.go + .vscode/settings.json if missing
twc.CreateDefaultWasmFileClientIfNotExist(false)

βš™οΈ Configuration

  • Config struct: shared deps (Store, Logger), directory functions (SourceDir, OutputDir). See config.go.
  • Setters: reactive β€” re-initialize internal state automatically.

πŸ“‹ Requirements

  • Go 1.21+
  • TinyGo (optional β€” needed for M/S modes only)

JavaScript composition

All JS is now the responsibility of tinywasm/js:

import "github.com/tinywasm/js"

// In tinywasm/app boot:
js.SetRuntime(js.RuntimeGo) // or RuntimeTinyGo
scripts := []any{js.PageBootstrap()} // registers with assetmin

See tinywasm/js for the full typed API including ServiceWorker and WebWorker.

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const StoreKeySizeMode = "wasmsize_mode"

StoreKeySizeMode is the key used to store the current compiler mode in the Database

Variables ΒΆ

This section is empty.

Functions ΒΆ

func ParseWasmSizeModeFlag ΒΆ added in v0.0.80

func ParseWasmSizeModeFlag() string

ParseWasmSizeModeFlag parses -wasmsize_mode flag from os.Args. Returns the value found, or empty string if not present.

func RunWasmBuild ΒΆ added in v0.6.1

func RunWasmBuild(args WasmBuildArgs) error

RunWasmBuild performs the common logic for the wasmbuild CLI.

func SetRunWasmBuildHooks ΒΆ added in v0.6.1

func SetRunWasmBuildHooks(h RunWasmBuildHooks) (restore func())

SetRunWasmBuildHooks updates RunWasmBuild dependencies for the duration of a test. It returns a restore function that should be deferred.

Types ΒΆ

type BuildStorage ΒΆ

type BuildStorage interface {
	// Compile performs the compilation.
	// For Memory: compiles to buffer.
	// For Disk: compiles to disk.
	Compile() error

	// RegisterRoutes registers the WASM file handler on the mux.
	RegisterRoutes(mux *http.ServeMux)

	// Name returns the Storage name for logging/debugging
	Name() string
}

BuildStorage defines the behavior for compiling and serving the WASM client.

type Config ΒΆ

type Config struct {
	// SourceDir specifies the directory containing the Go source for the webclient (relative to AppRootDir).
	// e.g., "web"
	SourceDir func() string

	// OutputDir specifies the directory for WASM and related assets (relative to AppRootDir).
	// e.g., "web/public"
	OutputDir func() string

	// AssetsURLPrefix is an optional URL prefix/folder for serving the WASM file.
	// e.g. "assets" -> serves at "/assets/client.wasm"
	// default: "" -> serves at "/client.wasm"
	AssetsURLPrefix string

	// gobuild integration fields
	Callback           func(error)     // Optional callback for async compilation
	CompilingArguments func() []string // Build arguments for compilation (e.g., ldflags)
	Env                []string        // Environment variables, e.g., []string{"GOOS=js", "TINYGOROOT=/path"}

	Database         KeyValueDataBase // Key-Value store for state persistence
	OnWasmExecChange func()           // Callback for runtime/wasm_exec changes
}

Config holds configuration for WASM compilation

func NewConfig ΒΆ

func NewConfig() *Config

NewConfig creates a WasmClient Config with sensible defaults

type DiskStorage ΒΆ added in v0.6.0

type DiskStorage struct {
	Client *WasmClient
}

DiskStorage compiles WASM to disk and serves the static file.

func (*DiskStorage) Compile ΒΆ added in v0.6.0

func (s *DiskStorage) Compile() error

func (*DiskStorage) Name ΒΆ added in v0.6.0

func (s *DiskStorage) Name() string

func (*DiskStorage) RegisterRoutes ΒΆ added in v0.6.0

func (s *DiskStorage) RegisterRoutes(mux *http.ServeMux)

type KeyValueDataBase ΒΆ

type KeyValueDataBase interface {
	Get(key string) (string, error)
	Set(key, value string) error
}

KeyValueDataBase defines the interface for a key-value Storage system used to persist the compiler state (e.g. current mode).

type MemoryStorage ΒΆ added in v0.6.0

type MemoryStorage struct {
	Client *WasmClient // Access to config and logger

	Mu          sync.RWMutex
	WasmContent []byte
	LastCompile time.Time
}

MemoryStorage compiles WASM to memory and serves it directly.

func (*MemoryStorage) Compile ΒΆ added in v0.6.0

func (s *MemoryStorage) Compile() error

func (*MemoryStorage) Name ΒΆ added in v0.6.0

func (s *MemoryStorage) Name() string

func (*MemoryStorage) RegisterRoutes ΒΆ added in v0.6.0

func (s *MemoryStorage) RegisterRoutes(mux *http.ServeMux)

type RunWasmBuildClient ΒΆ added in v0.6.1

type RunWasmBuildClient interface {
	SetMode(string)
	UseDiskStorage()
	SetLog(func(...any))
	Compile() error
	LogSuccessState(...any)
}

RunWasmBuildClient captures the subset of WasmClient methods used by RunWasmBuild. It is exported so tests can provide lightweight fakes without pulling in gobuild.

type RunWasmBuildHooks ΒΆ added in v0.6.1

type RunWasmBuildHooks struct {
	EnsureTinyGoInstalled func() (string, error)
	TinyGoEnv             func() []string
	NewClient             func(*Config) RunWasmBuildClient
}

RunWasmBuildHooks lets tests override RunWasmBuild dependencies (installer, env provider, client factory). Use SetRunWasmBuildHooks in tests to temporarily replace these functions.

type SetModeArgs ΒΆ added in v0.6.0

type SetModeArgs struct {
	Mode string `input:"required,enum=L;M;S"`
}

SetModeArgs defines arguments for the wasm_set_mode tool. ormc:formonly

func (*SetModeArgs) InputSchema ΒΆ added in v0.6.0

func (a *SetModeArgs) InputSchema() string

Schema will be generated by ormc.

func (*SetModeArgs) Pointers ΒΆ added in v0.6.0

func (m *SetModeArgs) Pointers() []any

func (*SetModeArgs) Schema ΒΆ added in v0.6.0

func (m *SetModeArgs) Schema() []fmt.Field

func (*SetModeArgs) Validate ΒΆ added in v0.6.0

func (m *SetModeArgs) Validate(action byte) error

type WasmBuildArgs ΒΆ added in v0.6.1

type WasmBuildArgs struct {
	Stdlib bool // true = Go standard compiler mode "L", false = TinyGo mode "S"
}

WasmBuildArgs defines the arguments for the RunWasmBuild function.

type WasmClient ΒΆ

type WasmClient struct {
	*Config

	// EXISTING: Keep for installation detection (no compilerMode needed - activeSizeBuilder handles state)
	// EXISTING: Keep for installation detection (no compilerMode needed - activeSizeBuilder handles state)
	TinyGoCompilerFlag bool // Enable TinyGo compiler (default: false for faster development)
	TinyGoInstalled    bool // Cached TinyGo installation status

	// NEW: Explicit mode tracking to fix Value() method
	CurrentSizeMode string // Track current mode explicitly ("L", "M", "S")

	Storage BuildStorage // Storage for compilation and serving (In-Memory vs External)

	// Configuration fields moved from Config
	AppRootDir    string
	MainInputFile string
	OutputName    string

	ShouldCreateIDEConfig     func() bool
	ShouldGenerateDefaultFile func() bool
	Log                       func(message ...any)

	// OnCompile is invoked after each compilation triggered by NewFileEvent.
	// err==nil indicates success; err!=nil indicates failure.
	OnCompile func(err error)
	// contains filtered or unexported fields
}

WasmClient provides WebAssembly compilation capabilities with 3-mode compiler selection

func New ΒΆ

func New(c *Config) *WasmClient

New creates a new WasmClient instance with the provided configuration

func (*WasmClient) ArgumentsForServer ΒΆ added in v0.0.77

func (w *WasmClient) ArgumentsForServer() []string

ArgumentsForServer returns runtime args to pass to the server, including the -wasmsize_mode flag based on current compiler mode.

func (*WasmClient) Change ΒΆ

func (w *WasmClient) Change(newValue string)

Change updates the compiler mode for WasmClient. Implements the HandlerEdit interface: Change(newValue string)

func (*WasmClient) Compile ΒΆ added in v0.5.52

func (w *WasmClient) Compile() error

Compile performs a synchronous compilation using the current settings. This exposes the underlying Storage's Compile method.

func (*WasmClient) CreateDefaultWasmFileClientIfNotExist ΒΆ

func (t *WasmClient) CreateDefaultWasmFileClientIfNotExist(skipIDEConfig bool) *WasmClient

CreateDefaultWasmFileClientIfNotExist creates a default WASM main.go file from the embedded markdown template It never overwrites an existing file and returns the WasmClient instance for method chaining.

func (*WasmClient) GetMCPTools ΒΆ added in v0.5.63

func (w *WasmClient) GetMCPTools() []mcp.Tool

GetMCPTools returns metadata for all WasmClient MCP tools

func (*WasmClient) GetTinyGoVersion ΒΆ

func (w *WasmClient) GetTinyGoVersion() (string, error)

GetTinyGoVersion returns the installed TinyGo version

func (*WasmClient) Label ΒΆ

func (w *WasmClient) Label() string

Label returns the field label for DevTUI display

func (*WasmClient) LogSuccessState ΒΆ added in v0.0.73

func (w *WasmClient) LogSuccessState(messages ...any)

LogSuccessState logs the standard success message with WASM details (Safe: Acquires Lock)

func (*WasmClient) Logger ΒΆ

func (w *WasmClient) Logger(messages ...any)

func (*WasmClient) MainInputFileRelativePath ΒΆ

func (w *WasmClient) MainInputFileRelativePath() string

MainInputFileRelativePath returns the relative path to the main WASM input file (e.g. "main.wasm.go").

func (*WasmClient) MainOutputFileAbsolutePath ΒΆ

func (w *WasmClient) MainOutputFileAbsolutePath() string

MainOutputFileAbsolutePath returns the absolute path to the main WASM output file (e.g. "main.wasm").

func (*WasmClient) Name ΒΆ

func (w *WasmClient) Name() string

Name returns the name of the WASM project

func (*WasmClient) NewFileEvent ΒΆ

func (w *WasmClient) NewFileEvent(fileName, extension, filePath, event string) error

NewFileEvent handles file events for WASM compilation with automatic project detection fileName: name of the file (e.g., main.wasm.go) extension: file extension (e.g., .go) filePath: full path to the file (e.g., ./home/userName/ProjectName/web/public/main.wasm.go) event: type of file event (e.g., create, remove, write, rename)

func (*WasmClient) OutputRelativePath ΒΆ

func (w *WasmClient) OutputRelativePath() string

OutputRelativePath returns the RELATIVE path to the final output file eg: "deploy/edgeworker/app.wasm" (relative to AppRootDir) This is used by file watchers to identify output files that should be ignored. The returned path always uses forward slashes (/) for consistency across platforms.

func (*WasmClient) RecompileMainWasm ΒΆ

func (w *WasmClient) RecompileMainWasm() error

RecompileMainWasm recompiles the main WASM file using the current Storage mode.

func (*WasmClient) RegisterRoutes ΒΆ

func (w *WasmClient) RegisterRoutes(mux *http.ServeMux)

RegisterRoutes registers the WASM client file route on the provided mux. It delegates to the active Storage.

func (*WasmClient) RequiresTinyGo ΒΆ added in v0.6.0

func (w *WasmClient) RequiresTinyGo(mode string) bool

RequiresTinyGo checks if the mode requires TinyGo compiler

func (*WasmClient) SetAppRootDir ΒΆ

func (w *WasmClient) SetAppRootDir(path string)

SetAppRootDir sets the application root directory (absolute).

func (*WasmClient) SetBuildShortcuts ΒΆ

func (w *WasmClient) SetBuildShortcuts(large, medium, small string)

SetBuildShortcuts sets the shortcuts for the three compilation modes. If an empty string is provided for a shortcut, it remains unchanged.

func (*WasmClient) SetLog ΒΆ

func (w *WasmClient) SetLog(f func(message ...any))

func (*WasmClient) SetMainInputFile ΒΆ

func (w *WasmClient) SetMainInputFile(file string)

SetMainInputFile sets the main input file for WASM compilation (default: "client.go").

func (*WasmClient) SetMode ΒΆ added in v0.5.52

func (w *WasmClient) SetMode(mode string)

SetMode explicitly sets the compilation mode (e.g., "S", "M", "L"). This is useful for CLI tools or programmatic control.

func (*WasmClient) SetOnCompile ΒΆ added in v0.6.2

func (w *WasmClient) SetOnCompile(fn func(err error))

SetOnCompile. registers a callback invoked after each compilation triggered by a file event. err==nil indicates success.

func (*WasmClient) SetOutputName ΒΆ

func (w *WasmClient) SetOutputName(name string)

SetOutputName sets the output name for WASM file (default: "client").

func (*WasmClient) SetShouldCreateIDEConfig ΒΆ

func (w *WasmClient) SetShouldCreateIDEConfig(f func() bool)

SetShouldCreateIDEConfig sets a function that determines if IDE configuration files (like .vscode) should be created.

func (*WasmClient) SetShouldGenerateDefaultFile ΒΆ

func (w *WasmClient) SetShouldGenerateDefaultFile(f func() bool)

SetShouldGenerateDefaultFile sets a function that determines if the default WASM client source file (usually client.go) should be created if it doesn't exist.

func (*WasmClient) Shortcuts ΒΆ

func (w *WasmClient) Shortcuts() []map[string]string

func (*WasmClient) ShouldCompileToWasm ΒΆ

func (w *WasmClient) ShouldCompileToWasm(fileName, filePath string) bool

ShouldCompileToWasm determines if a file should trigger WASM compilation

func (*WasmClient) SupportedExtensions ΒΆ

func (w *WasmClient) SupportedExtensions() []string

func (*WasmClient) TinyGoCompiler ΒΆ

func (w *WasmClient) TinyGoCompiler() bool

TinyGoCompiler returns if TinyGo compiler should be used (dynamic based on configuration)

func (*WasmClient) UnobservedFiles ΒΆ

func (w *WasmClient) UnobservedFiles() []string

UnobservedFiles returns files that should not be watched for changes e.g: main.wasm

func (*WasmClient) UpdateCurrentBuilder ΒΆ added in v0.6.0

func (w *WasmClient) UpdateCurrentBuilder(mode string)

UpdateCurrentBuilder sets the activeSizeBuilder based on mode and cancels ongoing operations

func (*WasmClient) UseDebugTinyGo ΒΆ added in v0.6.7

func (w *WasmClient) UseDebugTinyGo()

UseDebugTinyGo configures the client to compile with TinyGo in debug mode. Useful when iterating locally and you need TinyGo-compatible builds with extra debug info; never for deploy.

func (*WasmClient) UseDiskStorage ΒΆ added in v0.6.6

func (w *WasmClient) UseDiskStorage()

UseDiskStorage switches the client to disk-backed storage. Idempotent. Does NOT trigger compilation β€” the caller composes Compile() when needed.

func (*WasmClient) UseMemoryStorage ΒΆ added in v0.6.6

func (w *WasmClient) UseMemoryStorage()

UseMemoryStorage switches the client to in-memory storage. Idempotent. Provided for symmetry and test usage; production code does not call this (memory is the default at construction).

func (*WasmClient) UseProductionTinyGo ΒΆ added in v0.6.7

func (w *WasmClient) UseProductionTinyGo()

UseProductionTinyGo configures the client to compile with TinyGo in production (smallest possible binary). Callers (e.g. goflare) use this method instead of hardcoding the internal mode letter "S" β€” if the letter ever changes, only this method is updated, not every dependent.

Persists the mode to disk storage so it survives across runs and is not silently overridden by a stale value (e.g. a previous "L" run).

func (*WasmClient) UseStandardGo ΒΆ added in v0.6.7

func (w *WasmClient) UseStandardGo()

UseStandardGo configures the client to compile with the standard Go compiler. Produces large binaries (2-10 MB) and is incompatible with edge environments that enforce a 1 MiB wasm limit. Useful only when binary size does not matter (e.g. local servers that load wasm in a desktop browser).

func (*WasmClient) UseTinyGo ΒΆ added in v0.0.77

func (w *WasmClient) UseTinyGo() bool

UseTinyGo returns true if the current mode requires TinyGo's runtime

func (*WasmClient) ValidateMode ΒΆ added in v0.6.0

func (w *WasmClient) ValidateMode(mode string) error

ValidateMode validates if the provided mode is supported

func (*WasmClient) Value ΒΆ

func (w *WasmClient) Value() string

Value returns the current compiler mode shortcut (c, d, or p)

func (*WasmClient) VerifyTinyGoInstallation ΒΆ

func (w *WasmClient) VerifyTinyGoInstallation() error

VerifyTinyGoInstallation checks if TinyGo is properly installed

func (*WasmClient) VerifyTinyGoProjectCompatibility ΒΆ

func (w *WasmClient) VerifyTinyGoProjectCompatibility()

VerifyTinyGoProjectCompatibility checks if the project is compatible with TinyGo compilation

func (*WasmClient) VisualStudioCodeWasmEnvConfig ΒΆ

func (w *WasmClient) VisualStudioCodeWasmEnvConfig()

VisualStudioCodeWasmEnvConfig automatically creates and configures VS Code settings for WASM development. This method resolves the "could not import syscall/js" error by setting proper environment variables in .vscode/settings.json file. On Windows, the .vscode directory is made hidden for a cleaner project view. This configuration enables VS Code's Go extension to properly recognize WASM imports and provide accurate IntelliSense, error detection, and code completion for syscall/js and other WASM-specific packages.

func (*WasmClient) WasmProjectTinyGoJsUse ΒΆ

func (w *WasmClient) WasmProjectTinyGoJsUse(mode ...string) (isWasmProject bool, useTinyGo bool)

WasmProjectTinyGoJsUse returns dynamic state based on current configuration

func (*WasmClient) WebClientGenerator ΒΆ added in v0.6.1

func (w *WasmClient) WebClientGenerator() *webClientGenerator

WebClientGenerator returns a handler that generates the default web/client.go file.

Directories ΒΆ

Path Synopsis
benchmark
shared command
cmd
wasmbuild command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL