GoWM Navigation

GoWM - Wasm Manager

v1.0.0

Cache Active

Documentation

Complete guide for WebAssembly integration

GoWM (Go WebAssembly Manager) is a TypeScript library that simplifies loading and using WebAssembly modules in your JavaScript/TypeScript projects. It provides type-safe APIs, GitHub integration, and framework-specific helpers.

Key Features

  • • Zero configuration setup
  • • Direct GitHub repository loading
  • • Full TypeScript support
  • • React hooks and Vue composables
  • • Automatic caching and optimization
  • • Universal runtime support (Browser, Node.js, Edge)

Installation

Add GoWM to your project

View on npm
bash
npm install gowm
bash
yarn add gowm
bash
pnpm add gowm

Quick Start

Basic usage examples with real function calls

javascript
import { load, loadFromGitHub } from 'gowm';

// Load from local file
const math = await load('./math.wasm', { name: 'math' });

// Load from GitHub
const githubMath = await loadFromGitHub('benoitpetit/wasm-modules-repository', {
  branch: 'master',
  name: 'math-wasm'
});

// Check available functions
const functions = math.call('getAvailableFunctions');
console.log('Available functions:', functions);

// Enable silent mode for cleaner output
math.call('setSilentMode', true);

// Call math functions - returns numbers or error strings
const result = math.call('add', 5, 3);
if (typeof result === 'string' && result.includes('Erreur')) {
  console.error('Error:', result);
} else {
  console.log('5 + 3 =', result); // 8
}

// Async calls for complex operations
const asyncResult = await githubMath.callAsync('multiply', 4, 7);
console.log('4 * 7 =', asyncResult); // 28

// Check if function exists before calling
if (math.hasFunction('factorial')) {
  const factorial = math.call('factorial', 5);
  console.log('5! =', factorial); // 120
}

GitHub Repository Loading

Load WASM modules directly from repositories with auto-discovery

javascript
import { loadFromGitHub } from 'gowm';

// Basic loading - auto-discovers wasm files
const basic = await loadFromGitHub('benoitpetit/wasm-modules-repository', {
  branch: 'master',
  name: 'math-wasm'
});

// GoWM tries these locations automatically:
// - main.wasm in module directories
// - GitHub releases

// Load different modules from the same repository
const imageModule = await loadFromGitHub('benoitpetit/wasm-modules-repository', {
  branch: 'master',
  name: 'image-wasm'
});

// Load QR module
const qrModule = await loadFromGitHub('benoitpetit/wasm-modules-repository', {
  branch: 'master',
  name: 'qr-wasm'
});

// Load crypto module
const cryptoModule = await loadFromGitHub('benoitpetit/wasm-modules-repository', {
  branch: 'master',
  name: 'crypto-wasm'
});

// Load goxios HTTP client module
const goxiosModule = await loadFromGitHub('benoitpetit/wasm-modules-repository', {
  branch: 'master',
  name: 'goxios-wasm'
});

React Integration

Built-in hooks for React with proper imports

tsx
import React, { useState, useEffect } from 'react';
import { useWasmFromGitHub } from 'gowm/hooks/useWasm';

function CalculatorComponent() {
  const { wasm, loading, error } = useWasmFromGitHub('benoitpetit/wasm-modules-repository', {
    branch: 'master',
    name: 'math-wasm'
  });
  const [result, setResult] = useState<number | string | null>(null);
  const [functions, setFunctions] = useState<string[]>([]);

  useEffect(() => {
    if (wasm) {
      // Enable silent mode for cleaner output
      wasm.call('setSilentMode', true);
      
      // Get available functions
      const availableFunctions = wasm.call('getAvailableFunctions');
      setFunctions(availableFunctions);
    }
  }, [wasm]);

  const calculate = async (operation: string, a: number, b: number) => {
    if (!wasm) return;
    
    try {
      const result = await wasm.callAsync(operation, a, b);
      
      // Handle different return types
      if (typeof result === 'string' && result.includes('Erreur')) {
        setResult(`Error: ${result}`);
      } else {
        setResult(result);
      }
    } catch (err) {
      setResult(`Error: ${err.message}`);
    }
  };

  if (loading) return <div>Loading WASM module...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h3>Available Functions: {functions.join(', ')}</h3>
      <button onClick={() => calculate('add', 5, 3)}>5 + 3</button>
      <button onClick={() => calculate('multiply', 4, 7)}>4 × 7</button>
      <button onClick={() => calculate('factorial', 5)}>5!</button>
      {result !== null && <div>Result: {result}</div>}
    </div>
  );
}

Building a WASM Module

Guidelines for creating GoWM-compatible WebAssembly modules

Go Code Structure

go
//go:build js && wasm

package main

import (
    "fmt"
    "syscall/js"
)

// Global configuration
var silentMode = false

// Required: setSilentMode function
func setSilentMode(this js.Value, args []js.Value) interface{} {
    if len(args) == 1 {
        silentMode = args[0].Bool()
    }
    return js.ValueOf(silentMode)
}

// Required: getAvailableFunctions function
func getAvailableFunctions(this js.Value, args []js.Value) interface{} {
    functions := []interface{}{
        "add", "subtract", "multiply", "divide", 
        "getAvailableFunctions", "setSilentMode",
    }
    return js.ValueOf(functions)
}

// Your custom functions here
func add(this js.Value, args []js.Value) interface{} {
    if len(args) != 2 {
        return js.ValueOf("Error: two arguments required for add")
    }
    
    a := args[0].Float()
    b := args[1].Float()
    result := a + b
    
    if !silentMode {
        fmt.Printf("Go WASM: %f + %f = %f\n", a, b, result)
    }
    return js.ValueOf(result)
}

func main() {
    fmt.Println("Go WASM Module initializing...")
    
    // Register ALL functions with JavaScript global scope
    js.Global().Set("add", js.FuncOf(add))
    js.Global().Set("getAvailableFunctions", js.FuncOf(getAvailableFunctions))
    js.Global().Set("setSilentMode", js.FuncOf(setSilentMode))
    
    // REQUIRED: Set ready signal for GoWM detection
    js.Global().Set("__gowm_ready", js.ValueOf(true))
    
    fmt.Println("Go WASM Module ready!")
    
    // Keep the program running
    select {}
}

Build Commands

bash
# Build for WebAssembly
GOOS=js GOARCH=wasm go build -o main.wasm main.go

# Optional: Optimize with wasm-opt (if available)
wasm-opt -Oz main.wasm -o main.wasm

API Reference

Complete function and method documentation

Core Functions

load(wasmPath, options?)

Loads a WASM module from a local file path.

Parameters:
  • wasmPath (string): Path to the .wasm file
  • options.name (string): Module name (default: 'default')
Returns:Promise<WasmBridge>

loadFromGitHub(githubRepo, options?)

Loads a WASM module from GitHub with automatic file discovery.

Parameters:
  • githubRepo (string): Repository ('owner/repo' or full URL)
  • options.name (string): Module name
  • options.branch (string): Git branch (default: 'master')

Troubleshooting

Common issues and solutions

Module loading fails

Ensure the WASM file exists and is accessible. Check network connectivity for GitHub loading.

Functions not available

Verify that functions are properly exported in your Go code using js.Global().Set(). Check the browser console for any JavaScript errors.

Performance issues

Consider using WebAssembly SIMD instructions for computationally intensive tasks. Profile your code to identify bottlenecks.

Build errors

Ensure you have the latest version of Go and that GOOS=js GOARCH=wasm environment variables are set correctly.

Need More Help?

Can't find what you're looking for? Check our GitHub discussions or open an issue.