| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- //go:build !js
- // The generator runs the go toolchain to build the playground; it never
- // runs as WebAssembly itself, where starting processes is impossible.
- package main
- import (
- "fmt"
- "mime"
- "net/http"
- "os"
- "os/exec"
- "path/filepath"
- "strings"
- )
- // buildWasm compiles the playground engine (./cmd/agiwasm) to WebAssembly
- // and copies the matching wasm_exec.js of the same Go toolchain next to it.
- func buildWasm(dir string) error {
- goBin, err := exec.LookPath("go")
- if err != nil {
- return fmt.Errorf("the playground needs the go command to build its WebAssembly (or pass -nowasm): %w", err)
- }
- abs, err := filepath.Abs(dir)
- if err != nil {
- return err
- }
- if err := os.MkdirAll(abs, 0o755); err != nil {
- return err
- }
- cmd := exec.Command(goBin, "build", "-trimpath", "-ldflags=-s -w", "-o", filepath.Join(abs, "agi.wasm"), "./cmd/agiwasm")
- cmd.Env = append(os.Environ(), "GOOS=js", "GOARCH=wasm")
- if out, err := cmd.CombinedOutput(); err != nil {
- return fmt.Errorf("building the playground WebAssembly failed: %v\n%s", err, out)
- }
- out, err := exec.Command(goBin, "env", "GOROOT").Output()
- if err != nil {
- return fmt.Errorf("go env GOROOT: %w", err)
- }
- root := strings.TrimSpace(string(out))
- for _, p := range []string{
- filepath.Join(root, "lib", "wasm", "wasm_exec.js"), // Go 1.24 and later
- filepath.Join(root, "misc", "wasm", "wasm_exec.js"), // earlier releases
- } {
- raw, err := os.ReadFile(p)
- if err == nil {
- return os.WriteFile(filepath.Join(abs, "wasm_exec.js"), raw, 0o644)
- }
- }
- return fmt.Errorf("wasm_exec.js not found under %s", root)
- }
- // serve hosts the docs folder for a local look. Pages, the worker and the
- // WebAssembly need http(s): browsers refuse workers on file:// pages.
- func serve(addr, docsRoot, sub string) error {
- _ = mime.AddExtensionType(".wasm", "application/wasm")
- fsrv := http.FileServer(http.Dir(docsRoot))
- h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Cache-Control", "no-store")
- if r.URL.Path == "/" {
- http.Redirect(w, r, "/"+sub+"/", http.StatusFound)
- return
- }
- fsrv.ServeHTTP(w, r)
- })
- host := addr
- if strings.HasPrefix(host, ":") {
- host = "localhost" + host
- }
- fmt.Printf("Serving %s at http://%s/%s/ (Ctrl+C to stop)\n", docsRoot, host, sub)
- return http.ListenAndServe(addr, h)
- }
|