toolchain.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //go:build !js
  2. // The generator runs the go toolchain to build the playground; it never
  3. // runs as WebAssembly itself, where starting processes is impossible.
  4. package main
  5. import (
  6. "fmt"
  7. "mime"
  8. "net/http"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "strings"
  13. )
  14. // buildWasm compiles the playground engine (./cmd/agiwasm) to WebAssembly
  15. // and copies the matching wasm_exec.js of the same Go toolchain next to it.
  16. func buildWasm(dir string) error {
  17. goBin, err := exec.LookPath("go")
  18. if err != nil {
  19. return fmt.Errorf("the playground needs the go command to build its WebAssembly (or pass -nowasm): %w", err)
  20. }
  21. abs, err := filepath.Abs(dir)
  22. if err != nil {
  23. return err
  24. }
  25. if err := os.MkdirAll(abs, 0o755); err != nil {
  26. return err
  27. }
  28. cmd := exec.Command(goBin, "build", "-trimpath", "-ldflags=-s -w", "-o", filepath.Join(abs, "agi.wasm"), "./cmd/agiwasm")
  29. cmd.Env = append(os.Environ(), "GOOS=js", "GOARCH=wasm")
  30. if out, err := cmd.CombinedOutput(); err != nil {
  31. return fmt.Errorf("building the playground WebAssembly failed: %v\n%s", err, out)
  32. }
  33. out, err := exec.Command(goBin, "env", "GOROOT").Output()
  34. if err != nil {
  35. return fmt.Errorf("go env GOROOT: %w", err)
  36. }
  37. root := strings.TrimSpace(string(out))
  38. for _, p := range []string{
  39. filepath.Join(root, "lib", "wasm", "wasm_exec.js"), // Go 1.24 and later
  40. filepath.Join(root, "misc", "wasm", "wasm_exec.js"), // earlier releases
  41. } {
  42. raw, err := os.ReadFile(p)
  43. if err == nil {
  44. return os.WriteFile(filepath.Join(abs, "wasm_exec.js"), raw, 0o644)
  45. }
  46. }
  47. return fmt.Errorf("wasm_exec.js not found under %s", root)
  48. }
  49. // serve hosts the docs folder for a local look. Pages, the worker and the
  50. // WebAssembly need http(s): browsers refuse workers on file:// pages.
  51. func serve(addr, docsRoot, sub string) error {
  52. _ = mime.AddExtensionType(".wasm", "application/wasm")
  53. fsrv := http.FileServer(http.Dir(docsRoot))
  54. h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  55. w.Header().Set("Cache-Control", "no-store")
  56. if r.URL.Path == "/" {
  57. http.Redirect(w, r, "/"+sub+"/", http.StatusFound)
  58. return
  59. }
  60. fsrv.ServeHTTP(w, r)
  61. })
  62. host := addr
  63. if strings.HasPrefix(host, ":") {
  64. host = "localhost" + host
  65. }
  66. fmt.Printf("Serving %s at http://%s/%s/ (Ctrl+C to stop)\n", docsRoot, host, sub)
  67. return http.ListenAndServe(addr, h)
  68. }