vercel/next.js · #101874
Add the next/go SDK and move Go Proxy helpers into it
crates/next-api/src/app.rs23 + / 4 −
@@ -1721,10 +1721,28 @@ impl Endpoint for GoEndpoint { ]); let result = go_package_bundle_from_sources(*sources, session, alias.into(), generated).await?;- ensure!(- result.is_current().await?,- "Go route inputs changed during compilation; retry the request"- );+ // Inputs that changed while compiling invalidate this task, which recomputes. Until+ // then, publish nothing and leave the retry to request-side validation, instead of+ // failing change subscriptions with an internal error. Editing files next to a Go+ // entry, such as `next.config.ts` or `pages/` beside `proxy.go`, can race a compile.+ if matches!(result.outcome, GoBuildOutcome::Retry) || !result.is_current().await? {+ // Without a watcher, as in `next build`, nothing recomputes this task and build+ // output is not validated per request, so fail instead of omitting the executable.+ ensure!(+ watch,+ "Go route inputs changed during compilation; run the build again"+ );+ return Ok(EndpointOutput {+ project,+ output_assets: OutputAssets::empty().to_resolved().await?,+ output_paths: EndpointOutputPaths::NativeFailed {+ build: Some((*result).clone()),+ }+ .resolved_cell(),+ first_load_chunks: None,+ }+ .cell());+ } let content = match &result.outcome { GoBuildOutcome::Success(content) => *content, GoBuildOutcome::Failed(message) => {@@ -1745,6 +1763,7 @@ impl Endpoint for GoEndpoint { } .cell()); }+ // Handled above. GoBuildOutcome::Retry => { bail!("Go inputs changed during compilation; retry the request") }crates/next-api/src/templates/go_proxy_handler.go12 + / 94 −
@@ -3,42 +3,12 @@ package __NEXT_GO_PACKAGE__ import ( "net/http" "net/url"- "sort" "strconv" "strings" ) -// ProxyOptions configures the request forwarded by Next or Rewrite.-type ProxyOptions struct {- Request RequestOptions-}--// RequestOptions contains downstream request overrides.-type RequestOptions struct {- // A nil map preserves the request headers. A non-nil map replaces them;- // an empty map removes them. Names are case-insensitive: values for names- // that differ only in case are combined. Hop-by-hop headers, such as- // Connection and the headers it lists, are ignored.- Headers http.Header-}--// nextGoEmptyOverride stands in for an empty override list, which Next.js-// otherwise ignores. Listing a header that the request never carries removes-// every other request header without changing JavaScript proxy semantics.-const nextGoEmptyOverride = "x-next-internal-go-empty-override"--// Next continues routing only when the proxy explicitly returns this header.-// All other responses are terminal, including empty responses.-func Next(w http.ResponseWriter, options ...ProxyOptions) {- nextGoProxyOptions(w, options)- w.Header().Set("x-middleware-next", "1")-}--func Rewrite(w http.ResponseWriter, destination string, options ...ProxyOptions) {- nextGoProxyOptions(w, options)- w.Header().Set("x-middleware-rewrite", destination)-}-+// Proxy calls proxy.Next and proxy.Rewrite from next/go/proxy, which only set+// control headers. This writer turns those headers into the proxy response. type nextGoProxyWriter struct { http.ResponseWriter request *http.Request@@ -101,66 +71,6 @@ func (w *nextGoProxyWriter) Flush() { _ = http.NewResponseController(w.ResponseWriter).Flush() } -func nextGoProxyOptions(w http.ResponseWriter, options []ProxyOptions) {- if len(options) > 1 {- panic("Next and Rewrite accept at most one ProxyOptions value")- }- if len(options) == 0 || options[0].Request.Headers == nil {- return- }- headers := options[0].Request.Headers- // Connection-level headers describe the hop to the proxy, not the- // downstream request, and r.Header.Clone() includes them. Proxy- // credentials are kept so a cloned map matches passing nil.- hopByHop := map[string]bool{- "connection": true,- "keep-alive": true,- "proxy-connection": true,- "te": true,- "trailer": true,- "transfer-encoding": true,- "upgrade": true,- }- for key, values := range headers {- if strings.EqualFold(key, "Connection") {- for _, value := range values {- for _, name := range strings.Split(value, ",") {- if name = strings.TrimSpace(name); name != "" {- hopByHop[strings.ToLower(name)] = true- }- }- }- }- }- // Iterate in a stable order so values for names that differ only in case- // are combined deterministically instead of the last map entry winning.- keys := make([]string, 0, len(headers))- for key := range headers {- keys = append(keys, key)- }- sort.Strings(keys)- names := make([]string, 0, len(keys))- values := make(map[string][]string, len(keys))- for _, key := range keys {- name := strings.ToLower(key)- if hopByHop[name] {- continue- }- if _, seen := values[name]; !seen {- names = append(names, name)- values[name] = nil- }- values[name] = append(values[name], headers[key]...)- }- for _, name := range names {- w.Header()["x-middleware-request-"+name] = values[name]- }- if len(names) == 0 {- names = append(names, nextGoEmptyOverride)- }- w.Header().Set("x-middleware-override-headers", strings.Join(names, ","))-}- // nextGoForwardedProto returns the client-facing scheme. Proxies may append // their own hop to X-Forwarded-Proto, so only the first entry is used. func nextGoForwardedProto(value string) string {@@ -187,7 +97,9 @@ const nextGoProxyMaxQueryParams = 4096 // metadata, so nxtP/nxtI names are not promoted. Pages data URLs are rejected // because proxy.go only supports App Router applications, whose catch-all // handlers can otherwise reinterpret them, and so are paths that would still-// carry an RSC suffix after decoding (see nextGoHasRSCSegment).+// carry an RSC suffix after decoding (see nextGoHasRSCSegment), and targets+// with a literal #, which proxy.ts would drop as a fragment but Go handlers do+// not. func nextGoNormalizeURL(r *http.Request) bool { target := r.RequestURI if !strings.HasPrefix(target, "/") {@@ -196,7 +108,13 @@ func nextGoNormalizeURL(r *http.Request) bool { target += "?" + r.URL.RawQuery } }- target, _, _ = strings.Cut(target, "#")+ // Clients never send a fragment, and Go's HTTP server does not treat # as+ // one: a route.go handler that receives the original target parses query+ // fields after it. Truncating here would hide those fields from Proxy, so+ // reject a literal # instead.+ if strings.Contains(target, "#") {+ return false+ } rawPath, rawQuery, hasQuery := strings.Cut(target, "?") path := nextGoParsePath(rawPath) // Assigning URL.pathname reparses dot segments, including ones exposed bydocs/01-app/03-api-reference/03-file-conventions/proxy-go.mdx39 + / 54 −
@@ -4,116 +4,101 @@ description: API reference for writing experimental Go Proxy (middleware) with t version: experimental --- -`proxy.go` runs Go code before routing a request, using Go's `net/http` request and response APIs.+`proxy.go` runs Go code before a request is routed, using Go's `net/http` APIs. -```go filename="proxy.go" highlight={5,7}+```go filename="proxy.go" highlight={9,10} package proxy -import "net/http"+import (+ "net/http"+ "next/go/proxy"+) func Proxy(w http.ResponseWriter, r *http.Request) { w.Header().Set("x-proxy", "go")- Next(w)+ proxy.Next(w) } ``` -Enable `experimental.goRoutes` and follow the [Go setup requirements](/docs/app/api-reference/file-conventions/route-go#setup). Create `proxy.go` beside `app`, including inside `src` when applicable. Export a `Proxy` function with the signature shown above. Next.js only detects `proxy.go` when `experimental.goRoutes` is enabled, and a project can have one Proxy file: using `proxy.go` together with a JavaScript or TypeScript Proxy file is an error.+To use it, enable `experimental.goRoutes`, follow the [Go setup](/docs/app/api-reference/file-conventions/route-go#setup), and create `proxy.go` next to `app` (or inside `src`). Export a `Proxy` function with the signature above. A project can have only one Proxy file, so `proxy.go` cannot be combined with `proxy.ts` or `proxy.js`. ## Reference -Next.js generates these helpers in the proxy package:+Import `next/go/proxy` for the Proxy helpers. This import requires a Go module: create one with `go mod init example.com/app` if your project does not have a `go.mod`. `next dev` and `next build` add the `next/go` requirement and a replacement that points to the SDK in your installed `next` package. -| Helper | Behavior |-| ------------------------------------- | --------------------------------- |-| `Next(w, options...)` | Continue routing the request. |-| `Rewrite(w, destination, options...)` | Route the request to another URL. |+| Helper | Behavior |+| ------------------------------------------- | ------------------------------------------ |+| `proxy.Next(w, options...)` | Continue routing the request. |+| `proxy.Rewrite(w, destination, options...)` | Route the request to another URL. |+| Return without calling either | Send the response written to `w` directly. | -Both helpers accept zero or one `ProxyOptions` value:+Use standard Go APIs for everything else, such as `http.Redirect` for redirects and `http.SetCookie` for cookies. When the request continues or is rewritten, cookies set with `http.SetCookie` are available through [`cookies()`](/docs/app/api-reference/functions/cookies) in the page or route that handles it. -```go-// Continue or rewrite without modifying request headers.-Next(w)-Rewrite(w, "/destination")-```--### ProxyOptions--```go-type ProxyOptions struct {- Request RequestOptions-}--type RequestOptions struct {- Headers http.Header-}-```--`Request.Headers` replaces the downstream request headers. Headers omitted from the replacement are removed. A `nil` map preserves the incoming headers; a non-nil empty map (`http.Header{}`) removes them all. Header names are case-insensitive: values for names that differ only in case, such as `Foo` and `foo`, are combined. Passing more than one options value panics.--Go stores Host in `r.Host`, separately from `r.Header`. When cloning request headers, add `headers.Set("Host", r.Host)` to preserve Host.+Relative destinations passed to `http.Redirect` or `proxy.Rewrite` resolve against the incoming request URL. -Hop-by-hop headers in `Request.Headers`, such as `Connection`, `Keep-Alive`, `Upgrade`, `Transfer-Encoding`, and headers listed in `Connection`, are ignored because they describe the connection to the proxy rather than the downstream request. `r.Header` also contains the `X-Forwarded-Proto` header that Next.js or the platform sets for the proxy; a cloned map forwards it downstream. Delete it from the clone if the downstream request should not receive it.+### WithRequestHeaders -Returning without calling `Next` or `Rewrite` sends the response directly. Use standard Go APIs such as `http.Redirect`, `http.SetCookie`, and `http.Flusher` for redirects, response cookies, and streaming. Relative redirect and rewrite destinations resolve against the incoming URL.+Pass `proxy.WithRequestHeaders(headers)` to `proxy.Next` or `proxy.Rewrite` to replace the downstream request headers. Omit the option or use `proxy.WithRequestHeaders(nil)` to keep them unchanged. An empty `http.Header{}` removes them all. -The directory containing `proxy.go` is compiled as an ordinary Go package, such as `package proxy`, like a [`route.go` directory](/docs/app/api-reference/file-conventions/route-go). It cannot be `package main`: Next.js generates the program entrypoint and imports the directory as a package. For `proxy.go` beside `app`, that is the project root: the other `.go` files that Go selects in that directory compile with it and must use the same package name. Do not create `zz_next_route_*.go` files, which are reserved for generated code. If the project root already contains Go code, such as a Go module's command, place the proxy in `src/proxy.go` or move that code into its own directory. Shared code can live in imported packages.--When continuing or internally rewriting a request, cookies set with `http.SetCookie` are available through [`cookies()`](/docs/app/api-reference/functions/cookies) in the downstream render of the same request.--Go Proxy supports gzip, zlib-wrapped deflate, and Brotli response compression.+Hop-by-hop headers, such as `Connection`, `Keep-Alive`, `Upgrade`, `Transfer-Encoding`, and headers named by `Connection`, are ignored. Cloning `r.Header` also forwards `X-Forwarded-Proto` downstream. Delete it from the clone if the downstream request should not receive it. ## Examples ### Rewriting a request -Call `Rewrite` to route a request to another path while keeping the original URL in the browser. Call `Next` for requests that should continue without a rewrite.+Call `proxy.Rewrite` to serve another path while keeping the original URL in the browser. -```go filename="proxy.go" highlight={7,11}+```go filename="proxy.go" highlight={10,14} package proxy -import "net/http"+import (+ "net/http"+ "next/go/proxy"+) func Proxy(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/old-path" {- Rewrite(w, "/new-path")+ proxy.Rewrite(w, "/new-path") return } - Next(w)+ proxy.Next(w) } ``` -### Modifying downstream request headers+### Modifying request headers -Clone the incoming headers, apply changes, and pass them through `ProxyOptions.Request.Headers`. The same options value works with `Next` and `Rewrite`.+Clone the incoming headers, change them, and pass them with `proxy.WithRequestHeaders`. Go keeps the host in `r.Host` instead of `r.Header`, so set it explicitly when you clone the headers. -```go filename="proxy.go" highlight={10-13}+```go filename="proxy.go" highlight={10-14} package proxy -import "net/http"+import (+ "net/http"+ "next/go/proxy"+) func Proxy(w http.ResponseWriter, r *http.Request) { headers := r.Header.Clone() headers.Set("Host", r.Host) headers.Set("x-proxy", "go") headers.Del("x-example")- options := ProxyOptions{- Request: RequestOptions{Headers: headers},- }- Next(w, options)+ proxy.Next(w, proxy.WithRequestHeaders(headers)) } ``` ## Good to know - Go Proxy runs on every request by default.+- Other `.go` files that Go selects in the same directory as `proxy.go` compile with it and must use the same importable package name, such as `package proxy`. Go applies build constraints and platform filename suffixes and excludes `_test.go` files. The directory cannot use `package main`: Next.js generates a separate program entrypoint that imports it. Do not create `zz_next_route_*.go` files, which are reserved for generated code. If your project root already contains Go code, put the proxy in `src/proxy.go`, and put shared code in packages that `proxy.go` imports. - Go Proxy is only supported in App Router applications. A build fails when the project also contains Pages Router routes (pages or API routes in the `pages` directory) or sets the `i18n` configuration. Custom `_app`, `_document`, and `_error` files are allowed. - `r.URL` matches the request URL that a JavaScript Proxy receives, with these exceptions so that Go Proxy authorizes the same resource the route uses: - Query values ending in `.rsc` are kept as sent. - Query parameters whose names start with `nxtP` or `nxtI` are kept as sent. - Segment prefetch requests use the URL of their page. - Requests whose path still ends in `.rsc` after the RSC suffix is removed, including through percent-encoding such as `%2Ersc`, receive a `404` response before Go Proxy runs.+- Requests with a literal `#` anywhere in the HTTP request target, including its query string, receive a `404` response before Go Proxy runs. Percent-encoded `%23` remains supported. - Requests with a query string larger than 64 KiB or more than 4,096 parameters receive a `414 URI Too Long` response before Go Proxy runs. Empty parameters count toward this limit. - Only one proxy file is supported. Go and JavaScript proxies cannot be combined.-- Go Proxy requires Turbopack and runs as a compiled Go executable.-- Self-hosting uses `next build` and `next start`, or [`output: 'standalone'`](/docs/app/api-reference/config/next-config-js/output) with `node .next/standalone/server.js`. `output: 'export'` is unsupported. Platform deployments require an adapter that supports Go middleware.+- Go Proxy supports gzip, zlib-wrapped deflate, and Brotli response compression.+- Go Proxy requires Turbopack.docs/01-app/03-api-reference/03-file-conventions/route-go.mdx6 + / 2 −
@@ -48,6 +48,10 @@ module.exports = { Install Go 1.24 or newer on `PATH`, or set `TURBOPACK_GO` to its executable path. Go is required for `next dev` and `next build`. `next start` runs the compiled executables without the Go compiler. Applications without Go handlers do not require Go. +To import SDK packages such as `next/go/proxy`, your project needs a Go module. Create one with `go mod init example.com/app` if needed, using `go 1.21` or newer in `go.mod`. `next dev` and `next build` add the `next/go` requirement and a local replacement pointing to the SDK in your installed `next` package. Commit the updated `go.mod`.++Both commands refresh the replacement when the installed SDK moves, including after pnpm upgrades, and log any changes. This can update a committed `go.mod` during CI builds.+ ## Reference ### HTTP Methods@@ -472,8 +476,8 @@ Adapter deployments require an adapter that supports `runtime: 'go'`. See [Go ad - Runtime file reads are not traced. Use `go:embed` for assets shipped with Go handlers. - Go handlers read the process environment. `next.config` environment inlining does not apply. - Go builds target the build host operating system and architecture with CGO disabled. The build environment must match the deployment runtime.-- Dependencies must build with CGO disabled and already be downloaded into the selected toolchain's module cache. Builds do not download dependencies or modify `go.mod` or `go.sum`.-- Go workspaces, module replacements, vendoring, source symlinks, and cross-compilation are unsupported.+- Dependencies must build with CGO disabled and already be downloaded into the selected toolchain's module cache. Builds do not download dependencies or modify `go.sum`; the only `go.mod` changes Next.js makes are the `next/go` requirement and replacement.+- Go workspaces, versioned module replacements, directory replacements outside `turbopack.root`, vendoring, source symlinks, and cross-compilation are unsupported. Directory replacements inside it, such as the `next/go` mapping, are supported. - The same experiment enables [`proxy.go`](/docs/app/api-reference/file-conventions/proxy-go). Go Pages API routes, `page.go`, and `layout.go` are unsupported. Go routes support Turbopack's filesystem cache and Go's build cache. Unchanged executables can be reused across server or build processes. Source files, dependencies, embedded assets, generated wrappers, toolchain settings, and compilation targets participate in invalidation.packages/next/go/README.mdadded85 + / 0 −
@@ -0,0 +1,85 @@+# Next.js Go SDK++The `next/go` module is the Go SDK for Next.js Go handlers, enabled with+`experimental.goRoutes: true`. It ships inside the installed `next` package.++## Proxy helpers++Import `next/go/proxy` to continue or rewrite requests in `proxy.go`:++```go+package proxy++import (+ "net/http"+ "next/go/proxy"+)++func Proxy(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/old-path" {+ proxy.Rewrite(w, "/new-path")+ return+ }+ proxy.Next(w)+}+```++Use `proxy.WithRequestHeaders(headers)` with either helper to replace downstream+request headers. No option, or `proxy.WithRequestHeaders(nil)`, keeps them unchanged;+`proxy.WithRequestHeaders(http.Header{})` removes them all. Options apply in order,+so the last `WithRequestHeaders` wins.++`next/go` is the module path, not an importable root package. Import its subpackages;+a plain `route.go` needs only the standard library.++## Module mapping++The SDK is the `next/go` module shipped inside the installed `next` package.+Code that imports one of its packages must be in a Go module. Once it does,+`next dev` and `next build` add a requirement and a directory replacement to its+real location in `go.mod`. They log when they change `go.mod`, the same way they+reconfigure `tsconfig.json`:++```go+require next/go v0.0.0++replace next/go => ./node_modules/next/go+```++Editors, linters and other Go tools resolve the SDK through this ordinary+replacement, always at the installed Next.js version, without downloads or+`go.sum` entries.++- **Requirement:** added when a handler's selected source files, a Go package,+ its tests, or a dependency imports a `next/go/*` package. Handler directories+ include build-tagged and platform-suffixed siblings so SDK requirements are+ available across targets. Actual routes under `testdata` or `vendor` are+ included without treating unused Go fixture modules as application code.+ Next.js never removes a requirement. If `go mod tidy` removes one used only+ by a route that Go's wildcard patterns skip, Next.js adds it back when needed.+ During `next dev`, a changed handler result triggers setup; a `go.mod` update+ then makes Turbopack compile it again.+- **Replacement:** kept pointing at the installed SDK while the module requires+ it. With pnpm it names the package's real directory under `node_modules/.pnpm`,+ so it changes when `next` or one of its peer dependencies is upgraded, and the+ next `next dev` or `next build` updates it. Modules that neither require nor+ import the SDK are left unchanged.+- **Monorepos:** the `go.mod` can be in the application, in a directory nested in+ it, or at the workspace root, and `next` can be installed anywhere inside+ Turbopack's root (`turbopack.root`), such as the workspace's `node_modules`.+ Directory replacements can target ancestor modules within that root.+- **Libraries:** a Go package that imports `next/go/proxy` requires `next/go v0.0.0` in+ its own `go.mod`. The application's replacement applies to it too, so nothing+ needs to be published. Its own replacement, for developing it on its own, is+ ignored by applications.+- **No module:** Go cannot resolve `next/go` outside a module, so `next dev` and+ `next build` warn about Go files that import it without a `go.mod`.+- **Go version:** the SDK declares `go 1.21`, so modules with a `go 1.21` line or+ newer can use it, even though Next.js requires a Go 1.24 toolchain. Next.js does+ not change the `go` line, and Go does not raise it in `-mod=readonly` builds, so+ raise an older `go` line to at least 1.21.++Other requirements and `go.sum` are left to Go. SDK discovery is offline: private+module and VCS settings from the shell or a user Go environment file do not enable+fetches. Explicit Go toolchain and cache locations are preserved. Versioned+replacements and Go workspaces are not supported.packages/next/go/go.modadded6 + / 0 −
@@ -0,0 +1,6 @@+module next/go++// The lowest version the SDK sources need, so that application modules+// declaring an older go line can require it without go.mod updates, which+// -mod=readonly builds refuse. Next.js itself requires a Go 1.24 toolchain.+go 1.21packages/next/go/proxy/proxy.goadded104 + / 0 −
@@ -0,0 +1,104 @@+// Package proxy provides helpers for continuing and rewriting requests in proxy.go.+package proxy++import (+ "net/http"+ "sort"+ "strings"+)++// Option configures Next or Rewrite. Options are applied in order.+type Option func(*options)++type options struct {+ requestHeaders http.Header+}++// WithRequestHeaders replaces the downstream request headers. A nil map preserves+// the incoming headers; an empty map removes them all. Names are case-insensitive,+// and values for names that differ only in case are combined. Connection-level+// headers are ignored. When used more than once, the last WithRequestHeaders wins.+func WithRequestHeaders(headers http.Header) Option {+ return func(opts *options) { opts.requestHeaders = headers }+}++// emptyOverride stands in for an empty override list, which Next.js otherwise+// ignores. Listing a header that the request never carries removes every other+// request header without changing JavaScript proxy semantics.+const emptyOverride = "x-next-internal-go-empty-override"++// Next continues routing the request. Call it from Proxy before writing the+// response body. Only a response with this signal continues routing; all+// other responses are terminal, including empty responses.+func Next(w http.ResponseWriter, opts ...Option) {+ applyOptions(w, opts)+ w.Header().Set("x-middleware-next", "1")+}++// Rewrite routes the request to destination while keeping the browser URL.+// Relative destinations resolve against the incoming request URL.+func Rewrite(w http.ResponseWriter, destination string, opts ...Option) {+ applyOptions(w, opts)+ w.Header().Set("x-middleware-rewrite", destination)+}++func applyOptions(w http.ResponseWriter, opts []Option) {+ var config options+ for _, option := range opts {+ option(&config)+ }+ headers := config.requestHeaders+ if headers == nil {+ return+ }+ // Connection-level headers describe the hop to the proxy, not the+ // downstream request, and r.Header.Clone() includes them. Proxy+ // credentials are kept so a cloned map matches passing nil.+ hopByHop := map[string]bool{+ "connection": true,+ "keep-alive": true,+ "proxy-connection": true,+ "te": true,+ "trailer": true,+ "transfer-encoding": true,+ "upgrade": true,+ }+ for key, values := range headers {+ if strings.EqualFold(key, "Connection") {+ for _, value := range values {+ for _, name := range strings.Split(value, ",") {+ if name = strings.TrimSpace(name); name != "" {+ hopByHop[strings.ToLower(name)] = true+ }+ }+ }+ }+ }+ // Iterate in a stable order so values for names that differ only in case+ // are combined deterministically instead of the last map entry winning.+ keys := make([]string, 0, len(headers))+ for key := range headers {+ keys = append(keys, key)+ }+ sort.Strings(keys)+ names := make([]string, 0, len(keys))+ values := make(map[string][]string, len(keys))+ for _, key := range keys {+ name := strings.ToLower(key)+ if hopByHop[name] {+ continue+ }+ if _, seen := values[name]; !seen {+ names = append(names, name)+ values[name] = nil+ }+ values[name] = append(values[name], headers[key]...)+ }+ for _, name := range names {+ w.Header()["x-middleware-request-"+name] = values[name]+ }+ if len(names) == 0 {+ names = append(names, emptyOverride)+ }+ w.Header().Set("x-middleware-override-headers", strings.Join(names, ","))+}packages/next/go/proxy/proxy_test.goadded89 + / 0 −
@@ -0,0 +1,89 @@+package proxy_test++import (+ "net/http"+ "net/http/httptest"+ "reflect"+ "testing"++ "next/go/proxy"+)++func TestHelpers(t *testing.T) {+ for _, helper := range []struct {+ name string+ run func(http.ResponseWriter, ...proxy.Option)+ key string+ want string+ }{+ {"Next", proxy.Next, "x-middleware-next", "1"},+ {"Rewrite", func(w http.ResponseWriter, opts ...proxy.Option) {+ proxy.Rewrite(w, "/destination", opts...)+ }, "x-middleware-rewrite", "/destination"},+ } {+ t.Run(helper.name, func(t *testing.T) {+ for _, test := range []struct {+ name string+ opts []proxy.Option+ want string+ }{+ {"no options", nil, ""},+ {"nil headers", []proxy.Option{proxy.WithRequestHeaders(nil)}, ""},+ {"empty headers", []proxy.Option{proxy.WithRequestHeaders(http.Header{})}, "x-next-internal-go-empty-override"},+ {"replace headers", []proxy.Option{proxy.WithRequestHeaders(http.Header{"X-User": {"public"}})}, "x-user"},+ {"last option wins", []proxy.Option{+ proxy.WithRequestHeaders(http.Header{"X-Old": {"old"}}),+ proxy.WithRequestHeaders(http.Header{"X-User": {"public"}}),+ }, "x-user"},+ {"last nil preserves headers", []proxy.Option{+ proxy.WithRequestHeaders(http.Header{"X-Old": {"old"}}),+ proxy.WithRequestHeaders(nil),+ }, ""},+ } {+ t.Run(test.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ helper.run(w, test.opts...)+ if got := w.Header().Get(helper.key); got != helper.want {+ t.Fatalf("%s = %q, want %q", helper.key, got, helper.want)+ }+ if got := w.Header().Get("x-middleware-override-headers"); got != test.want {+ t.Fatalf("override headers = %q, want %q", got, test.want)+ }+ if got := w.Header()["x-middleware-request-x-old"]; got != nil {+ t.Fatalf("earlier option leaked headers: %v", got)+ }+ })+ }+ })+ }+}++func TestWithRequestHeaders(t *testing.T) {+ headers := http.Header{+ "Connection": {"X-Hop, Upgrade"},+ "X-Hop": {"private"},+ "Upgrade": {"websocket"},+ "Transfer-Encoding": {"chunked"},+ "X-User": {"first"},+ "x-user": {"second"},+ "Host": {"example.com"},+ }+ original := headers.Clone()+ option := proxy.WithRequestHeaders(headers)+ for i := 0; i < 2; i++ {+ w := httptest.NewRecorder()+ proxy.Next(w, option)+ if got := w.Header().Get("x-middleware-override-headers"); got != "host,x-user" {+ t.Fatalf("override headers = %q", got)+ }+ if got := w.Header()["x-middleware-request-x-user"]; !reflect.DeepEqual(got, []string{"first", "second"}) {+ t.Fatalf("combined values = %v", got)+ }+ if got := w.Header()["x-middleware-request-host"]; !reflect.DeepEqual(got, []string{"example.com"}) {+ t.Fatalf("host = %v", got)+ }+ if !reflect.DeepEqual(headers, original) {+ t.Fatal("WithRequestHeaders mutated the caller's headers")+ }+ }+}packages/next/package.json1 + / 0 −
@@ -62,6 +62,7 @@ "navigation-types/navigation.d.ts", "navigation-types/compat/navigation.d.ts", "font",+ "go", "navigation.js", "navigation.d.ts", "headers.js",packages/next/src/build/index.ts4 + / 0 −
@@ -125,6 +125,7 @@ import { discoverRoutes, createPagesMapping } from './route-discovery' import { sortByPageExts } from './sort-by-page-exts' import { getConventionFileBaseName } from './get-convention-file-base-name' import { getStaticInfoIncludingLayouts } from './get-static-info-including-layouts'+import { ensureGoSdk, goSdkOptions } from '../lib/go-sdk' import { PAGE_TYPES } from '../lib/page-types' import { generateBuildId } from './generate-build-id' import { isWriteable } from './is-writeable'@@ -1944,6 +1945,9 @@ export default async function build( let shutdownPromise = Promise.resolve() if (!isGenerateMode) { if (bundler === Bundler.Turbopack) {+ if (config.experimental.goRoutes) {+ await ensureGoSdk(goSdkOptions(dir, distDir, config))+ } const { duration: compilerDuration, shutdownPromise: p,packages/next/src/lib/go-sdk.test.tsadded710 + / 0 −
@@ -0,0 +1,710 @@+import { execFileSync, spawnSync } from 'child_process'+import { mkdtempSync } from 'fs'+import {+ cp,+ mkdir,+ mkdtemp,+ readFile,+ realpath,+ rm,+ symlink,+ writeFile,+} from 'fs/promises'+import * as os from 'os'+import { delimiter, dirname, join } from 'path'+import * as Log from '../build/output/log'+import { ensureGoSdk, ensureGoSdkQueued } from './go-sdk'++jest.mock('../build/output/log', () => ({+ info: jest.fn(),+ warn: jest.fn(),+}))++// The first Go build compiles the standard library into a cold cache.+jest.setTimeout(120_000)++const go = process.env.TURBOPACK_GO || 'go'+const hasGo = spawnSync(go, ['version']).status === 0+// The real SDK sources, so the fixtures compile against what ships.+const SDK_SOURCE = join(__dirname, '../../go')++const PROXY = `package main++import (+\t"net/http"+\t"next/go/proxy"+)++func Proxy(w http.ResponseWriter, r *http.Request) { proxy.Next(w) }++func main() { http.HandleFunc("/", Proxy) }+`+const PLAIN = `package main++func main() {}+`++const temporaryDirectories: string[] = []++async function temporaryDirectory() {+ const directory = await mkdtemp(join(os.tmpdir(), 'next-go-sdk-'))+ temporaryDirectories.push(directory)+ return realpath(directory)+}++async function write(path: string, content: string) {+ await mkdir(dirname(path), { recursive: true })+ await writeFile(path, content)+}++async function writeModule(+ directory: string,+ name: string,+ goVersion = '1.24.0'+) {+ await write(join(directory, 'go.mod'), `module ${name}\n\ngo ${goVersion}\n`)+}++/**+ * Installs next like pnpm: the package lives in a versioned directory under+ * node_modules/.pnpm, and node_modules/next is a symlink to it. Returns the+ * real SDK directory.+ */+async function installNext(root: string, version: string) {+ const pkg = join(root, `node_modules/.pnpm/next@${version}/node_modules/next`)+ await cp(SDK_SOURCE, join(pkg, 'go'), { recursive: true })+ const link = join(root, 'node_modules/next')+ await rm(link, { force: true })+ await symlink(pkg, link)+ return join(pkg, 'go')+}++function goMod(directory: string) {+ return readFile(join(directory, 'go.mod'), 'utf8')+}++/** Builds the package in `directory`, or the named files in it. */+function build(directory: string, files: string[] = ['.']) {+ // Windows cannot write a build output to os.devNull. An existing directory+ // receives the executable instead.+ const output = mkdtempSync(join(os.tmpdir(), 'next-go-sdk-build-'))+ temporaryDirectories.push(output)+ execFileSync(go, ['build', '-mod=readonly', '-o', output, ...files], {+ cwd: directory,+ env: {+ ...process.env,+ GOWORK: 'off',+ GOFLAGS: '',+ GOPROXY: 'off',+ GOTOOLCHAIN: 'local',+ },+ stdio: 'pipe',+ })+}++afterEach(async () => {+ jest.mocked(Log.info).mockClear()+ jest.mocked(Log.warn).mockClear()+ await Promise.all(+ temporaryDirectories+ .splice(0)+ .map((directory) => rm(directory, { recursive: true, force: true }))+ )+})+;(hasGo ? describe : describe.skip)('ensureGoSdk', () => {+ it('adds the requirement and the replacement when next/go is imported', async () => {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ await write(join(dir, 'proxy.go'), PROXY)+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ const content = await goMod(dir)+ expect(content).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(content).toContain(+ 'replace next/go => ./node_modules/.pnpm/next@16.0.0/node_modules/next/go'+ )+ expect(() => build(dir)).not.toThrow()++ // Idempotent: nothing to change, nothing logged.+ jest.mocked(Log.info).mockClear()+ await ensureGoSdk({ dir, rootDir: dir, sdkDir })+ expect(await goMod(dir)).toBe(content)+ expect(Log.info).not.toHaveBeenCalled()+ })++ it('detects imports through local packages', async () => {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ await write(+ join(dir, 'internal/mw/mw.go'),+ `package mw\n\nimport (\n\t"net/http"\n\t"next/go/proxy"\n)\n\nfunc Continue(w http.ResponseWriter) { proxy.Next(w) }\n`+ )+ await write(+ join(dir, 'proxy.go'),+ `package main\n\nimport "example.com/app/internal/mw"\n\nvar _ = mw.Continue\n\nfunc main() {}\n`+ )+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ expect(await goMod(dir)).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(() => build(dir)).not.toThrow()+ })++ it('detects imports in route directories that are not import paths', async () => {+ // `[id]` and `(group)` are not valid in Go import paths, so these packages+ // cannot be listed by pattern.+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ const route = join(dir, 'app/(group)/items/[id]')+ await write(+ join(route, 'route.go'),+ `package main\n\nimport (\n\t"net/http"\n\t"next/go/proxy"\n)\n\nfunc GET(w http.ResponseWriter, r *http.Request) { proxy.Next(w) }\n\nfunc main() {}\n`+ )+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ expect(await goMod(dir)).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(() => build(route, ['route.go'])).not.toThrow()+ })++ // These names cannot be created on Windows, but Go rejects them as package+ // paths on every platform. Turbopack still compiles their named source files.+ ;(process.platform === 'win32' ? describe.skip : describe)(+ 'Go import-path restrictions',+ () => {+ it.each([+ 'aux',+ 'con',+ 'nul',+ 'prn',+ 'com1',+ 'lpt1',+ 'AUX.txt',+ 'trailing.',+ ])(+ 'detects imports when Go rejects the route directory %s',+ async (folder) => {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ const route = join(dir, 'app', folder)+ await write(join(route, 'route.go'), PROXY)+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ expect(await goMod(dir)).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(() => build(route, ['route.go'])).not.toThrow()+ }+ )+ }+ )++ it.each(['proxy.go', 'app/api/route.go'])(+ 'inspects explicitly selected build-tagged source %s',+ async (entry) => {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ const file = join(dir, entry)+ await write(file, `//go:build next_sdk_custom\n\n${PROXY}`)+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ expect(await goMod(dir)).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(() =>+ build(dirname(file), [entry.split('/').pop()!])+ ).not.toThrow()+ }+ )++ it('inspects platform-suffixed siblings selected by the native compiler', async () => {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ await write(join(dir, 'proxy.go'), PLAIN)+ await write(+ join(dir, 'helper_plan9.go'),+ 'package main\n\nimport "next/go/proxy"\n\nvar _ = proxy.Next\n'+ )+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ expect(await goMod(dir)).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(() => build(dir, ['proxy.go', 'helper_plan9.go'])).not.toThrow()+ })++ it('keeps package-mode selection for ordinary Go dependencies', async () => {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ await write(join(dir, 'proxy.go'), PLAIN)+ await write(join(dir, 'internal/library/value.go'), 'package library\n')+ await write(+ join(dir, 'internal/library/value_plan9.go'),+ 'package library\n\nimport "next/go/proxy"\n\nvar _ = proxy.Next\n'+ )+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ expect(await goMod(dir)).not.toMatch(/next\/go/)+ })++ it.each(['testdata', 'vendor/nested'])(+ 'sets up actual route.go files under %s without scanning fixture modules',+ async (folder) => {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ const route = join(dir, 'app', folder)+ await write(join(route, 'route.go'), PROXY)+ // This is not a route and must never be passed to go mod edit.+ await write(+ join(dir, 'app/testdata/unused/go.mod'),+ 'invalid module fixture'+ )+ await write(join(dir, 'app/testdata/unused/helper.go'), PROXY)+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ expect(await goMod(dir)).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(Log.warn).not.toHaveBeenCalled()+ expect(() => build(route, ['route.go'])).not.toThrow()+ }+ )++ it('ignores ambient Go module, workspace and build-flag settings', async () => {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ await write(join(dir, 'proxy.go'), PROXY)+ const sdkDir = await installNext(dir, '16.0.0')+ const configDir = await temporaryDirectory()+ const goEnvFile = join(configDir, 'go-env')+ await write(goEnvFile, 'GO111MODULE=off\nGOFLAGS=-mod=vendor\n')+ const overrides = {+ GOENV: goEnvFile,+ GO111MODULE: 'off',+ GOWORK: join(configDir, 'missing.work'),+ GOFLAGS: '-mod=vendor',+ GOOS: 'js',+ GOARCH: 'wasm',+ }+ const previous = Object.fromEntries(+ Object.keys(overrides).map((key) => [key, process.env[key]])+ )+ try {+ Object.assign(process.env, overrides)+ await ensureGoSdk({ dir, rootDir: dir, sdkDir })+ } finally {+ for (const [key, value] of Object.entries(previous)) {+ if (value === undefined) delete process.env[key]+ else process.env[key] = value+ }+ }++ expect(Log.warn).not.toHaveBeenCalled()+ expect(await goMod(dir)).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(() => build(dir)).not.toThrow()+ })+ ;(process.platform === 'linux' ? describe : describe.skip)(+ 'Linux cache locations',+ () => {+ it('preserves XDG_CACHE_HOME when the home directory cannot hold a Go cache', async () => {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ await write(join(dir, 'proxy.go'), PROXY)+ const sdkDir = await installNext(dir, '16.0.0')+ const outside = await temporaryDirectory()+ const unavailableHome = join(outside, 'unavailable-home')+ await write(unavailableHome, 'not a directory')+ const overrides = {+ HOME: unavailableHome,+ XDG_CACHE_HOME: join(outside, 'cache'),+ GOCACHE: '',+ GOMODCACHE: join(outside, 'modules'),+ }+ const previous = Object.fromEntries(+ Object.keys(overrides).map((key) => [key, process.env[key]])+ )+ try {+ Object.assign(process.env, overrides)+ await ensureGoSdk({ dir, rootDir: dir, sdkDir })+ } finally {+ for (const [key, value] of Object.entries(previous)) {+ if (value === undefined) delete process.env[key]+ else process.env[key] = value+ }+ }++ expect(Log.warn).not.toHaveBeenCalled()+ expect(await goMod(dir)).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(() => build(dir)).not.toThrow()+ })+ }+ )++ it('never invokes VCS for uncached private dependencies during SDK discovery', async () => {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ await write(join(dir, 'proxy.go'), PROXY)+ await write(+ join(dir, 'private.go'),+ 'package main\n\nimport _ "github.com/next-sdk-offline-fixture/private"\n'+ )+ await write(+ join(dir, 'go.mod'),+ (await goMod(dir)) ++ '\nrequire github.com/next-sdk-offline-fixture/private v1.0.0\n'+ )+ // Without sum entries, -mod=readonly stops at a missing-checksum error+ // before reaching VCS, making this a false-green network regression test.+ // Synthetic sums are enough to reach the failing fake Git below; nothing+ // is downloaded or checksum-validated.+ const checksum = 'h1:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='+ await write(+ join(dir, 'go.sum'),+ `github.com/next-sdk-offline-fixture/private v1.0.0 ${checksum}\n` ++ `github.com/next-sdk-offline-fixture/private v1.0.0/go.mod ${checksum}\n`+ )+ const sdkDir = await installNext(dir, '16.0.0')+ const outside = await temporaryDirectory()+ const marker = join(outside, 'git-invoked')+ const gitSource = join(outside, 'fake-git.go')+ const gitBinary = join(+ outside,+ process.platform === 'win32' ? 'git.exe' : 'git'+ )+ await write(+ gitSource,+ `package main\nimport "os"\nfunc main() { os.WriteFile(${JSON.stringify(marker)}, []byte("invoked"), 0600); os.Exit(1) }\n`+ )+ execFileSync(go, ['build', '-o', gitBinary, gitSource], { stdio: 'pipe' })+ const overrides = {+ PATH: `${outside}${delimiter}${process.env.PATH ?? ''}`,+ GOPRIVATE: 'github.com/next-sdk-offline-fixture/*',+ GONOPROXY: '*',+ GOSUMDB: 'off',+ GOVCS: '*:all',+ GOMODCACHE: join(outside, 'modcache'),+ }+ const previous = Object.fromEntries(+ Object.keys(overrides).map((key) => [key, process.env[key]])+ )+ try {+ Object.assign(process.env, overrides)+ await ensureGoSdk({ dir, rootDir: dir, sdkDir })+ } finally {+ for (const [key, value] of Object.entries(previous)) {+ if (value === undefined) delete process.env[key]+ else process.env[key] = value+ }+ }++ await expect(readFile(marker, 'utf8')).rejects.toMatchObject({+ code: 'ENOENT',+ })+ expect(Log.warn).not.toHaveBeenCalled()+ expect(await goMod(dir)).toMatch(/^\s*next\/go v0\.0\.0$/m)+ })++ it('lets modules that declare an older go version require the SDK', async () => {+ // -mod=readonly refuses to raise the go line, so the SDK must not declare+ // a newer one than the application.+ for (const goVersion of ['1.21', '1.22', '1.23.0']) {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app', goVersion)+ await write(join(dir, 'proxy.go'), PROXY)+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ const content = await goMod(dir)+ expect(content).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(content).toContain(`go ${goVersion}\n`)+ expect(() => build(dir)).not.toThrow()+ }+ })++ it.each(['vendor'])(+ 'detects imports in a route folder named %s',+ async (folder) => {+ // Go gives vendor a meaning only at a module root.+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ const route = join(dir, 'app', folder)+ await write(+ join(route, 'route.go'),+ `package main\n\nimport (\n\t"net/http"\n\t"next/go/proxy"\n)\n\nfunc GET(w http.ResponseWriter, r *http.Request) { proxy.Next(w) }\n\nfunc main() {}\n`+ )+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ expect(await goMod(dir)).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(() => build(route, ['route.go'])).not.toThrow()+ }+ )++ it('skips testdata like go mod tidy', async () => {+ // A requirement only testdata needs would be removed by go mod tidy.+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ await write(join(dir, 'app/api/route.go'), PLAIN)+ await write(join(dir, 'app/testdata/fixture/main.go'), PROXY)+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ expect(await goMod(dir)).not.toMatch(/next\/go/)+ })++ it("skips a module's vendor directory", async () => {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ await write(join(dir, 'app/api/route.go'), PLAIN)+ await write(join(dir, 'vendor/example.com/lib/lib.go'), PROXY)+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ expect(await goMod(dir)).not.toMatch(/next\/go/)+ })++ it('shares a queued run between calls made before it starts', async () => {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ await write(join(dir, 'proxy.go'), PROXY)+ const sdkDir = await installNext(dir, '16.0.0')+ const options = { dir, rootDir: dir, sdkDir }++ const first = ensureGoSdkQueued(options)+ const second = ensureGoSdkQueued(options)+ expect(second).toBe(first)+ await first+ expect(await goMod(dir)).toMatch(/^require next\/go v0\.0\.0$/m)++ // Once a run has started, a new call queues another one.+ const third = ensureGoSdkQueued(options)+ expect(third).not.toBe(first)+ await third+ })++ it('leaves go.mod alone when next/go is not imported', async () => {+ // `go mod tidy` removes an unused requirement; adding it back on every+ // start would fight it. Without the requirement Go ignores a replacement,+ // so nothing is written at all.+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ await write(join(dir, 'app/api/route.go'), PLAIN)+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ expect(await goMod(dir)).toBe('module example.com/app\n\ngo 1.24.0\n')+ expect(Log.info).not.toHaveBeenCalled()++ // Importing it later adds the requirement.+ await write(join(dir, 'proxy.go'), PROXY)+ await rm(join(dir, 'app'), { recursive: true })+ await ensureGoSdk({ dir, rootDir: dir, sdkDir })+ expect(await goMod(dir)).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(() => build(dir)).not.toThrow()+ })++ it('keeps a requirement written by go mod tidy', async () => {+ const dir = await temporaryDirectory()+ await write(+ join(dir, 'go.mod'),+ 'module example.com/app\n\ngo 1.24.0\n\nrequire next/go v0.0.0-00010101000000-000000000000\n'+ )+ await write(join(dir, 'proxy.go'), PROXY)+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ const content = await goMod(dir)+ expect(content).toContain(+ 'require next/go v0.0.0-00010101000000-000000000000'+ )+ expect(content).not.toMatch(/^require next\/go v0\.0\.0$/m)+ expect(() => build(dir)).not.toThrow()+ })++ it('follows pnpm to the new directory when next is upgraded', async () => {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ await write(join(dir, 'proxy.go'), PROXY)+ const first = await installNext(dir, '16.0.0')+ await ensureGoSdk({ dir, rootDir: dir, sdkDir: first })+ expect(() => build(dir)).not.toThrow()++ // The package manager removes the old version on upgrade.+ const second = await installNext(dir, '16.1.0')+ await rm(join(dir, 'node_modules/.pnpm/next@16.0.0'), { recursive: true })+ expect(() => build(dir)).toThrow()++ await ensureGoSdk({ dir, rootDir: dir, sdkDir: second })++ const content = await goMod(dir)+ expect(content).toContain(+ 'replace next/go => ./node_modules/.pnpm/next@16.1.0/node_modules/next/go'+ )+ expect(content).not.toContain('next@16.0.0')+ expect(content.match(/^require next\/go/gm)).toHaveLength(1)+ expect(() => build(dir)).not.toThrow()+ })++ it('replaces a version-specific replacement, which would take precedence', async () => {+ const dir = await temporaryDirectory()+ await write(+ join(dir, 'go.mod'),+ 'module example.com/app\n\ngo 1.24.0\n\nrequire next/go v0.0.0\n\nreplace next/go v0.0.0 => ./elsewhere\n'+ )+ await write(join(dir, 'proxy.go'), PROXY)+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ const content = await goMod(dir)+ expect(content).not.toContain('elsewhere')+ expect(() => build(dir)).not.toThrow()+ })++ it('maps the SDK hoisted to the workspace root in an application module', async () => {+ const root = await temporaryDirectory()+ const dir = join(root, 'apps/web')+ await writeModule(dir, 'example.com/web')+ await write(join(dir, 'proxy.go'), PROXY)+ const sdkDir = await installNext(root, '16.0.0')++ await ensureGoSdk({ dir, rootDir: root, sdkDir })++ const content = await goMod(dir)+ expect(content).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(content).toContain(+ 'replace next/go => ../../node_modules/.pnpm/next@16.0.0/node_modules/next/go'+ )+ expect(() => build(dir)).not.toThrow()+ })++ it('maps the SDK in a module at the workspace root', async () => {+ const root = await temporaryDirectory()+ const dir = join(root, 'apps/web')+ await writeModule(root, 'example.com/monorepo')+ await write(join(dir, 'src/proxy.go'), PROXY)+ const sdkDir = await installNext(root, '16.0.0')++ await ensureGoSdk({ dir, rootDir: root, sdkDir })++ const content = await goMod(root)+ expect(content).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(content).toContain(+ 'replace next/go => ./node_modules/.pnpm/next@16.0.0/node_modules/next/go'+ )+ expect(() => build(join(dir, 'src'))).not.toThrow()+ })++ it('maps modules nested in the project', async () => {+ const dir = await temporaryDirectory()+ const nested = join(dir, 'app/api/items')+ await writeModule(nested, 'example.com/items')+ await write(join(nested, 'route.go'), PROXY)+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ const content = await goMod(nested)+ expect(content).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(content).toContain(+ 'replace next/go => ../../../node_modules/.pnpm/next@16.0.0/node_modules/next/go'+ )+ expect(() => build(nested)).not.toThrow()+ })++ it('skips Go sources in node_modules and the build output', async () => {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ await write(join(dir, 'app/api/route.go'), PLAIN)+ await write(join(dir, 'node_modules/some-package/main.go'), PROXY)+ await write(join(dir, 'build/server/main.go'), PROXY)+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({+ dir,+ rootDir: dir,+ distDir: join(dir, 'build'),+ sdkDir,+ })++ expect(await goMod(dir)).not.toMatch(/^require next\/go/m)+ })++ it('warns and leaves go.mod alone when next is outside the root', async () => {+ const root = await temporaryDirectory()+ const outside = await temporaryDirectory()+ const dir = join(root, 'apps/web')+ await writeModule(dir, 'example.com/web')+ await write(join(dir, 'proxy.go'), PROXY)+ const sdkDir = await installNext(outside, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ expect(await goMod(dir)).toBe('module example.com/web\n\ngo 1.24.0\n')+ expect(Log.warn).toHaveBeenCalledWith(+ expect.stringContaining('outside the project root')+ )+ })++ it('leaves nested modules that do not use the SDK alone', async () => {+ const dir = await temporaryDirectory()+ await writeModule(dir, 'example.com/app')+ await write(join(dir, 'proxy.go'), PROXY)+ const service = join(dir, 'services/worker')+ await writeModule(service, 'example.com/worker')+ await write(join(service, 'main.go'), PLAIN)+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ expect(await goMod(dir)).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(await goMod(service)).toBe(+ 'module example.com/worker\n\ngo 1.24.0\n'+ )+ })++ it('does nothing for Go sources without a module that do not import next/go', async () => {+ const dir = await temporaryDirectory()+ await write(join(dir, 'app/api/route.go'), PLAIN)+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ expect(Log.info).not.toHaveBeenCalled()+ expect(Log.warn).not.toHaveBeenCalled()+ })++ it('warns once when next/go is imported outside a Go module', async () => {+ // Go cannot resolve next/go without a go.mod replacement and would only+ // report "package next/go is not in std".+ const dir = await temporaryDirectory()+ await write(join(dir, 'proxy.go'), PROXY)+ const sdkDir = await installNext(dir, '16.0.0')++ await ensureGoSdk({ dir, rootDir: dir, sdkDir })++ expect(Log.info).not.toHaveBeenCalled()+ expect(Log.warn).toHaveBeenCalledTimes(1)+ expect(Log.warn).toHaveBeenCalledWith(+ expect.stringContaining(+ 'proxy.go imports next/go, but is not in a Go module'+ )+ )++ // The dev server runs this on every Go change; warn only once.+ await ensureGoSdk({ dir, rootDir: dir, sdkDir })+ expect(Log.warn).toHaveBeenCalledTimes(1)+ })+})packages/next/src/lib/go-sdk.tsadded471 + / 0 −
@@ -0,0 +1,471 @@+import { execFile } from 'child_process'+import { existsSync, promises as fs, realpathSync } from 'fs'+import path from 'path'+import { promisify } from 'util'+import * as Log from '../build/output/log'++const execFileAsync = promisify(execFile)++// The Go SDK ships in the installed `next` package. A directory replacement maps+// its module path there, so builds, editors and linters resolve the SDK version+// that matches the running Next.js without downloading anything.+const GO_SDK_MODULE = 'next/go'+// Go accepts any version for a module replaced by a directory. Use the same one+// everywhere, so apps and libraries that import the SDK agree.+const GO_SDK_VERSION = 'v0.0.0'++type GoMod = {+ Require?: Array<{ Path: string; Version: string }> | null+ Replace?: Array<{+ Old: { Path: string; Version?: string }+ New: { Path: string; Version?: string }+ }> | null+}++export type GoSdkOptions = {+ /** The Next.js project directory. */+ dir: string+ /**+ * Turbopack's root (`turbopack.root`, `outputFileTracingRoot`, or `dir`). In a+ * monorepo this is the workspace root: the Go module can live there or in the+ * project, and the SDK can be installed anywhere below it.+ */+ rootDir: string+ /** The build output directory, which never contains Go sources. */+ distDir?: string+ /** The SDK directory. Defaults to `go` in the installed `next` package. */+ sdkDir?: string+}++function defaultSdkDirectory(): string {+ return path.join(path.dirname(require.resolve('next/package.json')), 'go')+}++async function go(cwd: string, args: string[]): Promise<string> {+ // Like the compiler, inherit only OS/toolchain locations and explicit cache+ // settings. GOPRIVATE and GONOPROXY can bypass GOPROXY=off; GO111MODULE,+ // GOFLAGS, cross-compilation flags, and the user's go env file can also+ // change discovery independently of the compilation that follows it.+ const env: NodeJS.ProcessEnv = {+ NODE_ENV: process.env.NODE_ENV,+ GOENV: 'off',+ GO111MODULE: 'on',+ GOWORK: 'off',+ GOFLAGS: '',+ GOPROXY: 'off',+ GOSUMDB: 'off',+ GOVCS: '*:off',+ GOTOOLCHAIN: 'local',+ GOTELEMETRY: 'off',+ CGO_ENABLED: '0',+ }+ for (const name of [+ 'PATH',+ 'HOME',+ 'XDG_CACHE_HOME',+ 'USERPROFILE',+ 'LOCALAPPDATA',+ 'APPDATA',+ 'SystemRoot',+ 'TEMP',+ 'TMP',+ 'TMPDIR',+ 'GOROOT',+ 'GOCACHE',+ 'GOMODCACHE',+ 'GOPATH',+ ]) {+ if (process.env[name] !== undefined) env[name] = process.env[name]+ }+ const { stdout } = await execFileAsync(+ process.env.TURBOPACK_GO || 'go',+ args,+ {+ cwd,+ maxBuffer: 64 * 1024 * 1024,+ env,+ }+ )+ return stdout+}++function isInside(parent: string, child: string): boolean {+ const relative = path.relative(parent, child)+ return (+ relative === '' ||+ (relative !== '..' &&+ !relative.startsWith('..' + path.sep) &&+ !path.isAbsolute(relative))+ )+}++/** The nearest go.mod directory from `dir` up to `rootDir`, like Turbopack. */+function ancestorModule(dir: string, rootDir: string): string | undefined {+ let current = dir+ while (true) {+ if (existsSync(path.join(current, 'go.mod'))) return current+ if (current === rootDir || !isInside(rootDir, current)) return undefined+ const parent = path.dirname(current)+ if (parent === current) return undefined+ current = parent+ }+}++/**+ * Find project packages and modules, including actual Go entries in route+ * directories that Go's wildcard patterns ignore. Unused testdata/vendor+ * fixtures must not cause their modules to be edited.+ */+async function scanProject(+ dir: string,+ distDir: string | undefined+): Promise<{+ packages: string[]+ modules: string[]+ handlers: Set<string>+}> {+ const packages: string[] = []+ const modules: string[] = []+ const handlers = new Set<string>()+ const srcDir = path.join(dir, 'src')+ const rootAppDir = path.join(dir, 'app')+ const appDir = existsSync(rootAppDir) ? rootAppDir : path.join(srcDir, 'app')+ const pending = [{ directory: dir, ignoredByGo: false }]+ while (pending.length) {+ const { directory: current, ignoredByGo } = pending.pop()!+ let entries+ try {+ entries = await fs.readdir(current, { withFileTypes: true })+ } catch {+ continue+ }+ const isModuleRoot = entries.some(+ (entry) => entry.isFile() && entry.name === 'go.mod'+ )+ const isHandler = entries.some(+ (entry) =>+ entry.isFile() &&+ ((entry.name === 'route.go' && isInside(appDir, current)) ||+ (entry.name === 'proxy.go' &&+ (current === dir || current === srcDir)))+ )+ let hasGo = false+ for (const entry of entries) {+ const { name } = entry+ if (entry.isFile()) {+ if (name === 'go.mod' && current !== dir) modules.push(current)+ if (name.endsWith('.go')) hasGo = true+ } else if (+ entry.isDirectory() &&+ !name.startsWith('.') &&+ !name.startsWith('_') &&+ name !== 'node_modules'+ ) {+ const child = path.join(current, name)+ const childIgnored =+ ignoredByGo ||+ name === 'testdata' ||+ (name === 'vendor' && isModuleRoot) ||+ path.basename(current) === 'vendor'+ if (child === distDir || (childIgnored && !isInside(appDir, child))) {+ continue+ }+ pending.push({ directory: child, ignoredByGo: childIgnored })+ }+ }+ if (hasGo && (!ignoredByGo || isHandler)) packages.push(current)+ if (isHandler) handlers.add(current)+ }+ return { packages, modules, handlers }+}++// Quickly route directories such as `[id]` and `(group)` to named-file listing.+// Go also rejects some names using only these characters; let go list report+// those below rather than duplicating its import-path validation rules.+const IMPORT_PATH = /^[A-Za-z0-9._~/+-]*$/++const LIST = [+ 'list',+ '-e',+ '-mod=readonly',+ '-deps',+ '-f',+ // A package with no directory failed to load. Prefix its matching command+ // patterns with ! so the caller can retry those directories by filename.+ '{{.ImportPath}}{{if not .Dir}}{{range .Match}}\n!{{.}}{{end}}{{end}}',+]++/** Whether any of the packages, their tests, or their dependencies import the SDK. */+async function importsSdk(+ moduleDir: string,+ packages: string[],+ handlers: Set<string>+): Promise<boolean> {+ const patterns: string[] = []+ const byFiles = new Set<string>()+ for (const pkg of packages) {+ const relative = path.relative(moduleDir, pkg).split(path.sep).join('/')+ if (IMPORT_PATH.test(relative)) {+ patterns.push(relative ? `./${relative}` : '.')+ } else {+ byFiles.add(pkg)+ }+ // Turbopack compiles a handler's regular non-test files by name, ignoring+ // build tags and platform suffixes. Inspect that same selection even when+ // package-mode listing succeeds but omits one of those source files.+ if (handlers.has(pkg)) byFiles.add(pkg)+ }+ // -e reports packages that fail to load, including the SDK while its+ // requirement is still missing, instead of failing the whole listing.+ const outputs: string[] = []+ if (patterns.length) {+ const output = await go(moduleDir, [...LIST, '-test', ...patterns])+ outputs.push(output)+ for (const line of output.split('\n')) {+ if (!line.startsWith('!')) continue+ // Only retry a directory we scanned, never a dependency's reported path.+ const pkg = path.resolve(moduleDir, line.slice(1))+ if (packages.includes(pkg)) byFiles.add(pkg)+ }+ }+ // A directory that is not a valid import path cannot be named as a package,+ // so list its files instead, like Turbopack compiles it.+ for (const pkg of byFiles) {+ const files = (await fs.readdir(pkg, { withFileTypes: true }))+ .filter(+ (entry) =>+ entry.isFile() &&+ entry.name.endsWith('.go') &&+ !entry.name.endsWith('_test.go')+ )+ .map((entry) => entry.name)+ if (files.length) outputs.push(await go(pkg, [...LIST, ...files]))+ }+ return outputs.some((output) =>+ output.split('\n').some((line) => {+ // Test variants are listed as "path [pkg.test]".+ const importPath = line.split(' ')[0]+ return (+ importPath === GO_SDK_MODULE ||+ importPath.startsWith(`${GO_SDK_MODULE}/`)+ )+ })+ )+}++/** Go requires a ./ or ../ prefix for directory replacements. */+function replacementPath(moduleDir: string, sdkDir: string): string {+ const relative = path.relative(moduleDir, sdkDir).split(path.sep).join('/')+ return relative === '..' || relative.startsWith('../')+ ? relative+ : `./${relative}`+}++async function ensureModule(+ moduleDir: string,+ packages: string[],+ sdkDir: string,+ handlers: Set<string>+): Promise<void> {+ const goMod: GoMod = JSON.parse(await go(moduleDir, ['mod', 'edit', '-json']))+ const replacement = goMod.Replace?.find(+ ({ Old }) => Old.Path === GO_SDK_MODULE && !Old.Version+ )+ const versioned = (goMod.Replace ?? []).filter(+ ({ Old }) => Old.Path === GO_SDK_MODULE && Old.Version+ )+ // A path-wide directory replacement applies to every required version, so+ // libraries that import the SDK resolve to the same installed copy.+ // Version-specific replacements would take precedence over it.+ const mapped =+ replacement !== undefined &&+ !replacement.New.Version &&+ path.resolve(moduleDir, replacement.New.Path) === sdkDir &&+ versioned.length === 0+ const required = goMod.Require?.some(({ Path }) => Path === GO_SDK_MODULE)+ // Only add the requirement when the SDK is imported. `go mod tidy` removes an+ // unused one, and adding it back on every start would fight it.+ const require = !required && (await importsSdk(moduleDir, packages, handlers))+ // Go ignores a replacement for a module that is not required, so leave the+ // go.mod of a module that does not use the SDK, such as a Go service that+ // lives in the project directory, untouched.+ if (!required && !require) return+ if (mapped && !require) return++ const target = replacementPath(moduleDir, sdkDir)+ const args = ['mod', 'edit']+ if (require) args.push(`-require=${GO_SDK_MODULE}@${GO_SDK_VERSION}`)+ if (!mapped) {+ for (const { Old } of versioned) {+ args.push(`-dropreplace=${GO_SDK_MODULE}@${Old.Version}`)+ }+ args.push(`-replace=${GO_SDK_MODULE}=${target}`)+ }+ await go(moduleDir, args)++ const changes = [+ require && `added "require ${GO_SDK_MODULE} ${GO_SDK_VERSION}"`,+ !mapped && `mapped ${GO_SDK_MODULE} to ${target}`,+ ].filter(Boolean)+ Log.info(+ `Updated ${path.join(moduleDir, 'go.mod')} (${changes.join(', ')}) so Go tools resolve the Next.js Go SDK from the installed next package.`+ )+}++// Matches an import spec for the SDK, alone or in an import block, with or+// without a package name: `"next/go"`, `next "next/go"`, `import "next/go"`.+const SDK_IMPORT = /^\s*(?:import\s+)?(?:[\w.]+\s+)?"next\/go(?:\/[^"]*)?"\s*$/m++/** The Go files in `pkg` that import the SDK, by a source scan. */+async function filesImportingSdk(pkg: string): Promise<string[]> {+ const files: string[] = []+ for (const name of await fs.readdir(pkg)) {+ if (!name.endsWith('.go') || name.startsWith('.') || name.startsWith('_')) {+ continue+ }+ try {+ if (SDK_IMPORT.test(await fs.readFile(path.join(pkg, name), 'utf8'))) {+ files.push(path.join(pkg, name))+ }+ } catch {}+ }+ return files+}++// Packages already warned about, so the dev server, which runs this on every+// Go change, warns once per package.+const warnedWithoutModule = new Set<string>()++/**+ * Go only resolves `next/go` through a `go.mod` replacement, so a package that+ * imports it outside any module fails to compile with "package next/go is not+ * in std". Explain why instead.+ */+async function warnImportsWithoutModule(+ packages: string[],+ dir: string+): Promise<void> {+ for (const pkg of packages) {+ if (warnedWithoutModule.has(pkg)) continue+ const files = await filesImportingSdk(pkg)+ if (files.length === 0) continue+ warnedWithoutModule.add(pkg)+ const names = files.map((file) => path.relative(dir, file)).join(', ')+ Log.warn(+ `${names} imports ${GO_SDK_MODULE}, but is not in a Go module, so Go cannot resolve it. Create a go.mod in the project (for example with "go mod init example.com/app"), then run next dev or next build again to map ${GO_SDK_MODULE} in it.`+ )+ }+}++/**+ * `next dev` and `next build`: map `next/go` to the installed SDK in every Go+ * module that holds the project's Go sources and uses the SDK, like TypeScript+ * setup reconfigures tsconfig.json.+ *+ * - Modules that neither require nor import the SDK are left untouched, because+ * Go ignores a replacement for a module that is not required.+ * - The requirement is added only when the SDK is imported. It is never+ * removed; `go mod tidy` does that.+ * - The directory replacement is kept current while the SDK is required. With+ * pnpm its path changes when Next.js is upgraded.+ * - Packages that import the SDK outside any module get a warning, since Go+ * cannot resolve it there.+ *+ * Never throws: failures are logged, and Go reports any remaining problem when+ * the handler is compiled.+ */+export async function ensureGoSdk(options: GoSdkOptions): Promise<void> {+ try {+ // Turbopack rejects Go sources reached through symlinks, such as pnpm's+ // node_modules/next, so work with real paths throughout.+ const dir = realpathSync(options.dir)+ const rootDir = realpathSync(options.rootDir)+ const distDir =+ options.distDir && existsSync(options.distDir)+ ? realpathSync(options.distDir)+ : options.distDir+ const sdkDir = realpathSync(options.sdkDir ?? defaultSdkDirectory())++ const {+ packages,+ modules: nested,+ handlers,+ } = await scanProject(dir, distDir)+ const ancestor = ancestorModule(dir, rootDir)+ const modules = [...nested, ...(ancestor ? [ancestor] : [])]+ // Assign each package to its nearest module, as Go does.+ const packagesByModule = new Map<string, string[]>()+ const withoutModule: string[] = []+ for (const pkg of packages) {+ const owner = modules+ .filter((moduleDir) => isInside(moduleDir, pkg))+ .sort((a, b) => b.length - a.length)[0]+ if (!owner) {+ withoutModule.push(pkg)+ continue+ }+ packagesByModule.set(owner, [...(packagesByModule.get(owner) ?? []), pkg])+ }+ if (withoutModule.length) await warnImportsWithoutModule(withoutModule, dir)+ if (packagesByModule.size === 0) return++ if (!isInside(rootDir, sdkDir)) {+ // Turbopack only compiles directory replacements inside its root.+ Log.warn(+ `The installed next package (${sdkDir}) is outside the project root (${rootDir}), so ${GO_SDK_MODULE} cannot be mapped in go.mod. Set turbopack.root to a directory that contains it.`+ )+ return+ }+ for (const [moduleDir, modulePackages] of packagesByModule) {+ try {+ await ensureModule(moduleDir, modulePackages, sdkDir, handlers)+ } catch (error) {+ Log.warn(+ `Could not map ${GO_SDK_MODULE} to the installed Next.js in ${path.join(moduleDir, 'go.mod')}: ${error instanceof Error ? error.message : String(error)}`+ )+ }+ }+ } catch (error) {+ Log.warn(+ `Could not map ${GO_SDK_MODULE} to the installed Next.js: ${error instanceof Error ? error.message : String(error)}`+ )+ }+}++let queue: Promise<void> = Promise.resolve()+let pending: Promise<void> | undefined++/**+ * Like `ensureGoSdk`, but serialized, so the dev server can call it whenever Go+ * sources change without concurrent `go mod edit` runs.+ */+export function ensureGoSdkQueued(options: GoSdkOptions): Promise<void> {+ // Calls made while a run is waiting to start share it: it reads the files+ // when it starts, so it covers every change made before then. The dev server+ // calls this for each recompiled Go endpoint, often several at once.+ if (pending) return pending+ const run = queue.then(() => {+ pending = undefined+ return ensureGoSdk(options)+ })+ pending = run+ queue = run+ return run+}++/** The SDK options for a Next.js project, as `next dev` and `next build` use them. */+export function goSdkOptions(+ dir: string,+ distDir: string,+ nextConfig: {+ turbopack?: { root?: string }+ outputFileTracingRoot?: string+ }+): GoSdkOptions {+ return {+ dir,+ rootDir:+ nextConfig.turbopack?.root || nextConfig.outputFileTracingRoot || dir,+ distDir,+ }+}packages/next/src/server/dev/hot-reloader-turbopack.ts33 + / 0 −
@@ -24,6 +24,7 @@ import { HMR_MESSAGE_SENT_TO_SERVER, } from './hot-reloader-types' import { recursiveDeleteSyncWithAsyncRetries } from '../../lib/recursive-delete'+import { ensureGoSdkQueued, goSdkOptions } from '../../lib/go-sdk' import type { Update as TurbopackUpdate, Endpoint,@@ -105,6 +106,7 @@ import { setBundlerFindSourceMapImplementation } from '../patch-error-inspect' import { setBundlerFindSourceMapURLImplementation } from '../lib/source-maps' import { formatIssue,+ getIssueKey, isFileSystemCacheEnabledForDev, isWellKnownError, ModuleBuildError,@@ -679,6 +681,34 @@ export async function createHotReloaderTurbopack( } }, 500) + const goSdk = goSdkOptions(projectPath, distDir, nextConfig)+ // The last written state of each Go endpoint: its descriptor, or none when+ // compilation failed, and its issues.+ const goEndpointStates = new Map<EntryKey, string>()+ // Turbopack recompiles a Go endpoint when any of its tracked inputs change,+ // including imported packages outside the route directories that the dev+ // server's file watcher sees. A source there can start importing next/go,+ // which then fails to compile until go.mod requires it. Keep the go.mod+ // mapping current whenever an endpoint's result changes. Endpoints are also+ // written for requests that recompile nothing, so unchanged results are+ // skipped. Syncing writes nothing when nothing needs changing, so it cannot+ // loop; when it adds the requirement, Turbopack sees go.mod change.+ function syncGoSdkIfChanged(+ key: EntryKey,+ result: TurbopackResult<WrittenEndpoint>+ ) {+ if (!nextConfig.experimental.goRoutes || result.value.type !== 'native') {+ return+ }+ const state = [+ result.value.entryPath ?? '',+ ...result.issues.map(getIssueKey),+ ].join('\0')+ if (goEndpointStates.get(key) === state) return+ goEndpointStates.set(key, state)+ void ensureGoSdkQueued(goSdk)+ }+ // Server HMR supports App Router entries on the Node.js runtime. function participatesInServerHmr( key: EntryKey,@@ -1274,6 +1304,7 @@ export async function createHotReloaderTurbopack( hooks: { handleWrittenEndpoint: (id, result, forceDeleteCache) => { currentWrittenEntrypoints.set(id, result.value)+ syncGoSdkIfChanged(id, result) return clearRequireCache(id, result.value, { force: forceDeleteCache, })@@ -2178,6 +2209,7 @@ export async function createHotReloaderTurbopack( subscribeToChanges: subscribeToClientChanges, handleWrittenEndpoint: (id, result, forceDeleteCache) => { currentWrittenEntrypoints.set(id, result.value)+ syncGoSdkIfChanged(id, result) assetMapper.setPathsForKey(id, result.value.clientPaths) serverAssetMapper.setPathsForKey( id,@@ -2263,6 +2295,7 @@ export async function createHotReloaderTurbopack( handleServerComponentChanges, handleWrittenEndpoint: (id, result, forceDeleteCache) => { currentWrittenEntrypoints.set(id, result.value)+ syncGoSdkIfChanged(id, result) assetMapper.setPathsForKey(id, result.value.clientPaths) serverAssetMapper.setPathsForKey( id,packages/next/src/server/lib/native-route.external.ts18 + / 0 −
@@ -157,6 +157,24 @@ export class NativeRouteManager { private async start(executable: string): Promise<Worker> { const token = randomBytes(32).toString('hex')+ // A freshly written executable can briefly stay open for writing, for+ // example in a process forked while Turbopack wrote it. Spawning it then+ // fails with ETXTBSY until that handle closes, so retry for a short while.+ for (let attempt = 0; ; attempt++) {+ try {+ return await this.launch(executable, token)+ } catch (error) {+ if (+ (error as NodeJS.ErrnoException)?.code !== 'ETXTBSY' ||+ attempt >= 20+ )+ throw error+ await new Promise((resolve) => setTimeout(resolve, 25 * (attempt + 1)))+ }+ }+ }++ private async launch(executable: string, token: string): Promise<Worker> { const child = spawn(/* turbopackIgnore: true */ executable, [], { stdio: ['pipe', 'pipe', 'inherit'], env: { ...process.env, __NEXT_GO_TOKEN: token },packages/next/src/server/lib/router-utils/setup-dev-bundler.ts19 + / 0 −
@@ -59,6 +59,7 @@ import { } from '../../../shared/lib/constants' import { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher'+import { ensureGoSdkQueued, goSdkOptions } from '../../../lib/go-sdk' import { isMiddlewareFile,@@ -239,6 +240,11 @@ async function startWatcher( fs.mkdirSync(distDir, { recursive: true }) + const goSdk = goSdkOptions(dir, distDir, nextConfig)+ if (nextConfig.experimental.goRoutes) {+ await ensureGoSdkQueued(goSdk)+ }+ // Create server info to store in the lockfile itself // This allows other processes to discover the running server const appUrl =@@ -547,6 +553,7 @@ async function startWatcher( const slots: SlotInfo[] = [] let envFileChange = false+ let goFileChange = false let clientRouterFiltersChange = false let tsconfigChange = false let conflictingPageChange = 0@@ -628,6 +635,10 @@ async function startWatcher( (watchTime && watchTime !== nextWatchTime) fileWatchTimes.set(fileName, nextWatchTime) + if (fileChanged && fileName.endsWith('.go')) {+ goFileChange = true+ }+ if (envFiles.includes(fileName)) { if (fileChanged) { envFileChange = true@@ -980,6 +991,14 @@ async function startWatcher( } } + // A Go route or Proxy file can start importing next/go after startup.+ // Add the go.mod requirement before it is compiled; Turbopack tracks+ // go.mod. Other Go sources are covered when Turbopack recompiles the+ // endpoints that import them (see the hot reloader).+ if (goFileChange && nextConfig.experimental.goRoutes) {+ void ensureGoSdkQueued(goSdk)+ }+ // Also set on the initial scan, so that typed env definitions exist // from startup. if (envFileChange || isInitialScan) {test/e2e/app-dir/native-go-sdk-dev/app/hello/route.goadded11 + / 0 −
@@ -0,0 +1,11 @@+package route++import (+ "net/http"++ "example.com/sdkdev/internal/greet"+)++func GET(w http.ResponseWriter, r *http.Request) {+ w.Write([]byte(greet.Message()))+}test/e2e/app-dir/native-go-sdk-dev/app/layout.tsxadded9 + / 0 −
@@ -0,0 +1,9 @@+import type { ReactNode } from 'react'++export default function Root({ children }: { children: ReactNode }) {+ return (+ <html>+ <body>{children}</body>+ </html>+ )+}test/e2e/app-dir/native-go-sdk-dev/app/page.tsxadded3 + / 0 −
@@ -0,0 +1,3 @@+export default function Page() {+ return <p>Go SDK in development</p>+}test/e2e/app-dir/native-go-sdk-dev/go.modadded3 + / 0 −
@@ -0,0 +1,3 @@+module example.com/sdkdev++go 1.24.0test/e2e/app-dir/native-go-sdk-dev/internal/greet/greet.goadded3 + / 0 −
@@ -0,0 +1,3 @@+package greet++func Message() string { return "plain" }test/e2e/app-dir/native-go-sdk-dev/native-go-sdk-dev.test.tsadded42 + / 0 −
@@ -0,0 +1,42 @@+import { nextTestSetup } from 'e2e-utils'+import { retry } from 'next-test-utils'++// A package that a Go route imports lives outside the route directories, so+// the dev server's file watcher does not see it. Turbopack does: when the+// package starts importing next/go, the route recompiles, and Next.js adds the+// go.mod requirement that the next compile needs.+// @force-gate turbopack && !deploy+describe('next/go SDK in development', () => {+ const { next, isNextDev } = nextTestSetup({ files: __dirname })++ // @force-gate dev+ it('adds the requirement when an imported package starts using next/go', async () => {+ if (!isNextDev) return+ const response = await next.fetch('/hello')+ expect(await response.text()).toBe('plain')+ // Nothing imports the SDK yet, so go.mod is left alone.+ expect(await next.readFile('go.mod')).not.toContain('next/go')++ await next.patchFile(+ 'internal/greet/greet.go',+ `package greet++import "next/go/proxy"++var _ proxy.Option++func Message() string { return "sdk" }+`+ )+ // The first compile after the edit fails until go.mod requires next/go,+ // then Turbopack compiles again.+ await retry(async () => {+ expect(await (await next.fetch('/hello')).text()).toBe('sdk')+ }, 60_000)+ const goMod = await next.readFile('go.mod')+ expect(goMod).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(goMod).toMatch(/^replace next\/go => \.\/\S+\/next\/go$/m)+ // The first request waits for a cold Go build of the standard library,+ // which the flake job runs several times concurrently.+ }, 240_000)+})test/e2e/app-dir/native-go-sdk-dev/next.config.tsadded9 + / 0 −
@@ -0,0 +1,9 @@+import type { NextConfig } from 'next'++const nextConfig: NextConfig = {+ experimental: {+ goRoutes: true,+ },+}++export default nextConfigtest/e2e/app-dir/native-proxy-go-security/go.modadded3 + / 0 −
@@ -0,0 +1,3 @@+module example.com/native-proxy-go-security++go 1.24.0test/e2e/app-dir/native-proxy-go-security/native-proxy-go-security.test.ts13 + / 0 −
@@ -249,6 +249,19 @@ describe('adapter Go proxy authorization', () => { } }) + it('rejects a literal # that would hide query fields from Go Proxy', async () => {+ // Go route handlers parse query fields after a literal #, so Proxy must+ // not authorize a target truncated at it.+ for (const path of [+ '/native-security/query?resource=public#&resource=private',+ '/native-security/query#?resource=private',+ ]) {+ const response = await fetchViaRawHttp(origin, `/docs${path}`)+ expect({ path, status: response.status }).toEqual({ path, status: 404 })+ expect(await response.text()).not.toContain('"secret":true')+ }+ })+ it('bounds query bytes and parameter counts before calling Go Proxy', async () => { for (const query of [ 'resource=private&value=' + 'a'.repeat(64 * 1024),test/e2e/app-dir/native-proxy-go-security/proxy.go2 + / 1 −
@@ -2,6 +2,7 @@ package proxy import ( "net/http"+ "next/go/proxy" "strings" ) @@ -21,5 +22,5 @@ func Proxy(w http.ResponseWriter, r *http.Request) { } w.Header().Set("x-authorized-resource", resource) }- Next(w)+ proxy.Next(w) }test/e2e/app-dir/native-proxy-go/native-proxy-go.test.ts23 + / 8 −
@@ -123,6 +123,21 @@ describe('native-proxy-go', () => { // the default 120s test timeout. const coldGoBuildTimeout = 180_000 + it(+ 'maps next/go to the SDK in the installed next package',+ async () => {+ // proxy.go imports next/go. The fixture's go.mod has neither the+ // requirement nor the replacement: Next.js adds the replacement, and the+ // requirement because the SDK is imported, once the dev server or build+ // has set up the bundler, which happens no later than the first request.+ await next.fetch('/')+ const goMod = await next.readFile('go.mod')+ expect(goMod).toMatch(/^require next\/go v0\.0\.0$/m)+ expect(goMod).toMatch(/^replace next\/go => \.\/\S+\/next\/go$/m)+ },+ coldGoBuildTimeout+ )+ it( 'continues to a JS handler and matches all paths', async () => {@@ -336,7 +351,7 @@ describe('native-proxy-go', () => { { helper: 'Rewrite', mode: 'replace' }, { helper: 'Rewrite', mode: 'empty' }, ])(- '$helper applies ProxyOptions with $mode request headers',+ '$helper applies WithRequestHeaders with $mode request headers', async ({ helper, mode }) => { const query = new URLSearchParams({ headers: mode,@@ -399,14 +414,14 @@ describe('native-proxy-go', () => { ) it.each(['next', 'rewrite'])(- 'rejects multiple options for %s without stopping the worker',+ '%s uses the last WithRequestHeaders option', async (helper) => {- expect(- (await next.fetch(`/native-proxy/invalid-${helper}-options`)).status- ).toBe(500)- const following = await next.fetch('/native-proxy/inspect')- expect(following.status).toBe(200)- expect(following.headers.get('x-go-proxy')).toBe('yes')+ const response = await next.fetch(+ `/native-proxy/options?headers=multiple&rewrite=${helper === 'rewrite' ? '1' : '0'}`+ )+ expect(response.status).toBe(200)+ expect(await response.json()).toMatchObject({ fromGo: 'last' })+ expect(response.headers.get('x-go-proxy')).toBe('yes') } ) test/e2e/app-dir/native-proxy-go/proxy.go24 + / 22 −
@@ -5,6 +5,7 @@ import ( "fmt" "io" "net/http"+ "next/go/proxy" "strconv" "strings" "time"@@ -24,27 +25,30 @@ func Proxy(w http.ResponseWriter, r *http.Request) { return } if destination := r.URL.Query().Get("relative-rewrite"); destination != "" {- Rewrite(w, destination)+ proxy.Rewrite(w, destination) return } switch r.URL.Path { case "/native-proxy/options":- options := ProxyOptions{}+ var headers http.Header switch r.URL.Query().Get("headers") { case "replace":- options.Request.Headers = http.Header{"X-From-Go": {"options"}}+ headers = http.Header{"X-From-Go": {"options"}} case "empty":- options.Request.Headers = http.Header{}+ headers = http.Header{}+ }+ options := []proxy.Option{proxy.WithRequestHeaders(headers)}+ if r.URL.Query().Get("headers") == "multiple" {+ options = []proxy.Option{+ proxy.WithRequestHeaders(http.Header{"X-From-Go": {"first"}}),+ proxy.WithRequestHeaders(http.Header{"X-From-Go": {"last"}}),+ } } if r.URL.Query().Get("rewrite") == "1" {- Rewrite(w, "/native-proxy/inspect", options)+ proxy.Rewrite(w, "/native-proxy/inspect", options...) } else {- Next(w, options)+ proxy.Next(w, options...) }- case "/native-proxy/invalid-next-options":- Next(w, ProxyOptions{}, ProxyOptions{})- case "/native-proxy/invalid-rewrite-options":- Rewrite(w, "/native-proxy/inspect", ProxyOptions{}, ProxyOptions{}) case "/native-proxy/blocked": http.Error(w, "blocked by Go", http.StatusForbidden) case "/native-proxy/secure", "/native-proxy/pages-secure":@@ -56,37 +60,35 @@ func Proxy(w http.ResponseWriter, r *http.Request) { fmt.Fprint(compressed, "compressed by Go") compressed.Close() case "/native-proxy/rewrite":- Rewrite(w, "/api/proxy-query?rewritten=1")+ proxy.Rewrite(w, "/api/proxy-query?rewritten=1") case "/native-proxy/host-gate": if r.Host != "admin.example.test" { http.Error(w, "invalid host", http.StatusForbidden) return }- Rewrite(w, "./inspect")+ proxy.Rewrite(w, "./inspect") case "/native-proxy/redirect": http.Redirect(w, r, "/native-proxy/inspect", http.StatusTemporaryRedirect) case "/native-proxy/override": headers := r.Header.Clone() headers.Set("x-from-go", "overridden") headers.Del("x-client-remove")- Rewrite(w, "/native-proxy/inspect", ProxyOptions{- Request: RequestOptions{Headers: headers},- })+ proxy.Rewrite(w, "/native-proxy/inspect", proxy.WithRequestHeaders(headers)) case "/native-proxy/cookies": http.SetCookie(w, &http.Cookie{Name: "first", Value: "one", Path: "/"}) http.SetCookie(w, &http.Cookie{Name: "second", Value: "two", Path: "/"})- Rewrite(w, "/native-proxy/inspect")+ proxy.Rewrite(w, "/native-proxy/inspect") case "/native-proxy/cookie-state", "/native-proxy/cookie-rewrite":- options := ProxyOptions{}+ var options []proxy.Option if r.URL.Query().Get("override") == "1" { headers := r.Header.Clone() headers.Set("Host", r.Host)- options.Request.Headers = headers+ options = append(options, proxy.WithRequestHeaders(headers)) } if r.URL.Path == "/native-proxy/cookie-rewrite" {- Rewrite(w, "/native-proxy/cookie-state", options)+ proxy.Rewrite(w, "/native-proxy/cookie-state", options...) } else {- Next(w, options)+ proxy.Next(w, options...) } // Cookies may be set after selecting Next or Rewrite, until headers commit. http.SetCookie(w, &http.Cookie{Name: "first", Value: "fresh", Path: "/", HttpOnly: true})@@ -95,13 +97,13 @@ func Proxy(w http.ResponseWriter, r *http.Request) { case "/native-proxy/body": body, _ := io.ReadAll(r.Body) w.Header().Set("x-go-body", string(body))- Rewrite(w, "/native-proxy/inspect")+ proxy.Rewrite(w, "/native-proxy/inspect") case "/native-proxy/stream": w.WriteHeader(http.StatusCreated) fmt.Fprint(w, "first\n") w.(http.Flusher).Flush() fmt.Fprint(w, strings.Repeat("go", 1000)) default:- Next(w)+ proxy.Next(w) } }test/e2e/app-dir/native-proxy-go/src-fixture/go.mod2 + / 0 −
@@ -1,3 +1,5 @@ module example.com/native-proxy go 1.24.0++require next/go v0.0.0test/e2e/app-dir/native-proxy-go/src-fixture/src/proxy.go7 + / 4 −
@@ -1,6 +1,9 @@ package proxy -import "net/http"+import (+ "net/http"+ "next/go/proxy"+) func Proxy(w http.ResponseWriter, r *http.Request) { w.Header().Set("x-src-proxy", "yes")@@ -9,11 +12,11 @@ func Proxy(w http.ResponseWriter, r *http.Request) { headers.Set("Host", r.Host) headers.Set("x-from-go", "proxy") if r.URL.Path == "/native-proxy/rewrite" {- Rewrite(w, "/native-proxy/native", ProxyOptions{Request: RequestOptions{Headers: headers}})+ proxy.Rewrite(w, "/native-proxy/native", proxy.WithRequestHeaders(headers)) } else {- Next(w, ProxyOptions{Request: RequestOptions{Headers: headers}})+ proxy.Next(w, proxy.WithRequestHeaders(headers)) } return }- Next(w)+ proxy.Next(w) }test/production/next-server-nft/next-server-nft.test.ts1 + / 0 −
@@ -250,6 +250,7 @@ async function readNormalizedNFT(next, name) { "/node_modules/next/dist/lib/get-package-version.js", "/node_modules/next/dist/lib/get-project-dir.js", "/node_modules/next/dist/lib/git-worktree.js",+ "/node_modules/next/dist/lib/go-sdk.js", "/node_modules/next/dist/lib/has-necessary-dependencies.js", "/node_modules/next/dist/lib/helpers/get-cache-directory.js", "/node_modules/next/dist/lib/helpers/get-npx-command.js",test/unit/app-dir/native-route-runtime/native-route-runtime.test.ts88 + / 0 −
@@ -86,6 +86,94 @@ describe('native route runtime', () => { } ) + it('retries starting an executable that is still open for writing (ETXTBSY)', async () => {+ // A process forked while Turbopack wrote the executable can keep it open+ // for writing briefly, and spawning it fails with ETXTBSY until then.+ const children: Array<+ EventEmitter & {+ stdout: PassThrough+ stdin: PassThrough+ exitCode: number | null+ kill: jest.Mock+ }+ > = []+ let resolveStarted!: () => void+ const started = new Promise<void>((resolve) => {+ resolveStarted = resolve+ })+ let token!: string+ const spawn = jest+ .spyOn(childProcess, 'spawn')+ .mockImplementation((_, __, options) => {+ token = options!.env!.__NEXT_GO_TOKEN!+ const child = Object.assign(new EventEmitter(), {+ stdout: new PassThrough(),+ stdin: new PassThrough(),+ exitCode: null as number | null,+ kill: jest.fn(),+ })+ children.push(child)+ if (children.length <= 2) {+ process.nextTick(() =>+ child.emit(+ 'error',+ Object.assign(new Error('spawn ETXTBSY'), { code: 'ETXTBSY' })+ )+ )+ } else {+ resolveStarted()+ }+ return child as unknown as childProcess.ChildProcess+ })+ jest.spyOn(fs, 'readFile').mockResolvedValue(+ JSON.stringify({+ version: 1,+ executable: 'worker',+ goos: process.platform === 'win32' ? 'windows' : process.platform,+ goarch:+ process.arch === 'x64'+ ? 'amd64'+ : process.arch === 'ia32'+ ? '386'+ : process.arch,+ })+ )+ const dispatch = jest.spyOn(http, 'request').mockImplementation(() => {+ throw new Error('Disconnected request was dispatched')+ })+ const manager = new NativeRouteManager(__dirname, false)+ const req = new http.IncomingMessage(new Socket())+ const res = new http.ServerResponse(req)+ const invocation = manager.invoke(+ '/route',+ 'route.native.json',+ req,+ res,+ '/route'+ )++ try {+ await started+ // The third attempt starts. Disconnect before readiness so the request+ // is not dispatched to the fake worker.+ expect(spawn).toHaveBeenCalledTimes(3)+ res.destroy()+ children[2].stdout.write(`\x1eNEXT_GO_READY:${token}:12345\n`)+ await expect(invocation).resolves.toBeUndefined()+ expect(dispatch).not.toHaveBeenCalled()+ } finally {+ for (const child of children) {+ child.exitCode = 0+ child.emit('exit', 0)+ child.stdout.destroy()+ child.stdin.destroy()+ }+ req.destroy()+ res.destroy()+ await manager.close()+ }+ })+ it('strips private Go transport metadata at the public request boundary', () => { const headers = { 'x-next-internal-go-token': 'untrusted-token',test/unit/native-proxy-go/url-parity.test.ts8 + / 1 −
@@ -35,7 +35,9 @@ const nextGoTrustInternalHeaders = false func Proxy(w http.ResponseWriter, r *http.Request) { w.Header().Set("x-url", r.RequestURI) w.Header().Set("x-path", r.URL.Path)- Next(w)+ // What proxy.Next(w) from next/go/proxy sets; the harness builds without+ // a Go module, so it cannot import the SDK.+ w.Header().Set("x-middleware-next", "1") } type testCase struct {@@ -375,6 +377,11 @@ describe('proxy.go request URLs', () => { ['/a/x%2Ersc/b', null], ['/a/x.rsc%3Fy', null], ['/page.segments/_tree.segment.rsc.rsc', null],+ // Rejected: Go handlers parse query fields after a literal #, which+ // proxy.ts drops as a fragment, so Proxy would not see them.+ ['/page?resource=public#&resource=private', null],+ ['/page#?resource=private', null],+ ['/page#frag', null], ] const results = runHarness( binary,turbopack/crates/turbopack-cli/README.md1 + / 1 −
@@ -179,7 +179,7 @@ Go's build and module caches are separate from the Turbo Tasks cache. are unsupported. - Go inputs are filenames, not package paths or patterns. All Go entries in one invocation must have the same parent directory and form one executable.-- Module replacements (all `replace` directives), project Go workspaces, vendoring,+- Versioned module replacements, directory replacements outside the project root, project Go workspaces, vendoring, source symlinks and cross-compilation are unsupported. Symlink checks cover files and directory components in consumed inputs. turbopack/crates/turbopack-cli/tests/go.rs5 + / 2 −
@@ -1151,7 +1151,8 @@ fn watch_observes_imported_packages_and_embedded_assets() { let previous = std::fs::read(&target).unwrap(); std::fs::write( project.join("go.mod"),- "module example.com/watch\ngo 1.24\nreplace example.com/unsupported => ../outside\n",+ "module example.com/watch\ngo 1.24\nrequire example.com/unsupported v1.0.0\nreplace \+ example.com/unsupported => ../outside\n", ) .unwrap(); wait_for_log(@@ -1160,7 +1161,9 @@ fn watch_observes_imported_packages_and_embedded_assets() { || { std::fs::read_to_string(project.join("watch.log")) .unwrap()- .contains("Go module replacements are not supported")+ .contains(+ "Go module replacements must point to a directory inside the project root",+ ) }, ); assert_eq!(std::fs::read(&target).unwrap(), previous);turbopack/crates/turbopack-go/README.md4 + / 1 −
@@ -93,7 +93,10 @@ integration lives outside this crate. `go_source_set(boundary, directory, selection, session)` returns a tracked source set. It finds the nearest ancestor `go.mod` within the supplied boundary, falling back to-the source directory. Missing module files are observed too, so creating a nearer+the source directory. Directory replacements are resolved from the module and must stay+inside the boundary, so a module in a monorepo application can map a package installed at+the workspace root. They are tracked like module sources and need no download; versioned+replacements are rejected. Missing module files are observed too, so creating a nearer module invalidates selection. `GoSourceSelection::Files` accepts explicit names; `Directory` selects regular `.go` siblings except `_test.go`. Both use named-file semantics: platform suffixes and build tags do not filter the selected entry files.turbopack/crates/turbopack-go/src/lib.rs139 + / 33 −
@@ -497,14 +497,16 @@ struct Module { main: bool, #[serde(default)] go_mod: String,- replace: Option<serde_json::Value>,+ #[serde(default)]+ version: String,+ replace: Option<Box<Module>>, } #[derive(Deserialize, Default)] #[serde(rename_all = "PascalCase")] struct ModuleConfig { module: Option<Module>,- replace: Option<Vec<serde_json::Value>>,+ replace: Option<Vec<ModuleReplacement>>, #[serde(default)] // Go 1.24 emits null for an empty requirement slice. require: Option<Vec<Requirement>>,@@ -514,9 +516,54 @@ struct ModuleConfig { #[serde(rename_all = "PascalCase")] struct Requirement { path: String,+ #[serde(default)] version: String, } +#[derive(Deserialize)]+#[serde(rename_all = "PascalCase")]+struct ModuleReplacement {+ old: Requirement,+ new: Requirement,+}++/// Resolves a directory replacement's target, relative to the main module, inside the source+/// boundary. In a monorepo the boundary is the workspace root, so a module in an application+/// directory can map a package installed in the workspace's `node_modules`. Only directory+/// replacements are supported: they are tracked like module sources and need no download.+fn replacement_directory(+ boundary: &Path,+ project: &Path,+ replacement: &ModuleReplacement,+) -> Result<PathBuf> {+ ensure!(+ replacement.new.version.is_empty(),+ "versioned Go module replacements are not supported in this release: {}",+ replacement.old.path+ );+ // Normalize lexically; source path validation rejects symlinks when inputs are tracked.+ let mut directory = PathBuf::new();+ for part in project.join(&replacement.new.path).components() {+ match part {+ std::path::Component::CurDir => {}+ std::path::Component::ParentDir => {+ directory.pop();+ }+ part => directory.push(part),+ }+ }+ // An application can depend on a module at a workspace ancestor. Contain+ // it within the source boundary, but do not map another module onto the+ // main module's own directory.+ ensure!(+ directory.starts_with(boundary) && directory != project,+ "Go module replacements must point to a directory inside the project root: {} => {}",+ replacement.old.path,+ replacement.new.path+ );+ Ok(directory)+}+ // Go's module cache escapes uppercase ASCII as ! followed by its lowercase form. fn module_escape(value: &str) -> String { let mut escaped = String::with_capacity(value.len());@@ -1030,11 +1077,12 @@ async fn observe_assembly_includes( .collect()) } +/// `roots` maps the main module and each directory-replaced module to its directory. async fn observe_packages( tracker: &mut Tracker<'_>, packages: &[Package], project: &Path,- module: &str,+ roots: &[(&str, PathBuf)], goroot: &Path, aliases: &BTreeMap<RcStr, RcStr>, ) -> Result<BTreeMap<RcStr, RcStr>> {@@ -1046,23 +1094,25 @@ async fn observe_packages( // Track unresolved local imports and their nearest existing ancestors, so creation of a // previously missing package invalidates discovery without walking unrelated subtrees. for import in pkg.imports.iter().chain(std::iter::once(&pkg.import_path)) {- if let Some(relative) = import- .strip_prefix(module)- .and_then(|path| {- // An import equal to the module path refers to its root package.- // Missing packages have no Dir in go list's output, so this is also- // needed to watch for the first source file appearing there.- if path.is_empty() {- Some(path)- } else {- path.strip_prefix('/')- }- })- .filter(|_| !module.is_empty())- {- tracker- .parents(&source_path(project, aliases, &project.join(relative)))- .await?;+ for (module, root) in roots {+ if let Some(relative) = import+ .strip_prefix(module)+ .and_then(|path| {+ // An import equal to the module path refers to its root package.+ // Missing packages have no Dir in go list's output, so this is also+ // needed to watch for the first source file appearing there.+ if path.is_empty() {+ Some(path)+ } else {+ path.strip_prefix('/')+ }+ })+ .filter(|_| !module.is_empty())+ {+ tracker+ .parents(&source_path(project, aliases, &root.join(relative)))+ .await?;+ } } } if pkg.dir.is_empty() {@@ -1072,10 +1122,16 @@ async fn observe_packages( let dir: &Path = &source_path(project, aliases, Path::new(&pkg.dir)); tracker.dir(dir).await?; if let Some(module) = &pkg.module {- ensure!(- module.replace.is_none(),- "Go module replacements are not supported in this release"- );+ if let Some(replacement) = &module.replace {+ // The module configuration already admitted only directory replacements.+ ensure!(+ replacement.version.is_empty(),+ "versioned Go module replacements are not supported in this release"+ );+ if !replacement.go_mod.is_empty() {+ tracker.file(Path::new(&replacement.go_mod)).await?;+ }+ } if !module.go_mod.is_empty() { tracker.file(Path::new(&module.go_mod)).await?; }@@ -1138,6 +1194,7 @@ async fn observe_packages( #[turbo_tasks::function(session_dependent)] async fn discover( root: FileSystemPath,+ boundary: FileSystemPath, files: Vec<RcStr>, go_session: ResolvedVc<GoBuildSession>, generated: BTreeMap<RcStr, RcStr>,@@ -1151,7 +1208,17 @@ async fn discover( let project = to_sys_path(root.clone()) .await? .context("Go inputs require a disk filesystem")?;- let mut tracker = Tracker::new(&root, &project, &go_context);+ // Directory replacements may live outside the module but inside the boundary, so inputs+ // are tracked relative to the boundary. The module itself is always inside it.+ let boundary_path = to_sys_path(boundary.clone())+ .await?+ .context("Go inputs require a disk filesystem")?;+ ensure!(+ project.starts_with(&boundary_path),+ "Go module is outside its boundary: {}",+ project.display()+ );+ let mut tracker = Tracker::new(&boundary, &boundary_path, &go_context); let run = async { validate_build_cache(&project, &go_context)?; let directory = entry_directory(&project, &files)?;@@ -1178,14 +1245,36 @@ async fn discover( ) .await?; let config: ModuleConfig = serde_json::from_str(&config)?;- ensure!(- config.replace.as_ref().is_none_or(Vec::is_empty),- "Go module replacements are not supported in this release"- );+ let replacements = config.replace.as_deref().unwrap_or_default();+ let module = config.module.as_ref().map_or("", |m| m.path.as_str());+ let mut roots = vec![(module, project.clone())]; // Even an unresolved dependency needs cache dependencies. Downloading a module can // repair it without changing go.mod/go.sum, so retain reads for its future cache entries. let cache = Path::new(go_context.module_cache.as_str()); for requirement in config.require.iter().flatten() {+ // Go applies a version-specific replacement before a path-wide one, and ignores+ // replacements of modules that are not required.+ let replacement = replacements+ .iter()+ .find(|replacement| {+ replacement.old.path == requirement.path+ && replacement.old.version == requirement.version+ })+ .or_else(|| {+ replacements.iter().find(|replacement| {+ replacement.old.path == requirement.path+ && replacement.old.version.is_empty()+ })+ });+ if let Some(replacement) = replacement {+ // A directory replacement resolves from its own go.mod and sources, never the+ // module cache. Observe its go.mod so creating or editing it invalidates+ // discovery; its packages are tracked like module sources below.+ let directory = replacement_directory(&boundary_path, &project, replacement)?;+ tracker.file(&directory.join("go.mod")).await?;+ roots.push((requirement.path.as_str(), directory));+ continue;+ } ensure!( Path::new(&requirement.path) .components()@@ -1206,7 +1295,6 @@ async fn discover( .file(&download.join(format!("{version}.ziphash"))) .await?; }- let module = config.module.as_ref().map_or("", |m| m.path.as_str()); let mut mirrored = BTreeMap::new(); for (virtual_directory, source_directory) in &aliases { mirror_directory(@@ -1268,7 +1356,7 @@ async fn discover( &mut tracker, &packages, &project,- module,+ &roots, Path::new(go_context.goroot.as_str()), &aliases, )@@ -1542,6 +1630,7 @@ impl GoBundleResult { #[turbo_tasks::function] async fn bundle( root: FileSystemPath,+ boundary: FileSystemPath, mut files: Vec<RcStr>, go_session: ResolvedVc<GoBuildSession>, generated: BTreeMap<RcStr, RcStr>,@@ -1563,7 +1652,15 @@ async fn bundle( ); files.sort(); files.dedup();- let discovery = discover(root.clone(), files, *go_session, generated, aliases).await?;+ let discovery = discover(+ root.clone(),+ boundary,+ files,+ *go_session,+ generated,+ aliases,+ )+ .await?; let outcome = match &discovery.outcome { DiscoveryOutcome::Ready(plan) => { let project = to_sys_path(root.clone())@@ -1616,6 +1713,7 @@ pub fn go_bundle( go_context: GoBuildContext, ) -> Vc<GoBundleResult> { bundle(+ root.clone(), root, files, shared_session(go_context),@@ -1634,6 +1732,7 @@ pub fn go_bundle_with_generated_files( generated: BTreeMap<RcStr, RcStr>, ) -> Vc<GoBundleResult> { bundle(+ root.clone(), root, files, shared_session(go_context),@@ -1651,7 +1750,14 @@ pub fn go_bundle_with_session( session: ResolvedVc<GoBuildSession>, generated: BTreeMap<RcStr, RcStr>, ) -> Vc<GoBundleResult> {- bundle(root, files, *session, generated, BTreeMap::new())+ bundle(+ root.clone(),+ root,+ files,+ *session,+ generated,+ BTreeMap::new(),+ ) } #[cfg(test)]turbopack/crates/turbopack-go/src/sources.rs9 + / 1 −
@@ -318,7 +318,15 @@ async fn bundle_sources( (vec![], BTreeMap::from([(alias, RcStr::from(directory))])) } };- let result = bundle(sources.root.clone(), files, *session, generated, aliases).await?;+ let result = bundle(+ sources.root.clone(),+ sources.boundary.clone(),+ files,+ *session,+ generated,+ aliases,+ )+ .await?; stale = !result.is_current().await? || !sources.inputs.is_current().await?; (*result).clone() };turbopack/crates/turbopack-go/tests/live.rs206 + / 2 −
@@ -553,8 +553,8 @@ async fn standalone_and_unsupported_configuration() -> Result<()> { session .write( "go.mod",- "module example.com/native-fixture\ngo 1.24\nreplace example.com/outside => \- ../outside\n",+ "module example.com/native-fixture\ngo 1.24\nrequire example.com/outside \+ v0.0.0\nreplace example.com/outside => ../outside\n", ) .await?; assert!(@@ -604,6 +604,210 @@ async fn standalone_and_unsupported_configuration() -> Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn directory_replacements_inside_the_module_are_tracked_sources() -> Result<()> {+ let session = Session::new().await?;+ // Frameworks map an SDK shipped in node_modules with an ordinary directory replacement,+ // which editors and linters resolve too. No module download or go.sum entry is needed.+ session+ .write("node_modules/sdk/go.mod", "module next/go\ngo 1.24\n")+ .await?;+ session+ .write(+ "node_modules/sdk/sdk.go",+ "package next\nconst Message = \"sdk-v1\"\n",+ )+ .await?;+ let module = "module example.com/native-fixture\ngo 1.24\nrequire next/go v0.0.0\n";+ session+ .write(+ "go.mod",+ &format!("{module}replace next/go => ./node_modules/sdk\n"),+ )+ .await?;+ session+ .write(+ "main.go",+ "package main\nimport (\n\t\"fmt\"\n\tnext \"next/go\"\n)\nfunc main() { \+ fmt.Println(next.Message) }\n",+ )+ .await?;+ assert_eq!(session.run(&["main.go"]).await?.trim(), "sdk-v1");+ session+ .replace("node_modules/sdk/sdk.go", "sdk-v1", "sdk-v2")+ .await?;+ assert_eq!(session.run(&["main.go"]).await?.trim(), "sdk-v2");+ // A missing package in the replaced module is observed, so creating it recovers even+ // when no other package of that module is imported.+ session+ .write(+ "main.go",+ "package main\nimport (\n\t\"fmt\"\n\t\"next/go/extra\"\n)\nfunc main() { \+ fmt.Println(extra.Value) }\n",+ )+ .await?;+ let error = session.fetch(&["main.go"]).await.unwrap_err().to_string();+ assert!(error.contains("next/go/extra"), "{error}");+ // Write without invalidating the filesystem: only the tracked inputs reveal the change.+ std::fs::create_dir_all(session.project.join("node_modules/sdk/extra"))?;+ std::fs::write(+ session.project.join("node_modules/sdk/extra/extra.go"),+ "package extra\nconst Value = \"extra\"\n",+ )?;+ assert_eq!(session.run(&["main.go"]).await?.trim(), "extra");+ for (replacement, message) in [+ ("example.com/sdk v1.0.0", "versioned Go module replacements"),+ ("../outside", "inside the project root"),+ ] {+ session+ .write(+ "go.mod",+ &format!("{module}replace next/go => {replacement}\n"),+ )+ .await?;+ let error = session.fetch(&["main.go"]).await.unwrap_err().to_string();+ assert!(error.contains(message), "{error}");+ }+ session.stop().await;+ Ok(())+}++#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn directory_replacements_outside_the_module_resolve_within_the_boundary() -> Result<()> {+ let session = Session::new().await?;+ // In a monorepo the application has its own module, while the package manager installs+ // the SDK at the workspace root, which is the source boundary.+ session+ .write("node_modules/sdk/go.mod", "module next/go\ngo 1.24\n")+ .await?;+ session+ .write(+ "node_modules/sdk/sdk.go",+ "package next\nconst Message = \"sdk-v1\"\n",+ )+ .await?;+ let module = "module example.com/web\ngo 1.24\nrequire next/go v0.0.0\n";+ session+ .write(+ "apps/web/go.mod",+ &format!("{module}replace next/go => ../../node_modules/sdk\n"),+ )+ .await?;+ let directory = "apps/web/app/api";+ session+ .write(+ &format!("{directory}/main.go"),+ "package main\nimport (\n\t\"fmt\"\n\tnext \"next/go\"\n)\nfunc main() { \+ fmt.Println(next.Message) }\n",+ )+ .await?;+ let root = FileSystemPath {+ fs: ResolvedVc::upcast(session.fs),+ path: rcstr!(""),+ };+ let options = session.go_context.options.clone();+ let build = || {+ let root = root.clone();+ let options = options.clone();+ let tt = session.tt.clone();+ async move {+ tt.run_once(async move {+ let result = read_with_validated_inputs(+ || {+ let root = root.clone();+ let options = options.clone();+ async move {+ let sources = selected_sources(+ root.clone(),+ root.join(directory)?,+ GoSourceSelection::Directory,+ options.clone(),+ )+ .resolve()+ .strongly_consistent()+ .await?;+ selected_bundle(sources, options, BTreeMap::new())+ .read_strongly_consistent()+ .await+ }+ },+ |value| Some(&**value),+ )+ .await?;+ let file = match &result.outcome {+ GoBuildOutcome::Success(file) => *file,+ GoBuildOutcome::Failed(message) => anyhow::bail!("{message}"),+ outcome => anyhow::bail!("unexpected result: {outcome:?}"),+ }+ .await?;+ let FileContent::Content(file) = &*file else {+ anyhow::bail!("missing executable");+ };+ let mut bytes = vec![];+ file.read().read_to_end(&mut bytes)?;+ anyhow::Ok(bytes)+ })+ .await+ }+ };+ assert_eq!(session.run_bytes(build().await?).await?.trim(), "sdk-v1");+ // The replaced sources outside the module are tracked inputs.+ session+ .replace("node_modules/sdk/sdk.go", "sdk-v1", "sdk-v2")+ .await?;+ assert_eq!(session.run_bytes(build().await?).await?.trim(), "sdk-v2");+ // The workspace itself can also be a module required by the application.+ // Its sources are still inside the boundary, even though the replacement+ // directory is an ancestor of the main module rather than a sibling.+ session+ .write("go.mod", "module example.com/workspace\ngo 1.24\n")+ .await?;+ session+ .write(+ "library/value.go",+ "package library\nconst Message = \"parent-v1\"\n",+ )+ .await?;+ session+ .write(+ "apps/web/go.mod",+ &format!(+ "{module}require example.com/workspace v0.0.0\nreplace next/go => \+ ../../node_modules/sdk\nreplace example.com/workspace => ../..\n"+ ),+ )+ .await?;+ session+ .write(+ &format!("{directory}/main.go"),+ "package main\nimport (\n\t\"fmt\"\n\t\"example.com/workspace/library\"\n\tnext \+ \"next/go\"\n)\nfunc main() { fmt.Println(next.Message, library.Message) }\n",+ )+ .await?;+ assert_eq!(+ session.run_bytes(build().await?).await?.trim(),+ "sdk-v2 parent-v1"+ );+ session+ .replace("library/value.go", "parent-v1", "parent-v2")+ .await?;+ assert_eq!(+ session.run_bytes(build().await?).await?.trim(),+ "sdk-v2 parent-v2"+ );+ // The boundary still applies: a replacement leaving the project root is rejected.+ session+ .write(+ "apps/web/go.mod",+ &format!("{module}replace next/go => ../../../outside\n"),+ )+ .await?;+ let error = build().await.unwrap_err().to_string();+ assert!(error.contains("inside the project root"), "{error}");+ session.stop().await;+ Ok(())+}+ #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn assembly_dependencies_track_sources_headers_and_recover_from_errors() -> Result<()> {