Commit Graph

19167 Commits

Author SHA1 Message Date
Sebastian Markbåge
14fdd0e21c [Flight] Serialize rate limited objects in console logs as marker an increase limit (#30294)
This marker can then be emitted as a getter. When this object gets
accessed we use a special error to let the user know what is going on.

<img width="1350" alt="Screenshot 2024-07-08 at 10 13 46 PM"
src="https://github.com/facebook/react/assets/63648/e3eb698f-e02d-4394-a051-ba9ac3236480">

When you click the `...`:
<img width="1357" alt="Screenshot 2024-07-08 at 10 13 56 PM"
src="https://github.com/facebook/react/assets/63648/4b8ce1cf-d762-49a4-97b9-aeeb1aa8722c">

I also increased the object limit in console logs. It was arbitrarily
set very low before.

These limits are per message. So if you have a loop of many logs it can
quickly add up a lot of strain on the server memory and the client. This
is trying to find some tradeoff. Unfortunately we don't really do much
deduping in these logs so with cyclic objects it ends up maximizing the
limit and then siblings aren't logged.

Ideally we should be able to lazy load them but that requires a lot of
plumbing to wire up so if we can avoid it we should try to. If we want
to that though one idea is to use the getter to do a sync XHR to load
more data but the server needs to retain the objects in memory for an
unknown amount of time. The client could maybe send a signal to retain
them until a weakref clean up but even then it kind of needs a heartbeat
to let the server know the client is still alive. That's a lot of
complexity. There's probably more we can do to optimize deduping and
other parts of the protocol to make it possible to have even higher
limits.
2024-07-10 00:15:15 -04:00
Sebastian Markbåge
3b2e5f27c5 [Fiber] Override the getCurrentStack temporarily while printing errors (#30300)
Only for parent stacks. This ensures that we can use the regular
mechanism for appending stack traces. E.g. you can polyfill it.

This is mainly so that I can later remove the automatic appending.
2024-07-10 00:15:00 -04:00
Jan Kassens
39e69dc665 Dedupe legacy context warnings (#30299)
Similar to other warnings about legacy APIs, only raise a warning once per component.
2024-07-09 19:55:09 -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
8aafbcf115 [Flight] Fully support serializing Map/Set in console logs (#30295)
Currently we serialize Map/Set through our regular flow and not the
console serialization. The console one is more forgiving than the
regular one.
2024-07-09 14:22:50 -04:00
Jan Kassens
ba95cf4b8f Remove propTypes on instance warning (#30296)
`propTypes` are no longer supported at all in React 19, remove this
outdated warning.
2024-07-09 13:29:50 -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
Sebastian Markbåge
274c980c53 Warn for useFormState on initial render (#30292)
This was missed in the mount dev dispatcher. It was only in the rerender
dispatcher which means that it was only logged during the rerender.
Since DevTools can hide logs during rerenders, this hid the warning in
StrictMode.
2024-07-08 16:45:24 -04:00
Jan Kassens
21129d34a5 Upgrade flow to 0.235.0 (#30118)
See [Flow
changelog](https://github.com/facebook/flow/blob/main/Changelog.md) for
changes in this version.
2024-07-08 14:11:11 -04:00
Jan Kassens
094041495b Upgrade flow to 0.234.0 (#30117)
See [Flow
changelog](https://github.com/facebook/flow/blob/main/Changelog.md) for
changes in this version.
2024-07-08 14:00:00 -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
df783f9ea1 Add unknown location information to component stacks (#30290)
This is the same change as in #30289 but for the main runtime - e.g.
parent stacks in errorInfo.componentStack, appended stacks to
console.error coming from React itself and when we add virtual frames to
owner stacks.

Since we don't add location information these frames look weird to some
stack parsers - such as the native one. This is an existing issue when
you want to use some off-the-shelf parsers to parse production component
stacks for example.

While we won't add Error objects to logs ourselves necessarily, some
third party could want to do the same thing we do in DevTools and so we
should provide the same capability to just take this trace and print it
using an Error object.
2024-07-08 11:54:14 -04:00
Sebastian Silbermann
1b0132c05a Consider dispatch from useActionState stable (#29665) 2024-07-06 08:52:20 +02:00
Sebastian Markbåge
f38c22b244 [Flight] Set Current Owner / Task When Calling console.error or invoking onError/onPostpone (#30206)
Stacked on #30197.

This is similar to #30182 and #21610 in Fizz.

Track the current owner/stack/task on the task. This tracks it for
attribution when serializing child properties.

This lets us provide the right owner and createTask when we
console.error from inside Flight itself. This also affects the way we
print those logs on the client since we need the owner and stack. Now
console.errors that originate on the server gets the right stack on the
client:

<img width="760" alt="Screenshot 2024-07-03 at 6 03 13 PM"
src="https://github.com/facebook/react/assets/63648/913300f8-f364-4e66-a19d-362e8d776c64">

Unfortunately, because we don't track the stack we never pop it so it'll
keep tracking for serializing sibling properties. We rely on "children"
typically being the last property in the common case anyway. However,
this can lead to wrong attribution in some cases where the invalid
property is a next property (without a wrapping element) and there's a
previous element that doesn't. E.g. `<ClientComponent title={<div />}
invalid={nonSerializable} />` would use the div as the attribution
instead of ClientComponent.

I also wrap all of our own console.error, onError and onPostpone in the
context of the parent component. It's annoying to have to remember to do
this though.

We could always wrap the whole rendering in such as context but it would
add more overhead since this rarely actually happens. It might make
sense to track the whole current task instead to lower the overhead.
That's what we do in Fizz. We'd still have to remember to restore the
debug task though. I realize now Fizz doesn't do that neither so the
debug task isn't wrapping the console.errors that Fizz itself logs.
There's something off about that Flight and Fizz implementations don't
perfectly align.
2024-07-04 12:31:23 -04:00
Sebastian Markbåge
0b5835a46f [Flight] Implement captureStackTrace and owner stacks on the Server (#30197)
Wire up owner stacks in Flight to the shared internals. This exposes it
to `captureOwnerStack()`.

In this case we install it permanently as we only allow one RSC renderer
which then supports async contexts. Same thing we do for owner.

This also ends up adding it to errors logged by React through
`consoleWithStackDev`. The plan is to eventually remove that but this is
inline with what we do in Fizz and Fiber already.

However, at the same time we've instrumented the console so we need to
strip them back out before sending to the client. This lets the client
control whether to add the stack back in or allowing
`console.createTask` to control it.

This is another reason we shouldn't append them from React but for now
we hack it by removing them after the fact.
2024-07-04 12:15:51 -04:00
Sebastian Markbåge
8e9de898d3 [Flight] Add option to replay console logs or not (#30207)
Defaults to true in browser builds, otherwise defaults to false. The
assumption is that the server logs will already contain a log from the
original Flight server.

We currently always replay console logs but this leads to duplicates on
the server by default when you use SSR, because the Flight Client on the
server replays the logs. This can be nice since those logs gets badged.
It can also be nice if they're running in separate servers but when
they're logging to the same stream it's annoying. Which is really the
typical set up so we should just make that the default but leave it
configurable.
2024-07-04 12:15:35 -04:00
Jack Works
3da26163a3 fix: path handling in react devtools (#29199)
<!--
  Thanks for submitting a pull request!
We appreciate you spending the time to work on these changes. Please
provide enough information so that others can review your pull request.
The three fields below are mandatory.

Before submitting a pull request, please make sure the following is
done:

1. Fork [the repository](https://github.com/facebook/react) and create
your branch from `main`.
  2. Run `yarn` in the repository root.
3. If you've fixed a bug or added code that should be tested, add tests!
4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch
TestName` is helpful in development.
5. Run `yarn test --prod` to test in the production environment. It
supports the same options as `yarn test`.
6. If you need a debugger, run `yarn test --debug --watch TestName`,
open `chrome://inspect`, and press "Inspect".
7. Format your code with
[prettier](https://github.com/prettier/prettier) (`yarn prettier`).
8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only
check changed files.
  9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`).
  10. If you haven't already, complete the CLA.

Learn more about contributing:
https://reactjs.org/docs/how-to-contribute.html
-->

## Summary

Fix how devtools handles URLs. It

- cannot handle relative source map URLs `//# sourceMappingURL=x.map`
- cannot recognize Windows style URLs

## How did you test this change?

works on my side
2024-07-04 15:34:48 +01:00
Sebastian Markbåge
15ca8b6bad Don't strip out component stack in assertConsole helpers (#30204)
Use the same normalizeCodeLocInfo that we use everywhere else.

We should actually test the component stack itself. Not just that it
exists. This was causing false passes.

However, the logic was also wrong before because it wouldn't always
strip out the last line so wouldn't accurately normalize it. Leading to
false failures as well.
2024-07-03 16:57:05 -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
Hendrik Liebau
9c6806964f Add regression test for #30172 (#30198)
The issue reported in #30172 was fixed with #29823. The PR also added
the test [`should resolve deduped objects that are themselves
blocked`](6d2a97a711/packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMBrowser-test.js (L348-L393)),
which tests a similar scenario. However, the existing test would have
also succeeded before applying the changes from #29823. Therefore, I
believe it makes sense to add an additional test `should resolve deduped
objects in nested children of blocked models`, which does not succeed
without #29823, to prevent regressions.
2024-07-03 07:10:23 -04:00
Ruslan Lesiutin
572ded3762 React DevTools 5.3.0 -> 5.3.1 (#30199)
## Summary

Full list of changes, mostly fixes:
* chore[react-devtools/renderer]: dont show strict mode warning for prod
renderer builds ([hoxyq](https://github.com/hoxyq) in
[#30158](https://github.com/facebook/react/pull/30158))
* chore[react-devtools/ui]: fix strict mode badge styles
([hoxyq](https://github.com/hoxyq) in
[#30159](https://github.com/facebook/react/pull/30159))
* fix[react-devtools]: restore original args when recording errors
([hoxyq](https://github.com/hoxyq) in
[#30091](https://github.com/facebook/react/pull/30091))
* Read constructor name more carefully
([LoganDark](https://github.com/LoganDark) in
[#29954](https://github.com/facebook/react/pull/29954))
* refactor[react-devtools/extensions]: dont debounce cleanup logic on
navigation ([hoxyq](https://github.com/hoxyq) in
[#30027](https://github.com/facebook/react/pull/30027))
* lint: enable reportUnusedDisableDirectives and remove unused
suppressions ([kassens](https://github.com/kassens) in
[#28721](https://github.com/facebook/react/pull/28721))
* fix[react-devtools/extensions]: propagate globals from env
([hoxyq](https://github.com/hoxyq) in
[#29963](https://github.com/facebook/react/pull/29963))
* refactor[react-devtools/tests]: use registered marks instead of
cleared in tests ([hoxyq](https://github.com/hoxyq) in
[#29929](https://github.com/facebook/react/pull/29929))
2024-07-03 11:46:46 +01:00
Sebastian Markbåge
3db98c9177 [Fizz] Track Current debugTask and run it for onError Callbacks (#30182)
Stacked on #30174.

This tracks the current debugTask on the Task so that when an error is
thrown we can use it to run the `onError` (and `onShellError` and
`onFatalError`) callbacks within the Context of that task. Ideally it
would be associated with the error object but neither console.error [nor
reportError](https://crbug.com/350426235) reports this as the async
stack so we have to manually restore it.

That way when you inspect Fizz using node `--inspect` we show the right
async stack.

<img width="616" alt="Screenshot 2024-07-01 at 10 52 29 PM"
src="https://github.com/facebook/react/assets/63648/db68133e-124e-4509-8241-c67160db94fc">

This is equivalent to how we track the task that created the parent
server component or the Fiber:


6d2a97a711/packages/react-reconciler/src/ReactChildFiber.js (L1985)

Then use them when invoking the error callbacks:


6d2a97a711/packages/react-reconciler/src/ReactFiberThrow.js (L104-L108)

---------

Co-authored-by: Sebastian Silbermann <silbermann.sebastian@gmail.com>
2024-07-02 19:46:18 -04:00
Sebastian Markbåge
cfb8945f51 [Fizz] Implement debugInfo (#30174)
Stacked on #30170.

This lets us track Server Component parent stacks in Fizz which also
lets us track the correct owner stack for lazy.

In Fiber we're careful not to make any DEV only fibers but since the
ReactFizzComponentStack data structures just exist for debug meta data
anyway we can just expand on that.
2024-07-02 18:26:32 -04:00
Sebastian Markbåge
309e146193 Implement onError signature for renderToMarkup (#30170)
Stacked on #30132.

This way we can get parent and owner stacks from the error.

This forces us to confront multiple errors and whether or not a Flight
error that ends up being unobservable needs to really reject the render.

This implements stashing of Flight errors with a digest and only errors
if they end up erroring the Fizz render too. At this point they'll have
parent stacks so we can surface those.
2024-07-02 16:31:35 -04:00
Sebastian Markbåge
e60063d9e7 [Fizz] Include a component stack in prod but only lazily generate it (#30132)
When we added component stacks to Fizz in prod it severely slowed down
common cases where you intentionally are throwing error for purposes of
client rendering. Our parent component stack generation is very slow
since call components with fake errors to generate them.

Therefore we disabled them in prod but included them in prerenders.
https://github.com/facebook/react/pull/27850

However, we still kept generating data structures for them and the code
still exists there for the prerenders. We could stop generating the data
structures which are not completely free but also not crazy bad.

What we can do instead is just lazily generate the component stacks.
This is in fact what plain stacks do anyway. This doesn't work as well
in Fiber because the data structures are live but on the server they're
immutable so it's fine to do it later as well.

That way you can choose to not read this getter for intentionally thrown
errors - after inspecting the Error object - yet still get component
stacks in prod for other errors.
2024-07-02 16:05:20 -04:00
Sebastian Markbåge
6d2a97a711 [Fizz] Gate legacyContext field on disableLegacyContext (#30173)
We're running out of fields and this one we can avoid at runtime in any
modern builds.
2024-07-01 15:30:00 -04:00
Mike Vitousek
100dfd7dab [compiler][playground] Formatting changes to pass tabs
Summary: Compiler pass tabs are bolded when their contents have changed from previous passes; but currently the HIR and JS tabs are unbolded. Conceptually they should be, if HIR is "changed" from the source code and JS is "changed" from the last IR phase.

In addition, the "show diff" option doesn't make a ton of sense for tabs that either aren't part of the pipeline (EnvironmentConfig) or (maybe more controversially, but imo) passes where the IR representation has changed since the last pass (BuildReactiveFunctions). This diff drops the button from those tabs.

ghstack-source-id: 1d67e2f371
Pull Request resolved: https://github.com/facebook/react/pull/30151
2024-07-01 09:05:52 -07:00
Mike Vitousek
9a6e2d078c [compiler] Flow support for playground
Summary: The playground currently has limited support for Flow files--it tries to parse them if the // flow sigil is on the fist line, but this is often not the case for files one would like to inspect in practice. more importantly, component syntax isn't supported even then, because it depends on the Hermes parser.

This diff improves the state of flow support in the playground to make it more useful: when we see `flow` anywhere in the file, we'll assume it's a flow file, parse it with the Hermes parser, and disable typescript-specific features of Monaco editor.

ghstack-source-id: b99b1568d7
Pull Request resolved: https://github.com/facebook/react/pull/30150
2024-07-01 09:05:52 -07:00
Ruslan Lesiutin
97c5e6c9e4 chore[react-devtools/renderer]: dont show strict mode warning for prod renderer builds (#30158)
## Summary

We should not be showing StrictMode warnings when React is running in
production, since StrictMode is a dev-only feature.

## How did you test this change?

| Before | After |
| --- | --- |
| ![Screenshot 2024-06-30 at 23 42
41](https://github.com/facebook/react/assets/28902667/0154ab2a-435b-4317-b2e8-09083533acec)
| ![Screenshot 2024-06-30 at 23 44
14](https://github.com/facebook/react/assets/28902667/b10ffc6e-dbed-43d8-bf08-11188a151009)
|
2024-07-01 15:43:12 +01:00
Sebastian Markbåge
315109b02b [Fizz] Enable owner stacks for SSR (#30152)
Stacked on #30142.

This tracks owners and their stacks in DEV in Fizz. We use the
ComponentStackNode as the data structure to track this information -
effectively like ReactComponentInfo (Server) or Fiber (Client). They're
the instance.

I then port them same logic from ReactFiberComponentStack,
ReactFiberOwnerStack and ReactFiberCallUserSpace to Fizz equivalents.

This gets us both owner stacks from `captureOwnerStack()`, as well as
appended to console.errors logged by Fizz, while rendering and in
onError.
2024-07-01 10:27:52 -04:00
Ruslan Lesiutin
ad59ddf272 chore[react-devtools/ui]: fix strict mode badge styles (#30159)
## Summary

Just a minor UI fix to strict mode badge layout and component name text
overflow

## How did you test this change?
| Before | After |
| --- | --- |
| ![Screenshot 2024-06-30 at 23 35
19](https://github.com/facebook/react/assets/28902667/dbe62322-07f3-4291-808d-ecd2b0fba8cc)
| ![Screenshot 2024-06-30 at 23 31
06](https://github.com/facebook/react/assets/28902667/863b2f49-942f-4522-b815-5509a77b3b24)|
2024-07-01 15:27:15 +01:00
Sebastian Markbåge
e6783e7cc9 [Fizz] Run console.createTask during SSR when available (#30142)
Same as #30140 but for Fizz.

This is rarely used but it does allow seeing component stacks when
inspecting the Node.js server running Fizz using `--inspect` and the
Chrome DevTools.

<img width="504" alt="Screenshot 2024-06-29 at 4 08 22 PM"
src="https://github.com/facebook/react/assets/63648/f89bdf89-2598-42b4-8623-3b87f03326c4">
2024-07-01 09:50:45 -04:00
Sebastian Markbåge
d40ea875a4 [Flight Server] Run Server Components in console.createTask when available (#30140)
Same as #30142 but for Flight Server.

This is rarely used but it does allow seeing component stacks when
inspecting the Node.js server running Flight using `--inspect` and the
Chrome DevTools.

<img width="595" alt="Screenshot 2024-06-29 at 1 08 47 PM"
src="https://github.com/facebook/react/assets/63648/7f643e1e-a251-4e4d-b015-22a22a47031d">
2024-07-01 09:26:29 -04:00
Hendrik Liebau
b20d2327d6 Update react-refresh-webpack-plugin in Flight fixture (#30156) 2024-07-01 10:01:28 +02:00
Mike Vitousek
d6b1c488d4 [compiler] Clone computation block in change detection mode
Summary: In change-detection mode, we previously were spreading the contents of the computation block into the result twice. Other babel passes that cause in-place mutations of the AST would then be causing action at a distance and breaking the overall transform result. This pr creates clones of the nodes instead, so that mutations aren't reflected in both places where the block is used.

ghstack-source-id: b78def8d8d
Pull Request resolved: https://github.com/facebook/react/pull/30148
2024-06-30 22:43:32 -07: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
2e72ea8401 [Flight] Make byteLengthOfChunk Optional (#30130)
We use this to encode the binary length of a large string without
escaping it. This is really kind of optional though. This lets a Server
that can't encode strings but just pass them along able to emit RSC -
albeit a less optimal format.

The only build we have that does that today is react-html but the FB
version of Flight had a similar constraint.

It's still possible to support binary data as long as
byteLengthOfBinaryChunk is implemented which doesn't require a text
encoder. Many streams (including Node streams) support binary OR string
chunks.
2024-06-28 13:42:17 -04: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
0d1fdb5c2e Add doctype to renderToMarkup when html tags are rendered (#30122)
Stacked on top of #30121.

This is the same thing we do for `renderToReadableStream` so that you
don't have to manually inject it into the stream.

The only reason we didn't for `renderToString` / `renderToStaticMarkup`
was to preserve legacy behavior but since this is a new API we can
change that.

If you're rendering a partial it doesn't matter. This is likely what
you'd do for RSS feeds. The question is if you can reliably rely on the
doctype being used while rendering e-mails since many clients are so
quirky. However, if you're careful it also doesn't hurt so it seems best
to include it.
2024-06-28 09:35:12 -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
Sharath
b3aface19a [fix] replace polyfill.io with cloudflare equivalent (#30123) 2024-06-28 10:26:28 +02:00
Sebastian Markbåge
e02baf6c92 Warn for invalid type in renderer with the correct RSC stack (#30102)
This is all behind the `enableOwnerStacks` flag.

This is a follow up to #29088. In that I moved type validation into the
renderer since that's the one that knows what types are allowed.
However, I only removed it from `React.createElement` and not the JSX
which was an oversight.

However, I also noticed that for invalid types we don't have the right
stack trace for throws because we're not yet inside the JSX element that
itself is invalid. We should use its stack for the stack trace. That's
the reason it's enough to just use the throw now because we can get a
good stack trace from the owner stack. This is fixed by creating a fake
Throw Fiber that gets assigned the right stack.

Additionally, I noticed that for certain invalid types like the most
common one `undefined` we error in Flight so a missing import in RSC
leads to a generic error. Instead of erroring on the Flight side we
should just let anything that's not a Server Component through to the
client and then let the Client renderer determine whether it's a valid
type or not. Since we now have owner stacks through the server too, this
will still be able to provide a good stack trace on the client that
points to the server in that case.

<img width="571" alt="Screenshot 2024-06-25 at 6 46 35 PM"
src="https://github.com/facebook/react/assets/63648/6812c24f-e274-4e09-b4de-21deda9ea1d4">

To get the best stack you have to expand the little icon and the regular
stack is noisy [due to this Chrome
bug](https://issues.chromium.org/issues/345248263) which makes it a
little harder to find but once that's fixed it might be easier.
2024-06-27 12:10:09 -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
Sebastian Markbåge
3bee073c01 Remove isPrimaryRenderer from Flight Server Config (#30115)
This was used for Context but since ReactFlightNewContext is gone now
this is no longer used.
2024-06-27 12:08:56 -04:00
dependabot[bot]
f5a22fa27d Bump ws from 7.2.1 to 7.5.10 (#29919)
Bumps [ws](https://github.com/websockets/ws) from 7.2.1 to 7.5.10.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/websockets/ws/releases">ws's
releases</a>.</em></p>
<blockquote>
<h2>7.5.10</h2>
<h1>Bug fixes</h1>
<ul>
<li>Backported e55e5106 to the 7.x release line (22c28763).</li>
</ul>
<h2>7.5.9</h2>
<h1>Bug fixes</h1>
<ul>
<li>Backported bc8bd34e to the 7.x release line (0435e6e1).</li>
</ul>
<h2>7.5.8</h2>
<h1>Bug fixes</h1>
<ul>
<li>Backported 0fdcc0af to the 7.x release line (2758ed35).</li>
<li>Backported d68ba9e1 to the 7.x release line (dc1781bc).</li>
</ul>
<h2>7.5.7</h2>
<h1>Bug fixes</h1>
<ul>
<li>Backported 6946f5fe to the 7.x release line (1f72e2e1).</li>
</ul>
<h2>7.5.6</h2>
<h1>Bug fixes</h1>
<ul>
<li>Backported b8186dd1 to the 7.x release line (73dec34b).</li>
<li>Backported ed2b8039 to the 7.x release line (22a26afb).</li>
</ul>
<h2>7.5.5</h2>
<h1>Bug fixes</h1>
<ul>
<li>Backported ec9377ca to the 7.x release line (0e274acd).</li>
</ul>
<h2>7.5.4</h2>
<h1>Bug fixes</h1>
<ul>
<li>Backported 6a72da3e to the 7.x release line (76087fbf).</li>
<li>Backported 869c9892 to the 7.x release line (27997933).</li>
</ul>
<h2>7.5.3</h2>
<h1>Bug fixes</h1>
<ul>
<li>The <code>WebSocketServer</code> constructor now throws an error if
more than one of the
<code>noServer</code>, <code>server</code>, and <code>port</code>
options are specefied (66e58d27).</li>
<li>Fixed a bug where a <code>'close'</code> event was emitted by a
<code>WebSocketServer</code> before
the internal HTTP/S server was actually closed (5a587304).</li>
<li>Fixed a bug that allowed WebSocket connections to be established
after
<code>WebSocketServer.prototype.close()</code> was called
(772236a1).</li>
</ul>
<h2>7.5.2</h2>
<h1>Bug fixes</h1>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="d962d70649"><code>d962d70</code></a>
[dist] 7.5.10</li>
<li><a
href="22c2876323"><code>22c2876</code></a>
[security] Fix crash when the Upgrade header cannot be read (<a
href="https://redirect.github.com/websockets/ws/issues/2231">#2231</a>)</li>
<li><a
href="8a78f87706"><code>8a78f87</code></a>
[dist] 7.5.9</li>
<li><a
href="0435e6e12b"><code>0435e6e</code></a>
[security] Fix same host check for ws+unix: redirects</li>
<li><a
href="4271f07cfc"><code>4271f07</code></a>
[dist] 7.5.8</li>
<li><a
href="dc1781bc31"><code>dc1781b</code></a>
[security] Drop sensitive headers when following insecure redirects</li>
<li><a
href="2758ed3550"><code>2758ed3</code></a>
[fix] Abort the handshake if the Upgrade header is invalid</li>
<li><a
href="a370613fab"><code>a370613</code></a>
[dist] 7.5.7</li>
<li><a
href="1f72e2e14f"><code>1f72e2e</code></a>
[security] Drop sensitive headers when following redirects (<a
href="https://redirect.github.com/websockets/ws/issues/2013">#2013</a>)</li>
<li><a
href="8ecd890800"><code>8ecd890</code></a>
[dist] 7.5.6</li>
<li>Additional commits viewable in <a
href="https://github.com/websockets/ws/compare/7.2.1...7.5.10">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=ws&package-manager=npm_and_yarn&previous-version=7.2.1&new-version=7.5.10)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/facebook/react/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-27 10:07:09 -04:00
Mike Vitousek
fcfbfc1d1e [compiler] Always error on async reassignments
Summary: Addresses the issue in #30109: any mutation of a local in an async function may occur after rendering has finished.

ghstack-source-id: 9f15cf0f14
Pull Request resolved: https://github.com/facebook/react/pull/30111
2024-06-26 17:07:40 -07:00
Mike Vitousek
1f59d07042 [compiler] Repro for nested function local reassignment issue
Summary: Additional repro demonstrating a case that still exists after #30106

ghstack-source-id: f03176fd88
Pull Request resolved: https://github.com/facebook/react/pull/30110
2024-06-26 17:07:38 -07:00
Joe Savona
00775d94dc [compiler] Add todo fixtures for local reassignment in an async callback
ghstack-source-id: eca878f62a
Pull Request resolved: https://github.com/facebook/react/pull/30109
2024-06-26 16:51:15 -07:00
Joe Savona
4c9a2d2ddf [compiler] Validate against locals being reassigned after render
Adds a pass which validates that local variables are not reassigned by functions which may be called after render. This is a straightforward forward data-flow analysis, where we:
1. Build up a mapping of context variables in the outer component/hook
2. Find ObjectMethod/FunctionExpressions which may reassign those context variables
3. Propagate aliases of those functions via StoreLocal/LoadLocal
4. Disallow passing those functions with a Freeze effect. This includes JSX arguments, hook arguments, hook return types, etc.

Conceptually, a function that reassigns a local is inherently mutable. Frozen functions must be side-effect free, so these two categories are incompatible and we can use the freeze effect to find all instances of where such functions are disallowed rather than special-casing eg hook calls and JSX.

ghstack-source-id: c2b22e3d62
Pull Request resolved: https://github.com/facebook/react/pull/30107
2024-06-26 16:51:15 -07:00