tinywasm

package module
v0.0.20 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2025 License: MIT Imports: 13 Imported by: 1

README

tinywasm

Go package for intelligent WebAssembly compilation with automatic file detection and 3-mode compiler system.

Features

  • 3-Mode Compiler System: Coding ("c"), Debug ("d"), Production ("p")
  • DevTUI Integration: FieldHandler interface for interactive mode switching
  • Smart file detection via prefixes (frontend/backend separation)
  • Triple compiler support: Go standard (fast dev), TinyGo debug (-opt=1), TinyGo production (-opt=z)
  • VS Code auto-configuration for WASM development
  • Single output: All files → main.wasm

Quick Start

// Basic usage
config := tinywasm.NewConfig() // Pre-configured with defaults
config.WebFilesFolder = func() (string, string) { return "web", "public" }

tw := tinywasm.New(config)
tw.NewFileEvent("main.wasm.go", ".go", "web/main.wasm.go", "write")

// DevTUI Integration - 3 Mode System
fmt.Println("Current mode:", tw.Value())    // "c" (coding)
msg, err := tw.Change("d")                  // Switch to debug mode
fmt.Println("Status:", msg)                 // "Switching to debugging mode"

// Advanced configuration
config := &tinywasm.Config{
    WebFilesFolder:      func() (string, string) { return "web", "public" },
    FrontendPrefix:      []string{"f.", "ui.", "view."},
    CodingShortcut:      "c",  // Customizable shortcuts
    DebuggingShortcut:   "d",
    ProductionShortcut:  "p",
}

File Detection

