# goesm architecture

goesm is a proof of concept for producing ES Modules from real Go packages: the current Go toolchain is the frontend, and goesm lowers Go semantics to a tree of ESM-ready TypeScript files, one per Go package, plus its runtime as TypeScript. Any ESM bundler (Vite, Rolldown, esbuild) or TypeScript-aware runtime (Bun, Node.js with type stripping) consumes that tree; `goesm build` bundles it with esbuild as a convenience.
It is not "a Go-like language compiled to JavaScript". There is no custom syntax, no custom module system and no custom type system.

## 1. Pipeline and responsibilities

```
.go / go.mod / go.sum / go.work
        │  go command + golang.org/x/tools/go/packages   (internal/loader)
        ▼
parse / package load / type check  ── go/parser, go/types (Go is the language authority)
        │
        ▼
Go semantic lowering                ── internal/lower   (the core of goesm)
        │
        ▼
TypeScript tree + @goesm/runtime    ── goesm emit-ts: <dir>/<import path>.ts, <dir>/@goesm/runtime/*.ts
        │  any ESM bundler (Vite / Rolldown / esbuild) or TS-aware runtime (Bun, Node.js)
        │  goesm build: esbuild Go API (internal/build), a convenience
        ▼
JavaScript ESM (+ source maps pointing at .go with goesm build)
```

