Files
zeekay 6b47025279 feat(runtime): embed goja + esbuild; add ZAP-over-HTTP transport
Establish zip as the canonical Hanzo Go web framework with embedded
in-process JS execution and a native ZAP RPC HTTP transport. One Go
binary mounts native handlers, legacy TS/JS handlers, WebSocket, and
the ZAP RPC plane — no separate runtime service, no inter-service RPC,
no container-per-service.

zip/runtime/ (new):
- jsvm.go    NewJSRuntime / Eval / RegisterHostFn / LoadModule, backed
             by a pool of *goja.Runtime (pure Go, no CGO). Pool pattern
             lifted from hanzoai/base/plugins/gojavm, slimmed to run +
             forEach so late host-fn / module registration reaches warm
             VMs.
- pool.go    fixed-size goja VM pool; saturated calls fall back to a
             fully-provisioned one-off VM.
- require.go CommonJS-style require(): per-VM module sources + memoized
             exports in a Go-side side-table (never visible to JS).
- esbuild.go TranspileToES5: TS/modern-JS -> goja-ready JS via esbuild's
             pure-Go API (ES2015 target, CommonJS format).
- handler.go JSHandler / JSModule: mount an Express-shaped (req, res) JS
             function as a fiber.Handler; req mirrors method/path/query/
             headers/body, res mirrors status/set/json/send.
- json.go    encode/decode through internal/jsonenc — one wire format.

zip/zaprpc/ (new on existing Registry seam):
- envelope.go canonical ZAP RPC frame (service/method/payload) over the
              zap-proto/go wire codec.
- http.go     HTTPHandler(reg): serves the ZAP RPC plane over HTTP POST;
              binary envelope canonical, X-ZAP-* headers are a hint only.

examples/express-in-zip/ (new): legacy app.ts -> real esbuild -> real
goja -> real Fiber -> real HTTP, with an integration test proving
GET /legacy/foo and POST /legacy/bar body echo.

README: embedded-JS migration path + single-binary (HIP-0106) sections.

go build ./... and go test ./... (incl. -race) pass.
2026-06-16 13:07:04 -07:00

121 lines
3.3 KiB
Go

package runtime
import (
"fmt"
"sync"
"github.com/dop251/goja"
)
// CommonJS-style module loading without an external dependency. Each VM
// gets a require(name) global backed by a per-VM registry of module
// sources and a memoized cache of evaluated module.exports. A module is
// evaluated the first time it is required, wrapped in the canonical
// CommonJS function scope:
//
// (function (module, exports, require) { <src> })
//
// so module source can do `module.exports = ...` or `exports.foo = ...`.
const requireRegistryKey = "__zip_modules__"
const requireCacheKey = "__zip_module_cache__"
// vmModules holds a VM's module sources and evaluated-exports cache. It
// lives in a Go-side side-table keyed by the *goja.Runtime pointer so it
// is never visible to (or mutable from) JS.
type vmModules struct {
mu sync.Mutex
sources map[string]string
cache map[string]goja.Value
}
var (
moduleTablesMu sync.Mutex
moduleTables = map[*goja.Runtime]*vmModules{}
)
func tableFor(vm *goja.Runtime) *vmModules {
moduleTablesMu.Lock()
defer moduleTablesMu.Unlock()
t, ok := moduleTables[vm]
if !ok {
t = &vmModules{sources: map[string]string{}, cache: map[string]goja.Value{}}
moduleTables[vm] = t
}
return t
}
// installRequire registers the require() global on vm and seeds it with
// the given module sources.
func installRequire(vm *goja.Runtime, modules map[string]string) error {
t := tableFor(vm)
t.mu.Lock()
for name, src := range modules {
t.sources[name] = src
}
t.mu.Unlock()
return vm.Set("require", func(name string) (goja.Value, error) {
return requireModule(vm, name)
})
}
// registerModule adds (or replaces) one module source on vm and
// invalidates any cached evaluation of it.
func registerModule(vm *goja.Runtime, name, src string) error {
t := tableFor(vm)
t.mu.Lock()
t.sources[name] = src
delete(t.cache, name)
t.mu.Unlock()
// Ensure require() exists even if the VM was built with no modules.
if v := vm.Get("require"); v == nil || goja.IsUndefined(v) {
return vm.Set("require", func(name string) (goja.Value, error) {
return requireModule(vm, name)
})
}
return nil
}
// requireModule resolves name to its module.exports, evaluating the
// source on first use and memoizing the result.
func requireModule(vm *goja.Runtime, name string) (goja.Value, error) {
t := tableFor(vm)
t.mu.Lock()
if cached, ok := t.cache[name]; ok {
t.mu.Unlock()
return cached, nil
}
src, ok := t.sources[name]
t.mu.Unlock()
if !ok {
return nil, fmt.Errorf("zip/runtime: module not found: %q", name)
}
// Wrap in the CommonJS scope and evaluate.
wrapped := "(function(module, exports, require){" + src + "\n})"
fnVal, err := vm.RunString(wrapped)
if err != nil {
return nil, fmt.Errorf("zip/runtime: load module %q: %w", name, err)
}
fn, ok := goja.AssertFunction(fnVal)
if !ok {
return nil, fmt.Errorf("zip/runtime: module %q did not compile to a function", name)
}
module := vm.NewObject()
exports := vm.NewObject()
_ = module.Set("exports", exports)
requireFn := vm.Get("require")
if _, err := fn(goja.Undefined(), module, exports, requireFn); err != nil {
return nil, fmt.Errorf("zip/runtime: eval module %q: %w", name, err)
}
result := module.Get("exports")
t.mu.Lock()
t.cache[name] = result
t.mu.Unlock()
return result, nil
}