Commit Graph

2005 Commits

Author SHA1 Message Date
Jan Kassens
d09484c4aa Use explicit git hash length in version string (#30318)
This avoids potential differences between Git versions.

Having a guarantee unique hash isn't neccessary as it's just
informational and we have the date in the version string as well.
2024-07-11 13:58:11 -04:00
Sebastian Markbåge
9647333b3d Add RN fork of consoleWithStackDev so we can improve the mainline one (#30305)
We're removing this wrapper from the mainline but RN is still using
component stacks to filter out warnings.

This is unfortunate since it'll be hard to keep track of the interplay
with these, DevTools and how you're supposed to implement error dialogs
in userspace.
2024-07-10 13:37:56 -04:00
Sebastian Markbåge
b73dcdc04f [Fizz] Refactor Component Stack Nodes (#30298)
Component stacks have a similar problem to the problem with keyPath
where we had to move it down and set it late right before recursing.
Currently we work around that by popping exactly one off when something
suspends. That doesn't work with the new server stacks being added which
are more than one. It also meant that we kept having add a single frame
that could be popped when there shouldn't need to be one.

Unlike keyPath component stacks has this weird property that once
something throws we might need the stack that was attempted for errors
or the previous stack if we're going to retry and just recreate it.

I've tried a few different approaches and I didn't like either but this
is the one that seems least problematic.

I first split out renderNodeDestructive into a retryNode helper. During
retries only retryNode is called. When we first discover a node, we pass
through renderNodeDestructive.

Instead of add a component stack frame deep inside renderNodeDestructive
after we've already refined a node, we now add it before in
renderNodeDestructive. That way it's only added once before being
attempted. This is similar to how Fiber works where in ChildFiber we
match the node once to create the instance and then later do we attempt
to actually render it and it's only the second part that's ever retried.

This unfortunately means that we now have to refine the node down to
element/lazy/thenables twice. To avoid refining the type too I move that
to be done lazily.
2024-07-09 15:44:01 -04:00
Sebastian Markbåge
c3cdbec0a7 [Flight] Add context for non null prototype error (#30293)
We already added this for other thrown errors, not just console.errors.
There's a production form of this. We just missed adding this context.

Mainly the best context is the line number though which comes from owner
stacks.
2024-07-08 22:51:59 -04:00
Sebastian Markbåge
491a4eacce [DevTools] Print component stacks as error objects to get source mapping (#30289)
Before:

<img width="844" alt="Screenshot 2024-07-04 at 3 20 34 PM"
src="https://github.com/facebook/react/assets/63648/0fd8a53f-538a-4429-a4cf-c22f85a09aa8">

After:

<img width="845" alt="Screenshot 2024-07-05 at 6 08 28 PM"
src="https://github.com/facebook/react/assets/63648/7b9da13a-fa97-4581-9899-06de6fface65">

Firefox:

<img width="1338" alt="Screenshot 2024-07-05 at 6 09 50 PM"
src="https://github.com/facebook/react/assets/63648/f2eb9f2a-2251-408f-86d0-b081279ba378">

The first log doesn't get a stack because it's logged before DevTools
boots up and connects which is unfortunate.

The second log already has a stack printed by React (this is on stable)
it gets replaced by our object now.

The third and following logs don't have a stack and get one appended.

I only turn the stack into an error object if it matches what we would
emit from DevTools anyway. Otherwise we assume it's not React. Since I
had to change the format slightly to make this work, I first normalize
the stack slightly before doing a comparison since it won't be 1:1.
2024-07-08 18:42:58 -04:00
Jan Kassens
b0f51f7e5e Upgrade flow to 0.233.0 (#30116)
See [Flow
changelog](https://github.com/facebook/flow/blob/main/Changelog.md) for
changes in this version.
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/30116).
* #30118
* #30117
* __->__ #30116
2024-07-08 13:48:24 -04:00
Sebastian Markbåge
6e169fc65d [Flight] Allow String Chunks to Passthrough in Node streams and renderToMarkup (#30131)
It can be efficient to accept raw string chunks to pass through a stream
instead of encoding them into a binary copy first.

Previously our Flight parsers didn't accept receiving string chunks.
That's partly because we sometimes need to encode binary chunks anyway
so string only transport isn't enough but some chunks can be strings.
This adds a partial ability for chunks to be received as strings.

However, accepting strings comes with some downsides. E.g. if the
strings are split up we need to buffer it which compromises the perf for
the common case. If the chunk represents binary data, then we'd need to
encode it back into a typed array which would require a TextEncoder
dependency in the parser. If the string chunk represents a byte length
encoded string we don't know how many unicode characters to read without
measuring them in terms of binary - also requiring a TextEncoder.

This PR is mainly intended for use for pass-through within the same
memory. We can simplify the implementation by assuming that any string
chunk is passed as the original chunk. This requires that the server
stream config doesn't arbitrarily concatenate strings (e.g. large
strings should not be concatenated which is probably a good heuristic
anyway). It also means that this is not suitable to be used with for
example receiving string chunks on the client by passing them through
SSR hydration data - except if the encoding that way was only used with
chunks that were already encoded as strings by Flight.

Web streams mostly just work on binary data anyway so they can't use
this.

In Node.js streams we concatenate precomputed and small strings into
larger buffers. It might make sense to do that using string ropes
instead. However, in the meantime we can at least pass large strings
that are outside our buffer view size as raw strings. There's no benefit
to us eagerly encoding those.

Also, let Node accept string chunks as long as they're following our
expected constraints. This lets us test the mixed protocol using
pass-throughs. This can also be useful when the RSC server is in the
same environment as the SSR server as they don't have to go from strings
to typed arrays back to strings.

Now we can also use this in the pass-through used in renderToMarkup.
This lets us avoid the dependency on TextDecoder/TextEncoder in that
package.
2024-07-03 13:25:04 -04:00
Mike Vitousek
05cebffe16 [prettier][eslint] Support sapling in prettier changed files command
Summary: The listChangesFiles module didn't work under sapling; this fixes

ghstack-source-id: 9f685de5e7
Pull Request resolved: https://github.com/facebook/react/pull/30149
2024-06-30 14:22:22 -07:00
Sebastian Markbåge
58af67a8f8 Only build react-html in experimental channel (#30129)
Even though the whole package is private right now. Once we publish it,
it'll likely be just the experimental channel first before upgrading to
stable.

This means it gets excluded from the built packages.
2024-06-28 10:19:20 -04:00
Sebastian Markbåge
1e241f9d6c Add renderToMarkup for Client Components (#30121)
Follow up to #30105.

This supports `renderToMarkup` in a non-RSC environment (not the
`react-server` condition).

This is just a Fizz renderer but it errors at runtime when you use
state, effects or event handlers that would require hydration - like the
RSC version would. (Except RSC can give early errors too.)

To do this I have to move the `react-html` builds to a new `markup`
dimension out of the `dom-legacy` dimension so that we can configure
this differently from `renderToString`/`renderToStaticMarkup`.
Eventually that dimension can go away though if deprecated. That also
helps us avoid dynamic configuration and we can just compile in the
right configuration so the split helps anyway.

One consideration is that if a compiler strips out useEffects or inlines
initial state from useState, then it would not get called an the error
wouldn't happen. Therefore to preserve semantics, a compiler would need
to inject some call that can check the current renderer and whether it
should throw.

There is an argument that it could be useful to not error for these
because it's possible to write components that works with SSR but are
just optionally hydrated. However, there's also an argument that doing
that silently is too easy to lead to mistakes and it's better to error -
especially for the e-mail use case where you can't take it back but you
can replay a queue that had failures. There are other ways to
conditionally branch components intentionally. Besides if you want it to
be silent you can still use renderToString (or better yet
renderToReadableStream).

The primary mechanism is the RSC environment and the client-environment
is really the secondary one that's only there to support legacy
environments. So this also ensures parity with the primary environment.
2024-06-28 09:25:10 -04:00
Sebastian Markbåge
ffec9ec5b5 Add new package with renderToMarkup export (#30105)
Name of the package is tbd (straw: `react-html`). It's a new package
separate from `react-dom` though and can be used as a standalone package
- e.g. also from a React Native app.

```js
import {renderToMarkup} from '...';
const html = await renderToMarkup(<Component />);
```

The idea is that this is a helper for rendering HTML that is not
intended to be hydrated. It's primarily intended to support a subset of
HTML that can be used as embedding and not served as HTML documents from
HTTP. For example as e-mails or in RSS/Atom feeds or other
distributions. It's a successor to `renderToStaticMarkup`.

A few differences:

- This doesn't support "Client Components". It can only use the Server
Components subset. No useEffect, no useState etc. since it will never be
hydrated. Use of those are errors.
- You also can't pass Client References so you can't use components
marked with `"use client"`.
- Unlike `renderToStaticMarkup` this does support async so you can
suspend and use data from these components.
- Unlike `renderToReadableStream` this does not support streaming or
Suspense boundaries and any error rejects the promise. Since there's no
feasible way to "client render" or patch up the document.
- Form Actions are not supported since in an embedded environment
there's no place to post back to across versions. You can render plain
forms with fixed URLs though.
- You can't use any resource preloading like `preload()` from
`react-dom`.

## Implementation

This first version in this PR only supports Server Components since
that's the thing that doesn't have an existing API. Might add a Client
Components version later that errors.

We don't want to maintain a completely separate implementation for this
use case so this uses the `dom-legacy` build dimension to wire up a
build that encapsulates a Flight Server -> Flight Client -> Fizz stream
to render Server Components that then get SSR:ed.

There's no problem to use a Flight Client in a Server Component
environment since it's already supported for Server-to-Server. Both of
these use a bundler config that just errors for Client References though
since we don't need any bundling integration and this is just a
standalone package.

Running Fizz in a Server Component environment is a problem though
because it depends on "react" and it needs the client version.
Therefore, for this build we embed the client version of "react" shared
internals into the build. It doesn't need anything to be able to use
those APIs since you can't call the client APIs anyway.

One unfortunate thing though is that since Flight currently needs to go
to binary and back, we need TextEncoder/TextDecoder to be available but
this shouldn't really be necessary. Also since we use the legacy stream
config, large strings that use byteLengthOfChunk errors atm. This needs
to be fixed before shipping. I'm not sure what would be the best
layering though that isn't unnecessarily burdensome to maintain. Maybe
some kind of pass-through protocol that would also be useful in general
- e.g. when Fizz and Flight are in the same process.

---------

Co-authored-by: Sebastian Silbermann <silbermann.sebastian@gmail.com>
2024-06-27 12:09:40 -04:00
Lauren Tan
27e9476f0a [ci] Cleanup
- Made each workflow's name consistent
- Rename each workflow file with consistent naming scheme
- Promote flow-ci-ghaction to flow-ci

ghstack-source-id: 490b643dcd
Pull Request resolved: https://github.com/facebook/react/pull/30037
2024-06-22 12:37:42 -04:00
Lauren Tan
85215413cb [ci] Improve parallelism of yarn test
This PR adds parallelism similar to our existing circleci setup for
running yarn tests with the various test params. It does this by
sharding tests into `$SHARD_COUNT` number of groups, then spawning a job
for each of them and using jest's built in `--shard` option.

Effectively this means that the job will spawn an additional (where `n`
is the number of test params)

`n * $SHARD_COUNT` number of jobs to run tests in parallel

for a total of `n + (n * $SHARD_COUNT)` jobs. This does mean the
GitHub UI at the bottom of each PR gets longer and unfortunately it's
not sorted in any way as far as I can tell. But if something goes wrong
it should still be easy to find out what the problem is.

The PR also changes the `ci` argument for jest-cli to be an enum instead
so the tests use all available workers in GitHub actions. This will have
to live around for a bit until we can fully migrate off of circleci.

ghstack-source-id: 08f2d16353
Pull Request resolved: https://github.com/facebook/react/pull/30033
2024-06-22 12:37:42 -04:00
Lauren Tan
419ace93ec [ci] Parallelize flow github action
The existing flow-ci script makes some assumptions about running inside
of circleci for parallelization. This PR forks the script with very smal
ll tweaks to allow for a short name to be passed in as an argument.
These short names are discovered in a new GH job and then each one is
passed as an argument for parallelization

ghstack-source-id: dc85486388f74088c22b386b77b45996ef753f1a
Pull Request resolved: https://github.com/facebook/react/pull/30026
2024-06-21 12:32:47 -04:00
Jan Kassens
b565373afd lint: enable reportUnusedDisableDirectives and remove unused suppressions (#28721)
This enables linting against unused suppressions and removes the ones
that were unused.
2024-06-21 12:24:32 -04:00
Lauren Tan
49c37048de [prettier] Combine compiler and runtime configs
Merges the existing config to the root one so we can have a single
configuration file. I've tried to keep the compiler config as much as
possible in this PR so that no formatting changes occur.

ghstack-source-id: 8bbfc9f269
Pull Request resolved: https://github.com/facebook/react/pull/30021
2024-06-21 12:05:29 -04:00
Lauren Tan
0f568418d2 Re-enable prettier for compiler/
Now that the compiler directory has its own prettier config, we can
remove the prettierignore entry for compiler/ so it still runs in your
editor if you open the root directory

ghstack-source-id: 5e3bd597cf2f11a9931f084eb909ffd81ebdca81
Pull Request resolved: https://github.com/facebook/react/pull/29993
2024-06-20 19:09:31 -04:00
nakjun
395e2fc6a0 [chore] Fix TypeError in shouldSkipBundle During yarn build-for-devtools-dev and yarn build-for-devtools-prod Commands (#29906)
## Summary

Fix bundle type filtering logic to correctly handle array input in
argv.type and use some with includes for accurate filtering. This
addresses a TypeError encountered during yarn build-for-devtools-prod
and yarn build-for-devtools-dev commands.

## Motivation

The current implementation of the `shouldSkipBundle` function in
`scripts/rollup/build.js` has two issues:

1. **Incorrect array handling in
`parseRequestedNames`([#29613](https://github.com/facebook/react/issues/29613)):**
    
The function incorrectly wraps the `argv.type` value in an additional
array when it's already an array. This leads to a `TypeError:
names[i].split is not a function` when `parseRequestedNames` attempts to
split the nested array, as seen in this error message:
    
    ```
C:\Users\Administrator\Documents\새 폴더\react\scripts\rollup\build.js:76
        let splitNames = names[i].split(',');
                            ^
    TypeError: names[i].split is not a function
    ```
This PR fixes this by correctly handling both string and array inputs in
`argv.type`:
    
    ```diff
    - const requestedBundleTypes = argv.type
    -   ? parseRequestedNames([argv.type], 'uppercase')
+ const argvType = Array.isArray(argv.type) ? argv.type : [argv.type];
    + const requestedBundleTypes = argv.type
    +   ? parseRequestedNames(argvType, 'uppercase')
    ```
    
2. **Inaccurate filtering logic in
`shouldSkipBundle`([#29614](https://github.com/facebook/react/issues/29614)):**
    
The function uses `Array.prototype.every` with `indexOf` to check if
**all** requested bundle types are missing in the current bundle type.
However, when multiple bundle types are requested (e.g., `['NODE',
'NODE_DEV']`), the function should skip a bundle only if **none** of the
requested types are present. The current implementation incorrectly
allows bundles that match any of the requested types.
    
    To illustrate, consider the following example output:
    
    ```
    requestedBundleTypes [ 'NODE', 'NODE_DEV' ]
    bundleType NODE_DEV
    isAskingForDifferentType false

    requestedBundleTypes [ 'NODE', 'NODE_DEV' ]
    bundleType NODE_PROD
    isAskingForDifferentType false  // Incorrect behavior
    ```
    
In this case, even though the bundle type is `NODE_PROD` and doesn't
include `NODE_DEV`, the bundle is not skipped due to the incorrect
logic.
    
This PR fixes this by replacing `every` with `some` and using `includes`
for a more accurate check:
    
    ```diff
    - const isAskingForDifferentType = requestedBundleTypes.every(
    -   requestedType => bundleType.indexOf(requestedType) === -1
    - );
    + const isAskingForDifferentType = requestedBundleTypes.some(
    +   requestedType => !bundleType.includes(requestedType)
    + );
    ```
    
This ensures that the bundle is skipped only if **none** of the
requested types are found in the `bundleType`.

This PR addresses both of these issues to ensure correct bundle type
filtering in various build scenarios.


## How did you test this change?

1. **Verification of `requestedBundleTypes` usage in
`shouldSkipBundle`:**

   * I manually tested the following scenarios:
* `yarn build`: Verified that `requestedBundleTypes` remains an empty
array, as expected.
* `yarn build-for-devtools`: Confirmed that `requestedBundleTypes` is
correctly set to `['NODE']`, as in the original implementation.
* `yarn build-for-devtools-dev`: This previously failed due to the
error. After the fix, I confirmed that `requestedBundleTypes` is now
correctly passed as `['NODE', 'NODE_DEV']`.

2. **Debugging of filtering logic in `shouldSkipBundle`:**

* I added the following logging statements to the `shouldSkipBundle`
function to observe its behavior during the build process:

     ```javascript
     console.log('requestedBundleTypes', requestedBundleTypes);
     console.log('bundleType', bundleType);
     console.log('isAskingForDifferentType', isAskingForDifferentType);
     ```

* By analyzing the log output, I confirmed that the filtering logic now
correctly identifies when a bundle should be skipped based on the
requested types. This allowed me to verify that the fix enables building
specific target bundles as intended.
2024-06-20 21:12:41 +01:00
Sebastian Markbåge
6b4646cbd0 Export captureOwnerStacks() only in DEV "react" builds (#29923)
Only with the enableOwnerStacks flag (which is not on in www).

This is a new DEV-only API to be able to implement what we do for
console.error in user space.

This API does not actually include the current stack that you'd get from
`new Error().stack`. That you'd have to add yourself.

This adds the ability to have conditional development exports because we
plan on eventually having separate ESM builds that use the "development"
or "production" export conditions.

NOTE: This removes the export of `act` from `react` in prod (as opposed
to a function that throws) - inline with what we do with other
conditional exports.
2024-06-19 14:19:48 -04:00
Ruslan Lesiutin
ff6e05a705 chore[react-devtools]: unify console patching and default to ansi escape symbols (#29869)
Stacked on https://github.com/facebook/react/pull/29856.

## Summary

By default, React DevTools will apply dimming with ANSI escape symbols,
so it works for both terminals and browser consoles.

For Firefox, which doesn't support ANSI escape symbols console stylings,
we fallback to css properties, like we used to do before.

## How did you test this change?

| Environment | Dark mode | Light mode |
|--------|--------|--------|
| Terminal | ![Screenshot 2024-06-12 at 19 39
46](https://github.com/facebook/react/assets/28902667/2d470eee-ec5f-4362-be7d-8d80c6c72d09)
| ![Screenshot 2024-06-12 at 19 39
09](https://github.com/facebook/react/assets/28902667/616f2c58-a251-406b-aee6-841e07d652ba)
|
| Fusebox&nbsp;console | ![Screenshot 2024-06-12 at 21 03
14](https://github.com/facebook/react/assets/28902667/6050f730-8e82-4aa1-acbc-7179aac3a8aa)
| ![Screenshot 2024-06-12 at 21 02
48](https://github.com/facebook/react/assets/28902667/6708b938-8a90-476f-a057-427963d58caa)
|
| Firefox&nbsp;console | ![Screenshot 2024-06-12 at 21 40
29](https://github.com/facebook/react/assets/28902667/4721084f-bbfa-438c-b61b-395da8ded590)
| ![Screenshot 2024-06-12 at 21 40
42](https://github.com/facebook/react/assets/28902667/72bbf001-2d3d-49e7-91c9-20a4f0914d4d)
|
| Chrome&nbsp;console | ![Screenshot 2024-06-12 at 21 43
09](https://github.com/facebook/react/assets/28902667/93c47881-a0dd-44f8-8dc2-8710149774e5)
| ![Screenshot 2024-06-12 at 21 43
00](https://github.com/facebook/react/assets/28902667/07ea4ff5-4322-4db9-9c12-4321d9577c9d)
|
2024-06-17 16:31:36 +01:00
Lenz Weber-Tronic
50e89ec9f2 Avoid acccessing React internals from use-sync-external-store/shim (#29868)
Co-authored-by: eps1lon <sebastian.silbermann@vercel.com>
2024-06-12 20:13:17 +02:00
Ricky
d172bdaf95 Add jest lint rules (#29760)
## Overview

Updates `eslint-plugin-jest` and enables the recommended rules with some
turned off that are unhelpful.

The main motivations is:
a) we have a few duplicated tests, which this found an I deleted 
b) making sure we don't accidentally commit skipped tests
2024-06-10 14:31:37 -04:00
Ricky
6b35ff766a Move @generated from build to sync (#29799)
## Overview

Reverts https://github.com/facebook/react/pull/26616 and implements the
suggested way instead.

This change in #26616 broken the internal sync command, which now
results in duplicated `@generated` headers. It also makes it harder to
detect changes during the diff train sync. Instead, we will check for
changes, and if there are changes sign the files and commit them to the
sync branch.

## Strategy

The new sync strategy accounts for the generated headers during the
sync:
- **Revert Version**: Revert the version strings
- **Revert @generated**: Re-sign the files (will be the same hash as
before if unchanged)
- **Check**: Check if there are changes **if not, skip**
- **Re-apply Version**: Now add back the new version string
- **Re-sign @generated**: And re-generate the headers

Then commit to branch. This ensures that if there are no changes, we'll
skip.

---------

Co-authored-by: Timothy Yung <yungsters@gmail.com>
2024-06-10 10:16:40 -04:00
Sebastian Markbåge
c2ae9e28bc Minify DEV bundles with closure (#29809)
The goal is to improve speed of the development by inlining and DCE
unused branches.

We have the ability to preserve some variable names and pretty print in
the production version so might as well do the same with DEV.
2024-06-08 11:15:57 -04:00
Josh Story
c4b433f8cb [Flight] Allow aborting during render (#29764)
Stacked on #29491

Previously if you aborted during a render the currently rendering task
would itself be aborted which will cause the entire model to be replaced
by the aborted error rather than just the slot currently being rendered.

This change updates the abort logic to mark currently rendering tasks as
aborted but allowing the current render to emit a partially serialized
model with an error reference in place of the current model.

The intent is to support aborting from rendering synchronously, in
microtasks (after an await or in a .then) and in lazy initializers. We
don't specifically support aborting from things like proxies that might
be triggered during serialization of props
2024-06-06 14:41:27 -07:00
Ricky
90499a730e Fix RN version string in builds (#29787)
The version was set for React but not the renderers
2024-06-06 14:07:16 -04:00
Josh Story
b526a0a419 [Flight][Fizz] schedule work async (#29551)
While most builds of Flight and Fizz schedule work in new tasks some do
execute work synchronously. While this is necessary for legacy APIs like
renderToString for modern APIs there really isn't a great reason to do
this synchronously.

We could schedule works as microtasks but we actually want to yield so
the runtime can run events and other things that will unblock additional
work before starting the next work loop.

This change updates all non-legacy uses to be async using the best
availalble macrotask scheduler.

Browser now uses postMessage
Bun uses setTimeout because while it also supports setImmediate the
scheduling is not as eager as the same API in node
the FB build also uses setTimeout

This change required a number of changes to tests which were utilizing
the sync nature of work in the Browser builds to avoid having to manage
timers and tasks. I added a patch to install MessageChannel which is
required by the browser builds and made this patched version integrate
with the Scheduler mock. This way we can effectively use `act` to flush
flight and fizz work similar to how we do this on the client.
2024-06-06 10:07:24 -07:00
Ricky
eabb681535 Add xplat test variants (#29734)
## Overview

We didn't have any tests that ran in persistent mode with the xplat
feature flags (for either variant).

As a result, invalid test gating like in
https://github.com/facebook/react/pull/29664 were not caught.

This PR adds test flavors for `ReactFeatureFlag-native-fb.js` in both
variants.
2024-06-04 13:07:29 -04:00
Ricky
8c3697a849 Fix xplat sync to ignore @generated header (#29738)
Use some clever git diffing to ignore lines that only change the
`@generated` header. We can't do this for the version string because the
version string can be embedded in lines with other changes, but this
header is always on one line.
2024-06-03 16:39:38 -04:00
Andrew Clark
bf3a29d097 Update build script to automatically generate RCs (#29736)
RC releases are a special kind of prerelease build because unlike
canaries we shouldn't publish new RCs from any commit on `main`, only
when we intentionally bump the RC number. But they are still prerelases
— like canary and experimental releases, they should use exact version
numbers in their dependencies (no ^).

We only need to generate these builds during the RC phase, i.e. when the
canary channel label is set to "rc".

Example of resulting package.json output:

```json
{
  "name": "react-dom",
  "version": "19.0.0-rc.0",
  "dependencies": {
    "scheduler": "0.25.0-rc.0"
  },
  "peerDependencies": {
    "react": "19.0.0-rc.0"
  }
}
```


https://react-builds.vercel.app/prs/29736/files/oss-stable-rc/react-dom/package.json
2024-06-03 12:21:21 -04:00
Josh Story
def67b9b32 Fix stylesheet typo in 29693 (#29732)
stylehsheet -> stylesheet
2024-06-03 07:51:21 -07:00
Josh Story
47d0c30246 [Fiber][Float] Error when a host fiber changes "flavor" (#29693)
Host Components can exist as four semantic types

1. regular Components (Vanilla obv)
2. singleton Components
2. hoistable components
3. resources

Each of these component types have their own rules related to mounting
and reconciliation however they are not direclty modeled as their own
unique fiber type. This is partly for code size but also because
reconciling the inner type of these components would be in a very hot
path in fiber creation and reconciliation and it's just not practical to
do this logic check here.

Right now we have three Fiber types used to implement these 4 concepts
but we probably need to reconsider the model and think of Host
Components as a single fiber type with an inner implementation. Once we
do this we can regularize things like transitioning between a resource
and a regular component or a singleton and a hoistable instance. The
cases where these transitions happen today aren't particularly common
but they can be observed and currently the handling of these transitions
is incomplete at best and buggy at worst. The most egregious case is the
link type. This can be a regular component (stylesheet without
precedence) a hoistable component (non stylesheet link tags) or a
resource (stylesheet with a precedence) and if you have a single jsx
slot that tries to reconcile transitions between these types it just
doesn't work well.

This commit adds an error for when a Hoistable goes from Instance to
Resource. Currently this is only possible for `<link>` elements going to
and from stylesheets with precedence. Hopefully we'll be able to remove
this error and implement as an inner type before we encounter new
categories for the Hoistable types

detecting type shifting to and from regular components is harder to do
efficiently because we don't want to reevaluate the type on every update
for host components which is currently not required and would add
overhead to a very hot path

singletons can't really type shift in their one practical implementation
(DOM) so they are only a problem in theroy not practice
2024-06-03 07:47:45 -07:00
Ricky
5ad2c37273 Skip empty sync commits (both repos) (#29707)
Requires https://github.com/facebook/react/pull/29706

The strategy here is to:
- Checkout the builds/facebook-www branch
- Read the current sync'd VERSION
- Checkout out main and sync new build
- sed/{new version string}/{old version string}
- Run git status, skip sync if clean
- Otherwise, sed/{old version string}/{new version string} and push
commit

This means that:
- We're using the real version strings from the builds
- We are checking the last commit on the branch for the real last
version
- We're skipping any commits that won't result in changes
- ???
- Profit!
2024-06-03 10:09:23 -04:00
Timothy Yung
5bd4031226 Revert Build Versions from Content Hash to Commit Hash (#29663)
https://github.com/facebook/react/pull/29236 caused issues for internal
syncs at Meta, because we were computing version numbers using file
hashes (to eliminate "no-op" internal sync commits). The problem is that
since version numbers may not be consistent across synced files (e.g. if
some files have not changed in recent commits), the newly introduced
version mismatch check fails.

There's some more work that needs to be done here to restore the
benefits of file-specific hashing, but for now this simply reverts the
content hash changes from the following PRs:

- https://github.com/facebook/react/pull/28633
(95319ab5af)
- https://github.com/facebook/react/pull/28590
(37676aba76)
- https://github.com/facebook/react/pull/28582
(cb076b593c)
- https://github.com/facebook/react/pull/26734
(5dd90c5623)
- https://github.com/facebook/react/pull/26331
(3cad3a54ed)
2024-05-30 07:26:12 -07:00
Sophie Alpert
38e3b23483 Tweak error message for "Should have a queue" (#29626) 2024-05-29 08:41:10 -07:00
Jack Pope
2787eebe52 Clean up disableDOMTestUtils (#29610)
`disableDOMTestUtils` and the FB build `ReactTestUtilsFB` allowed us to
finish migrating internal callsites off of ReactTestUtils. Now that
usage is cleaned up, we can remove the flag, build artifact, and test
coverage for the deprecated utility methods.
2024-05-28 14:55:14 -04:00
Andrew Clark
681a4aa810 Throw if React and React DOM versions don't match (#29236)
Throw an error during module initialization if the version of the
"react-dom" package does not match the version of "react".

We used to be more relaxed about this, because the "react" package
changed so infrequently. However, we now have many more features that
rely on an internal protocol between the two packages, including Hooks,
Float, and the compiler runtime. So it's important that both packages
are versioned in lockstep.

Before this change, a version mismatch would often result in a cryptic
internal error with no indication of the root cause.

Instead, we will now compare the versions during module initialization
and immediately throw an error to catch mistakes as early as possible
and provide a clear error message.
2024-05-28 14:06:30 -04:00
Sebastian Markbåge
d6cfa0f295 [Fiber] Use Owner/JSX Stack When Appending Stacks to Console (#29206)
This one should be fully behind the `enableOwnerStacks` flag.

Instead of printing the parent Component stack all the way to the root,
this now prints the owner stack of every JSX callsite. It also includes
intermediate callsites between the Component and the JSX call so it has
potentially more frames. Mainly it provides the line number of the JSX
callsite. In terms of the number of components is a subset of the parent
component stack so it's less information in that regard. This is usually
better since it's more focused on components that might affect the
output but if it's contextual based on rendering it's still good to have
parent stack. Therefore, I still use the parent stack when printing DOM
nesting warnings but I plan on switching that format to a diff view
format instead (Next.js already reformats the parent stack like this).

__Follow ups__

- Server Components show up in the owner stack for client logs but logs
done by Server Components don't yet get their owner stack printed as
they're replayed. They're also not yet printed in the server logs of the
RSC server.

- Server Component stack frames are formatted as the server and added to
the end but this might be a different format than the browser. E.g. if
server is running V8 and browser is running JSC or vice versa. Ideally
we can reformat them in terms of the client formatting.

- This doesn't yet update Fizz or DevTools. Those will be follow ups.
Fizz still prints parent stacks in the server side logs. The stacks
added to user space `console.error` calls by DevTools still get the
parent stacks instead.

- It also doesn't yet expose these to user space so there's no way to
get them inside `onCaughtError` for example or inside a custom
`console.error` override.

- In another follow up I'll use `console.createTask` instead and
completely remove these stacks if it's available.
2024-05-25 11:58:17 -04:00
Sebastian Markbåge
2e540e22b2 Set the current fiber to the source of the error during error reporting (#29044)
This lets us expose the component stack to the error reporting that
happens here as `console.error` patching. Now if you just call
`console.error` in the error handlers it'll get the component stack
added to the end by React DevTools.

However, unfortunately this happens a little too late so the Fiber will
be disconnected with its `.return` pointer set to null already. So it'll
be too late to extract a parent component stack from but you can at
least get the stack from source to error boundary. To work around this I
manually add the parent component stack in our default handlers when
owner stacks are off. We could potentially fix this but you can also
just include it yourself if you're calling `console.error` and it's not
a problem for owner stacks.

This is not a problem for owner stacks because we'll still have those
and so for those just calling `console.error` just works. However, the
main feature is that by letting React add them, we can switch to using
native error stacks when available.
2024-05-23 12:39:52 -04:00
Jan Kassens
26f2496093 Remove 2 no longer existing files from inlinedHostConfig (#29027)
Remove 2 no longer existing files from inlinedHostConfig

While looking for `.classic` forks, I noticed these files no longer
exist.
2024-05-14 10:07:00 -04:00
Sebastian Markbåge
6c409acefd [Flight Reply] Encode Objects Returned to the Client by Reference (#29010)
Stacked on #28997.

We can use the technique of referencing an object by its row + property
name path for temporary references - like we do for deduping. That way
we don't need to generate an ID for temporary references. Instead, they
can just be an opaque marker in the slot and it has the implicit ID of
the row + path.

Then we can stash all objects, even the ones that are actually available
to read on the server, as temporary references. Without adding anything
to the payload since the IDs are implicit. If the same object is
returned to the client, it can be referenced by reference instead of
serializing it back to the client. This also helps preserve object
identity.

We assume that the objects are immutable when they pass the boundary.

I'm not sure if this is worth it but with this mechanism, if you return
the `FormData` payload from a `useActionState` it doesn't have to be
serialized on the way back to the client. This is a common pattern for
having access to the last submission as "default value" to the form
fields. However you can still control it by replacing it with another
object if you want. In MPA mode, the temporary references are not
configured and so it needs to be serialized in that case. That's
required anyway for hydration purposes.

I'm not sure if people will actually use this in practice though or if
FormData will always be destructured into some other object like with a
library that turns it into typed data, and back. If so, the object
identity is lost.
2024-05-09 20:00:56 -04:00
Sebastian Markbåge
151cce3740 Track Stack of JSX Calls (#29032)
This is the first step to experimenting with a new type of stack traces
behind the `enableOwnerStacks` flag - in DEV only.

The idea is to generate stacks that are more like if the JSX was a
direct call even though it's actually a lazy call. Not only can you see
which exact JSX call line number generated the erroring component but if
that's inside an abstraction function, which function called that
function and if it's a component, which component generated that
component. For this to make sense it really need to be the "owner" stack
rather than the parent stack like we do for other component stacks. On
one hand it has more precise information but on the other hand it also
loses context. For most types of problems the owner stack is the most
useful though since it tells you which component rendered this
component.

The problem with the platform in its current state is that there's two
ways to deal with stacks:

1) `new Error().stack` 
2) `console.createTask()`

The nice thing about `new Error().stack` is that we can extract the
frames and piece them together in whatever way we want. That is great
for constructing custom UIs like error dialogs. Unfortunately, we can't
take custom stacks and set them in the native UIs like Chrome DevTools.

The nice thing about `console.createTask()` is that the resulting stacks
are natively integrated into the Chrome DevTools in the console and the
breakpoint debugger. They also automatically follow source mapping and
ignoreLists. The downside is that there's no way to extract the async
stack outside the native UI itself so this information cannot be used
for custom UIs like errors dialogs. It also means we can't collect this
on the server and then pass it to the client for server components.

The solution here is that we use both techniques and collect both an
`Error` object and a `Task` object for every JSX call.

The main concern about this approach is the performance so that's the
main thing to test. It's certainly too slow for production but it might
also be too slow even for DEV.

This first PR doesn't actually use the stacks yet. It just collects them
as the first step. The next step is to start utilizing this information
in error printing etc.

For RSC we pass the stack along across over the wire. This can be
concatenated on the client following the owner path to create an owner
stack leading back into the server. We'll later use this information to
restore fake frames on the client for native integration. Since this
information quickly gets pretty heavy if we include all frames, we strip
out the top frame. We also strip out everything below the functions that
call into user space in the Flight runtime. To do this we need to figure
out the frames that represents calling out into user space. The
resulting stack is typically just the one frame inside the owner
component's JSX callsite. I also eagerly strip out things we expect to
be ignoreList:ed anyway - such as `node_modules` and Node.js internals.
2024-05-09 12:23:05 -04:00
Sebastian Markbåge
6bac4f2f31 [Fizz] Fallback to client replaying actions if we're trying to serialize a Blob (#28987)
This follows the same principle as in #28611.

We cannot serialize Blobs of a form data into HTML because you can't
initialize a file input to some value. However the serialization of
state in an Action can contain blobs. In this case we do error but
outside the try/catch that recovers to error to client replaying instead
of MPA mode. This errors earlier to ensure that this works.

Testing this is a bit annoying because JSDOM doesn't have any of the
Blob methods but the Blob needs to be compatible with FormData and the
FormData needs to be compatible with `<form>` nodes in these tests. So I
polyfilled those in JSDOM with some hacks.

A possible future enhancement would be to encode these blobs in a base64
mode instead and have some way to receive them on the server. It's just
a matter of layering this. I think the RSC layer's `FORM_DATA`
implementation can pass some flag to encode as base64 and then have
decodeAction include some way to parse them. That way this case would
work in MPA mode too.
2024-05-07 21:53:10 -04:00
Sebastian Silbermann
0fc9c84e63 Allow specifying timeout in tests via third argument (#29006) 2024-05-07 17:15:39 +02:00
Jack Pope
5d29478716 Add FB build for ReactReconcilerConstants (#29003)
In order to integrate the `react-reconciler` build created in #28880
with third party libraries, we need to have matching
`react-reconciler/constants` to go with it.
2024-05-06 11:32:43 -04:00
Jan Kassens
0a0a3af75a Bundle config: inline internal hook wrapper (#28978)
Bundle config: inline internal hook wrapper

Instead of reading this wrapper from 2 files for "start" and "end" and
then string modifying the templates, just inline them like the other
wrappers in this file.
2024-05-03 14:08:10 -04:00
Moti Zilberman
8f7dd5592b [DevTools] Check in frontend.d.ts for react-devtools-fusebox, include in build output (#28970)
## Summary

The `react-devtools-fusebox` private package is used in the React Native
DevTools (Fusebox) frontend by checking build artifacts into RN's
[fork]([`facebookexperimental/rn-chrome-devtools-frontend`](https://github.com/facebookexperimental/rn-chrome-devtools-frontend))
of the Chrome DevTools (CDT) repo - see
https://github.com/facebookexperimental/rn-chrome-devtools-frontend/pull/22.

Currently, the CDT fork also includes a [manually written TypeScript
definition
file](1d5f8d5209/front_end/third_party/react-devtools/package/frontend.d.ts)
which describes `react-devtools-fusebox`'s API. This PR moves that file
into the React repo, next to the implementation of
`react-devtools-fusebox`, so we can update it atomically with changes to
the package.

As this is the first bit of TypeScript in this repo, the PR adds minimal
support for formatting `.d.ts` files with Prettier. It also opts out
`react-devtools-fusebox/dist/` from linting/formatting as a drive-by
fix.

For now, we'll just maintain the `.d.ts` file manually, but we could
consider leveraging
[`flow-api-translator`](https://www.npmjs.com/package/flow-api-translator)
to auto-generate it in the future.

## How did you test this change?

Build `react-devtools-fusebox`, observe that `dist/frontend.d.ts`
exists.
2024-05-03 17:32:41 +01:00
Jan Kassens
4508873393 Move useMemoCache hook to react/compiler-runtime (#28954)
Move useMemoCache hook to react/compiler-runtime

For Meta-internal purposes, we keep the export on `react` itself to
reduce churn.
2024-04-30 12:00:22 -04:00
Alex Yang
8090457c77 fix: add react-server condition for react/jsx-dev-runtime (#28921) 2024-04-27 21:45:52 +02:00
Josh Story
cb151849e1 [react-dom] move all client code to react-dom/client (#28271)
This PR reorganizes the `react-dom` entrypoint to only pull in code that
is environment agnostic. Previously if you required anything from this
entrypoint in any environment the entire client reconciler was loaded.
In a prior release we added a server rendering stub which you could
alias in server environments to omit this unecessary code. After landing
this change this entrypoint should not load any environment specific
code.

While a few APIs are truly client (browser) only such as createRoot and
hydrateRoot many of the APIs you import from this package are only
useful in the browser but could concievably be imported in shared code
(components running in Fizz or shared components as part of an RSC app).
To avoid making these require opting into the client bundle we are
keeping them in the `react-dom` entrypoint and changing their
implementation so that in environments where they are not particularly
useful they do something benign and expected.

#### Removed APIs
The following APIs are being removed in the next major. Largely they
have all been deprecated already and are part of legacy rendering modes
where concurrent features of React are not available
* `render`
* `hydrate`
* `findDOMNode`
* `unmountComponentAtNode`
* `unstable_createEventHandle`
* `unstable_renderSubtreeIntoContainer`
* `unstable_runWithPrioirty`

#### moved Client APIs
These APIs were available on both `react-dom` (with a warning) and
`react-dom/client`. After this change they are only available on
`react-dom/client`
* `createRoot`
* `hydrateRoot`

#### retained APIs
These APIs still exist on the `react-dom` entrypoint but have normalized
behavior depending on which renderers are currently in scope
* `flushSync`: will execute the function (if provided) inside the
flushSync implemention of FlightServer, Fizz, and Fiber DOM renderers.
* `unstable_batchedUpdates`: This is a noop in concurrent mode because
it is now the only supported behavior because there is no legacy
rendering mode
* `createPortal`: This just produces an object. It can be called from
anywhere but since you will probably not have a handle on a DOM node to
pass to it it will likely warn in environments other than the browser
* preloading APIS such as `preload`: These methods will execute the
preload across all renderers currently in scope. Since we resolve the
Request object on the server using AsyncLocalStorage or the current
function stack in practice only one renderer should act upon the
preload.

In addition to these changes the server rendering stub now just rexports
everything from `react-dom`. In a future minor we will add a warning
when using the stub and in the next major we will remove the stub
altogether
2024-04-24 08:50:32 -07:00