| layer | owns | does not own |
|---|---|---|
| Go toolchain (`go list` / go/packages / go/types) | module and package resolution, go.mod / go.sum / go.work / GOPROXY, build constraints, parsing, type checking, constant folding, init order | — |
| goesm (`internal/lower`) | mapping Go semantics to TS + runtime calls, type metadata, blocking analysis, the first source map hop (TS→Go) | parsing, type checking, module resolution, JS printing |
| `@goesm/runtime` | Go semantics JS lacks (slices, maps, pointers, interfaces, panic, defer, channels, select, integer wrapping, type descriptors) | typing decisions (go/types settled them at compile time) |
| the host bundler or runtime (`goesm build`: esbuild's Go API) | TS syntax stripping, JS printing, target lowering, bundling, tree shaking, minification, code splitting, final source maps | any Go-semantic decision |

## 2. Repository layout

```
cmd/goesm/            CLI: goesm build / goesm emit-ts
internal/loader/      go/packages frontend and diagnostics (tagged go list / go/parser / go/types)
internal/natives/     goesm's Go-source replacements for standard library packages (runtime, reflect, internal/reflectlite, sync, syscall/js)
internal/lower/       typed AST → TypeScript lowering
  program.go          whole-program analysis (address-taken variables, blocking analysis)
  emit.go decl.go     package = one TS module, type descriptors, struct classes, method tables
  func.go stmt.go     function bodies and statements (defer, switch, select, range, range-over-func ...)
  expr.go types.go    expressions, conversions, operators, type descriptors / zero values
  writer.go           code writer with position markers (source locations kept during codegen)
internal/sourcemap/   TS→Go Source Map v3 builder
internal/build/       pipeline wiring, the module cache, writing the TS tree, esbuild Go API (goesm build) and its split-mode resolver
runtime/              @goesm/runtime (TypeScript), embedded into the goesm binary and written to <dir>/@goesm/runtime/
test/                 end-to-end tests (run in Node.js, golden comparison with native Go)
testdata/             fixture modules (plain Go modules: gofmt / go vet / go test work as usual)
docs/                 GopherJS comparison, example output
```

## 3. Frontend: the Go toolchain as is

* Packages are loaded with `golang.org/x/tools/go/packages` (`NeedSyntax|NeedTypes|NeedTypesInfo|NeedDeps`). Module resolution, `go.work`, `GOPROXY` and `go.sum` verification are all the go command's job; goesm reimplements none of it.
* Inputs are Go package patterns (`./main`, `example.com/app/...`). There are no custom imports such as `import "./foo.go"`.
* `-overlay file` (`build` / `emit-ts`) takes the go command's own overlay format (`go build -overlay`, `packages.Config.Overlay`): files that replace or add to the disk by absolute path, even in directories that do not exist. Hosts that embed Go in other files (gosfc for Vue SFCs) generate a Go file with `//line` directives and pass it this way; go/types diagnostics and goesm's source maps then point at the host file (`Summary.vue:17:21`), because positions are always taken through `token.FileSet.Position`, which honours `//line`.
* `-toolexec prog` (`build` / `emit-ts`, or `-toolexec` in `GOFLAGS`) plugs in tools that rewrite the source a compile sees, such as OpenTelemetry's compile-time instrumentation ([docs/otelc.md](https://goesm.dev/reference/otelc.md)). goesm runs `go list -deps -export` for the target with `prog` as the toolexec program and a recorder of its own in place of the compiler (`internal/toolexec`): the recorder notes the Go files of every compile, keeps those in the build's temporary directory, and runs the compiler. Recorded files that differ from the package's own become an overlay. The go command refuses overlays beneath `GOMODCACHE` (dependency modules, and the standard library of a toolchain downloaded through `GOTOOLCHAIN`), so for those files goesm lists the packages as they are on disk, parses the overlay's files instead, adds the added ones to their package, resolves the imports they add by package path, and type-checks the packages itself the way go/packages does (`loader/check.go`). Records are kept by compile action ID in the user cache directory, because the go command does not run tools for compiles it has cached; goesm marks the compiler version it reports so that these compiles are cached apart from ordinary builds.
* Target build constraints are `GOOS=js GOARCH=wasm`, the existing port closest to a JS host. `int` is type-checked as 64-bit.
* **No pinned Go version**: go/parser and go/types are linked into the goesm binary, so the newest syntax goesm understands is that of the toolchain goesm was built with. goesm is therefore meant to be built by the toolchain the module selects, via `go tool goesm` (a `tool` directive in go.mod) or `go run`. When the toolchain is newer than goesm, `loader.VersionHint` reports it. This PoC is built with Go 1.27 and its fixtures use Go 1.27 generic methods (`testdata/semantics/generics`).

## 4. Lowering from the AST or from x/tools/go/ssa

**Decision: lower directly from the typed AST (go/ast + go/types).** SSA is not used.

| criterion | typed AST | go/ssa |
|---|---|---|
| 1. keeping up with new Go syntax | anything go/types accepts is usable at once; a new construct needs one lowering case | waits for x/tools' SSA builder (generic methods, range-over-func etc. must be implemented there first) |
| 2. Go semantic accuracy | evaluation order, defer, named results must be handled explicitly | SSA already makes evaluation order explicit (an advantage) |
| 3. implementation size | structured control flow maps onto JS control flow directly | basic blocks + phis need a relooper/stackifier to get back to JS, which is large |
| 4. source locations | AST node positions are embedded as markers directly | positions per instruction are coarse and must be re-associated after restructuring |
| 5. future runtime semantics | async/await, try/finally and labeled break fit JS structure naturally | goroutine resume points push toward state machines |

The weakness in 2 is covered by spilling to temporaries in the lowering where evaluation order matters (multi-assignment, defer argument evaluation, evaluating a range expression once, ...). GopherJS also works from the typed AST.

## 5. Lowering

* **One Go package = one TypeScript module = one ES module.** `goesm emit-ts -o <dir>` writes the module of Go package `p` to `<dir>/<p>.ts` (`example.com/app/main.ts`, `strings.ts`, `internal/bytealg.ts`) and the runtime to `<dir>/@goesm/runtime/index.ts`, with the natives in `natives.ts` and the other runtime files next to them. This tree is goesm's primary output.
  * Modules import each other with relative specifiers ending in `.ts`: a Go import becomes `import * as mathx from "./mathx.ts"`, and the runtime is `import * as $rt from "../../@goesm/runtime/index.ts"` (`import * as $natives from "../@goesm/runtime/natives.ts"` in `internal/bytealg.ts`). A Go import path cannot start with `@`, so the runtime never collides with a package. No resolver is needed: TypeScript (`allowImportingTsExtensions`), Vite, Rolldown, esbuild, Bun and Node.js type stripping resolve these specifiers as they are.
  * `goesm build` (default) has esbuild bundle the tree into one file (`dist/main.js`), with no plugin.
  * `goesm build -split` emits one module per package, e.g. `dist/example.com/app/mathx.js`, plus `dist/@goesm/runtime/index.js` and `dist/@goesm/runtime/natives.js`. A small built-in resolver marks imports of other entry points (package modules and the runtime) as external and rewrites `.ts` to `.js`, so Go imports remain ESM dependencies such as `import * as mathx from "./mathx.js"`.
* **The JS calling ABI.** JavaScript calls the exported functions and methods of the entry package (the package a build starts from) through wrappers (`internal/lower/jsexport.go`) that convert the arguments from JavaScript and the results to JavaScript by the declaration's Go types, with the table `//goesm:import` uses the other way round (`runtime/src/jsabi.ts`): strings, slices as arrays, structs as plain objects, a final `error` thrown as a `GoError`. A pointer to a struct type with methods, a non-empty interface and a channel pass as the Go value, a handle; the struct classes of the entry package call the wrappers from their methods. Numbers are passed as they are, so a call with numbers costs a JS call, and strings are converted inline. Go code calls the functions themselves, and the module's `$goesm` table lists them with their type descriptors. The modules of other packages export Go's representation. [docs/js-exports.md](https://goesm.dev/reference/js-exports.md) is the user-facing description.
* Names: Go identifiers never contain `$`, so every name goesm introduces does (`User$type`, `User$Adult`, `$rt`, `$t3`). Each Go object within a function declaration gets a unique JS name, so Go shadowing never has to be reproduced with JS scoping rules.
* Constant expressions are emitted as the values go/types computed (iota, typed constants, `unsafe.Sizeof`, ...).
* Package variables are initialised in `types.Info.InitOrder` order, then `init()` runs, then `main()` if the entry package has `func main`. A variable whose initializer has no side effects (constants, composite literals and their addresses, function literals, other package-level variables and functions) is declared with it as a `/* @__PURE__ */` expression, and a defined type is declared with `$rt.defined`, a pure call whose callback sets up its underlying type and methods when the module calls `$rt.flushTypes()`: bundlers then drop the tables and types (with their methods) nothing uses. A library using only `strings.ToUpper` bundles to 88 KB (27 KB gzipped) instead of 363 KB, and `fmt`'s hello world to 132 KB gzipped instead of 222 KB. An effect analysis (`internal/lower/effects.go`) finds the other initializers with no effect besides computing their value, also through calls (writes to memory they allocate themselves, or to their locals), which are declared as pure expressions too, and the `init` functions that only assign package variables, which run only if reachable code (`internal/lower/reach.go`) uses one of those variables. An initializer without effects that reachable code never uses is left out: the TypeScript of a package run without a bundler would evaluate it. net/http's TLS defaults, crypto/tls's tables, nistec's P-256 table and x/text's normalization tables kept TLS, X.509 and elliptic curves in a Cloudflare Worker serving one Connect service; with them and the blocking analysis below limited to reachable code, its bundle went from 4.5 MB (1.18 MB gzipped) to 1.9 MB (457 KB gzipped).
* The generated code carries TypeScript types; Go typing is decided by go/types, and the types follow it. The whole tree (generated modules and runtime) type-checks under tsc in strict mode with `verbatimModuleSyntax` and `erasableSyntaxOnly`, so it also runs under type-stripping runtimes (Node.js 22.18+, Bun). `TestTSC` is a required CI check: it type-checks the fixtures and examples together with a consumer whose `@ts-expect-error` cases prove that exported Go APIs carry their Go types (`Total(items: $rt.S<Item>): number`, a blocking function returns `Promise<number>`). Exported signatures and struct classes are typed precisely; internal temporaries and wrappers are `any`, and a type parameter is typed by its constraint (core type, or `number` / `string`). Comparing results with native Go stays the semantic gate.

### Value representation

| Go | JS representation | notes |
|---|---|---|
| bool, float64 | boolean, number | |
| float32 | number (rounded with `Math.fround`) | |
| int8/16/32, uint8/16/32 | number, wrapped after every operation (`\|0`, `>>>0`, `<<24>>24`, `Math.imul`) | exact |
| int64, uint64 | bigint, wrapped with `BigInt.asIntN` / `asUintN(64, ...)` after every operation | exact |
| int, uint, uintptr | number | **inexact above 2^53, no 64-bit wrap-around** (known difference) |
| string | JS string with one code unit per byte | `len`, indexing, slicing, comparison and invalid UTF-8 match Go; converted at the JS boundary (export wrappers, `//goesm:import`) with `toJSString` / `fromJSString`, which pass an ASCII string unchanged (the runtime remembers the two latest strings found to be ASCII, so a string JS passes through `strings.ToUpper` and back is scanned once); `[]byte(s)` and `string(b)` of 64 bytes or more go through the engine's `TextEncoder` and windows-1252 `TextDecoder`, which treat ASCII as Go does, and fall back to a loop over the bytes otherwise |
| struct | instance of a generated class (`$clone` / `$set`) | value copies are inserted by the lowering; the object identity is the address. A range loop whose struct value variable is only read field by field loads those fields into locals instead of copying the element |
| array | JS array | copied explicitly, like structs |
| slice | `Slice{$array,$offset,$length,$capacity}`, nil is `null`; `$array` is a JS array, or a `Uint8Array` for a `[]byte` made by `make`, `append` or `[]byte(s)` (slices of Go arrays and literals keep JS arrays); one of 65 bytes to 4 KiB is a view into a shared 16 KiB slab, since V8 allocates the store of a larger `Uint8Array` outside its heap at 1-3 µs each. A local `[]bool` variable whose value never leaves its function (only made, indexed, passed to `len`/`cap`) is also backed by bytes, a quarter of the memory of an array of booleans, its loads are converted back to booleans (inline `!!b[i]`: V8 ran a sieve 1.5× slower through a helper) and its stores write 1 or 0. `s[i]` has an inline bounds check, left out where the index is in range by construction (`for i := range s`, `for i := lo; i < len(s); i++` with `lo >= 0`, `i < n` after `s := make([]T, n)`, or `for i := range n` and `i < n` after `n := len(s)`, `s`, `n` and `i` not otherwise assigned). An array element needs none for a byte index into a table of 256, a masked index such as `x&0xff`, or the index of a loop over an array or up to a constant no larger than the array. In a backing array of structs or arrays, the elements beyond the length of every slice of it are made when a slice first reaches them (reslicing, `append`, `unsafe.Slice`), so `append` to `make([]T, 0, n)` or to a grown slice makes each element once | append / re-slice aliasing as in Go |
| map | `GoMap` over a JS `Map`, nil is `null`: boolean, integer, string and channel keys are the `Map`'s keys (its equality is Go's for them) with the values directly; other keys are hashed with Go equality to `[key, value]` entries | struct / interface / NaN keys, nil-map panics |
| pointer | `*struct` / `*array` is the object itself; otherwise an object with a `.v` accessor (`Cell` / `FieldPtr` / `IndexPtr`) | `&x == &x` and `&s.f == &s.f` guaranteed by caching |
| interface | an object with `t` (type descriptor) and `v` (value), nil is `null`: an instance of the dynamic type's box class, or a plain `Iface` (below). A struct value's box is a struct object of a subclass of the struct's class, whose prototype has `t` and a `v` that is the object itself: boxing allocates one object. Likewise a pointer to a struct whose type has a box class is its own interface value: the struct class's prototype has the pointer type's `t`, `v` and methods, and the conversion allocates nothing. For other pointers to structs, interface values never change, so the one made last from a pointer is kept on the struct (under a symbol) and converting the same pointer again allocates nothing | keeps the dynamic type: `MyInt(1)` ≠ `int(1)`, an interface holding a nil `*T` is non-nil |
| func | JS function | |
| chan | runtime `Chan` | |
| type parameter | the representation of its type argument (erasure) | type descriptors arrive as dictionary parameters |

### Several results

A function with several results that does not block returns its first result and leaves the others in the runtime's result registers, `$rt.$R.r1`, `$rt.$R.r2` and so on (`runtime/src/results.ts`). The caller reads them right after the call, before anything else can run Go code: `n, err := parse(s)` becomes `const $1 = parse(s); let n = $1; let err = $rt.$R.r1;`, and `return n, nil` becomes `return ($rt.$R.r1 = null, n)`. Comma-ok forms of map lookups and type assertions work the same way (`$rt.mapLookup`, `$rt.assertOk`). A return statement whose values call Go code evaluates them in order into temporaries before it sets the registers, and `return f()` passes the results of a call with the same result types on as they are. An array of the results would be allocated at every call that V8 does not inline: `strconv.Atoi`-style parsing loops, `utf8.DecodeRuneInString` loops and comma-ok map lookups ran 1.2 to 1.5 times as fast with registers on Node and Bun.

