This implements falling back to try multiple locations loading chunks
for sourcemap tracing.
Unfortunately, when RSC replays server errors on the client, it does not
carry over the [0] symbol used to annotate server frames. Instead,
errors are recreated by React and only include the message and stack.
This allows more tests to pass, as we are able to correctly trace stack
frames by loading the appropriate server chunk.
Closes PACK-2442
### What
This PR injects a build-time error for the turbopack if
`client|server-only` is imported in incorrect context. The basic idea is
using resolve plugin, so in resolve time if matching context (which
alises erroneous import), raise a build time error.
Unfortunately this won't fix all of the tests in `invalid-imports`, due
to
1. resolveplugin does not have way to trace import from transformed, so
not able to detect `styled-jsx` from using `<styled..` tags
2. webpack (in our implementation) and turbopack's resolveplugin have
different order of transform / module trace chain, so enabling resolve
plugin in some context raises build error instead of runtime error in
rsc-build-error.
Closes PACK-2397
Fixes: #47978
When an error occurs in getInitialProps, the error page's
getInitialProps is run server-side and returned in `__NEXT_DATA__`.
Following, there's no need to re-run `getInitialProps` client-side on
the hydrate pass.
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
In preparation for the refactor of cache utils in subsequent PRs, this PR moves the one-off prefetch cache utils into a shared `prefetch-cache-utils` file, and also relocates the `buildCustomRoute` util into an isolated lib so that it can be imported into base-server (in a future PR).
This PR does not make any changes to these functions.
Closes NEXT-2394
### What
Exclude precompiled react packages from browser layer loaders coverage.
### Why
Since we're transpiling all the browser layer code now after #59569,
then SWC will also compile react. But when it compiles
`react.production.min.js` it gives me with the code and ESM helper
inserted
```js
import { _ as _type_of } from "@swc/helpers/_/_type_of"; // This is not correct
var l = Symbol.for("react.element"), n = Symbol.for("react.portal"), p = Symbol.for("react.fragment"), q = Sym
bol.for("react.strict_mode"), r = Symbol.for("react.profiler"), t = Symbol.for("react.provider"), u = Symbol.f
```
This makes bundler think it's a ESM package but actually it's CJS, which
converts the module into `{ default: .., __esModule }` instead of the
original react module.
When you're using `React.useEffect` or other API through namespace
import (`import * as React from 'react'`), this will break the module
exports check in bundling as the property doesn't directly attached to
the module now. This PR disabled the transform for precompiled react
packages now and will see the deeper issue in next-swc side later.
Fixes#60890Fixes#61185
Closes NEXT-2362
### What?
Fix the user-facing `MiddlewareConfig` interface.
~While in the codebase, I also made the incoming config object type a
bit more strict by converting from `any` to `unknown`.~ Reverted, as we
do a config assertion already in a [different
place](https://github.com/vercel/next.js/blob/canary/packages/next-swc/crates/next-custom-transforms/src/transforms/page_config.rs/#L171-L180).
### Why?
The interface we previously exposed was the one we used internally,
_after_ we did some parsing on the config object, which is different
from what the user is expected to pass.
### How?
I separated the internal type to its own `MiddlewareConfigParsed`
interface.
Closes NEXT-2375
Fixes#61705
Ref: #61576
### What?
depends on https://github.com/facebook/react/pull/28108
* fixes CSS Ordering issues due to CSS duplication in production mode
* The issues still happen in dev mode
* Highlights broken CSS Ordering for more dev cases, e. g. CSS in client
components
Closes PACK-2300
### What?
fixes unexpected use client build warning in some applications.
We've consolidated all the ecmaplugins into custom rules. It behaves
different for the ecma inputs, while plugin runs any ecmascript inputs
rules only runs with matching target. The culprit module in question was
published as `.mjs`, so the necessary transform didn't ran.
Closes PACK-2419
In #61649 the paragraph `"This function allows you to redirect the user
to another URL. It can be used in..."` describing `notFound` was copied
as is from the `redirect` jsDoc
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
### What
This adds support for navigation signals like `notFound()` and
`redirect(url)` when Partial Prerendering has been enabled.
### Why
Navigation API's like `notFound()` and `redirect(url)` throw errors in
order to interrupt the rendering of components. When a page both invokes
API's that cause the render to be marked as dynamic (like
`unstable_noStore()`) and also a navigation API, these errors may race
to the end. In the case where the navigation error does not beat out the
error emitted by dynamic API's will still trigger the detection warning
that's present to warn you about situations where you may have
accidentally caught the error.
### How
This resolves this issue by explicitly checking for navigation signals
(errors) thrown during the render, and not displaying the "caught
dynamic API" error and console warning.
Closes NEXT-2037
## History
Previously, we added support for `squoosh` because it was a wasm
implementation that "just worked" on all platforms when running `next
dev` for the first time. However, it was slow so we always recommended
manually installing `sharp` for production use cases running `next
build` and `next start`.
Now that [`sharp` supports
webassembly](https://sharp.pixelplumbing.com/install#webassembly), we no
longer need to maintain `squoosh`, so it can be removed. We also don't
need to make the user install sharp manually because it can be installed
under `optionalDependencies`. I left it optional in case there was some
platform that still needed to manually install the wasm variant with
`npm install --cpu=wasm32 sharp` such as codesandbox/stackblitz (I don't
believe sharp has any fallback built in yet).
Since we can guarantee `sharp`, we can also remove `get-orientation` dep
and upgrade `image-size` dep.
I also moved an [existing `sharp`
test](https://github.com/vercel/next.js/pull/56674) into its own fixture
since it was unrelated to image optimization.
## Related Issues
- Fixes https://github.com/vercel/next.js/issues/41417
- Closes https://github.com/vercel/next.js/pull/54670
- Related https://github.com/vercel/next.js/issues/54708
- Related https://github.com/vercel/next.js/issues/44804
- Related https://github.com/vercel/next.js/issues/48820
- parsed stack traces (and error stack locations in js) have 1-based
lines and 1-based columns
- source map tokens have 0-based lines and 0-based columns
- babel code frames use 1-based lines and 0-based columns
This was not always respected. This preserves the 1-based lines and
columns in anything called a stack frame, 0-based lines and columns for
source map apis, and converts to babel’s format as needed.
Closes PACK-2341
---------
Co-authored-by: Tobias Koppers <tobias.koppers@googlemail.com>
<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:
## For Contributors
### Improving Documentation
- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide
### Adding or Updating Examples
- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md
### Fixing a bug
- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md
### Adding a feature
- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md
## For Maintainers
- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change
### How?
Closes NEXT-
Fixes #
-->
### What?
This PR introduces a ground work to generate wasm bindings package from
our napi bindings. This doesn't actually replace anything yet, however
aim to establish our napi bindings package can be built against wasm32
target.
### Why?
We currently have two bindings package to generate native / wasm target
support, one for napi and one other for wasm. Recently napi-rs started
to support to generate bindings for the wasm directly - which means we
can get rid of the wasm-pack based bindings code entirely and maintain a
single bindings code only.
This'll makes our `next-swc` simpler as well, since the invocation to
the bindings now becomes identical we don't have to additional wasm
specific logics to invoke functions (i.e transform, transformsync..).
Also napi generates wasi-supported wasm bindings, provides few more
features to the current wasm bindings.
#### Good
- Async napi binding fn works transparently (`transform`, `minify`...)
- (Experimental) thread supports depends on node.js runtime
- Wasi support: i.e it can even read filesystem directly!
#### Things to consider
- node.js's wasi support is experimental yet
- napi-rs's wasm support is in beta yet, specifically `packaging`
generated wasm output.
Due to `things to consider` reasons, this PR does not replace existing
wasm target yet. We should be able to plan out things later.
**What happens to the turbopack api in napi bindings?**
Simply put, this **does not support turbopack in wasm**. Build works by
disabling turbopack (more notably, underlying dependency doesn't support
wasm) features. It is something to explore separately.
Closes PACK-2367
There is a branch at https://github.com/vercel/next.js/pull/61586 shows
quick demo for importing, running sync / async / read external files.
### What?
This PR wraps up supporting rsc transforms (mostly for the assertion) in
Turbopack. PR contains a few changes to support it, including:
- adjust / expand transform rules for the corresponding contexts
- fix file name / node_modules check
- extract visitors for the assertion / transforms
This change enables most of the rsc-build* tests and some more other
tests. The only failing tests in the rsc-build-errors is due to
Turbopack not triggering hmr with empty file.
Closes PACK-2303
### What & Why
We have a modularize imports config for `next/server` before, which will
transform the `next/server` imports to directly import from the actual
file, for instance: `import { NextRequest } from 'next/server'` will
become `import { NextRequest } from
'next/dist/server/web/exports/next-request'`, where the NextRequest is
exported as default export. This is fine in most case until you're using
a ESM pkg, then it will be resolved as `{ default: NextRequest }`
according to the spec. Since it's a ESM import to a CJS module in
`next/dist`.
Since we already have the ESM alias introduced in #59852 , this can
handle the case more properly.
### How
Remove the modularize imports config for `next/server`, use the ESM api
alias instead.
Migrate the cjs optimizer tests from middleware to a separate endpoint
`/cjs/server`. As now ESM imports for next/server are not going to get
tree-shaken in dev, but since we don't have image response there it's
still fine.
Closes NEXT-2376
Closes NEXT-2374
### What
When navigating to a page with dynamic params using a certain casing,
and then following a link to another page using _different_ casing for
the same param, the router would get stuck in an infinite suspense
cycle.
### Why
On the client we normalize cache keys by lowercasing the values for
dynamic segments. However the RSC data for each segment wouldn't have
this same casing logic applied. This is causing the router to not
recognize that there is already RSC data available for that segment,
resulting in an infinite suspense cycle.
### How
The `toLowerCase()` logic shouldn't be needed here. Technically we could
leave this in place and update `matchSegment` to also apply the
lowercase logic, but currently there are too many utility functions that
parse segments to comfortably make that change. I confirmed that the bug
related to why we lowercased these router cache keys is no longer
present after making this change.
Fixes#61722
Closes NEXT-2377
### What?
Let the developer check the instance of `ReadonlyURLSearchParams` to
match against `URLSearchParams`
### Why?
`useSearchParams()`'s return type is `ReadonlyURLSearchParams` which
implements all the methods of `URLSearchParams`, therefore its type
should be extended from `URLSearchParams` as well. Deprecated methods
are also implemented to throw an error, so no runtime behavior is being
changed
### How?
Mark the unavailable methods as `@deprecated` which will visually mark
them in IDEs:
![image](https://github.com/vercel/next.js/assets/18369201/f3de2858-14ac-4021-981d-b0267610faa7)
This is similar how `ReadonlyHeaders` extends `Headers`, added in:
#49075
[Slack
thread](https://vercel.slack.com/archives/C03KAR5DCKC/p1706628877916779)
Closes NEXT-2305
### What
Client-side transitioning to a page that triggered a loading boundary
with async metadata would cause the transition to stall, potentially
getting stuck in a refetch loop.
### Why
In layout-router, we trigger a "lazy fetch" when we encounter a segment
that we don't have cache nodes for. This calls out to the server and
suspends until the data fetch is resolved, and applied to the router
tree. However after suspending but before updating the client router, we
set `childNode.lazyData` to null. When we unsuspend from the server
patch action, `childNode.rsc` might still be missing and clearing
`lazyData` means we've blown away the reference to the fetch we already
had pending, triggering a refetch loop.
### How
This removes the logic that mutates the cache node in render, as this is
not concurrent safe, and doesn't appear to be needed for anything.
Fixes#61117
Closes NEXT-2361
---------
Co-authored-by: Jiachi Liu <inbox@huozhi.im>
### What
#### Core
This PR respect the error's digest when recieves new error occurred from
server side, and it will be logged into client on production with the
same `digest` property.
If we discover the original RSC error in SSR error handler, retrieve the
original error
#### Tests
* Move the errors related tests from `test/e2e/app-dir/app` to a
separate test suite `test/e2e/app-dir/errors`
* Add a new test case for logging the original RSC error
* Add a new test case for logging the original Server Action error
### Why
This will help associate the `digest` property of the errors logged from
client with the actual generated server errors. Previously they're
different as we might re-compute the digest proper in handler that react
server renderer thinks it's a new error, which causes we have 2
different errors logged on server side, and 1 logged on client side. The
one on client side can associate to the server errors but it's from
react renderer which is not the original error.
Closes NEXT-2094
Fixes#60684
### What?
I forgot to check the `preload` option when implementing it and just
looked at the `subsets`.
This also fixes duplicate preload tags by adding them to a set in the
default `_document.tsx`
Closes PACK-2392
This PR fixes `.eslintrc.json` not being created after the user runs
`next lint` and selects an option of `Strict` or `Base`.
The reason is that the lint check was looking for `pages` and
`src/pages` only. Added `app` and `src/app` to be checked also.
Fixes: #55094Fixes: #55102
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
### What?
Fixes `setAssetPrefix` when running on a custom server using next()
function
### Why?
Looks like when we run next custom server, there are 2 instances created
to handle this case
* main server in `/server/next.ts`
* and Render server `./server/lib/render-server.ts`
The issue mainly happens when calling `setAssetPrefix` it will update
only the main server and not render server
``` javascript
const next = require('next')
const app = next({ });
app.setAssetPrefix('my-fancy-cdn/static');
app.render(); // render server is used instead of the main server
```
### How?
when calling `setAssetPrefix` on the main server also update the render
server with the same information.
Fixes: #59940Fixes: #51223Fixes: #61383
### Related Resources
#53523#49805c9c6ff6d77/docs/03-pages/01-building-your-application/06-configuring/10-custom-server.mdx
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
### What
This PR attempts to adjust import map to `server-only` / `client-only`
close to the existing webpack configs, makes to pass more tests.
Closes PACK-2396
### What?
This PR adds JSDoc comments to the most common public APIs to improve
the DX in IDEs like VSCode.
### Why?
Currently, we provide no information on some of the most used APIs in
IDEs, which makes it harder than it needs to be to look up the extra
information.
<details>
<summary><b>Before:</b></summary>
<img
src="https://github.com/vercel/next.js/assets/18369201/8b6092e8-8f9b-49da-a3df-b07a59982069"
width="640"/>
</details>
<details>
<summary><b>After:</b></summary>
<img
src="https://github.com/vercel/next.js/assets/18369201/30216f76-414a-43b0-9aa6-2fdd742ab3fe"
width="640"/>
</details>
### How?
Using JSDoc comments, I added a basic description to most public APIs
that link back to the current docs for more details. The description is
kept minimal to avoid out-of-sync documentation.
Note: In the future, the flow could be reversed here, and our API
Reference docs could actually be generated from a single source of
truth, the source code itself. However, this will require more work by
re-organizing our public API submodules in a single directory, (related
#61525), so the API docs are easy to maintain even without a deeper
knowledge of the codebase.
Note: These comments should also be extended to
methods/properties/arguments in these public APIs in the future.
Closes NEXT-2357
[Slack
thread](https://vercel.slack.com/archives/C03KAR5DCKC/p1706735292633029)