Compiles: *.wasm.go, frontend prefixes (f.*.go), modules/*/ Ignores: Backend prefixes (b.*.go), root main.go, non-Go files

DevTUI FieldHandler Interface

TinyWasm implements the DevTUI FieldHandler interface for interactive development:

// DevTUI Integration
label := tw.Label()           // "Compiler Mode"
current := tw.Value()         // Current mode shortcut ("c", "d", "p")
canEdit := tw.Editable()      // true
timeout := tw.Timeout()       // 0 (no timeout)

// Interactive mode change with validation
msg, err := tw.Change("d")
if err != nil {
    // Handle validation errors (invalid mode, missing TinyGo, etc.)
}
// msg contains success message or warning if auto-compilation fails

VS Code Integration

Auto-creates .vscode/settings.json with WASM environment:

{"gopls": {"env": {"GOOS": "js", "GOARCH": "wasm"}}}

API

Core:

  • New(config *Config) *TinyWasm
  • NewConfig() *Config - Pre-configured with sensible defaults
  • NewFileEvent(fileName, ext, path, event string) error
  • ShouldCompileToWasm(fileName, path string) bool

DevTUI FieldHandler Interface:

  • Label() string - Returns "Compiler Mode"
  • Value() string - Current mode shortcut ("c", "d", "p")
  • Editable() bool - Returns true (field is editable)
  • Change(newValue any) (string, error) - Switch compiler mode with validation
  • Timeout() time.Duration - Returns 0 (no timeout)

Legacy Compiler Methods (deprecated):

  • TinyGoCompiler() bool - Use Value() instead
  • SetTinyGoCompiler(bool) error - Use Change() instead
  • VerifyTinyGoInstallation() error

Utils:

  • MainFilePath() string
  • UnobservedFiles() []string
  • JavascriptForInitializing() (string, error)

Config

type Config struct {
    // Core settings
    WebFilesFolder func() (string, string) // web dir, public dir
    FrontendPrefix []string                // frontend prefixes
    Writer io.Writer                       // compilation output (renamed from Log)
    
    // 3-Mode System (NEW)
    CodingShortcut     string             // default: "c"
    DebuggingShortcut  string             // default: "d" 
    ProductionShortcut string             // default: "p"
    
    // Legacy/Advanced
    TinyGoCompiler     bool               // deprecated, use mode system
    Callback           func(string, error) // optional callback
    CompilingArguments func() []string     // compiler args
}

// Pre-configured constructor (recommended)
func NewConfig() *Config

Migration from v1:

// Old way (deprecated)
config.TinyGoCompiler = true

// New way (recommended)  
tw.Change("p")  // production mode with TinyGo -opt=z
tw.Change("d")  // debug mode with TinyGo -opt=1
tw.Change("c")  // coding mode with Go standard

Requirements

  • Go 1.20+
  • TinyGo (optional, required for debug/production modes)
  • DevTUI (optional, for interactive development)

Migration Guide

From TinyWasm v1.x:

Old API New API Notes
SetTinyGoCompiler(true) Change("p") Production mode
SetTinyGoCompiler(false) Change("c") Coding mode
TinyGoCompiler() Value() == "p" || Value() == "d" Check if using TinyGo
config.Log config.Writer Field renamed

Benefits of v2.x:

  • 🎯 3 optimized modes instead of binary choice
  • 🔧 DevTUI integration for interactive development
  • 📦 Smaller debug builds with TinyGo -opt=1
  • Auto-recompilation on mode switch
  • 🛠️ Better error handling with validation

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetModuleName

func GetModuleName(filePath string) (string, error)

GetModuleName extracts module name from file path

Types

type Config added in v0.0.7

type Config struct {
	// WebFilesFolder returns root web folder and subfolder eg: "web","public"
	WebFilesFolder func() (string, string)
	Logger         io.Writer // For logging output to external systems (e.g., TUI, console)
	FrontendPrefix []string  // Prefixes used to identify frontend files (e.g., "f.", "front.")
	TinyGoCompiler bool      // Enable TinyGo compiler (default: false for faster development)

	// NEW: Shortcut configuration (default: "c", "d", "p")
	CodingShortcut     string // default "c"
	DebuggingShortcut  string // default "d"
	ProductionShortcut string // default "p"

	// gobuild integration fields
	Callback           func(error)     // Optional callback for async compilation
	CompilingArguments func() []string // Build arguments for compilation (e.g., ldflags)
}

Config holds configuration for WASM compilation

func NewConfig added in v0.0.11

func NewConfig() *Config

NewConfig creates a TinyWasm Config with sensible defaults

type TinyWasm

type TinyWasm struct {
	*Config
	ModulesFolder string // default "modules". for test change eg: "test/modules"
	// contains filtered or unexported fields
}

TinyWasm provides WebAssembly compilation capabilities with 3-mode compiler selection

func New

func New(c *Config) *TinyWasm

New creates a new TinyWasm instance with the provided configuration Timeout is set to 40 seconds maximum as TinyGo compilation can be slow Default values: ModulesFolder="modules", mainInputFile="main.wasm.go"

func (*TinyWasm) Change added in v0.0.11

func (w *TinyWasm) Change(newValue any) (string, error)

RENAME: SetTinyGoCompiler -> Change (implements DevTUI FieldHandler interface)

func (*TinyWasm) GetTinyGoVersion

func (t *TinyWasm) GetTinyGoVersion() (string, error)

GetTinyGoVersion returns the installed TinyGo version

func (*TinyWasm) IsFrontendFile added in v0.0.4

func (w *TinyWasm) IsFrontendFile(filename string) bool

IsFrontendFile checks if a file should trigger WASM compilation based on frontend prefixes

func (*TinyWasm) JavascriptForInitializing

func (h *TinyWasm) JavascriptForInitializing() (js string, err error)

JavascriptForInitializing returns the JavaScript code needed to initialize WASM

func (*TinyWasm) Label added in v0.0.11

func (w *TinyWasm) Label() string

Label returns the field label for DevTUI display

func (*TinyWasm) MainFilePath added in v0.0.15

func (w *TinyWasm) MainFilePath() string

MainFilePath returns the complete path to the main WASM output file

func (*TinyWasm) Name added in v0.0.10

func (w *TinyWasm) Name() string

Name returns the name of the WASM project

func (*TinyWasm) NewFileEvent

func (w *TinyWasm) 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., web/public/wasm/main.wasm.go, modules/users/wasm/users.wasm.go, modules/auth/f.logout.go) event: type of file event (e.g., create, remove, write, rename)

func (*TinyWasm) ShouldCompileToWasm added in v0.0.4

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

ShouldCompileToWasm determines if a file should trigger WASM compilation

func (*TinyWasm) TinyGoCompiler

func (w *TinyWasm) TinyGoCompiler() bool

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

func (*TinyWasm) UnobservedFiles

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

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

func (*TinyWasm) Value added in v0.0.11

func (w *TinyWasm) Value() string

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

func (*TinyWasm) VerifyTinyGoInstallation

func (t *TinyWasm) VerifyTinyGoInstallation() error

VerifyTinyGoInstallation checks if TinyGo is properly installed

func (*TinyWasm) VerifyTinyGoProjectCompatibility

func (w *TinyWasm) VerifyTinyGoProjectCompatibility()

VerifyTinyGoProjectCompatibility checks if the project is compatible with TinyGo compilation

func (*TinyWasm) VisualStudioCodeWasmEnvConfig added in v0.0.7

func (w *TinyWasm) 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 (*TinyWasm) WasmProjectTinyGoJsUse

func (w *TinyWasm) WasmProjectTinyGoJsUse() (bool, bool)

WasmProjectTinyGoJsUse returns dynamic state based on current configuration

Directories

Path Synopsis
benchmark

Jump to

Keyboard shortcuts

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