A function that blocks (an async function) still resolves to an array of its results, since other goroutines run before its caller resumes and could overwrite the registers. The caller moves them into the registers when the await returns (`$rt.untuple(await f())`), so code after a call looks the same whichever kind of function it called; this is also what makes a call through a function value or an interface method, which may be either, work. Natives return arrays too, which the function wrapping a native moves into the registers. JavaScript sees neither form: export wrappers return several results as an array, and the `$goesm` table's `tuple` collects them for the test harness.

### 64-bit integers

`int64` and `uint64` are BigInts; `int`, `uint` and `uintptr` stay JS numbers. Explicit 64-bit types are where Go code needs all 64 bits (hashes, random numbers, `time` nanoseconds, IDs in JSON, `math.Float64bits`), while `int` indexes and counts, where a number is several times faster and exact for anything an array or string can hold.

Arithmetic is inline (`BigInt.asIntN(64, a * b)`), which V8 compiles to machine arithmetic; division, remainder and shifts call small runtime helpers (divide-by-zero panic, Go's shift semantics). Conversions between the two worlds are explicit (`BigInt(i)`, `Number(x)`); converting an `int64` beyond 2^53 to `int` rounds. Exported functions take and return `bigint` for these types.

`bench/int64.mjs` compared the representations goesm could lower to, on four workloads written as goesm would emit them (best of 5, Node 22 / Bun 1.3):

| workload | number (inexact) | BigInt | `{hi, lo}` object | two uint32 locals | number, BigInt beyond 2^53 |
|---|---|---|---|---|---|
| counter and sum (small values) | 13 / 6 ms | 136 / 1003 ms | 260 / 397 ms | 141 / 55 ms | 124 / 30 ms |
| FNV-1a 64 over 4 MiB | 38 / 32 ms | 35 / 498 ms | 170 / 241 ms | 104 / 101 ms | 306 / 849 ms |
| xorshift64* | n/a | 209 / 684 ms | 97 / 273 ms | 113 / 86 ms | n/a |
| Unix nanoseconds (add, div, mod) | 13 / 45 ms | 41 / 296 ms | 758 / 978 ms | 306 / 845 ms | 147 / 359 ms |

On V8 (Chrome, Node, Deno) BigInt is the fastest exact representation in three of four workloads and close to plain numbers for hashing. On JavaScriptCore (Safari, Bun) it is 3 to 18 times slower than two uint32 halves. Halves would double every `int64` variable, field, parameter and result in the lowering and in the JS API. BigInt keeps the lowering and the exported API simple and is exact everywhere, so it is the representation.

Hot local arithmetic takes the halves path anyway, without changing the value representation. `internal/lower/split64.go` implements it. An `int64` or `uint64` local whose arithmetic in its deepest loop outweighs its conversions is held as two int32 locals, `x$hi` and `x$lo`. Addition, subtraction, multiplication, the bitwise operators and constant shifts on it compile to int32 arithmetic and `Math.imul`, and it becomes a BigInt only where its value leaves the function's arithmetic: a call, a store, a return. This way FNV-1a 64 takes about 1.3× native Go's time on V8 and JavaScriptCore alike. A run of statements that only assign one `int64` or `uint64` field of a local variable from that field, locals and constants, as in xorshift, likewise works on a local copy of the field and stores it back once after the run (`internal/lower/fieldpromo.go`). `GOESM_SPLIT64=off` turns the lowering off and `GOESM_SPLIT64=all` applies it to every candidate, for tests.

### Type metadata

Every named type has a runtime descriptor (`$rt.named(pkgPath, name)`) with its underlying type, fields (name, pkgPath, tag, embedded) and value / pointer method sets (method names and signature descriptors). Composite types (`[]T`, `map[K]V`, `func(...)`, `struct{...}`, `interface{...}`) are memoized by structure, so **descriptor identity is Go type identity**. Interface checks use these method tables and never rely on TypeScript structural typing. Unexported methods are qualified with their pkgPath. A call through an interface is a call of the interface value's method with the interface value as the receiver argument (`x.$M(x, ...)`), so each call site has its own inline cache for the few types flowing through it. A non-generic package-level type with methods called through interfaces has a box class, whose prototype holds the type's method functions themselves where the interface value is the value (struct values and pointers to structs; boxes holding the value have methods that unwrap it), so like a JS class method the lookup resolves per hidden class to a known function, which the engine can inline (`internal/lower/box.go`). The interface values of other types (generic or unnamed types, the runtime's) are plain `Iface`s, whose methods call through the type's method table (`t.mt`). As with Go's linker, a table lists only the methods that can be called dynamically: those whose name and signature belong to an interface type of the program (plus `String() string`, which the runtime prints panics with), or every exported method when the program enumerates methods by reflection (`Method`, `MethodByName`, `NumMethod`); reachable code calling `Method` or `MethodByName` keeps the functions of the exported methods of the types stored in interface values, and only of those of its name for `MethodByName` with a constant name, as protobuf's descriptor formatting calls `Get`. Other methods are referenced only by the code that calls them, so bundlers drop the unused ones; a table listing all 47 methods of `time.Time` kept `Format` and the encoders in any program using `time` (`internal/lower/methods.go`). A listed method keeps its function only if reachable code calls it through an interface (`internal/lower/reach.go`), and a type that reachable code never stores in an interface value has an empty table, since no interface value ever has it as its dynamic type: the signatures of its methods would keep the types they mention. Reachable code starts from the functions of the entry packages, package initialization and the methods JavaScript calls on handles; the other packages of the program's module count only for what the entries use, so the client half of a generated connect-go package stays out of a server. The runtime itself calls `Error` and `String` only on a value it prints as a panic or hands to JavaScript, so a program that calls `strconv.Atoi` and only compares the error with nil leaves out `NumError.Error`, with `strconv.Quote` and its tables. For the same reason the classes of struct types have JS methods only in the entry package, where they are the API (the JS calling ABI).

### Generics: type erasure + runtime type dictionaries

* One copy of each function or method is generated (erasure); type arguments are passed as leading **dictionary parameters** holding runtime type descriptors: `First($T_T, values)`.
* With descriptors available, zero values (`var x T`), interface conversion (`any(x)`), `==`, aggregate copies, `new(T)` and `make([]T)` all behave correctly for each type argument.
* Instances of generic types (`Stack[Pair[string,int]]`) are memoized descriptors too, so `a.(Pair[string,int])` and `a.(Pair[string,string])` are told apart.
* Go 1.27 generic methods receive the receiver's type arguments, then the method's own. They cannot satisfy interfaces, so they are not in method tables.
* Why: specialization multiplies code per type argument, which is bad for JS bundles. Keeping only TS generics leaves no type information at run time, so zero values, interface conversion and reflect would be impossible. Erasure + dictionaries is the same idea as gc's GC-shape stenciling with dictionaries; it is the simplest option and leads to reflect. `<T>` is kept in the TS for readability only.

### defer / panic / recover

```ts
function F() {
  let $r0 = zero;                 // result variables (named results keep their names)
  const $d = new $rt.Defers();
  $body: try {
    ...; $r0 = expr; break $body; // return assigns results, then defers run
  } catch ($e) { $d.fail($e); } finally { $d.run(); }
  return $r0;                     // returns values the defers may have changed
}
```

* A panic throws a `GoPanic` (a JS Error). The panic value is kept as an interface value; runtime errors have types implementing `runtime.Error` (`Error()` / `RuntimeError()`). A JS `TypeError` (touching null) becomes the nil pointer dereference runtime error. Field and element accesses through pointers (`p.f`, `*p`, `p[i]` on `*[N]T`) rely on that instead of an explicit nil check, which costs V8 its fast property access; the entry package's exported functions and methods, and Go functions called back from JS, are wrapped so that JS still sees a `GoPanic`.
* The function value and arguments of a deferred call are evaluated at the defer statement and captured in a closure.
* recover() recovers only in the deferred function itself. Each deferred call records which function it calls when that is known statically (a function, a method of a concrete type, a function literal, the `recover` builtin), and a function that calls recover() asks on entry whether it is that call (`const $rf = $rt.recoverFrame("main.F")`; a recursive call is not). The answer is the frame whose panic recover() then recovers, so it also works after an await. A deferred `recover()` is called by the function that defers it.
* From JS, an unrecovered panic is a `GoPanic` exception; with `--enable-source-maps` its stack points at `.go` lines (tested).

### goroutines / channels / select

* **Blocking analysis** (whole program): a function is blocking if it contains channel operations (other than the cases of a select with a default), a select without default, a range over a channel, a call or defer of a blocking function, or a dynamic call that may reach one. Blocking functions become `async function`s and every blocking point is an `await`; all other functions stay synchronous (no await cost). Dynamic calls are resolved conservatively: a call through a function value may reach any function of the same signature that is used as a value somewhere (a function literal not called in place, or a function or method referenced other than as a callee). A call of a variable of function type that is only ever assigned function literals, declared functions or nil, and whose address is never taken, reaches only those (`internal/lower/funcvars.go`): a component's `update := func() {...}` stays synchronous in a program where some other `func()` value blocks. An interface method call may reach the method of that name of any type that can be stored in an interface value and implements the interface: the types converted to an interface type somewhere (assignment, argument, return, composite literal element, send, map key, explicit conversion, `append`, `panic`), the type arguments of every instantiation, and the types reachable from those through fields, elements and pointers (for reflection). So `io.PipeWriter.Write`, which blocks, does not make every `io.Writer.Write` call async, and `fmt.Println` stays synchronous unless the program stores a pipe in an `io.Writer`. A method called through an interface that embeds the interface declaring it counts by the outer interface: `hash.Hash`'s `Write` reaches the hashes, not every `io.Writer`. Blocking can also depend on the arguments. The parameters of interface or function type that a declared function never assigns or takes the address of are tracked, with the methods it calls on them, directly or by passing them on to such parameters. A function that blocks only through those calls gets a synchronous clone, `F$sync`, and a call whose arguments cannot block there calls the clone: a `*strings.Builder` passed to `fmt.Fprintf` as its `io.Writer`, or a function literal that does not block passed as a `func()`. So `fmt.Sprintf` and the `Formatter`s it calls stay synchronous although the program writes to a pipe with `fmt.Fprintf`. A function parameter that is only called, compared with nil and passed on as such a parameter does not escape. The function literals, functions and method values passed for it at the function's static calls, directly or through a local variable used only that way like the one `sync.OnceFunc` passes to `Once.Do`, are then not function values, and a call through the parameter blocks only if one of those arguments may. When the function is also called through a function value or an interface, from a `go` statement or from a package variable initializer, any function value of the parameter's type counts as well. A range-over-func body is the yield function passed to the iterator: if it may block it becomes an async callback, and the analysis counts it as a function value of the yield type, so the iterators that may call it await it. Once the entry packages are known, the analysis is redone for the code reachable from them (`refineBlocking` in `internal/lower/program.go`): an interface call then reaches only the methods of the types that reachable code stores in interface values, a call through a function value only the function values of reachable code, and a tracked parameter only the arguments of reachable calls. Code that cannot run cannot make other code wait: in a Worker serving Connect requests, the `io.Pipe` of connect-go's client streams and net/http's client made `io.Reader`'s `Read` block, and through protobuf's `Format` methods every `fmt.Sprintf`, although the Worker never runs that code. Unreachable code keeps what the first analysis decided.
* **Mutexes**: a goroutine can only find a `sync.Mutex` locked if the holder is blocked, so `Lock` is synchronous and never waits. goesm finds the critical sections a blocked goroutine may hold: from a `Lock` to the matching `Unlock` in the same block (or to the end after `defer Unlock`, or, for a `Lock` in an `if` branch or block without an `Unlock`, on to the first later statement of an enclosing list that unlocks it, as in `if c { mu.Lock() }; ...; if c { mu.Unlock() }`) when a blocking operation lies in between, and every `Lock` without a matching `Unlock` or with a path (`return`, `panic`, `runtime.Goexit` or a call of a function that may call it, a `break`, `continue` or `goto` out of the block) that leaves before reaching it. A section locks its mutex either directly, by a variable or struct field path (the mutex's key), or indirectly: through a pointer, a `sync.Locker` (also a type parameter constrained by it), or with no name such as `f().Lock()`. A direct `Lock` / `RLock` becomes the waiting (async) `lockSlow` / `rLockSlow` if its key has such a section, or if an indirect section exists and the key's mutex escapes (its address is taken, it is used as a method value or through `RLocker`, or it is embedded in a type stored in an interface). An indirect one waits if any indirect section exists or a held key escapes; `Locker.Lock` then becomes `lockerSlow`, which waits for the mutexes of package `sync` and calls other Lockers, retrying after the next unlock when such a Lock is an embedded mutex's and finds it held. This repeats with the blocking analysis until nothing changes. Method expressions such as `(*sync.Mutex).Lock(&mu)` count like `mu.Lock()`, except for a method promoted from an embedded mutex. Sections that statements do not delimit count as held: a `TryLock`, a `Lock` in an `if` / `switch` initializer or a deferred one, and a `Lock` method value (`lock := mu.Lock`). A `Lock` method value or method expression value that may have to wait by the same rules is bound to the waiting variant; calls of function values of its type (`func()`, `func(*sync.Mutex)`) are then async. A blocking operation in a `go` statement's function value or arguments counts, since they are evaluated by the goroutine running the statement. Package `sync`'s own locking (`Cond.Wait`, `RLocker`) is left out of the analysis.
* `go f(x)` evaluates the function value and arguments in place; `$rt.go(closure)` starts it as a microtask.
* Channels are a buffer plus send/receive wait queues in the runtime. An operation that can complete immediately returns synchronously; only a blocking one returns a Promise. Implemented: unbuffered handoff, close (including panicking blocked senders), and `select` (uniformly random among ready cases, default, nil channels block forever).
* So "converting to async/await makes it Go" is not the assumption. Blocking semantics live at the runtime boundary (the wait queues); async/await is only the mechanism to suspend and resume a goroutine. `runtime.Goexit` (deferred calls run, `recover` does not stop it) and the `sync` replacement (§9) are built on it; deadlock detection, goroutine-local panic state and timers will be too.
* JS boundary: a blocking exported function returns a Promise (`await Example()` is 42).
* **Programs**: the main package's module runs `main` through `$rt.runMain`. As in Go, the process exits when `main` returns (also with other goroutines still running), `os.Exit` exits with its code without running deferred calls, and a panic nothing recovers prints `panic: ...` and `goroutine 1 [running]:` with the JS stack to standard error and exits with status 2. That includes a panic while a package is initialized: the main module first imports `@goesm/runtime/program.ts`, which turns an uncaught exception into the same crash, so it also covers the variable initializers and `init` functions of every dependency. `runtime.Goexit` in `main` ends only the main goroutine; once the others are done, the program reports `fatal error: no goroutines (main called runtime.Goexit) - deadlock!`. If the host's event loop runs dry while `main` is still blocked (Node's and Bun's `beforeExit`; an exit JavaScript code asks for is not one), no goroutine can be woken any more: goesm prints Go's `fatal error: all goroutines are asleep - deadlock!` and exits with status 2. `program.ts` starts this watch too, so an `init` function that blocks forever is reported the same way under Node; Bun keeps spinning on a top-level `await` that never settles, so there such a program hangs. In browsers, which have no process, an unrecovered panic is reported with `reportError`, a blocked `main` simply stays blocked, and `os.Exit` unwinds the goroutine without running deferred calls (nothing can recover it).

### Incremental builds: the module cache

Lowering the packages is the largest part of a build's time: for goesm.dev's `site` package (77 packages, most of them from the standard library), loading and type-checking take about 0.28 s, the whole-program analysis about 0.23 s and lowering about 0.64 s. `internal/build` therefore keeps each package's module in a cache (`internal/build/cache.go`) and lowers only the packages whose key is not in it. The frontend and the analysis still run on every build: what a package's module looks like depends on the whole program, since a function becomes async when a function value of the same signature anywhere may block, and a package variable needs a `Cell` when another package assigns it.

The key of a package's module covers the goesm executable (the lowering, the runtime and the natives are part of it), `GOESM_SPLIT64`, whether the package is the entry, and, for the package and every package it depends on, the import path, the files (name, Go version and content) and a digest of the analysis results that lowering reads (`lower.Program.Facts`). That digest holds what the analysis decided about the functions, function literals, range-over-func statements and variables the package declares (async, synchronous-only, with a synchronous clone, boxed, linkname pulls and providers), and the answers to the questions the lowering asks about the package's own nodes (`CallBlocks`, `RangeBlocks`, `WaitLock`, `WaitLockVal`, `SyncClone`). Positions in it are offsets within files, so an edit changes the digests of the packages it affects and of no others. `TestFactsCoverProgram` fails when the lowering starts reading a part of `Program` the digest does not cover. Warnings produced while lowering a package are kept with its module.

The cache lives in `goesm/modules` below the user cache directory, or in `$GOESMCACHE`; `GOESMCACHE=off` disables it. As in the go command's build cache, entries unused for five days are removed. A rebuild of goesm.dev's `site` after editing one package takes 0.7 s instead of 1.2 s, and `astro build` of the whole site 8.7 s instead of 11.1 s. `TestModuleCache` checks that the modules taken from the cache are byte for byte the ones lowering produces, also for the standard library modules other programs stored, and `TestModuleCacheFollowsFacts` that a change in one package re-lowers a dependency whose facts it changed.

## 6. Runtime (`runtime/src`, emitted as `<dir>/@goesm/runtime/*.ts`)

| file | responsibility |
|---|---|
| `types.ts` | type descriptors (reflect.Kind numbering, memoized named / composite types, method tables, generic instances, `error`) |
| `iface.ts` | interface values, box / assert / type switch (a case of a concrete type compares the dynamic type, loaded once), `==`, map hash keys |
| `slice.ts` | slices, append / copy / bounds checks, indexing type parameters without a core type |
| `map.ts` | Go maps |
| `ptr.ts` | Cell / field pointers / element pointers, load / store through type parameters |
| `string.ts` | byte strings ⇔ UTF-8 / runes, JS boundary conversion |
| `int.ts` | integer division and remainder (divide-by-zero panic), shifts, 64-bit bitwise ops, min / max |
| `panic.ts` | GoPanic, runtime error types, Defers, recover |
| `chan.ts` | channels, select, goroutine start and count, running `main` (exit status, crash output, deadlock) |
| `complex.ts` | complex numbers |
| `host.ts` | standard output and error (Node / Bun / Deno `fs` write, or the console in browsers), process exit |
| `print.ts` | the `print` / `println` builtins in the Go runtime's format |
| `natives.ts` | standard library functions without a Go body (§9); a separate module, imported only by the standard library modules that need it, with one export per function so tree shaking drops the unused ones |
| `fmt.ts`, `json.ts` | the fast paths of `fmt.Sprintf` and of `encoding/json`'s `Marshal` and `Unmarshal`, imported by `natives.ts`; like it, they use the runtime only through `index.ts`, so that a `-split` build keeps one runtime |
| `interop.ts` | Go value → JSON-shaped JS value guided by descriptors (golden tests) |
| `jsabi.ts` | Go ⇔ JS value conversion for `//goesm:import` ([docs/js-imports.md](https://goesm.dev/reference/js-imports.md)); the lowering converts strings, numbers and flat structs inline and calls `goToJS` / `jsToGo` with the descriptor for the rest |

Only what the fixtures need is implemented; no scheduler or reflect was built ahead of time.

## 7. reflect / unsafe / memory representation

* **reflect**: codegen always keeps named type identity, field names, tags and embedding, method sets (names and signatures) and type arguments in runtime descriptors, and `Kind` uses reflect's numbering. Package `reflect` is replaced by Go source over them (§9): a `reflect.Type` is the descriptor of an interface value, and a `reflect.Value` is (descriptor, value), or (descriptor, goesm pointer) when it is addressable, so `Set` writes through the pointer. Building on that, `fmt` and `encoding/json` (Go 1.27's json v2 underneath, or the encoder and decoder of its own implementation, below) compile from their own Go source. What needs memory addresses (`UnsafeAddr`, `NewAt`, `StructOf`) panics, `Value.Call` of a function that blocks panics, and channel operations through reflect work only when they do not block.
* **Pointer representation**: currently "aggregates are the object itself, everything else is an accessor object". All pointer creation goes through `ptr.ts`, so the representation can be replaced when `unsafe.Pointer` interop arrives.
* **unsafe / linear memory**: the architecture does not close with "JS has no pointers, so unsupported". The planned direction, step by step: (1) back numeric slices such as `[]byte` with TypedArrays (the slice backing store is private to `slice.ts`); (2) represent `unsafe.Pointer` as a tagged (ArrayBuffer, byte offset) or (object, field) value and implement `unsafe.Slice` / `unsafe.String` / `unsafe.Add` on DataView; (3) lay out structs in linear memory (ArrayBuffer) only for packages that need it. Today:
  * an `unsafe.Pointer` holds the pointer object itself, so `*T` → `unsafe.Pointer` → `*T` is the identity (`strings.Builder`, `sync/atomic.Pointer`, `internal/race` rely on it);
  * `unsafe.String(&b[i], n)`, `unsafe.String(unsafe.SliceData(b), n)`, `unsafe.Slice(&a[i], n)` and `unsafe.SliceData(s)` work on slice and array elements (a slice over the same backing array); `unsafe.Slice(unsafe.StringData(s), n)` copies, which is unobservable because the bytes are immutable;
  * `unsafe.Sizeof` / `Alignof` of a type parameter are computed from the descriptor with the wasm sizes;
  * pointers keep their provenance: `unsafe.StringData(s)` remembers its string, `unsafe.SliceData` its backing array, so `unsafe.String` and `unsafe.Slice` of them (and of a pointer to a single variable) work;
  * reinterpreting memory (`(*T)(unsafe.Pointer(&u))` with a different `T`) works for the layouts libraries such as protobuf rely on (`runtime/src/unsafe.ts`): a pointer variable read as another pointer type (`(*unsafe.Pointer)(unsafe.Pointer(&p))` for `sync/atomic`), structs with the same layout, and header structs that mirror a string (`{data, len}`), a slice (`{data, len, cap}`, read-only) or an empty interface (`{type, data}`), which become views of the value. A `[]byte` variable read as a `string` (`*(*string)(unsafe.Pointer(&b))`, the zero-copy idiom of older libraries) and a `string` read as a `[]byte` are copies, taken at each read; Other reinterpretations are goesm diagnostics (in a dependency, the function becomes a stub, §9); `uintptr(unsafe.Pointer(p))` is a stand-in address, stable and distinct per pointer, which is enough for printing (`%p`) and identity maps, and converts back to the same pointer while it is live;
  * pointer arithmetic on field offsets, as protobuf-go's generated-message fast path does it (`unsafe.Pointer(uintptr(p) + off)`, `unsafe.Add`): the result is an (object, byte offset) address into the struct or array `p` points into, and converting it to `*T` finds the field or element at that offset in the wasm layout `reflect` reports (`StructField.Offset`), descending into nested structs and arrays. A struct's first field is the struct itself (protobuf's `messageState` trick), `reflect.NewAt` takes such addresses, a `[]*T` field read as a slice of structs holding only a pointer (protobuf's `[]pointer`) is a view that wraps and unwraps its elements, and `unsafe.Pointer` comparisons compare addresses. An offset into the middle of a field, or reading a field as a type of another layout, panics. In the standard library the few functions that do this are natives instead (`math.Float64bits`, `slices.overlaps`, ...).

## 8. Source maps and diagnostics

* The lowering embeds Go position markers in expression and statement strings; the writer records a mapping once the output column is known. Location information is never dropped during codegen.
* Each generated TS module carries an inline TS→Go Source Map v3 (`emit-ts` also writes it next to the module as `<p>.ts.map`). In `goesm build`, esbuild reads it and composes the final **JS→.go** map (with Go source in `sourcesContent`). Other bundlers do not necessarily compose it: with Vite 8.3 and Bun 1.3 the final map points at the generated `.ts` files. A test checks that with Node's `--enable-source-maps` a panic's stack points at `panics.go:NN`.
* Diagnostics are tagged by layer:
  * `file.go:4:17: ... [go/types]` / `[go/parser]` / `[go list]` — errors from the Go frontend, at the original `.go` position.
  * `file.go:6:9: reinterpreting *int64 as *[2]int32 through unsafe.Pointer is not supported [goesm lowering]` — a goesm limitation, shown separately from Go compile errors.
  * In standard library packages, a function goesm cannot lower yet is not an error: it becomes a stub that panics if called (`goesm: <func> is not supported yet`), and the CLI reports how many there are (`-v` lists them with the first reason). Most programs never reach them (`internal/abi`'s gc type layout, complex numbers, ...); tree shaking drops the unreached ones.
  * `internal error: esbuild rejected TypeScript generated by goesm ... [esbuild]` (`goesm build`) — a goesm bug, never disguised as a Go error.

## 9. Standard library

The policy is to compile the ordinary Go source, not to port packages to TS by hand. Like GopherJS's natives, a few packages tied to the gc runtime have target-specific replacements, but goesm keeps them as **Go source** (`internal/natives/goroot/<import path>/`):

| replaced package | replacement |
|---|---|
| `runtime` | the exported API other packages use (`GOOS`, `Error`, `Goexit`, `Gosched`, `KeepAlive`, `Caller`, `MemStats`, ...); scheduling and memory stay in `@goesm/runtime` |
| `reflect` | the full API (types, values, `Set*`, `Call`, `MakeFunc`, maps, slices, `Convert`, `DeepEqual`, `VisibleFields`, ...) over the runtime type descriptors; enough for `fmt` and `encoding/json` |
| `internal/reflectlite` | `Type` = a runtime type descriptor, `Value` = (descriptor, value or pointer); enough for `errors.Is` / `errors.As`, `sort.Slice`, `context` |
| `sync` | `Mutex` and `RWMutex` lock synchronously, and wait (async) only for the mutexes held across a blocking operation (§5); `WaitGroup` and `Cond` wait on channels; `Once`, `Map`, `Pool` are plain Go |
| `syscall/js` | the js/wasm `syscall/js` API over the JS values themselves (a `Value` holds the value). goesm compiles the standard library for js/wasm, so `os`, `syscall` and `time` reach the host through it: `js.Global().Get("fs")` is always goesm's own file system with the callback API package `syscall` expects, calling back before it returns (over `node:fs` in Node, Bun and Deno, a console-backed stand-in in browsers), whatever `globalThis.fs` holds, so `os.Stdout` and `os.Stderr` work everywhere and do not make callers async; `process` is the host's, or a minimal stand-in in browsers. `Value.Get`, `Set`, `SetIndex`, `Call`, `Invoke` and `New` calls whose arguments are booleans, numbers, strings, `Value`s, `Func`s or nil are lowered to unexported variants that take the arguments already converted, in a JavaScript array, and a constant ASCII name as it is (`internal/lower/jsvalue.go`), instead of boxing each argument for `ValueOf` |

How it works:

* The loader sets `packages.Config.ParseFile`: when go/packages parses a file of a replaced package under `$GOROOT/src`, the first file becomes the replacement and the others become empty files. go/types therefore type-checks every importer against the replacement, and the package graph the go command resolved is unchanged. `packages.Config.Overlay` cannot do this: the go command refuses to overlay files under the module cache, where `go tool goesm`'s toolchain lives.
* Only packages reachable through the type-checked imports (after replacement) are lowered, so the gc runtime's internals (`internal/runtime/*`, `internal/abi` users, ...) drop out.
* Packages are loaded with the build tags `purego` and `math_big_pure_go`, which select the portable Go code where the standard library also has assembly (as gc builds it without assembly).
* A function without a Go body (assembly, `//go:linkname` declarations, or left bodyless by a replacement) in the standard library is implemented in `runtime/src/natives.ts`, one export per function named after `types.Func.FullName`. goesm checks at compile time that the export exists. A short fixed list (`natives.Override`) also replaces functions whose Go body reinterprets memory: `math.Float64bits` and friends, the 64-bit `math/bits` functions (on BigInt halves), `internal/strconv.formatBits` (whose Go body narrows `uint64` digits through `uint`), `slices.overlaps`, `internal/abi.NoEscape`. The math functions whose results IEEE 754 fixes (`Floor`, `Ceil`, `Trunc`, `Round`, `RoundToEven`, `Sqrt`, `Abs`, `Signbit`, `Copysign`, `Inf`) are JS builtins too, several times faster than their Go bodies' bit manipulation.
* A **patch** (`internal/natives/patch/<import path>/<file>.go`) changes a few declarations of a package that is otherwise compiled from its own source: its declarations replace the package's declarations of the same names (renamed to `_` in place, so they stay type-checked but are never emitted) and are added, with its imports, to the file of that name. A patch may import packages the file does not: the go command, which lists a package's imports from its files, is handed an overlay of the file with blank imports of them (`patchImports` in internal/loader). `time` is patched this way: `Sleep`, `Timer`, `Ticker` and the timer functions the gc runtime implements run on the host's `setTimeout` (`armTimer` in natives.ts), and a timer's function runs in a new goroutine when it fires. The other patches replace code that reads memory through `unsafe.Pointer` or that gc implements in the compiler: `sync/atomic.Value`, `hash/maphash` (hashed by the runtime), `log/slog.Value`'s strings and groups, `crypto/internal/fips140/subtle.XORBytes`, `alias.AnyOverlap` and SHA-3's permutation, `crypto/internal/fips140/check`'s self-verification (FIPS 140 mode cannot be enabled) and the self-tests `CAST` and `PCT` run in FIPS 140 mode only, whose `init` functions kept the hashes, AES and the key derivations in any program importing them, `crypto/internal/constanttime`, `internal/abi`'s escape hints, and `context`'s `cancelCtx.Err` (which waits on a channel that is already closed, and would make `Context.Err` async). Others connect packages to the host: `os/signal` hears signals through `process.on`, `os.Executable` is the script under Node.js and Bun, and `net/http`'s client always uses `fetch` (the js/wasm port talks to a fake in-process network under Node.js, for Go's own tests), also for a Transport whose dialer is a plain `net.Dialer`'s, which the port would dial its in-process network with (OpenTelemetry's OTLP/HTTP exporter builds one). That patch keeps the original `RoundTrip`, which instrumentation such as otelc rewrites, and calls it: a patch function with the directive `//goesm:original name` renames the declaration it replaces to `name` instead of `_`. Outside browsers the client asks fetch for `redirect: "manual"`, so that `http.Client` follows redirects itself, as natively (`CheckRedirect`, cookie jars, the limit of 10); browsers only return an opaque response for that, so there fetch follows them. `net/http`'s server is connected to the host too: `Server.ListenAndServe` serves with the host's own HTTP server (`node:http` under Node.js, `Bun.serve`, `Deno.serve`) instead of listening on the fake network, and `Close` and `Shutdown` stop it through the listener it registers; the runtime's `fetchHandler` (`runtime/src/http.ts`) turns an `http.Handler` into a fetch handler (Cloudflare Workers, `Deno.serve`, service workers). Both run one Go function of the patch, which builds the server-side `*Request` from a Fetch API `Request` (its body read in full) and runs the handler in a goroutine; the `ResponseWriter` collects the body into one `Response` when the handler returns, or turns it into a `ReadableStream` when the handler flushes (Server-Sent Events, Connect's server streaming). `unique` is replaced: one Go map holds the canonical values, which are never freed. `math/big`'s word functions are patched to 32-bit words, `crypto/internal/fips140/bigmod` and `crypto/internal/boring/bbig` are replaced by 32-bit-limb versions, `crypto/internal/fips140/nistec`'s P-256 table is decoded instead of aliased, and `iter`'s coroutines run on goroutines. For speed, `fmt.Sprintf` formats `%v %d %s %t %x %X %f %F` of strings, booleans, integers and float64s with a format it parses once (`runtime/src/fmt.ts`), and otherwise the common verbs (`%v %d %s %t %x %X %f %e %g` of strings, booleans and numbers of predeclared types, with `-`, `0`, a width and a float precision) by concatenating strings, numbers by the engine (`toString`, `toFixed`, `toExponential`), and leaves everything else (other verbs and flags, named types, argument errors) to fmt's own code; `encoding/json`'s `Marshal` and `Unmarshal` of plain values (booleans, numbers, strings, slices, arrays, string-keyed maps, pointers, `any`, and structs whose tags use only names and `omitempty`, with no methods anywhere) are done in `runtime/src/json.ts`: `Marshal` converts the value to JS values for the engine's `JSON.stringify` (and escapes HTML characters afterwards, as Go does), and `Unmarshal` parses the input once with a decoder built per type, and hand anything else (marshalers, embedded fields, other tag options, non-nil slices, maps or pointers to decode into, errors) to the package's Go code from the start. That code is not json v2, which is several times the size, but the encoder and decoder of encoding/json's own implementation (`GOEXPERIMENT=nojsonv2`), patched in to write and return what json v2 with v1 options does: its errors (an `UnmarshalTypeError` with json v2's offset and JSON Pointer path, a method's error as it is, decoding going on after each), its partial results, the map keys it accepts, its reading of struct tags and its text for invalid UTF-8; their input and the output of `MarshalJSON` methods are checked by the runtime (`jsonSyntax`). A program declaring a method named `MarshalJSONTo` or `UnmarshalJSONFrom` outside encoding/json, which only json v2 calls, keeps json v2 (`JSONv2` in internal/lower/json.go). `testdata/programs/jsonlegacy` compares both with native Go on random JSON text and values. The `json.Unmarshal` calls goesm lowers go to the runtime's `jsonDecode` instead, which also handles what the one pass gives up on: it checks the input as jsontext does, decodes in place with v1's merge rules and returns encoding/json's own errors with the same messages, offsets and fields. A call whose target type it always decodes itself (no methods, no arrays, and no interface that could already hold a pointer) refers to nothing in the package, and a package whose calls are all of that kind does not import `encoding/json`, whose initialization keeps json v2, jsontext and most of reflect: a program that only decodes JSON into structs goes from 553 to 36 KB minified; `strings`' `ToUpper` and `ToLower` of ASCII strings are the engine's `toUpperCase` and `toLowerCase`, `Split` with a separator and `Join` are its `split` and `join`, `TrimSpace` and `Split` with an empty separator walk the string in natives.ts instead of keeping `unicode`'s tables and `utf8`'s decoder, a `strings.Builder` grows a string by concatenation (a rope in the engine; `Cap` reports what the `[]byte` would have), `slices.Sort` (so also `sort.Ints` and `sort.Strings`) of integers and strings is the engine's built-in sort (equal elements cannot be told apart; floats keep Go's pdqsort for NaN and -0), which a call whose element type is an integer or string type where it is called reaches directly, so that a program sorting only those leaves out `Sort` and its pdqsort (`internal/lower/sortcall.go`), `unicode`'s `ToUpper` and `ToLower` beyond ASCII are the engine's `toUpperCase` and `toLowerCase` of the rune, with Go's simple mapping where the engine's full mapping gives several runes, so that a program converting case leaves out `CaseRanges`, `internal/strconv`'s `FormatFloat` and `AppendFloat` take a float64's digits from the engine's `toExponential` and `toFixed` (`ftoaDigits` in natives.ts, which rounds exact ties to even as Go does, where the engine rounds them up), `fmt`'s `fmtInteger` computes the digits of values below 2^53 on `uint` instead of `uint64`, and `internal/strconv`'s multiprecision decimal shifts by at most 28 bits at a time, as on 32-bit platforms (its 60-bit shifts on `uint` would lose digits). `Atoi`'s slow path is `ParseInt` written out for base 10, so that `Atoi` does not keep `ParseInt` and `ParseUint` with their bases, bit sizes and underscores. `fmt.Print`, `Println` and `Printf`, and `Fprint`, `Fprintln` and `Fprintf` to `os.Stdout` or `os.Stderr`, write their string with the fmt patch's `printStd` when the program never assigns those variables, takes their address or closes them (`internal/lower/printcall.go`), so that printing leaves out `*os.File`, `internal/poll` and `syscall`'s file table. `regexp` is patched so that a program whose patterns are all known at compile time matches with the engine's `RegExp`: goesm parses each pattern with Go's `regexp/syntax` while compiling, and translates it when a RegExp finds the same matches and a search by backtracking takes at most quadratic time (no capture group or subexpression matching the empty string under a repetition, and an automaton that is at most polynomially ambiguous of degree 1, such as `^(\S+)\s+(.*)$`; for a pattern that is not anchored, degree 1 only when the run whose splits are tried holds no character a match starts with; `internal/lower/regexpjs.go`). Go's engines take linear time, so a long input can take longer with the RegExp: `\d+x` tries a match from each digit of a run. The program then leaves out regexp's parser and engines: a calendar package that parses dates with a pattern and `strconv.Atoi` grows by 4.5 KB gzipped over one that only uses `time`, instead of 55 KB. A program that may compile any other pattern keeps Go's engines for all of its patterns.
* Replacements, patches, overrides and natives are a fixed set compiled into goesm. They apply only to files under `$GOROOT/src`, and nothing a dependency contains can add to them.
* A function of a third-party dependency that goesm cannot lower becomes a panicking stub like a standard library function, with a warning; a program's own packages must lower completely.
* `//go:linkname` between Go packages: a bodyless declaration with a target (a "pull", which compile-time instrumentation generates to reach its hooks) calls the Go function of that name (`internal/lower/linkname.go`). The call goes through a symbol table in `@goesm/runtime`, not an ES module import, so that the linked packages keep Go's initialization order: the providing package registers its functions once its variables are initialized, and an earlier call that returns nothing is deferred until then.
* `//go:embed` initializes `string`, `[]byte` and `embed.FS` variables with the files of the package directory, before the package's other variables.
* Goroutine-local storage for instrumentation: when a program uses the `runtime` functions otelc adds (`GetTraceContextFromGLS` and the like), every goroutine carries the two values, a new goroutine starts with copies of its creator's (cloned through `OtelContextCloner`, as otelc's `newproc1` patch does), and each `await` restores the running goroutine when it resumes (`$rt.resumeG`). Programs that do not use them pay nothing.

Status (`go test ./test -run TestStdlibStatus -v`; golden tests in `testdata/semantics/stdlibuse`):

* Compiled from Go source and matching native Go: `errors` (`Is`, `As`, `Join`, `Unwrap`), `strings` (search, split, fields, case mapping, `Builder`, `Replacer`, `EqualFold`), `strconv` (integer formatting, `Atoi`, quoting, `NumError`), `sort`, `slices`, `maps`, `sync`, `unicode`, `unicode/utf8`, `math/bits`, `strconv` 64-bit parsing and shortest float formatting (`testdata/semantics/int64s`).
* `fmt` (verbs, flags, width and precision, `Stringer` / `error` / `Formatter` / `GoStringer`, `Errorf` with `%w`, `Sscanf`), `reflect` and `encoding/json` (struct tags, embedding, maps, `RawMessage`, `Marshaler` / `TextMarshaler`, `Decoder` streams, `UseNumber`, errors) match native Go in `testdata/programs/fmtverbs`, `reflection`, `jsoncodec` and `jsonlegacy`.
* `time` (`Sleep`, `Timer` with `Stop` / `Reset`, `Ticker`, `AfterFunc`, `After` in `select`, clocks, `Duration`, formatting and parsing) matches native Go in `testdata/programs/timers`.
* `crypto` hashes and ciphers (MD5, SHA-1, SHA-2, SHA-3, HMAC, AES-GCM, CTR), `crypto/rand` (the host's `crypto.getRandomValues`), `math/rand`, `math/rand/v2`, `hash/maphash`, `sync/atomic.Value` and slice to array pointer conversions match native Go in `testdata/programs/stdlibmisc`.
* `math/big` (`testdata/programs/mathbig`) and public-key cryptography (`crypto/rsa`, `crypto/ecdsa`, `crypto/ecdh`, `crypto/ed25519`, `crypto/x509`; `testdata/programs/cryptopk`) match native Go. Under goesm `math/big.Word` is `uint32` (`_W = 32`, as on 32-bit platforms) and `crypto/internal/fips140/bigmod` uses 32-bit limbs, because `uint` is a JS number; the multiplication inner loops and `bits.{Add,Sub,Mul,Div,Rem}32` are natives. The 64-bit-limb field arithmetic of P-384, P-521 and Ed25519 runs on BigInt and is slow.
* `iter.Pull` / `Pull2` (`testdata/programs/iterpull`): a sequence that is a function literal calling yield only directly, and blocking on nothing else, also gets a JS generator of its body in programs that reference `Pull` or `Pull2` (`internal/lower/seqgen.go`); `Pull` steps it synchronously. Any other sequence runs as a coroutine on a goroutine, and `coroswitch` hands over through channels (a patch). The coroutine's function literals count as function values for the blocking analysis only in programs that reference `Pull` or `Pull2`, and not even there for `next` and `stop` when their only uses are calls of local variables (`TestAsyncStaysLocal`).

## 10. Tooling compatibility and security

* `.go` files are plain Go: no goesm-specific syntax or magic comments. The one directive, `//goesm:import`, is only for code that calls JavaScript ([docs/js-imports.md](https://goesm.dev/reference/js-imports.md)), which then builds only with goesm. The fixtures pass `go vet` / `go build` / `go run`, and the golden tests compare against exactly that native execution. The package graph is the one the go command resolved, so call graphs for govulncheck and similar tools are unchanged.
* Importing a dependency never runs code inside goesm. There is no compiler plugin or third-party extension mechanism; the only esbuild plugin is goesm's own split-mode resolver in `goesm build -split`, and the emitted tree needs none. The standard library replacements, patches and natives (§9) are a fixed set inside goesm that applies only to `$GOROOT/src`; a Go function without a body outside the standard library is an error unless `//go:linkname` names another Go function of the program, never a hook into goesm. `-toolexec` runs the program the user names, as `go build -toolexec` does.
* Concerns: (1) go/packages runs `go list`, so goesm inherits the go command's trust boundary for its environment (`GOFLAGS` etc.), `go.work` and fetching modules from `GOPROXY` (goesm does not widen it). (2) Generated code relies on Go's type safety; a lowering bug shows up as wrong behaviour, not memory unsafety (JS itself is memory safe). (3) Generated ESM uses host APIs such as `globalThis.reportError`; the DOM is used through `syscall/js` ([docs/dom.md](https://goesm.dev/reference/dom.md)), and goesm has no DOM bindings of its own. (4) `GoPanic` messages and the source map's `sourcesContent` include Go source, so a published bundle ships the source (an option to drop `SourcesContent` is not implemented).

## 11. Implemented / not implemented / differences from native Go

**Implemented (verified by golden tests against native Go)**: package import, functions, multiple results, named results, closures, structs (value copies, methods, pointer methods, embedding and promotion, promoted fields as composite literal keys, comparison), arrays, slices (aliasing, append, copy, re-slicing, nil), maps (struct / interface keys, comma-ok, delete, nil maps, range), pointers (variables, fields, elements, `new`, identity), defer (ordering, modifying named results, LIFO), panic / recover (runtime errors, re-panic), interfaces (dispatch, type assertions, type switches, comparison, nil interface vs nil pointer), generics (generic functions, constraints and constraint methods, generic types also through interfaces, operators and conversions following the type argument, Go 1.27 generic methods, type identity, local types of generic functions, which take the function's type parameters as implicit leading type arguments as in gc), method values / method expressions, switch / fallthrough / labeled break and continue, `goto` (backward jumps become a state machine), range over int, range-over-func (break / continue / return from nested statements, labeled branches, `defer` (on the enclosing function's frame) and `goto` in the body, blocking operations and select in the body, Go's panics for iterators that misuse yield), Go 1.22 per-iteration loop variables (shared ones in files for earlier Go versions), `//go:linkname` between Go packages, `//go:embed`, calling JavaScript and TypeScript through `//goesm:import` (`TestJSImport`, against expected output), calling Go from JavaScript with converted arguments and results (`TestJS`), compile-time instrumentation through `-toolexec`, 8/16/32-bit integer wrap-around, integer divide-by-zero panics, UTF-8 strings and runes, goroutines, unbuffered / buffered channels, close, range over channels, select (including default), `runtime.Goexit` / `Gosched`, package variable init order and `init()`; the standard library packages listed in §9.

**Not implemented** (produces a goesm diagnostic or does not work):
* exact 64-bit `int` and `uint` (they are numbers, see §5)
* the parts of `unsafe` and `reflect` beyond §7
* deadlock detection while the host still has pending work that Go does not know about (JavaScript timers, I/O), goroutine preemption, goroutine-local recover state

**Known differences from native Go** (`TestKnownGaps` asserts that the first two still differ, via `IntWrap`, `UintWrap` and `AppendCap`; the rest are not deterministic enough to pin and are documented only):
* `int` and `uint` are inexact above 2^53 and do not wrap on 64-bit overflow (`uint(0)-1` is `-1`); `int64` and `uint64` are exact. An ordered comparison of a conversion `uint(i)` of a negative `i`, the bounds check idiom `uint(i) < uint(len(s))`, does compare as the wrapped value.
* A backward `goto` over a variable declaration reuses the variable where Go makes a new one; only closures created before the jump can tell.
* `append` capacity growth is approximated (no size-class rounding), so `cap()` can differ from gc.
* Map range order is insertion order (Go randomises it; both are unspecified).
* When the deferred function is only known at run time (a function value, an interface method), `recover()` also works in the functions it calls (Go requires a direct call).
* Goroutines switch only at blocking points (cooperative). Blocking exported functions return Promises to JS. [docs/concurrency.md](https://goesm.dev/reference/concurrency.md) describes what this means for data races and parallelism.
* Blocking of dynamic calls is decided conservatively (§5), which can add unneeded `await`s (behaviour is unchanged).
* `print` / `println` write to stderr in the Go runtime's format, but pointer, map, channel, func, slice and interface values print a fixed address instead of a real one.
* `sync`: a `Lock` the analysis (§5) left synchronous panics if it would have to wait; the analysis is meant to rule that out, so it is a goesm bug. A second `Once.Do` while the first call's function is blocked panics instead of waiting; misuse such as unlocking an unlocked `Mutex` is a recoverable panic, not a fatal error. `runtime.Caller` / `Callers` / `Stack` report nothing and `SetFinalizer` is a no-op.
* `unicode.ToUpper` and `ToLower`, and so `strings.ToUpper` and `ToLower` beyond ASCII, follow the engine's Unicode version: a case pair added in a later version than the engine's (Unicode 17's under Node.js 24) is left unmapped.
* Under Bun, JavaScriptCore does not keep NaN payloads, so `math.Float64bits` of a NaN can differ from Go's.
* `time`: timer channels have a buffer of one, as with `GODEBUG=asynctimerchan=1` (`len(t.C)` can be 1); `Stop` and `Reset` drain them, so no stale value is received afterwards, as in Go 1.23. `Timer` and `Ticker` carry one more unexported field, which `%+v` shows. Timers fire when the host's event loop gets to them, so a busy goroutine delays them.
* `net/http` server (`ListenAndServe`, `fetchHandler`): the request body is read in full before the handler runs, and a response is sent when the handler returns or flushes, not when a write fills a buffer. There is no HTTP/2, TLS (`ListenAndServeTLS`), `Hijack`, trailers or 1xx informational responses, `Serve` with a `net.Listener` uses the fake network, and `Shutdown` returns without waiting for requests in flight. `Server` fields other than `Addr`, `Handler`, `BaseContext` and `ErrorLog` are ignored.

## 12. Next three items

1. **Completing the goroutine runtime**: goroutine-local panic / recover state (recover across async boundaries).
2. **Speed of 64-bit arithmetic**: `int64`/`uint64` are BigInts, so code built on 64-bit limbs (the P-384 / P-521 field arithmetic, `crypto/ed25519`, `hash/crc64`-style bit twiddling) is much slower than native; 32-bit or number-based paths for the hot ones, like the 32-bit words `math/big` and `crypto/internal/fips140/bigmod` use under goesm.
3. **Bundle size**: unused package variables and types are dropped now, but `fmt` keeps `reflect` and everything its methods reach (a `fmt` hello world is about 130 KB gzipped).
