Compare commits

...

666 Commits

Author SHA1 Message Date
Joe Savona
6f53c391fb [compiler] Remove local CompilerError accumulators, emit directly to env.recordError()
Removes unnecessary indirection in 17 compiler passes that previously
accumulated errors in a local `CompilerError` instance before flushing
them to `env.recordErrors()` at the end of each pass. Errors are now
emitted directly via `env.recordError()` as they're discovered.

For passes with recursive error-detection patterns (ValidateNoRefAccessInRender,
ValidateNoSetStateInRender), the internal accumulator is kept but flushed
via individual `recordError()` calls. For InferMutationAliasingRanges,
a `shouldRecordErrors` flag preserves the conditional suppression logic.
For TransformFire, the throw-based error propagation is replaced with
direct recording plus an early-exit check in Pipeline.ts.
2026-02-23 16:11:25 -08:00
Joseph Savona
9075330979 [compiler] Remove tryRecord, add catch-all error handling, fix remaining throws (#35881)
Remove `tryRecord()` from the compilation pipeline now that all passes
record
errors directly via `env.recordError()` / `env.recordErrors()`. A single
catch-all try/catch in Program.ts provides the safety net for any pass
that
incorrectly throws instead of recording.

Key changes:
- Remove all ~64 `env.tryRecord()` wrappers in Pipeline.ts
- Delete `tryRecord()` method from Environment.ts
- Add `CompileUnexpectedThrow` logger event so thrown errors are
detectable
- Log `CompileUnexpectedThrow` in Program.ts catch-all for non-invariant
throws
- Fail snap tests on `CompileUnexpectedThrow` to surface pass bugs in
dev
- Convert throwTodo/throwDiagnostic calls in HIRBuilder (fbt, this),
  CodegenReactiveFunction (for-in/for-of), and BuildReactiveFunction to
  record errors or use invariants as appropriate
- Remove try/catch from BuildHIR's lower() since inner throws are now
recorded
- CollectOptionalChainDependencies: return null instead of throwing on
  unsupported optional chain patterns (graceful optimization skip)

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35881).
* #35888
* #35884
* #35883
* #35882
* __->__ #35881
2026-02-23 16:10:17 -08:00
Joseph Savona
8a33fb3a1c [compiler] Cleanup: consistent tryRecord() wrapping and error recording (#35880)
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35880).
* #35888
* #35884
* #35883
* #35882
* #35881
* __->__ #35880
2026-02-23 16:08:04 -08:00
Joseph Savona
cebe42e245 [compiler] Add fault tolerance test fixtures (#35879)
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35879).
* #35888
* #35884
* #35883
* #35882
* #35881
* #35880
* __->__ #35879
2026-02-23 16:06:39 -08:00
Joseph Savona
d6558f36e2 [compiler] Phase 3: Make lower() always produce HIRFunction (#35878)
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35878).
* #35888
* #35884
* #35883
* #35882
* #35881
* #35880
* #35879
* __->__ #35878
2026-02-23 16:05:05 -08:00
Joseph Savona
59d7c27087 [compiler] Phase 8: Add multi-error test fixture and update plan (#35877)
Add test fixture demonstrating fault tolerance: the compiler now reports
both a mutation error and a ref access error in the same function, where
previously only one would be reported before bailing out.

Update plan doc to mark all phases as complete.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35877).
* #35888
* #35884
* #35883
* #35882
* #35881
* #35880
* #35879
* #35878
* __->__ #35877
2026-02-23 16:02:32 -08:00
Joseph Savona
9b2d8013ee [compiler] Phase 4 (batch 2), 5, 6: Update remaining passes for fault tolerance (#35876)
Update remaining validation passes to record errors on env:
- validateMemoizedEffectDependencies
- validatePreservedManualMemoization
- validateSourceLocations (added env parameter)
- validateContextVariableLValues (changed throwTodo to recordError)
- validateLocalsNotReassignedAfterRender (changed throw to recordError)
- validateNoDerivedComputationsInEffects (changed throw to recordError)

Update inference passes:
- inferMutationAliasingEffects: return void, errors on env
- inferMutationAliasingRanges: return Array<AliasingEffect> directly,
errors on env

Update codegen:
- codegenFunction: return CodegenFunction directly, errors on env
- codegenReactiveFunction: same pattern

Update Pipeline.ts to call all passes directly without tryRecord/unwrap.
Also update AnalyseFunctions.ts which called
inferMutationAliasingRanges.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35876).
* #35888
* #35884
* #35883
* #35882
* #35881
* #35880
* #35879
* #35878
* #35877
* __->__ #35876
2026-02-23 16:01:02 -08:00
Joseph Savona
e3e5d95cc4 [compiler] Phase 4 (batch 1): Update validation passes to record errors on env (#35875)
Update 9 validation passes to record errors directly on fn.env instead
of
returning Result<void, CompilerError>:
- validateHooksUsage
- validateNoCapitalizedCalls (also changed throwInvalidReact to
recordError)
- validateUseMemo
- dropManualMemoization
- validateNoRefAccessInRender
- validateNoSetStateInRender
- validateNoImpureFunctionsInRender
- validateNoFreezingKnownMutableFunctions
- validateExhaustiveDependencies

Each pass now calls fn.env.recordErrors() instead of returning
errors.asResult().
Pipeline.ts call sites updated to remove tryRecord() wrappers and
.unwrap().

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35875).
* #35888
* #35884
* #35883
* #35882
* #35881
* #35880
* #35879
* #35878
* #35877
* #35876
* __->__ #35875
2026-02-23 15:35:52 -08:00
Joseph Savona
426a394845 [compiler] Phase 2+7: Wrap pipeline passes in tryRecord for fault tolerance (#35874)
- Change runWithEnvironment/run/compileFn to return
Result<CodegenFunction, CompilerError>
- Wrap all pipeline passes in env.tryRecord() to catch and record
CompilerErrors
- Record inference pass errors via env.recordErrors() instead of
throwing
- Handle codegen Result explicitly, returning Err on failure
- Add final error check: return Err(env.aggregateErrors()) if any errors
accumulated
- Update tryCompileFunction and retryCompileFunction in Program.ts to
handle Result
- Keep lint-only passes using env.logErrors() (non-blocking)
- Update 52 test fixture expectations that now report additional errors

This is the core integration that enables fault tolerance: errors are
caught,
recorded, and the pipeline continues to discover more errors.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35874).
* #35888
* #35884
* #35883
* #35882
* #35881
* #35880
* #35879
* #35878
* #35877
* #35876
* #35875
* __->__ #35874
2026-02-23 15:26:28 -08:00
Joseph Savona
eca778cf8b [compiler] Phase 1: Add error accumulation infrastructure to Environment (#35873)
Add error accumulation methods to the Environment class:
- #errors field to accumulate CompilerErrors across passes
- recordError() to record a single diagnostic (throws if Invariant)
- recordErrors() to record all diagnostics from a CompilerError
- hasErrors() to check if any errors have been recorded
- aggregateErrors() to retrieve the accumulated CompilerError
- tryRecord() to wrap callbacks and catch CompilerErrors

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35873).
* #35888
* #35884
* #35883
* #35882
* #35881
* #35880
* #35879
* #35878
* #35877
* #35876
* #35875
* #35874
* __->__ #35873
2026-02-23 15:18:23 -08:00
Joseph Savona
0dbb43bc57 [compiler] Add fault tolerance plan document (#35872)
Add detailed plan for making the React Compiler fault-tolerant by
accumulating errors across all passes instead of stopping at the first
error. This enables reporting multiple compilation errors at once.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35872).
* #35888
* #35884
* #35883
* #35882
* #35881
* #35880
* #35879
* #35878
* #35877
* #35876
* #35875
* #35874
* #35873
* __->__ #35872
2026-02-23 15:15:29 -08:00
Joseph Savona
8b6b11f703 [compiler] Remove fallback compilation pipeline dead code (#35827)
Remove dead code left behind after the removal of retryCompileFunction,
enableFire, and inferEffectDependencies:
- Delete ValidateNoUntransformedReferences.ts (always a no-op)
- Remove CompileProgramMetadata type and retryErrors from ProgramContext
- Remove 'client-no-memo' output mode
- Change compileProgram return type from CompileProgramMetadata | null
to void
2026-02-23 08:54:49 -08:00
Andrew Clark
ab18f33d46 Fix context propagation through suspended Suspense boundaries (#35839)
When a Suspense boundary suspends during initial mount, the primary
children's fibers are discarded because there is no current tree to
preserve them. If the suspended promise never resolves, the only way to
retry is something external like a context change. However, lazy context
propagation could not find the consumer fibers — they no longer exist in
the tree — so the Suspense boundary was never marked for retry and
remained stuck in fallback state indefinitely.

The fix teaches context propagation to conservatively mark suspended
Suspense boundaries for retry when a parent context changes, even when
the consumer fibers can't be found. This matches the existing
conservative approach used for dehydrated (SSR) Suspense boundaries.
2026-02-20 22:03:11 -05:00
Joseph Savona
b16b768fbd [compiler] Feature flag cleanup (#35825)
Cleans up feature flags that do not have an active experiment and which
we don't currently plan to ship, one commit per flag. Notable removals:
* Automatic (inferred) effect dependencies / Fire: abandoned due to
early feedback. Shipped useEffectEvent which addresses some of the
use-cases.
* Inline JSX transform (experimented, not a consistent win)
* Context selectors (experimented, not a sufficient/consistent win given
the benefit the compiler already provides)
* Instruction Reordering (will try a different approach)

To decide which features to remove, I looked at Meta's internal repos as
well as eslint-pugin-react-hooks to see which flags were never
overridden anywhere. That gave a longer list of flags, from which I then
removed some features that I know are used in OSS.
2026-02-20 12:29:12 -08:00
Sebastian "Sebbie" Silbermann
2ba3065527 [Flight] Add support for transporting Error.cause (#35810) 2026-02-19 15:50:34 -08:00
Josh Story
38cd020c1f Don't outline Suspense boundaries with suspensey CSS during shell flush (#35824)
When flushing the shell, stylesheets with precedence are emitted in the
`<head>` which blocks paint regardless. Outlining a boundary solely
because it has suspensey CSS provides no benefit during the shell flush
and causes a higher-level fallback to be shown unnecessarily (e.g.
"Middle Fallback" instead of "Inner Fallback").

This change passes a flushingInShell flag to hasSuspenseyContent so the
host config can skip stylesheet-only suspensey content when flushing the
shell. Suspensey images (used for ViewTransition animation reveals)
still trigger outlining during the shell since their motivation is
different.

When flushing streamed completions the behavior is unchanged — suspensey
CSS still causes outlining so the parent content can display sooner
while the stylesheet loads.
2026-02-19 12:29:21 -08:00
Tim Neutkens
f247ebaf44 [Flight] Walk parsed JSON instead of using reviver for parsing RSC payload (#35776)
## Summary

Follow-up to https://github.com/vercel/next.js/pull/89823 with the
actual changes to React.

Replaces the `JSON.parse` reviver callback in `initializeModelChunk`
with a two-step approach: plain `JSON.parse()` followed by a recursive
`reviveModel()` post-process (same as in Flight Reply Server). This
yields a **~75% speedup** in RSC chunk deserialization.

| Payload | Original (ms) | Walk (ms) | Speedup |
|---------|---------------|-----------|---------|
| Small (2 elements, 142B) | 0.0024 | 0.0007 | **+72%** |
| Medium (~12 elements, 914B) | 0.0116 | 0.0031 | **+73%** |
| Large (~90 elements, 16.7KB) | 0.1836 | 0.0451 | **+75%** |
| XL (~200 elements, 25.7KB) | 0.3742 | 0.0913 | **+76%** |
| Table (1000 rows, 110KB) | 3.0862 | 0.6887 | **+78%** |

## Problem

`createFromJSONCallback` returns a reviver function passed as the second
argument to `JSON.parse()`. This reviver is called for **every key-value
pair** in the parsed JSON. While the logic inside the reviver is
lightweight, the dominant cost is the **C++ → JavaScript boundary
crossing** — V8's `JSON.parse` is implemented in C++, and calling back
into JavaScript for every node incurs significant overhead.

Even a trivial no-op reviver `(k, v) => v` makes `JSON.parse` **~4x
slower** than bare `JSON.parse` without a reviver:

```
108 KB payload:
  Bare JSON.parse:    0.60 ms
  Trivial reviver:    2.95 ms  (+391%)
```

## Change

Replace the reviver with a two-step process:

1. `JSON.parse(resolvedModel)` — parse the entire payload in C++ with no
callbacks
2. `reviveModel` — recursively walk the resulting object in pure
JavaScript to apply RSC transformations

The `reviveModel` function includes additional optimizations over the
original reviver:
- **Short-circuits plain strings**: only calls `parseModelString` when
the string starts with `$`, skipping the vast majority of strings (class
names, text content, etc.)
- **Stays entirely in JavaScript** — no C++ boundary crossings during
the walk

## Results

You can find the related applications in the [Next.js PR
](https://github.com/vercel/next.js/pull/89823)as I've been testing this
on Next.js applications.

### Table as Server Component with 1000 items

Before:

```
    "min": 13.782875000000786,
    "max": 22.23400000000038,
    "avg": 17.116868530000083,
    "p50": 17.10766700000022,
    "p75": 18.50787499999933,
    "p95": 20.426249999998618,
    "p99": 21.814125000000786
```

After:

```
    "min": 10.963916999999128,
    "max": 18.096083000000363,
    "avg": 13.543286884999988,
    "p50": 13.58350000000064,
    "p75": 14.871791999999914,
    "p95": 16.08429099999921,
    "p99": 17.591458000000785
```

### Table as Client Component with 1000 items

Before:

```
    "min": 3.888875000000553,
    "max": 9.044959000000745,
    "avg": 4.651271475000067,
    "p50": 4.555749999999534,
    "p75": 4.966624999999112,
    "p95": 5.47754200000054,
    "p99": 6.109499999998661
````

After:

```
    "min": 3.5986250000005384,
    "max": 5.374291000000085,
    "avg": 4.142990245000046,
    "p50": 4.10570799999914,
    "p75": 4.392041999999492,
    "p95": 4.740084000000934,
    "p99": 5.1652500000000146
```

### Nested Suspense

Before:

```
  Requests:  200
  Min:       73ms
  Max:       106ms
  Avg:       78ms
  P50:       77ms
  P75:       80ms
  P95:       85ms
  P99:       94ms
```

After:

```
  Requests:  200
  Min:       56ms
  Max:       67ms
  Avg:       59ms
  P50:       58ms
  P75:       60ms
  P95:       65ms
  P99:       66ms
```

### Even more nested Suspense (double-level Suspense)

Before:

```
  Requests:  200
  Min:       159ms
  Max:       208ms
  Avg:       169ms
  P50:       167ms
  P75:       173ms
  P95:       183ms
  P99:       188ms
```

After:

```
  Requests:  200
  Min:       125ms
  Max:       170ms
  Avg:       134ms
  P50:       132ms
  P75:       138ms
  P95:       148ms
  P99:       160ms
```

## How did you test this change?

Ran it across many Next.js benchmark applications.

The entire Next.js test suite passes with this change.

---------

Co-authored-by: Hendrik Liebau <mail@hendrik-liebau.de>
2026-02-19 08:37:41 -08:00
Sebastian "Sebbie" Silbermann
3a2bee26d2 [DevTools] Fix alignment of breadcrumbs separator (#35817) 2026-02-18 10:53:49 -08:00
chirokas
4842fbea02 [react-dom] Add support for onFullscreenChange and onFullscreenError events (#34621) 2026-02-17 17:34:16 -08:00
Nick Gerleman
61db53c179 [Native] Add RCTSelectableText as a recognized Text component (#35780)
## Summary

Add "RCTSelectableText" to the list of component names recognized as
being inside a text element, alongside "RCTText".

React Native's new text stack, tries to optimize and allows
differentiating between a custom TextView, with lower level control,
that can reuse the work performed during Fabric/Yoga layout, and a
native TextView, used for fidelity. On Android at least, the only place
we've needed native TextView for fidelity/native UX has been support for
`selectable` text, which has many unique UI interactions.

## How did you test this change?

When I patch this in, alongside
https://github.com/facebook/react-native/pull/55552, we no longer see
warnings when we render text inside of RCTSelectableText component.

---------

Co-authored-by: Eli White <github@eli-white.com>
2026-02-17 16:16:06 -08:00
Joseph Savona
4ac47537dd [compiler] Track locations for dependencies (#35794)
Tracks locations for reactive scope dependencies, both on the deps and
portions of the path. The immediate need for this is a non-public
experiment where we're exploring type-directed compilation, and
sometimes look up the types of expressions by location. We need to
preserve locations accurately for that to work, including the locations
of the deps.

## Test Plan

Locations for dependencies are not easy to test: i manually spot-checked
the new fixture to ensure that the deps look right. This is fine as
best-effort since it doesn't impact any of our core compilation logic, i
may fix forward if there are issues and will think about how to test.
2026-02-17 14:06:21 -08:00
Hendrik Liebau
47d1ad1454 [Flight] Skip transferReferencedDebugInfo during debug info resolution (#35795)
When the Flight Client resolves chunk references during model parsing,
it calls `transferReferencedDebugInfo` to propagate debug info entries
from referenced chunks to the parent chunk. Debug info on chunks is
later moved to their resolved values, where it is used by React DevTools
to show performance tracks and what a component was suspended by.

Debug chunks themselves (specifically `ReactComponentInfo`,
`ReactAsyncInfo`, `ReactIOInfo`, and their outlined references) are
metadata that is never rendered. They don't need debug info attached to
them. Without this fix, debug info entries accumulate on outlined debug
chunks via their references to other debug chunks (e.g. owner chains and
props deduplication paths). Since each outlined chunk's accumulated
entries are copied to every chunk that references it, this creates
exponential growth in deep component trees, which can cause the dev
server to hang and run out of memory.

This generalizes the existing skip of `transferReferencedDebugInfo` for
Element owner/stack references (which already recognizes that references
to debug chunks don't need debug info transferred) to all references
resolved during debug info resolution. It adds an
`isInitializingDebugInfo` flag set in `initializeDebugChunk` and
`resolveIOInfo`, which propagates through all nested
`initializeModelChunk` calls within the same synchronous stack. For the
async path, `waitForReference` captures the flag at call time into
`InitializationReference.isDebug`, so deferred fulfillments also skip
the transfer.
2026-02-16 09:22:32 -08:00
Azat S.
e8c6362678 [eslint-plugin-react-hooks] Add ESLint v10 support (#35720)
## Summary

ESLint v10.0.0 was released on February 7, 2026. The current
`peerDependencies` for `eslint-plugin-react-hooks` only allows up to
`^9.0.0`, which causes peer dependency warnings when installing with
ESLint v10.

This PR:

- Adds `^10.0.0` to the eslint peer dependency range
- Adds `eslint-v10` to devDependencies for testing
- Adds an `eslint-v10` e2e fixture (based on the existing `eslint-v9`
fixture)

ESLint v10's main breaking changes (removal of legacy eslintrc config,
deprecated context methods) don't affect this plugin - flat config is
already supported since v7.0.0, and the deprecated APIs already have
fallbacks in place.

## How did you test this change?

Ran the existing unit test suite:

```
cd packages/eslint-plugin-react-hooks && yarn test
```

All 5082 tests passed.
2026-02-13 10:26:01 -08:00
Ruslan Lesiutin
03ca38e6e7 [DevTools] Check suspense child node presence in parentSuspense.children before removing (#35775)
Currently, this silently removes the last child in the list, which
doesn't contain the `id`.
2026-02-13 15:33:22 +00:00
Sebastian "Sebbie" Silbermann
6066c782fe [DevTools] Dedicated empty state for roots that aren't suspended by anything (#35769) 2026-02-12 17:48:02 +01:00
Sebastian "Sebbie" Silbermann
705055d7ac [DevTools] Enable Suspense tab by default (#35768) 2026-02-12 16:50:29 +01:00
Ruslan Lesiutin
8374c2abf1 [DevTools] Remove experimental __IS_INTERNAL_MCP_BUILD__ flag and related code (#35755)
This is unused.
2026-02-11 16:59:43 +00:00
Ricky
892c68605c [fiber] bugfix - don't show <Offscreen> in error message. (#35763)
## Overview

While building the RSC sandboxes I notice error messages like:

>  An error occurred in the `<Offscreen>` component

This is an internal component so it should show either:

>  An error occurred in the `<Suspense>` component.

>  An error occurred in the `<Activity>` component.

It should only happen when there's a lazy in the direct child position
of a `<Suspense>` or `<Activity>` component.
2026-02-11 11:20:51 -05:00
Jack Pope
cd515d7e22 Minor DOM FragmentInstance refactors (#35641)
Handles TODOs, small follow up refactors
2026-02-11 10:03:36 -05:00
Jack Pope
78f5c504b7 Notify FragmentInstance of added/removed text (#35637)
Follow up to https://github.com/facebook/react/pull/35630

We don't currently have any operations that depend on the updating of
text nodes added or removed after Fragment mount. But for the sake of
completeness and extending the ability to any other host configs, this
change calls `commitNewChildToFragmentInstance` and
`deleteChildFromFragmentInstance` on HostText fibers.

Both DOM and Fabric configs early return because we cannot attach event
listeners or observers to text. In the future, there could be some
stateful Fragment feature that uses text that could extend this.
2026-02-11 09:26:22 -05:00
Sebastian "Sebbie" Silbermann
e49335e961 [DevTools] Display React.optimisticKey in key positions (#35760) 2026-02-11 00:35:36 +01:00
Sebastian "Sebbie" Silbermann
57b79b0388 [DevTools] Only block child Suspense boundaries if the parent has all shared suspenders removed (#35737) 2026-02-10 17:52:35 +01:00
Sebastian "Sebbie" Silbermann
70890e7c58 Consistent handling of work tags for rename, delete, and overriding state (#35740)
Co-authored-by: Ruslan Lesiutin <28902667+hoxyq@users.noreply.github.com>
2026-02-10 16:35:02 +01:00
Sebastian "Sebbie" Silbermann
f23aa1d9f5 [DevTools] Fix memory leak when unmounting hoistables (#35741) 2026-02-10 13:09:23 +01:00
Sebastian "Sebbie" Silbermann
49c3b270f9 [test] Include uniqueSuspenders in Suspense tree snapshots (#35736) 2026-02-10 12:51:58 +01:00
Ruslan Lesiutin
c6bb26bf83 [DevTools] Don't capture durations for disconnected subtrees when profiling (#35718)
After https://github.com/facebook/react/pull/34089, when updating
(possibly, mounting) inside disconnected subtree, we don't record this
as an operation. This only happens during reconnect. The issue is that
`recordProfilingDurations()` can be called, which diffs tree base
duration and reports it to the Frontend:

65db1000b9/packages/react-devtools-shared/src/backend/fiber/renderer.js (L4506-L4521)

This operation can be recorded before the "Add" operation, and it will
not be resolved properly on the Frontend side.

Before the fix:
```
commit tree › Suspense › should handle transitioning from fallback back to content during profiling

    Could not clone the node: commit tree does not contain fiber "5". This is a bug in React DevTools.

      162 |     const existingNode = nodes.get(id);
      163 |     if (existingNode == null) {
    > 164 |       throw new Error(
          |             ^
      165 |         `Could not clone the node: commit tree does not contain fiber "${id}". This is a bug in React DevTools.`,
      166 |       );
      167 |     }

      at getClonedNode (packages/react-devtools-shared/src/devtools/views/Profiler/CommitTreeBuilder.js:164:13)
      at updateTree (packages/react-devtools-shared/src/devtools/views/Profiler/CommitTreeBuilder.js:348:24)
      at getCommitTree (packages/react-devtools-shared/src/devtools/views/Profiler/CommitTreeBuilder.js:112:20)
      at ProfilingCache.getCommitTree (packages/react-devtools-shared/src/devtools/ProfilingCache.js:40:46)
      at Object.<anonymous> (packages/react-devtools-shared/src/__tests__/profilingCommitTreeBuilder-test.js:257:44)
```
2026-02-09 22:18:17 +00:00
Sebastian "Sebbie" Silbermann
6a939d0b54 [DevTools] Allow renaming Host Component props (#35735) 2026-02-09 23:14:46 +01:00
Sebastian "Sebbie" Silbermann
4c9d62d2b4 [DevTools] Fix crash when revealing stable, filtered <Activity> children (#35734) 2026-02-09 22:52:24 +01:00
Ruslan Lesiutin
24f215ce8b [DevTools] Fix false-positive re-render reports for filtered nodes (#35723)
Fixes https://github.com/facebook/react/issues/33423,
https://github.com/facebook/react/issues/35245,
https://github.com/facebook/react/issues/19732.

As demoed
[here](https://github.com/facebook/react/issues/33423#issuecomment-2970750588),
React DevTools incorrectly highlights re-renders for descendants of
filtered-out nodes that didn't actually render.

There were multiple fixes suggesting changes in `didFiberRender()`
function, but these doesn't seem right, because this function is used in
a context of whether the Fiber actually rendered something (updated),
not re-rendered compared to the previous Fiber.

Instead, this PR adds additional validation at callsites that either
used for highlighting re-renders or capturing tree base durations and
are relying on `didFiberRender`. I've also added a few tests that
reproduce the failure scenario. Without the changes, the tests are
failing.
2026-02-09 20:39:33 +00:00
Sebastian "Sebbie" Silbermann
eab523e2a9 [Fiber] Avoid duplicate debug info for array children (#35733) 2026-02-09 20:36:56 +01:00
Hendrik Liebau
272441a9ad [Flight] Add unstable_allowPartialStream option to Flight Client (#35731)
When using a partial prerender stream, i.e. a prerender that is
intentionally aborted before all I/O has resolved, consumers of
`createFromReadableStream` would need to keep the stream unclosed to
prevent React Flight from erroring on unresolved chunks. However, some
browsers (e.g. Chrome, Firefox) keep unclosed ReadableStreams with
pending reads as native GC roots, retaining the entire Flight response.

With this PR we're adding an `unstable_allowPartialStream` option, that
allows consumers to close the stream normally. The Flight Client's
`close()` function then transitions pending chunks to halted instead of
erroring them. Halted chunks keep Suspense fallbacks showing (i.e. they
never resolve), and their `.then()` is a no-op so no new listeners
accumulate. Inner stream chunks (ReadableStream/AsyncIterable) are
closed gracefully, and `getChunk()` returns halted chunks for new IDs
that are accessed after closing the response. Blocked chunks are left
alone because they may be waiting on client-side async operations like
module loading, or on forward references to chunks that appeared later
in the stream, both of which resolve independently of closing.
2026-02-09 19:19:32 +01:00
Hendrik Liebau
b07aa7d643 [Flight] Fix encodeReply for JSX with temporary references (#35730)
`encodeReply` throws "React Element cannot be passed to Server Functions
from the Client without a temporary reference set" when a React element
is the root value of a `serializeModel` call (either passed directly or
resolved from a promise), even when a temporary reference set is
provided.

The cause is that `resolveToJSON` hits the `REACT_ELEMENT_TYPE` switch
case before reaching the `existingReference`/`modelRoot` check that
regular objects benefit from. The synthetic JSON root created by
`JSON.stringify` is never tracked in `writtenObjects`, so
`parentReference` is `undefined` and the code falls through to the
throw. This adds a `modelRoot` check in the `REACT_ELEMENT_TYPE` case,
following the same pattern used for promises and plain objects.

The added `JSX as root model` test also uncovered a pre-existing crash
in the Flight Client: when the JSX element round-trips back, it arrives
as a frozen object (client-created elements are frozen in DEV), and
`Object.defineProperty` for `_debugInfo` fails because frozen objects
are non-configurable. The same crash can occur with JSX exported as a
client reference. For now, we're adding `!Object.isFrozen()` guards in
`moveDebugInfoFromChunkToInnerValue` and `addAsyncInfo` to prevent the
crash, which means debug info is silently dropped for frozen elements.
The proper fix would likely be to clone the element so each rendering
context gets its own mutable copy with correct debug info.

closes #34984
closes #35690
2026-02-09 16:17:53 +01:00
Jimmy Lai
2dd9b7cf76 [Flight] Fix debug channel flag in Node.js server renderToPipeableStream (#35724)
## Summary

- Fixes the `createRequest` call in `renderToPipeableStream` to pass
`debugChannelReadable !== undefined` instead of `debugChannel !==
undefined` in the turbopack, esm, and parcel Node.js server
implementations
- The webpack version already had the correct check; this brings the
other bundler implementations in line

The bug was introduced in #33754. With `debugChannel !== undefined`, the
server could signal that debug info should be emitted even when only a
write-only debug channel is provided (no readable side), potentially
causing the client to block forever waiting for debug data that never
arrives.
2026-02-08 20:14:15 +01:00
Sebastian "Sebbie" Silbermann
65db1000b9 [test] Move profilingCommitTreeBuilder to versioned renderer (#35711) 2026-02-06 16:00:43 +01:00
Sebastian "Sebbie" Silbermann
2a879cdc95 [DevTools] Fix broken commit tree builder for initial operations (#35710) 2026-02-06 15:16:23 +01:00
Sebastian "Sebbie" Silbermann
9a5996a6c1 [flags] Cleanup enableHalt (#35708) 2026-02-06 10:33:51 +01:00
Sebastian "Sebbie" Silbermann
1c66ac740c [DevTools] Separate breadcrumbs with » (#35705) 2026-02-06 00:40:31 +01:00
Sebastian "Sebbie" Silbermann
8b276df415 [DevTools] Avoid scrollbars in Suspense breadcrumbs (#35700) 2026-02-05 23:27:57 +01:00
Ricky
95ffd6cd9c Disable parallel transitions in canary (#35709)
Accidentally enabled this
2026-02-05 13:34:23 -05:00
Ruslan Lesiutin
b9323509be [DevTools] Throw an error when attempting to clone non-existent node (#35702)
There is an existing issue with serialisation logic for the traces from
Profiler panel.

I've discovered that `TREE_OPERATION_UPDATE_TREE_BASE_DURATION`
operation for some reason appears earlier in a sequence of operations,
before the `TREE_OPERATION_ADD` that registers the new node. It ends up
cloning non-existent node, which just creates an empty object and adds
it to the map of nodes.

This change only adds additional layer of validation to cloning logic,
so we don't swallow the error, if we attempt to clone non-existent node.
2026-02-05 17:49:18 +00:00
Sebastian "Sebbie" Silbermann
bb53387716 [DevTools] Shrink/Deshrink Owners breadcrumbs on any resizes (#35694) 2026-02-05 12:08:02 +01:00
Ricky
3aaab92a26 [flags] add enableEffectEventMutationPhase (#35548)
Small optimization for useEffectEvent. Not sure we even need a flag for
it, but it will be a nice killswitch.

As an added benefit, it fixes a bug when `enableViewTransition` is on,
where we were not updating the useEffectEvent callback when a tree went
from hidden to visible.
2026-02-04 15:04:57 -05:00
Ricky
087a34696f [test] add activity test with gSBU and enableViewTransition bugfix (#35555)
Related to https://github.com/facebook/react/pull/35548,
`enableViewTransition` fixes a bug where `getSnapshotBeforeUpdate` was
running in hidden trees when it shouldn't (`componentWillUpdate` won't
run for hidden updates, and when it becomes visible it will be called
with `componentWillMount`).
2026-02-04 14:37:45 -05:00
Ricky
6913ea4d28 [flags] Add enableParallelTransitions (#35392)
## Overview

Adds a feature flag `enableParallelTransitions` to experiment with
engantling transitions less often.

## Motivation

Currently we over-entangle transition lanes. 

It's a common misunderstanding that React entangles all transitions,
always. We actually will complete transitions independently in many
cases. For example, [this
codepen](https://codepen.io/GabbeV/pen/pvyKBrM) from
[@gabbev](https://bsky.app/profile/gabbev.bsky.social/post/3m6uq2abihk2x)
shows transitions completing independently.

However, in many cases we entangle when we don't need to, instead of
letting the independent transitons complete independently. We still want
to entangle for updates that happen on the same queue.

## Example

As an example of what this flag would change, consider two independent
counter components:

```js
function Counter({ label }) {
  const [count, setCount] = useState(0);

  return (
    <div>
      <span>{use(readCache(`${label} ${count}`))} </span>
      <Button
        action={() => {
          setCount((c) => c + 1);
        }}
      >
        Next {label}
      </Button>
    </div>
  );
}
```
```js
export default function App() {
  return (
    <>
      <Counter label="A" />
      <Counter label="B" />
    </>
  );
}
```

### Before
The behavior today is to entange them, meaning they always commit
together:



https://github.com/user-attachments/assets/adead60e-8a98-4a20-a440-1efdf85b2142

### After

In this experiment, they will complete independently (if they don't
depend on each other):


https://github.com/user-attachments/assets/181632b5-3c92-4a29-a571-3637f3fab8cd

## Early Research

This change is in early research, and is not in the experimental
channel. We're going to experiment with this at Meta to understand how
much of a breaking change, and how beneficial it is before commiting to
shipping it in experimental and beyond.
2026-02-04 13:58:34 -05:00
Hendrik Liebau
cf993fb457 [Flight] Fix stack overflow in visitAsyncNode with deep async chains (#35612)
Database libraries like Gel/EdgeDB can create very long linear chains of
async sequences through temporal async sequencing in connection pools.
The recursive traversal of `node.previous` chains in `visitAsyncNode`
causes stack overflow on these deep chains.

The fix converts the `previous` chain traversal from recursive to
iterative. We collect the chain into an array, then process from deepest
to shallowest.

The `awaited` traversal remains recursive since its depth is bounded by
promise dependency depth, not by the number of event loop turns. Each
`awaited` branch still benefits from the iterative `previous` handling
within its own traversal.

I've verified that this fixes the
[repro](https://github.com/jere-co/next-debug) provided in #35246.

closes #35246
2026-02-04 19:43:23 +01:00
Jorge Cabiedes
c137dd6f54 Fix exhaustive deps bug with flow type casting. (#35691)
Summary:
I noticed there's a bug where the lint will recognize the type on a cast
annotation as a missing dependency;

```
        function MyComponent() {
          type ColumnKey = 'id' | 'name';
          type Item = {id: string, name: string};

          const columns = useMemo(
            () => [
              {
                type: 'text',
                key: 'id',
              } as TextColumn<ColumnKey, Item>,
                              ^^^^^^^^ here
            ],
            [],
          );
        }
```

This is due to the AST of AsExpressions being something like:

AsExpression
  └── typeAnnotation: GenericTypeAnnotation
        └── typeParameters: TypeParameterInstantiation
              └── params[0]: GenericTypeAnnotation
                    └── id: Identifier (name: "ColumnKey")

Where `ColumnKey` never has a TypeParameter Annotation. So we need to
consider it to be a flow type due to it belonging to a
GenericTypeAnnotation

Test Plan:
Added unit tests

Before:
```
Test Suites: 1 failed, 2 passed, 3 total
Tests:       2 failed, 5065 passed, 5067 total
Snapshots:   0 total
Time:        16.517 s
Ran all test suites.
error Command failed with exit code 1.
```

After:
```
 PASS  __tests__/ReactCompilerRuleTypescript-test.ts
 PASS  __tests__/ESLintRulesOfHooks-test.js (6.192 s)
 PASS  __tests__/ESLintRuleExhaustiveDeps-test.js (9.97 s)

Test Suites: 3 passed, 3 total
Tests:       5067 passed, 5067 total
Snapshots:   0 total
Time:        10.21 s, estimated 11 s
Ran all test suites.
  Done in 12.66s.
```
2026-02-04 08:24:24 -08:00
Anton Chesnokov
22a20e1f2f [compiler] Fix setState-in-effect for React.useEffect namespace calls (#35377) (#35419)
## Summary
Fix react-hooks/set-state-in-effect false negatives when Hooks are
called via a namespace import (e.g. `import * as React from 'react'` and
`React.useEffect(...))`. The validation now checks the MethodCall
property (the actual hook function) instead of the receiver object.

Issue: Bug: #35377

## How did you test this change?
Added a regression fixture;
Ran tests and verified it reports `EffectSetState` and matches the
expected output.

<img width="461" height="116" alt="Screenshot 2025-12-27 at 14 13 38"
src="https://github.com/user-attachments/assets/fff5aab9-0f2c-40e9-a6a5-b864c3fa6fbd"
/>
2026-02-04 11:07:17 -05:00
Joseph Savona
90c6d1b218 [compiler][snap] More minimization improvements (#35689)
* A few new minimization strategies, removing function params and
array/object pattern elements
* Ensure that we preserve the same set of errors based on not just
category+reason but also description.
2026-02-04 10:09:28 -05:00
Sebastian "Sebbie" Silbermann
f84ce5a45c [flags] Turn on enableViewTransition in OSS react-test-renderer (#35684) 2026-02-04 11:42:49 +01:00
Sebastian "Sebbie" Silbermann
c9ff56ec74 [DevTools] Disable Activity slices by default (#35685) 2026-02-04 10:56:33 +01:00
Joseph Savona
3ce1316b05 [compiler][snap] Fixes to relative path resolution; compile subcommand (#35688)
More snap improvements for use with agents:
* `yarn snap compile [--debug] <path>` for compiling any file,
optionally with debug logs
* `yarn snap minimize <path>` now accepts path as a positional param for
consistency w 'compile' command
* Both compile/minimize commands properly handle paths relative to the
compiler/ directory. When using `yarn snap` the current working
directory is compiler/packages/snap, but you're generally running it
from the compiler directory so this matches expectations of callers
better.
2026-02-03 22:12:21 -05:00
Joseph Savona
cd0c4879a2 [compiler] Fix for loops in try/catch (#35686)
This is a combination of a) a subagent for investigating compiler errors
and b) testing that agent by fixing bugs with for loops within
try/catch. My recent diffs to support maybe-throw within value blocks
was incomplete and handled many cases, like optionals/logicals/etc
within try/catch. However, the handling for for loops was making more
assumptions and needed additional fixes.

Key changes:
* `maybe-throw` terminal `handler` is now nullable. PruneMaybeThrows
nulls the handler for blocks that cannot throw, rather than changing to
a `goto`. This preserves more information, and makes it easier for
BuildReactiveFunction's visitValueBlock() to reconstruct the value
blocks
* Updates BuildReactiveFunction's handling of `for` init/test/update
(and similar for `for..of` and `for..in`) to correctly extract value
blocks. The previous logic made assumptions about the shape of the
SequenceExpression which were incorrect in some cases within try/catch.
The new helper extracts a flattened SequenceExpression.

Supporting changes:
* The agent itself (tested via this diff)
* Updated the script for invoking snap to keep `compiler/` as the
working directory, allowing relative paths to work more easily
* Add an `--update` (`-u`) flag to `yarn snap minimize`, which updates
the fixture in place w the minimized version
2026-02-03 18:04:34 -05:00
Sebastian "Sebbie" Silbermann
6853d7ab2f [Perf Tracks] Prevent crash when accessing $$typeof (#35679) 2026-02-03 17:53:45 +01:00
Sebastian "Sebbie" Silbermann
e32c126121 [flags] Turn on enableAsyncDebugInfo everywhere (#35683) 2026-02-03 17:52:57 +01:00
Ricky
3e00319b35 [Flight] allow context providers from client modules (#35675)
Allows Server Components to import Context from a `"use client'` module
and render its Provider.

Only tricky part was that I needed to add `REACT_CONTEXT_TYPE` handling
in mountLazyComponent so lazy-resolved Context types can be rendered.
Previously only functions, REACT_FORWARD_REF_TYPE, and REACT_MEMO_TYPE
were handled.

Tested in the Flight fixture.

ty bb claude

Closes https://github.com/facebook/react/issues/35340

---------

Co-authored-by: Sophie Alpert <git@sophiebits.com>
2026-02-03 10:22:57 -05:00
Sebastian "Sebbie" Silbermann
3419420e8b [flags] Cleanup enableActivity (#35681) 2026-02-03 16:08:18 +01:00
Janka Uryga
b1533b034e [Flight] Allow overriding request.timeOrigin via options.startTime (#35598)
Currently, IO that finished before the request started is not considered
IO:

6a0ab4d2dd/packages/react-server/src/ReactFlightServer.js (L5338-L5343)
This leads to loss of debug info when a flight stream is deserialized
and serialized again.
We can solve this by allowing "when the the request started" to be set
to a point in the past, when the original stream started by doing

```js
const startTime = performance.now() + performance.timeOrigin
// ... stuff happens and time passes...
ReactServer.renderToReadableStream(..., { startTime })
```
2026-02-03 15:29:51 +01:00
Ruslan Lesiutin
5dad2b47b8 [DevTools] Fix commit index reset when switching profiler roots (#35672)
Fixes https://github.com/facebook/react/issues/31463,
https://github.com/facebook/react/issues/30114.

When switching between roots in the profiler flamegraph, the commit
index was preserved from the previous root. This caused an error
"Invalid commit X. There are only Y commits." when the new root had
fewer commits than the selected index.

This fix resets the commit index to 0 (or null if no commits) when the
commitData changes, which happens when switching roots.
2026-02-03 12:44:04 +00:00
Sebastian "Sebbie" Silbermann
748ee74e22 Use modern JSX runtime in Flight fixture (#35677) 2026-02-03 12:05:24 +01:00
Joseph Savona
d4a325df4d [compiler] Add snap subcommand to minimize a test input (#35663)
Snap now supports subcommands 'test' (default) and 'minimize`. The
minimize subcommand attempts to minimize a single failing input fixture
by incrementally simplifying the ast so long as the same error occurs. I
spot-checked it and it seemed to work pretty well. This is intended for
use in a new subagent designed for investigating bugs — fixture
simplification is an important part of the process and we can automate
this rather than light tokens on fire.

Example Input:

```js
function Component(props) {
  const x = [];
  let result;
  for (let i = 0; i < 10; i++) {
    if (cond) {
      try {
        result = {key: bar([props.cond && props.foo])};
      } catch (e) {
        console.log(e);
      }
    }
  }
  x.push(result);
  return <Stringify x={x} />;
}
```

Command output:

```
$ yarn snap minimize --path .../input.js
Minimizing: .../input.js

Minimizing................

--- Minimized Code ---
function Component(props) {
  try {
    props && props;
  } catch (e) {}
}

Reduced from 16 lines to 5 lines
```

This demonstrates things like:
* Removing one statement at at time
* Replacing if/else with the test, consequent, or alternate. Similar for
other control-flow statements including try/catch
* Removing individual array/object expression properties
* Replacing single-value array/object with the value
* Replacing control-flow expression (logical, consequent) w the test or
left/right values
* Removing call arguments
* Replacing calls with a single argument with the argument
* Replacing calls with multiple arguments with an array of the arguments
* Replacing optional member/call with non-optional versions
* Replacing member expression with the object. If computed, also try
replacing w the key
* And a bunch more strategies, see the code
2026-02-02 22:03:47 -05:00
Sebastian "Sebbie" Silbermann
7b023d7073 [react-dom] Include submitter in submit events (#35590) 2026-02-02 21:17:31 +01:00
Sebastian "Sebbie" Silbermann
dcab44d757 [react-dom] Fire onReset when automatically resetting forms (#35176) 2026-02-02 21:17:14 +01:00
Joseph Savona
b8a6bfa22c [compiler] Support optional/logical/etc within try/catch (#35606)
Adds support for value terminals (optional/logical/ternary/sequence)
within try/catch clauses.

Try/catch expressions insert maybe-throw terminals after each
instruction, but BuildReactiveFunction's value block extraction was not
expecting these terminals. The fix is to roughly treat maybe-throw
similarly to goto, falling through to the continuation block, but there
are a few edge cases to handle.

I've also added extensive tests, including testing that errors correctly
flow to the catch handler.
2026-02-02 09:27:05 -08:00
Sebastian "Sebbie" Silbermann
ed4bd540ca [Flight] Warn once if eval is disabled in dev environment (#35661) 2026-02-02 12:56:14 +01:00
Nathan
64b4605cb8 [compiler] fix source location for return statements (#35660)
Fixes missing source locations for ReturnStatement nodes in generated
ast. Simple change using existing pattern, only required changes to the
codegen step, no other pipeline changes.

**Most file changes are new lines in generated code.** [First
commit](d15e90ebe0)
has the relevant changes, second commit has the noisy snap updates.

I added an exception to the validator to not report an error when a
return statement will be optimized to an implicit return by codegen, as
there's no separate return statement to instrument anyways in the final
ast. An edge case when it comes to preserving source locations for
instrumentation that is likely not as common for most babel transforms
since they are not doing optimizations.
2026-01-30 08:37:19 -08:00
Sebastian "Sebbie" Silbermann
da64117876 [Perf Tracks] Handle function names that aren't strings (#35659) 2026-01-29 18:32:18 +01:00
Ricky
230772f99d [tests] Fix ReactDOMAttribute-test (#35654)
In https://github.com/facebook/react/pull/35646 I thought there was a
bug in trusted types, but the bug is in jsdom.

For trusted types we still want to check the coersion and throw for a
good dev warning, but prod will also throw becuase the browser will
implicitly coerce to a string. This ensures there's no behavior
difference between dev and prod.

So the right fix is to add in the JSDOM hack that's used in
`ReactDOMSelect-test.js`.
2026-01-28 16:00:40 -05:00
Jack Pope
90b2dd442c Add additional fixtures for FragmentInstance text node support (#35631)
Stacked on https://github.com/facebook/react/pull/35630

- Adds test case for compareDocumentPosition, missing before and also
extending to text nodes
- Adds event handling fixture case for text
- Adds getRootNode fixture case for text
2026-01-28 14:55:07 -05:00
Jack Pope
875b06489f Add text node support to FragmentInstance operations (#35630)
This PR adds text node support to FragmentInstance operations, allowing
fragment refs to properly handle fragments that contain text nodes
(either mixed with elements or text-only).

Not currently adding/removing new text nodes as we don't need to track
them for events or observers in DOM. Will follow up on this and with
Fabric support.

## Support through parent element
- `dispatchEvent`
- `compareDocumentPosition`
- `getRootNode`

## Support through Range API
- `getClientRects`: Uses Range to calculate bounding rects for text
nodes
- `scrollIntoView`: Uses Range to scroll to text node positions directly

## No support
- `focus`/`focusLast`/`blur`: Noop for text-only fragments
- `observeUsing`:  Warns for text-only fragments in DEV
- `addEventListener`/`removeEventListener`: Ignores text nodes, but
still works on Fragment level through `dispatchEvent`
2026-01-28 14:45:17 -05:00
Jan Olaf Martin
d4d099f05b [flags] make enableTrustedTypesIntegration dynamic (#35646)
Co-authored-by: Rick Hanlon <rickhanlonii@meta.com>
2026-01-28 13:15:33 -05:00
Sebastian "Sebbie" Silbermann
c0c37063e2 [Flight] Restore original function name in dev, server callstacks served with unsafe-eval (#35650) 2026-01-28 18:41:08 +01:00
Sebastian "Sebbie" Silbermann
87ae75b33f [Perf Tracks] Use minus (-) instead of en dash for removed props (#35649) 2026-01-28 12:14:59 +01:00
Sebastian "Sebbie" Silbermann
ff191f24b5 [Perf Tracks] Handle arrays with bigints in deep objects (#35648) 2026-01-28 11:54:50 +01:00
Ricky
e66ef6480e [tests] remove withoutStack from assertConsole helpers (#35498)
Stacked on https://github.com/facebook/react/pull/35497

-----

Now that the assert helpers require a component stack, we don't need the
`{withoutStack: true}` option.
2026-01-27 22:34:03 -05:00
Sebastian "Sebbie" Silbermann
8c34556ca8 [Flight] Fix react-markup types for server references (#35634) 2026-01-26 21:13:16 +01:00
Hendrik Liebau
10680271fa [Flight] Add more DoS mitigations to Flight Reply, and harden Flight (#35632)
This fixes security vulnerabilities in Server Functions.

---------

Co-authored-by: Sebastian Markbåge <sebastian@calyptus.eu>
Co-authored-by: Josh Story <josh.c.story@gmail.com>
Co-authored-by: Janka Uryga <lolzatu2@gmail.com>
Co-authored-by: Sebastian Sebbie Silbermann <sebastian.silbermann@vercel.com>
2026-01-26 20:24:58 +01:00
Ruslan Lesiutin
699abc89ce [flags] make enableComponentPerformanceTrack static everywhere (#35629)
Follow-up to https://github.com/facebook/react/pull/34665.

Already gated on `enableProfilerTimer` everywhere, which is only enabled
for `__PROFILE__`, except for Flight should be unified in a future.
2026-01-26 18:38:56 +00:00
Sebastian "Sebbie" Silbermann
3e319a943c [DevTools] Apply component filters on initial load (#35587) 2026-01-26 11:06:04 +01:00
Sebastian "Sebbie" Silbermann
2c30ebc4e3 [DevTools] Update inspected element on component filter changes (#35599) 2026-01-26 11:04:06 +01:00
Ricky
a0566250b2 [repo] init claude config (#35617)
## Overview

Adds a claude setup that works with the nested /compiler setup.

The constraints are:
- when working in the root repo, don't use the compiler configs (easy)
- when working in the compiler/ don't use the parent contigs (hard)

The first one is easy: there's a claude.md and .claude directory in
/compiler that is only loaded when you start a session from /compuler.
The second one is hard, because if you start a session from /compiler,
the parent claude files and skills are loaded.

I was able to deny the permissions to the parent skills in
settings.json, but the descriptions are still loaded into context and I
don't think that's avoidable.

To keep the parent claude file out of context, I created a hook hack: I
moved all the non-compiler claude file context to instructions.md and
added a SessionStart hook to cat the file into context if the cwd isn't
the /compiler. Works well, but won't show it as part of the `/context`
slash command.


## Skills

I also added a number of skills specific to the React repo:

| Skill | Description |
|-------|-------------|
| `/extract-errors` |  `yarn extract-errors` |
| `/feature-flags` | how feature flags work and `@gate`  |
| `/fix` | linc and prettier |
| `/flags` | `yarn flags` |
| `/flow` | `yarn flow <variant>` |
| `/test` | `yarn test-*` |
| `/verify` | `run all the lints/tests/flow to verify` |

### Example: Flow

| before | after |
|-----|-----|
| <img width="1076" height="442" alt="flow-before"
src="https://github.com/user-attachments/assets/73eec143-d0af-4771-b501-c9dc29cc09ac"
/> | <img width="1076" height="273" alt="flow-after"
src="https://github.com/user-attachments/assets/292d33af-1d98-4252-9c08-744b33e88b86"
/> |

### Example: Tests

| before | after |
|-----|-----|
| <img width="1048" height="607" alt="test-before"
src="https://github.com/user-attachments/assets/aa558ccf-2cee-4d22-b1f1-e4221c5a59dd"
/> | <img width="1075" height="359" alt="test-after"
src="https://github.com/user-attachments/assets/eb795392-6f46-403f-b9bb-8851ed790165"
/> |
2026-01-23 20:16:06 -05:00
Joseph Savona
870cccd656 [compiler] Summaries of the compiler passes to assist agents in development (#35595)
Autogenerated summaries of each of the compiler passes which allow
agents to get the key ideas of a compiler pass, including key
input/output invariants, without having to reprocess the file each time.
In the subsequent diff this seemed to help.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35595).
* #35607
* #35298
* #35596
* #35573
* __->__ #35595
* #35539
2026-01-23 11:26:47 -08:00
Joseph Savona
c3b95b0979 [compiler] Improve snap workflow for debugging errors (#35539)
Much nicer workflow for working through errors in the compiler:
* Run `yarn snap -w`, oops there are are errors
* Hit 'p' to select a fixture => the suggestions populate with recent
failures, sorted alphabetically. No need to copy/paste the name of the
fixture you want to focus on!
* tab/shift-tab to pick one, hit enter to select that one
* ...Focus on fixing that test...
* 'p' to re-enter the picker. Snap tracks the last state of each fixture
and continues to show all tests that failed on their last run, so you
can easily move on to the next one. The currently selected test is
highlighted, making it easy to move to the next one.
* 'a' at any time to run all tests
* 'd' at any time to toggle debug output on/off (while focusing on a
single test)

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35539).
* #35607
* #35298
* #35596
* #35573
* #35595
* __->__ #35539
2026-01-23 11:26:33 -08:00
Joseph Savona
006ae37972 [compiler] Collapse CompilerError.{invariant,simpleInvariant} (#35614)
`invariant()` was a pain to use - we always record a single location,
but the API required passing a compiler detail. This PR replaces
`invariant()` (keeping the name) with `simpleInvariant()`s signature,
and updates call sites accordingly. I've noticed that agents
consistently get invariant() wrong, which aligns with it being tedious
to call when you're writing code by hand. The simplified API should help
a bit.
2026-01-23 11:07:11 -08:00
Joseph Savona
a688a3d18c worktree script improvements (#35603)
A few small improvements:
* Use `<root>/.worktrees` as the directory for worktrees so its hidden
by default in finder/ls
* Generate names with a timestamp, and allow auto-generating a name so
that you can just call eg `./scripts/worktree.sh --compiler --claude`
and get a random name
2026-01-23 10:41:17 -08:00
Joseph Savona
2c8725fdfd [compiler] snap fails if nothing compiled, unless @expectNothingCompiled (#35615)
A few times an agent has constructed fixtures that are silently skipped
because the component has no jsx or hook calls. This PR updates snap to
ensure that for each fixture either:

1) There are at least one compile success/failure *and* the
`@expectNothingCompiled` pragma is missing
2) OR there are zero success/failures *and* the `@expectNothingCompiled`
pragma is present

This ensures we are intentional about fixtures that are expected not to
have compilation, and know if that expectation breaks.
2026-01-23 10:38:40 -08:00
Joseph Savona
03613cd68c [compiler] Improve snap usability (#35537)
A whole bunch of changes to snap aimed at making it more usable for
humans and agents. Here's the new CLI interface:

```
node dist/main.js --help
Options:
      --version         Show version number                            [boolean]
      --sync            Run compiler in main thread (instead of using worker
                        threads or subprocesses). Defaults to false.
                                                      [boolean] [default: false]
      --worker-threads  Run compiler in worker threads (instead of
                        subprocesses). Defaults to true.
                                                       [boolean] [default: true]
      --help            Show help                                      [boolean]
  -w, --watch           Run compiler in watch mode, re-running after changes
                                                                       [boolean]
  -u, --update          Update fixtures                                [boolean]
  -p, --pattern         Optional glob pattern to filter fixtures (e.g.,
                        "error.*", "use-memo")                          [string]
  -d, --debug           Enable debug logging to print HIR for each pass[boolean]
```

Key changes:
* Added abbreviations for common arguments
* No more testfilter.txt! Filtering/debugging works more like Jest, see
below.
* The `--debug` flag (`-d`) controls whether to emit debug information.
In watch mode, this flag sets the initial debug value, and it can be
toggled by pressing the 'd' key while watching.
* The `--pattern` flag (`-p`) sets a filter pattern. In watch mode, this
flag sets the initial filter. It can be changed by pressing 'p' and
typing a new pattern, or pressing 'a' to switch to running all tests.
* As before, we only actually enable debugging if debug mode is enabled
_and_ there is only one test selected.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35537).
* #35607
* #35298
* #35596
* #35573
* #35595
* #35539
* __->__ #35537
* #35523
2026-01-23 10:36:55 -08:00
Joseph Savona
2af6822c21 [compiler] Claude file/settings (#35523)
Initializes CLAUDE.md and a settings file for the compiler/ directory to
help use claude with the compiler. Note that some of the commands here
depend on changes to snap from the next PR.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35523).
* #35607
* #35298
* #35596
* #35573
* #35595
* #35539
* #35537
* __->__ #35523
2026-01-23 10:36:43 -08:00
Sebastian "Sebbie" Silbermann
24d8716e36 Gitignore local Claude files (#35610) 2026-01-23 16:30:08 +01:00
Ruslan Lesiutin
94913cbffe [flags] cleanup renameElementSymbol (#35600)
Removed the feature flag completely, enabled by default. Will land once
I have everything ready on xplat side.
2026-01-23 10:46:30 +00:00
Ricky
2d8e7f1ce3 [flags] Remove enableHydrationLaneScheduling (#35549)
This is just a killswitch and has been on for over a year
https://github.com/facebook/react/pull/31751
2026-01-22 13:51:48 -05:00
Joseph Savona
6a0ab4d2dd Add worktree script (#35593)
Intended to be used directly and/or from skills in an agent.

Usage is `./scripts/worktree.sh [--compiler] [--claude] <name>`. The
script:
* Checks that ./worktrees is in gitignore
* Checks the named worktree does not exist yet
* Creates the named worktree in ./worktrees/
* Installs deps
* cds into the worktree (optionally the compiler dir if `--compiler`)
* optionally runs claude in the worktree if `--claude`
2026-01-21 22:38:37 -08:00
Joseph Savona
03ee29da2f [eslint-plugin-react-hooks] Skip compilation for non-React files (#35589)
Add a fast heuristic to detect whether a file may contain React
components or hooks before running the full compiler. This avoids the
overhead of Babel AST parsing and compilation for utility files, config
files, and other non-React code.

The heuristic uses ESLint's already-parsed AST to check for functions
with React-like names at module scope:
- Capitalized functions: MyComponent, Button, App
- Hook pattern functions: useEffect, useState, useMyCustomHook

Files without matching function names are skipped and return an empty
result, which is cached to avoid re-checking for subsequent rules.

Also adds test coverage for the heuristic edge cases.
2026-01-21 12:49:15 -08:00
Sebastian "Sebbie" Silbermann
cdbd55f440 Type react-devtools-hook-installer and react-devtools-hook-settings-injector messages (#35586) 2026-01-21 19:13:24 +01:00
Sebastian Markbåge
b546603bcb [Fiber] getNearestMountedFiber should consider fibers with alternates as mounted (#35578) 2026-01-21 08:33:35 -05:00
Sebastian "Sebbie" Silbermann
7fccd6b5a3 [DevTools] Fix console links not being openable (#35229) 2026-01-21 10:34:26 +01:00
Sebastian Markbåge
d29087523a Cancel animation when a custom Timeline is used (#35567)
Follow up to #35559.

The clean up function of the custom timeline doesn't necessarily clean
up the animation. Just the timeline's internal state.

This affects Firefox which doesn't support ScrollTimeline so uses the
polyfill's custom timeline.
2026-01-19 20:53:05 -05:00
Sebastian Markbåge
d343c39cce Remove Gesture warning when cloning the root (#35566)
Currently we always clone the root when a gesture transition happens.
The was to add an optimization where if a Transition could be isolated
to an absolutely positioned subtree then we could just clone that
subtree or just do a plain insertion if it was simple an Enter. That way
when switching between two absolutely positioned pages the shell
wouldn't need to be cloned. In that case `detectMutationOrInsertClones`
would return false. However, currently it always return true because we
don't yet have that optimization.

The idea was to warn when the root required cloning to ensure that you
optimize it intentionally since it's easy to accidentally update more
than necessary. However, since this is not yet actionable I'm removing
this warning for now.

Instead, I add a warning for particularly bad cases where you really
shouldn't clone like iframe and video. They may not be very actionable
without the optimization since you can't scope it down to a subtree
without the optimization. So if they're above the gesture then they're
always cloned atm. However, it might also be that it's unnecessary to
keep them mounted if they could be removed or hidden with Activity.
2026-01-19 19:28:12 -05:00
Sebastian Markbåge
1ecd99c774 Temporarily Mount useInsertionEffect while a Gesture snapshot is being computed (#35565)
`useInsertionEffect` is meant to be used to insert `<style>` tags that
affect the layout. It allows precomputing a layout before it mounts.

Since we're not normally firing any effects during the "apply gesture"
phase where we create the clones, it's possible for the target snapshot
to be missing styles. This makes it so that `useInsertionEffect` for a
new tree are mounted before the snapshot is taken and then unmounted
before the animation starts.

Note that because we are mounting a clone of the DOM tree and the
previous DOM tree remains mounted during the snapshot, we can't unmount
any previous insertion effects. This can lead to conflicts but that is
similar to what can happen with conflicts for two mounted Activity
boundaries since insertion effects can remain mounted inside those.

A revealed Activity will have already had their insertion effects fired
while offscreen.

However, one thing this doesn't yet do is handle the case where a
`useInsertionEffect` is *updated* as part of a gesture being applied.
This means it's still possible for it to miss some styles in that case.
The interesting thing there is that since the old state and the new
state will both be applicable to the global DOM in this phase, what
should really happen is that we should mount the new updated state
without unmounting the old state and then unmount the updated state.
Meaning you can have the same hook in the mounted state twice at the
same time.
2026-01-19 19:27:59 -05:00
Sebastian Markbåge
c55ffb5ca3 Add Clean Up Callbacks to View Transition and Gesture Transition Events (#35564)
Stacked on #35556 and #35559.

Given that we don't automatically clean up all view transition
animations since #35337 and browsers are buggy, it's important that you
clean up any `Animation` started manually from the events. However,
there was no clean up function for when the View Transition is forced to
stop. This also makes it harder to clean up custom timers etc too.

This lets you return a clean up function from all the events on
`<ViewTransition>`.
2026-01-19 19:27:45 -05:00
Sebastian Markbåge
a49952b303 Properly clean up gesture Animations (#35559)
Follow up to #35337.

During a gesture, we always cancel the original animation and create a
new one that we control. That's the one we need to add to the set that
needs to be cancelled. Otherwise future gestures hang.

An unfortunate consequence is that any custom ones that you start e.g.
with #35556 or through other means aren't automatically cleaned up (in
fact there's not even a clean up callback yet). This can lead these to
freeze the whole UI afterwards. It would be really good to get this
fixed in browsers instead so we can revert #35337.
2026-01-19 19:26:28 -05:00
Sebastian Markbåge
4bcf67e746 Support onGestureEnter/Exit/Share/Update events (#35556)
This is like the onEnter/Exit/Share/Update events but for gestures. It
allows manually controlling the animation using the passed timeline.
2026-01-19 19:26:09 -05:00
Sebastian "Sebbie" Silbermann
41b3e9a670 [Fizz] Push a stalled use() to the ownerStack/debugTask (#35226) 2026-01-19 09:10:16 +01:00
Ricky
195fd2286b [tests] Fix flaky flight tests (#35513)
Flights tests are failing locally and in CI non-deterministically
because we're not disabling async hooks after tests, and GC can clear
WeakRefs non-deterministically.

This PR fixes the issue by adding an afterEach to disable installed
hooks, and normalizing the `value` to `value: {value: undefined}}` when
snapshotting.
2026-01-18 15:36:00 -05:00
Ricky
d87298ae16 [tests] add silent reporter (#35547)
Adds silent reporter so you can run tests and only see the failed tests

This helps reduce context agents use, if you're inclined to use agents:

<img width="630" height="292" alt="Screenshot 2026-01-17 at 12 39 58 PM"
src="https://github.com/user-attachments/assets/373b9803-59a6-4b9a-99f9-d74a7b41462e"
/>
2026-01-18 10:17:17 -05:00
Ricky
be3fb29904 [internal] revert change merged accidentally (#35546)
I accidentally pushed this to new flag to
https://github.com/facebook/react/pull/35541 and then merged it.

Reverting it so I can submit a review.
2026-01-17 13:21:46 -05:00
Ricky
23e5edd05c [flags] clean up enableUseEffectEventHook (#35541)
This is landed everywhere
2026-01-17 12:46:05 -05:00
Jack Pope
3926e2438f Fix ViewTransition null stateNode with SuspenseList (#35520)
I was experimenting with animations in SuspenseList and hit a crash
using ViewTransition as a direct child with `revealOrder="together"`

```
    TypeError: Cannot read properties of null (reading 'autoName')

      33 |     return props.name;
      34 |   }
    > 35 |   if (instance.autoName !== null) {
         |                ^
      36 |     return instance.autoName;
      37 |   }
```

When ViewTransition is direct child of SuspenseList, the second render
pass calls resetChildFibers, setting stateNode to null. Other fibers
create stateNode in completeWork. ViewTransition does not, so stateNode
is lost.

Followed the pattern used for Offscreen to update stateNode in beginWork
if it is null.

Also added a regression test.
2026-01-16 16:39:25 -05:00
Hendrik Liebau
6baff7ac76 [Flight] Allow cyclic references to be serialized when unwrapping lazy elements (#35471)
When `renderModelDestructive` unwraps a lazy element and subsequently
calls `renderModelDestructive` again with the resolved model, we should
preserve the parent connection so that cyclic references can be
serialized properly. This can occur in an advanced scenario where the
result from the Flight Client is serialized again with the Flight
Server, e.g. for slicing a precomputed payload into multiple parts.

Note: The added test only fails when run with `--prod`. In dev mode, the
component info outlining prevents the issue from occurring.
2026-01-16 18:42:09 +01:00
Sebastian "Sebbie" Silbermann
bef88f7c11 [DevTools] Stop setting unused global variables (#35532) 2026-01-16 16:13:29 +01:00
Sebastian "Sebbie" Silbermann
01c4d03d84 [DevTools] Clear element inspection if host element not owned by any renderer is selected (#35504) 2026-01-16 13:20:44 +01:00
Sebastian "Sebbie" Silbermann
cbc4d40663 Typecheck React DevTools extension main script (#35519) 2026-01-16 13:08:28 +01:00
Josh Story
db71391c5c [Fiber] Instrument the lazy initializer thenable in all cases (#35521)
When a lazy element or component is initialized a thenable is returned
which was only be conditionally instrumented in dev when asyncDebugInfo
was enabled. When instrumented these thenables can be used in
conjunction with the SuspendOnImmediate optimization where if a thenable
resolves before the stack unwinds we can continue rendering from the
last suspended fiber. Without this change a recent fix to the useId
implementation cannot be easily tested in production because this
optimization pathway isn't available to regular React.lazy thenables. To
land the prior PR I changed the thenables to a custom type so I could
instrument manually in the test. WIth this change we can just use a
regular Promise since ReactLazy will instrument in all
environments/flags now
2026-01-15 19:05:23 -08:00
Sebastian Markbåge
4cf906380d Optimize gesture by allowing the original work in progress tree to be a suspended commit (#35510)
Stacked on #35487.

This is slightly different because the first suspended commit is on
blockers that prevent us from committing which still needs to be
resolved first.

If a gesture lane has to be rerendered while the gesture is happening
then it reenters this state with a new tree. (Currently this doesn't
happen for a ping I think which is not really how it usually works but
better in this case.)
2026-01-15 20:51:36 -05:00
Sebastian Markbåge
eac3c95537 Defer useDeferredValue updates in Gestures (#35511)
If an initial value is specified, then it's always used regardless as
part of the gesture render.

If a gesture render causes an update, then previously that was not
treated as deferred and could therefore be blocking the render. However,
a gesture is supposed to flush synchronously ideally. Therefore we
should consider these as urgent.

The effect is that useDeferredValue renders the previous state.
2026-01-15 20:46:11 -05:00
Sebastian Markbåge
35a81cecf7 Entangle Gesture revert commit with the corresponding Action commit (#35487)
Stacked on #35486.

When a Gesture commits, it leaves behind work on a Transition lane
(`revertLane`). This entangles that lane with whatever lane we're using
in the event that cancels the Gesture. This ensures that the revert and
the result of any resulting Action commits as one batch. Typically the
Action would apply a new state that is similar or the same as the revert
of the Gesture.

This makes it resilient to unbatching in #35392.
2026-01-15 20:45:14 -05:00
Sebastian Markbåge
4028aaa50c Commit the Gesture lane if a gesture ends closer to the target state (#35486)
Stacked on #35485.

Before this PR, the `startGestureTransition` API would itself never
commit its state. After the gesture releases it stops the animation in
the next commit which just leaves the DOM tree in the original state. If
there's an actual state change from the Action then that's committed as
the new DOM tree. To avoid animating from the original state to the new
state again, this is DOM without an animation. However, this means that
you can't have the actual action committing be in a slightly different
state and animate between the final gesture state and into the new
action.

Instead, we now actually keep the render tree around and commit it in
the end. Basically we assume that if the Timeline was closer to the end
then visually you're already there and we can commit into that state.
Most of the time this will be at the actual end state when you release
but if you have something else cancelling the gesture (e.g.
`touchcancel`) it can still commit this state even though your gesture
recognizer might not consider this an Action. I think this is ok and
keeps it simple.

When the gesture lane commits, it'll leave a Transition behind as work
from the revert lanes on the Optimistic updates. This means that if you
don't do anything in the Action this will cause another commit right
after which reverts. This revert can animate the snap back.

There's a few fixes needed in follow up PRs:

- Fixed in #35487. ~To support unentangled Transitions we need to
explicitly entangle the revert lane with the Action to avoid committing
a revert followed by a forward instead of committing the forward
entangled with the revert. This just works now since everything is
entangled but won't work with #35392.~
- Fixed in #35510. ~This currently rerenders the gesture lane once
before committing if it was already completed but blocked. We should be
able to commit the already completed tree as is.~
2026-01-15 20:43:52 -05:00
Josh Story
f0fbb0d199 [Fiber] fix useId tracking on replay (#35518)
When Fiber replays work after suspending and resolving in a microtask it
stripped the Forked flag from Fibers because this flag type was not
considered a Static flag. The Forked nature of a Fiber is not render
dependent and should persist after unwinding work. By making this change
the replay correctly generates the necessary tree context.
2026-01-15 17:27:58 -08:00
Sebastian "Sebbie" Silbermann
bb8a76c6cc [DevTools] Show fallback in inspected element pane when no element is selected (#35503) 2026-01-15 14:28:02 +01:00
Sebastian "Sebbie" Silbermann
fae15df40e [DevTools] Add React Element pane to browser Elements panel (#35240) 2026-01-15 13:24:06 +01:00
Błażej Kustra
53daaf5aba Improve the detection of changed hooks (#35123)
## Summary

cc @hoxyq 

Fixes https://github.com/facebook/react/issues/28584. Follow up to PR:
https://github.com/facebook/react/pull/34547

This PR updates getChangedHooksIndices to account for the fact that
`useSyncExternalStore`, `useTransition`, `useActionState`,
`useFormState` internally mounts more than one hook while DevTools
should treat it as a single user-facing hook.

Approach idea came from
[this](https://github.com/facebook/react/pull/34547#issuecomment-3504113776)
comment 😄

Before:


https://github.com/user-attachments/assets/6bd5ce80-8b52-4bb8-8bb1-5e91b1e65043


After:


https://github.com/user-attachments/assets/47f56898-ab34-46b6-be7a-a54024dcefee



## How did you test this change?

I used this component to reproduce this issue locally (I followed
instructions in `packages/react-devtools/CONTRIBUTING.md`).

<details><summary>Details</summary>

```ts

import * as React from 'react';

function useDeepNestedHook() {
  React.useState(0); // 1
  return React.useState(1); // 2
}

function useNestedHook() {
  const deepState = useDeepNestedHook();
  React.useState(2); // 3
  React.useState(3); // 4

  return deepState;
}

// Create a simple store for useSyncExternalStore
function createStore(initialValue) {
  let value = initialValue;
  const listeners = new Set();
  return {
    getSnapshot: () => value,
    subscribe: listener => {
      listeners.add(listener);
      return () => {
        listeners.delete(listener);
      };
    },
    update: newValue => {
      value = newValue;
      listeners.forEach(listener => listener());
    },
  };
}

const syncExternalStore = createStore(0);

export default function InspectableElements(): React.Node {
  const [nestedState, setNestedState] = useNestedHook();

  // 5
  const syncExternalValue = React.useSyncExternalStore(
    syncExternalStore.subscribe,
    syncExternalStore.getSnapshot,
  );

  // 6
  const [isPending, startTransition] = React.useTransition();

  // 7
  const [formState, formAction, formPending] = React.useActionState(
    async (prevState, formData) => {
      return {count: (prevState?.count || 0) + 1};
    },
    {count: 0},
  );

  const handleTransition = () => {
    startTransition(() => {
      setState(Math.random());
    });
  };

  // 8
  const [state, setState] = React.useState('test');

  return (
    <>
      <div
        style={{
          padding: '20px',
          display: 'flex',
          flexDirection: 'column',
          gap: '10px',
        }}>
        <div
          onClick={() => setNestedState(Math.random())}
          style={{backgroundColor: 'red', padding: '10px', cursor: 'pointer'}}>
          State: {nestedState}
        </div>

        <button onClick={handleTransition} style={{padding: '10px'}}>
          Trigger Transition {isPending ? '(pending...)' : ''}
        </button>

        <div style={{display: 'flex', gap: '10px', alignItems: 'center'}}>
          <button
            onClick={() => syncExternalStore.update(syncExternalValue + 1)}
            style={{padding: '10px'}}>
            Trigger useSyncExternalStore
          </button>
          <span>Value: {syncExternalValue}</span>
        </div>

        <form
          action={formAction}
          style={{display: 'flex', gap: '10px', alignItems: 'center'}}>
          <button
            type="submit"
            style={{padding: '10px'}}
            disabled={formPending}>
            Trigger useFormState {formPending ? '(pending...)' : ''}
          </button>
          <span>Count: {formState.count}</span>
        </form>

        <div
          onClick={() => setState(Math.random())}
          style={{backgroundColor: 'red', padding: '10px', cursor: 'pointer'}}>
          State: {state}
        </div>
      </div>
    </>
  );
}
```


</details>

---------

Co-authored-by: Ruslan Lesiutin <28902667+hoxyq@users.noreply.github.com>
2026-01-15 11:06:14 +00:00
Sebastian Markbåge
4a3d993e52 Add the suffix to cancelled view transition names (#35485)
When a View Transition might not need to update we add it to a queue. If
the parent are able to be reverted, we then cancel the already started
view transitions. We do this by adding an animation that hides the "old"
state and remove the view transition name from the old state.

There was a bug where if you have more than one child in a
`<ViewTransition>` we didn't add the right suffix to the name we added
in the queue so it wasn't adding an animation that hides the old state.
The effect was that it playing an exit animation instead of being
cancelled.
2026-01-14 10:00:06 -05:00
Ricky
3e1abcc8d7 [tests] Require exact error messages in assertConsole helpers (#35497)
Requires full error message in assert helpers. 

Some of the error messages we asset on add a native javascript stack
trace, which would be a pain to add to the messages and maintain. This
PR allows you to just add `\n in <stack>` placeholder to the error
message to denote a native stack trace is present in the message.

---
Note: i vibe coded this so it was a pain to backtrack this to break this
into a stack, I tried and gave up, sorry.
2026-01-13 15:52:53 -05:00
Josh Story
c18662405c [Fiber] Correctly handle replaying when hydrating (#35494)
When hydrating if something suspends and then resolves in a microtask it
is possible that React will resume the render without fully unwinding
work in progress. This can cause hydration cursors to be offset and lead
to hydration errors. This change adds a restore step when replaying
HostComponent to ensure the hydration cursor is in the appropriate
position when replaying.

fixes: #35210
2026-01-13 12:48:01 -08:00
Yukimasa Funaoka
583e200332 [DevTools] Enable minimal support in pages with sandbox Content-Security-Policy (#35208) 2026-01-13 17:49:44 +01:00
Sebastian "Sebbie" Silbermann
8a83073753 [test] Fix DevTools regression tests (#35501) 2026-01-13 16:00:16 +01:00
Sebastian "Sebbie" Silbermann
5aec1b2a8d [DevTools] Attach async info in filtered fallback to parent of Suspense (#35456) 2026-01-10 11:33:48 +01:00
lauren
d6cae440e3 [ci] Add size-balanced test sequencer for better shard distribution (#35458)
Jest's default test sequencer sorts alphabetically, causing large test
files
(eg ReactDOMFloat-test.js at 9k lines,
ReactHooksWithNoopRenderer-test.js at 4k
lines) to cluster in shard 3/5. This made shard 3/5 average 117s vs 77s
for
other shards, a 52% slowdown. I'm using filesize as a rough proxy for
number of tests.

This custom sequencer sorts tests by file size and distributes large
files evenly across all shards
instead of clustering them together.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35458).
* __->__ #35458
* #35459
2026-01-06 21:29:22 -05:00
lauren
00908be9ff [ci] Increase DevTools test shards and bump timeout (#35459)
[ci] Increase DevTools test shards and bump timeout

- Increase DevTools test shards from 3 to 5
- Bump timeout to 20s

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35459).
* #35458
* __->__ #35459
2026-01-06 21:23:05 -05:00
lauren
0e180141bf [ci] Separate DevTools test-build into dedicated job with fewer shards (#35457)
DevTools has ~45 test files which don't distribute well across 10
shards,
causing shard 3 to run 2x slower than others (104s vs ~50s). This moves
DevTools build tests to a separate job with 3 shards for better load
balancing.
2026-01-06 20:23:40 -05:00
Jon Jensen
65eec428c4 Use FormData submitter parameter (#29028) 2025-12-18 11:34:15 +01:00
Hendrik Liebau
454fc41fc7 [test] Add tests for cyclic arrays in Flight and Flight Reply (#35347)
We already had tests for cyclic objects, but not for cyclic arrays.
2025-12-17 18:08:16 +01:00
Sebastian Markbåge
f93b9fd44b Skip hydration errors when a view transition has been applied (#35380)
When the Fizz runtime runs a view-transition we apply
`view-transition-name` and `view-transition-class` to the `style`. These
can be observed by Fiber when hydrating which incorrectly leads to
hydration errors.

More over, even after we remove them, the `style` attribute has now been
normalized which we are unable to diff because we diff against the SSR
generated `style` attribute string and not the normalized form. So if
there are other inline styles defined, we have to skip diffing them in
this scenario.
2025-12-17 09:37:43 -05:00
Christian Van
b731fe28cc Improve cyclic thenable detection in ReactFlightReplyServer (#35369)
## Summary

This PR improves cyclic thenable detection in
`ReactFlightReplyServer.js`. Fixes #35368.
The previous fix only detected direct self-references (`inspectedValue
=== chunk`) and relied on the `cycleProtection` counter to eventually
bail out of longer cycles. This change keeps the existing
MAX_THENABLE_CYCLE_DEPTH ($1000$) `cycleProtection` cap as a hard
guardrail and adds a visited set so that we can detect self-cycles and
multi-node cycles as soon as any `ReactPromise` is revisited and while
still bounding the amount of work we do for deep acyclic chains via
`cycleProtection`.

## How did you test this change?

- Ran the existing test suite for the server renderer:

  ```bash
  yarn test react-server
  yarn test --prod react-server
  yarn flow dom-node
  yarn linc
  ```

---------

Co-authored-by: Hendrik Liebau <mail@hendrik-liebau.de>
2025-12-17 12:22:26 +01:00
Jack Pope
88ee1f5955 Add reporting modes for react-hooks/exhaustive-effect-dependencies and temporarily enable (#35365)
`react-hooks/exhaustive-effect-dependencies` from
`ValidateExhaustiveDeps` reports errors for both missing and extra
effect deps. We already have `react-hooks/exhaustive-deps` that errors
on missing dependencies. In the future we'd like to consolidate this all
to the compiler based error, but for now there's a lot of overlap. Let's
enable testing the extra dep warning by splitting out reporting modes.

This PR
- Creates `on`, `off`, `missing-only`, and `extra-only` reporting modes
for the effect dep validation flag
- Temporarily enables the new rule with `extra-only` in
`eslint-plugin-react-hooks`
- Adds additional null checking to `manualMemoLoc` to fix a bug found
when running against the fixture
2025-12-15 18:59:27 -05:00
emily8rown
bcf97c7564 Devtools disable log dimming strict mode setting (#35207)
<!--

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`).

-->

## Summary

Currently, every second console log is dimmed, receiving a special style
that indicates to user that it was raising because of [React Strict
Mode](https://react.dev/reference/react/StrictMode) second rendering.
This introduces a setting to disable this.

## How did you test this change?
Test in console-test.js


https://github.com/user-attachments/assets/af6663ac-f79b-4824-95c0-d46b0c8dec12

Browser extension react devtools


https://github.com/user-attachments/assets/7e2ecb7a-fbdf-4c72-ab45-7e3a1c6e5e44

React native dev tools:


https://github.com/user-attachments/assets/d875b3ac-1f27-43f8-8d9d-12b2d65fa6e6

---------

Co-authored-by: Ruslan Lesiutin <28902667+hoxyq@users.noreply.github.com>
2025-12-15 13:41:43 +00:00
Sebastian "Sebbie" Silbermann
ba5b843692 [test] Exclude repository root from assertions (#35361) 2025-12-15 11:45:17 +01:00
Jack Pope
b061b597f7 Upgrade nextjs for compiler playground (#35353)
Upgrading due to CVE-2025-55183 and CVE-2025-67779
2025-12-12 09:06:31 -05:00
Jorge Cabiedes
38a6f4e4a1 [compiler] Only run validations with env.logErrors on outputMode: 'lint' (#35216)
Summary:
These validations are not essential for compilation, with this we only
run that logic when outputMode is 'lint'

Test Plan:
Update fixtures and run tests
2025-12-11 16:36:36 -08:00
Nathan
b85cf6af3d [compiler] Fix VariableDeclarator source location (#35348)
Putting up https://github.com/facebook/react/pull/35129 again
Reverted in https://github.com/facebook/react/pull/35346 after breaking
main before security patch

This change impacts output formatting in a lot of snaps, so is very
sensitive to additions in main to the fixtures resulting in broken tests
after merging, so we should try merge quickly after rebasing or do a
fast follow to the merge with a snap update.
2025-12-11 18:02:05 -05:00
Sebastian Markbåge
b45bb335db [Flight] Add extra loop protection (#35351)
In case we get into loops.
2025-12-11 17:23:01 -05:00
Sebastian Markbåge
80cb7a9925 Revert "[compiler] Fix VariableDeclarator source location (#35129)" (#35346)
This broke main.
2025-12-11 15:27:07 -05:00
Sebastian Markbåge
894bc73cb4 [Flight] Patch Promise cycles and toString on Server Functions (#35345)
Server Functions can be stringified (sometimes implicitly) when passed
as data. This adds an override to hide the source code in that case -
just in case someone puts sensitive information in there.

Note that this still preserves the `name` field but this is also
available on the export but in practice is likely minified anyway.
There's nothing else on these referenes we'd consider unsafe unless you
explicitly expose expandos which are part of the `"use server"` export.

This adds a safety check to ensure you don't encode cyclic Promises.
This isn't a parser bug per se. Promises do have a safety mechanism that
avoids them infinite looping. However, since we use custom Thenables,
what can happen is that every time a native Promise awaits it, another
Promise wrapper is created around the Thenable which foils the
ECMAScript Promise cycle detection which can lead to an infinite loop.

This also ensures that embedded `ReadableStream` and `AsyncIterable`
streams are properly closed if the source stream closes early both on
the Server and Client. This doesn't cause an infinite loop but just to
make sure resource clean up can proceed properly.

We're also adding some more explicit clear errors for invalid payloads
since we no longer need to obfuscate the original issue.
2025-12-11 15:24:24 -05:00
Nathan
d3eb566291 [compiler] Fix VariableDeclarator source location (#35129)
### What
Fixes source locations for VariableDeclarator in the generated AST.
Fixes a number of the errors in the snapshot I added yesterday in the
source loc validator PR https://github.com/facebook/react/pull/35109

I'm not entirely sure why, but a side effect of the fix has resulted in
a ton of snaps needing updating, with some empty lines no longer present
in the generated output. I broke the change up into 2 separate commits.
The [first
commit](f4e4dc0f44)
has the core change and the update to the missing source locations test
expectation, and the [second
commit](cd4d9e944c)
has the rest of the snapshot updates.

### How
- Add location for variable declarators in ast codegen.
- We don't actually have the location preserved in HIR, since when we
lower the declarations we pass through the location for the
VariableDeclaration. Since VariableDeclarator is just a container for
each of the assignments, the start of the `id` and end of the `init` can
be used to accurately reconstruct it when generating the AST.
- Add source locations for object/array patterns for destructuring
assignment source location support
2025-12-11 14:35:03 -05:00
Ruslan Lesiutin
37bcdcde04 fix[devtools]: feature-check document with typeof instead of direct reference (#35343)
Follow-up to https://github.com/facebook/react/pull/35296.

We can get `ReferenceError` if this is unavailable. Using `typeof` check
instead for safety.
2025-12-11 12:15:00 +00:00
Ruslan Lesiutin
5a970933c0 fix[devtools]: feature-check structure stack trace methods (#35293)
`Error.prepareStackTrace` is non-standard feature and not all JavaScript
runtimes implement the methods that we are using in React DevTools
backend.

This PR adds additional checks for the presence of the methods that we
are using.
2025-12-10 19:21:54 +00:00
Ruslan Lesiutin
5d80124345 fix[devtools]: still show overlay, if getClientRects is not implemented (#35294)
Follow-up to https://github.com/facebook/react/pull/34653.

React Native doesn't implement `getClientRect`, since this is applicable
to CSS box, which is not a concept for Native (maybe yet).

I am loosening the condition that gates `showOverlay()` call to pass if
`getClientRect` is not implemented.

Conceptually, everything that is inside `react-devtools-shared/backend`
should be Host-agnostic, because both on Web and Native it is installed
inside the Host JavaScript runtime, be it main frame of the page, or RN
instance. Since overlay & highlighting logic also lives there, it should
also follow these principles.
2025-12-10 19:21:28 +00:00
Jack Pope
eade0d0fb7 Attach instance handle to DOM in DEV for enableInternalInstanceMap (#35341)
Continue attaching `internalInstanceKey` to DOM nodes in DEV. This
prevents breaking some internal dev tooling while we experiment with the
broader change. Note that this does not reference the DOM handle within
the flag, just attaches it and deletes it. Internals tracking is still
done through the private map.
2025-12-10 13:35:20 -05:00
emily8rown
d763f3131e [Devtools] Navigating commits performance panel hotkey (#35238)
## Summary
Add keyboard shortcuts (Cmd/Ctrl + Left/Right arrow keys) to navigate
between commits in the Profiler's snapshot view.

Moved `filteredCommitIndices` management and commit navigation logic
(`selectNextCommitIndex`, `selectPrevCommitIndex`) from
`SnapshotSelector` into `useCommitFilteringAndNavigation` used by
`ProfilerContext` to enable keyboard shortcuts from the top-level
Profiler component.

## How did you test this change?
- New tests in ProfilerContext-tests
- Built browser extension: `yarn build:<browser name>`
- tested in browser: `yarn run test:<browser name>`
- Manually verified Left/Right arrow navigation cycles through commits
- Verified navigation respects commit duration filter
- Verified reload-and-profile button unaffected

Chrome:


https://github.com/user-attachments/assets/01d2a749-13dc-4d08-8bcb-3d4d45a5f97c

Edge with duration filter:


https://github.com/user-attachments/assets/a7f76ff7-2a0b-4b9c-a0ce-d4449373308b

firefox mixing hotkey with clicking arrow buttons:


https://github.com/user-attachments/assets/48912d68-7c75-40f2-a203-5e6d7e6b2d99
2025-12-10 13:07:35 +00:00
lauren
734f1bf1ac [eprh] Enable enableUseKeyedState and enableVerboseNoSetStateInEffect (#35338)
Temporarily enables these 2 flags for internal testing.
2025-12-09 14:20:22 -05:00
dan
61331f3c9e Fix ViewTransition crash in Mobile Safari (#35337)
Speculative fix to https://github.com/facebook/react/issues/35336
written by Claude.

I have verified that applying a similar patch locally to the repro from
#35336 does fix the crash.

I'm not familiar enough with the underlying APIs to tell whether the fix
is correct or sufficient.
2025-12-10 03:35:15 +09:00
Sebastian "Sebbie" Silbermann
55480b4d22 [playground] Downgrade Next.js to a secure version (#35317)
Was bumped to a canary in https://github.com/facebook/react/pull/34499/
which got never released as stable.

Presumeably to use `Activity` which only made it into Activity in later
Next.js releases. However, `Activity` never ended up being used due to
incompatibilities with Monaco Editor. Downgrading should be safe.

Downgrading to fix
https://github.com/vercel/next.js/security/advisories/GHSA-9qr9-h5gf-34mp.
This will allow new deploys since Vercel is currently blocking new
deploys of unsafe version

---------

Co-authored-by: Eugene Choi <4eugenechoi@gmail.com>
2025-12-08 14:06:57 -05:00
lauren
3640f38a72 [compiler] Add enableVerboseNoSetStateInEffect to suggest options to user/agent (#35306)
The current `validateNoSetStateInEffects` error has potential false
positives because
we cannot fully statically detect patterns where calling setState in an
effect is
actually valid. This flag `enableVerboseNoSetStateInEffect` adds a
verbose error mode that presents multiple possible
use-cases, allowing an agent to reason about which fix is appropriate
before acting:

1. Non-local derived data - suggests restructuring state ownership
2. Derived event pattern - suggests requesting an event callback from
parent
3. Force update / external sync - suggests using `useSyncExternalStore`

This gives agents the context needed to make informed decisions rather
than
blindly applying a fix that may not be correct for the specific
situation.
2025-12-08 12:16:28 -05:00
Joseph Savona
ec9cc003d2 [compiler][poc] Reuse ValidateExhaustiveDeps for effect dep validation (#35285)
Alternative approach to #35282 for validating effect deps in the
compiler that builds on the machinery in ValidateExhaustiveDependencies.
Key changes to that pass:

* Refactor to track the dependencies of array expressions as temporaries
so we can look them up later if they appear as effect deps.
* Instead of not storing temporaries for LoadLocals of locally created
variables, we store the temporary but also propagate the local-ness
through. This allows us to record deps at the top level, necessary for
effect deps. Previously the pass was only ever concerned with tracking
deps within function expressions.
* Refactor the bulk of the dependency-checking logic from
`onFinishMemoize()` into a standalone helper to use it for the new
`onEffect()` helper as well.
* Add a new ErrorCategory for effect deps, use it for errors on
effects
* Put the effect dep validation behind a feature flag
* Adjust the error reason for effect errors

---------

Co-authored-by: Jack Pope <jackpope1@gmail.com>
2025-12-08 10:58:38 -05:00
Sebastian "Sebbie" Silbermann
380778d296 [test] Cleanup stack assertions in tests mixing React Server and Client (#35316) 2025-12-07 17:45:06 +01:00
Sebastian "Sebbie" Silbermann
41745339cd Run CI for backport releases (#35313) 2025-12-07 11:46:19 +01:00
Sebastian "Sebbie" Silbermann
c0b7c0d31f [scripts] Remove perf-counters (#35308) 2025-12-06 12:33:42 +01:00
Joseph Savona
2cb08e65b3 [compiler] Fix bug w functions depending on hoisted primitives (#35284)
Fixes an edge case where a function expression would fail to take a
dependency if it referenced a hoisted `const` inferred as a primitive
value. We were incorrectly skipping primitve-typed operands when
determing scopes for merging in InferReactiveScopeVariables.

This was super tricky to debug, for posterity the trick is that Context
variables (StoreContext etc) are modeled just like a mutable object,
where assignment to the variable is equivalent to `object.value = ...`
and reading the variable is equivalent to `object.value` property
access. Comparing to an equivalent version of the repro case replaced
with an object and property read/writes showed that everything was
exactly right, except that InferReactiveScopeVariables wasn't merging
the scopes of the function and the context variable, which led me right
to the problematic line.

Closes #35122
2025-12-05 14:29:06 -05:00
Ruslan Lesiutin
ad5971febd fix[devtools]: no-op unsupported backend bridge events (#35296)
Follow-up to https://github.com/facebook/react/pull/34641.
Similar to https://github.com/facebook/react/pull/35293,
https://github.com/facebook/react/pull/35294.

React DevTools backend can be used in non-DOM environments, so we have
to feature-check some DOM APIs.
For now I am just no-oping newly added commands for Native, we should
revisit this decision once we would roll out Suspense panel there, if
needed. I am not sure if scrolling will be required as much as it is
needed on Web.

`isReactNativeEnvironment()` check is kinda clowny, but we've been
relying on it for quite some time already.
2025-12-05 16:41:58 +00:00
Sebastian "Sebbie" Silbermann
378973b387 [Flight] Move react-server-dom-webpack/*.unbundled to private react-server-dom-unbundled (#35290)
Co-authored-by: Hendrik Liebau <mail@hendrik-liebau.de>
2025-12-05 03:59:21 +01:00
Sebastian Markbåge
3016ff87d8 [Flight] Never parse "then" functions (#35289)
AFAIK this is not needed to prevent any exploit but we don't really need
this. We allow functions on pretty much any other object anyway but
never on the "then" property since those would be serialized as Promises
by the client anyway.
2025-12-04 19:05:52 -05:00
lauren
f99241b2e6 [compiler] Add enableUseKeyedState flag and improve setState-in-render errors (#35230)
Adds a new `enableUseKeyedState` compiler flag that changes the error
message for unconditional setState calls during render.

When `enableUseKeyedState` is enabled, the error recommends using
`useKeyedState(initialState, key)` to reset state when dependencies
change. When disabled (the default), it links to the React docs for the
manual pattern of storing previous values in state.

Both error messages now include helpful bullet points explaining the two
main alternatives:
1. Use useKeyedState (or manual pattern) to reset state when other
state/props change
2. Compute derived data directly during render without using state
2025-12-04 18:29:10 -05:00
Kyℓe Hensel
66ae640b36 [eprh] fix react-compiler rules missing meta.docs.url property (#35258)
## Summary

To help people access the documentation easier, we can [add
`meta.docs.url`](https://eslint.org/docs/latest/extend/custom-rules#:~:text=Specifies%20the%20URL)
to the new react-compiler rules. This allows IDEs to make the rule name
a clickable link.

## How did you test this change?

`yarn test`, `yarn prettier`, `yarn lint` and in a separate project
[using file:// URLs](https://stackoverflow.com/a/38417065)
2025-12-04 15:28:13 -05:00
Felipe Cardozo
bf1afade8d [react-dom/server] Fix hanging on Deno (#35235) 2025-12-04 06:50:27 +01:00
Sebastian "Sebbie" Silbermann
0526c799d4 Update changelog with latest releases (#35279) 2025-12-03 18:13:43 +01:00
Sebastian Markbåge
7dc903cd29 Patch FlightReplyServer with fixes from ReactFlightClient (#35277)
FlightReplyServer are for client->server and ReactFlightClient is for
server->client. They're not 100% symmetrical.

We did a number of refactors to ReactFlightClient in PRs like #29823 and
#33664 to change the structure of the resolution. This PR brings those
changes to synchronize the two approaches. Which addresses deep
resolution of cycles and deferred error handling.

This also fixes a critical security vulnerability.
2025-12-03 10:41:19 -05:00
Sebastian "Sebbie" Silbermann
36df5e8b42 [release] Allow building single release channel with processed versions (#35270) 2025-12-02 22:05:10 +01:00
Jack Pope
09f05694a2 [compiler] Extend setState in effect validation to useEffectEvent (#35214)
ValidateNoSetStateInEffects already supports transitive setter
functions. This PR marks any synchonous state setter useEffectEvent
function so we can validate that uEE isn't being used only as
misdirection to avoid the validation within an effect body.

The error points to the call of the effect event.

Example:

```js
export default function MyApp() {
  const [count, setCount] = useState(0)
  const effectEvent = useEffectEvent(() => {
    setCount(10)
  })
  useEffect(() => {
    effectEvent()
  }, [])
  return <div>{count}</div>;
```

```
Found 1 error:

Error: Calling setState synchronously within an effect can trigger cascading renders

Effects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:
* Update external systems with the latest state from React.
* Subscribe for updates from some external system, calling setState in a callback function when external state changes.

Calling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect).

   5 |   })
   6 |   useEffect(() => {
>  7 |     effectEvent()
     |     ^^^^^^^^^^^ Avoid calling setState() directly within an effect
   8 |   }, [])
   9 |   return <div>{count}</div>;
  10 | }
```
2025-12-01 14:55:42 -05:00
Sebastian "Sebbie" Silbermann
0af4fd80ed [test] Update ESLint e2e tests (#35233) 2025-12-01 19:03:59 +01:00
Sebastian "Sebbie" Silbermann
1721e73e14 [test] Fix Error Proxy in Node.js 21+ (#35227) 2025-11-29 16:52:39 +01:00
Sebastian "Sebbie" Silbermann
6875c3eab4 [test] Only run tests overriding fallback and error states in supported versions (#35234) 2025-11-27 16:15:14 +01:00
Sebastian "Sebbie" Silbermann
74fa1667a7 [DevTools] Move "Back to full tree view" into Activity list item (#35164) 2025-11-26 10:42:18 +01:00
Joseph Savona
627b583650 [compiler][snap] Fix for filter mode with nested files, 'error.' prefix (#35215)
Fixes some issues i ran into w my recent snap changes:
* Correctly match against patterns that contain subdirectories, eg
`fbt/fbt-call`
* When checking if the input pattern has an extension, only prune known
supported extensions. Our convention of `error.<name>` for fixtures that
error makes the rest of the test name look like an extension to
`path.extname()`.

Tested with lots of different patterns including `error.` examples at
the top level and in nested directories, etc.
2025-11-25 15:39:07 -08:00
Joseph Savona
fb18ad3fd3 [compiler] Exhaustive deps: extra tests, improve diagnostic (#35213)
First, this adds some more tests and organizes them into an
`exhaustive-deps/` subdirectory.

Second, the diagnostics are overhauled. For each memo block we now
report a single diagnostic which summarizes the issue, plus individual
errors for each missing/extra dependency. Within the extra deps, we
distinguish whether it's truly extra vs whether its just a more (too)
precise version of an inferred dep. For example, if you depend on
`x.y.z` but the inferred dep was `x.y`. Finally, we print the full
inferred deps at the end as a hint (it's also a suggestion, but this
makes it more clear what would be suggested).
2025-11-25 12:09:09 -08:00
Joseph Savona
ddff35441a [compiler] Enable validateExhaustiveMemoizationDependencies by default (#35201)
Enables `@validateExhaustiveMemoizationDependencies` feature flag by
default, and disables it in select tests that failed due to the change.
Some of our tests intentionally use incorrect memo dependencies in order
to test edge cases.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35201).
* #35213
* __->__ #35201
2025-11-25 12:07:55 -08:00
Joseph Savona
d39a1d6b63 [compiler] Distingush optional/extraneous deps (#35204)
In ValidateExhaustiveDependencies, I previously changed to allow
extraneous dependencies as long as they were non-reactive. Here we make
that more precise, and distinguish between values that are definitely
referenced in the memo function but optional as dependencies vs values
that are not even referenced in the memo function. The latter now error
as extraneous even if they're non-reactive. This also turned up a case
where constant-folded primitives could show up as false positives of the
latter category, so now we track manual deps which quality for constant
folding and don't error on them.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35204).
* #35213
* #35201
* __->__ #35204
2025-11-25 12:06:25 -08:00
Joseph Savona
16e16ec6ff [compiler] Script to enable a feature by default and update tests (#35202)
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35202).
* #35201
* __->__ #35202
2025-11-24 12:21:35 -08:00
Joseph Savona
9599e7a787 [compiler] Adjustments to exhaustive deps messages, disable the lint rule (#35192)
Similar to ValidateHookUsage, we implement this check in the compiler
for safety but (for now) continue to rely on the existing rule for
actually reporting errors to users.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35192).
* #35201
* #35202
* __->__ #35192
2025-11-24 12:20:12 -08:00
Joseph Savona
67c1487ffd [compiler] Allow extraneous non-reactive locals (#35190)
The existing exhaustive-deps rule allows omitting non-reactive
dependencies, even if they're not memoized. Conceptually, if a value is
non-reactive then it cannot semantically change. Even if the value is a
new object, that object represents the exact same value and doesn't
necessitate redoing downstream computation. Thus its fine to exclude
nonreactive dependencies, whether they're a stable type or not.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35190).
* #35201
* #35202
* #35192
* __->__ #35190
2025-11-24 12:18:49 -08:00
Joseph Savona
454e01e603 [compiler] Allow manual dependencies to have different optionality than inferred deps (#35186)
Since adding this validation we've already changed our inference to use
knowledge from manual memoization to inform when values are frozen and
which values are non-nullable. To align with that, if the user chooses
to use different optionality btw the deps and the memo block/callback,
that's fine. The key is that eg `x?.y` will invalidate whenever `x.y`
would, so from a memoization correctness perspective its fine. It's not
our job to be a type checker: if a value is potentially nullable, it
should likely use a nullable property access in both places but
TypeScript/Flow can check that.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35186).
* #35201
* #35202
* #35192
* #35190
* __->__ #35186
2025-11-24 12:17:03 -08:00
Joseph Savona
c9a8cf3411 [compiler] Allow nonreactive stable types as extraneous deps (#35185)
When checking ValidateExhaustiveDeps internally, this seems to be the
most common case that it flags. The current exhaustive-deps rule allows
extraneous deps if they are a set of stable types. So here we reuse our
existing isStableType() util in the compiler to allow this case.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35185).
* #35201
* #35202
* #35192
* #35190
* #35186
* __->__ #35185
2025-11-24 12:15:06 -08:00
Joseph Savona
fca172e3f3 [compiler] Ignore ESLint suppressions when ValidateMemoDeps enabled (#35184)
With `ValidateExhaustiveMemoDependencies` we can now check exhaustive
dependencies for useMemo and useCallback within the compiler, without
relying on the separate exhaustive-deps rule. Until now we've bailed out
of any component/hook that suppresses this rule, since the suppression
_might_ affect a memoization value. Compiling code with incorrect memo
deps can change behavior so this wasn't safe. The downside was that a
suppression within a useEffect could prevent memoization, even though
non-exhaustive deps for effects do not cause problems for memoization
specifically.

So here, we change to ignore ESLint suppressions if we have both the
compiler's hooks validation and memo deps validations enabled.

Now we just have to test out the new validation and refine before we can
enable this by default.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35184).
* #35201
* #35202
* #35192
* #35190
* #35186
* #35185
* __->__ #35184
2025-11-24 12:12:49 -08:00
emily8rown
fd524fe02a [DevTools] hotkey to start/stop profiling (#35160)
## Summary

The built-in browser profiler supports starting/stopping with Cmd+E. For
Symmetry this adds the same hotkey for react devtools profiler.

## How did you test this change?
yarn build:\<browser name\> 
yarn run test:\<browser name\>

<img width="483" height="135" alt="Screenshot 2025-11-17 at 14 30 34"
src="https://github.com/user-attachments/assets/426939aa-15da-4c21-87a4-e949e6949482"
/>

firefox:

https://github.com/user-attachments/assets/6f225b90-828f-4e79-a364-59d6bc942f83

edge:

https://github.com/user-attachments/assets/5b2e9242-f0e8-481b-99a2-2dd78099f3ac

chrome:

https://github.com/user-attachments/assets/790aab02-2867-4499-aec1-e32e38c763f9

---------

Co-authored-by: Ruslan Lesiutin <28902667+hoxyq@users.noreply.github.com>
2025-11-21 11:37:10 -05:00
Joseph Savona
40b4a5bf71 [compiler] ValidateExhaustiveDeps disallows unnecessary non-reactive deps (#34472)
Just to be consistent, we disallow unnecessary deps even if they're
known to be non-reactive.
2025-11-20 19:30:35 -08:00
Joseph Savona
df75af4edc [compiler] Auto-fix for non-exhaustive deps (#34471)
Records more information in DropManualMemoization so that we know the
full span of the manual dependencies array (if present). This allows
ValidateExhaustiveDeps to include a suggestion with the correct deps.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34471).
* #34472
* __->__ #34471
2025-11-20 19:28:08 -08:00
Joseph Savona
bcc3fd8b05 [compiler] Implement exhaustive dependency checking for manual memoization (#34394)
The compiler currently drops manual memoization and rewrites it using
its own inference. If the existing manual memo dependencies has missing
or extra dependencies, compilation can change behavior by running the
computation more often (if deps were missing) or less often (if there
were extra deps). We currently address this by relying on the developer
to use the ESLint plugin and have `eslint-disable-next-line
react-hooks/exhaustive-deps` suppressions in their code. If a
suppression exists, we skip compilation.

But not everyone is using the linter! Relying on the linter is also
imprecise since it forces us to bail out on exhaustive-deps checks that
only effect (ahem) effects — and while it isn't good to have incorrect
deps on effects, it isn't a problem for compilation.

So this PR is a rough sketch of validating manual memoization
dependencies in the compiler. Long-term we could use this to also check
effect deps and replace the ExhaustiveDeps lint rule, but for now I'm
focused specifically on manual memoization use-cases. If this works, we
can stop bailing out on ESLint suppressions, since the compiler will
implement all the appropriate checks (we already check rules of hooks).

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34394).
* #34472
* #34471
* __->__ #34394
2025-11-20 19:26:26 -08:00
Joseph Savona
50e7ec8a69 [compiler] Deprecate noEmit, add outputMode (#35112)
This deprecates the `noEmit: boolean` flag and adds `outputMode:
'client' | 'client-no-memo' | 'ssr' | 'lint'` as the replacement.
OutputMode defaults to null and takes precedence if specified, otherwise
we use 'client' mode for noEmit=false and 'lint' mode for noEmit=true.

Key points:
* Retrying failed compilation switches from 'client' mode to
'client-no-memo'
* Validations are enabled behind
Environment.proto.shouldEnableValidations, enabled for all modes except
'client-no-memo'. Similar for dropping manual memoization.
* OptimizeSSR is now gated by the outputMode==='ssr', not a feature flag
* Creation of reactive scopes, and related codegen logic, is now gated
by outputMode==='client'
2025-11-20 15:12:40 -08:00
Joseph Savona
4cf770d7e1 [compiler][poc] Quick experiment with SSR-optimization pass (#35102)
Just a quick poc:
* Inline useState when the initializer is known to not be a function.
The heuristic could be improved but will handle a large number of cases
already.
* Prune effects
* Prune useRef if the ref is unused, by pruning 'ref' props on primitive
components. Then DCE does the rest of the work - with a small change to
allow `useRef()` calls to be dropped since function calls aren't
normally eligible for dropping.
* Prune event handlers, by pruning props whose names start w "on" from
primitive components. Then DCE removes the functions themselves.

Per the fixture, this gets pretty far.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35102).
* #35112
* __->__ #35102
2025-11-20 15:02:38 -08:00
Jorge Cabiedes
7d67591041 [compiler] Remove useState argument constraint. no-derived-computations-in-effects (#35174)
Summary:
I missed this conditional messing things up for undefined useState()
calls. We should be tracking them.

I also missed a test that expect an error was not throwing.

Test Plan:
Update broken test

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35174).
* __->__ #35174
* #35173
2025-11-20 10:45:17 -08:00
Jorge Cabiedes
7ee974de92 [compiler] Prevent innaccurate derivation recording on FunctionExpressions on no-derived-computation-in-effects (#35173)
Summary:
The operands of a function expression are the elements passed as
context. This means that it doesn't make sense to record mutations for
them.

The relevant mutations will happen in the function body, so we need to
prevent FunctionExpression type instruction from running the logic for
effect mutations.

This was also causing some values to depend on themselves in some cases
triggering an infinite loop. Also added n invariant to prevent this
issue

Test Plan:
Added fixture test

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35173).
* #35174
* __->__ #35173
2025-11-20 10:44:45 -08:00
Sebastian "Sebbie" Silbermann
8ac5f4eb36 Fix form status reset when component state is updated (#34075)
Co-authored-by: Vordgi <sasha2822222@gmail.com>
2025-11-19 18:22:07 +01:00
Sebastian Markbåge
eb89912ee5 Add expertimental optimisticKey behind a flag (#35162)
When dealing with optimistic state, a common problem is not knowing the
id of the thing we're waiting on. Items in lists need keys (and single
items should often have keys too to reset their state). As a result you
have to generate fake keys. It's a pain to manage those and when the
real item comes in, you often end up rendering that with a different
`key` which resets the state of the component tree. That in turns works
against the grain of React and a lot of negatives fall out of it.

This adds a special `optimisticKey` symbol that can be used in place of
a `string` key.

```js
import {optimisticKey} from 'react';
...
const [optimisticItems, setOptimisticItems] = useOptimistic([]);
const children = savedItems.concat(
  optimisticItems.map(item =>
    <Item key={optimisticKey} item={item} />
  )
);
return <div>{children}</div>;
```

The semantics of this `optimisticKey` is that the assumption is that the
newly saved item will be rendered in the same slot as the previous
optimistic items. State is transferred into whatever real key ends up in
the same slot.

This might lead to some incorrect transferring of state in some cases
where things don't end up lining up - but it's worth it for simplicity
in many cases since dealing with true matching of optimistic state is
often very complex for something that only lasts a blink of an eye.

If a new item matches a `key` elsewhere in the set, then that's favored
over reconciling against the old slot.

One quirk with the current algorithm is if the `savedItems` has items
removed, then the slots won't line up by index anymore and will be
skewed. We might be able to add something where the optimistic set is
always reconciled against the end. However, it's probably better to just
assume that the set will line up perfectly and otherwise it's just best
effort that can lead to weird artifacts.

An `optimisticKey` will match itself for updates to the same slot, but
it will not match any existing slot that is not an `optimisticKey`. So
it's not an `any`, which I originally called it, because it doesn't
match existing real keys against new optimistic keys. Only one
direction.
2025-11-18 16:29:18 -05:00
Ricky
0972e23908 [compiler] Consider setter from useOptimistic non-reactive (#35141)
Closes https://github.com/facebook/react/issues/35138
2025-11-18 10:50:43 -05:00
Sebastian "Sebbie" Silbermann
194c12d949 [DevTools] Name root "Transition" when focusing on Activity (#35108) 2025-11-18 10:16:58 +01:00
Sebastian "Sebbie" Silbermann
7f1a085b28 [DevTools] Show list of named Activities in Suspense tab (#35092) 2025-11-18 09:52:44 +01:00
Joseph Savona
ea4899e13f [compiler][snap] Support pattern of files to test as CLI argument (#35148)
I've been trying out LLM agents for compiler development, and one thing
i found is that the agent naturally wants to run `yarn snap <pattern>`
to test a specific fixture, and I want to be able to tell it (directly
or in rules/skills) to do this in order to get the debug output from all
the compiler passes. Agents can figure out our current testfilter.txt
file system but that's just tedious. So here we add support for `yarn
snap -p <pattern>`. If you pass in a pattern with an extension, we
target that extension specifically. If you pass in a .expect.md file, we
look at that specific fixture. And if the pattern doesn't have
extensions, we search for `<pattern>{.js,.jsx,.ts,.tsx}`. When patterns
are enabled we automatically log as in debug mode (if there is a single
match), and disable watch mode.

Open to feedback!
2025-11-17 12:09:09 -08:00
Joseph Savona
b946a249b5 [compiler] Improve setState-in-effects rule to account for ref-gated conditionals (#35147)
Conditionally calling setState in an effect is sometimes necessary, but
should generally follow the pattern of using a "previous vaue" ref to
manually compare and ensure that the setState is idempotent. See fixture
for an example.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35147).
* #35148
* __->__ #35147
2025-11-17 12:07:43 -08:00
Joseph Savona
d6b1a0573b [compiler] Extract reusable logic for control dominators (#35146)
The next PR needs to check if a block is controlled by a value derived
from a ref.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35146).
* #35148
* #35147
* __->__ #35146
2025-11-17 12:05:52 -08:00
Joseph Savona
b315a0f713 [compiler] Fix for destructuring with mixed declaration/reassignment (#35144)
Destructing statements that start off as declarations can end up
becoming reassignments if the variable is a scope declaration, so we
have existing logic to handle cases where some parts of a destructure
need to be converted into new locals, with a reassignment to the hoisted
scope variable afterwards. However, there is an edge case where all of
the values are reassigned, in which case we don't need to rewrite and
can just set the instruction kind to reassign.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35144).
* #35148
* #35147
* #35146
* __->__ #35144
2025-11-17 11:34:49 -08:00
Sebastian "Sebbie" Silbermann
7df96b0c1a [Flight] Complete list of Node.js' internal Promise awaits (#35161) 2025-11-17 19:28:26 +01:00
Sebastian "Sebbie" Silbermann
45bc3c9f04 [Flight] Reduce risk of maximum call stack exceeded when emitting async sequence (#35159) 2025-11-17 18:54:13 +01:00
Hendrik Liebau
fb2177c153 [Flight] Fix pending chunks count for streams & async iterables in DEV (#35143)
In DEV, we need to prevent the response from being GC'd while there are
still pending chunks for ReadableSteams or pending results for
AsyncIterables.

Co-authored-by: Sebastian "Sebbie" Silbermann <silbermann.sebastian@gmail.com>
2025-11-14 23:52:11 +01:00
Joseph Savona
647e13366c [compiler] fix bad rebase from sapling (#35145)
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35145).
* #35144
* __->__ #35145
2025-11-14 14:50:38 -08:00
Joseph Savona
19b769fa5f [compiler] Fix for inferring props-derived-value as mutable (#35140)
Fix for the repro from the previous PR. A `Capture x -> y` effect should
downgrade to `ImmutableCapture` when the source value is maybe-frozen.
MaybeFrozen represents the union of a frozen value with a non-frozen
value.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35140).
* __->__ #35140
* #35139
2025-11-14 12:14:34 -08:00
Joseph Savona
dbf2538355 [compiler] Repro for false positive mutation of a value derived from props (#35139)
Repro from the compiler WG (Thanks Cody!) of a case where the compiler
incorrectly thinks a value is mutable.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35139).
* #35140
* __->__ #35139
2025-11-14 12:14:23 -08:00
Eliot Pontarelli
21f282425c [compiler] Allow ref access in callbacks passed to event handler props (#35062)
## Summary

Fixes #35040. The React compiler incorrectly flags ref access within
event handlers as ref access at render time. For example, this code
would fail to compile with error "Cannot access refs during render":

```tsx
  const onSubmit = async (data) => {
    const file = ref.current?.toFile(); // Incorrectly flagged as error
  };

  <form onSubmit={handleSubmit(onSubmit)}>
```
This is a false positive because any built-in DOM event handler is
guaranteed not to run at render time. This PR only supports built-in
event handlers because there are no guarantees that user-made event
handlers will not run at render time.

## How did you test this change?

I created 4 test fixtures which validate this change:
* allow-ref-access-in-event-handler-wrapper.tsx - Sync handler test
input
* allow-ref-access-in-event-handler-wrapper.expect.md - Sync handler
expected output
* allow-ref-access-in-async-event-handler-wrapper.tsx - Async handler
test input
* allow-ref-access-in-async-event-handler-wrapper.expect.md - Async
handler expected output

All linters and test suites also pass.
2025-11-14 09:00:33 -08:00
Jorge Cabiedes
257b033fc7 [Compiler] Avoid capturing global setStates for no-derived-computations lint (#35135)
Summary:
This only matters when enableTreatSetIdentifiersAsStateSetters=true

This pattern is still bad. But Right now the validation can only
recommend to move stuff to "calculate in render"

A global setState should not be moved to render, not even conditionally
and you can't remove state without crossing Component boundaries, which
makes this a different kind of fix.

So while we are only suggesting "calculate in render" as a fix we should
disallow the lint from throwing in this case IMO

Test Plan:
Added a fixture

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35135).
* __->__ #35135
* #35134
2025-11-13 22:56:06 -08:00
Jorge Cabiedes
de97ef9ad5 [Compiler] Don't count a setState in the dependency array of the effect it is called on as a usage (#35134)
Summary:
The validation only allows setState declaration as a usage outside of
the effect.

Another edge case is that if you add the setState being validated in the
dependency array you also make the validation opt out since it counts as
a usage outside of the effect.

Added a bit of logic to consider the effect's deps when creating the
cache for setState usages within the effect

Test Plan:
Added a fixture

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35134).
* #35135
* __->__ #35134
2025-11-13 22:52:23 -08:00
Hendrik Liebau
93fc57400b [Flight] Fix broken byte stream parsing caused by buffer detachment (#35127)
This PR fixes a critical bug where `ReadableStream({type: 'bytes'})`
instances passed through React Server Components (RSC) would stall after
reading only the first chunk or the first few chunks in the client. This
issue was masked by using `web-streams-polyfill` in tests, but manifests
with native Web Streams implementations.

The root cause is that when a chunk is enqueued to a
`ReadableByteStreamController`, the spec requires the underlying
ArrayBuffer to be synchronously transferred/detached. In the React
Flight Client's chunk parsing, embedded byte stream chunks are created
as views into the incoming RSC stream chunk buffer using `new
Uint8Array(chunk.buffer, offset, length)`. When embedded byte stream
chunks are enqueued, they can detach the shared buffer, leaving the RSC
stream parsing in a broken state.

The fix is to copy embedded byte stream chunks before enqueueing them,
preventing buffer detachment from affecting subsequent parsing. To not
affect performance too much, we use a zero-copy optimization: when a
chunk ends exactly at the end of the RSC stream chunk, or when the row
spans into the next RSC chunk, no further parsing will access that
buffer, so we can safely enqueue the view directly without copying.

We now also enqueue embedded byte stream chunks immediately as they are
parsed, without waiting for the full row to complete.

To simplify the logic in the client, we introduce a new `'b'` protocol
tag specifically for byte stream chunks. The server now emits `'b'`
instead of `'o'` for `Uint8Array` chunks from byte streams (detected via
`supportsBYOB`). This allows the client to recognize byte stream chunks
without needing to track stream IDs.

Tests now use the proper Jest environment with native Web Streams
instead of polyfills, exposing and validating the fix for this issue.
2025-11-13 21:23:02 +01:00
Sebastian "Sebbie" Silbermann
093b3246e1 [react-dom] Batch updates from resize until next frame (#35117) 2025-11-13 13:30:21 +01:00
Nathan
3a495ae722 [compiler] source location validator (#35109)
@josephsavona this was briefly discussed in an old thread, lmk your
thoughts on the approach. I have some fixes ready as well but wanted to
get this test case in first... there's some things I don't _love_ about
this approach, but end of the day it's just a tool for the test suite
rather than something for end user folks so even if it does a 70% good
enough job that's fine.

### refresher on the problem
when we generate coverage reports with jest (istanbul), our coverage
ends up completely out of whack due to the AST missing a ton of (let's
call them "important") source locations after the compiler pipeline has
run.

At the moment to get around this, we've been doing something a bit
unorthodox and also running our test suite with istanbul running before
the compiler -- which results in its own set of issues (for eg, things
being memoized differently, or the compiler completely bailing out on
the instrumented code, etc).

before getting in fixes, I wanted to set up a test case to start
chipping away on as you had recommended.

### how it works

The validator basically:
1. Traverses the original AST and collects the source locations for some
"important" node types
- (excludes useMemo/useCallback calls, as those are stripped out by the
compiler)
3. Traverses the generated AST and looks for nodes with matching source
locations.
4. Generates errors for source locations missing nodes in the generated
AST

### caveats/drawbacks

There are some things that don't work super well with this approach. A
more natural test fit I think would be just having some explicit
assertions made against an AST in a test file, as you can just bake all
of the assumptions/nuance in there that are difficult to handle in a
generic manner. However, this is maybe "good enough" for now.

1. Have to be careful what you put into the test fixture. If you put in
some code that the compiler just removes (for eg, a variable assignment
that is unused), you're creating a failure case that's impossible to
fix. I added a skip for useMemo/useCallback.
2. "Important" locations must exactly match for validation to pass.
- Might get tricky making sure things are mapped correctly when a node
type is completely changed, for eg, when a block statement arrow
function body gets turned into an implicit return via the body just
being an expression/identifier.
- This can/could result in scenarios where more changes are needed to
shuttle the locations through due to HIR not having a 1:1 mapping all
the babel nuances, even if some combination of other data might be good
enough even if not 10000% accurate. This might be the _right_ thing
anyways so we don't end up with edge cases having incorrect source
locations.
2025-11-12 19:02:46 -08:00
Ricky
bbe3f4d322 [flags] disableLegacyMode in native-fb (#35120)
this is failing test too because we need the legacy mode in the react
package until we fix the tests
2025-11-12 15:38:58 -05:00
Sebastian "Sebbie" Silbermann
1ea46df8ba [DevTools] Batch updates when updating component filters (#35093) 2025-11-11 23:20:22 +01:00
Sebastian "Sebbie" Silbermann
8c15edd57c [DevTools] Send root unmount as a regular removal operation (#35107) 2025-11-11 23:08:54 +01:00
Jorge Cabiedes
5e94655cbb [compiler] _exp version of ValidateNoDerivedComputationsInEffects take precedence over stable version when enabled (#35099)
Summary:
We should only run one version of the validation. I think it makes sense
that if the exp version is enable it takes precedence over the stable
one

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35099).
* __->__ #35099
* #35100
2025-11-11 10:16:20 -08:00
Jorge Cabiedes
db8273c12f [compiler] Update test snap to include fixture comment (#35100)
Summary:
I missed this test case failing and now having @loggerTestOnly after
landing some other PRs good to know they're not land blocking

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35100).
* #35099
* __->__ #35100
2025-11-11 10:16:04 -08:00
Ricky
04ee54cd12 [tests] add more portal activity tests (#35095)
I copied some tests from
[`Activity-test.js`](1d68bce19c/packages/react-reconciler/src/__tests__/Activity-test.js)
and made them portal specific just to confirm my understanding of how
Portals + Activity interact is correct. Seems good to include them.
2025-11-11 12:47:56 -05:00
Jorge Cabiedes
100fc4a8cf [compiler] Prevent local state source variables from depending on other state (#35044)
Summary:
When a local state is created sometimes it uses a `prop` or even other
local state for its initial value.

This value is only relevant on first render so we shouldn't consider it
part of our data flow

Test Plan:
Added tests
2025-11-10 12:29:34 -08:00
Jorge Cabiedes
92ac4e8b80 [compiler] Don't validate when effect cleanup function depends on effect localized setState state derived values (#35020)
Summary:
If we are using a clean up function in an effect and that clean up
function depends on a value that is used to set the state we are
validating for we shouldn't throw an error since it is a valid use case
for an effect.

Test Plan:
added test

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35020).
* #35044
* __->__ #35020
2025-11-10 12:28:19 -08:00
Jorge Cabiedes
f76c3617e0 [compiler] Switch to track setStates by aliasing and id instead of identifier names (#34973)
Summary:
This makes the setState usage logic much more robust. We no longer rely
on identifierName.

Now we track when a setState is loaded into a new promoted identifier
variable and track this in a map `setStateLoaded` map.

For other types of instructions we consider the setState to be being
used. In this case we record its usage into the `setStateUsages` map.



Test Plan:
We expect no changes in behavior for the current tests

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34973).
* #35044
* #35020
* __->__ #34973
* #34972
2025-11-10 12:16:27 -08:00
Jorge Cabiedes
7296120396 [compiler] Update ValidateNoDerivedComputationsInEffects_exp to log the error instead of throwing (#34972)
Summary:
TSIA

Simple change to log errors in Pipeline.ts instead of throwing in the
validation

Test Plan:
updated snap tests

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34972).
* #35044
* #35020
* #34973
* __->__ #34972
2025-11-10 12:16:13 -08:00
Jorge Cabiedes
6347c6d373 [compiler] Fix false negatives and add data flow tree to compiler error for no-deriving-state-in-effects (#34995)
Summary:
Revamped the derivationCache graph.

This fixes a bunch of bugs where sometimes we fail to track from which
props/state we derived values from.

Also, it is more intuitive and allows us to easily implement a Data Flow
Tree.

We can print this tree which gives insight on how the data is derived
and should facilitate error resolution in complicated components

Test Plan:
Added a test case where we were failing to track derivations. Also
updated the test cases with the new error containing the data flow tree

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34995).
* #35044
* #35020
* #34973
* #34972
* __->__ #34995
* #34967
2025-11-10 12:09:13 -08:00
Jorge Cabiedes
01fb328632 [compiler] Prevent overriding a derivationEntry on effect mutation and instead update typeOfValue and fix infinite loops (#34967)
Summary:
With this we are now comparing a snapshot of the derivationCache with
the new changes every time we are done recording the derivations
happening in the HIR.

We have to do this after recording everything since we still do some
mutations on the cache when recording mutations.



Test Plan:
Test the following in playground:
```
// @validateNoDerivedComputationsInEffects_exp

function Component({ value }) {
  const [checked, setChecked] = useState('');

  useEffect(() => {
    setChecked(value === '' ? [] : value.split(','));
  }, [value]);

  return (
    <div>{checked}</div>
  )
}
```

This no longer causes an infinite loop.

Added a test case in the next PR in the stack

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34967).
* #35044
* #35020
* #34973
* #34972
* #34995
* __->__ #34967
2025-11-10 12:08:05 -08:00
Sebastian "Sebbie" Silbermann
ce4054ebdd [DevTools] Measure when reconnecting Suspense (#35098) 2025-11-10 20:55:31 +01:00
Sebastian "Sebbie" Silbermann
21c1d51acb [DevTools] Don't attempt to draw bounding box if inspected element is not a Suspense (#35097) 2025-11-10 20:01:59 +01:00
Facebook Community Bot
be48396dbd Remove Dead Code in WWW JS
Differential Revision: D86593830

Pull Request resolved: https://github.com/facebook/react/pull/35085
2025-11-10 16:34:01 +00:00
Andrew Clark
5268492536 Fix: Activity should hide portal contents (#35091)
This PR updates the behavior of Activity so that when it is hidden, it
hides the contents of any portals contained within it.

Previously we had intentionally chosen not to implement this behavior,
because it was thought that this concern should be left to the userspace
code that manages the portal, e.g. by adding or removing the portal
container from the DOM. Depending on the use case for the portal, this
is often desirable anyway because the portal container itself is not
controlled by React.

However, React does own the _contents_ of the portal, and we can hide
those elements regardless of what the user chooses to do with the
container. This makes the hiding/unhiding behavior of portals with
Activity automatic in the majority of cases, and also benefits from
aligning the DOM mutations with the rest of the React's commit phase
lifecycle.

The reason we have to special case this at all is because usually we
only hide the direct DOM children of the Activity boundary. There's no
reason to go deeper than that, because hiding a parent DOM element
effectively hides everything inside of it. Portals are the exception,
because they don't exist in the normal DOM hierarchy; we can't assume
that just because a portal has a parent in the React tree that it will
also have that parent in the actual DOM.

So, whenever an Activity boundary is hidden, we must search for and hide
_any_ portal that is contained within it, and recursively hide its
direct children, too.

To optimize this search, we use a new subtree flag, PortalStatic, that
is set only on fiber paths that contain a HostPortal. This lets us skip
over any subtree that does not contain a portal.
2025-11-10 10:42:26 -05:00
Sebastian Markbåge
c83be7da9f [Fizz] Simplify createSuspenseBoundary path (#35087)
Small follow up to #35068.

Since this is now a single argument we can simplify the creation
branching a bit and make sure it's const.
2025-11-09 15:19:43 -05:00
Sebastian Markbåge
6362b5c711 [DevTools] Special case the selected root outline (#35071)
When I moved the outline to above all other rects, I thought it was
clever to unify with the root so that the outline was also used for the
root selection. But the root outline is not drawn like the other rects.
It's outside the padding and doesn't have the 1px adjustment which leads
the overlay to be slightly inside the other rect instead of above it.

This goes back to just having the selected root be drawn by the root
element.

Before:

<img width="652" height="253" alt="Screenshot 2025-11-07 at 11 39 28 AM"
src="https://github.com/user-attachments/assets/334237d1-f190-4995-94cc-9690ec0f7ce1"
/>

After:

<img width="674" height="220" alt="Screenshot 2025-11-07 at 11 44 01 AM"
src="https://github.com/user-attachments/assets/afaa86d8-942a-44d8-a1a5-67c7fb642c0d"
/>
2025-11-09 15:03:31 -05:00
Sebastian "Sebbie" Silbermann
5a9921b839 [DevTools] Apply Activity slice filter when double clicking Activity (#34908) 2025-11-08 18:09:44 +01:00
Andrew Clark
717e70843e Fix: Errors should not escape a hidden Activity (#35074)
If an error is thrown inside a hidden Activity, it should not escape
into the visible part of the UI. Conceptually, a hidden Activity
boundary is not part of the current UI; it's the same as an unmounted
tree, except for the fact that the state will be restored if it's later
revealed.

Fixes:
- https://github.com/facebook/react/issues/35073
2025-11-07 18:18:24 -05:00
Stian Jensen
a10ff9c857 Upgrade devtools dependency update-notifier to 5.x (#31655)
## Summary

This PR upgrades the dependency on update-notifier, used in
react-devtools, to 5.x
This is the latest non-ESM version, so upgrading to it should be
unproblematic (while updating to 6.x and beyond will have to wait).

Upgrading means we avoid installing a lot of outdated dependencies (as
can be seen from the diff in yarn.lock), and resolves part of
https://github.com/facebook/react/issues/28058

Changelog:
https://github.com/yeoman/update-notifier/releases

The most relevant breaking change seems to be that the minimum support
node version is increased from v6 to v10, but I couldn't find what is
currently React's official node version support.

## How did you test this change?

I ran the test-suite locally (`yarn test` in root folder), but I'm not
sure if that one actually covers devtools?

I also built and tested this version of devtools with some internal
company projects (both react and react-native based) – following
guidelines from
https://github.com/facebook/react/issues/28058#issuecomment-1943619292.
2025-11-07 18:43:42 +00:00
Sebastian Markbåge
fa50caf5f8 [Fizz] Unify preamble only fields to save a field (#35068)
Stacked on #35067.

Same idea of saving a field on the SuspenseBoundary in the common case.
The case where they can have a preamble is rare.
2025-11-07 09:19:19 -05:00
Sebastian Markbåge
1e986f514f [Fizz] Unify prerender only fields to save a field (#35067)
I need to regain a field because the SuspenseBoundary type is already at
16 fields in prod, after which it deopts v8.

There are two fields that are only used in prerender to track postpones.
These are ripe to be split into an optional object so that they only
take up one field when they're not used.
2025-11-07 09:18:28 -05:00
Sebastian Markbåge
38bdda1ca6 Don't skip content in visible offscreen trees for Gesture View Transitions (#35066)
Follow up to #35063.

I forgot there's another variant of this in the ApplyGesture path.
2025-11-06 20:59:08 -05:00
Jack Pope
a44e750e87 Store instance handles in an internal map behind flag (#35053)
We already append `randomKey` to each handle name to prevent external
libraries from accessing and relying on these internals. But more
libraries recently have been getting around this by simply iterating
over the element properties and using a `startsWith` check.

This flag allows us to experiment with moving these handles to an
internal map.

This PR starts with the two most common internals, the props object and
the fiber. We can consider moving additional properties such as the
container root and others depending on perf results.
2025-11-06 18:17:53 -05:00
Sebastian Markbåge
37b089a59c Don't skip content in visible offscreen trees for View Transitions (#35063)
Also, don't not skip hidden trees.

Memoized state is null when an Offscreen boundary (Suspense or Activity)
is visible.

This logic was inversed in a couple of View Transition checks which
caused pairs to be discovered or not discovered incorrectly for
insertion and deletion of Suspense or Activity boundaries.
2025-11-06 16:03:02 -05:00
Sebastian Markbåge
1a31a814f1 Escape View Transition Name Strings as base64 (#35060)
This is an alternative to #35059.

If the name needs escaping, then instead of escaping it, we just use a
base64 name. This wouldn't allow you to match on an escaped name in your
own CSS like you should be able to if browsers worked properly. But at
least it would provide matching name in current browsers which is
probably sufficient if you're using auto-generated names.

This also covers some cases where `CSS.escape()` isn't sufficient anyway
like when the name ends in a dot.
2025-11-06 16:02:06 -05:00
Alexander Kachkaev
5a2205ba28 Update bug report template for eslint plugin label (#34959)
## Summary

When creating https://github.com/facebook/react/issues/34957, I noticed
a reference to `eslint-plugin-react-compiler` instead of
`eslint-plugin-react-hooks`. Since the former is merged into the latter
(https://github.com/facebook/react/pull/32416,
https://github.com/facebook/react/pull/34228), I have decided to update
the issue template to avoid confusion.
2025-11-05 16:57:26 -05:00
Sebastian Markbåge
fa767dade6 Remove unstable_expectedLoadTime option (#35051)
Follow up to #35022.

It's now replaced by the `defer` option.

Sounds like nobody is actually using this option, including Meta, so we
can just delete it.
2025-11-05 15:52:21 -05:00
Sebastian Markbåge
0ba2f01f74 Rename <Suspense unstable_expectedLoadTime> to <Suspense defer> and implement in SSR (#35022)
We've long had the CPU suspense feature behind a flag under the terrible
API `unstable_expectedLoadTime={arbitraryNumber}`. We've known for a
long time we want it to just be `defer={true}` (or just `<Suspense
defer>` in the short hand syntax). So this adds the new name and warns
for the old name.

For only the new name, I also implemented SSR semantics in Fizz. It has
two effects here.
1) It renders the fallback before the content (similar to prerender)
allowing siblings to complete quicker.
2) It always outlines the result. When streaming this should really
happen naturally but if you defer a prerendered content it also implies
that it's expensive and should be outlined. It gives you a opt-in to
outlining similar to suspensey images and css but let you control it
manually.
2025-11-05 14:12:09 -05:00
Sebastian Markbåge
dd048c3b2d Clean up enablePostpone Experiment (#35048)
We're not shipping this and it's a lot of code to maintain that is
blocking my refactor of Fizz for SuspenseList.
2025-11-05 00:05:59 -05:00
Sebastian Markbåge
c308cb5905 Disable enablePostpone flag in experimental (#31042)
I don't think we're ready to land this yet since we're using it to run
other experiments and our tests. I'm opening this PR to indicate intent
to disable and to ensure tests in other combinations still work. Such as
enableHalt without enablePostpone. I think we'll also need to rewrite
some tests that depend on enablePostpone to preserve some coverage.

The conclusion after this experiment is that try/catch around these are
too likely to block these signals and consider them error. Throwing
works for Hooks and `use()` because the lint rule can ensure that
they're not wrapped in try/catch. Throwing in arbitrary functions not
quite ecosystem compatible. It's also why there's `use()` and not just
throwing a Promise. This might also affect the Catch proposal.

The "prerender" for SSR that's supporting "Partial Prerendering" is
still there. This just disables the `React.postpone()` API for creating
the holes.
2025-11-04 23:23:25 -05:00
Sebastian Markbåge
986323f8c6 [Fiber] SuspenseList with "hidden" tail row should "catch" suspense (#35042)
Normally if you suspend in a SuspenseList row above a Suspense boundary
in that row, it'll suspend the parent. Which can itself delay the commit
or resuspend a parent boundary. That's because SuspenseList mostly just
coordinates the state of the inner boundaries and isn't a boundary
itself.

However, for tail "hidden" and "collapsed" this is not quite the case
because the rows themselves can avoid being rendered.

In the case of "collapsed" we require at least one Suspense boundary
above to have successfully rendered before committing the list because
the idea of this mode is that you should at least always show some
indicator that things are still loading. Since we'd never try the next
one after that at all, this just works. Expect there was an unrelated
bug that meant that "suspend with delay" on a Retry didn't suspend the
commit. This caused a scenario were it'd allow a commit proceed when it
shouldn't. So I fixed that too. The counter intuitive thing here is that
we won't actually show a previous completed row if the loading state of
the next row is still loading.

For tail "hidden" it's a little different because we don't actually
require any loading indicator at all to be shown while it's loading. If
we attempt a row and it suspends, we can just hide it (and the rest) and
move to commit. Therefore this implements a path where if all the rest
of the tail are new mounts (we wouldn't be required to unmount any
existing boundaries) then we can treat the SuspenseList boundary itself
as "catching" the suspense. This is more coherent semantics since any
future row that we didn't attempt also wouldn't resuspend the parent.

This allows simple cases like `<SuspenseList>{list}</SuspenseList>` to
stream in each row without any indicator and no need for Suspense
boundaries.
2025-11-04 22:11:33 -05:00
Jordan Brown
8f8b336734 [eslint] Fix useEffectEvent checks in component syntax (#35041)
We were not recording uEE calls in component/hook syntax. Easy fix.

Added tests matching function component syntax for component syntax +
added one for hooks
2025-11-04 14:59:29 -05:00
Alex Hunt
d000261eef [Tracks] Annotate devtools.performanceIssue for Cascading Updates in DEV (#34961) 2025-11-04 17:07:31 +00:00
Hendrik Liebau
f646e8ffd8 [Flight] Fix hasReadable flag in Node.js clients' debug channel (#35039)
For Edge Flight servers, that use Web Streams, we're defining the
`debugChannel` option as:

```
debugChannel?: {readable?: ReadableStream, writable?: WritableStream, ...}
```

Whereas for Node.js Flight servers, that use Node.js Streams, we're
defining it as:

```
debugChannel?: Readable | Writable | Duplex | WebSocket
```

For the Edge Flight clients, there is currently only one direction of
the debug channel supported, so we define the option as:

```
debugChannel?: {readable?: ReadableStream, ...}
```

Consequently, for the Node.js Flight clients, we define the option as:

```
debugChannel?: Readable
```

The presence of a readable debug channel is passed to the Flight client
internally via the `hasReadable` flag on the internal `debugChannel`
option. For the Node.js clients, that flag was accidentally derived from
the public option `debugChannel.readable`, which is conceptually
incorrect, because `debugChannel` is a `Readable` stream, not an options
object with a `readable` property. However, a `Readable` also has a
`readable` property, which is a boolean that indicates whether the
stream is in a readable state. This meant that the `hasReadable` flag
was incidentally still set correctly. Regardless, this was confusing and
unintentional, so we're now fixing it to always set `hasReadable` to
`true` when a `debugChannel` is provided to the Node.js clients. We'll
revisit this in case we ever add support for writable debug channels in
Node.js (and Edge) clients.
2025-11-04 16:30:08 +01:00
Jack Pope
edd05f181b Add fragment handles to children of FragmentInstances (#34935)
This PR adds a `unstable_reactFragments?: Set<FragmentInstance>`
property to DOM nodes that belong to a Fragment with a ref (top level
host components). This allows you to access a FragmentInstance from a
DOM node.

This is flagged behind `enableFragmentRefsInstanceHandles`.

The primary use case to unblock is reusing IntersectionObserver
instances. A fairly common practice is to cache and reuse
IntersectionObservers that share the same config, with a map of
node->callbacks to run for each entry in the IO callback. Currently this
is not possible with Fragment Ref `observeUsing` because the key in the
cache would have to be the `FragmentInstance` and you can't find it
without a handle from the node. This works now by accessing
`entry.target.fragments`.

This also opens up possibilities to use `FragmentInstance` operations in
other places, such as events. We can do
`event.target.unstable_reactFragments`, then access
`fragmentInstance.getClientRects` for example. In a future PR, we can
assign an event's `currentTarget` as the Fragment Ref for a more direct
handle when the event has been dispatched by the Fragment itself.

The first commit here implemented a handle only on observed elements.
This is awkward because there isn't a good way to document or expose
this temporary property. `element.fragments` is closer to what we would
expect from a DOM API if a standard was implemented here. And by
assigning it to all top-level nodes of a Fragment, it can be used beyond
the cached IntersectionObserver callback.

One tradeoff here is adding extra work during the creation of
FragmentInstances as well as keeping track of adding/removing nodes.
Previously we only track the Fiber on creation but here we add a
traversal which could apply to a large set of top-level host children.
The `element.unstable_reactFragments` Set can also be randomly ordered.
2025-11-03 17:51:00 -05:00
Hendrik Liebau
67f7d47a9b [Flight] Fix debug info filtering to include later resolved I/O (#35036)
In #35019, we excluded debug I/O info from being considered for
enhancing the owner stack if it resolved after the defined `endTime`
option that can be passed to the Flight client. However, we should
include any I/O that was awaited before that end time, even if it
resolved later.
2025-11-03 22:59:40 +01:00
Hendrik Liebau
561ee24d4a [Fizz] Push halted await to the owner stack for late-arriving I/O info (#35019) 2025-11-01 16:03:09 +01:00
Sebastian Markbåge
488d88b018 Render children passed to "backwards" SuspenseList in reverse mount order (#35021)
Stacked on #35018.

This mounts the children of SuspenseList backwards. Meaning the first
child is mounted last in the DOM (and effect list). It's like calling
reverse() on the children.

This is meant to set us up for allowing AsyncIterable children where the
unknown number of children streams in at the end (which is the beginning
in a backwards SuspenseList). For consistency we do that with other
children too.

`unstable_legacy-backwards` still exists for the old mode but is meant
to be deprecated.

<img width="100" alt="image"
src="https://github.com/user-attachments/assets/5c2a95d7-34c4-4a4e-b602-3646a834d779"
/>
2025-10-31 13:33:23 -04:00
Sebastian Markbåge
26cf280480 Switch the default revealOrder to "forwards" and tail "hidden" on SuspenseList (#35018)
We have warned about this for a while now so we can make the switch.

Often when you reach for SuspenseList, you mean forwards. It doesn't
make sense to have the default to just be a noop. While "together" is
another useful mode that's more like a Group so isn't so associated with
the default as List. So we're switching it.

However, tail=hidden isn't as obvious of a default it does allow for a
convenient pattern for streaming in list of items by default.

This doesn't yet switch the rendering order of "backwards". That's
coming in a follow up.
2025-10-31 12:58:18 -04:00
Sebastian "Sebbie" Silbermann
c9ddee7e36 [DevTools] Reset forced states when changing component filters (#34929) 2025-10-31 12:57:11 +01:00
Sebastian Markbåge
6fb7754494 [DevTools] Render selected outline on top of every other rect (#35012)
When rects are close together (or overlapping) the outline can end up
being covered up by sibling rects or deeper rects. This renders the
selected outline on top of everything so it's always visible.

<img width="275" height="730" alt="Screenshot 2025-10-29 at 8 43 28 PM"
src="https://github.com/user-attachments/assets/69224883-f548-45ec-ada1-1a04ec17eaf5"
/>
<img width="266" height="737" alt="Screenshot 2025-10-29 at 8 58 53 PM"
src="https://github.com/user-attachments/assets/946f7dde-450d-49fd-9fbd-57487f67f461"
/>

Additionally, this makes it so that it's not part of the translucent
tree when things are hidden by the timeline. That way it's easier to see
what is selected inside a hidden tree.

<img width="498" height="196" alt="Screenshot 2025-10-29 at 8 45 24 PM"
src="https://github.com/user-attachments/assets/723107ab-a92c-42c2-8a7d-a548ac3332d0"
/>
<img width="571" height="735" alt="Screenshot 2025-10-29 at 8 59 06 PM"
src="https://github.com/user-attachments/assets/d653f1a7-4096-45c3-b92a-ef155d4742e6"
/>
2025-10-30 15:26:49 -04:00
Sebastian Markbåge
3a0ab8a7ee [DevTools] Synchronize Scroll Position Between Suspense Tab and Main Document (#34641)
It's annoying to have to try to find where it lines up with no hints.

This way when you hover over something it should be on screen.

The strategy I went with is that it scrolls to a percentage along the
scrollable axis but the two might not be exactly the same. Partially
because they have different aspect ratios but also because suspended
boundaries can shrink the document while the suspense tab needs to still
be able to show the boundaries that are currently invisible.
2025-10-29 21:49:35 -04:00
Sebastian Markbåge
0a5fb67ddf [DevTools] Sort suspense timeline by end time instead of just document order (#35011)
Right now it's possible for things like server environments to appear
before other content in the timeline just because it's in a different
document order.

Ofc the order in production is not guaranteed but we can at least use
the timing information we have as a hint towards the actual order.

Unfortunately since the end time of the RSC stream itself is always
after the content that resolved to produce it, it becomes kind of
determined by the chunking. Similarly since for a clean refresh, the
scripts and styles will typically load after the server content they
appear later. Similarly SSR typically finishes after the RSC parts.
Therefore a hack here is that I artificially delay everything with a
non-null environment (RSC) so that RSC always comes after client-side
(Suspense). This is also consistent with how we color things that have
an environment even if children are just Suspense.

To ensure that we never show a child before a parent, in the timeline,
each child has a minimum time of its parent.
2025-10-29 15:05:04 -04:00
Sebastian Markbåge
4f93170066 [Flight] Cache the value if we visit the same I/O or Promise multiple times along different paths (#35005)
We avoid visiting the same async node twice but if we see it again we
returned "null" indicating that there's no I/O there.

This means that if you have two different Promises both resolving from
the same I/O node then we only show one of them. However, in general we
treat that as two different I/O entries to allow for things like
batching to still show up separately.

This fixes that by caching the return value for multiple visits. So if
we found I/O (but no user space await) in one path and then we visit
that path through a different Promise chain, then we'll still emit it
twice.

However, if we visit the same exact Promise that we emitted an await on
then we skip it. Because there's no need to emit two awaits on the same
thing. It only matters when the path ends up informing whether it has
I/O or not.
2025-10-29 10:55:43 -04:00
Sebastian Markbåge
0fa32506da [Flight] Clone subsequent I/O nodes if it's resolved more than once (#35003)
IO tasks can execute more than once. E.g. a connection may fire each
time a new message or chunk comes in or a setInterval every time it
executes.

We used to treat these all as one I/O node and just updated the end time
as we go. Most of the time this was fine because typically you would
have a Promise instance whose end time is really the one that gets used
as the I/O anyway.

However, in a pattern like this it could be problematic:

```js
setTimeout(() => {
  function App() {
    return Promise.resolve(123);
  }
  renderToReadableStream(<App />);
});
```

Because the I/O's end time is before the render started so it should be
excluded from being considered I/O as part of the render. It happened
outside of render. But because the `Promise.resolve()` is inside render
its end time is after the render start so the promise is considered part
of the render. This is usually not a problem because the end time of the
I/O is still before the start of the render so even though the Promise
is valid it has no I/O source so it's properly excluded.

However, if the I/O's end time updates before we observe this then the
I/O can be considered part of the render. E.g. if this was a setInterval
it would be clearly wrong. But it turns out that even setTimeout can
sometimes execute more than once in the async_hooks because each run of
"process.nextTick" and microtasks respectively are ran in their own
before/after. When a micro task executes after this main body it'll
update the end time which can then turn the whole I/O as being inside
the render.

To solve this properly I create a new I/O node each time before() is
invoked so that each one gets to observe a different end time. This has
a potential CPU and memory allocation cost when there's a lot of them
like in a quick stream.
2025-10-28 13:27:35 -04:00
Ricky
fb0d96073c [tests] disableLegacyMode in test-renderer (#35002)
500 tests failed from not using async act. Will fix the tests and then
re-land this.
2025-10-28 12:53:30 -04:00
Michael H
b4455a6ee6 [react-dom] Include all Node.js APIs in Bun entrypoint for /server (#34193) 2025-10-27 23:06:45 +01:00
lauren
17b3765244 [generate-changelog] Refactor (#34993)
Just a light reorganization.
2025-10-27 18:04:48 -04:00
lauren
69f3e9d034 [generate-changelog] Add --format option (#34992)
Adds a new `--format` option which can be `text` (default), `csv`, or
`json`.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34992).
* #34993
* __->__ #34992
2025-10-27 17:54:09 -04:00
Ricky
dd53a946ec [rn] enabled disableLegacyMode everywhere (#34947)
Stacked on https://github.com/facebook/react/pull/34946

This should be a noop, now that the legacy renderers are not being
sync'd.
2025-10-27 17:48:33 -04:00
Ricky
90817f8810 [rn] delete the legacy renderers from the sync (#34946)
Now that RN is only on the New Architecture, we can stop stop syncing
the legacy React Native renderers.

In this diff, I just stop syncing them. In a follow up I'll delete the
code for them so only Fabric is left.

This will also allow us to remove the `enableLegacyMode` feature flag.
2025-10-27 17:38:56 -04:00
Hendrik Liebau
0d721b60c2 [Flight] Don't hang after resolving cyclic references (#34988) 2025-10-27 22:06:28 +01:00
lauren
d3d0ce329e [script] Add yarn generate-changelog (#34962)
(disclaimer: I used codex to write this script)

Adds a new `yarn generate-changelog` script to simplify the process of
writing changelogs. You can use it as follows:

```
$ yarn generate-changelog --help

Usage: yarn generate-changelog [--codex|--claude] [--debug] [<pkg@version> ...]

Options:
  --codex     Use Codex for commit summarization.                      [boolean]
  --claude    Use Claude for commit summarization.                     [boolean]
  --debug     Enable verbose debug logging.           [boolean] [default: false]
  -h, --help  Show help                                                [boolean]

Examples:
  generate-changelog --codex                Generate changelog for a single
  eslint-plugin-react-hooks@7.0.1           package using Codex.
  generate-changelog --claude react@19.3    Generate changelog entries for
  react-dom@19.3                            multiple packages using Claude.
  generate-changelog --codex                Generate changelog for all stable
                                            packages using recorded versions.
```

For example, if no args are passed, the script will print find all the
relevant commits affecting packages (defaults to `stablePackages` in
`ReactVersions.js`) and format them as a simple markdown list.

```
$ yarn generate-changelog

## eslint-plugin-react-hooks@7.0.0
* [compiler] improve zod v3 backwards compat (#34877) ([#34877](https://github.com/facebook/react/pull/34877) by [@henryqdineen](https://github.com/henryqdineen))
* [ESLint] Disallow passing effect event down when inlined as a prop (#34820) ([#34820](https://github.com/facebook/react/pull/34820) by [@jf-eirinha](https://github.com/jf-eirinha))
* Switch to `export =` to fix eslint-plugin-react-hooks types (#34949) ([#34949](https://github.com/facebook/react/pull/34949) by [@karlhorky](https://github.com/karlhorky))
* [eprh] Type `configs.flat` more strictly (#34950) ([#34950](https://github.com/facebook/react/pull/34950) by [@poteto](https://github.com/poteto))
* Add hint for Node.js cjs-module-lexer for eslint-plugin-react-hook types (#34951) ([#34951](https://github.com/facebook/react/pull/34951) by [@karlhorky](https://github.com/karlhorky))
* Add hint for Node.js cjs-module-lexer for eslint-plugin-react-hook types (#34953) ([#34953](https://github.com/facebook/react/pull/34953) by [@karlhorky](https://github.com/karlhorky))

// etc etc...
```

If `--codex` or `--claude` is passed, the script will attempt to use
them to summarize the commit(s) in the same style as our existing
CHANGELOG.md.

And finally, for debugging the script you can add `--debug` to see
what's going on.
2025-10-27 15:48:36 -04:00
Eugene Choi
ba0590f306 [playground] Upgrade playwright (#34991)
Some vulnerabilities were detected in older versions of Playwright,
upgrading for the playground.
2025-10-27 13:42:02 -04:00
Joseph Savona
408b38ef73 [compiler] Improve display of errors on multi-line expressions (#34963)
When a longer function or expression is identified as the source of an
error, we currently print the entire expression in our error message.
This is because we delegate to a Babel helper to print codeframes. Here,
we add some checking and abbreviate the result if it spans too many
lines.
2025-10-23 11:30:28 -07:00
Jorge Cabiedes
09056abde7 [Compiler] Improve error for calculate in render useEffect validation (#34580)
Summary:
Change error and update snapshots

The error now mentions what values are causing the issue which should
provide better context on how to fix the issue

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34580).
* __->__ #34580
* #34579
* #34578
* #34577
* #34575
* #34574
2025-10-23 11:05:55 -07:00
lauren
c91783c1f2 [eprh] Bump ReactVersions for next version (#34965)
This was outdated from previously.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34965).
* __->__ #34965
* #34964
2025-10-23 13:43:27 -04:00
lauren
e0654becf7 [eprh] Update changelog for 7.0.1 (#34964)
Add changelog entry for 7.0.1

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34964).
* #34965
* __->__ #34964
2025-10-23 13:43:16 -04:00
Timothy Lau
6160773f30 [playground] Refactor ConfigEditor to use <Activity> component (#34958)
## Summary

This PR addresses a pending TODO comment left in
https://github.com/facebook/react/pull/34499


eb2f784e75/compiler/apps/playground/components/Editor/ConfigEditor.tsx (L37)

This change removes the temporary workaround and replaces it with
`<Activity>`, as originally intended.

## How did you test this change?

- Updated the component to use `<Activity>` directly
- Verified the editor renders correctly in both development and
production builds.
- The `<Activity>` UI updates as expected.



https://github.com/user-attachments/assets/ce976123-da59-4579-b063-b308a9167b21
2025-10-23 11:13:18 -04:00
Karl Horky
eb2f784e75 Add hint for Node.js cjs-module-lexer for eslint-plugin-react-hook types (#34953)
<!--
  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
-->

Supersedes #34951

## Summary

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

Fix the runtime error with named imports and make the last remaining
[Are The Types
Wrong?](https://arethetypeswrong.github.io/?p=eslint-plugin-react-hooks%400.0.0-experimental-6b344c7c-20251022)
error with `eslint-plugin-react-hooks` go away, thanks to the hint from
Andrew Branch:

- https://github.com/facebook/react/issues/34801#issuecomment-3433478810

## How did you test this change?

<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->

I tried adding this to `node_modules` and it fixed the failures when
importing named imports like `import { configs, meta, rules } from
'eslint-plugin-react-hooks'`:

```bash
➜  eslint-config-upleveled git:(renovate/react-monorepo) pnpm eslint . --max-warnings 0

Oops! Something went wrong! :(

ESLint: 9.37.0

file:///Users/k/p/eslint-config-upleveled/index.js:13
import reactHooks, { configs } from 'eslint-plugin-react-hooks';
                     ^^^^^^^
SyntaxError: Named export 'configs' not found. The requested module 'eslint-plugin-react-hooks' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'eslint-plugin-react-hooks';
const { configs } = pkg;

    at ModuleJob._instantiate (node:internal/modules/esm/module_job:228:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:335:5)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:647:26)
    at async dynamicImportConfig (/Users/k/p/eslint-config-upleveled/node_modules/.pnpm/eslint@9.37.0/node_modules/eslint/lib/config/config-loader.js:186:17)
    at async loadConfigFile (/Users/k/p/eslint-config-upleveled/node_modules/.pnpm/eslint@9.37.0/node_modules/eslint/lib/config/config-loader.js:276:9)
    at async ConfigLoader.calculateConfigArray (/Users/k/p/eslint-config-upleveled/node_modules/.pnpm/eslint@9.37.0/node_modules/eslint/lib/config/config-loader.js:589:23)
    at async #calculateConfigArray (/Users/k/p/eslint-config-upleveled/node_modules/.pnpm/eslint@9.37.0/node_modules/eslint/lib/config/config-loader.js:743:23)
    at async directoryFilter (/Users/k/p/eslint-config-upleveled/node_modules/.pnpm/eslint@9.37.0/node_modules/eslint/lib/eslint/eslint-helpers.js:309:5)
    at async NodeHfs.<anonymous> (file:///Users/k/p/eslint-config-upleveled/node_modules/.pnpm/@humanfs+core@0.19.1/node_modules/@humanfs/core/src/hfs.js:586:29)
    at async NodeHfs.walk (file:///Users/k/p/eslint-config-upleveled/node_modules/.pnpm/@humanfs+core@0.19.1/node_modules/@humanfs/core/src/hfs.js:614:3)
➜  eslint-config-upleveled git:(renovate/react-monorepo) pnpm eslint . --max-warnings 0
➜  eslint-config-upleveled git:(renovate/react-monorepo) # no error
```

The named imports identifiers `configs`, `meta`, and `rules` also
contain values, as a sanity check:

- https://github.com/facebook/react/pull/34951#issuecomment-3433555636

cc @poteto
2025-10-22 17:51:01 -04:00
Karl Horky
723b25c644 Add hint for Node.js cjs-module-lexer for eslint-plugin-react-hook types (#34951)
<!--
  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

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

Fix the runtime error with named imports and make the last remaining
[Are The Types
Wrong?](https://arethetypeswrong.github.io/?p=eslint-plugin-react-hooks%400.0.0-experimental-6b344c7c-20251022)
error with `eslint-plugin-react-hooks` go away, thanks to the hint from
@andrewbranch:

- https://github.com/facebook/react/issues/34801#issuecomment-3433478810

## How did you test this change?

<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->

I tried adding this to `node_modules` and it fixed the failures when
importing named imports like `import { configs, meta, rules } from
'eslint-plugin-react-hooks'`:

```bash
➜  eslint-config-upleveled git:(renovate/react-monorepo) pnpm eslint . --max-warnings 0

Oops! Something went wrong! :(

ESLint: 9.37.0

file:///Users/k/p/eslint-config-upleveled/index.js:13
import reactHooks, { configs } from 'eslint-plugin-react-hooks';
                     ^^^^^^^
SyntaxError: Named export 'configs' not found. The requested module 'eslint-plugin-react-hooks' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'eslint-plugin-react-hooks';
const { configs } = pkg;

    at ModuleJob._instantiate (node:internal/modules/esm/module_job:228:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:335:5)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:647:26)
    at async dynamicImportConfig (/Users/k/p/eslint-config-upleveled/node_modules/.pnpm/eslint@9.37.0/node_modules/eslint/lib/config/config-loader.js:186:17)
    at async loadConfigFile (/Users/k/p/eslint-config-upleveled/node_modules/.pnpm/eslint@9.37.0/node_modules/eslint/lib/config/config-loader.js:276:9)
    at async ConfigLoader.calculateConfigArray (/Users/k/p/eslint-config-upleveled/node_modules/.pnpm/eslint@9.37.0/node_modules/eslint/lib/config/config-loader.js:589:23)
    at async #calculateConfigArray (/Users/k/p/eslint-config-upleveled/node_modules/.pnpm/eslint@9.37.0/node_modules/eslint/lib/config/config-loader.js:743:23)
    at async directoryFilter (/Users/k/p/eslint-config-upleveled/node_modules/.pnpm/eslint@9.37.0/node_modules/eslint/lib/eslint/eslint-helpers.js:309:5)
    at async NodeHfs.<anonymous> (file:///Users/k/p/eslint-config-upleveled/node_modules/.pnpm/@humanfs+core@0.19.1/node_modules/@humanfs/core/src/hfs.js:586:29)
    at async NodeHfs.walk (file:///Users/k/p/eslint-config-upleveled/node_modules/.pnpm/@humanfs+core@0.19.1/node_modules/@humanfs/core/src/hfs.js:614:3)
➜  eslint-config-upleveled git:(renovate/react-monorepo) pnpm eslint . --max-warnings 0
➜  eslint-config-upleveled git:(renovate/react-monorepo) # no error
```

The named imports identifiers `configs`, `meta`, and `rules` also
contain values, as a sanity check:

- https://github.com/facebook/react/pull/34951#issuecomment-3433555636

cc @poteto
2025-10-22 14:05:49 -04:00
lauren
bbb7a1fdf7 [eprh] Type configs.flat more strictly (#34950)
Addresses #34801 where `configs.flat` is possibly undefined as it was
typed as a record of arbitrary string keys.

<img width="990" height="125" alt="Screenshot 2025-10-22 at 1 16 44 PM"
src="https://github.com/user-attachments/assets/8b0d37b9-d7b0-4fc0-aa62-1b0968dae75f"
/>
2025-10-22 13:18:44 -04:00
Karl Horky
6b344c7c53 Switch to export = to fix eslint-plugin-react-hooks types (#34949)
<!--
  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

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

Resolve the type error with the types, according to [Are the types
wrong?](https://arethetypeswrong.github.io/?p=eslint-plugin-react-hooks%407.0.0),
as an additional

- Last attempt: https://github.com/facebook/react/pull/34746
- Original issue: https://github.com/facebook/react/issues/34745

## How did you test this change?

I edited `node_modules/eslint-plugin-react-hooks/index.d.ts` in my
`"module": "Node16"` + `"type": "module"` project and my error went
away:

- https://github.com/facebook/react/issues/34801#issuecomment-3433053067

cc @poteto @michaelfaith @andrewbranch 

<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->
2025-10-22 12:31:09 -04:00
lauren
71b3a03cc9 [forgive] Various fixes to prepare for internal sync (#34928)
Fixes a few small things:

- Update imports to reference root babel-plugin-react-compiler rather
than from `[...]/src/...`
- Remove unused cosmiconfig options parsing for now
- Update type exports in babel-plugin-react-compiler accordingly
2025-10-21 10:57:18 -04:00
Błażej Kustra
39c6545cef Fix indices of hooks in devtools when using useSyncExternalStore (#34547)
## Summary

This PR updates getChangedHooksIndices to account for the fact that
useSyncExternalStore internally mounts two hooks, while DevTools should
treat it as a single user-facing hook.

It introduces a helper isUseSyncExternalStoreHook to detect this case
and adjust iteration so the extra internal hook is skipped when counting
changes.

Before:


https://github.com/user-attachments/assets/0db72a4e-21f7-44c7-ba02-669a272631e5

After:


https://github.com/user-attachments/assets/4da71392-0396-408d-86a7-6fbc82d8c4f5

## How did you test this change?

I used this component to reproduce this issue locally (I followed
instructions in `packages/react-devtools/CONTRIBUTING.md`).

```ts
function Test() {
  // 1
  React.useSyncExternalStore(
    () => {},
    () => {},
    () => {},
  );
  // 2
  const [state, setState] = useState('test'); 
  return (
    <>
      <div
        onClick={() => setState(Math.random())}
        style={{backgroundColor: 'red'}}>
        {state}
      </div>
    </>
  );
}
```
2025-10-21 13:59:20 +01:00
Ruslan Lesiutin
613cf80f26 [DevTools] chore: add useSyncExternalStore examples to shell (#34932)
Few examples of using `useSyncExternalStore` that can be useful for
debugging hook tree reconstruction logic and hook names parsing feature.
2025-10-21 13:51:44 +01:00
Nathan
ea0c17b095 [compiler] loosen computed key restriction for compiler (#34902)
We have a whole ton of compiler errors due to us using a helper to
return breakpoints for CSS-in-js, which results in code like:

```
const styles = {
  [responsive.up('xl')]: { ... }
}
```

this results in TONS of bailouts due to `(BuildHIR::lowerExpression)
Expected Identifier, got CallExpression key in ObjectExpression`.

I was looking into what it would take to fix it and why we don't allow
it, and following the paper trail is seems like the gotchas have been
fixed with the new mutability aliasing model that is fully rolled out.
It looks like this is the same pattern/issue that was fixed (see
https://github.com/facebook/react/blob/main/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-object-expression-computed-key-modified-during-after-construction-hoisted-sequence-expr.js
and the old bug in
d58c07b563/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/bug-object-expression-computed-key-modified-during-after-construction-hoisted-sequence-expr.expect.md).

@josephsavona can you confirm if that's the case and if we're able to
drop this restriction now? (or alternatively, is there another case we
can ignore?)
2025-10-20 13:52:11 -07:00
Sebastian Markbåge
031595d720 [DevTools] Title color tweak (#34927)
<img width="521" height="365" alt="Screenshot 2025-10-20 at 11 53 50 AM"
src="https://github.com/user-attachments/assets/1a073c09-d440-4498-b2b3-c0dcb2272c96"
/>
2025-10-20 14:54:27 -04:00
Ruslan Lesiutin
3cde211b0c React DevTools 7.0.0 -> 7.0.1 (#34926)
Full list of changes:

* Text layout fixes for stack traces with badges
([eps1lon](https://github.com/eps1lon) in
[#34925](https://github.com/facebook/react/pull/34925))
* chore: read from build/COMMIT_SHA fle as fallback for commit hash
([hoxyq](https://github.com/hoxyq) in
[#34915](https://github.com/facebook/react/pull/34915))
* fix: dont ship source maps for css in prod builds
([hoxyq](https://github.com/hoxyq) in
[#34913](https://github.com/facebook/react/pull/34913))
* Lower case "rsc stream" debug info
([sebmarkbage](https://github.com/sebmarkbage) in
[#34921](https://github.com/facebook/react/pull/34921))
* BuiltInCallSite should have padding-left
([sebmarkbage](https://github.com/sebmarkbage) in
[#34922](https://github.com/facebook/react/pull/34922))
* Show the Suspense boundary name in the rect if there's no overlap
([sebmarkbage](https://github.com/sebmarkbage) in
[#34918](https://github.com/facebook/react/pull/34918))
* Don't attach filtered IO to grandparent Suspense
([eps1lon](https://github.com/eps1lon) in
[#34916](https://github.com/facebook/react/pull/34916))
* Infer name from stack if it's the generic "lazy" name
([sebmarkbage](https://github.com/sebmarkbage) in
[#34907](https://github.com/facebook/react/pull/34907))
* Use same Suspense naming heuristics when reconnecting
([eps1lon](https://github.com/eps1lon) in
[#34898](https://github.com/facebook/react/pull/34898))
* Assign a different color and label based on environment
([sebmarkbage](https://github.com/sebmarkbage) in
[#34893](https://github.com/facebook/react/pull/34893))
* Compute environment names for the timeline
([sebmarkbage](https://github.com/sebmarkbage) in
[#34892](https://github.com/facebook/react/pull/34892))
* Don't highlight the root rect if no roots has unique suspenders
([sebmarkbage](https://github.com/sebmarkbage) in
[#34885](https://github.com/facebook/react/pull/34885))
* Highlight the rect when the corresponding timeline bean is hovered
([sebmarkbage](https://github.com/sebmarkbage) in
[#34881](https://github.com/facebook/react/pull/34881))
* Repeat the "name" if there's no short description in groups
([sebmarkbage](https://github.com/sebmarkbage) in
[#34894](https://github.com/facebook/react/pull/34894))
* Tweak the rects design and create multi-environment color scheme
([sebmarkbage](https://github.com/sebmarkbage) in
[#34880](https://github.com/facebook/react/pull/34880))
* Adjust the rects size by one pixel smaller
([sebmarkbage](https://github.com/sebmarkbage) in
[#34876](https://github.com/facebook/react/pull/34876))
* Remove steps title from scrubber
([sebmarkbage](https://github.com/sebmarkbage) in
[#34878](https://github.com/facebook/react/pull/34878))
* Include some sub-pixel precision in rects
([sebmarkbage](https://github.com/sebmarkbage) in
[#34873](https://github.com/facebook/react/pull/34873))
* Don't pluralize if already plural
([sebmarkbage](https://github.com/sebmarkbage) in
[#34870](https://github.com/facebook/react/pull/34870))
* Don't try to load anonymous or empty urls
([sebmarkbage](https://github.com/sebmarkbage) in
[#34869](https://github.com/facebook/react/pull/34869))
* Add inspection button to Suspense tab
([sebmarkbage](https://github.com/sebmarkbage) in
[#34867](https://github.com/facebook/react/pull/34867))
* Don't select on hover ([sebmarkbage](https://github.com/sebmarkbage)
in [#34860](https://github.com/facebook/react/pull/34860))
* Don't highlight on timeline
([sebmarkbage](https://github.com/sebmarkbage) in
[#34861](https://github.com/facebook/react/pull/34861))
* The bridge event types should only be defined in one direction
([sebmarkbage](https://github.com/sebmarkbage) in
[#34859](https://github.com/facebook/react/pull/34859))
* Attempt at a better "unique suspender" text
([sebmarkbage](https://github.com/sebmarkbage) in
[#34854](https://github.com/facebook/react/pull/34854))
* Track whether a boundary is currently suspended and make transparent
([sebmarkbage](https://github.com/sebmarkbage) in
[#34853](https://github.com/facebook/react/pull/34853))
* Don't hide overflow rectangles
([sebmarkbage](https://github.com/sebmarkbage) in
[#34852](https://github.com/facebook/react/pull/34852))
* Measure text nodes ([sebmarkbage](https://github.com/sebmarkbage) in
[#34851](https://github.com/facebook/react/pull/34851))
* Don't measure fallbacks when suspended
([sebmarkbage](https://github.com/sebmarkbage) in
[#34850](https://github.com/facebook/react/pull/34850))
* Filter out built-in stack frames
([sebmarkbage](https://github.com/sebmarkbage) in
[#34828](https://github.com/facebook/react/pull/34828))
* Exclude Suspense boundaries in hidden Activity
([eps1lon](https://github.com/eps1lon) in
[#34756](https://github.com/facebook/react/pull/34756))
* Group consecutive suspended by rows by the same name
([sebmarkbage](https://github.com/sebmarkbage) in
[#34830](https://github.com/facebook/react/pull/34830))
* Preserve the original index when sorting suspended by
([sebmarkbage](https://github.com/sebmarkbage) in
[#34829](https://github.com/facebook/react/pull/34829))
* Don't show the root as being non-compliant
([sebmarkbage](https://github.com/sebmarkbage) in
[#34827](https://github.com/facebook/react/pull/34827))
* Ignore suspense boundaries, without visual representation, in the
timeline ([sebmarkbage](https://github.com/sebmarkbage) in
[#34824](https://github.com/facebook/react/pull/34824))
* Explicitly say which id to scroll to and only once
([sebmarkbage](https://github.com/sebmarkbage) in
[#34823](https://github.com/facebook/react/pull/34823))
* devtools: fix ellipsis truncation for key values
([sophiebits](https://github.com/sophiebits) in
[#34796](https://github.com/facebook/react/pull/34796))
* fix(devtools): remove duplicated "Display density" field in General
settings ([Anatole-Godard](https://github.com/Anatole-Godard) in
[#34792](https://github.com/facebook/react/pull/34792))
* Gate SuspenseTab ([hoxyq](https://github.com/hoxyq) in
[#34754](https://github.com/facebook/react/pull/34754))
* Release `<ViewTransition />` to Canary
([eps1lon](https://github.com/eps1lon) in
[#34712](https://github.com/facebook/react/pull/34712))
2025-10-20 18:39:28 +01:00
Sebastian "Sebbie" Silbermann
1d3664665b [DevTools] Text layout fixes for stack traces with badges (#34925) 2025-10-20 19:33:47 +02:00
Joseph Savona
2bcbf254f1 [compiler] Fix false positive for useMemo reassigning context vars (#34904)
Within a function expression local variables may use StoreContext for
local context variables, so the reassignment check here was firing too
often. We should only report an error for variables that are declared
outside the function, ie part of its `context`.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34904).
* #34903
* __->__ #34904
2025-10-20 08:42:04 -07:00
Ruslan Lesiutin
aaad0ea055 [DevTools] chore: read from build/COMMIT_SHA fle as fallback for commit hash (#34915)
This eliminates the gap in a reproducer for the React DevTools browser
extension from the source code that we submit to Firefox extension
stores.

We use the commit hash as part of the Backend version, here:

2cfb221937/packages/react-devtools-extensions/utils.js (L26-L38)

The problem is that we archive the source code for Mozilla extension
store reviews and there is no git. But since we still download the React
sources from the CI, we could reuse the hash from `build/COMMIT_HASH`
file.
2025-10-20 16:14:47 +01:00
Ruslan Lesiutin
02c80f0d87 [DevTools] fix: dont ship source maps for css in prod builds (#34913)
This has been causing some issues with the submission review on Firefox
store: we use OS-level paths in these source maps, which makes the build
artifact different from the one that's been submitted.

Also saves ~100Kb for main.js artifact.
2025-10-20 13:39:42 +01:00
Sebastian Markbåge
21272a680f Lower case "rsc stream" debug info (#34921)
This is an aesthetic thing. Most simple I/O entries are things like
"script", "stylesheet", "fetch" etc. which are all a single word and
lower case. The "RSC stream" name sticks out and draws unnecessary
attention to itself where as it's really the least interesting to look
at.

I don't love the name because I'm not sure how to explain it. It's
really mainly the byte size of the payload itself without considering
things like server awaits things which will have their own cause. So I'm
trying to communicate the download size of the stream of downloading the
`.rsc` file or the `"rsc stream"`.
2025-10-20 02:42:38 -04:00
Sebastian Markbåge
1440f4f42d [DevTools] BuiltInCallSite should have padding-left (#34922)
We don't normally show this but when we do, it should have the same
padding as other callsites.

<img width="313" height="241" alt="Screenshot 2025-10-19 at 10 46 22 PM"
src="https://github.com/user-attachments/assets/7f72149e-d748-4b71-8291-889038d676e7"
/>
2025-10-20 01:52:50 -04:00
Sebastian Markbåge
f6a4882859 [DevTools] Show the Suspense boundary name in the rect if there's no overlap (#34918)
This shows the title in the top corner of the rect if there's enough
space.

The complex bit here is that it can be noisy if too many boundaries
occupy the same space to overlap or partially overlap.

This uses an R-tree to store all the rects to find overlapping
boundaries to cut the available space to draw inside the rect. We use
this to compute the rectangle within the rect which doesn't have any
overlapping boundaries.

The roots don't count as overlapping. Similarly, a parent rect is not
consider overlapping a child. However, if two sibling boundaries occupy
the same space, no title will be drawn.

<img width="734" height="813" alt="Screenshot 2025-10-19 at 5 34 49 PM"
src="https://github.com/user-attachments/assets/2b848b9c-3b78-48e5-9476-dd59a7baf6bf"
/>

We might also consider drawing the "Initial Paint" title at the root but
that's less interesting. It's interesting in the beginning before you
know about the special case at the root but after that it's just always
the same value so just adds noise.
2025-10-19 22:17:45 -04:00
Sebastian "Sebbie" Silbermann
b485f7cf64 [DevTools] Don't attach filtered IO to grandparent Suspense (#34916) 2025-10-20 00:47:27 +02:00
Sebastian Markbåge
2cfb221937 [Flight] Allow passing DEV only startTime as an option (#34912)
When you use the `createFromFetch` API we assume that the start time of
the request is the same time as when you call `createFromFetch` but in
principle you could use it with a Promise that starts earlier and just
happens to resolve to a `Response`.

When you use `createFromReadableStream` that is almost definitely the
case. E.g. you might have started it way earlier and you don't call
`createFromReadableStream` until you get the headers back (the fetch
promise resolves).

This adds an option to pass in the start time for debug purposes if you
started the request before starting to parse it.
2025-10-19 16:38:33 -04:00
Sebastian Markbåge
58bdc0bb96 [Flight] Ignore bound-anonymous-fn resources as they're not considered I/O (#34911)
When you create a snapshot from an AsyncLocalStorage in Node.js, that
creates a new bound AsyncResource which everything runs inside of.


3437e1c4bd/lib/internal/async_local_storage/async_hooks.js (L61-L67)

This resource is itself tracked by our async debug tracking as I/O. We
can't really distinguish these in general from other AsyncResources
which are I/O.

However, by default they're given the name `"bound-anonymous-fn"` if you
pass it an anonymous function or in the case of a snapshot, that's
built-in:


3437e1c4bd/lib/async_hooks.js (L262-L263)

We can at least assume that these are non-I/O. If you want to ensure
that a bound resource is not considered I/O, you can ensure your
function isn't assigned a name or give it this explicit name.

The other issue here is that, the sequencing here is that we track the
callsite of the `.snapshot()` or `.bind()` call as the trigger. So if
that was outside of render for example, then it would be considered
non-I/O. However, this might miss stuff if you resolve promises inside
the `.run()` of the snapshot if the `.run()` call itself was spawned by
I/O which should be tracked. Time will tell if those patterns appear.
However, in cases like nested renders (e.g. Next.js's "use cache") then
restoring it as if it was outside the parent render is what you do want.
2025-10-19 14:56:56 -04:00
Sebastian Markbåge
bf11d2fb2f [DevTools] Infer name from stack if it's the generic "lazy" name (#34907)
Stacked on #34906.

Infer name from stack if it's the generic "lazy" name. It might be
wrapped in an abstraction. E.g. `next/dynamic`.

Also use the function name as a description of a resolved function
value.

<img width="310" height="166" alt="Screenshot 2025-10-18 at 10 42 05 AM"
src="https://github.com/user-attachments/assets/c63170b9-2b19-4f30-be7a-6429bb3ef3d9"
/>
2025-10-19 14:56:40 -04:00
Sebastian Markbåge
ec7d9a7249 Resolve the .default export of a React.lazy as the canonical value (#34906)
For debug purposes this is the value that the `React.lazy` resolves to.
It also lets us look at that value for descriptions like its name.
2025-10-19 14:56:25 -04:00
Sebastian "Sebbie" Silbermann
40c7a7f6ca [DevTools] Use same Suspense naming heuristics when reconnecting (#34898) 2025-10-18 12:54:05 +02:00
Sebastian Markbåge
3a669170e9 [DevTools] Assign a different color and label based on environment (#34893)
Stacked on #34892.

In the timeline scrubber each timeline entry gets a label and color
assigned based on the environment computed for that step.

In the rects, we find the timeline step that this boundary is part of
and use that environment to assign a color. This is slightly different
than picking from the boundary itself since it takes into account parent
boundaries.

In the "suspended by" section we color each entry individually based on
the environment that spawned the I/O.

<img width="790" height="813" alt="Screenshot 2025-10-17 at 12 18 56 AM"
src="https://github.com/user-attachments/assets/c902b1fb-0992-4e24-8e94-a97ca8507551"
/>
2025-10-17 19:03:15 -04:00
Sebastian Markbåge
a083344699 [DevTools] Compute environment names for the timeline (#34892)
Stacked on #34885.

This refactors the timeline to store not just an id but a complex object
for each step. This will later represent a group of boundaries.

Each timeline step is assigned an environment name. We pick the last
environment name (assumed to have resolved last) from the union of the
parent and child environment names. I.e. a child step is considered to
be blocked by the parent so if a child isn't blocked on any environment
name it still gets marked as the parent's environment name.

In a follow up, I'd like to reorder the document order timeline based on
environment names to favor loading everything in one environment before
the next.
2025-10-17 18:54:53 -04:00
Sebastian Markbåge
423c44b886 [DevTools] Don't highlight the root rect if no roots has unique suspenders (#34885)
Stacked on #34881.

We don't paint suspense boundaries if there are no suspenders. This does
the same with the root. The root is still selectable so you can confirm
but there's no affordance drawing attention to click the root.

This could happen if you don't use the built-ins of React to load things
like scripts and css. It would never happen in something like Next.js
where code and CSS is loaded through React-native like RSC.

However, it could also happen in the Activity scoped case when all
resources are always loaded early.
2025-10-17 18:53:30 -04:00
Sebastian Markbåge
f970d5ff32 [DevTools] Highlight the rect when the corresponding timeline bean is hovered (#34881)
Stacked on #34880.

In #34861 I removed the highlight of the real view when hovering the
timeline since it was disruptive to stepping through the visuals.

This makes it so that when we hover the timeline we highlight the rect
with the subtle hover effect added in #34880.

We can now just use the one shared state for this and don't need the CSS
psuedo-selectors.

<img width="603" height="813" alt="Screenshot 2025-10-16 at 3 11 17 PM"
src="https://github.com/user-attachments/assets/a018b5ce-dd4d-4e77-ad47-b4ea068f1976"
/>
2025-10-17 18:52:26 -04:00
Sebastian Markbåge
724e7bfb40 [DevTools] Repeat the "name" if there's no short description in groups (#34894)
It looks weird when the row is blank when there's no short description
for the entry in a group.

<img width="328" height="436" alt="Screenshot 2025-10-17 at 12 25 30 AM"
src="https://github.com/user-attachments/assets/12f5c55f-a37f-4b6d-913e-f763cec6b211"
/>
2025-10-17 18:52:07 -04:00
Sebastian Markbåge
ef88c588d5 [DevTools] Tweak the rects design and create multi-environment color scheme (#34880)
<img width="1011" height="811" alt="Screenshot 2025-10-16 at 2 20 46 PM"
src="https://github.com/user-attachments/assets/6dea3962-d369-4823-b44f-2c62b566c8f1"
/>

The selection is now clearer with a wider outline which spans the
bounding box if there are multi rects.

The color now gets darked changes on hover with a slight animation.

The colors are now mixed from constants defined which are consistently
used in the rects, the time span in the "suspended by" side bar and the
scrubber. I also have constants defined for "server" and "other" debug
environments which will be used in a follow up.
2025-10-17 18:51:02 -04:00
Hendrik Liebau
dc485c7303 [Flight] Fix detached ArrayBuffer error when streaming typed arrays (#34849)
Using `renderToReadableStream` in Node.js with binary data from
`fs.readFileSync` (or `Buffer.allocUnsafe`) could cause downstream
consumers (like compression middleware) to fail with "Cannot perform
Construct on a detached ArrayBuffer".

The issue occurs because Node.js uses an 8192-byte Buffer pool for small
allocations (< 4KB). When React's `VIEW_SIZE` was 2KB, files between
~2KB and 4KB would be passed through as views of pooled buffers rather
than copied into `currentView`. ByteStreams (`type: 'bytes'`) detach
ArrayBuffers during transfer, which corrupts the shared Buffer pool and
causes subsequent Buffer operations to fail.

Increasing `VIEW_SIZE` from 2KB to 4KB ensures all chunks smaller than
4KB are copied into `currentView` (which uses a dedicated 4KB buffer
outside the pool), while chunks 4KB or larger don't use the pool anyway.
Thus no pooled buffers are ever exposed to ByteStream detachment.

This adds 2KB memory per active stream, copies chunks in the 2-4KB range
instead of passing them as views (small CPU cost), and buffers up to 2KB
more data before flushing. However, it avoids duplicating large binary
data (which copying everything would require, like the Edge entry point
currently does in `typedArrayToBinaryChunk`).

Related issues:

- https://github.com/vercel/next.js/issues/84753
- https://github.com/vercel/next.js/issues/84858
2025-10-17 22:13:52 +02:00
Joseph Savona
c35f6a3041 [compiler] Optimize props spread for common cases (#34900)
As part of the new inference model we updated to (correctly) treat
destructuring spread as creating a new mutable object. This had the
unfortunate side-effect of reducing precision on destructuring of props,
though:

```js
function Component({x, ...rest}) {
  const z = rest.z;
  identity(z);
  return <Stringify x={x} z={z} />;
}
```

Memoized as the following, where we don't realize that `z` is actually
frozen:

```js
function Component(t0) {
  const $ = _c(6);
  let x;
  let z;
  if ($[0] !== t0) {
    const { x: t1, ...rest } = t0;
    x = t1;
    z = rest.z;
    identity(z);
...
```

#34341 was our first thought of how to do this (thanks @poteto for
exploring this idea!). But during review it became clear that it was a
bit more complicated than I had thought. So this PR explores a more
conservative alternative. The idea is:

* Track known sources of frozen values: component props, hook params,
and hook return values.
* Find all object spreads where the rvalue is a known frozen value.
* Look at how such objects are used, and if they are only used to access
properties (PropertyLoad/Destructure), pass to hooks, or pass to jsx
then we can be very confident the object is not mutated. We consider any
such objects to be frozen, even though technically spread creates a new
object.

See new fixtures for more examples.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34900).
* __->__ #34900
* #34887
2025-10-17 11:59:17 -07:00
Joseph Savona
adbc32de32 [compiler] More fbt compatibility (#34887)
In my previous PR I fixed some cases but broke others. So, new approach.
Two phase algorithm:

* First pass is forward data flow to determine all usages of macros.
This is necessary because many of Meta's macros have variants that can
be accessed via properties, eg you can do `macro(...)` but also
`macro.variant(...)`.
* Second pass is backwards data flow to find macro invocations (JSX and
calls) and then merge their operands into the same scope as the macro
call.

Note that this required updating PromoteUsedTemporaries to avoid
promoting macro calls that have interposing instructions between their
creation and usage. Macro calls in general are pure so it should be safe
to reorder them.

In addition, we're now more precise about `<fb:plural>`, `<fbt:param>`,
`fbt.plural()` and `fbt.param()`, which don't actually require all their
arguments to be inlined. The whole point is that the plural/param value
is an arbitrary value (along with a string name). So we no longer
transitively inline the arguments, we just make sure that they don't get
inadvertently promoted to named variables.

One caveat: we actually don't do anything to treat macro functions as
non-mutating, so `fbt.plural()` and friends (function form) may still
sometimes group arguments just due to mutability inference. In a
follow-up, i'll work to infer the types of nested macro functions as
non-mutating.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34887).
* #34900
* __->__ #34887
2025-10-17 11:37:28 -07:00
Joseph Savona
1324e1bb1f [compiler] Cleanup and enable validateNoVoidUseMemo (#34882)
This is a great validation, so let's enable by default. Changes:
* Move the validation logic into ValidateUseMemo alongside the new check
that the useMemo result is used
* Update the lint description
* Make the void memo errors lint-only, they don't require us to skip
compilation (as evidenced by the fact that we've had this validation
off)

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34882).
* #34855
* __->__ #34882
2025-10-16 13:08:57 -07:00
Joseph Savona
7f5ea1bf67 [compiler] More useMemo validation (#34868)
Two additional validations for useMemo:
* Disallow reassigning to values declared outside the useMemo callback
(always on)
* Disallow unused useMemo calls (part of the validateNoVoidUseMemo
feature flag, which in turn is off by default)

We should probably enable this flag though!

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34868).
* #34855
* #34882
* __->__ #34868
2025-10-16 13:05:18 -07:00
Damjan Petrovic
0e32da71c7 Add MIT license header to feature flag utility script (#34833)
Added the standard Meta Platforms, Inc. MIT license notice to the top of
the feature flag comparison script to ensure compliance with repository
licensing requirements and for code consistency.
**No functional or logic changes were made to the code.**
2025-10-16 14:20:21 -04:00
João Eirinha
2381ecc290 [ESLint] Disallow passing effect event down when inlined as a prop (#34820)
## Summary

Fixes https://github.com/facebook/react/issues/34793.

We are allowing passing down effect events when they are inlined as a
prop.

```
<Child onClick={useEffectEvent(...)} />
```

This seems like a case that someone not familiar with `useEffectEvent`'s
purpose could fall for so this PR introduces logic to disallow its
usage.

An alternative implementation would be to modify the name and function
of `recordAllUseEffectEventFunctions` to record all `useEffectEvent`
instances either assigned to a variable or not, but this seems clearer.
Or we could also specifically disallow its usage inside JSX. Feel free
to suggest any improvements.

## How did you test this change?

- Added a new test in
`packages/eslint-plugin-react-hooks/__tests__/ESLintRulesOfHooks-test.js`.
All tests pass.
2025-10-16 14:18:01 -04:00
Ricky
5418d8bdc1 Fix changelog link (#34879)
Closes https://github.com/reactjs/react.dev/issues/8081
2025-10-16 13:40:26 -04:00
Henry Q. Dineen
ed1351c4fb [compiler] improve zod v3 backwards compat (#34877)
## Summary

When upgrading to `babel-plugin-react-compiler@1.0.0` in a project that
uses `zod@3` we are running into TypeScript errors like:

```
node_modules/babel-plugin-react-compiler/dist/index.d.ts:435:10 - error TS2694: Namespace '"/REDACTED/node_modules/zod/v3/external"' has no exported member 'core'.

435     }, z.core.$strip>>>;
             ~~~~
```

This problem seems to be related to
d6eb735938, which introduced zod v3/v4
compatibility. Since `zod` is bundled into the compiler source this does
not cause runtime issues and only manifests as TypeScript errors. My
proposed solution is this PR is to use zod's [subpath versioning
strategy](https://zod.dev/v4/versioning?id=versioning-in-zod-4) which
allows you to support v3 and v4 APIs on both major versions.

Changes in this PR include:

- Updated `zod` import paths to `zod/v4`
- Bumped min `zod` version to `^3.25.0` for zod which guarantees the
`zod/v4` subpath is available.
- Updated `zod-validation-error` import paths to
`zod-validation-error/v4`
- Bumped min `zod-validation-error ` version to `^3.5.0` 
- Updated `externals` tsup configuration where appropriate. 

Once the compiler drops zod v3 support we could optionally remove the
`/v4` subpath from the imports.

## How did you test this change?

Not totally sure the best way to test. I ran `NODE_ENV=production yarn
workspace babel-plugin-react-compiler run build --dts` and diffed the
`dist/` folder between my change and `v1.0.0` and it looks correct. We
have a `patch-package` patch to workaround this for now and it works as
expected.

```diff
diff --git a/node_modules/babel-plugin-react-compiler/dist/index.d.ts b/node_modules/babel-plugin-react-compiler/dist/index.d.ts
index 81c3f3d..daafc2c 100644
--- a/node_modules/babel-plugin-react-compiler/dist/index.d.ts
+++ b/node_modules/babel-plugin-react-compiler/dist/index.d.ts
@@ -1,7 +1,7 @@
 import * as BabelCore from '@babel/core';
 import { NodePath as NodePath$1 } from '@babel/core';
 import * as t from '@babel/types';
-import { z } from 'zod';
+import { z } from 'zod/v4';
 import { NodePath, Scope } from '@babel/traverse';
 
 interface Result<T, E> {
```

Co-authored-by: Henry Q. Dineen <henryqdineen@gmail.com>
2025-10-16 09:46:55 -07:00
Sebastian Markbåge
93f8593289 [DevTools] Adjust the rects size by one pixel smaller (#34876)
This ensures that the outline of a previous rectangle lines up on the
same pixel as the next rectangle so that they appear consecutive.

<img width="244" height="51" alt="Screenshot 2025-10-16 at 11 35 32 AM"
src="https://github.com/user-attachments/assets/75ffde6f-8cc6-49c1-8855-3953569546b4"
/>

I don't love this implementation. There's probably a smarter way. Was
trying to avoid adding another element.
2025-10-16 12:16:16 -04:00
Sebastian Markbåge
dc1becd893 [DevTools] Remove steps title from scrubber (#34878)
The hover now has a reach tooltip for the "environment" instead.
2025-10-16 12:16:04 -04:00
Sebastian "Sebbie" Silbermann
d8aa94b0f4 Only capture stacks for up to 10 frames for Owner Stacks (#34864) 2025-10-16 18:00:41 +02:00
Sebastian Markbåge
03ba0c76e1 [DevTools] Include some sub-pixel precision in rects (#34873)
Currently the sub-pixel precision is lost which can lead to things not
lining up properly and being slightly off or overlapping.

We need some sub-pixel precision.

Ideally we'd just keep the floating point as is. I'm not sure why the
operations is limited to integers. We don't send it as a typed array
anyway it seems which would ideally be more optimal. Even if we did, we
haven't defined a precision for the protocol. Is it 32bit integer?
64bit? If it's 64bit we can fit a float anyway. Ideally it would be more
variable precision like just pushing into a typed array directly with
the option to write whatever precision we want.
2025-10-16 10:50:41 -04:00
Sebastian Markbåge
4e00747378 [DevTools] Don't pluralize if already plural (#34870)
In a demo today, `cookies()` showed up as `cookieses`. While adorable,
is wrong.
2025-10-16 10:50:18 -04:00
Sebastian Markbåge
7bd8716acd [DevTools] Don't try to load anonymous or empty urls (#34869)
This triggers unnecessary fetches.
2025-10-16 10:49:37 -04:00
Sebastian Markbåge
7385d1f61a [DevTools] Add inspection button to Suspense tab (#34867)
Add inspection button to Suspense tab which lets you select only among
Suspense nodes. It highlights all the DOM nodes in the root of the
Suspense node instead of just the DOM element you hover. The name is
inferred.

<img width="1172" height="841" alt="Screenshot 2025-10-15 at 8 03 34 PM"
src="https://github.com/user-attachments/assets/f04d965b-ef6e-4196-9ba0-51626148fa1a"
/>
2025-10-16 10:49:23 -04:00
Joseph Savona
85f415e33b [compiler] Fix fbt for the ∞th time (#34865)
We now do a single pass over the HIR, building up two data structures:
* One tracks values that are known macro tags or macro calls.
* One tracks operands of macro-related instructions so that we can later
group them.

After building up these data structures, we do a pass over the latter
structure. For each macro call instruction, we recursively traverse its
operands to ensure they're in the same scope. Thus, something like
`fbt('hello' + fbt.param(foo(), "..."))` will correctly merge the fbt
call, the `+` binary expression, the `fbt.param()` call, and `foo()`
into a single scope.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34865).
* #34855
* __->__ #34865
2025-10-15 16:23:31 -07:00
Sebastian Markbåge
903366b8b1 [DevTools] Don't select on hover (#34860)
We should only persist a selection once you click. Currently, we persist
the selection if you just hover which means you lose your selection
immediately when just starting to inspect. That's not what Chrome
Elements tab does - it selects on click.
2025-10-15 13:43:55 -04:00
Sebastian Markbåge
0fbb9b3683 [DevTools] Don't highlight on timeline (#34861)
I find it very frustrating that the highlight covers up the content that
I'm trying to review when stepping through the timeline. It also
triggered on keyboard navigation due to the focus which was annoying.

We could highlight something in the rects instead potentially.
2025-10-15 13:43:43 -04:00
Joseph Savona
e096403c59 [compiler] Infer types for properties after holes in array patterns (#34847)
In InferTypes when we infer types for properties during destructuring,
we were breaking out of the loop when we encounter a hole in the array.
Instead we should just skip that element and continue inferring later
properties.

Closes #34748

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34847).
* #34855
* __->__ #34847
2025-10-15 09:45:06 -07:00
Sebastian Markbåge
1873ad7960 [DevTools] The bridge event types should only be defined in one direction (#34859)
This revealed that a lot of the event types were defined on the wrong
end of the bridge.

It was also a problem that events with the same name couldn't have
different arguments.
2025-10-15 11:42:03 -04:00
Sebastian Markbåge
77b2f909f6 [DevTools] Attempt at a better "unique suspender" text (#34854)
Nobody knows what this terminology means.

Also, this tooltip component sucks:

<img width="634" height="137" alt="Screenshot 2025-10-15 at 12 04 49 AM"
src="https://github.com/user-attachments/assets/a1c33650-7c7d-441f-8f8b-0ea7ebea9351"
/>
2025-10-15 10:26:46 -04:00
Sebastian Markbåge
6773248311 [DevTools] Track whether a boundary is currently suspended and make transparent (#34853)
This makes the rects that are currently in a suspended state appear
ghostly so that you can see where along the timeline you are in the
rects screen.

<img width="451" height="407" alt="Screenshot 2025-10-14 at 11 43 20 PM"
src="https://github.com/user-attachments/assets/f89e362b-a0d5-46e3-8171-564909715cd1"
/>
2025-10-15 10:26:07 -04:00
Sebastian Markbåge
5747cadf44 [DevTools] Don't hide overflow rectangles (#34852)
I get the wish to click the shadow but not all child boundaries are
within the bounds of the outer Suspense boundary's node.

Sometimes they overflow naturally and if we make it overflow hidden we
hide the boundaries. Maybe it would be ok if they're actually clipped by
the real DOM but right now it covers up boundaries that should be there.

Additionally, there's also a common case where the parent boundary
shrinks when suspending the children. That then causes the suspended
child boundaries to be clipped so that you can't restore them. Maybe the
virtual boundary shouldn't shrink in this case.
2025-10-15 10:25:46 -04:00
Sebastian Markbåge
751edd6e2c [DevTools] Measure text nodes (#34851)
We can't measure Text nodes directly but we can measure a Range around
them.

This is useful since it's common, at least in examples, to use text
nodes as children of a Suspense boundary. Especially fallbacks.
2025-10-15 10:24:45 -04:00
Sebastian Markbåge
6cfc9c1ff3 [DevTools] Don't measure fallbacks when suspended (#34850)
We already do this in the update pass. That's what
`shouldMeasureSuspenseNode` does.

We also don't update measurements when we're inside an offscreen tree.

However, we didn't check if the boundary itself was in a suspended state
when in the `measureUnchangedSuspenseNodesRecursively` path.

This caused boundaries to disappear when their fallback didn't have a
rect (including their timeline entries).
2025-10-15 10:12:26 -04:00
Eugene Choi
e7984651e4 [playground] Allow accordion tabs to open on error (#34844)
There was a bug where the other output passes (aside from the "Output"
tab) were unable to open on compiler error. This PR still allows for the
"Output" tab to automatically open on error, but also allows other tabs
to be opened.


https://github.com/user-attachments/assets/157bf5d6-c289-46fd-bafb-073c2e0ff52b
2025-10-14 15:07:27 -04:00
Sebastian Markbåge
5f2b571878 [DevTools] Filter out built-in stack frames (#34828)
Treat fake eval anonymous stacks as built-in. Hide built-in stack frames
unless they're used to call into a non-ignored stack frame.

The two main things to fix here is that 1) we're showing a linkified
stack for fake anonymous and 2) we're showing only built-ins when the
stack is completely internal. Meaning framework code is all noise.
2025-10-14 09:34:57 -04:00
Sebastian Markbåge
56e846921d [Flight] Exclude RSC Stream if the stream resolves in a task (#34838) 2025-10-14 14:28:47 +02:00
Sebastian Markbåge
19b71673b1 [Flight] Forward the current environment when forwarding I/O entries (#34836) 2025-10-14 13:57:48 +02:00
Sebastian "Sebbie" Silbermann
73507ec457 [DevTools] Exclude Suspense boundaries in hidden Activity (#34756) 2025-10-14 13:57:08 +02:00
Sebastian Markbåge
03a62b20fd [Flight] Look for moved debugInfo when logging component performance track (#34839) 2025-10-14 13:21:12 +02:00
Ruslan Lesiutin
b9ec735de2 [Perf Tracks]: Clear potentially large measures (#34803)
Fixes https://github.com/facebook/react/issues/34770.

We need to clear measures at some point, otherwise all these copies of
props that we end up recording will allocate too much memory in
Chromium. This adds `performance.clearMeasures(...)` calls to such cases
in DEV.

Validated that entries are still shown on Performance panel timeline.
2025-10-13 17:42:13 -04:00
Ruslan Lesiutin
47905a7950 Fix/add missing else branch for renders with no props change (#34837)
Stacked on https://github.com/facebook/react/pull/34822.
Fixes a bug introduced in https://github.com/facebook/react/pull/34370.

Just copying the lower else branch to the `properties.length` else
branch at the top.
2025-10-13 17:23:04 -04:00
Sebastian "Sebbie" Silbermann
7b971c0a55 Current behavior for excluding Component render with unchanged props from Components track (#34822)
If we rerender with the same props, the render time will not be
accounted for in the Components track. The attached test reproduces the
behavior observed in
https://codesandbox.io/p/sandbox/patient-fast-j94f2g:
<img width="1118" height="354" alt="CleanShot 2025-10-13 at 00 13 41@2x"
src="https://github.com/user-attachments/assets/4be10ee9-d529-4d98-9035-4f26f9587f52"
/>
2025-10-13 17:14:51 -04:00
Sebastian Markbåge
83ea655a0b [DevTools] Group consecutive suspended by rows by the same name (#34830)
Stacked on #34829.

This lets you get an overview more easily when there's lots of things
like scripts downloading. Pluralized the name. E.g. `script` ->
`scripts` or `fetch` -> `fetches`.

This only groups them consecutively when they'd have the same place in
the list anyway because otherwise it might cover up some kind of
waterfall effects.

<img width="404" height="225" alt="Screenshot 2025-10-13 at 12 06 51 AM"
src="https://github.com/user-attachments/assets/da204a8e-d5f7-4eb0-8c51-4cc5bfd184c4"
/>

Expanded:

<img width="407" height="360" alt="Screenshot 2025-10-13 at 12 07 00 AM"
src="https://github.com/user-attachments/assets/de3c3de9-f314-4c87-b606-31bc49eb4aba"
/>
2025-10-13 13:07:39 -04:00
Sebastian Markbåge
026abeaa5f [Flight] Respect displayName of Promise instances on the server (#34825)
This lets you assign a name to a Promise that's passed into first party
code from third party since it otherwise would have no other stack frame
to indicate its name since the whole creation stack would be in third
party.

We already respect the `displayName` on the client but it's more
complicated on the server because we don't only consider the exact
instance passed to `use()` but the whole await sequence and we can pick
any Promise along the way for consideration. Therefore this also adds a
change where we pick the Promise node for consideration if it has a name
but no stack. Where we otherwise would've picked the I/O node.

Another thing that this PR does is treat anonymous stack frames (empty
url) as third party for purposes of heuristics like "hasUnfilteredFrame"
and the name assignment. This lets you include these in the actual
generated stacks (by overriding `filterStackFrame`) but we don't
actually want them to be considered first party code in the heuristics
since it ends up favoring those stacks and using internals like
`Function.all` in name assignment.
2025-10-13 12:29:00 -04:00
Sebastian Markbåge
d7215b4970 [DevTools] Preserve the original index when sorting suspended by (#34829)
The index is both used as the key and for hydration purposes. Previously
we didn't preserve the index when sorting so the index didn't line up
which caused hydration to be the wrong slot when sorted.
2025-10-13 12:12:12 -04:00
Sebastian Markbåge
e2ce64acb9 [DevTools] Don't show the root as being non-compliant (#34827)
`isStrictModeNonCompliant` on the root just means that it supports
strict mode. It's inherited by other nodes.

It's not possible to opt-in to strict mode on the root itself but rather
right below it. So we should not mark the root as being non-compliant.

This lets you select the root in the suspense tab and it shouldn't show
as red with a warning.
2025-10-13 12:11:52 -04:00
Sebastian Markbåge
34b1567427 [DevTools] Ignore suspense boundaries, without visual representation, in the timeline (#34824)
This ignore a Suspense boundary from the timeline when it has no visual
representation. No rect. In effect, this is not blocking the user
experience.

Technically it could be an effect that mounts which can have a
side-effect which is visible.

It could also be a meta-data tag like `<title>` which is visible. We
could hoistables a virtual representation by giving them a virtual rect.
E.g. at the top of the page. This could be added after the fact.
2025-10-13 12:10:54 -04:00
Sebastian Markbåge
b467c6e949 [DevTools] Explicitly say which id to scroll to and only once (#34823)
This ensures that we don't scroll on changes to the timeline such as
when loading a new page or while the timeline is still loading.

We only auto scroll to a boundary when we perform an explicit operation
from the user.
2025-10-13 12:09:45 -04:00
Sebastian "Sebbie" Silbermann
93d4458fdc [Fiber] Ensure useEffectEvent reads latest values in forwardRef and memo() Components (#34831) 2025-10-13 17:58:43 +02:00
Sebastian Markbåge
1d68bce19c [Fiber] Don't unhide a node if a direct parent offscreen is still hidden (#34821)
If an inner Offscreen commits an unhide, but an outer Offscreen is still
hidden but they're controlling the same DOM node then we shouldn't
unhide the DOM node yet.

This keeps track of whether we're directly inside a hidden offscreen. It
might be better to just do the tree search instead of keeping the stack
state since it's a rare case. Although this hide/unhide path does
trigger a lot of times even when there's no change.

This was technically a bug with Suspense too but it doesn't appear
because a suspended Suspense boundary never commits its partial state.
If it did, it would trigger this same path. But it can happen with an
outer Activity and inner Suspense.
2025-10-12 19:50:06 -04:00
Hendrik Liebau
ead92181bd [Flight] Avoid unnecessary indirection when serializing debug info (#34797)
When a debug channel is hooked up, and we're serializing debug models,
if the result is an already outlined reference, we can emit it directly,
without also outlining the reference. This would create an unnecessary
indirection.

Before:

```
:N1760023808330.2688
0:D"$2"
0:D"$3"
0:D"$4"
0:"hi"

1:{"name":"Component","key":null,"env":"Server","stack":[],"props":{}}
2:{"time":3.0989999999999327}
3:"$1"
4:{"time":3.261792000000014}
```

After:

```
:N1760023786873.8916
0:D"$2"
0:D"$1"
0:D"$3"
0:"hi"

1:{"name":"Component","key":null,"env":"Server","stack":[],"props":{}}
2:{"time":2.4145829999999933}
3:{"time":2.5488749999999527}
```

Notice how the second debug info chunk is now directly referencing chunk
`1` in the debug channel, without outlining and referencing `"$1"` as
its own debug chunk `3`.

This not only simplifies the RSC payload, and reduces overhead. But more
importantly it helps the client resolve cyclic references when a model
has debug info that has a reference back to the model. The client is
currently not able to resolve such a cycle when those chunk indirections
are involved. Ideally, it would also be able to resolve them regardless,
but that requires more work. In the meantime, this fixes an immediate
issue.
2025-10-10 21:44:28 +02:00
Hendrik Liebau
d44659744f [Flight] Fix preload as attribute for stylesheets (#34760)
Follow-up to #34604. For a stylesheet, we need to render `<link
rel="preload" as="style" ...>`, and not `<link rel="preload"
as="stylesheet" ...>`.
([ref](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/preload#what_types_of_content_can_be_preloaded))

fixes vercel/next.js#84569
2025-10-10 21:40:56 +02:00
Sophie Alpert
8454a32f3c devtools: fix ellipsis truncation for key values (#34796)
before
<img width="349" height="73" alt="Screenshot 2025-10-09 at 11 38 03"
src="https://github.com/user-attachments/assets/93fec45d-4ef2-498f-9550-36ff807b63f9"
/>

after
<img width="349" height="73" alt="Screenshot 2025-10-09 at 11 38 39"
src="https://github.com/user-attachments/assets/cb279384-4229-4d56-a803-93c2df897754"
/>
2025-10-10 14:05:49 -04:00
Ian Duvall
06fcc8f380 [playground] Fix syntax error from crashing the Compiler playground (#34623)
<!--
  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

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

Fixes a syntax error causing the Compiler playground to crash. Resolves
https://github.com/facebook/react/issues/34622.

## How did you test this change?

<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->

Tested locally and added a test.

<img width="1470" height="836" alt="Screenshot 2025-09-27 at 8 13 07 AM"
src="https://github.com/user-attachments/assets/29473682-94c3-49dc-9ee9-c2004062aaea"
/>
2025-10-09 12:02:55 -07:00
Anatole-Godard
91e5c3daf1 fix(devtools): remove duplicated "Display density" field in General settings (#34792)
<!--
  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

This pull request fixes a small UI issue in the React Developer Tools
settings panel.
The “Display density” field was appearing twice in the General tab.

Fix : https://github.com/facebook/react/issues/34791
2025-10-09 10:38:23 -07:00
lauren
4b3e662e4c [compiler] Add VoidUseMemo rule to RecommendedLatest (#34783)
Adds a new error category VoidUseMemo which is only enabled in the
RecommendedLatest preset for now.
2025-10-08 15:55:13 -04:00
lauren
3e1b34dc51 [compiler] Setup RecommendedLatest preset (#34782)
Renames the `recommended` property on LintRule to `preset`, to allow
exporting rules for different presets. For now the `Recommended` and
`RecommendedLatest` presets are the same, but in the next PR I will
enable more rules for the latest preset.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34782).
* #34783
* __->__ #34782
2025-10-08 15:45:22 -04:00
lauren
7568e71854 [eprh] Prepare for 7.0.0 (#34757)
For 7.0.0:

Slim down presets to just 2 configurations:

- `recommended`: legacy and flat config with all recommended rules, and
- `recommended-latest`: legacy and flat config with all recommended
rules plus new bleeding edge experimental compiler rules

Removed:
- `recommended-latest-legacy`
- `flat/recommended`

Please see the README for new install instructions.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34757).
* #34783
* #34782
* __->__ #34757
2025-10-08 15:17:31 -04:00
Ruslan Lesiutin
9724e3e66e [DevTools] Gate SuspenseTab (#34754) 2025-10-08 05:47:50 -07:00
lauren
848e0e3a4f [eprh] Update plugin config to be compatible with flat and legacy (#34762)
This has been incredibly frustrating as [ESLint's own
docs](https://eslint.org/docs/latest/extend/plugins#backwards-compatibility-for-legacy-configs)
are clearly wrong (see #34679).

This PR uses [eslint-plugin-react's
setup](https://github.com/jsx-eslint/eslint-plugin-react/blob/master/index.js)
as a reference, where the presets are assigned to `configs.flat` (not
documented by eslint).
2025-10-07 16:23:56 -04:00
lauren
5c15c1cd34 [ci] Dry run with debug mode (#34767)
Adds `--debug` to our dry run command so we can see the npm dry run
output
2025-10-07 15:16:18 -04:00
lauren
69b4cb8df4 [ci] Allow dry run (#34765)
Allow running the compiler release script as dry run.
2025-10-07 14:44:46 -04:00
lauren
a664f5f2ee [compiler] Fix incorrect version name (#34764)
Script was using the wrong version name.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34764).
* #34765
* __->__ #34764
2025-10-07 14:32:51 -04:00
lauren
1384ea8230 [compiler] Update release script for latest tag (#34763)
Updates our release script so we can publish to the `latest` tag.
2025-10-07 14:14:50 -04:00
Sebastian Markbåge
3025aa3964 [Flight] Don't serialize toJSON in Debug path and omit wide arrays (#34759)
There's a couple of issues with serializing Buffer in the debug renders.

For one, the Node.js Buffer has a `toJSON` on it which turns the binary
data into a JSON array which is very inefficient to serialize compared
to the real buffer. For debug info we never really want to resolve these
and unlike the regular render we can't error. So this uses the trick
where we read the original value. It's still unfortunate that this
intermediate gets created at all but at least now we're not serializing
it.

Second, we have a limit on depth of objects but we didn't have a limit
on width like large arrays or typed arrays. This omits large arrays from
the payload when possible and make them deferred when there's a debug
channel.
2025-10-07 06:59:34 -07:00
Sebastian "Sebbie" Silbermann
a4eb2dfa6f Release Fragment refs to Canary (#34720)
## Overview

This PR adds the `ref` prop to `<Fragment>` in `react@canary`.

This means this API is ready for final feedback and prepared for a
semver stable release.

## What this means

Shipping Fragment refs to canary means they have gone through extensive
testing in production, we are confident in the stability of the APIs,
and we are preparing to release it in a future semver stable version.

Libraries and frameworks following the [Canary
Workflow](https://react.dev/blog/2023/05/03/react-canaries) should begin
implementing and testing these features.

## Why we follow the Canary Workflow

To prepare for semver stable, libraries should test canary features like
Fragment refs with `react@canary` to confirm compatibility and prepare
for the next semver release in a myriad of environments and
configurations used throughout the React ecosystem. This provides
libraries with ample time to catch any issues we missed before slamming
them with problems in the wider semver release.

Since these features have already gone through extensive production
testing, and we are confident they are stable, frameworks following the
[Canary Workflow](https://react.dev/blog/2023/05/03/react-canaries) can
also begin adopting canary features like Fragment refs.

This adoption is similar to how different Browsers implement new
proposed browser features before they are added to the standard. If a
frameworks adopts a canary feature, they are committing to stability for
their users by ensuring any API changes before a semver stable release
are opaque and non-breaking to their users.

Apps not using a framework are also free to adopt canary features like
Fragment refs as long as they follow the [Canary
Workflow](https://react.dev/blog/2023/05/03/react-canaries), but we
generally recommend waiting for a semver stable release unless you have
the capacity to commit to following along with the canary changes and
debugging library compatibility issues.

Waiting for semver stable means you're able to benefit from libraries
testing and confirming support, and use semver as signal for which
version of a library you can use with support of the feature.

## Docs 

Check out the ["React Labs: View Transitions, Activity, and
more"](https://react.dev/blog/2025/04/23/react-labs-view-transitions-activity-and-more#fragment-refs)
blog post, and [the new docs for Fragment
refs`](https://react.dev/reference/react/Fragment#fragmentinstance) for
more info.
2025-10-06 21:24:24 -07:00
Sebastian "Sebbie" Silbermann
6a8c7fb6f1 Release <ViewTransition /> to Canary (#34712)
## Overview

This PR ships the View Transition APIs to `react@canary`:
- [`<ViewTransition
/>`](https://react.dev/reference/react/ViewTransition)
-
[`addTransitionType`](https://react.dev/reference/react/addTransitionType)

This means these APIs are ready for final feedback and prepare for
semver stable release.

## What this means

Shipping `<ViewTransition />` and `addTransitionType` to canary means
they have gone through extensive testing in production, we are confident
in the stability of the APIs, and we are preparing to release it in a
future semver stable version.

Libraries and frameworks following the [Canary
Workflow](https://react.dev/blog/2023/05/03/react-canaries) should begin
implementing and testing these features.

## Why we follow the Canary Workflow

To prepare for semver stable, libraries should test canary features like
`<ViewTransition />` with `react@canary` to confirm compatibility and
prepare for the next semver release in a myriad of environments and
configurations used throughout the React ecosystem. This provides
libraries with ample time to catch any issues we missed before slamming
them with problems in the wider semver release.

Since these features have already gone through extensive production
testing, and we are confident they are stable, frameworks following the
[Canary Workflow](https://react.dev/blog/2023/05/03/react-canaries) can
also begin adopting canary features like `<ViewTransition />`.

This adoption is similar to how different Browsers implement new
proposed browser features before they are added to the standard. If a
frameworks adopts a canary feature, they are committing to stability for
their users by ensuring any API changes before a semver stable release
are opaque and non-breaking to their users.

Apps not using a framework are also free to adopt canary features like
`<ViewTransition>` as long as they follow the [Canary
Workflow](https://react.dev/blog/2023/05/03/react-canaries), but we
generally recommend waiting for a semver stable release unless you have
the capacity to commit to following along with the canary changes and
debugging library compatibility issues.

Waiting for semver stable means you're able to benefit from libraries
testing and confirming support, and use semver as signal for which
version of a library you can use with support of the feature.

## Docs 

Check out the ["React Labs: View Transitions, Activity, and
more"](https://react.dev/blog/2025/04/23/react-labs-view-transitions-activity-and-more#view-transitions)
blog post, and [the new docs for `<ViewTransition
/>`](https://react.dev/reference/react/ViewTransition) and
[`addTransitionType`](https://react.dev/reference/react/addTransitionType)
for more info.
2025-10-06 21:23:34 -07:00
lauren
b65e6fc58b Revert [eprh] Remove hermes-parser (#34747)
Adds back HermesParser to eslint-plugin-react-hooks. There are still
[external users of
Flow](https://github.com/facebook/react/pull/34719#issuecomment-3368137743)
using the plugin, so we shouldn't break the plugin for them. However, we
still have the problem of double parsing: once from eslint (which we
discard) and then another via babel/hermes parser.

In the long run we should investigate a translation layer from estree to
babel (or alternatively, update the compiler to take estree as input).
But for now, I am reverting the PR.

This does mean that [Sandpack in
react.dev](11cb6b5915/src/components/MDX/Sandpack/runESLint.tsx (L31))
cannot update to the latest eprh as HermesParser does not appear to be
able to be run in a browser. I discovered this while trying to update
eprh on react.dev last week, but didn't investigate deeply. I'll need to
double check that again to find out more.
2025-10-06 12:43:39 -04:00
lauren
c786258422 [eprh] Fix config type not being exported correctly (#34746)
Another attempt to fix #34745. I updated our fixture for eslint-v9 to
include running tsc. I believe there were 2 issues:

1. `export * from './cjs/eslint-plugin-react-hooks'` in npm/index.d.ts
was no longer correct as we updated index.ts to export default instead
of named exports
2. After fixing ^ there was a typescript error which I fixed by making
some small tweaks
2025-10-06 00:53:21 -04:00
Sebastian "Sebbie" Silbermann
1be3ce9996 [Fiber] Bail out of diffing wide objects and arrays (#34742) 2025-10-06 01:13:22 +02:00
Ruslan Lesiutin
3b2a398106 [DevTools] Bump version of react-devtools-core for react-devtools (#34740)
This one was overlooked and yarn.lock was not synced.

Related:
- https://github.com/facebook/react/pull/34692
- https://github.com/facebook/react/pull/34723
2025-10-05 13:45:41 +01:00
Ruslan Lesiutin
62ff1e61fc Revert "[DevTools] Always include the root in the timeline and select it by default" (#34739)
Reverts facebook/react#34654
2025-10-05 13:35:07 +01:00
Sebastian Markbåge
0e79784702 [DevTools] Use documentElement to override cmd+F (#34734)
We override Cmd+F to jump to our search input instead of searching
through the HTML. This is ofc critical since our view virtualized.

However, Chrome DevTools installs its own listener on the document as
well (in the bubble phase) so if we prevent it at the document level
it's too late and it ends up stealing the focus instead. If we instead
listen at the documentElement it works as intended.
2025-10-05 13:13:22 +01:00
lauren
a2329c10ff [eprh] 6.1.1 changelog (#34726)
Update changelog for 6.1.1
2025-10-03 17:58:06 -04:00
Ruslan Lesiutin
d3f84a433a [DevTools] Bump version for extensions (#34723)
`./scripts/devtools/prepare-release.js` actually does automate the
version bump, but only path / minor ones.
2025-10-03 22:03:48 +01:00
lauren
bc2356176b [ci] Fix incorrect filtering logic for prereleases (#34725)
The workflow was correctly publishing the package(s) specified in
`only`, but due to incorrect logic it would also run the 'Publish all
packages' step.
2025-10-03 16:37:55 -04:00
lauren
4fdf7cf249 [ci] Fix runtime_prereleases (#34722)
When using the "only" or "skip" option in the workflow, we were adding
the `--skipTests` param, but that isn't an actual option:
1de32a5e75/scripts/release/publish-commands/parse-params.js
2025-10-03 14:41:34 -04:00
Sebastian "Sebbie" Silbermann
614a945d9d React DevTools 7.0.0 (#34692)
[Preview](https://github.com/eps1lon/react/blob/sebbie/09-28-react_devtools_7.0.0/packages/react-devtools/CHANGELOG.md#700)

Suspense tab is omitted since that's gated on Canary or 19.3.

Will draft a separate blog post for suspended by and open-in-editor
instructions while the extension is in review.
2025-10-03 18:48:28 +01:00
Joseph Savona
d6eb735938 [compiler] Update for Zod v3/v4 compatibility (#34717)
Partial redo of #34710. The changes there tried to use `z.function(args,
return)` to be compatible across Zod v3 and v4, but Zod 4's function API
has completely changed. Instead, I've updated to just use `z.any()`
where we expect a function, and manually validate that it's a function
before we call the value. We already have validation of the return type
(also using Zod).

Co-authored-by: kolvian <eliot@pontarelli.com>
2025-10-03 10:08:20 -07:00
lauren
71753ac90a [eprh] Remove hermes-parser (#34719)
We will be focusing eslint-plugin-react-hooks as the primary OSS-only
package for our lint plugin. eslint-plugin-react-compiler will remain as
a Meta only package as some limitations of our internal infra require us
to use packages that aren't widely adopted by the rest of the industry.

This PR removes `hermes-parser`, which was meant to support parsing Flow
syntax.
2025-10-03 12:58:00 -04:00
Joseph Savona
f24d3bbc70 Update readme for eprh (#34714) 2025-10-03 09:47:34 -07:00
Joseph Savona
85c427d822 [compiler] Remove @babel/plugin-proposal-private-methods (#34715)
redo of #34458 but fixing up prettier

Co-authored-by: Arnaud Barré <arnaud.barre@carbometrix.com>
2025-10-03 09:13:55 -07:00
Sebastian Markbåge
02bd4458f7 [DevTools] Double clicking the root should jump to the beginning of the timeline (#34704)
Unlike the rects, this never toggles. It just jumps.
2025-10-03 11:52:44 -04:00
Eugene Choi
0eebd37041 [playground] Config panel quality fixes (#34611)
Fixed two small issues with the config panel in the compiler playground:
1. Object descriptions were being confined in the config box and most of
it would not be visible upon hover
2. Changed it so that "Applied Configs" would only display a valid set
of configs, rather than switching between "Invalid Configs" and the set
of options. This would be less visually jarring for users as the Output
panel already displays errors. Additionally, if users want to see the
list of config options but have a currently broken config, they would
previously not know how to fix it.

Object hover before: 
<img width="702" height="481" alt="Screenshot 2025-09-26 at 10 41 03 AM"
src="https://github.com/user-attachments/assets/b2ddec2f-16ba-41a1-be1f-96211f46764c"
/>
Hover after:
<img width="702" height="481" alt="Screenshot 2025-09-26 at 10 40 37 AM"
src="https://github.com/user-attachments/assets/dc713a22-4710-46a8-a5d7-485060cc9074"
/>

Applied Configs always displays the last valid set of configs:


https://github.com/user-attachments/assets/2fb9232f-7388-4488-9b7a-bb48bf09e4ca
2025-10-03 10:52:36 -04:00
Jack Pope
74dee8ef64 Add getClientRects to fabric fragment instance (#34545)
Stacked on #34544 

We only have getBoundingClientRect available from RN currently. This
should work as a substitute for this case because the equivalent of
multi-rect elements in RN is a nested Text component. We only include
the rects of top-level host components here so we can assume that
calling getBoundingClientRect on each child is the same result.

Tested in react-native with Fantom.
2025-10-03 09:54:33 -04:00
Jack Pope
e866b1d1e9 Add getRootNode to fabric fragment instance (#34544)
Stacked on #34533 for root fragment handling

This is the same approach as DOM, where we call getRootNode on the
parent.
    
Tests are in react-native using Fantom.
2025-10-03 09:48:37 -04:00
lauren
19f65ff179 [eprh] Remove NoUnusedOptOutDirectives (#34703)
This rule was a leftover from a while ago and doesn't actually lint
anything useful. Specifically, you get a lint error if you try to opt
out a component that isn't already bailing out. If there's a bailout the
compiler already safely skips over it, so adding `'use no memo'` there
is unnecessary.

Fixes #31407

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34703).
* __->__ #34703
* #34700
2025-10-02 19:19:01 -04:00
lauren
26b177bc5e [eprh] Fix recommended config for flat config compatibility (#34700)
Previously, the `recommended` config used the legacy ESLint format
(plugins as an array of strings). This causes errors when used with
ESLint v9's `defineConfig()` helper. This was following [eslint's own
docs](https://eslint.org/docs/latest/extend/plugins#backwards-compatibility-for-legacy-configs):

> With this approach, both configuration systems recognize
"recommended". The old config system uses the recommended key while the
current config system uses the flat/recommended key. The defineConfig()
helper first looks at the recommended key, and if that is not in the
correct format, it looks for the flat/recommended key. This allows you
an upgrade path if you’d later like to rename flat/recommended to
recommended when you no longer need to support the old config system.

However,
[`isLegacyConfig()`](https://github.com/eslint/rewrite/blob/main/packages/config-helpers/src/define-config.js#L73-L81)
(also see
[`eslintrcKeys`](https://github.com/eslint/rewrite/blob/main/packages/config-helpers/src/define-config.js#L24-L35))
function doesn't check for the `plugins` key, so our config was
incorrectly treated as flat config despite being in legacy format.

This PR fixes the issue, along with a few other fixes combined:

1. Convert `recommended` to flat config format
2. Separate basic rules (exhaustive-deps, rules-of-hooks) from compiler
rules
3. Add `recommended-latest-legacy` config for non-flat config users who
want all recommended rules (including compiler rules)
4. Adding more types for the exported config

Our shipped presets in 6.x.x will essentially be:
- `recommended-legacy`: legacy (non-flat), with basic rules only
- `recommended-latest-legacy`: legacy (non-flat), all rules (basic +
compiler)
- `flat/recommended`: flat, basic rules only (now the same as
recommended, but to avoid making a breaking change we'll just keep it
around in 6.x.x)
- `recommended-latest`: flat, all rules (basic + compiler)
- `recommended`: flat, basic rules only

In the next breaking release 7.x.x, we will collapse down the presets
into three:

- `recommended-legacy`: all recommended rules
- `recommended`: all recommended rules
- `recommended-experimental`: all recommended rules + new bleeding edge
experimental rules

Closes #34679

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34700).
* #34703
* __->__ #34700
2025-10-02 18:52:52 -04:00
lauren
056a586928 [fixtures] Update eslint fixture lockfiles (#34699)
Updates the eslint fixture lockfiles.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34699).
* #34703
* #34700
* __->__ #34699
* #34675
2025-10-02 18:42:43 -04:00
lauren
5cc3d49f72 [eprh] Add compiler rules to recommended preset (#34675)
Adds back the compiler rules to the recommended preset, intended for the
next release.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34675).
* #34703
* #34700
* #34699
* __->__ #34675
2025-10-02 18:42:30 -04:00
Eugene Choi
289f070d64 [playground] Improve DiffEditor scrollbar + view (#34691)
The previous DiffEditor view of the playground looked broken and not
cohesive. There would be parts of the scrollbar appearing on the left
side for some reason, along with two scrollbars on the right side. This
PR makes the DiffEditor look more cohesive.

Previous:


https://github.com/user-attachments/assets/1aa1c775-5940-43b2-a75a-9b46452fb78b

After:


https://github.com/user-attachments/assets/b5c04998-6a6c-4b52-b3c5-b2fef21729e0
2025-10-02 17:41:29 -04:00
Sebastian "Sebbie" Silbermann
6a8a8ef326 [Flight] Add <Activity> (#34697) 2025-10-02 23:14:52 +02:00
Sebastian Markbåge
f89ed71ddf [DevTools] Track whether to auto select when new timeline entries come on (#34698)
This auto updates to select the last entry in the timeline until we make
the first selection. That way when new content loads in, we show the
last timeline of what is visible.
2025-10-02 17:06:52 -04:00
Josh Story
7d9f876cbc [Fizz] Detatch boundary after flushing segment with boundary (#34694)
When we flush a Suspense boundary we might not flush the fallback
segment, it might only flush a placeholder instead. In this case the
segment can flush again but we do not want to flush the boundary itself
a second time. We now detach the boundary after flushing it.

better solution to: https://github.com/facebook/react/pull/34668
2025-10-02 13:21:57 -07:00
Sebastian "Sebbie" Silbermann
df3562dc7f Fix DevTools regression tests (#34696) 2025-10-02 21:52:50 +02:00
Sebastian Markbåge
b56907db51 [DevTools] Show Props as Read-only for Suspense/Activity but below (#34695)
Somehow my last commit didn't make it in #34630.
2025-10-02 15:29:38 -04:00
Sebastian Markbåge
c825f03067 [DevTools] Hide State and Props in the Sidebar for Suspense (#34630)
We're showing too much noise in the side-panel when selecting a Suspense
boundary. The interesting thing to see directly is the "Suspended by".

The "props" are mostly useless because the `"name"` prop is already in
the tree. I'm now also showing it in the title bar of the selected
element panel. The "children" and "fallback" props are just the thing
that you can see in the tree view anyway.

The "state" is this weird section with just one field in it, which we
already have duplicated in the top toolbar as well. We can just delete
this. I make sure to show the icon and a "suspended..." section while
the boundary is still loading but now yet resuspended by force
suspending.

While still loading:

<img width="600" height="193" alt="Screenshot 2025-09-27 at 11 54 37 PM"
src="https://github.com/user-attachments/assets/1c3f3a96-46e0-4b11-806f-032569c7d5b5"
/>

After loading:

<img width="602" height="266" alt="Screenshot 2025-09-27 at 11 54 53 PM"
src="https://github.com/user-attachments/assets/c43cc4cb-036f-4ced-9b0d-226c6320cd76"
/>

Resuspended after loading:

<img width="602" height="300" alt="Screenshot 2025-09-27 at 11 55 07 PM"
src="https://github.com/user-attachments/assets/0be01735-48a7-47dc-b5cf-e72ec71e0148"
/>
2025-10-02 15:18:41 -04:00
Sebastian Markbåge
2e68dc76a4 [DevTools] Give a distinct color to the root (#34690)
Stacked on #34654.

The root is special since it represents "Initial Paint" (or a
"Transition" when an Activity is selected). This gives it a different
color in the timeline as well as gives it an outline that's clickable.
Hovering the timeline now shows "Initial Paint" or "Suspense".

Also made the cursor a pointer to invite you to try to click things and
some rounded corners.

<img width="1219" height="420" alt="Screenshot 2025-10-02 at 1 26 38 PM"
src="https://github.com/user-attachments/assets/12451f93-8917-4f3b-8f01-930129e5fc13"
/>

<img width="1217" height="419" alt="Screenshot 2025-10-02 at 1 26 54 PM"
src="https://github.com/user-attachments/assets/02b5e94c-3fbe-488d-b0f2-225b73578608"
/>

<img width="1215" height="419" alt="Screenshot 2025-10-02 at 1 27 24 PM"
src="https://github.com/user-attachments/assets/c24e8861-e74a-4ccc-8643-ee9d04bef43c"
/>

<img width="1216" height="419" alt="Screenshot 2025-10-02 at 1 27 10 PM"
src="https://github.com/user-attachments/assets/d5cc2b62-fa64-41bf-b485-116b1cd67467"
/>
2025-10-02 14:37:03 -04:00
Sebastian Markbåge
ced705d756 [DevTools] Always include the root in the timeline and select it by default (#34654)
Rebased on #34454.

Always include the root in the timeline even if it has no unique
suspenders, since even if it won't suspend, we have to be able to see
that and step to one step before the next boundary to see the first
boundary that does suspend in its fallback state.

Also, if there's no current selection on initial mount, select the last
entry in the timeline. We usually do this with `selectedSuspenseID` but
that doesn't happen on initial load. So this does it on initial load if
nothing else is selected by then. That way when you reload you get the
initial root selected.

There's a problem here because we should really use one source of truth
and `selectedSuspenseID` doesn't really do anything now. Either it
should be its separate source of truth and you can't show components in
the side-panel or it should be derived from the other state.

If it's derived, once there's a selection, e.g. in the root, then even
if new timelines load it will never change but that's probably a good
thing.
2025-10-02 14:20:02 -04:00
Joseph Savona
70b52beca6 [compiler] @enablePreserveExistingMemoizationGuarantees on by default (#34689)
This enables `@enablePreserveExistingMemoizationGuarantees` by default.
As of the previous PR (#34503), this mode now enables the following
behaviors:

- Treating variables referenced within a `useMemo()` or `useCallback()`
as "frozen" (immutable) as of the start of the call. Ie, the compiler
will assume that the values you reference are not mutated by the body of
the useMemo, not are they mutated later. Directly modifying them (eg
`var.property = true`) will be an error.
- Similarly, the results of the useMemo/useCallback are treated as
frozen (immutable) after the call.

These two rules match the behavior for other hooks: this means that
developers will see similar behavior to swapping out `useMemo()` for a
custom `useMyMemo()` wrapper/alias.

Additionally, as of #34503 the compiler uses information from the manual
dependencies to know which variables are non-nullable. Even if a useMemo
block conditionally accesses a nested property — `if (cond) { log(x.y.z)
}` — where the compiler would not usually know that `x` is non-nullable,
if the user specifies `x.y.z` as a manual dependency then the compiler
knows that `x` and `x.y` are non-nullable and can infer a more precise
dependency.

Finally, this mode also ensures that we always memoize function calls
that return primitives. See #34343 for more details.

For now, I've explicitly opted out of this feature in all test fixtures
where the behavior changed.
2025-10-02 10:25:00 -07:00
Sebastian "Sebbie" Silbermann
4a28227960 [DevTools] Inspect the Initial Paint when inspecting a Root (#34454) 2025-10-02 19:18:15 +02:00
Sebastian "Sebbie" Silbermann
e4a27db283 [DevTools] Defer Suspense tab to 19.3.0-canary (#34688) 2025-10-02 19:13:52 +02:00
Joseph Savona
57d5a59748 [compiler] enablePreserveMemo treats manual deps as non-nullable (#34503)
The `@enablePreserveExistingMemoizationGuarantees` mode can still fail
to preserve manual memoization due to mismtached dependencies.
Specifically, where the user's dependencies are more precise than the
compiler infers bc the compiler is being conservative about what might
be nullable. In this mode though we're intentionally using information
from the manual memoization and can also rely on the deps as a signal
for what's non-nullable.

The idea of the PR is that we treat manual memo deps just like other
inferred-as-non-nullable objects during PropagateScopeDeps. We're
careful to not treat the full path as non-nullable, only up to the last
property index. So `x.y.z` as a manual dep treats `x` and `x.y` as
non-nullable, allowing us to preserve a conditional dependency on
`x.y.z`.

Optionals within manual dependencies are a bit trickier and aren't
handled yet, but hopefully that's less common and something we can
improve in a follow-up. Not handling them just means that developers may
hit false positives on validating existing memoization if they use
optional chains in manual dependencies.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34503).
* #34689
* __->__ #34503
2025-10-02 09:48:52 -07:00
Sebastian "Sebbie" Silbermann
bc828bf6e3 [DevTools] Recommend React Performance tracks if supported when Timeline profiler is not supported (#34684) 2025-10-02 18:33:50 +02:00
Sebastian "Sebbie" Silbermann
a757cb7667 Fix DevTools fixture crash due to usage of renamed APIs (#34682) 2025-10-02 14:43:02 +02:00
Sebastian Markbåge
d74f061b69 [Fiber] Clean up ViewTransition when it fails to start (#34676)
The View Transition docs were unclear about this but apparently the
`finished` promise never settles if the animation never started. So if
there's an error that rejects the `ready` promise, we'll never run the
clean up which can cause it to stall.

Fixes #34662.

However, ultimately that is caused by Chrome stalling our default
`onDefaultTransitionIndicator` but it should be unblocked after 10
seconds, not a minute.
2025-10-01 21:58:13 -04:00
Eugene Choi
f7254efc5c [playground] Persist open tabs on compiler error (#34673)
This change allows it so that tabs that were open before a compiler
error are automatically opened again when the error is resolved. Quality
of life change for those especially working with the advanced view of
the playground.


https://github.com/user-attachments/assets/cd2dc117-e6fc-4f57-a08f-259757c4f5e8
2025-10-01 21:26:16 -04:00
Sebastian "Sebbie" Silbermann
79ca5ae855 Bump next prerelease version numbers (#34674) 2025-10-02 00:31:55 +02:00
lauren
ae74234eae [eprh] Allow compiler rules to be opted-in but not in the preset (#34672)
Follow up to #34649. This adds the compiler rules back so they can be
opted-in 6.1.0, but aren't included in the presets as that would be a
breaking change.
2025-10-01 17:05:42 -04:00
Sebastian "Sebbie" Silbermann
861811347b Bump scheduler version (#34671)
The canaries have been published depending on 0.27-canary. Bumping
scheduler just in case to be sure.
2025-10-01 22:45:31 +02:00
Ricky
7f9d99749c Land enableHiddenSubtreeInsertionEffectCleanup (#34372)
Fixes a bug where insertion effects were not cleaned up if a hidden
Activity is unmounted.
2025-10-01 16:31:30 -04:00
Sebastian "Sebbie" Silbermann
aef8b1b562 19.2 changelog (#34655)
Co-authored-by: Jack Pope <jackpope1@gmail.com>
Co-authored-by: Rick Hanlon <rickhanlonii@meta.com>
2025-10-01 22:11:02 +02:00
Jack Pope
67e24bc527 Improve lint error messages for useEffectEvent (#34669)
Called Before:

> `logEvent` is a function created with React Hook "useEffectEvent", and
can only be called from the same component.

Called After:

> `logEvent` is a function created with React Hook "useEffectEvent", and
can only be called from Effects and Effect Events in the same component.

Referenced Before:

> `logEvent` is a function created with React Hook "useEffectEvent", and
can only be called from the same component. They cannot be assigned to
variables or passed down.

Referenced After:

> `logEvent` is a function created with React Hook "useEffectEvent", and
can only be called from Effects and Effect Events in the same component.
It cannot be assigned to a variable or passed down.
2025-10-01 15:17:08 -04:00
Sebastian Markbåge
bbc2d596fa Traverse down an updated tree even if it has no passive effects in profiling mode (#34667)
We need this to be able to log the renders that happened inside.

This is the same thing we do here but for the offscreen special cases:


https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactFiberCommitWork.js#L3452-L3457
2025-10-01 13:45:37 -04:00
Sebastian "Sebbie" Silbermann
1bd1f01f2a Ship partial-prerendering APIs to Canary (#34633) 2025-10-01 18:22:30 +02:00
Sebastian "Sebbie" Silbermann
548235db10 Enable React performance tracks in Canary (#34665)
Co-authored-by: Ruslan Lesiutin <28902667+hoxyq@users.noreply.github.com>
2025-10-01 18:13:15 +02:00
Sebastian "Sebbie" Silbermann
1f460f31ee [DevTools] Fix host instance highlighting (#34661) 2025-10-01 17:32:34 +02:00
Sebastian "Sebbie" Silbermann
2f0649a0b2 [Fizz] Remove nonce option from resume-and-prerender APIs (#34664) 2025-10-01 17:32:26 +02:00
Sebastian Markbåge
7bccdbd765 Fix "Consecutive" Event Logs in Performance Track (#34659)
Reset EventTime when clearing timers. We need to track repeat updates
separately.

Typically we always reset all timers when we've logged an update. The
same update shouldn't be logged again.

I was trying to be clever and not reset the XEventTime because we also
need the timestamp to know if it's a repeat event. However, because of
this it looked like we had an event schedule an update even after we had
reset them.

This always resets the XEventTime to -1.1 and then stashes the old time
on EventRepeatTime which is our indication whether the next update was a
repeat of the old event.

---------

Co-authored-by: Ruslan Lesiutin <28902667+hoxyq@users.noreply.github.com>
Co-authored-by: Ricky <rickhanlonii@gmail.com>
2025-10-01 10:53:08 -04:00
Sebastian "Sebbie" Silbermann
5667a41fe4 Bump next prerelease version numbers (#34639) 2025-10-01 15:15:24 +02:00
lauren
cf884083e0 [eprh] Temporarily disable compiler rules (#34649)
Temporarily disables the compiler rules in eslint-plugin-react-hooks.
Will revert this later.
2025-09-30 18:45:33 -04:00
Jack Pope
57b16e3788 [lint] Remove experimental gating useEffectEvent rules (#34660)
Stacked on https://github.com/facebook/react/pull/34637

`useEffectEvent` is now in canary so we need to remove this
`__EXPERIMENTAL__` gating on the rules and tests
2025-09-30 16:55:56 -04:00
Jordan Brown
2a04bae651 [lint] Use settings for additional hooks in exhaustive deps (#34637)
Like in the diff below, we can read from the shared configuration to
check exhaustive deps.

I allow the classic additionalHooks configuration to override it so that
this change
is backwards compatible.


--

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34637).
* __->__ #34637
* #34497
2025-09-30 16:44:43 -04:00
Jordan Brown
92cfdc3a4e [lint] Enable custom hooks configuration for useEffectEvent calling rules (#34497)
We need to be able to specify additional effect hooks for the
RulesOfHooks lint rule
in order to allow useEffectEvent to be called by custom effects.
ExhaustiveDeps
does this with a regex suppplied to the rule, but that regex is not
accessible from
other rules.

This diff introduces a `react-hooks` entry you can put in the eslint
settings that
allows you to specify custom effect hooks and share them across all
rules.

This works like:
```
{
  settings: {
    'react-hooks': {
      additionalEffectHooks: string,
    },
  },
}
```

The next diff allows useEffect to read from the same configuration.


----

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34497).
* #34637
* __->__ #34497
2025-09-30 16:44:22 -04:00
Eugene Choi
a55e98f738 [playground] ViewTransition on internals toggle & tab expansion (#34597)
<!--
  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

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

Added `<ViewTransition>` for when the "Show Internals" button is toggled
for a basic fade transition. Additionally added a transition for when
tabs are expanded in the advanced view of the Compiler Playground to
display a smoother show/hide animation.

## How did you test this change?

<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->


https://github.com/user-attachments/assets/c706b337-289e-488d-8cd7-45ff1d27788d
2025-09-30 15:25:10 -04:00
Ruslan Lesiutin
063394cf82 [Perf Tracks]: Always log effect that spawned blocking update (#34648)
We've observed some scenarios, where cascading update happens in an
effect that was shorter than 0.05ms. In this case, this effect won't be
displayed on a timeline, because of the threshold that we are using, but
it would be shown in entry properties or in a stack trace.

To avoid confusion, we should always log such effects.

Validated via manually changing the threshold to 100ms+ and observing
that only effects that triggered an update are visible on a timeline.
2025-09-30 20:05:44 +01:00
Sebastian Markbåge
d8a15c49a4 [Fiber] Reset remaining child lanes after propagating context inside Offscreen (#34658)
Otherwise, when a context is propagated into an Activity (or Suspense)
this will leave work behind on the Offscreen component itself. Which
will cause an extra unnecessary render and commit pass just to figure
out that we're still defering it to idle.

This is because lazy context propagation, when calling to schedule some
work walks back up the tree all the way to the root. This is usually
fine for other nodes since they'll recompute their remaining child lanes
on the way up. However, for the Offscreen component we'll have already
computed it. We need to set it after propagation to ensure it gets
reset.
2025-09-30 14:51:48 -04:00
Sebastian Markbåge
0d8ff4d8c7 [DevTools] Show "Initial Paint" in the breadcrumbs when root is selected (#34652)
We selected the root. This means that we're currently viewing the
Transition that rendered the whole screen. In laymans terms this is
really "Initial Paint". Once we add subtree selection, then the
equivalent should be called "Transition" since in that case it's really
about a Transition within the page. So if you've selected an Activity
tree this should be called "Transition".

Once we add the environment support to the timeline. The first entry on
the timeline should also be called "Initial Paint" when you haven't
selected an Activity and "Transition" when you have.

Technically they're both meant to be "Transition" but nobody thinks of
initial load as a "Transition" from the previous MPA page.

<img width="1214" height="419" alt="Screenshot 2025-09-29 at 5 18 58 PM"
src="https://github.com/user-attachments/assets/cae263e3-133c-4fa9-9587-a7b2344199f4"
/>
2025-09-30 14:40:33 -04:00
Sebastian Markbåge
554a373d7e [DevTools] Use the scrollWidth/Height for the root when the root is the documentElement (#34651)
If I can scroll the document due to it overflowing, I should be able to
scroll the suspense tab as much. The real rect for the root when it's
the document is really the full scroll height.

This doesn't fully eliminate the need to do recursive bounding boxes for
the root since it's still possible to have the rects overflow. E.g. if
they're currently resuspended or inside nested scrolls.

~However, maybe we should have the actual paintable root rect just be
this rectangle instead of including the recursive ones.~ Actually never
mind. The root really represents the Transition so it doesn't make sense
to give it any specific rectangle. It's rather the whole background.
2025-09-30 14:37:40 -04:00
Sebastian Markbåge
5dd163b49e [DevTools] Auto-scroll when stepping through the timeline (#34653)
This brings the Suspense boundary that's switching into view so that
when you play the loading sequence you can see how it plays out.
Otherwise it's really hard to find where things are changing.

This assumes we'll also scroll synchronize the suspense tab which will
bring it into view there too.
2025-09-30 14:37:14 -04:00
Pieter De Baets
ef8894452b Rollout enablePersistedModeClonedFlag (#34520)
## Summary

Experimentation has completed for this at Meta and we've observed
positive impact on key React Native surfaces.

## How did you test this change?

yarn flow fabric
2025-09-30 12:34:13 +01:00
Sebastian "Sebbie" Silbermann
e6f2a8a376 Allow running yarn lint on subset of paths (#34646) 2025-09-30 12:30:40 +02:00
Jack Pope
ba2214e571 Apply build script changes for RN to main (#34640)
This was merged into the 19.1.1 patch release branch in
https://github.com/facebook/react/pull/33972 but we never upstreamed it
to main. This should merge to main to make it easier to sync versions to
RN after future releases.

---------

Co-authored-by: Riccardo Cipolleschi <cipolleschi@meta.com>
2025-09-29 20:40:24 -04:00
Sebastian "Sebbie" Silbermann
ecb2ce6c5f [Flight] Compute better I/O description for exotic types (#34650) 2025-09-29 21:03:07 +02:00
Eugene Choi
3580584ba2 [playground] ViewTransition on tab switch (#34596)
<!--
  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

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

Utilized `<ViewTransition>` to introduce a sliding animation upon
switching between the Output and SourceMap tabs in the default
playground view.

## How did you test this change?

<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->


https://github.com/user-attachments/assets/1ac93482-8104-4f9a-887e-6adca3537dca
2025-09-29 14:40:33 -04:00
Eugene Choi
319a7867d0 [playground] ViewTransition on config expand (#34595)
<!--
  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

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

Introduced `<ViewTransition>` to the React Compiler Playground. Added an
initial animation on the config panel opening/closing to allow for a
smoother visual experience. Previously, the panel would flash in and out
of the screen upon open/close.

## How did you test this change?

<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->




https://github.com/user-attachments/assets/9dc77a6b-d4a5-4a7a-9d81-007ebb55e8d2
2025-09-29 14:09:37 -04:00
Sebastian Markbåge
d15d7fd79e [DevTools] Double click a Suspense Rect to jump to its position in the timeline (#34642)
When you double click it will hide or show by jumping to the selected
index or one step before the selected.

Let's you go from a suspense boundary into the timeline to find its
position. I also highlight the step in the timeline when you hover the
rect.

This only works if it's in the selected root but all of those should be
merged into one single timeline.

One thing that's weird about the SuspenseNodes now is that they
sometimes gets deleted but not always when they're resupended. Nested
ones maybe? This means that if you double click to hide it, you can't
double click again to show it. This seems like an unrelated bug that we
should fix.

We could potentially repurpose the existing "Suspend" button in the
toolbar to do this too, or maybe add another icon there.
2025-09-29 10:43:01 -04:00
Sebastian "Sebbie" Silbermann
8674c3ba28 [DevTools] Enable Suspense tab for Canary releases (#34591) 2025-09-29 16:23:30 +02:00
Sebastian "Sebbie" Silbermann
24e260d35b Enable rules-of-hooks for DevTools (#34645) 2025-09-29 15:31:06 +02:00
Sebastian "Sebbie" Silbermann
2bbb7be0e1 [DevTools] Don't call Hooks conditionally (#34644) 2025-09-29 15:15:09 +02:00
Sebastian Markbåge
dce1f6cd5d [DevTools] Custom Scrubber Design (#34627)
Stacked on #34620.

This will let us use different color for different segments of the
timeline.

Since we're modeling discrete steps (sometimes just a couple), a
scrubber with a handle that you have to move is quite annoying and
misleading. Doesn't show you how many steps there are. Therefore I went
with a design that highlights each segment as its own step and you can
click to jump to a step.

This is still backed by an input range for accessibility and keyboard
controls.

<img width="1213" height="434" alt="Screenshot 2025-09-27 at 4 50 21 PM"
src="https://github.com/user-attachments/assets/2c81753d-1b66-4434-8b1d-0a163fa22ab3"
/>
<img width="1213" height="430" alt="Screenshot 2025-09-27 at 4 50 45 PM"
src="https://github.com/user-attachments/assets/07983978-a8f6-46ed-8c51-6ec96487af66"
/>


https://github.com/user-attachments/assets/bc725f01-f0b5-40a8-bbb5-24cc4e84e86d
2025-09-28 20:00:09 -04:00
Sebastian Markbåge
7c0fff6f2b [DevTools] Add Play/Pause and Skip Controls to the Timeline (#34620)
Stacked on #34625.

This is a nice way to step through the timeline and simulate the visuals
on screen as you do it. It's also convenient to step through one at a
time, especially with the forwards button.

However, the secondary purpose of this is that it helps anchor the UI
visually as something like a timeline like in a video so that the
timeline itself becomes more identifiable.


https://github.com/user-attachments/assets/cb367c8e-9efb-4a00-a58e-4579be20beb8
2025-09-28 19:14:28 -04:00
Sebastian Markbåge
e2d19bf6a9 [DevTools] Use pretty icon with icon for unique suspenders toggle (#34625)
Stacked on #34624.

<img width="638" height="170" alt="Screenshot 2025-09-27 at 12 57 10 PM"
src="https://github.com/user-attachments/assets/f67023b1-e7be-4252-93ab-6302bc63ac26"
/>
<img width="641" height="250" alt="Screenshot 2025-09-27 at 12 57 21 PM"
src="https://github.com/user-attachments/assets/f96a9b48-c6f4-406f-a0ea-b3da288411b5"
/>
2025-09-28 19:13:15 -04:00
Sebastian Markbåge
a7d8dddaf3 [DevTools] Add Settings button on Suspense Tab (#34624)
The settings dialog appears on all tabs and should be reachable from
Suspense tab too. It's a bit weird because it's not contextual to the
tab and it shows you whatever your last settings tab was opened. Maybe
it should default to opening to the current tab's settings?

There aren't any Suspense specific settings yet but there definitely
will be. We could move the "Show all" into settings but it might be
frequently that you want to check why something isn't suspending a
Suspense boundary or test SSR streaming.

However, the general settings still apply to the Suspense tab. E.g.
switching dark/light mode.

<img width="857" height="233" alt="Screenshot 2025-09-27 at 12 35 05 PM"
src="https://github.com/user-attachments/assets/4a38e94f-2074-4dce-906b-9a1c40bccb9b"
/>
2025-09-28 19:09:52 -04:00
Sebastian Markbåge
8309724cb4 [Fiber][DevTools] Add scheduleRetry to DevTools Hook (#34635)
When forcing suspense/error we're doing that by scheduling a sync update
on the fiber. Resuspending a Suspense boundary can only happen sync
update so that makes sense. Erroring also forces a sync commit. This
means that no View Transitions fire.

However, unsuspending (and dismissing an error dialog) can be async so
the reveal should be able to be async.

This adds another hook for scheduling using the Retry lane. That way
when you play through a reveal sequence of Suspense boundaries (like
playing through the timeline), it'll run the animations that would've
ran during a loading sequence.
2025-09-28 13:51:35 -04:00
Sebastian Markbåge
09d3cd8fb5 [DevTools] Larger panel buttons and center (#34619)
The panel icons are quite small. Especially compared to the equivalent
buttons elsewhere in Chrome DevTools that otherwise use the same icons.
This makes them a little bigger to make them similar size to our other
button icons.

They were also a bit off center. This centers them as well.

Before:

<img width="409" height="426" alt="Screenshot 2025-09-26 at 4 23 15 PM"
src="https://github.com/user-attachments/assets/4a5de032-e316-44ed-9424-8bccce00f0cd"
/>

After:

<img width="519" height="388" alt="Screenshot 2025-09-26 at 4 22 57 PM"
src="https://github.com/user-attachments/assets/1763e522-5683-4fac-a913-27910a30a039"
/>
2025-09-28 12:09:08 -04:00
Sebastian Markbåge
f78b2343cc [DevTools] Recursively compute the bounding rect of the roots (#34629)
It's possible for the children to overflow the bounding rect of the root
in general when they overflow in the DOM. However even when it doesn't
overflow in the DOM, the bounding rect of the root can shrink while the
content is suspended. In fact, it's very likely.

Originally I thought we didn't need to consider this recursively because
document scrolling takes absolute positioned content into account but
because we're using nested overflow scrolling, we have to manually
compute this.
2025-09-28 10:15:31 -04:00
Sebastian "Sebbie" Silbermann
e08f53b182 Match react-dom/static test entrypoints and published entrypoints (#34599) 2025-09-28 13:26:31 +02:00
Sebastian Markbåge
2622487a74 [DevTools] Move Timeline to footer instead of header (#34617)
One thing that always bothered me is that the collapse buttons on either
side of the toolbar looks like left/right buttons which would conflict
with some steps buttons I plan to add. Another issue is that we'll need
to add more tool buttons to the top and probably eventually a Search
field. Ideally this whole section should line up vertically with the
height of the title row.

I also realized that all UIs that have some kind of timeline control
(and play/pause/skip) do that in the bottom below the content. E.g.
music players and video players all do that. We're better off playing
into that structure since that's the UI analogy we're going for here.
Makes it clearer what the weird timeline is for.

By moving it to the bottom it also frees up the top for the collapse
buttons and more controls.

__Horizontal__

<img width="794" height="809" alt="Screenshot 2025-09-26 at 3 40 35 PM"
src="https://github.com/user-attachments/assets/dacad9c4-d52f-4b66-9585-5cc74f230e6f"
/>

__Vertical__

<img width="570" height="812" alt="Screenshot 2025-09-26 at 3 40 53 PM"
src="https://github.com/user-attachments/assets/db225413-849e-46f1-b764-8fbd08b395c4"
/>
2025-09-26 16:27:49 -04:00
Sebastian "Sebbie" Silbermann
8a24ef3e75 [DevTools] Show Transition indicator when "suspended by" rows are expanded (#34565) 2025-09-26 22:27:22 +02:00
Ruslan Lesiutin
c552618a82 flags: make enableAsyncDebugInfo dynamic for www (#34430)
As titled. This adds dev-only debugging information to Fizz / Flight
that could be used for tracking Promise's stack traces in "suspended by"
section of DevTools.
2025-09-26 11:43:03 -07:00
Sebastian "Sebbie" Silbermann
df38ac9a3b Ensure useEffectEvent implementation is available in Canary (#34614) 2025-09-26 18:53:12 +02:00
Jack Pope
8bb7241f4c Bump useEffectEvent to Canary (#34610)
Bumps `useEffectEvent` from `@experimental` to `@canary`. Removes the
`experimental_` prefix from the export.

## TODO
- [ ] Update useEffectEvent reference page and Canary badging in docs:
https://github.com/reactjs/react.dev/pull/8025
2025-09-26 11:51:30 -04:00
Sebastian "Sebbie" Silbermann
8d557a638e [DevTools] Only show Suspense rects matching "unique-suspenders-only" filter (#34607) 2025-09-26 17:29:15 +02:00
Sebastian Markbåge
6a51a9fea6 [DevTools] Track Server Environment Names of Each SuspenseNode (#34605)
Tracks the environment names of the I/O in each SuspenseNode and sent it
to the front end when the suspenders change.

In the front end, every child boundary should really be treated as it
has all environment names of the parents too since they're blocked by
the parent too. We could do this tracking on backend but if there's ever
one added on the root would need to be send for every child.

This lets us highlight which subtrees are blocked by content on the
server.

---------

Co-authored-by: Sebastian "Sebbie" Silbermann <silbermann.sebastian@gmail.com>
2025-09-26 09:43:38 -04:00
Sebastian Markbåge
1fd291d3c5 [DevTools] Disable the tree list for now (#34606)
When there are no named Activities we should hide the tree side panel
(and the button to show it). Since it's not implemented yet there are
never any ones so it's always hidden.
2025-09-26 09:43:00 -04:00
Sebastian Markbåge
047715c4ba [Flight] Preload <img> and <link> using hints before they're rendered (#34604)
In Fizz and Fiber we emit hints for suspensey images and CSS as soon as
we discover them during render. At the beginning of the stream. This
adds a similar capability when a Host Component is known to be a Host
Component during the Flight render.

The client doesn't know that these resources are in the payload until it
parses that particular component which is lazy. So they need to be
hoisted with hints. We detect when these are rendered during Flight and
add them as hints. That allows you to consume a Flight payload to
preload prefetched content without having to render it.

`<link rel="preload">` can be hoisted more or less as is.

`<link rel="stylesheet">` we preload but we don't actually insert them
anywhere until they're rendered. We do these even for non-suspensey
stylesheets since we know that when they're rendered they're going to
start loading even if they're not immediately used. They're never lazy.

`<img src>` we only preload if they follow the suspensey image pattern
since otherwise they may be more lazy e.g. by if they're in the
viewport. We also skip if they're known to be inside `<picture>`. Same
as Fizz. Ideally this would preload the other `<source>` but it's
tricky.

The downside of this is that you might conditionally render something in
only one branch given a client component. However, in that case you're
already eagerly fetching the server component's data in that branch so
it's not too much of a stretch that you want to eagerly fetch the
corresponding resources as well. If you wanted it to be lazy, you
should've done a lazy fetch of the RSC.

We don't collect hints when any of these are wrapped in a Client
Component. In those cases you might want to add your own preload to a
wrapper Shared Component.

Everything is skipped if it's known to be inside `<noscript>`.

Note that the format context is approximate (see #34601) so it's
possible for these hints to overfetch or underfetch if you try to trick
it. E.g. by rendering Server Components inside a Client Component that
renders `<noscript>`.

---------

Co-authored-by: Josh Story <josh.c.story@gmail.com>
2025-09-25 23:44:14 -04:00
Eugene Choi
250f1b20e0 [playground] Fix useEffect on tabify (#34594)
There was a bug in the Compiler Playground related to the "Show
Internals" toggle due to a useEffect that was causing the tab names to
flicker from a rerender. Rewritten instead with a `<Suspense>` boundary
+ `use`.
2025-09-25 14:56:41 -04:00
Sebastian Markbåge
b0c1dc01ec [Flight] Add approximate parent context for FormatContext (#34601)
Flight doesn't have any semantically sound notion of a parent context.
That's why we removed Server Context. Each root can really start
anywhere in the tree when you refetch subtrees. Additionally when you
dedupe elements they can end up in multiple different parent contexts.

However, we do have a DEV only version of this with debugTask being
tracked for the nearest parent element to track the context of
properties inside of it.

To apply certain DOM specific hints and optimizations when you render
host components we need some information of the context. This is usually
very local so doesn't suffer from the likelihood that you refetch in the
middle. We'll also only use this information for optimistic hints and
not hard semantics so getting it wrong isn't terrible.

```
<picture>
  <img />
</picture>
<noscript>
  <p>
    <img />
  </p>
</noscript>
```

For example, in these cases we should exclude preloading the image but
we have to know if that's the scope we're in.

We can easily get this wrong if they're split or even if they're wrapped
in client components that we don't know about like:

```
<NoScript>
  <p>
    <img />
  </p>
</NoScript>
```

However, getting it wrong in either direction is not the end of the
world. It's about covering the common cases well.
2025-09-25 12:05:47 -04:00
Sebastian Markbåge
6eb5d67e9c [Fizz] Outline a Suspense Boundary if it has Suspensey CSS or Images (#34552)
We should favor outlining a boundary if it contains Suspensey CSS or
Suspensey Images since then we can load that content separately and not
block the main content. This also allows us to animate the reveal.

For example this should be able to animate the reveal even though the
actual HTML content isn't large in this case it's worth outlining so
that the JS runtime can choose to animate this reveal.

```js
<ViewTransition>
  <Suspense>
    <img src="..." />
  </Suspense>
</ViewTransition>
```

For Suspensey Images, in Fizz, we currently only implement the suspensey
semantics when a View Transition is running. Therefore the outlining
only applies if it appears inside a Suspense boundary which might
animate. Otherwise there's no point in outlining. It is also only if the
Suspense boundary itself might animate its appear and not just any
ViewTransition. So the effect is very conservative.

For CSS it applies even without ViewTransition though, since it can help
unblock the main content faster.
2025-09-25 09:38:41 -04:00
Hendrik Liebau
ac2c1a5a58 [Flight] Ensure blocked debug info is handled properly (#34524)
This PR ensures that server components are reliably included in the
DevTools component tree, even if debug info is received delayed, e.g.
when using a debug channel. The fix consists of three parts:

- We must not unset the debug chunk before all debug info entries are
resolved.
- We must ensure that the "RSC Stream" IO debug info entry is pushed
last, after all other entries were resolved.
- We need to transfer the debug info from blocked element chunks onto
the lazy node and the element.

Ideally, we wouldn't even create a lazy node for blocked elements that
are at the root of the JSON payload, because that would basically wrap a
lazy in a lazy. This optimization that ensures that everything around
the blocked element can proceed is only needed for nested elements.
However, we also need it for resolving deduped references in blocked
root elements, unless we adapt that logic, which would be a bigger lift.

When reloading the Flight fixture, the component tree is now displayed
deterministically. Previously, it would sometimes omit synchronous
server components.

<img width="306" height="565" alt="complete"
src="https://github.com/user-attachments/assets/db61aa10-1816-43e6-9903-0e585190cdf1"
/>

---------

Co-authored-by: Sebastian Markbage <sebastian@calyptus.eu>
2025-09-25 15:13:15 +02:00
Sebastian "Sebbie" Silbermann
c44fbf43b1 [DevTools] Fix instrumentation error when reconciling promise-as-a-child (#34587) 2025-09-24 22:50:12 +02:00
Joseph Savona
8ad773b1f3 [compiler] Add support for commonjs (#34589)
We previously always generated import statements for any modules that
had to be required, notably the `import {c} from
'react/compiler-runtime'` for the memo cache function. However, this
obviously doesn't work when the source is using commonjs. Now we check
the sourceType of the module and generate require() statements if the
source type is 'script'.

I initially explored using
https://babeljs.io/docs/babel-helper-module-imports, but the API design
was unfortunately not flexible enough for our use-case. Specifically,
our pipeline is as follows:
* Compile individual functions. Generate candidate imports,
pre-allocating the local names for those imports.
* If the file is compiled successfully, actually add the imports to the
program.

Ie we need to pre-allocate identifier names for the imports before we
add them to the program — but that isn't supported by
babel-helper-module-imports. So instead we generate our own require()
calls if the sourceType is script.
2025-09-24 11:17:42 -07:00
Sebastian "Sebbie" Silbermann
58d17912e8 Fix failing React DevTools regression tests (#34585) 2025-09-24 19:08:13 +02:00
Joseph Savona
2c6d92fd80 [compiler] Name anonymous functions from inlined useCallbacks (#34586)
@eps1lon flagged this case. Inlined useCallback has an extra LoadLocal
indirection which caused us not to add a name. While I was there I added
some extra checks to make sure we don't generate names for a given node
twice (just in case).
2025-09-24 09:18:16 -07:00
Sebastian Markbåge
e233218359 Track "Animating" Entry for Gestures while the Gesture is Still On-going (#34548)
Stacked on #34546.

Same as #34538 but for gestures.

Includes various fixes.

This shows how it ends with a Transition when you release in the
committed state. Note how the Animation of the Gesture continues until
the Transition is done so that the handoff is seamless.

<img width="853" height="134" alt="Screenshot 2025-09-20 at 7 37 29 PM"
src="https://github.com/user-attachments/assets/6192a033-4bec-43b9-884b-77e3a6f00da6"
/>
2025-09-24 11:26:03 -04:00
Sebastian Markbåge
05b61f812a Add Gesture Track in Performance Tab (#34546) 2025-09-24 17:20:14 +02:00
Sebastian Markbåge
e0c421ab71 Include SyncLane in includesBlockingLane helper (#34543)
This helper weirdly doesn't include the sync lane.

Everywhere we use it we have to check the sync lane separately. We can
simplify things by simply including the sync lane.

This fixes a lack of optimization because we should not check the store
consistency for a `flushSync` render.


d91d28c8ba/packages/react-reconciler/src/ReactFiberHooks.js (L1691-L1693)
2025-09-24 09:34:35 -04:00
Ruslan Lesiutin
2ee6147510 [DevTools] Switch sourcemap-codec dependency (#34569)
[sourcemap-codec](https://www.npmjs.com/package/sourcemap-codec)
(deprecated) ->
[@jridgewell/sourcemap-codec](https://www.npmjs.com/package/@jridgewell/sourcemap-codec)

Validated that symbolication still works.
2025-09-24 06:11:53 -07:00
Jordan Brown
e02c173fa5 [lint] Allow useEffectEvent in useLayoutEffect and useInsertionEffect (#34492)
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34492).
* #34497
* __->__ #34492
2025-09-23 16:56:09 -04:00
Ruslan Lesiutin
24a2ba03fb [DevTools] fix: dedupe file fetch requests and define a timeout (#34566)
If there is a large owner stack, we could potentially spam multiple
fetch requests for the same source map. This adds a simple deduplication
logic, based on URL.

Also, this adds a timeout of 60 seconds to all fetch requests initiated
by fileFetcher content script.
2025-09-23 11:38:07 -07:00
Sebastian "Sebbie" Silbermann
012b371cde [DevTools] Handle LegacyHidden Fibers like Offscreen Fibers. (#34564) 2025-09-23 20:14:53 +02:00
Jack Pope
83c88ad470 Handle fabric root level fragment with compareDocumentPosition (#34533)
The root instance doesn't have a canonical property so we were not
returning a public instance that we can call compareDocumentPosition on
when a Fragment had no other host parent in Fabric. In this case we need
to get the ReactNativeElement from the ReactNativeDocument.

I've also added test coverage for this case in DOM for consistency,
though it was already working there because we use DOM elements as root.
This same test will be copied to RN using Fantom.
2025-09-23 10:56:43 -04:00
Sebastian "Sebbie" Silbermann
cad813ac1e Fix CI from stale merge (#34555) 2025-09-23 08:49:16 +02:00
Sebastian "Sebbie" Silbermann
720bb13069 [compiler] Export PluginOptions as a type that can be used in input positions (#34550) 2025-09-22 18:28:19 +02:00
Eugene Choi
1eca9a2747 [playground] Add compiler playground tests (#34528)
<!--
  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

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

Added more tests for the compiler playground with the addition of the
new config editor and "Show Internals" button. Added testing to check
for incomplete store params in the URL, toggle functionality, and
correct errors showing for syntax/validation errors in the config
overrides.
2025-09-22 12:11:45 -04:00
Sebastian "Sebbie" Silbermann
cd85bb5616 Include Fizz runtime diff in CI (#34525) 2025-09-22 17:09:50 +02:00
Sebastian "Sebbie" Silbermann
07e4974bad [compiler] Don't leak global __DEV__ type (#34551) 2025-09-22 16:51:57 +02:00
Sebastian Markbåge
d91d28c8ba Use the JSX of the ViewTransition as the Stack Trace of "Animating" Traces (#34539)
Stacked on #34538.

Track the Task of the first ViewTransition that we detected as
animating. Use this as the Task as "Starting Animation", "Animating"
etc. That way you can see which ViewTransition spawned the Animation.
Although it's likely to be multiple.

<img width="757" height="393" alt="Screenshot 2025-09-19 at 10 19 18 PM"
src="https://github.com/user-attachments/assets/a6cdcb89-bd02-40ec-b3c3-11121c29e892"
/>
2025-09-20 11:11:27 -04:00
Sebastian Markbåge
b4fe1e6c7e Log the time until the Animation finishes as "Animating" (#34538)
Stacked on #34522.

<img width="1025" height="200" alt="Screenshot 2025-09-19 at 6 37 28 PM"
src="https://github.com/user-attachments/assets/f25900f6-6503-48b1-876d-bd6697a29c6f"
/>

We already cover the time between "Starting Animation" and "Remaining
Effects" as "Animating". However, if the effects are forced then we can
still be animating after that. This fills in that gap.

This also fills in the gap if another render starts before the animation
finishes on the same track. It'll mark the blank space between the
previous render finishing and the next render starting as "Animating".

This should correspond roughly to the native "Animations" track.
2025-09-20 11:10:42 -04:00
Sebastian Markbåge
b204edda3a Log Custom Reason for the Suspended Commit Track (#34522)
Stacked on #34511.

We currently log all Suspended Commit as "Suspended on Images or CSS"
but it can really be other reasons too now. Like waiting on the previous
View Transition. This allows the host config configure this reason.

Now when one animation starts before another one finishes we log that as
"Waiting for the previous Animation".

<img width="592" height="257" alt="Screenshot 2025-09-17 at 11 53 45 PM"
src="https://github.com/user-attachments/assets/817af8b5-37ae-46d8-bfd1-cd3fc637f3f3"
/>
2025-09-20 11:01:52 -04:00
Hendrik Liebau
115e3ec15f [ci] Document that full git shas are required for manual prereleases (#34537)
Triggering the "(Runtime) Publish Prereleases Manual" workflow with a
short git sha doesn't work. It needs the full sha. We might be able to
make it work with the short sha as well, but for now we can at least
document the restriction.
2025-09-20 08:09:44 +02:00
Sebastian Markbåge
565eb7888e Unwrap a reference to a Lazy value (#34535)
If we are referencing a lazy value that isn't explicitly lazy ($L...)
it's because we added it around an element that was blocked to be able
to defer things inside.

However, once that is unblocked we can start unwrap it and just use the
inner element instead for any future reference. The race condition is
still there since it's a race condition whether we added the wrapper in
the first place.

This just makes it consistent with unwrapping of the rest of the path.
2025-09-19 18:23:18 -04:00
Hendrik Liebau
d415fd3ed7 [Flight] Handle Lazy in renderDebugModel (#34536)
If we don't handle Lazy types specifically in `renderDebugModel`, all of
their properties will be emitted using `renderDebugModel` as well. This
also includes its `_debugInfo` property, if the Lazy comes from the
Flight client. That array might contain objects that are deduped, and
resolving those references in the client can cause runtime errors, e.g.:

```
TypeError: Cannot read properties of undefined (reading '$$typeof')
```

This happened specifically when an "RSC stream" debug info entry, coming
from the Flight client through IO tracking, was emitted and its
`debugTask` property was deduped, which couldn't be resolved in the
client.

To avoid actually initializing a lazy causing a side-effect, we make
some assumptions about the structure of its payload, and only emit
resolved or rejected values, otherwise we emit a halted chunk.
2025-09-19 23:38:11 +02:00
Jack Pope
5e3cd53f20 Update MAINTAINERS (#34534) 2025-09-19 15:49:08 -04:00
Janka Uryga
01cad9eaca [Flight] Support Async Modules in Turbopack Server References (#34531)
Seems like this was missed in
https://github.com/facebook/react/pull/31313
2025-09-19 12:12:37 -07:00
Eugene Choi
6eda534718 [playground] bug fixes & UX improvements (#34499)
<!--
  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

Made many small changes to the compiler playground to improve user
experience. Removed any "Loading" indicators that would flash in before
a component would finish loading in. Additionally, before users would
see the "Show Internals" button toggling from false to true if they had
set it at true previously. I was able to refactor the URL/local storage
loading so that the `Store` would be fully initialized before the
components would load in.

Attempted to integrate `<Activity>` into showing/hiding these different
editors, but the current state of [monaco
editors](https://github.com/suren-atoyan/monaco-react) does not allow
for this. I created an issue for them to address:
https://github.com/suren-atoyan/monaco-react/issues/753

Added a debounce to the config editor so every key type wouldn't cause
the output panel to respond instantly. Users can type for 500 ms before
an error is thrown at them.

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

## How did you test this change?

Here is what loading the page would look like before (not sure why its
so blurry):


https://github.com/user-attachments/assets/58f4281a-cc02-4141-b9b5-f70d6ace12a2


Here is how it looks now:


https://github.com/user-attachments/assets/40535165-fc7c-44fb-9282-9c7fa76e7d53

Here is the debouncing:


https://github.com/user-attachments/assets/e4ab29e4-1afd-4249-beca-671fb6542f5e



<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->
2025-09-18 15:44:25 -04:00
Hendrik Liebau
c03a51d836 Move getDebugInfo test util function to internal-test-utils (#34523)
In an upstack PR, I need `getDebugInfo` in another test file, so I'm
moving it to `internal-test-utils` so it can be shared.
2025-09-18 21:32:36 +02:00
Sebastian Markbåge
ad578aa01f Log Suspended startViewTransition Phase (#34511)
Stacked on #34510.

The "Commit" phase for a View Transition starts before the snapshot
phase (before mutation) and then stretches into the async gap of
`startViewTransition`, encompasses the mutation phase inside of its
update callback and finally the layout phase.

However, between the mutation phase and the layout phase we may suspend
the start of the view transition on fonts and/or images. In that case we
now split the Commit phase into first one before we suspend and then we
log "Waiting for Images and/or Fonts" and then another Commit phase
around the layout effects.

<img width="897" height="119" alt="Screenshot 2025-09-16 at 11 37 26 PM"
src="https://github.com/user-attachments/assets/0fe21388-bb48-4456-a594-62227d12d9b7"
/>
2025-09-18 15:25:41 -04:00
Sebastian "Sebbie" Silbermann
03a96c75db [DevTools] Record Suspense node for roots in legacy renderers (#34516) 2025-09-18 18:50:23 +02:00
Sebastian "Sebbie" Silbermann
755cebad6b [DevTools] Elevate Suspense rects to visualize hierarchy (#34455) 2025-09-18 18:37:00 +02:00
zeki
581321160f [Compiler Bug] Complier mark ts instantiation expression as reorderable in build hir (#34488)
<!--
  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

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
--> The React Compiler rejected a default parameter that contains a
TSInstantiationExpression with the todo message that the expression
cannot be safely reordered. This change teaches the reorder check in
BuildHIR.ts to treat TSInstantiationExpression as reorderable. This is
safe because TypeScript instantiation only affects types and is erased
at runtime, so it has no side effects and does not change semantics.

## How did you test this change?

```
Set-Content testfilter.txt 'ts-instantiation-default-param'

yarn test --filter --update

yarn test --filter
```


<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
--> I added a fixture: 
>
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ts-instantiation-default-param.js
2025-09-18 09:34:47 -07:00
Joseph Savona
1bcdd224b1 [compiler] Don't show hint about ref-like naming if we infer another type (#34521)
Some components accept a union of a ref callback function or ref object.
In this case we may infer the type as a function due to the presence of
invoking the ref callback function. In that case, we currently report a
"Hint: name `fooRef` as "ref" or with a "-Ref" suffix..." even though
the variable is already named appropriately — the problem is that we
inferred a non-ref type. So here we check the type and don't report this
hint if we inferred another type.
2025-09-18 09:26:10 -07:00
Sebastian Markbåge
84af9085c1 Log Performance Track Entries for View Transitions (#34510)
Stacked on #34509.

View Transitions introduces a bunch of new types of gaps in the commit
phase which needs to be logged differently in the performance track.

One thing that can happen is that a `flushSync` update forces the View
Transition to abort before it has started if it happens in the gap
before the transition is ready. In that case we log "Interrupted View
Transition".

Otherwise, when we're done in `startViewTransition` there's some work to
finalize the animations before the `ready` calllback. This is logged as
"Starting Animation".

Then there's a gap before the passive effects fire which we log as
"Animating". This can be long unless they're forced to flush early e.g.
due to another lane updating.

The "Animating" track should then pick up which doesn't do yet. This one
is tricky because this is after the actual commit phase and needs to be
interrupted by new renders which themselves can be suspended on the
animation finshing.

This PR is just a subset of all the cases. Will need a lot more work.

<img width="679" height="161" alt="Screenshot 2025-09-16 at 10 19 06 PM"
src="https://github.com/user-attachments/assets/0407372d-aaed-41f5-a262-059b2686ae87"
/>
2025-09-17 13:06:30 -04:00
Sebastian "Sebbie" Silbermann
128abcfa01 [DevTools] Don't inline workers for extensions (#34508) 2025-09-17 17:59:55 +02:00
Sebastian Markbåge
e3c9656d20 Ensure Performance Track are Clamped and Don't overlap (#34509)
This simplifies the logic for clamping the start times of various
phases. Instead of checking in multiple places I ensure we compute a
value for each phase that is then clamped to the next phase so they
don't overlap. If they're zero they're not printed.

I also added a name for all the anonymous labels. Those are mainly
fillers for sync work that should be quick but it helps debugging if we
can name them.

Finally the real fix is to update the clamp time which previously could
lead to overlapping entries for consecutive updates when a previous
update never finalized before the next update.
2025-09-17 10:52:02 -04:00
Sebastian "Sebbie" Silbermann
27b4076ab0 [DevTools] Use a single Webpack config for the extensions (#34513) 2025-09-17 15:45:25 +02:00
Sebastian "Sebbie" Silbermann
81d66927af [DevTools] Stop polyfilling Buffer (#34512) 2025-09-17 15:36:21 +02:00
Sebastian "Sebbie" Silbermann
6a4c8f51fa [DevTools] Store Webpack stats when building extensions (#34514) 2025-09-17 15:03:12 +02:00
Sebastian "Sebbie" Silbermann
16df13b84c [DevTools] Minify backend (#34507) 2025-09-17 14:52:32 +02:00
Joseph Savona
7899729130 [compiler] Option to treat "set-" prefixed callees as setState functions (#34505)
Calling setState functions during render can lead to extraneous renders
or even infinite loops. We also have runtime detection for loops, but
static detection is obviously even better.

This PR adds an option to infer identifers as setState functions if both
the following conditions are met:
- The identifier is named starting with "set"
- The identifier is used as the callee of a call expression

By inferring values as SetState type, this allows our existing
ValidateNoSetStateInRender rule to flag calls during render, disallowing
examples like the following:

```js
function Component({setParentState}) {
  setParentState(...);
  ^^^^^^^^^^^^^^ Error: Cannot call setState in render
}
```
2025-09-16 15:48:27 -07:00
Sebastian "Sebbie" Silbermann
a51f925217 [DevTools] Only check if we previously removed IO if its removal failed (#34506) 2025-09-16 19:55:03 +02:00
Sebastian "Sebbie" Silbermann
941cd803a7 [DevTools] Don't keep stale root instances we never mounted around (#34504) 2025-09-16 19:17:28 +02:00
Sebastian "Sebbie" Silbermann
851bad0c88 [DevTools] Ignore repeated removals of the same IO (#34495) 2025-09-16 18:54:52 +02:00
Sebastian Markbåge
5e0c951b58 Add forwards fill mode to animations in view transition fixture (#34502)
It turns out that View Transitions can sometimes overshoot and then we
need to ensure it fills. It can otherwise sometimes flash in Chrome.

This is something users might hit as well.
2025-09-16 10:20:40 -04:00
Sebastian Markbåge
348a4e2d44 [Fiber] Wait for suspensey image in the viewport before starting an animation (#34500)
Stacked on #34486.

If we gave up on loading suspensey images for blocking the commit (e.g.
due to #34481), we can still block the view transition from committing
to allow an animation to include the image from the start.

At this point we have more information about the layout so we can
include only the images that are within viewport in the calculation
which may end up with a different answer.

This only applies when we attempt to run an animation (e.g. something
mutated inside a `<ViewTransition>` in a Transition). We could attempt a
`startViewTransition` if we gave up on the suspensey images just so that
we could block it even if no animation would be running.

However, this point the screen is frozen and you can no longer have sync
updates interrupt so ideally we would have already blocked the commit
from happening in the first place.

The reason to have two points where we block is that ideally we leave
the UI responsive while blocking, which blocking the commit does. In the
simple case of all images or a single image being within the viewport,
that's favorable. By combining the techniques we only end up freezing
the screen in the special case that we had a lot of images added outside
the viewport and started an animation with some image inside the
viewport (which presumably is about to finish anyway).
2025-09-15 18:11:04 -04:00
Sebastian Markbåge
5d49b2b7f4 [Fiber] Track SuspendedState on stack instead of global (#34486)
Stacked on #34481.

We currently track the suspended state temporarily with a global which
is safe as long as we always read it during a sync pass. However, we
sometimes read it in closures and then we have to be carefully to pass
the right one since it's possible another commit on a different root has
started at that point. This avoids this footgun.

Another reason to do this is that I want to read it in
`startViewTransition` which is in an async gap after which point it's no
longer safe. So I have to pass that through the `commitRoot` bound
function.
2025-09-15 16:10:47 -04:00
Sebastian Markbåge
ae22247dce [Fiber] Don't wait on Suspensey Images if we guess that we don't load them all in time anyway (#34481)
Stacked on #34478.

In general we don't like to deal with timeouts in suspense world. We've
had that in the past but in general it doesn't work well because if you
have a timeout and then give up you made everything wait longer for no
benefit at the end. That's why the recommendation is to remove a
Suspense boundary if you expect it to be fast and add one if you expect
it to be slow. You have to estimate as the developer.

Suspensey images suffer from this same problem. We want to apply
suspensey images to as much as possible so that it's the default to
avoid flashing because if just a few images flash it's still almost as
bad as all of them. However, we do know that it's also very common to
use images and on a slow connection or many images, it's not worth it so
we have the timeout to eventually give up.

However, this means that in cases that are always slow or connections
that are always slow, you're always punished for no reason.

Suspensey images is mainly a polish feature to make high end experiences
on high end connections better but we don't want to unnecessarily punish
all slow connections in the process or things like lots of images below
the viewport.

This PR adds an estimate for whether or not we'll likely be able to load
all the images within the timeout on a high end enough connection. If
not, we'll still do a short suspend (unless we've already exceeded the
wait time adjusted for #34478) to allow loading from cache if available.

This estimate is based on two heuristics:

1) We compute an estimated bandwidth available on the current device in
mbps. This is computed from performance entries that have loaded static
resources already on the site. E.g. this can be other images, css, or
scripts. We see how long they took. If we don't have any entries (or if
they're all cross-origin in Safari) we fallback to
`navigator.connection.downlink` in Chrome or a 5mbps default in
Firefox/Safari.
2) To estimate how many bytes we'll have to download we use the
width/height props of the img tag if available (or a 100 pixel default)
times the device pixel ratio. We assume that a good img implementation
downloads proper resolution image for the device and defines a
width/height up front to avoid layout trash. Then we estimate that it
takes about 0.25 bytes per pixel which is somewhat conservative
estimate.

This is somewhat conservative given that the image could've been
preloaded and be better compressed.

So it really only kicks in for high end connections that are known to
load fast.

In a follow up, we can add an additional wait for View Transitions that
does the same estimate but only for the images that turn out to be in
viewport.
2025-09-15 16:08:59 -04:00
Sebastian Markbåge
e3f191803c [Fiber] Adjust the suspensey image/css timeout based on already elapsed time (#34478)
Currently suspensey images doesn't account for how long we've already
been waiting. This means that you can for example wait for 300ms for the
throttle + 500ms for the images. If a Transition takes a while to
complete you can also wait that time + an additional 500ms for the
images.

This tracks the start time of a Transition so that we can count the
timeout starting from when the user interacted or when the last fallback
committed (which is where the 300ms throttle is computed from). Creating
a single timeline.

This also moves the timeout to a central place which I'll use in a
follow up.
2025-09-15 16:05:20 -04:00
Cody Olsen
e12b0bdc3b [compiler]: add @tanstack/react-virtual to known incompatible libraries (#34493)
Replaces #31820. #34027 added a check for `@tanstack/react-table`, but
not `@tanstack/react-virtual`.
In our testing `@tanstack/react-virtual`'s `useVirtualizer` returns
functions that cannot be memoized, [this is also documented in the
community](https://github.com/TanStack/virtual/issues/736#issuecomment-3065658277).
2025-09-15 11:53:45 -07:00
Ruslan Lesiutin
92d7ad5dd9 [DevTools] fix: validate url in file fetcher bridging calls (#34498)
This was prone to races and sometimes messed up symbolication when
multiple source maps were fetched simultaneously.
2025-09-15 18:14:09 +01:00
Eugene Choi
67a44bcd1b Playground applied configs (#34474)
<!--
  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
Added an "Applied Configs" section under the Config Overrides panel.
Users will now be able to see the full list of configs applied to the
compiler in the playground. Adds greater discoverability for config
options to override as well. Updated the default config as well to be a
commented config option, so users will start with empty overrides.

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

## How did you test this change?


https://github.com/user-attachments/assets/1a57b2d5-0405-4fc8-9990-1747c30181c0


<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->
2025-09-15 12:13:28 -04:00
Sebastian "Sebbie" Silbermann
3fa927b674 Fix some DevTools regression test actions and assertions (#34459) 2025-09-15 15:31:58 +02:00
Sebastian "Sebbie" Silbermann
47664deb8e Allow running download_devtools_regression_build.js on a clean repo (#34456) 2025-09-13 11:07:36 +02:00
Sebastian "Sebbie" Silbermann
5502d85cc7 [DevTools] Unmount fallbacks in the context of the parent Suspense (#34475)
Co-authored-by: Ruslan Lesiutin <hoxy@meta.com>
2025-09-13 11:03:32 +02:00
Ricky
8a8e9a7edf move devtools notify to different channel (#34476) 2025-09-12 14:14:25 -04:00
Ricky
68f00c901c Release Activity in Canary (#34374)
## Overview

This PR ships `<Activity />` to the `react@canary` release channel for
final feedback and prepare for semver stable release.

## What this means

Shipping `<Activity />` to canary means it has gone through extensive
testing in production, we are confident in the stability of the feature,
and we are preparing to release it in a future semver stable version.

Libraries and frameworks following the [Canary
Workflow](https://react.dev/blog/2023/05/03/react-canaries) should begin
implementing and testing the feature.

## Why we follow the Canary Workflow

To prepare for semver stable, libraries should test canary features like
`<Activity>` with `react@canary` to confirm compatibility and prepare
for the next semver release in a myriad of environments and
configurations used throughout the React ecosystem. This provides
libraries with ample time to catch any issues we missed before slamming
them with problems in the wider semver release.

Since these features have already gone through extensive production
testing, and we are confident they are stable, frameworks following the
[Canary Workflow](https://react.dev/blog/2023/05/03/react-canaries) can
also begin adopting canary features like `<Activity />`.

This adoption is similar to how different Browsers implement new
proposed browser features before they are added to the standard. If a
frameworks adopts a canary feature, they are committing to stability for
their users by ensuring any API changes before a semver stable release
are opaque and non-breaking to their users.

Apps not using a framework are also free to adopt canary features like
Activity as long as they follow the [Canary
Workflow](https://react.dev/blog/2023/05/03/react-canaries), but we
generally recommend waiting for a semver stable release unless you have
the capacity to commit to following along with the canary changes and
debugging library compatibility issues.

Waiting for semver stable means you're able to benefit from libraries
testing and confirming support, and use semver as signal for which
version of a library you can use with support of the feature.

## Docs 

Check out the ["React Labs: View Transitions, Activity, and
more"](https://react.dev/blog/2025/04/23/react-labs-view-transitions-activity-and-more#activity)
blog post, and [the new docs for
`<Activity>`](https://react.dev/reference/react/Activity) for more info.

## TODO
- [x] Bump Activity docs to Canary
https://github.com/reactjs/react.dev/pull/7974

---------

Co-authored-by: Sebastian Sebbie Silbermann <sebastian.silbermann@vercel.com>
2025-09-12 12:47:40 -04:00
Sebastian Markbåge
93d7aa69b2 [Fiber] Add context for the display: inline warning (#34461)
This warning doesn't execute within any particular context so doesn't
have a stack.

Pick the fiber of the child if it exists, otherwise the parent.

<img width="846" height="316" alt="Screenshot 2025-09-10 at 12 38 28 PM"
src="https://github.com/user-attachments/assets/7ab283a9-6e11-428d-9def-38f80ca958ef"
/>
2025-09-12 11:55:25 -04:00
Sebastian Markbåge
20e5431747 [Flight][Fiber] Encode owner in the error payload in dev and use it as the Error's Task (#34460)
When we report an error we typically log the owner stack of the thing
that caught the error. Similarly we restore the `console.createTask`
scope of the catching component when we call `reportError` or
`console.error`.

We also have a special case if something throws during reconciliation
which uses the Server Component task as far as we got before we threw.


https://github.com/facebook/react/blob/main/packages/react-reconciler/src/ReactChildFiber.js#L1952-L1960

Chrome has since fixed it (on our request) that the Error constructor
snapshots the Task at the time the constructor was created and logs that
in `reportError`. This is a good thing since it means we get a coherent
stack. Unfortunately, it means that the fake Errors that we create in
Flight Client gets a snapshot of the task where they were created so
when they're reported in the console they get the root Task instead of
the Task of the handler of the error.

Ideally we'd transfer the Task from the server and restore it. However,
since we don't instrument the Error object to snapshot the owner and we
can't read the native Task (if it's even enabled on the server) we don't
actually have a correct snapshot to transfer for a Server Component
Error. However, we can use the parent's task for where the error was
observed by Flight Server and then encode that as a pseudo owner of the
Error.

Then we use this owner as the Task which the Error is created within.
Now the client snapshots that Task which is reported by `reportError` so
now we have an async stack for Server Component errors again. (Note that
this owner may differ from the one observed by `captureOwnerStack` which
gets the nearest Server Component from where it was caught. We could
attach the owner to the Error object and use that owner when calling
`onCaughtError`/`onUncaughtError`).

Before:

<img width="911" height="57" alt="Screenshot 2025-09-10 at 10 57 54 AM"
src="https://github.com/user-attachments/assets/0446ef96-fad9-4e17-8a9a-d89c334233ec"
/>

After:

<img width="910" height="128" alt="Screenshot 2025-09-10 at 11 06 20 AM"
src="https://github.com/user-attachments/assets/b30e5892-cf40-4246-a588-0f309575439b"
/>

Similarly, there are Errors and warnings created by ChildFiber itself.
Those execute in the scope of the general render of the parent Fiber.
They used to get the scope of the nearest client component parent (e.g.
div in this case) but that's the parent of the Server Component. It
would be too expensive to run every level of reconciliation in its own
task optimistically, so this does it only when we know that we'll throw
or log an error that needs this context. Unfortunately this doesn't
cover user space errors (such as if an iterable errors).

Before:

<img width="903" height="298" alt="Screenshot 2025-09-10 at 11 31 55 AM"
src="https://github.com/user-attachments/assets/cffc94da-8c14-4d6e-9a5b-bf0833b8b762"
/>

After:

<img width="1216" height="252" alt="Screenshot 2025-09-10 at 11 50
54 AM"
src="https://github.com/user-attachments/assets/f85f93cf-ab73-4046-af3d-dd93b73b3552"
/>

<img width="412" height="115" alt="Screenshot 2025-09-10 at 11 52 46 AM"
src="https://github.com/user-attachments/assets/a76cef7b-b162-4ecf-9b0a-68bf34afc239"
/>
2025-09-12 11:55:07 -04:00
Eugene Choi
1a27af3607 [playground] Update the playground UI (#34468)
<!--
  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

Updated the UI of the React compiler playground. The config, Input, and
Output panels will now span the viewport width when "Show Internals" is
not toggled on. When "Show Internals" is toggled on, the old vertical
accordion tabs are still used. Going to add support for the "Applied
Configs" tabs underneath the "Config Overrides" tab next.

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

## How did you test this change?


https://github.com/user-attachments/assets/b8eab028-f58c-4cb9-a8b2-0f098f2cc262


<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->
2025-09-12 11:43:04 -04:00
Ruslan Lesiutin
0e10ee906e [Reconciler] Set ProfileMode for Host Root Fiber by default in dev (#34432)
Requiring DevTools to be present for dev builds seems like an overkill,
let's enable the instrumentation by default.

Nothing changes for profiling or production artifacts.
2025-09-12 12:20:39 +01:00
Ruslan Lesiutin
0c813c528d [Tracks]: display method name and component name for updates in DEV (#34463)
For every "Update" entry we are going to add properties that will be
displayed when the user clicks on that entry: name of the method that
caused this first update and name of the component where this update
happened.

We could use the name of the component as a deeplink to React DevTools
components panel in the future, once we support stable identificators on
Fibers.

<img width="1444" height="530" alt="Screenshot 2025-09-10 at 18 31 10"
src="https://github.com/user-attachments/assets/7f9af037-2e7f-4e7b-9b7e-bf9f7d5a6e72"
/>
<img width="2088" height="530" alt="Screenshot 2025-09-10 at 18 24 21"
src="https://github.com/user-attachments/assets/f557a173-bd9b-43f7-9333-74066f433ced"
/>
<img width="2088" height="530" alt="Screenshot 2025-09-10 at 18 26 04"
src="https://github.com/user-attachments/assets/ff37d13f-bbe3-4f85-800e-81aa3aed7833"
/>
2025-09-12 11:34:41 +01:00
Sebastian "Sebbie" Silbermann
a9ad64c852 [DevTools] Stop mounting empty roots (#34467) 2025-09-11 20:00:53 +02:00
Sebastian "Sebbie" Silbermann
7fc888dde2 [DevTools] Stop recording reorders in disconnected subtrees (#34464) 2025-09-11 19:13:14 +02:00
Sebastian "Sebbie" Silbermann
67415c8c4a [DevTools] Stop using native title for buttons/icons (#34379) 2025-09-11 18:49:35 +02:00
Hendrik Liebau
f3a803617e [Flight] Ensure async info owners are outlined properly (#34465)
When we emit objects of type `ReactAsyncInfo`, we need to make sure that
their owners are outlined, using `outlineComponentInfo`. Otherwise we
would end up accidentally emitting stashed fields that are not part of
the transport protocol, specifically `debugStack`, `debugTask`, and
`debugLocation`. This would lead to runtime errors in the client, when
for example, the stack for a `debugLocation` is processed in
`buildFakeCallStack`, but the stack was actually omitted from the RSC
payload, because for those fields we don't ensure that the object limit
is increased by the length of the stack, as we do when we're emitting
the `stack` of a `ReactComponentInfo` object in `outlineComponentInfo`.
2025-09-11 18:10:25 +02:00
Eugene Choi
fe84397e81 [compiler][playground] (4/N) Config override panel (#34436)
<!--
  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

Removed the old `OVERRIDE` pragma to make the source of truth for config
overrides in the left-hand pane. Now, it will automatically update the
output pane each time there is an edit to the config. The old pragma
format is still supported, but it will be overwritten by the config pane
if they are modifying the same flags. Removed the gating on the config
panel so now all users will automatically be able to view it, but it
will be initially collapsed.

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

## How did you test this change?


https://github.com/user-attachments/assets/9d4512b9-e203-4ce0-ae95-dd96ff03bbc1


<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->
2025-09-11 11:51:32 -04:00
Sebastian "Sebbie" Silbermann
b1c519f3d4 [DevTools] Only show boundaries with unique suspenders by default in the timeline (#34397) 2025-09-11 11:33:05 +02:00
Sebastian "Sebbie" Silbermann
8c1501452c [DevTools] Preserve Suspense lineage when clicking through breadcrumbs (#34422) 2025-09-11 10:54:25 +02:00
Joseph Savona
bd9e6e0bed [compiler] More flexible/helpful lazy ref initialization (#34449)
Two small QoL improvements inspired by feedback:
* `if (ref.current === undefined) { ref.current = ... }` is now allowed.
* `if (!ref.current) { ref.current = ... }` is still disallowed, but we
emit an extra hint suggesting the `if (!ref.current == null)` pattern.

I was on the fence about the latter. We got feedback asking to allow `if
(!ref.current)` but if your ref stores a boolean value then this would
allow reading the ref in render. The unary form is also less precise in
general due to sketchy truthiness conversions. I figured a hint is a
good compromise.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34449).
* __->__ #34449
* #34424
2025-09-10 13:42:01 -07:00
lauren
835b00908b [compiler] Allow setStates in use{Layout,Insertion}Effect where the set value is derived from a ref (#34462)
@stipsan found this issue where the compiler would bailout on the
`useLayoutEffect` examples in the React docs. While setState in an
effect is typically an anti-pattern due to the fact that it hurts
performance through cascading renders, the one scenario where it _is_
allowed is if the value being set flows from a ref.
2025-09-10 14:56:04 -04:00
Ruslan Lesiutin
e2ba45bb39 [DevTools] fix: keep search query in a local sync state (#34423)
When the search query changes, we kick off a transition that updates the
search query in a reducer for TreeContext. The search input is also
using this value for an `input` HTML element.

For a larger applications, sometimes there is a noticeable delay in
displaying the updated search query. This changes the approach to also
keep a local synchronous state that is being updated on a change
callback.
2025-09-10 18:38:47 +01:00
Sebastian Markbåge
886b3d36d7 [DevTools] Show suspended by subtree from Activity to next Suspense boundary (#34438)
Stacked on #34435.

This adds a method to get all suspended by filtered by a specific
Instance. The purpose of this is to power the feature when you filter by
Activity. This would show you the "root" within that Activity boundary.

This works by selecting the nearest Suspense boundary parent and then
filtering its data based on if all the instances for a given I/O info is
within the Activity instance. If something suspended within the Suspense
boundary but outside the Activity it's not included even if it's also
suspending inside the Activity since we assume it would've already been
loaded then.

Right now I wire this up to be a special case when you select an
Activity boundary same as when you select a Suspense boundary in the
Components tab but we could also only use this when you select the root
in the Suspense tab for example.
2025-09-10 09:44:51 -04:00
Sebastian Markbåge
288d428af1 [DevTools] Only show the highest end/byteSize I/O of RSC streams (#34435)
Stacked on #34425.

RSC stream info is split into one I/O entry per chunk. This means that
when a single instance or boundary depends on multiple chunks, it'll
show the same stream multiple times. This makes it so just the last one
is shown.

This is a special case for the name "RSC stream" but ideally we'd more
explicitly model the concept of awaiting only part of a stream.

<img width="667" height="427" alt="Screenshot 2025-09-09 at 2 09 43 PM"
src="https://github.com/user-attachments/assets/890f6f61-4657-4ca9-82fd-df55a696bacc"
/>

Another remaining issue is that it's possible for an intermediate chunk
to be depended on by just a child boundary. In that case that can be
considered a "unique suspender" even though the parent depends on a
later one. Ideally it would dedupe on everything below. Could also model
it as every Promise depends on its chunk and every previous chunk.
2025-09-10 09:08:36 -04:00
Sebastian Markbåge
a34c5dff15 Ignore generic InvalidStateError in View Transitions (#34450)
Fixes #34098.

There's an issue in Chrome where the `InvalidStateError` always has the
same error message. The spec doesn't specify the error message to use
but it's more useful to have a specific one for each case like Safari
does.

One reason it's better to have a specific error message is because the
browser console is not the main surface that people look for errors.
Chrome relies on a separate log also in the console. Frameworks has
built-in error dialogs that pop up first and that's where you see the
error and that dialog can't show something specific. Additionally, these
errors can't log something specific to servers in production logging. So
this is a bad strategy.

It's not good to have those error dialogs pop up for non-actionable
errors like when it doesn't start because the document was hidden. Since
we don't have more specific information we have no choice but to hide
all of them. This includes actionable things like duplicate names
(although we also have a React specific warning for that in the common
case).
2025-09-10 09:07:11 -04:00
Sebastian Markbåge
3bf8ab430e Add missing Activity export to development mode (#34439)
This is exported in the prod version of ReactServer experimental but not
the development version so we can't use it in fixtures from Server
Components.
2025-09-09 21:30:37 -04:00
Joseph Savona
acada3035f [compiler] Fix false positive hook return mutation error (#34424)
This was fun. We previously added the MaybeAlias effect in #33984 in
order to describe the semantic that an unknown function call _may_ alias
its return value in its result, but that we don't know this for sure. We
record mutations through MaybeAlias edges when walking backward in the
data flow graph, but downgrade them to conditional mutations. See the
original PR for full context.

That change was sufficient for the original case like

```js
const frozen = useContext();
useEffect(() => {
  frozen.method().property = true;
}, [...]);
```

But it wasn't sufficient for cases where the aliasing occured between
operands:

```js
const dispatch = useDispatch();
<div onClick={(e) => {
  dispatch(...e.target.value)
  e.target.value = ...;
}} />
```

Here we would record a `Capture dispatch <- e.target` effect. Then
during processing of the `event.target.value = ...` assignment we'd
eventually _forward_ from `event` to `dispatch` (along a MaybeAlias
edge). But in #33984 I missed that this forward walk also has to
downgrade to conditional.

In addition to that change, we also have to be a bit more precise about
which set of effects we create for alias/capture/maybe-alias. The new
logic is a bit clearer, I think:

* If the value is frozen, it's an ImmutableCapture edge
* If the values are mutable, it's a Capture
* If it's a context->context, context->mutable, or mutable->context,
count it as MaybeAlias.
2025-09-09 14:07:47 -07:00
Sebastian Markbåge
969a9790ad [Flight] Track I/O Entry for the RSC Stream itself (#34425)
One thing that can suspend is the downloading of the RSC stream itself.
This tracks an I/O entry for each Promise (`SomeChunk<T>`) that
represents the request to the RSC stream. As the value we use the
`Response` for `createFromFetch` (or the `ReadableStream` for
`createFromReadableStream`). The start time is when you called those.

Since we're not awaiting the whole stream, each I/O entry represents the
part of the stream up until it got unblocked. However, in a production
environment with TLS packets and buffering in practice the chunks
received by the client isn't exactly at the boundary of each row. It's a
bit longer into larger chunks. From testing, it seems like multiples of
16kb or 64kb uncompressed are common. To simulate a production
environment we group into roughly 64kb chunks if they happen in rapid
sequence. Note that this might be too small to give a good idea because
of the throttle many boundaries might be skipped anyway so this might
show too many.

The React DevTools will see each I/O entry as separate but dedupe if an
outer boundary already depends on the same chunk. This deduping makes it
so that small boundaries that are blocked on the same chunk, don't get
treated as having unique suspenders. If you have a boundary with large
content, then that content will likely be in a separate chunk which is
not in the parent and then it gets marked as.

This is all just an approximation. The goal of this is just to highlight
that very large boundaries will very likely suspend even if they don't
suspend on any I/O on the server. In practice, these boundaries can
float around a lot and it's really any Suspense boundary that might
suspend but some are more likely than others which this is meant to
highlight.

It also just lets you inspect how many bytes needs to be transferred
before you can show a particular part of the content, to give you an
idea that it's not just I/O on the server that might suspend.

If you don't use the debug channel it can be misleading since the data
in development mode stream will have a lot more data in it which leads
to more chunking.

Similarly to "client references" these I/O infos don't have an "env"
since it's the client that has the I/O and so those are excluded from
flushing in the Server performance tracks.

Note that currently the same Response can appear many times in the same
Instance of SuspenseNode in DevTools when there are multiple chunks. In
a follow up I'll show only the last one per Response at any given level.

Note that when a separate debugChannel is used it has its own I/O entry
that's on the `_debugInfo` for the debug chunks in that channel.
However, if everything works correctly these should never leak into the
DevTools UI since they should never be propagated from a debug chunk to
the values waited by the runtime. This is easy to break though.
2025-09-09 16:46:11 -04:00
Joseph Savona
665de2ed28 [compiler] Improve name hints for outlined functions (#34434)
The previous PR added name hints for anonymous functions, but didn't
handle the case of outlined functions. Here we do some cleanup around
function `id` and name hints:
* Make `HIRFunction.id` a ValidatedIdentifierName, which involved some
cleanup of the validation helpers
* Add `HIRFunction.nameHint: string` as a place to store the generated
name hints which are not valid identifiers
* Update Codegen to always use the `id` as the actual function name, and
only use nameHint as part of generating the object+property wrapper for
debug purposes.

This ensures we don't conflate synthesized hints with real function
names. Then, we also update OutlineFunctions to use the function name
_or_ the nameHint as the input to generating a unique identifier. This
isn't quite as nice as the object form since we lose our formatting, but
it's a simple step that gives more context to the developer than `_temp`
does.

Switching to output the object+property lookup form for outlined
functions is a bit more involved, let's do that in a follow-up.
2025-09-09 12:14:09 -07:00
mofeiZ
eda778b8ae [compiler] Fix false positive memo validation (alternative) (#34319)
Alternative to #34276

---
(Summary taken from @josephsavona 's #34276)
Partial fix for #34262. Consider this example:

```js
function useInputValue(input) {
  const object = React.useMemo(() => {
    const {value} = transform(input);
    return {value};
  }, [input]);
  return object;
}
```

React Compiler breaks this code into two reactive scopes:
* One for `transform(input)`
* One for `{value}`

When we run ValidatePreserveExistingMemo, we see that the scope for
`{value}` has the dependency `value`, whereas the original memoization
had the dependency `input`, and throw an error that the dependencies
didn't match.

In other words, we're flagging the fact that memoized _better than the
user_ as a problem. The more complete solution would be to validate that
there is a subgraph of reactive scopes with a single input and output
node, where the input node has the same dependencies as the original
useMemo, and the output has the same outputs. That is true in this case,
with the subgraph being the two consecutive scopes mentioned above.

But that's complicated. As a shortcut, this PR checks for any
dependencies that are defined after the start of the original useMemo.
If we find one, we know that it's a case where we were able to memoize
more precisely than the original, and we don't report an error on the
dependency. We still check that the original _output_ value is able to
be memoized, though. So if the scope of `object` were extended, eg with
a call to `mutate(object)`, then we'd still correctly report an error
that we couldn't preserve memoization.

Co-authored-by: Joe Savona <joesavona@fb.com>
2025-09-09 14:26:52 -04:00
Jorge Cabiedes
1836b46fff [compiler] Have react-compiler eslint plugin return a RuleModule (#34421)
Eslint is expecting a map of [string] => RuleModule. Before we were
passing {rule: RuleModule, severity: ErrorSeverity} which was breaking
legacy Eslint configurations
2025-09-09 11:18:37 -07:00
Sebastian "Sebbie" Silbermann
eec50b17b3 [Flight] Only use debug component info for parent stacks (#34431) 2025-09-09 19:58:02 +02:00
Joseph Savona
a9410fb487 [compiler] Option to infer names for anonymous functions (#34410)
Adds a `@enableNameAnonymousFunctions` feature to infer helpful names
for anonymous functions within components and hooks. The logic is
inspired by a custom Next.js transform, flagged to us by @eps1lon, that
does something similar. Implementing this transform within React
Compiler means that all React (Compiler) users can benefit from more
helpful names when debugging.

The idea builds on the fact that JS engines try to infer helpful names
for anonymous functions (in stack traces) when those functions are
accessed through an object property lookup:

```js
({'a[xyz]': () => {
  throw new Error('hello!')
} }['a[xyz]'])()

// Stack trace:
Uncaught Error: hello!
    at a[xyz] (<anonymous>:1:26) // <-- note the name here
    at <anonymous>:1:60
```

The new NameAnonymousFunctions transform is gated by the above flag,
which is off by default. It attemps to infer names for functions as
follows:

First, determine a "local" name:
* Assigning a function to a named variable uses the variable name.
`const f = () => {}` gets the name "f".
* Passing the function as an argument to a function gets the name of the
function, ie `foo(() => ...)` get the name "foo()", `foo.bar(() => ...)`
gets the name "foo.bar()". Note the parenthesis to help understand that
it was part of a call.
* Passing the function to a known hook uses the name of the hook,
`useEffect(() => ...)` uses "useEffect()".
* Passing the function as a JSX prop uses the element and attr name, eg
`<div onClick={() => ...}` uses "<div>.onClick".

Second, the local name is combined with the name of the outer
component/hook, so the final names will be strings like `Component[f]`
or `useMyHook[useEffect()]`.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34410).
* #34434
* __->__ #34410
2025-09-09 10:22:19 -07:00
Sebastian "Sebbie" Silbermann
6b70072c4f [DevTools] Finalize heuristic for naming unnamed <Suspense> (#34428) 2025-09-09 17:56:26 +02:00
Ruslan Lesiutin
b2cff47472 [DevTools] feat: propagate fetchFileWithCaching from initialization options for Fusebox (#34429)
Each integrator: browser extension, Chrome DevTools Frontend fork,
Electron shell must define and provide `fetchFileWithCaching` in order
for DevTools to be able to fetch application resources, such as scripts
or source maps.

More specifically, if this is available, React DevTools will be able to
symbolicate source locations for component frames, owner stacks,
"suspended by" Promises call frames.

This will be available with the next release of React DevTools.
2025-09-09 13:00:53 +01:00
Sebastian "Sebbie" Silbermann
8943025358 [DevTools] Fix handling of host roots on mount (#34400) 2025-09-08 22:53:02 +02:00
Eugene Choi
3d9d22cbdb [playground] Fix CompilerError mismatch (#34420)
The compiler playground was crashing at any small syntax errors in the
`Input` panel due to updating the `CompilerErrorDetailOptions` type in
#34401. Updated the option to take in a `ErrorCategory` instead.

---------

Co-authored-by: lauren <poteto@users.noreply.github.com>
2025-09-08 15:06:54 -04:00
Eugene Choi
d4374b3ae3 [compiler] [playground] Show internals toggle (#34399)
<!--
  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

Added a "Show Internals" toggle switch to either show only the Config,
Input, Output, and Source Map tabs, or these tabs + all the additional
compiler options. The open/close state of these tabs will be preserved
(unless on page refresh, which is the same as the currently
functionality).


<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

## How did you test this change?

<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->



https://github.com/user-attachments/assets/8eb0f69e-360c-4e9b-9155-7aa185a0c018
2025-09-08 14:21:03 -04:00
Joseph Savona
3f2a42a5de [compiler] Handle empty list of eslint suppression rules (#34323)
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34323).
* #34276
* __->__ #34323
2025-09-08 10:33:10 -07:00
Sebastian Markbåge
294c33f34d [Flight] Always initialize a debug info array for each Chunk (#34419)
I'm about to add info for pretty much all of these anyway since they all
depend on the data stream itself.
2025-09-08 12:28:14 -04:00
Sebastian "Sebbie" Silbermann
3fb190f729 [DevTools] Avoid renders of stale Suspense store (#34396) 2025-09-08 11:42:03 +02:00
Joseph Savona
f5e96b9740 [compiler] Add missing source locations to statements, expressions (#34406)
Adds missing locations to all the statement kinds that we produce in
codegenInstruction(), and adds generic handling of source locations for
the nodes produced by codegenInstructionValue(). There are definitely
some places where we are still missing a location, but this should
address some of the known issues we've seen such as missing location on
`throw`.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34406).
* #34394
* __->__ #34406
* #34346
2025-09-06 11:14:30 -07:00
lauren
78992521a8 [compiler] Filter out disabled errors from being reported (#34409)
This PR stops error details of severity `ErrorSeverity.Off` from being
reported.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34409).
* __->__ #34409
* #34404
2025-09-06 13:07:23 -04:00
lauren
80d7aa17ad [compiler] Fix error description inconsistency (#34404)
Small fix to make all descriptions consistently printed with a single
period at the end.

Ran `grep -rn "description:" packages/babel-plugin-react-compiler/src
--include="*.ts" --exclude-dir="__tests__" | grep '\.\s*["\`]'` to find
all descriptions ending in a period and manually fixed them.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34404).
* #34409
* __->__ #34404
2025-09-06 13:07:02 -04:00
lauren
474f25842a [compiler] Migrate CompilerError.invariant to new CompilerDiagnostic infra (#34403)
Mechanical PR to migrate existing invariants to use the new
CompilerDiagnostic infra @josephsavona added. Will tackle the others at
a later time.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34403).
* #34409
* #34404
* __->__ #34403
2025-09-06 12:58:08 -04:00
lauren
1fef581e1a [compiler] Deprecate CompilerErrorDetail (#34402)
Now that we have a new CompilerDiagnostic type (which the CompilerError
aggregate can hold), the old CompilerErrorDetail type can be marked as
deprecated. Eventually we should migrate everything to the new
CompilerDiagnostic type.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34402).
* #34409
* #34404
* #34403
* __->__ #34402
* #34401
2025-09-06 12:41:54 -04:00
lauren
60d9b9740d [compiler] Derive ErrorSeverity from ErrorCategory (#34401)
With #34176 we now have granular lint rules created for each compiler
ErrorCategory. However, we had remnants of our old error severities
still in use which makes reporting errors quite clunky. Previously you
would need to specify both a category and severity which often ended up
being the same.

This PR moves severity definition into our rules which are generated
from our categories. For now I decided to defer "upgrading" categories
from a simple string to a sum type since we are only using severities to
map errors to eslint severity.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34401).
* #34409
* #34404
* #34403
* #34402
* __->__ #34401
2025-09-06 12:41:29 -04:00
KimCookieYa
c4e2508dad [react-devtools-shared] Fix URL construction when base URL is invalid (#34407)
### Problem
- Users encounter “Failed to construct 'URL': Invalid base URL” when
clicking the “View source” action in DevTools if the underlying base URL
is invalid.
- This exception originates from `new URL(relative, base)` and bubbles
up, interrupting the DevTools UI.
- Fixes GitHub issue
[#34317](https://github.com/facebook/react/issues/34317)

### Solution
- Wrap URL construction to:
  - First try `new URL(sourceMapAt, sourceURL)`.
  - If that fails, try `new URL(sourceMapAt)` as an absolute URL.
  - If both fail, return `null` (no symbolication) rather than throwing.
- This preserves normal behavior for valid bases and absolute URLs,
while avoiding crashes for invalid bases.

### Implementation details
- Updated `symbolicateSource` in
`packages/react-devtools-shared/src/symbolicateSource.js` to handle
invalid base URL scenarios without throwing.
- Added/verified tests in
`packages/react-devtools-shared/src/__tests__/utils-test.js`:
- “should not throw for invalid base URL with relative source map” →
resolves to `null`.
- “should resolve absolute source map even if base URL is invalid” →
still resolves correctly.

### Test plan
- Lint/format:
  - `yarn prettier-check`
  - `yarn linc`
- Type checking:
  - `yarn flow dom-node`
- Unit tests:
  - `yarn test --watchAll=false utils-test`
  - Optionally: `yarn test --watchAll=false utils-test inspectedElement`
- All of the above pass locally for experimental channel.

### Risks and rollout
- Risk: Low. Only affects cases where the base URL is invalid.
- Normal cases (valid base or absolute `sourceMappingURL`) are
unchanged.
- No user-facing API changes; DevTools UX becomes more resilient.

### Affected packages
- `react-devtools-shared`

### Related
- Fixes GitHub issue
[#34317](https://github.com/facebook/react/issues/34317)

### Checklist
- [x] Ran `yarn prettier-check`
- [x] Ran `yarn linc`
- [x] Ran `yarn flow dom-node`
- [x] Relevant unit tests passing
- [x] Linked issue and added a concise summary


<!--
  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

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

## How did you test this change?

<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->
2025-09-06 14:00:45 +01:00
Eugene Choi
de5a1b203e [compiler][playground] (3/N) Config override panel (#34371)
<!--
  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

Part 3 of adding a "Config Override" panel to the React compiler
playground. Added a button to apply config changes to the Input panel,
as well as making the tab collapsible. Added validation for the the
PluginOptions type (although comes with a bit more boilerplate) to make
it very obvious what the possible config errors could be. Added some
toasts for trying to apply broken configs.

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->

## How did you test this change?


https://github.com/user-attachments/assets/63ab8636-396f-45ba-aaa5-4136e62ccccc


<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->
2025-09-05 10:12:01 -04:00
Sebastian "Sebbie" Silbermann
b9a045368b [DevTools] Allow inspecting root when navigating Suspense timeline (#34380) 2025-09-04 16:42:25 +02:00
Sebastian "Sebbie" Silbermann
e2cc315a1b [DevTools] Don't suspend shell while retrieving original source for "open-in-editor" (#34381) 2025-09-04 16:39:07 +02:00
Sebastian "Sebbie" Silbermann
5a31758ed6 [DevTools] Allow inspection before streaming has finished in Chrome (#34360) 2025-09-04 12:21:06 +02:00
Sebastian "Sebbie" Silbermann
ba6590dd7c [DevTools] Rerender boundaries when they unsuspend when advancing the timeline (#34359) 2025-09-04 10:49:16 +02:00
Joseph Savona
2710795a1e [compiler] Cleanup for @enablePreserveExistingMemoizationGuarantees (#34346)
I tried turning on `@enablePreserveExistingMemoizationGuarantees` by
default and cleaned up a couple small things:

* We emit freeze calls for StartMemoize deps but these had
ValueReason.Other so the message wasn't great. We now treat these like
other hook arguments.
* PruneNonEscapingScopes was being too aggressive in this mode and
memoizing even loads of globals. Switching to
MemoizationLevel.Conditional ensures we build a graph that connects
through to primitive-returning function calls, but doesn't unnecessarily
force memoization otherwise.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34346).
* #34347
* __->__ #34346
2025-09-03 21:30:52 -07:00
Joseph Savona
735e9ac54e [compiler] enablePreserveExistingMemo memoizes primitive-returning functions (#34343)
`@enablePreserveExistingMemoizationGuarantees` mode currently does not
guarantee memoization of primitive-returning functions. We're often able
to infer that a function returns a primitive based on how its result is
used, for example `foo() + 1` or `object[getIndex()]`, and by default we
do not currently memoize computation that produces a primitive. The
reasoning behind this is that the compiler is primarily focused on
stopping cascading updates — it's fine to recompute a primitive since we
can cheaply compare that primitive and avoid unnecessary downstream
recomputation. But we've gotten a lot of feedback that people find this
surprising, and that sometimes the computation can be expensive enough
that it should be memoized.

This PR changes `@enablePreserveExistingMemoizationGuarantees` mode to
ensure that primitive-returning functions get memoized. Other modes will
not memoize these functions. Separately from this we are considering
enabling this mode by default.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34343).
* #34347
* #34346
* __->__ #34343
* #34335
2025-09-03 17:45:17 -07:00
Joseph Savona
5d64f74211 [compiler] Fix for scopes with unreachable fallthroughs (#34335)
Fixes #34108. If a scope ends with with a conditional where some/all
branches exit via labeled break, we currently compile in a way that
works but bypasses memoization. We end up with a shape like


```js
let t0;
label: {
 if (changed) {
   ...
   if (cond) {
     t0 = ...;
     break label;
   }
   // we don't save the output if the break happens!
   t0 = ...;
   $[0] = t0;
 } else {
   t0 = $[0];
}
```

The fix here is to update AlignReactiveScopesToBlockScopes to take
account of breaks that don't go to the natural fallthrough. In this
case, we take any active scopes and extend them to start at least as
early as the label, and extend at least to the label fallthrough. Thus
we produce the correct:

```js
let t0;
if (changed) {
  label: {
    ...
    if (cond) {
      t0 = ...;
      break label;
    }
    t0 = ...;
  }
  // now the break jumps here, and we cache the value
  $[0] = t0;
} else {
  t0 = $[0];
}
```

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34335).
* #34347
* #34346
* #34343
* __->__ #34335
2025-09-03 17:44:42 -07:00
Andrew Clark
3302d1f791 Fix: uDV skipped initial value if earlier transition suspended (#34376)
Fixes a bug in useDeferredValue's optional `initialValue` argument. In
the regression case, if a new useDeferredValue hook is mounted while an
earlier transition is suspended, the `initialValue` argument of the new
hook was ignored. After the fix, the `initialValue` argument is
correctly rendered during the initial mount, regardless of whether other
transitions were suspended.

The culprit was related to the mechanism we use to track whether a
render is the result of a `useDeferredValue` hook: we assign the
deferred lane a TransitionLane, then entangle that lane with the
DeferredLane bit. During the subsequent render, we check for the
presence of the DeferredLane bit to determine whether to switch to the
final, canonical value.

But because transition lanes can themselves become entangled with other
transitions, the effect is that every entangled transition was being
treated as if it were the result of a `useDeferredValue` hook, causing
us to skip the initial value and go straight to the final one.

The fix I've chosen is to reserve some subset of TransitionLanes to be
used only for deferred work, instead of using entanglement. This is
similar to how retries are already implemented. Originally I tried not
to implement it this way because it means there are now slightly fewer
lanes allocated for regular transitions, but I underestimated how
similar deferred work is to retries; they end up having a lot of the
same requirements. Eventually it may be possible to merge the two
concepts.
2025-09-03 19:24:38 -04:00
lauren
7697a9f62e [playground] Upgrade to latest next (#34375)
We were still on a canary version of next in the playground, so let's
update to the latest version.
2025-09-03 13:47:37 -04:00
Ricky
3168e08f83 [flags] enable opt-in for enableDefaultTransitionIndicator (#34373)
So we can test the feature.
2025-09-03 12:33:55 -04:00
Ruslan Lesiutin
2805f0ed9e Performance Tracks: log properties diff for renders in DEV if no console task available (#34370)
React Native doesn't support `console.createTask` yet, but it does
support `performance.measure` and extensibility APIs for Performance
panel, including `detail.devtools` field.

Previously, this logic was gated with `if (__DEV__ && debugTask)`, now
`debugTask` is no longer required to log render. If there is no console
task, we will just call `performance.measure(...)`. The same pattern is
used in other reporters.
2025-09-03 17:08:05 +01:00
Eugene Choi
ac3e705a18 [compiler][playground] (2/N) Config override panel (#34344)
<!--
  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

Part 2 of adding a "Config Override" panel to the React compiler
playground. Added sync from the config editor (still only accessible
with the "showConfig" param) to the main source code editor. Adding a
valid config to the editor will add/replace the `@OVERRIDE` pragma above
the source code. Additionally refactored the old implementation to
remove `useEffect`s and unnecessary renders.

Realized upon testing that the user experience is quite jarring,
planning to add a `sync` button in the next PR to fix this.

## How did you test this change?

<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->



https://github.com/user-attachments/assets/a71b1b5f-0539-4c00-8d5c-22426f0280f9
2025-09-02 17:38:57 -04:00
Sebastian "Sebbie" Silbermann
8e60cb7ed5 [DevTools] Remove markers from Suspense timeline (#34357) 2025-09-02 14:59:15 +02:00
Sebastian "Sebbie" Silbermann
6a58b80020 [DevTools] Only inspect elements on left mouseclick (#34361) 2025-09-02 12:40:54 +02:00
Sebastian "Sebbie" Silbermann
b1b0955f2b [DevTools] Fix inspected element scroll in Suspense tab (#34355) 2025-09-01 16:40:30 +02:00
Hendrik Liebau
1549bda33f [Flight] Only assign _store in dev mode when creating lazy types (#34354)
Small follow-up to #34350. The `_store` property is now only assigned in
development mode when creating lazy types. It also uses the `validated`
value that was passed to `createElement`, if applicable.
2025-09-01 12:13:05 +02:00
Hendrik Liebau
bb6f0c8d2f [Flight] Fix wrong missing key warning when static child is blocked (#34350) 2025-09-01 11:03:57 +02:00
Hendrik Liebau
aad7c664ff [Flight] Don't try to close debug channel twice (#34340)
When the debug channel was already closed, we must not try to close it
again when the Response gets garbage collected.

**Test plan:**

1. reduce the Flight fixture `App` component to a minimum [^1]
    - remove everything from `<body>`
    - delete the `console.log` statement
2. open the app in Firefox (seems to have a more aggressive GC strategy)
3. wait a few seconds

On `main`, you will see the following error in the browser console:

```
TypeError: Can not close stream after closing or error
```

With this change, the error is gone.

[^1]: It's a bit concerning that step 1 is needed to reproduce the
issue. Either GC is behaving differently with the unmodified App, or we
may hold on to the Response under certain conditions, potentially
creating a memory leak. This needs further investigation.
2025-08-29 17:22:39 +02:00
Hendrik Liebau
3fe51c9e14 [Flight] Use more robust web socket implementation in fixture (#34338)
The `WebSocketStream` implementation seems to be a bit unreliable. We've
seen `Cannot close a ERRORED writable stream` errors when expanding the
logged deep object, for example. And when reducing the fixture to a
minimal app, we even get `Connection closed` errors, because the web
socket connection is closed before all debug chunks are sent.

We can improve the reliability of the web socket connection by using a
normal `WebSocket` instance on the client, along with manually creating
a `WritableStream` and a `ReadableStream` for processing the messages.

As an additional benefit, the debug channel now also works in Firefox
and Safari.

On the server, we're simplifying the integration with the Express server
a bit by utilizing the `server` property for `WebSocket.Server`, instead
of the `noServer` property with the manual upgrade handling.
2025-08-29 12:04:27 +02:00
Joseph Savona
4082b0e7d3 [compiler] Detect known incompatible libraries (#34027)
A few libraries are known to be incompatible with memoization, whether
manually via `useMemo()` or via React Compiler. This puts us in a tricky
situation. On the one hand, we understand that these libraries were
developed prior to our documenting the [Rules of
React](https://react.dev/reference/rules), and their designs were the
result of trying to deliver a great experience for their users and
balance multiple priorities around DX, performance, etc. At the same
time, using these libraries with memoization — and in particular with
automatic memoization via React Compiler — can break apps by causing the
components using these APIs not to update. Concretely, the APIs have in
common that they return a function which returns different values over
time, but where the function itself does not change. Memoizing the
result on the identity of the function will mean that the value never
changes. Developers reasonable interpret this as "React Compiler broke
my code".

Of course, the best solution is to work with developers of these
libraries to address the root cause, and we're doing that. We've
previously discussed this situation with both of the respective
libraries:
* React Hook Form:
https://github.com/react-hook-form/react-hook-form/issues/11910#issuecomment-2135608761
* TanStack Table:
https://github.com/facebook/react/issues/33057#issuecomment-2840600158
and https://github.com/TanStack/table/issues/5567

In the meantime we need to make sure that React Compiler can work out of
the box as much as possible. This means teaching it about popular
libraries that cannot be memoized. We also can't silently skip
compilation, as this confuses users, so we need these error messages to
be visible to users. To that end, this PR adds:

* A flag to mark functions/hooks as incompatible
* Validation against use of such functions
* A default type provider to provide declarations for two
known-incompatible libraries

Note that Mobx is also incompatible, but the `observable()` function is
called outside of the component itself, so the compiler cannot currently
detect it. We may add validation for such APIs in the future.

Again, we really empathize with the developers of these libraries. We've
tried to word the error message non-judgementally, because we get that
it's hard! We're open to feedback about the error message, please let us
know.
2025-08-28 16:21:15 -07:00
Smruti Ranjan Badatya
6b49c449b6 Update Code Sandbox CI to Node 20 to Match .nvmrc (#34329)
## Summary
Update the CodeSandbox CI configuration to use Node 20 instead of Node
18, so that it matches the Node version specified in .nvmrc. This
ensures consistency between local development environments and CI
builds, reducing the risk of version-related build issues.

Closes #34328

## How did you test this change?
- Verified that .nvmrc specifies Node 20 and .codesandbox/ci.json is
updated accordingly.
- Locally switched to Node 20 using nvm use 20 and successfully ran
build scripts for all packages: `react`, `react-dom`,
`react-server-dom-webpack`, and `scheduler`.
- Confirmed there are no Node 20–specific build errors or warnings
locally.
- CI on the feature branch will now run with Node 20, and all builds are
expected to succeed.
2025-08-28 18:33:12 -04:00
lauren
872b4fef6d [eprh] Update installation instructions in readme (#34331)
Small PR to update our readme for eslint-plugin-react-hooks, to better
describe what a minimal but complete eslint config would look like.
2025-08-28 18:27:49 -04:00
Eugene Choi
c5362a380f [compiler][playground] (1/N) Config override panel (#34303)
## Summary
Part 1 of adding a "Config Override" panel to the React compiler
playground. The panel is placed to the left of the current input
section, and supports converting the comment pragmas in the input
section to a JavaScript-based config. Backwards sync has not been
implemented yet.

NOTE: I have added support for a new `OVERRIDE` type pragma to add
support for Map and Function types. (For now, the old pragma format is
still intact)

## Testing
Example of the config overrides synced to the source code:
<img width="1542" height="527" alt="Screenshot 2025-08-28 at 3 38 13 PM"
src="https://github.com/user-attachments/assets/d46e7660-61b9-4145-93b5-a4005d30064a"
/>
2025-08-28 16:26:15 -04:00
Sebastian "Sebbie" Silbermann
89a803fcec [DevTools] Add breadcrumbs to Suspense tab (#34312) 2025-08-28 16:03:54 +02:00
Joseph Savona
8d7b5e4903 [compiler] Show a ref name hint when assigning to non-ref in a callback (#34298)
In #34125 I added a hint where if you assign to the .current property of
a frozen object, we suggest naming the variable as `ref` or `-Ref`.
However, the tracking for mutations that assign to .current specifically
wasn't propagated past function expression boundaries, which meant that
the hint only showed up if you mutated the ref in the main body of the
component/hook. That's less likely to happen since most folks know not
to access refs in render. What's more likely is that you'll (correctly)
assign a ref in an effect or callback, but the compiler will throw an
error. By showing a hint in this case we can help people understand the
naming pattern.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34298).
* #34276
* __->__ #34298
2025-08-27 17:05:44 -07:00
Jack Pope
3434ff4f4b Add scrollIntoView to fragment instances (#32814)
This adds `experimental_scrollIntoView(alignToTop)`. It doesn't yet
support `scrollIntoView(options)`.

Cases:
- No host children: Without host children, we represent the virtual
space of the Fragment by attempting to scroll to the nearest edge by
using its siblings. If the preferred sibling is not found, we'll try the
other side, and then the parent.
- 1 or more host children: In order to handle the case of children
spread between multiple scroll containers, we scroll to each child in
reverse order based on the `alignToTop` flag.

Due to the complexity of multiple scroll containers and dealing with
portals, I've added this under a separate feature flag with an
experimental prefix. We may stabilize it along with the other APIs, but
this allows us to not block the whole feature on it.

This PR was previously implementing a much more complex approach to
handling multiple scroll containers and portals. We're going to start
with the simple loop and see if we can find any concrete use cases where
that doesn't suffice. 01f31d43013ba7f6f54fd8a36990bbafc3c3cc68 is the
diff between approaches here.
2025-08-27 18:05:57 -04:00
lauren
bd5b1b7639 [compiler] Emit better error for unsupported syntax this (#34322) 2025-08-27 17:58:44 -04:00
lauren
0a1f1fcd50 [ci] Cache playwright in run_devtools_e2e_tests (#34320)
I happened to notice that I forgot to cache playwright in
run_devtools_e2e_tests, so it would try to install it every time which
can randomly take a while to complete (I'm not sure why it's not
deterministic, but the dependencies appear to be installed
inconsistently across multiple workflows).

This PR adds the same cache we use for other steps that use playwright,
which should shave off some time from this workflow when the cache is
warm.

Additionally I omitted the standalone install-deps command as it appears
to be redundant and adds a lot of extra time to CI, due to the fact that
it installs many unrelated dependencies.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34320).
* #34321
* __->__ #34320
2025-08-27 14:37:18 -04:00
lauren
b870042915 [compiler] Validate against component/hook factories (#34305)
Previously, the compiler would incorrectly attempt to compile nested
components/hooks defined inside non-React functions. This would lead to
scope reference errors at runtime because the compiler would optimize
the nested React function without understanding its closure over the
parent function's variables.

This PR adds detection when non-React functions declare components or
hooks, and reports a clear error before compilation. I put this under a
new compiler flag defaulting to false. I'll run a test on this
internally first, but I expect we should be able to just turn it on in
both compiler (so we stop miscompiling) and linter.

Closes #33978

Playground example:
https://react-compiler-playground-git-pr34305-fbopensource.vercel.app/#N4Igzg9grgTgxgUxALhAejQAgAIDcCGANgJYAm+ALggHIQAiAngHb4C2xcRhDAwjApQSkeEVgAcITBEwpgA8jAASECAGswAHSkAPCTAqYAZlCZwKxSZgDmCCgEkmYqBQAU+AJSZgWzJjiSwAwB1GHwxMQQYTABeTBdPaIA+Lx9fPwCDAAt8JlJCBB5sphsYuITk7yY0tPwAOklCnJt4gG5U3wBfNqZ2zH4KWCqAHmJHZ0wGopto4CK8gqmEDsw0RO7O7tT+wcwQsIiYbo6QDqA
2025-08-27 13:59:26 -04:00
Joseph Savona
33a1095d72 [compiler] Infer render helpers for additional validation (#33647)
We currently assume that any functions passes as props may be event
handlers or effect functions, and thus don't check for side effects such
as mutating globals. However, if a prop is a function that returns JSX
that is a sure sign that it's actually a render helper and not an event
handler or effect function. So we now emit a `Render` effect for any
prop that is a JSX-returning function, triggering all of our render
validation.

This required a small fix to InferTypes: we weren't correctly populating
the `return` type of function types during unification. I also improved
the printing of types so we can see the inferred return types.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/33647).
* #33643
* #33650
* #33642
* __->__ #33647
2025-08-27 08:44:09 -07:00
Sebastian "Sebbie" Silbermann
213594860f [DevTools] Better scrolling in Suspense tab (#34299) 2025-08-27 16:00:06 +02:00
Hendrik Liebau
9c2e2b8475 [Flight] Don't drop debug info if there's only a readable debug channel (#34304)
When the Flight Client is waiting for pending debug chunks, it drops the
debug info if there is no writable side of the debug channel defined.
However, it should instead check if there's no readable side defined.

Fixing this is not only important for browser clients that don't want or
need a return channel, but it's also crucial for server-side rendering,
because the Node and Edge clients only accept a readable side of the
debug channel. So they can't even define a noop writable side as a
workaround.
2025-08-27 13:50:19 +02:00
Sebastian "Sebbie" Silbermann
4123f6b771 [Fizz] Skip past hidden inputs when attempting to hydrate hydration boundaries (#34302) 2025-08-26 17:28:36 +02:00
Sebastian "Sebbie" Silbermann
cb1e73be04 [DevTools] Batch Suspense toggles when advancing the Suspense timeline (#34251) 2025-08-26 17:22:30 +02:00
Hendrik Liebau
cacc20e37c [Flight] Wait for both streams to end before closing the response (#34301)
When a debug channel is defined, we must ensure that we don't close the
Flight Client's response when the debug channel's readable is done, but
the RSC stream is still flowing. Now, we wait for both streams to end
before closing the response.
2025-08-26 17:15:25 +02:00
Sebastian "Sebbie" Silbermann
bb7c9c1b8a Create more realistic containers in DevTools fixture (#34296) 2025-08-26 17:13:37 +02:00
Sebastian "Sebbie" Silbermann
44f8451ede [DevTools] Avoid tearing Suspense store (#34294) 2025-08-26 17:09:55 +02:00
Sebastian "Sebbie" Silbermann
ad4ecb6e6e [DevTools] Fix symbolication with Index Source Maps (#34300) 2025-08-26 15:18:20 +02:00
Jan Kassens
26e87b5f15 Fix Flow issue from land race (#34293)
A Flow upgrade removed the bundled library definitinos for
SynthaticEvent and we probably want to use our internal definitions.
Those are not properly typed at this point yet, but we can look into
that as a followup.
2025-08-25 12:58:12 -04:00
Sebastian "Sebbie" Silbermann
75dc0026d6 [DevTools] Initial version of Suspense timeline (#34233) 2025-08-25 17:47:29 +02:00
Jan Kassens
df10309e2b Update Flow to 0.279 (#34277)
Multiple of these version upgrades required minor additional
annotations.
2025-08-25 11:02:56 -04:00
Sebastian "Sebbie" Silbermann
e42f3d30ca [DevTools] Include name prop when highlighting host instances (#34258) 2025-08-25 16:40:56 +02:00
Sebastian "Sebbie" Silbermann
67e743fba5 [compiler] Fix missing dependency in eslint-plugin-react-hooks (#34287) 2025-08-25 16:39:23 +02:00
Sebastian "Sebbie" Silbermann
9eede45646 Stop treating all Node.js builtins implicitly as externals (#34249) 2025-08-25 09:39:56 +02:00
Jan Kassens
090777d78a Update Flow to 0.274 (#34275)
An exported needed explicit typing as it was inferred incorrectly.
2025-08-22 17:46:37 -04:00
Jan Kassens
4049cfeeab Update Flow to 0.273 (#34274)
This version introduces "Natural Inference" which requires a couple more
type annotations to make Flow pass.
2025-08-22 16:58:01 -04:00
Jan Kassens
e67e3bed92 Update Flow to 0.272 (#34273)
This is the last version before "Natural Inference" change to Flow that
will require more changes, so doing a quick fast-forward PR here.

- Disabled a new Flow lint against unsafe `Object.assign`.
2025-08-22 16:25:49 -04:00
Jan Kassens
06cfa99f37 Update Flow to 0.267 (#34272)
Changes to type inference require some more annotations.
2025-08-22 15:53:07 -04:00
Jan Kassens
05addfc663 Update Flow to 0.266 (#34271)
- replace `$ElementType` and `$PropertyType` with `T[K]` accesses.
- Use component types
2025-08-22 15:46:41 -04:00
Jan Kassens
d260b0d8b8 Update Flow to 0.265 (#34270)
Looks like this version removed `Object.prototype` although I didn't see
that in the changelog. This is fine for this code here.
2025-08-22 15:22:22 -04:00
Joseph Savona
425ba0ad6d [compiler] Script to produce markdown of lint rule docs (#34260)
The docs site is in a separate repo, but this gives us a semi-automated
way to update the docs about our lint rules. The script generates
markdown files from the rule definitions which we can then manually
copy/paste into the docs site somewhere. In the future we can automate
this fully.
2025-08-22 09:59:28 -07:00
Jan Kassens
6de32a5a07 Update Flow to 0.263 (#34269)
This update was a bit more involved.

- `React$Component` was removed, I replaced it with Flow component
types.
- Flow removed shipping the standard library. This adds the environment
libraries back from `flow-typed` which seemed to have changed slightly
(probably got more precise and less `any`s). Suppresses some new type
errors.
2025-08-22 12:10:13 -04:00
Abdulwahab Omira
698bb4deb7 Add support for ARIA 1.3 attributes (#34264)
Co-authored-by: Abdulwahab Omira <abdulwahabomira@gmail.com>
Co-authored-by: Sebastian Sebbie Silbermann <sebastian.silbermann@vercel.com>
2025-08-22 16:22:18 +02:00
Sebastian Markbåge
11d7bcf88c [DevTools] Use source maps to infer name asynchronously (#34212) 2025-08-22 00:38:09 +02:00
Sebastian Markbåge
a85ec041d6 [DevTools] Ignore List Stack Traces (#34210)
Co-authored-by: Sebastian Sebbie Silbermann <sebastian.silbermann@vercel.com>
2025-08-22 00:03:05 +02:00
Joseph Savona
7d29ecbeb2 [compiler] Aggregate error reporting, separate eslint rules (#34176)
NOTE: this is a merged version of @mofeiZ's original PR along with my
edits per offline discussion. The description is updated to reflect the
latest approach.

The key problem we're trying to solve with this PR is to allow
developers more control over the compiler's various validations. The
idea is to have a number of rules targeting a specific category of
issues, such as enforcing immutability of props/state/etc or disallowing
access to refs during render. We don't want to have to run the compiler
again for every single rule, though, so @mofeiZ added an LRU cache that
caches the full compilation output of N most recent files. The first
rule to run on a given file will cause it to get cached, and then
subsequent rules can pull from the cache, with each rule filtering down
to its specific category of errors.

For the categories, I went through and assigned a category roughly 1:1
to existing validations, and then used my judgement on some places that
felt distinct enough to warrant a separate error. Every error in the
compiler now has to supply both a severity (for legacy reasons) and a
category (for ESLint). Each category corresponds 1:1 to a ESLint rule
definition, so that the set of rules is automatically populated based on
the defined categories.

Categories include a flag for whether they should be in the recommended
set or not.

Note that as with the original version of this PR, only
eslint-plugin-react-compiler is changed. We still have to update the
main lint rule.

## Test Plan

* Created a sample project using ESLint v9 and verified that the plugin
can be configured correctly and detects errors
* Edited `fixtures/eslint-v9` and introduced errors, verified that the w
latest config changes in that fixture it correctly detects the errors
* In the sample project, confirmed that the LRU caching is correctly
caching compiler output, ie compiling files just once.

Co-authored-by: Mofei Zhang <feifei0@meta.com>
2025-08-21 14:53:34 -07:00
Sebastian Markbåge
253abc78a1 [Flight] Transfer Debug Info from a synchronous Reference to another Chunk (#34229) 2025-08-21 23:50:20 +02:00
Jan Kassens
d73b6f1110 Update Flow to 0.261 (#34255)
- 0.261 required to pull out a constant to preserve refinement
- 0.259 needed some updated suppressions for hacky stuff
2025-08-21 15:02:49 -04:00
Jan Kassens
d5586e2059 Update Flow to 0.258 (#34254)
Minor new suppressions only.
2025-08-21 14:17:13 -04:00
Jan Kassens
ec5dd0ab3a Update Flow to 0.257 (#34253)
After an easy couple version with #34252, this version is less flexible
(and safer) on inferring exported types mainly.

We require to annotate some exported types to differentiate between
`boolean` and literal `true` types, etc.
2025-08-21 13:30:01 -04:00
Ruslan Lesiutin
8120753665 [DevTools] fix: always send a response to fetch-file request in the extension (#34235)
This fixes the displaying of "rendered by" section if owner stacks
contained any native frames. This regressed after
https://github.com/facebook/react/pull/34185, where we added the
Suspense boundary for the StackTraceView.

This fails because the Promise that is responsible for symbolication of
the source is never getting resolved or rejected.
Previously, we would just throw an Error without sending a corresponding
message to the `main` script, and it would just cache a Promise that is
never resolved, hence the Suspense boundary for "rendered by" section is
never resolved.

In a separate change, I think we need to update StackTraceView component
to display `native` as location, instead of `:0`:
<img width="712" height="118" alt="Screenshot 2025-08-20 at 00 20 42"
src="https://github.com/user-attachments/assets/c79735c9-fdd2-467c-96cd-2bc29d38c4e0"
/>
2025-08-21 18:28:33 +01:00
Jan Kassens
3770ff3853 Update Flow to 0.256 (#34252)
Looks like these versions didn't require changes, so easy fast forward.
2025-08-21 12:33:56 -04:00
Jan Kassens
873f711299 Update Flow to 0.248 (#34248)
This update remove support for `%checks`.

Thanks @SamChou19815 for finding a close replacement that works.
2025-08-21 11:15:34 -04:00
Jan Kassens
5f06c3d22a Update Flow to 0.247 (#34245)
`$Call` was removed.
2025-08-20 22:19:57 -04:00
Jan Kassens
243a56b9a2 Update Flow to 0.246 (#34244)
Catching up Flow versions. Since there's plenty new errors, I'm taking
each version with breaking changes as a new PR.
2025-08-20 21:46:55 -04:00
Jan Kassens
83c7379b96 Add flow suppression for Constant Condition rollout (#34243) 2025-08-20 18:24:01 -04:00
lauren
c2ac8b4f0e [ci] Fix permissions for direct sync branch PRs workflow (#34241)
Because we sync built artifacts into Meta, we can't support edits from
inside www/fbsource to be synced back into OSS as it would cause merge
conflicts for future OSS PRs.

We have a workflow that should automatically catch and close these PRs,
but it looks like this one was missing one permission.
2025-08-20 17:09:38 -04:00
Sebastian "Sebbie" Silbermann
03fda05d2c [DevTools] Fix display of stack frames with anonymous sources (#34237) 2025-08-20 17:31:42 +02:00
Hendrik Liebau
0bc71e67ab [Flight] Add debugChannel option to Edge and Node clients (#34236)
When a debug channel is used between the Flight server and a browser
Flight client, we want to allow the same RSC stream to be used for
server-side rendering. To support this, the Edge and Node Flight clients
also need to accept a `debugChannel` option. Without it, debug
information would be missing (e.g. for SSR error stacks), and in some
cases this could result in `Connection closed` errors.

This PR adds support for the `debugChannel` option in the Edge and Node
clients for ESM, Parcel, Turbopack, and Webpack. Unlike the browser
clients, these clients only support a one-way channel, since the Flight
server’s return protocol is not designed for multiple clients.

The implementation follows the approach used in the browser clients, but
excludes the writable parts.
2025-08-20 16:46:34 +02:00
Sebastian "Sebbie" Silbermann
3e20dc8b9c [DevTools] Fix crash when inspecting Components suspended on data awaited in anonymous functions (#34234) 2025-08-20 09:34:06 +02:00
Sebastian "Sebbie" Silbermann
ae5c2f82b3 [DevTools] Handle reorders when resuspending while fallback contains Suspense (#34225) 2025-08-19 20:22:54 +02:00
Sebastian Markbåge
0bdb9206b7 [Fizz] If we haven't painted yet, wait to reveal everything until next paint (#34230)
Before the first rAF, we don't know if there has been other paints
before this and if so when. (We could get from performance observer.) We
can assume that it's not earlier than 0 so we used delay up until the
throttle time starting from zero but if the first paint is about to
happen that can be very soon after.

Instead, this reveals it during the next paint which should let us be
able to get into the first paint. If we can trust `rel="expect"` to have
done its thing we should schedule our raf before first paint but ofc
browsers can cheat and paint earlier if they want to.

If we're wrong, this is at least more batched than doing it
synchronously. However it will mean that things might get more flashy
than it should be if it would've been throttled. An alternative would be
to always throttle first reveal.
2025-08-18 20:22:40 -04:00
lauren
f508edc83f [compiler] Stop publishing eslint-plugin-react-compiler to npm (#34228)
While we still use this package internally, we now ask users to install
eslint-plugin-react-hooks instead, so this package can now be deprecated
on npm.
2025-08-18 11:34:55 -04:00
Sebastian Markbåge
0c89b160f6 [Flight] Add DebugInfo for Bundler Chunks (#34226)
This adds a "suspended by" row for each chunk that is referenced from a
client reference. So when you select a client component, you can see
what bundles will block that client component when loading on the
client.

This is only done in the browser build since if we added it on the
server, it would show up as a blocking resource and while it's possible
we expect that a typical server request won't block on loading JS.

<img width="664" height="486" alt="Screenshot 2025-08-17 at 3 45 14 PM"
src="https://github.com/user-attachments/assets/b1f83445-2a4e-4470-9a20-7cd215ab0482"
/>

<img width="745" height="678" alt="Screenshot 2025-08-17 at 3 46 58 PM"
src="https://github.com/user-attachments/assets/3558eae1-cf34-4e11-9d0e-02ec076356a4"
/>

Currently this is only included if it ends up wrapped in a lazy like in
the typical type position of a Client Component, but there's a general
issue that maybe hard references need to transfer their debug info to
the parent which can transfer it to the Fiber.
2025-08-18 11:34:00 -04:00
Benjamin
87a45ae37f [eslint-plugin-react-hooks][RulesOfHooks] handle React.useEffect in addition to useEffect (#34076)
## Summary

This is a fix for https://github.com/facebook/react/issues/34074

## How did you test this change?

I added tests in the eslint package, and ran `yarn jest`. After adding
the new tests, I have this:

On main | On this branch
-|-
<img width="356" height="88" alt="image"
src="https://github.com/user-attachments/assets/4ae099a1-0156-4032-b2ca-635ebadcaa3f"
/> | <img width="435" height="120" alt="image"
src="https://github.com/user-attachments/assets/b06c04b8-6cec-43de-befa-a8b4dd20500e"
/>

## Changes

- Add tests to check that we are checking both `CallExpression`
(`useEffect(`), and `MemberExpression` (`React.useEffect(`). To do that,
I copied the `getNodeWithoutReactNamespace(` fn from `ExhaustiveDeps.ts`
to `RulesOfHooks.ts`
2025-08-18 09:12:49 -04:00
Sebastian "Sebbie" Silbermann
01ed0e9642 [DevTools] Avoid uncached Promise when symbolicating sources in environments without file fetching (#34224) 2025-08-18 12:46:19 +02:00
Sebastian "Sebbie" Silbermann
b58a8e3c40 [DevTools] Handle mount of disconnected Suspense boundaries (#34208) 2025-08-18 10:15:56 +02:00
Sebastian Markbåge
42b1b33a24 [DevTools] Add byteSize field to ReactIOInfo and show this in the tooltip (#34221)
This is intended to be used by various client side resources where the
transfer size is interesting to know how it'll perform in various
network conditions. Not intended to be added by the server.

For now it's only added internally by DevTools itself on img/css but
I'll add it from Flight Client too in a follow up.

This now shows this as the "transfer size" which is the encoded body
size + headers/overhead. Where as the "fileSize" that I add to images is
the decoded body size, like what you'd see on disk. This is what Chrome
shows so it's less confusing if you compare Network tab and this view.
2025-08-17 16:17:11 -04:00
Sebastian Markbåge
7a36dfedc7 [Fizz] Delay retrying hydration until after an animation frame (#34220)
The theory here is that when we reveal a boundary coming from the server
we want to paint that before hydrating it. Hydration gets scheduled in a
macrotask with the scheduler but it's in theory possible that it runs
before the paint. If that's the case, then the JS that runs before
yielding during hydration might slightly delay the paint and we might
miss a window to skip the previous paint.
2025-08-16 12:16:58 -04:00
Sebastian "Sebbie" Silbermann
546bac7281 [DevTools] Always attempt to mount dehydrated roots (#34209) 2025-08-16 10:45:39 +02:00
Sebastian "Sebbie" Silbermann
2cb8edbb05 [DevTools] Handle dehydrated Suspense boundaries (#34196) 2025-08-16 10:34:19 +02:00
Sebastian Markbåge
431bb0bddb [DevTools] Mark Unknown Reasons for Suspending with a Note (#34200)
We currently only track the reason something might suspend in
development mode through debug info but this excludes some cases. As a
result we can end up with boundary that suspends but has no cause. This
tries to detect that and show a notice for why that might be. I'm also
trying to make it work with old React versions to cover everything.

In production we don't track any of this meta data like `_debugInfo`,
`_debugThenable` etc. so after resolution there's no information to take
from. Except suspensey images / css which we can track in prod too. We
could track lazy component types already. We'd have to add something
that tracks after the fact if something used a lazy child, child as a
promise, hooks, etc. which doesn't exist today. So that's not backwards
compatible and might add some perf/memory cost. However, another
strategy is also to try to replay the components after the fact which
could be backwards compatible. That's tricky for child position since
there's so many rules for how to do that which would have to be
replicated.

If you're in development you get a different error. Given that we've
added instrumentation very recently. If you're on an older development
version of React, then you get a different error. Unfortunately I think
my feature test is not quite perfect because it's tricky to test for the
instrumentation I just added.
https://github.com/facebook/react/pull/34146 So I think for some
prereleases that has `_debugOwner` but doesn't have that you'll get a
misleading error.

Finally, if you're in a modern development environment, the only reason
we should have any gaps is because of throw-a-Promise. This will
highlight it as missing. We can detect that something threw if a
Suspense boundary commits with a RetryCache but since it's a WeakSet we
can't look into it to see anything about what it might have been. I
don't plan on doing anything to improve this since it would only apply
to new versions of React anyway and it's just inherently flawed. So just
deprecate it #34032.

Note that nothing in here can detect that we suspended Transition. So
throwing at the root or in an update won't show that anywhere.
2025-08-15 18:32:27 -04:00
Joseph Savona
5063b3283f [compiler] Remove now-unused FunctionEffect type (#34029)
The new mutation/aliasing model significantly expands on the idea of
FunctionEffect. The type (and its usage in HIRFunction.effects) was only
necessary for the now-deleted old inference model so we can clean up
this code now.
2025-08-15 15:27:30 -07:00
Joseph Savona
eaf6adb127 [compiler][wip] Remove old mutation/aliasing implementation (#34028)
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34028).
* #34029
* __->__ #34028
2025-08-15 15:21:28 -07:00
Joseph Savona
6ffcac8558 [compiler] Add support for diagnostic hints (#34126)
Hints are meant as additional information to present to the developer
about an error. The first use-case here is for the suggestion to name
refs with "-Ref" if we encounter a mutation that looks like it might be
a ref. The original error printing used a second error detail which
printed the source code twice, a hint with just extra text is less
noisy.
2025-08-15 15:09:27 -07:00
Joseph Savona
724b324b96 [compiler] Add hint to name variables with "Ref" suffix (#34125)
If you have a ref that the compiler doesn't know is a ref (say, a value
returned from a custom hook) and try to assign its `.current = ...`, we
currently fail with a generic error that hook return values are not
mutable. However, an assignment to `.current` specifically is a very
strong hint that the value is likely to be a ref. So in this PR, we
track the reason for the mutation and if it ends up being an error, we
use it to show an additional hint to the user. See the fixture for an
example of the message.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/34125).
* #34126
* __->__ #34125
* #34124
2025-08-15 15:05:29 -07:00
Jack Pope
45a6532a08 Add compareDocumentPosition to Fabric FragmentInstance (#34103)
Stacked on https://github.com/facebook/react/pull/34069

Same basic semantics as the react-dom for determining document position
of a Fragment compared to a given node. It's simpler here because we
don't have to deal with inserted nodes or portals. So we can skip a
bunch of the validation logic.

The logic for handling empty fragments is the same so I've split out
`compareDocumentPositionForEmptyFragment` into a shared module. There
doesn't seem to be a great place to put shared DOM logic between Fabric
and DOM configs at the moment. There may be more of this coming as we
add more and more DOM APIs to RN.

For testing I've written Fantom tests internally which pass the basic
cases on this build. The renderer we have configured for Fabric tests in
the repo doesn't support the Element APIs we need like
`compareDocumentPosition`.
2025-08-15 15:07:42 -04:00
Sebastian "Sebbie" Silbermann
8dba9311e5 [DevTools] Handle fallback unmount in Suspense update path (#34199) 2025-08-15 19:40:35 +02:00
Sebastian "Sebbie" Silbermann
2d98b45d92 [DevTools] Fix Suspense boundaries always being marked as not suspended (#34206) 2025-08-15 19:39:59 +02:00
Sebastian Markbåge
2ba7b07ce1 [DevTools] Compute a min and max range for the currently selected suspense boundary (#34201)
This computes a min and max range for the whole suspense boundary even
when selecting a single component so that each component in a boundary
has a consistent range.

The start of this range is the earliest start of I/O in that boundary or
the end of the previous suspense boundary, whatever is earlier. If the
end of the previous boundary would make the range large, then we cap it
since it's likely that the other boundary was just an independent
render.

The end of the range is the latest end of I/O in that boundary. If this
is smaller than the end of the previous boundary plus the 300ms
throttle, then we extend the end. This visualizes what throttling could
potentially do if the previous boundary committed right at its end. Ofc,
it might not have committed exactly at that time in this render. So this
is just showing a potential throttle that could happen. To see actual
throttle, you look in the Performance Track.

<img width="661" height="353" alt="Screenshot 2025-08-14 at 12 41 43 AM"
src="https://github.com/user-attachments/assets/b0155e5e-a83f-400c-a6b9-5c38a9d8a34f"
/>

We could come up with some annotation to highlight that this is eligible
to be throttled in this case. If the lines don't extend to the edge,
then it's likely it was throttled.
2025-08-15 13:34:07 -04:00
Jack Pope
a96a0f3903 Fix fragmentInstance#compareDocumentPosition nesting and portal cases (#34069)
Found a couple of issues while integrating
FragmentInstance#compareDocumentPosition into Fabric.

1. Basic checks of nested host instances were inaccurate. For example,
checking the first child of the first child of the Fragment would not
return CONTAINED_BY.
2. Then fixing that logic exposed issues with Portals. The DOM
positioning relied on the assumption that the first and last top-level
children were in the same order as the Fiber tree. I added additional
checks against the parent's position in the DOM, and special cased a
portaled Fragment by getting its DOM parent from the child instance,
rather than taking the instance from the Fiber return. This should be
accurate in more cases. Though its still a guess and I'm not sure yet
I've covered every variation of this. Portals are hard to deal with and
we may end up having to push more results towards
IMPLEMENTATION_SPECIFIC if accuracy is an issue.
2025-08-15 12:14:23 -04:00
Sebastian "Sebbie" Silbermann
02a8811864 [SuspenseTab] Scuffed version of Suspense rects (#34188) 2025-08-14 18:24:41 +02:00
Sebastian "Sebbie" Silbermann
379a083b9a Include stack of cause in React instrumentation errors (#34198) 2025-08-13 19:18:02 +02:00
Sebastian "Sebbie" Silbermann
534bed5fa7 Use yarn run in Flight fixture (#34197) 2025-08-13 15:49:44 +02:00
Sebastian Markbåge
db06f6b751 [DevTools] Track virtual debug info from suspensey images (#34181)
Same as #34166 but for Suspensey images.

The trick here is to check the `SuspenseyImagesMode` since not all
versions of React and not all subtrees will have Suspensey images
enabled yet.

The other trick is to read back from `currentSrc` to get the image url
we actually resolved to in this case. Similar to how for Suspensey CSS
we check if the media query would've matched.

<img width="591" height="205" alt="Screenshot 2025-08-11 at 9 32 56 PM"
src="https://github.com/user-attachments/assets/ac98785c-d3e0-407c-84e0-c27f86c0ecac"
/>
2025-08-13 09:26:21 -04:00
Sebastian "Sebbie" Silbermann
9433fe357a Fail tests if unasserted console calls contain undefined (#34191) 2025-08-13 08:48:04 +02:00
Sebastian "Sebbie" Silbermann
0032b2a3ee [Flight] Log error if prod elements are rendered (#34189) 2025-08-13 08:47:09 +02:00
Sebastian Markbåge
14c50e344c [DevTools] Use Visually Lighter Skeletons (#34185)
The skeletons right now are too jarring because they're visually heavier
than the content that comes in later. This makes them draw attention to
themselves as flashing things.

A good skeleton and loading indicator should ideally start as invisible
as possible and then gradually become more visible the longer time
passes so that if it loads quickly then it was never much visible at
all.

Even at its max it should never be heavier weight than the final content
so that it visually reverts into lesser. Another rule of thumb is that
it should be as close as possible to the final content in size but if
it's unknown it should always be smaller than the final content so that
the content grows into its slot rather than the slot contracting.

This makes the skeleton fade from invisible into the dimmest color just
as a subtle hint that something is still loading.

I also added a missing skeleton since the stack traces in rendered by
can now suspend while source mapping.

The other tweak I did is use disabled buttons in all the cases where we
load the ability to enable a button. This is more subtle and if you
hover over you can see why it's still disabled. Rather than flashing the
button each time you change element.
2025-08-12 23:10:31 -04:00
Sebastian Markbåge
f1222f7652 [Fiber] Don't bind retry listener if it's in the cache (#34183)
This did an unnecessary bind allocation even if there's cache hit.
2025-08-12 21:42:24 -04:00
Josh Story
9baecbf02b [Fizz] Avoid hanging when suspending after aborting while rendering (#34192)
This fixes an edge case where you abort the render while rendering a
component that ends up Suspending. It technically only applied if you
were deep enough to be inside `renderNode` and was not susceptible to
hanging if the abort + suspending component was being tried inside
retryRenderTask/retryReplaytask.

The fix is to preempt the thenable checks in renderNode and check if the
request is aborting and if so just bubble up to the task handler.

The reason this hung before is a new task would get scheduled after we
had aborted every other task (minus the currently rendering one). This
led to a situation where the task count would not hit zero.
2025-08-12 16:46:56 -07:00
Sebastian "Sebbie" Silbermann
0422a00e3e [DevTools] Fix missing key warning (#34186) 2025-08-12 19:58:19 +02:00
Sebastian Markbåge
47fd2f5e14 [DevTools] Fix index (#34187)
I used the wrong indexer and tested with one entry.
2025-08-12 13:57:35 -04:00
Jan Kassens
1dc3bdead1 Remove unused arguments from ReactElement (#34174)
After various feature flag removals recently, these arguments became
unused and can be deleted.
2025-08-12 11:09:35 -04:00
Sebastian "Sebbie" Silbermann
de06211dbe [DevTools] Send Suspense rects to frontend (#34170) 2025-08-12 16:48:35 +02:00
2353 changed files with 101343 additions and 43357 deletions

46
.claude/instructions.md Normal file
View File

@@ -0,0 +1,46 @@
# React
**Scope**: All code EXCEPT `/compiler/` (compiler has its own instructions).
## Project Structure
| Directory | Purpose |
|-----------|---------|
| `/packages/` | Publishable packages (react, react-dom, scheduler, etc.) |
| `/scripts/` | Build, test, and development scripts |
| `/fixtures/` | Test applications for manual testing |
| `/compiler/` | React Compiler (separate sub-project) |
## Key Packages
| Package | Purpose |
|---------|---------|
| `react` | Core React library |
| `react-dom` | DOM renderer |
| `react-reconciler` | Core reconciliation algorithm |
| `scheduler` | Cooperative scheduling |
| `react-server-dom-*` | Server Components |
| `react-devtools-*` | Developer Tools |
| `react-refresh` | Fast Refresh runtime |
## Requirements
- **Node**: Must be installed. Stop and prompt user if missing.
- **Package Manager**: Use `yarn` only.
## Verification
**IMPORTANT**: Use `/verify` to validate all changes before committing.
## Commands
| Command | Purpose |
|----------|----------------------|
| `/fix` | Lint and format code |
| `/test` | Run tests |
| `/flow` | Type check with Flow |
| `/flags` | Check feature flags |
## Building
Builds are handled by CI. Do not run locally unless instructed.

44
.claude/settings.json Normal file
View File

@@ -0,0 +1,44 @@
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "if [[ \"$PWD\" != */compiler* ]]; then cat .claude/instructions.md 2>/dev/null || true; fi"
}
]
}
]
},
"permissions": {
"allow": [
"Skill(extract-errors)",
"Skill(feature-flags)",
"Skill(fix)",
"Skill(flags)",
"Skill(flow)",
"Skill(test)",
"Skill(verify)",
"Bash(yarn test:*)",
"Bash(yarn test-www:*)",
"Bash(yarn test-classic:*)",
"Bash(yarn test-stable:*)",
"Bash(yarn linc:*)",
"Bash(yarn lint:*)",
"Bash(yarn flow:*)",
"Bash(yarn prettier:*)",
"Bash(yarn build:*)",
"Bash(yarn extract-errors:*)",
"Bash(yarn flags:*)"
],
"deny": [
"Bash(yarn download-build:*)",
"Bash(yarn download-build-for-head:*)",
"Bash(npm:*)",
"Bash(pnpm:*)",
"Bash(bun:*)",
"Bash(npx:*)"
]
}
}

View File

@@ -0,0 +1,12 @@
---
name: extract-errors
description: Use when adding new error messages to React, or seeing "unknown error code" warnings.
---
# Extract Error Codes
## Instructions
1. Run `yarn extract-errors`
2. Report if any new errors need codes assigned
3. Check if error codes are up to date

View File

@@ -0,0 +1,79 @@
---
name: feature-flags
description: Use when feature flag tests fail, flags need updating, understanding @gate pragmas, debugging channel-specific test failures, or adding new flags to React.
---
# React Feature Flags
## Flag Files
| File | Purpose |
|------|---------|
| `packages/shared/ReactFeatureFlags.js` | Default flags (canary), `__EXPERIMENTAL__` overrides |
| `packages/shared/forks/ReactFeatureFlags.www.js` | www channel, `__VARIANT__` overrides |
| `packages/shared/forks/ReactFeatureFlags.native-fb.js` | React Native, `__VARIANT__` overrides |
| `packages/shared/forks/ReactFeatureFlags.test-renderer.js` | Test renderer |
## Gating Tests
### `@gate` pragma (test-level)
Use when the feature is completely unavailable without the flag:
```javascript
// @gate enableViewTransition
it('supports view transitions', () => {
// This test only runs when enableViewTransition is true
// and is SKIPPED (not failed) when false
});
```
### `gate()` inline (assertion-level)
Use when the feature exists but behavior differs based on flag:
```javascript
it('renders component', async () => {
await act(() => root.render(<App />));
if (gate(flags => flags.enableNewBehavior)) {
expect(container.textContent).toBe('new output');
} else {
expect(container.textContent).toBe('legacy output');
}
});
```
## Adding a New Flag
1. Add to `ReactFeatureFlags.js` with default value
2. Add to each fork file (`*.www.js`, `*.native-fb.js`, etc.)
3. If it should vary in www/RN, set to `__VARIANT__` in the fork file
4. Gate tests with `@gate flagName` or inline `gate()`
## Checking Flag States
Use `/flags` to view states across channels. See the `flags` skill for full command options.
## `__VARIANT__` Flags (GKs)
Flags set to `__VARIANT__` simulate gatekeepers - tested twice (true and false):
```bash
/test www <pattern> # __VARIANT__ = true
/test www variant false <pattern> # __VARIANT__ = false
```
## Debugging Channel-Specific Failures
1. Run `/flags --diff <channel1> <channel2>` to compare values
2. Check `@gate` conditions - test may be gated to specific channels
3. Run `/test <channel> <pattern>` to isolate the failure
4. Verify flag exists in all fork files if newly added
## Common Mistakes
- **Forgetting both variants** - Always test `www` AND `www variant false` for `__VARIANT__` flags
- **Using @gate for behavior differences** - Use inline `gate()` if both paths should run
- **Missing fork files** - New flags must be added to ALL fork files, not just the main one
- **Wrong gate syntax** - It's `gate(flags => flags.name)`, not `gate('name')`

View File

@@ -0,0 +1,17 @@
---
name: fix
description: Use when you have lint errors, formatting issues, or before committing code to ensure it passes CI.
---
# Fix Lint and Formatting
## Instructions
1. Run `yarn prettier` to fix formatting
2. Run `yarn linc` to check for remaining lint issues
3. Report any remaining manual fixes needed
## Common Mistakes
- **Running prettier on wrong files** - `yarn prettier` only formats changed files
- **Ignoring linc errors** - These will fail CI, fix them before committing

View File

@@ -0,0 +1,39 @@
---
name: flags
description: Use when you need to check feature flag states, compare channels, or debug why a feature behaves differently across release channels.
---
# Feature Flags
Arguments:
- $ARGUMENTS: Optional flags
## Options
| Option | Purpose |
|--------|---------|
| (none) | Show all flags across all channels |
| `--diff <ch1> <ch2>` | Compare flags between channels |
| `--cleanup` | Show flags grouped by cleanup status |
| `--csv` | Output in CSV format |
## Channels
- `www`, `www-modern` - Meta internal
- `canary`, `next`, `experimental` - OSS channels
- `rn`, `rn-fb`, `rn-next` - React Native
## Legend
✅ enabled, ❌ disabled, 🧪 `__VARIANT__`, 📊 profiling-only
## Instructions
1. Run `yarn flags $ARGUMENTS`
2. Explain the output to the user
3. For --diff, highlight meaningful differences
## Common Mistakes
- **Forgetting `__VARIANT__` flags** - These are tested both ways in www; check both variants
- **Comparing wrong channels** - Use `--diff` to see exact differences

View File

@@ -0,0 +1,30 @@
---
name: flow
description: Use when you need to run Flow type checking, or when seeing Flow type errors in React code.
---
# Flow Type Checking
Arguments:
- $ARGUMENTS: Renderer to check (default: dom-node)
## Renderers
| Renderer | When to Use |
|----------|-------------|
| `dom-node` | Default, recommended for most changes |
| `dom-browser` | Browser-specific DOM code |
| `native` | React Native |
| `fabric` | React Native Fabric |
## Instructions
1. Run `yarn flow $ARGUMENTS` (use `dom-node` if no argument)
2. Report type errors with file locations
3. For comprehensive checking (slow), use `yarn flow-ci`
## Common Mistakes
- **Running without a renderer** - Always specify or use default `dom-node`
- **Ignoring suppressions** - Check if `$FlowFixMe` comments are masking real issues
- **Missing type imports** - Ensure types are imported from the correct package

View File

@@ -0,0 +1,46 @@
---
name: test
description: Use when you need to run tests for React core. Supports source, www, stable, and experimental channels.
---
Run tests for the React codebase.
Arguments:
- $ARGUMENTS: Channel, flags, and test pattern
Usage Examples:
- `/test ReactFiberHooks` - Run with source channel (default)
- `/test experimental ReactFiberHooks` - Run with experimental channel
- `/test www ReactFiberHooks` - Run with www-modern channel
- `/test www variant false ReactFiberHooks` - Test __VARIANT__=false
- `/test stable ReactFiberHooks` - Run with stable channel
- `/test classic ReactFiberHooks` - Run with www-classic channel
- `/test watch ReactFiberHooks` - Run in watch mode (TDD)
Release Channels:
- `(default)` - Source/canary channel, uses ReactFeatureFlags.js defaults
- `experimental` - Source/experimental channel with __EXPERIMENTAL__ flags = true
- `www` - www-modern channel with __VARIANT__ flags = true
- `www variant false` - www channel with __VARIANT__ flags = false
- `stable` - What ships to npm
- `classic` - Legacy www-classic (rarely needed)
Instructions:
1. Parse channel from arguments (default: source)
2. Map to yarn command:
- (default) → `yarn test --silent --no-watchman <pattern>`
- experimental → `yarn test -r=experimental --silent --no-watchman <pattern>`
- stable → `yarn test-stable --silent --no-watchman <pattern>`
- classic → `yarn test-classic --silent --no-watchman <pattern>`
- www → `yarn test-www --silent --no-watchman <pattern>`
- www variant false → `yarn test-www --variant=false --silent --no-watchman <pattern>`
3. Report test results and any failures
Hard Rules:
1. **Use --silent to see failures** - This limits the test output to only failures.
2. **Use --no-watchman** - This is a common failure in sandboxing.
Common Mistakes:
- **Running without a pattern** - Runs ALL tests, very slow. Always specify a pattern.
- **Forgetting both www variants** - Test `www` AND `www variant false` for `__VARIANT__` flags.
- **Test skipped unexpectedly** - Check for `@gate` pragma; see `feature-flags` skill.

View File

@@ -0,0 +1,24 @@
---
name: verify
description: Use when you want to validate changes before committing, or when you need to check all React contribution requirements.
---
# Verification
Run all verification steps.
Arguments:
- $ARGUMENTS: Test pattern for the test step
## Instructions
Run these first in sequence:
1. Run `yarn prettier` - format code (stop if fails)
2. Run `yarn linc` - lint changed files (stop if fails)
Then run these with subagents in parallel:
1. Use `/flow` to type check (stop if fails)
2. Use `/test` to test changes in source (stop if fails)
3. Use `/test www` to test changes in www (stop if fails)
If all pass, show success summary. On failure, stop immediately and report the issue with suggested fixes.

View File

@@ -1,7 +1,7 @@
{
"packages": ["packages/react", "packages/react-dom", "packages/react-server-dom-webpack", "packages/scheduler"],
"buildCommand": "download-build-in-codesandbox-ci",
"node": "18",
"node": "20",
"publishDirectory": {
"react": "build/oss-experimental/react",
"react-dom": "build/oss-experimental/react-dom",

View File

@@ -28,3 +28,6 @@ packages/react-devtools-shared/src/hooks/__tests__/__source__/__untransformed__/
packages/react-devtools-shell/dist
packages/react-devtools-timeline/dist
packages/react-devtools-timeline/static
# Imported third-party Flow types
flow-typed/

View File

@@ -331,6 +331,7 @@ module.exports = {
'packages/react-server-dom-turbopack/**/*.js',
'packages/react-server-dom-parcel/**/*.js',
'packages/react-server-dom-fb/**/*.js',
'packages/react-server-dom-unbundled/**/*.js',
'packages/react-test-renderer/**/*.js',
'packages/react-debug-tools/**/*.js',
'packages/react-devtools-extensions/**/*.js',
@@ -468,6 +469,7 @@ module.exports = {
files: ['packages/react-server-dom-webpack/**/*.js'],
globals: {
__webpack_chunk_load__: 'readonly',
__webpack_get_script_filename__: 'readonly',
__webpack_require__: 'readonly',
},
},
@@ -505,7 +507,6 @@ module.exports = {
__IS_FIREFOX__: 'readonly',
__IS_EDGE__: 'readonly',
__IS_NATIVE__: 'readonly',
__IS_INTERNAL_MCP_BUILD__: 'readonly',
__IS_INTERNAL_VERSION__: 'readonly',
chrome: 'readonly',
},
@@ -516,6 +517,14 @@ module.exports = {
__IS_INTERNAL_VERSION__: 'readonly',
},
},
{
files: ['packages/react-devtools-*/**/*.js'],
excludedFiles: '**/__tests__/**/*.js',
plugins: ['eslint-plugin-react-hooks-published'],
rules: {
'react-hooks-published/rules-of-hooks': ERROR,
},
},
{
files: ['packages/eslint-plugin-react-hooks/src/**/*'],
extends: ['plugin:@typescript-eslint/recommended'],
@@ -546,13 +555,10 @@ module.exports = {
},
globals: {
$Call: 'readonly',
$ElementType: 'readonly',
$Flow$ModuleRef: 'readonly',
$FlowFixMe: 'readonly',
$Keys: 'readonly',
$NonMaybeType: 'readonly',
$PropertyType: 'readonly',
$ReadOnly: 'readonly',
$ReadOnlyArray: 'readonly',
$ArrayBufferView: 'readonly',
@@ -567,6 +573,7 @@ module.exports = {
BigInt: 'readonly',
BigInt64Array: 'readonly',
BigUint64Array: 'readonly',
CacheType: 'readonly',
Class: 'readonly',
ClientRect: 'readonly',
CopyInspectedElementPath: 'readonly',
@@ -578,16 +585,20 @@ module.exports = {
$AsyncIterator: 'readonly',
Iterator: 'readonly',
AsyncIterator: 'readonly',
IntervalID: 'readonly',
IteratorResult: 'readonly',
JSONValue: 'readonly',
JSResourceReference: 'readonly',
mixin$Animatable: 'readonly',
MouseEventHandler: 'readonly',
NavigateEvent: 'readonly',
Partial: 'readonly',
PerformanceMeasureOptions: 'readonly',
PropagationPhases: 'readonly',
PropertyDescriptor: 'readonly',
React$AbstractComponent: 'readonly',
PropertyDescriptorMap: 'readonly',
Proxy$traps: 'readonly',
React$Component: 'readonly',
React$ComponentType: 'readonly',
React$Config: 'readonly',
React$Context: 'readonly',
React$Element: 'readonly',
@@ -619,12 +630,12 @@ module.exports = {
PropertyIndexedKeyframes: 'readonly',
KeyframeAnimationOptions: 'readonly',
GetAnimationsOptions: 'readonly',
Animatable: 'readonly',
ScrollTimeline: 'readonly',
EventListenerOptionsOrUseCapture: 'readonly',
FocusOptions: 'readonly',
OptionalEffectTiming: 'readonly',
__REACT_ROOT_PATH_TEST__: 'readonly',
spyOnDev: 'readonly',
spyOnDevAndProd: 'readonly',
spyOnProd: 'readonly',

View File

@@ -11,7 +11,7 @@ body:
options:
- label: React Compiler core (the JS output is incorrect, or your app works incorrectly after optimization)
- label: babel-plugin-react-compiler (build issue installing or using the Babel plugin)
- label: eslint-plugin-react-compiler (build issue installing or using the eslint plugin)
- label: eslint-plugin-react-hooks (build issue installing or using the eslint plugin)
- label: react-compiler-healthcheck (build issue installing or using the healthcheck script)
- type: input
attributes:

View File

@@ -57,8 +57,6 @@ jobs:
key: playwright-browsers-v6-${{ runner.arch }}-${{ runner.os }}-${{ steps.playwright_version.outputs.playwright_version }}
- run: npx playwright install --with-deps chromium
if: steps.cache_playwright_browsers.outputs.cache-hit != 'true'
- run: npx playwright install-deps
if: steps.cache_playwright_browsers.outputs.cache-hit == 'true'
- run: CI=true yarn test
- run: ls -R test-results
if: '!cancelled()'

View File

@@ -19,6 +19,9 @@ on:
tag_version:
required: false
type: string
dry_run:
required: false
type: boolean
secrets:
NPM_TOKEN:
required: true
@@ -55,7 +58,13 @@ jobs:
key: compiler-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('compiler/yarn.lock') }}
- run: yarn install --frozen-lockfile
if: steps.node_modules.outputs.cache-hit != 'true'
- name: Publish packages to npm
- if: inputs.dry_run == true
name: Publish packages to npm (dry run)
run: |
cp ./scripts/release/ci-npmrc ~/.npmrc
scripts/release/publish.js --frfr --debug --ci --versionName=${{ inputs.version_name }} --tag=${{ inputs.dist_tag }} ${{ inputs.tag_version && format('--tagVersion={0}', inputs.tag_version) || '' }}
- if: inputs.dry_run != true
name: Publish packages to npm
run: |
cp ./scripts/release/ci-npmrc ~/.npmrc
scripts/release/publish.js --frfr --ci --versionName=${{ inputs.version_name }} --tag=${{ inputs.dist_tag }} ${{ inputs.tag_version && format('--tagVersion={0}', inputs.tag_version) || '' }}

View File

@@ -17,6 +17,9 @@ on:
tag_version:
required: false
type: string
dry_run:
required: false
type: boolean
permissions: {}
@@ -33,5 +36,6 @@ jobs:
dist_tag: ${{ inputs.dist_tag }}
version_name: ${{ inputs.version_name }}
tag_version: ${{ inputs.tag_version }}
dry_run: ${{ inputs.dry_run }}
secrets:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}

View File

@@ -19,5 +19,6 @@ jobs:
release_channel: experimental
dist_tag: experimental
version_name: '0.0.0'
dry_run: false
secrets:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}

View File

@@ -0,0 +1,49 @@
name: (DevTools) Discord Notify
on:
pull_request_target:
types: [opened, ready_for_review]
paths:
- packages/react-devtools**
- .github/workflows/devtools_**.yml
permissions: {}
jobs:
check_access:
if: ${{ github.event.pull_request.draft == false }}
runs-on: ubuntu-latest
outputs:
is_member_or_collaborator: ${{ steps.check_is_member_or_collaborator.outputs.is_member_or_collaborator }}
steps:
- run: echo ${{ github.event.pull_request.author_association }}
- name: Check is member or collaborator
id: check_is_member_or_collaborator
if: ${{ github.event.pull_request.author_association == 'MEMBER' || github.event.pull_request.author_association == 'COLLABORATOR' }}
run: echo "is_member_or_collaborator=true" >> "$GITHUB_OUTPUT"
check_maintainer:
if: ${{ needs.check_access.outputs.is_member_or_collaborator == 'true' || needs.check_access.outputs.is_member_or_collaborator == true }}
needs: [check_access]
uses: facebook/react/.github/workflows/shared_check_maintainer.yml@main
permissions:
# Used by check_maintainer
contents: read
with:
actor: ${{ github.event.pull_request.user.login }}
notify:
if: ${{ needs.check_maintainer.outputs.is_core_team == 'true' }}
needs: check_maintainer
runs-on: ubuntu-latest
steps:
- name: Discord Webhook Action
uses: tsickert/discord-webhook@86dc739f3f165f16dadc5666051c367efa1692f4
with:
webhook-url: ${{ secrets.DEVTOOLS_DISCORD_WEBHOOK_URL }}
embed-author-name: ${{ github.event.pull_request.user.login }}
embed-author-url: ${{ github.event.pull_request.user.html_url }}
embed-author-icon-url: ${{ github.event.pull_request.user.avatar_url }}
embed-title: '#${{ github.event.number }} (+${{github.event.pull_request.additions}} -${{github.event.pull_request.deletions}}): ${{ github.event.pull_request.title }}'
embed-description: ${{ github.event.pull_request.body }}
embed-url: ${{ github.event.pull_request.html_url }}

View File

@@ -92,7 +92,7 @@ jobs:
uses: actions/upload-artifact@v4
with:
name: react-devtools
path: build/devtools.tgz
path: build/devtools
if-no-files-found: error
# Simplifies getting the extension for local testing
- name: Archive chrome extension
@@ -201,5 +201,5 @@ jobs:
- uses: actions/upload-artifact@v4
with:
name: screenshots
path: ./tmp/screenshots
path: ./tmp/playwright-artifacts
if-no-files-found: warn

View File

@@ -3,6 +3,10 @@ name: (Runtime) Build and Test
on:
push:
branches: [main]
tags:
# To get CI for backport releases.
# This will duplicate CI for releases from main which is acceptable
- "v*"
pull_request:
paths-ignore:
- compiler/**
@@ -41,7 +45,7 @@ jobs:
with:
path: |
**/node_modules
key: runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
key: runtime-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
lookup-only: true
- uses: actions/setup-node@v4
if: steps.node_modules.outputs.cache-hit != 'true'
@@ -55,10 +59,8 @@ jobs:
with:
path: |
**/node_modules
key: runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
restore-keys: |
runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-
runtime-node_modules-v6-
key: runtime-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
# Don't use restore-keys here. Otherwise the cache grows indefinitely.
- run: yarn install --frozen-lockfile
if: steps.node_modules.outputs.cache-hit != 'true'
- name: Save cache
@@ -67,7 +69,7 @@ jobs:
with:
path: |
**/node_modules
key: runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
key: runtime-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
runtime_compiler_node_modules_cache:
name: Cache Runtime, Compiler node_modules
@@ -82,7 +84,7 @@ jobs:
with:
path: |
**/node_modules
key: runtime-and-compiler-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }}
key: runtime-and-compiler-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }}
lookup-only: true
- uses: actions/setup-node@v4
if: steps.node_modules.outputs.cache-hit != 'true'
@@ -98,10 +100,8 @@ jobs:
with:
path: |
**/node_modules
key: runtime-and-compiler-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }}
restore-keys: |
runtime-and-compiler-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-
runtime-and-compiler-node_modules-v6-
key: runtime-and-compiler-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }}
# Don't use restore-keys here. Otherwise the cache grows indefinitely.
- run: yarn install --frozen-lockfile
if: steps.node_modules.outputs.cache-hit != 'true'
- run: yarn --cwd compiler install --frozen-lockfile
@@ -112,7 +112,7 @@ jobs:
with:
path: |
**/node_modules
key: runtime-and-compiler-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }}
key: runtime-and-compiler-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }}
# ----- FLOW -----
discover_flow_inline_configs:
@@ -154,10 +154,8 @@ jobs:
with:
path: |
**/node_modules
key: runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
restore-keys: |
runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-
runtime-node_modules-v6-
key: runtime-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
# Don't use restore-keys here. Otherwise the cache grows indefinitely.
- name: Ensure clean build directory
run: rm -rf build
- run: yarn install --frozen-lockfile
@@ -184,17 +182,15 @@ jobs:
with:
path: |
**/node_modules
key: runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
restore-keys: |
runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-
runtime-node_modules-v6-
key: runtime-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
# Don't use restore-keys here. Otherwise the cache grows indefinitely.
- name: Ensure clean build directory
run: rm -rf build
- run: yarn install --frozen-lockfile
if: steps.node_modules.outputs.cache-hit != 'true'
- run: |
yarn generate-inline-fizz-runtime
git diff --quiet || (echo "There was a change to the Fizz runtime. Run `yarn generate-inline-fizz-runtime` and check in the result." && false)
git diff --exit-code || (echo "There was a change to the Fizz runtime. Run \`yarn generate-inline-fizz-runtime\` and check in the result." && false)
# ----- FEATURE FLAGS -----
flags:
@@ -216,7 +212,7 @@ jobs:
with:
path: |
**/node_modules
key: runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
key: runtime-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
- name: Ensure clean build directory
run: rm -rf build
- run: yarn install --frozen-lockfile
@@ -274,16 +270,15 @@ jobs:
with:
path: |
**/node_modules
key: runtime-and-compiler-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }}
restore-keys: |
runtime-and-compiler-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-
runtime-and-compiler-node_modules-v6-
key: runtime-and-compiler-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }}
# Don't use restore-keys here. Otherwise the cache grows indefinitely.
- name: Ensure clean build directory
run: rm -rf build
- run: yarn install --frozen-lockfile
if: steps.node_modules.outputs.cache-hit != 'true'
- run: yarn --cwd compiler install --frozen-lockfile
if: steps.node_modules.outputs.cache-hit != 'true'
- run: node --version
- run: yarn test ${{ matrix.params }} --ci --shard=${{ matrix.shard }}
# Hardcoded to improve parallelism
@@ -306,7 +301,7 @@ jobs:
with:
path: |
**/node_modules
key: runtime-and-compiler-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }}
key: runtime-and-compiler-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }}
- name: Install runtime dependencies
run: yarn install --frozen-lockfile
if: steps.node_modules.outputs.cache-hit != 'true'
@@ -316,7 +311,7 @@ jobs:
if: steps.node_modules.outputs.cache-hit != 'true'
- run: ./scripts/react-compiler/build-compiler.sh && ./scripts/react-compiler/link-compiler.sh
- run: yarn workspace eslint-plugin-react-hooks test
# ----- BUILD -----
build_and_lint:
name: yarn build and lint
@@ -349,10 +344,8 @@ jobs:
with:
path: |
**/node_modules
key: runtime-and-compiler-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }}
restore-keys: |
runtime-and-compiler-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-
runtime-and-compiler-node_modules-v6-
key: runtime-and-compiler-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }}
# Don't use restore-keys here. Otherwise the cache grows indefinitely.
- name: Ensure clean build directory
run: rm -rf build
- run: yarn install --frozen-lockfile
@@ -390,9 +383,6 @@ jobs:
-r=experimental --env=development,
-r=experimental --env=production,
# Dev Tools
--project=devtools -r=experimental,
# TODO: Update test config to support www build tests
# - "-r=www-classic --env=development --variant=false"
# - "-r=www-classic --env=production --variant=false"
@@ -440,10 +430,8 @@ jobs:
with:
path: |
**/node_modules
key: runtime-and-compiler-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }}
restore-keys: |
runtime-and-compiler-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-
runtime-and-compiler-node_modules-v6-
key: runtime-and-compiler-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock', 'compiler/yarn.lock') }}
# Don't use restore-keys here. Otherwise the cache grows indefinitely.
- name: Ensure clean build directory
run: rm -rf build
- run: yarn install --frozen-lockfile
@@ -458,8 +446,54 @@ jobs:
merge-multiple: true
- name: Display structure of build
run: ls -R build
- run: node --version
- run: yarn test --build ${{ matrix.test_params }} --shard=${{ matrix.shard }} --ci
test_build_devtools:
name: yarn test-build (devtools)
needs: [build_and_lint, runtime_node_modules_cache]
strategy:
fail-fast: false
matrix:
shard:
- 1/5
- 2/5
- 3/5
- 4/5
- 5/5
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.commit_sha != '' && github.event.inputs.commit_sha || github.event.pull_request.head.sha || github.sha }}
- uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: yarn
cache-dependency-path: yarn.lock
- name: Restore cached node_modules
uses: actions/cache/restore@v4
id: node_modules
with:
path: |
**/node_modules
key: runtime-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
# Don't use restore-keys here. Otherwise the cache grows indefinitely.
- name: Ensure clean build directory
run: rm -rf build
- run: yarn install --frozen-lockfile
if: steps.node_modules.outputs.cache-hit != 'true'
- name: Restore archived build
uses: actions/download-artifact@v4
with:
pattern: _build_*
path: build
merge-multiple: true
- name: Display structure of build
run: ls -R build
- run: node --version
- run: yarn test --build --project=devtools -r=experimental --shard=${{ matrix.shard }} --ci
process_artifacts_combined:
name: Process artifacts combined
needs: [build_and_lint, runtime_node_modules_cache]
@@ -483,10 +517,8 @@ jobs:
with:
path: |
**/node_modules
key: runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
restore-keys: |
runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-
runtime-node_modules-v6-
key: runtime-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
# Don't use restore-keys here. Otherwise the cache grows indefinitely.
- name: Ensure clean build directory
run: rm -rf build
- run: yarn install --frozen-lockfile
@@ -548,10 +580,8 @@ jobs:
with:
path: |
**/node_modules
key: runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
restore-keys: |
runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-
runtime-node_modules-v6-
key: runtime-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
# Don't use restore-keys here. Otherwise the cache grows indefinitely.
- name: Ensure clean build directory
run: rm -rf build
- run: yarn install --frozen-lockfile
@@ -567,7 +597,7 @@ jobs:
- name: Search build artifacts for unminified errors
run: |
yarn extract-errors
git diff --quiet || (echo "Found unminified errors. Either update the error codes map or disable error minification for the affected build, if appropriate." && false)
git diff --exit-code || (echo "Found unminified errors. Either update the error codes map or disable error minification for the affected build, if appropriate." && false)
check_release_dependencies:
name: Check release dependencies
@@ -588,10 +618,8 @@ jobs:
with:
path: |
**/node_modules
key: runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
restore-keys: |
runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-
runtime-node_modules-v6-
key: runtime-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
# Don't use restore-keys here. Otherwise the cache grows indefinitely.
- name: Ensure clean build directory
run: rm -rf build
- run: yarn install --frozen-lockfile
@@ -740,10 +768,8 @@ jobs:
with:
path: |
**/node_modules
key: runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
restore-keys: |
runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-
runtime-node_modules-v6-
key: runtime-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
# Don't use restore-keys here. Otherwise the cache grows indefinitely.
- name: Ensure clean build directory
run: rm -rf build
- run: yarn install --frozen-lockfile
@@ -766,6 +792,11 @@ jobs:
name: react-devtools-${{ matrix.browser }}-extension
path: build/devtools/${{ matrix.browser }}-extension.zip
if-no-files-found: error
- name: Archive ${{ matrix.browser }} metadata
uses: actions/upload-artifact@v4
with:
name: react-devtools-${{ matrix.browser }}-metadata
path: build/devtools/webpack-stats.*.json
merge_devtools_artifacts:
name: Merge DevTools artifacts
@@ -776,7 +807,7 @@ jobs:
uses: actions/upload-artifact/merge@v4
with:
name: react-devtools
pattern: react-devtools-*-extension
pattern: react-devtools-*
run_devtools_e2e_tests:
name: Run DevTools e2e tests
@@ -797,10 +828,8 @@ jobs:
with:
path: |
**/node_modules
key: runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
restore-keys: |
runtime-node_modules-v6-${{ runner.arch }}-${{ runner.os }}-
runtime-node_modules-v6-
key: runtime-node_modules-v7-${{ runner.arch }}-${{ runner.os }}-${{ hashFiles('yarn.lock') }}
# Don't use restore-keys here. Otherwise the cache grows indefinitely.
- name: Ensure clean build directory
run: rm -rf build
- run: yarn install --frozen-lockfile
@@ -811,12 +840,27 @@ jobs:
pattern: _build_*
path: build
merge-multiple: true
- run: |
npx playwright install
sudo npx playwright install-deps
- name: Check Playwright version
id: playwright_version
run: echo "playwright_version=$(npm ls @playwright/test | grep @playwright | sed 's/.*@//' | head -1)" >> "$GITHUB_OUTPUT"
- name: Cache Playwright Browsers for version ${{ steps.playwright_version.outputs.playwright_version }}
id: cache_playwright_browsers
uses: actions/cache@v4
with:
path: ~/.cache/ms-playwright
key: playwright-browsers-v6-${{ runner.arch }}-${{ runner.os }}-${{ steps.playwright_version.outputs.playwright_version }}
- name: Playwright install deps
if: steps.cache_playwright_browsers.outputs.cache-hit != 'true'
run: npx playwright install --with-deps chromium
- run: ./scripts/ci/run_devtools_e2e_tests.js
env:
RELEASE_CHANNEL: experimental
- name: Archive Playwright report
uses: actions/upload-artifact@v4
with:
name: devtools-playwright-artifacts
path: tmp/playwright-artifacts
if-no-files-found: warn
# ----- SIZEBOT -----
sizebot:

View File

@@ -162,10 +162,13 @@ jobs:
mv build/facebook-react-native/react-is/cjs/ $BASE_FOLDER/RKJSModules/vendor/react/react-is/
mv build/facebook-react-native/react-test-renderer/cjs/ $BASE_FOLDER/RKJSModules/vendor/react/react-test-renderer/
# Delete OSS renderer. OSS renderer is synced through internal script.
# Delete the OSS renderers, these are sync'd to RN separately.
RENDERER_FOLDER=$BASE_FOLDER/react-native-github/Libraries/Renderer/implementations/
rm $RENDERER_FOLDER/ReactFabric-{dev,prod,profiling}.js
rm $RENDERER_FOLDER/ReactNativeRenderer-{dev,prod,profiling}.js
# Delete the legacy renderer shim, this is not sync'd and will get deleted in the future.
SHIM_FOLDER=$BASE_FOLDER/react-native-github/Libraries/Renderer/shims/
rm $SHIM_FOLDER/ReactNative.js
# Copy eslint-plugin-react-hooks
# NOTE: This is different from www, here we include the full package

View File

@@ -4,8 +4,10 @@ on:
pull_request_target:
types: [opened, ready_for_review]
paths-ignore:
- packages/react-devtools**
- compiler/**
- .github/workflows/compiler_**.yml
- .github/workflows/devtools**.yml
permissions: {}

View File

@@ -29,6 +29,7 @@ jobs:
- "7"
- "8"
- "9"
- "10"
steps:
- uses: actions/checkout@v4
with:

View File

@@ -82,7 +82,6 @@ jobs:
run: |
scripts/release/publish.js \
--ci \
--skipTests \
--tags=${{ inputs.dist_tag }} \
--onlyPackages=${{ inputs.only_packages }} ${{ (inputs.dry && '') || '\'}}
${{ inputs.dry && '--dry' || '' }}
@@ -91,11 +90,10 @@ jobs:
run: |
scripts/release/publish.js \
--ci \
--skipTests \
--tags=${{ inputs.dist_tag }} \
--skipPackages=${{ inputs.skip_packages }} ${{ (inputs.dry && '') || '\'}}
${{ inputs.dry && '--dry' || '' }}
- if: '${{ !(inputs.skip_packages && inputs.only_packages) }}'
- if: '${{ !inputs.skip_packages && !inputs.only_packages }}'
name: 'Publish all packages'
run: |
scripts/release/publish.js \

View File

@@ -18,6 +18,7 @@ jobs:
permissions:
# Used to create a review and close PRs
pull-requests: write
contents: write
steps:
- name: Close PR
uses: actions/github-script@v7

3
.gitignore vendored
View File

@@ -23,6 +23,9 @@ chrome-user-data
.vscode
*.swp
*.swo
/tmp
/.worktrees
.claude/*.local.*
packages/react-devtools-core/dist
packages/react-devtools-extensions/chrome/build

View File

@@ -1,3 +1,88 @@
## 19.2.1 (Dec 3, 2025)
### React Server Components
- Bring React Server Component fixes to Server Actions (@sebmarkbage [#35277](https://github.com/facebook/react/pull/35277))
## 19.2.0 (October 1st, 2025)
Below is a list of all new features, APIs, and bug fixes.
Read the [React 19.2 release post](https://react.dev/blog/2025/10/01/react-19-2) for more information.
### New React Features
- [`<Activity>`](https://react.dev/reference/react/Activity): A new API to hide and restore the UI and internal state of its children.
- [`useEffectEvent`](https://react.dev/reference/react/useEffectEvent) is a React Hook that lets you extract non-reactive logic into an [Effect Event](https://react.dev/learn/separating-events-from-effects#declaring-an-effect-event).
- [`cacheSignal`](https://react.dev/reference/react/cacheSignal) (for RSCs) lets your know when the `cache()` lifetime is over.
- [React Performance tracks](https://react.dev/reference/dev-tools/react-performance-tracks) appear on the Performance panels timeline in your browser developer tools
### New React DOM Features
- Added resume APIs for partial pre-rendering with Web Streams:
- [`resume`](https://react.dev/reference/react-dom/server/resume): to resume a prerender to a stream.
- [`resumeAndPrerender`](https://react.dev/reference/react-dom/static/resumeAndPrerender): to resume a prerender to HTML.
- Added resume APIs for partial pre-rendering with Node Streams:
- [`resumeToPipeableStream`](https://react.dev/reference/react-dom/server/resumeToPipeableStream): to resume a prerender to a stream.
- [`resumeAndPrerenderToNodeStream`](https://react.dev/reference/react-dom/static/resumeAndPrerenderToNodeStream): to resume a prerender to HTML.
- Updated [`prerender`](https://react.dev/reference/react-dom/static/prerender) APIs to return a `postponed` state that can be passed to the `resume` APIs.
### Notable changes
- React DOM now batches suspense boundary reveals, matching the behavior of client side rendering. This change is especially noticeable when animating the reveal of Suspense boundaries e.g. with the upcoming `<ViewTransition>` Component. React will batch as much reveals as possible before the first paint while trying to hit popular first-contentful paint metrics.
- Add Node Web Streams (`prerender`, `renderToReadableStream`) to server-side-rendering APIs for Node.js
- Use underscore instead of `:` IDs generated by useId
### All Changes
#### React
- `<Activity />` was developed over many years, starting before `ClassComponent.setState` (@acdlite @sebmarkbage and many others)
- Stringify context as "SomeContext" instead of "SomeContext.Provider" (@kassens [#33507](https://github.com/facebook/react/pull/33507))
- Include stack of cause of React instrumentation errors with `%o` placeholder (@eps1lon [#34198](https://github.com/facebook/react/pull/34198))
- Fix infinite `useDeferredValue` loop in popstate event (@acdlite [#32821](https://github.com/facebook/react/pull/32821))
- Fix a bug when an initial value was passed to `useDeferredValue` (@acdlite [#34376](https://github.com/facebook/react/pull/34376))
- Fix a crash when submitting forms with Client Actions (@sebmarkbage [#33055](https://github.com/facebook/react/pull/33055))
- Hide/unhide the content of dehydrated suspense boundaries if they resuspend (@sebmarkbage [#32900](https://github.com/facebook/react/pull/32900))
- Avoid stack overflow on wide trees during Hot Reload (@sophiebits [#34145](https://github.com/facebook/react/pull/34145))
- Improve Owner and Component stacks in various places (@sebmarkbage, @eps1lon: [#33629](https://github.com/facebook/react/pull/33629), [#33724](https://github.com/facebook/react/pull/33724), [#32735](https://github.com/facebook/react/pull/32735), [#33723](https://github.com/facebook/react/pull/33723))
- Add `cacheSignal` (@sebmarkbage [#33557](https://github.com/facebook/react/pull/33557))
#### React DOM
- Block on Suspensey Fonts during reveal of server-side-rendered content (@sebmarkbage [#33342](https://github.com/facebook/react/pull/33342))
- Use underscore instead of `:` for IDs generated by `useId` (@sebmarkbage, @eps1lon: [#32001](https://github.com/facebook/react/pull/32001), [https://github.com/facebook/react/pull/33342](https://github.com/facebook/react/pull/33342)[#33099](https://github.com/facebook/react/pull/33099), [#33422](https://github.com/facebook/react/pull/33422))
- Stop warning when ARIA 1.3 attributes are used (@Abdul-Omira [#34264](https://github.com/facebook/react/pull/34264))
- Allow `nonce` to be used on hoistable styles (@Andarist [#32461](https://github.com/facebook/react/pull/32461))
- Warn for using a React owned node as a Container if it also has text content (@sebmarkbage [#32774](https://github.com/facebook/react/pull/32774))
- s/HTML/text for for error messages if text hydration mismatches (@rickhanlonii [#32763](https://github.com/facebook/react/pull/32763))
- Fix a bug with `React.use` inside `React.lazy`\-ed Component (@hi-ogawa [#33941](https://github.com/facebook/react/pull/33941))
- Enable the `progressiveChunkSize` option for server-side-rendering APIs (@sebmarkbage [#33027](https://github.com/facebook/react/pull/33027))
- Fix a bug with deeply nested Suspense inside Suspense fallback when server-side-rendering (@gnoff [#33467](https://github.com/facebook/react/pull/33467))
- Avoid hanging when suspending after aborting while rendering (@gnoff [#34192](https://github.com/facebook/react/pull/34192))
- Add Node Web Streams to server-side-rendering APIs for Node.js (@sebmarkbage [#33475](https://github.com/facebook/react/pull/33475))
#### React Server Components
- Preload `<img>` and `<link>` using hints before they're rendered (@sebmarkbage [#34604](https://github.com/facebook/react/pull/34604))
- Log error if production elements are rendered during development (@eps1lon [#34189](https://github.com/facebook/react/pull/34189))
- Fix a bug when returning a Temporary reference (e.g. a Client Reference) from Server Functions (@sebmarkbage [#34084](https://github.com/facebook/react/pull/34084), @denk0403 [#33761](https://github.com/facebook/react/pull/33761))
- Pass line/column to `filterStackFrame` (@eps1lon [#33707](https://github.com/facebook/react/pull/33707))
- Support Async Modules in Turbopack Server References (@lubieowoce [#34531](https://github.com/facebook/react/pull/34531))
- Add support for .mjs file extension in Webpack (@jennyscript [#33028](https://github.com/facebook/react/pull/33028))
- Fix a wrong missing key warning (@unstubbable [#34350](https://github.com/facebook/react/pull/34350))
- Make console log resolve in predictable order (@sebmarkbage [#33665](https://github.com/facebook/react/pull/33665))
#### React Reconciler
- [createContainer](https://github.com/facebook/react/blob/v19.2.0/packages/react-reconciler/src/ReactFiberReconciler.js#L255-L261) and [createHydrationContainer](https://github.com/facebook/react/blob/v19.2.0/packages/react-reconciler/src/ReactFiberReconciler.js#L305-L312) had their parameter order adjusted after `on*` handlers to account for upcoming experimental APIs
## 19.1.2 (Dec 3, 2025)
### React Server Components
- Bring React Server Component fixes to Server Actions (@sebmarkbage [#35277](https://github.com/facebook/react/pull/35277))
## 19.1.1 (July 28, 2025)
### React
@@ -50,6 +135,12 @@ An Owner Stack is a string representing the components that are directly respons
* Exposed `registerServerReference` in client builds to handle server references in different environments. [#32534](https://github.com/facebook/react/pull/32534)
* Added react-server-dom-parcel package which integrates Server Components with the [Parcel bundler](https://parceljs.org/) [#31725](https://github.com/facebook/react/pull/31725), [#32132](https://github.com/facebook/react/pull/32132), [#31799](https://github.com/facebook/react/pull/31799), [#32294](https://github.com/facebook/react/pull/32294), [#31741](https://github.com/facebook/react/pull/31741)
## 19.0.1 (Dec 3, 2025)
### React Server Components
- Bring React Server Component fixes to Server Actions (@sebmarkbage [#35277](https://github.com/facebook/react/pull/35277))
## 19.0.0 (December 5, 2024)
Below is a list of all new features, APIs, deprecations, and breaking changes. Read [React 19 release post](https://react.dev/blog/2024/04/25/react-19) and [React 19 upgrade guide](https://react.dev/blog/2024/04/25/react-19-upgrade-guide) for more information.

8
CLAUDE.md Normal file
View File

@@ -0,0 +1,8 @@
# React
React is a JavaScript library for building user interfaces.
## Monorepo Overview
- **React**: All files outside `/compiler/`
- **React Compiler**: `/compiler/` directory (has its own instructions)

View File

@@ -1,5 +1,6 @@
acdlite
eps1lon
EugeneChoi4
gaearon
gnoff
unstubbable

View File

@@ -7,18 +7,18 @@
//
// The @latest channel uses the version as-is, e.g.:
//
// 19.1.0
// 19.3.0
//
// The @canary channel appends additional information, with the scheme
// <version>-<label>-<commit_sha>, e.g.:
//
// 19.1.0-canary-a1c2d3e4
// 19.3.0-canary-a1c2d3e4
//
// The @experimental channel doesn't include a version, only a date and a sha, e.g.:
//
// 0.0.0-experimental-241c4467e-20200129
const ReactVersion = '19.2.0';
const ReactVersion = '19.3.0';
// The label used by the @canary channel. Represents the upcoming release's
// stability. Most of the time, this will be "canary", but we may temporarily
@@ -33,8 +33,8 @@ const canaryChannelLabel = 'canary';
const rcNumber = 0;
const stablePackages = {
'eslint-plugin-react-hooks': '6.1.0',
'jest-react': '0.17.0',
'eslint-plugin-react-hooks': '7.1.0',
'jest-react': '0.18.0',
react: ReactVersion,
'react-art': ReactVersion,
'react-dom': ReactVersion,
@@ -42,12 +42,12 @@ const stablePackages = {
'react-server-dom-turbopack': ReactVersion,
'react-server-dom-parcel': ReactVersion,
'react-is': ReactVersion,
'react-reconciler': '0.33.0',
'react-refresh': '0.18.0',
'react-reconciler': '0.34.0',
'react-refresh': '0.19.0',
'react-test-renderer': ReactVersion,
'use-subscription': '1.12.0',
'use-sync-external-store': '1.6.0',
scheduler: '0.27.0',
'use-subscription': '1.13.0',
'use-sync-external-store': '1.7.0',
scheduler: '0.28.0',
};
// These packages do not exist in the @canary or @latest channel, only

View File

@@ -8,6 +8,7 @@ module.exports = {
'@babel/plugin-syntax-jsx',
'@babel/plugin-transform-flow-strip-types',
['@babel/plugin-transform-class-properties', {loose: true}],
['@babel/plugin-transform-private-methods', {loose: true}],
'@babel/plugin-transform-classes',
],
presets: [

View File

@@ -0,0 +1,113 @@
---
name: investigate-error
description: Investigates React compiler errors to determine the root cause and identify potential mitigation(s). Use this agent when the user asks to 'investigate a bug', 'debug why this fixture errors', 'understand why the compiler is failing', 'find the root cause of a compiler issue', or when they provide a snippet of code and ask to debug. Use automatically when encountering a failing test case, in order to understand the root cause.
model: opus
color: pink
---
You are an expert React Compiler debugging specialist with deep knowledge of compiler internals, intermediate representations, and optimization passes. Your mission is to systematically investigate compiler bugs to identify root causes and provide actionable information for fixes.
## Your Investigation Process
### Step 1: Create Test Fixture
Create a new fixture file at `packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/<fixture-name>.js` containing the problematic code. Use a descriptive name that reflects the issue (e.g., `bug-optional-chain-in-effect.js`).
### Step 2: Run Debug Compilation
Execute `yarn snap -d -p <fixture-name>` to compile the fixture with full debug output. This shows the state of the program after each compilation pass. You can also use `yarn snap compile -d <path-to-fixture>`.
### Step 3: Analyze Compilation Results
### Step 3a: If the fixture compiles successfully
- Compare the output against the user's expected behavior
- Review each compilation pass output from the `-d` flag
- Identify the first pass where the output diverges from expected behavior
- Proceed to binary search simplification
### Step 3b: If the fixture errors
Execute `yarn snap minimize --update <path-to-fixture>` to remove non-critical aspects of the failing test case. This **updates the fixture in place**.
Re-read the fixture file to see the latest, minimal reproduction of the error.
### Step 4: Iteratively adjust the fixture until it stops erroring
After the previous step the fixture will have all extraneous aspects removed. Try to make further edits to determine the specific feature that is causing the error.
Ideas:
* Replace immediately-invoked function expressions with labeled blocks
* Remove statements
* Simplify calls (remove arguments, replace the call with its lone argument)
* Simplify control flow statements by picking a single branch. Try using a labeled block with just the selected block
* Replace optional member/call expressions with non-optional versions
* Remove items in array/object expressions
* Remove properties from member expressions
Try to make the minimal possible edit to get the fixture stop erroring.
### Step 5: Compare Debug Outputs
With both minimal versions (failing and non-failing):
- Run `yarn snap -d -p <fixture-name>` on both
- Compare the debug output pass-by-pass
- Identify the exact pass where behavior diverges
- Note specific differences in HIR, effects, or generated code
### Step 6: Investigate Compiler Logic
- Read the documentation for the problematic pass in `packages/babel-plugin-react-compiler/docs/passes/`
- Examine the pass implementation in `packages/babel-plugin-react-compiler/src/`
- Key directories to investigate:
- `src/HIR/` - IR definitions and utilities
- `src/Inference/` - Effect inference (aliasing, mutation)
- `src/Validation/` - Validation passes
- `src/Optimization/` - Optimization passes
- `src/ReactiveScopes/` - Reactive scope analysis
- Identify specific code locations that may be handling the pattern incorrectly
## Output Format
Provide a structured investigation report:
```
## Investigation Summary
### Bug Description
[Brief description of the issue]
### Minimal Failing Fixture
```javascript
// packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/<name>.js
[minimal code that reproduces the error]
```
### Minimal Non-Failing Fixture
```javascript
// The simplest change that makes it work
[code that compiles correctly]
```
### Problematic Compiler Pass
[Name of the pass where the issue occurs]
### Root Cause Analysis
[Explanation of what the compiler is doing wrong]
### Suspect Code Locations
- `packages/babel-plugin-react-compiler/src/<path>:<line>:<column>` - [description of what may be incorrect]
- [additional locations if applicable]
### Suggested Fix Direction
[Brief suggestion of how the bug might be fixed]
```
## Key Debugging Tips
1. The debug output (`-d` flag) shows the program state after each pass - use this to pinpoint where things go wrong
2. Look for `@aliasingEffects=` on FunctionExpressions to understand data flow
3. Check for `Impure`, `Render`, `Capture` effects on instructions
4. The pass ordering in `Pipeline.ts` shows when effects are populated vs validated
5. Todo errors indicate unsupported but known patterns; Invariant errors indicate unexpected states
## Important Reminders
- Always create the fixture file before running tests
- Use descriptive fixture names that indicate the bug being investigated
- Keep both failing and non-failing minimal versions for your report
- Provide specific file:line:column references when identifying suspect code
- Read the relevant pass documentation before making conclusions about the cause

View File

@@ -0,0 +1,18 @@
{
"permissions": {
"allow": [
"Bash(yarn snap:*)",
"Bash(yarn snap:build)",
"Bash(node scripts/enable-feature-flag.js:*)"
],
"deny": [
"Skill(extract-errors)",
"Skill(feature-flags)",
"Skill(fix)",
"Skill(flags)",
"Skill(flow)",
"Skill(test)",
"Skill(verify)"
]
}
}

2
compiler/.gitignore vendored
View File

@@ -8,7 +8,9 @@ dist
.vscode
!packages/playground/.vscode
testfilter.txt
.claude/settings.local.json
# forgive
*.vsix
.vscode-test

248
compiler/CLAUDE.md Normal file
View File

@@ -0,0 +1,248 @@
# React Compiler Knowledge Base
This document contains knowledge about the React Compiler gathered during development sessions. It serves as a reference for understanding the codebase architecture and key concepts.
## Project Structure
When modifying the compiler, you MUST read the documentation about that pass in `compiler/packages/babel-plugin-react-compiler/docs/passes/` to learn more about the role of that pass within the compiler.
- `packages/babel-plugin-react-compiler/` - Main compiler package
- `src/HIR/` - High-level Intermediate Representation types and utilities
- `src/Inference/` - Effect inference passes (aliasing, mutation, etc.)
- `src/Validation/` - Validation passes that check for errors
- `src/Entrypoint/Pipeline.ts` - Main compilation pipeline with pass ordering
- `src/__tests__/fixtures/compiler/` - Test fixtures
- `error.todo-*.js` - Unsupported feature, correctly throws Todo error (graceful bailout)
- `error.bug-*.js` - Known bug, throws wrong error type or incorrect behavior
- `*.expect.md` - Expected output for each fixture
## Running Tests
```bash
# Run all tests
yarn snap
# Run tests matching a pattern
# Example: yarn snap -p 'error.*'
yarn snap -p <pattern>
# Run a single fixture in debug mode. Use the path relative to the __tests__/fixtures/compiler directory
# For each step of compilation, outputs the step name and state of the compiled program
# Example: yarn snap -p simple.js -d
yarn snap -p <file-basename> -d
# Update fixture outputs (also works with -p)
yarn snap -u
```
## Compiling Arbitrary Files
Use `yarn snap compile` to compile any file (not just fixtures) with the React Compiler:
```bash
# Compile a file and see the output
yarn snap compile <path>
# Compile with debug logging to see the state after each compiler pass
# This is an alternative to `yarn snap -d -p <pattern>` when you don't have a fixture file yet
yarn snap compile --debug <path>
```
## Minimizing Test Cases
Use `yarn snap minimize` to automatically reduce a failing test case to its minimal reproduction:
```bash
# Minimize a file that causes a compiler error
yarn snap minimize <path>
# Minimize and update the file in-place with the minimized version
yarn snap minimize --update <path>
```
## Version Control
This repository uses Sapling (`sl`) for version control. Sapling is similar to Mercurial: there is not staging area, but new/deleted files must be explicitlyu added/removed.
```bash
# Check status
sl status
# Add new files, remove deleted files
sl addremove
# Commit all changes
sl commit -m "Your commit message"
# Commit with multi-line message using heredoc
sl commit -m "$(cat <<'EOF'
Summary line
Detailed description here
EOF
)"
```
## Key Concepts
### HIR (High-level Intermediate Representation)
The compiler converts source code to HIR for analysis. Key types in `src/HIR/HIR.ts`:
- **HIRFunction** - A function being compiled
- `body.blocks` - Map of BasicBlocks
- `context` - Captured variables from outer scope
- `params` - Function parameters
- `returns` - The function's return place
- `aliasingEffects` - Effects that describe the function's behavior when called
- **Instruction** - A single operation
- `lvalue` - The place being assigned to
- `value` - The instruction kind (CallExpression, FunctionExpression, LoadLocal, etc.)
- `effects` - Array of AliasingEffects for this instruction
- **Terminal** - Block terminators (return, branch, etc.)
- `effects` - Array of AliasingEffects
- **Place** - A reference to a value
- `identifier.id` - Unique IdentifierId
- **Phi nodes** - Join points for values from different control flow paths
- Located at `block.phis`
- `phi.place` - The result place
- `phi.operands` - Map of predecessor block to source place
### AliasingEffects System
Effects describe data flow and operations. Defined in `src/Inference/AliasingEffects.ts`:
**Data Flow Effects:**
- `Impure` - Marks a place as containing an impure value (e.g., Date.now() result, ref.current)
- `Capture a -> b` - Value from `a` is captured into `b` (mutable capture)
- `Alias a -> b` - `b` aliases `a`
- `ImmutableCapture a -> b` - Immutable capture (like Capture but read-only)
- `Assign a -> b` - Direct assignment
- `MaybeAlias a -> b` - Possible aliasing
- `CreateFrom a -> b` - Created from source
**Mutation Effects:**
- `Mutate value` - Value is mutated
- `MutateTransitive value` - Value and transitive captures are mutated
- `MutateConditionally value` - May mutate
- `MutateTransitiveConditionally value` - May mutate transitively
**Other Effects:**
- `Render place` - Place is used in render context (JSX props, component return)
- `Freeze place` - Place is frozen (made immutable)
- `Create place` - New value created
- `CreateFunction` - Function expression created, includes `captures` array
- `Apply` - Function application with receiver, function, args, and result
### Hook Aliasing Signatures
Located in `src/HIR/Globals.ts`, hooks can define custom aliasing signatures to control how data flows through them.
**Structure:**
```typescript
aliasing: {
receiver: '@receiver', // The hook function itself
params: ['@param0'], // Named positional parameters
rest: '@rest', // Rest parameters (or null)
returns: '@returns', // Return value
temporaries: [], // Temporary values during execution
effects: [ // Array of effects to apply when hook is called
{kind: 'Freeze', value: '@param0', reason: ValueReason.HookCaptured},
{kind: 'Assign', from: '@param0', into: '@returns'},
],
}
```
**Common patterns:**
1. **RenderHookAliasing** (useState, useContext, useMemo, useCallback):
- Freezes arguments (`Freeze @rest`)
- Marks arguments as render-time (`Render @rest`)
- Creates frozen return value
- Aliases arguments to return
2. **EffectHookAliasing** (useEffect, useLayoutEffect, useInsertionEffect):
- Freezes function and deps
- Creates internal effect object
- Captures function and deps into effect
- Returns undefined
3. **Event handler hooks** (useEffectEvent):
- Freezes callback (`Freeze @fn`)
- Aliases input to return (`Assign @fn -> @returns`)
- NO Render effect (callback not called during render)
**Example: useEffectEvent**
```typescript
const UseEffectEventHook = addHook(
DEFAULT_SHAPES,
{
positionalParams: [Effect.Freeze], // Takes one positional param
restParam: null,
returnType: {kind: 'Function', ...},
calleeEffect: Effect.Read,
hookKind: 'useEffectEvent',
returnValueKind: ValueKind.Frozen,
aliasing: {
receiver: '@receiver',
params: ['@fn'], // Name for the callback parameter
rest: null,
returns: '@returns',
temporaries: [],
effects: [
{kind: 'Freeze', value: '@fn', reason: ValueReason.HookCaptured},
{kind: 'Assign', from: '@fn', into: '@returns'},
// Note: NO Render effect - callback is not called during render
],
},
},
BuiltInUseEffectEventId,
);
// Add as both names for compatibility
['useEffectEvent', UseEffectEventHook],
['experimental_useEffectEvent', UseEffectEventHook],
```
**Key insight:** If a hook is missing an `aliasing` config, it falls back to `DefaultNonmutatingHook` which includes a `Render` effect on all arguments. This can cause false positives for hooks like `useEffectEvent` whose callbacks are not called during render.
## Feature Flags
Feature flags are configured in `src/HIR/Environment.ts`, for example `enableJsxOutlining`. Test fixtures can override the active feature flags used for that fixture via a comment pragma on the first line of the fixture input, for example:
```javascript
// enableJsxOutlining @enableNameAnonymousFunctions:false
...code...
```
Would enable the `enableJsxOutlining` feature and disable the `enableNameAnonymousFunctions` feature.
## Debugging Tips
1. Run `yarn snap -p <fixture>` to see full HIR output with effects
2. Look for `@aliasingEffects=` on FunctionExpressions
3. Look for `Impure`, `Render`, `Capture` effects on instructions
4. Check the pass ordering in Pipeline.ts to understand when effects are populated vs validated
## Error Handling for Unsupported Features
When the compiler encounters an unsupported but known pattern, use `CompilerError.throwTodo()` instead of `CompilerError.invariant()`. Todo errors cause graceful bailouts in production; Invariant errors are hard failures indicating unexpected/invalid states.
```typescript
// Unsupported but expected pattern - graceful bailout
CompilerError.throwTodo({
reason: `Support [description of unsupported feature]`,
loc: terminal.loc,
});
// Invariant is for truly unexpected/invalid states - hard failure
CompilerError.invariant(false, {
reason: `Unexpected [thing]`,
loc: terminal.loc,
});
```

View File

@@ -12,6 +12,7 @@
# next.js
/.next/
/out/
/next-env.d.ts
# production
/build

View File

@@ -1,5 +1,4 @@
import { c as _c } from "react/compiler-runtime"; // 
@compilationMode:"all"
import { c as _c } from "react/compiler-runtime"; // @compilationMode:"all"
function nonReactFn() {
  const $ = _c(1);
  let t0;

View File

@@ -0,0 +1,5 @@
import type { PluginOptions } from 
'babel-plugin-react-compiler/dist';
({
  //compilationMode: "all"
} satisfies PluginOptions);

View File

@@ -5,8 +5,9 @@
* LICENSE file in the root directory of this source tree.
*/
import {expect, test} from '@playwright/test';
import {expect, test, type Page} from '@playwright/test';
import {encodeStore, type Store} from '../../lib/stores';
import {defaultConfig} from '../../lib/defaultStore';
import {format} from 'prettier';
function isMonacoLoaded(): boolean {
@@ -20,6 +21,16 @@ function formatPrint(data: Array<string>): Promise<string> {
return format(data.join(''), {parser: 'babel'});
}
async function expandConfigs(page: Page): Promise<void> {
const expandButton = page.locator('[title="Expand config editor"]');
await expandButton.click();
await page.waitForSelector('.monaco-editor-config', {state: 'visible'});
}
const TEST_SOURCE = `export default function TestComponent({ x }) {
return <Button>{x}</Button>;
}`;
const TEST_CASE_INPUTS = [
{
name: 'module-scope-use-memo',
@@ -121,10 +132,9 @@ test('editor should open successfully', async ({page}) => {
test('editor should compile from hash successfully', async ({page}) => {
const store: Store = {
source: `export default function TestComponent({ x }) {
return <Button>{x}</Button>;
}
`,
source: TEST_SOURCE,
config: defaultConfig,
showInternals: false,
};
const hash = encodeStore(store);
await page.goto(`/#${hash}`, {waitUntil: 'networkidle'});
@@ -136,7 +146,7 @@ test('editor should compile from hash successfully', async ({page}) => {
path: 'test-results/01-compiles-from-hash.png',
});
const text =
(await page.locator('.monaco-editor').nth(1).allInnerTexts()) ?? [];
(await page.locator('.monaco-editor-output').allInnerTexts()) ?? [];
const output = await formatPrint(text);
expect(output).not.toEqual('');
@@ -145,10 +155,9 @@ test('editor should compile from hash successfully', async ({page}) => {
test('reset button works', async ({page}) => {
const store: Store = {
source: `export default function TestComponent({ x }) {
return <Button>{x}</Button>;
}
`,
source: TEST_SOURCE,
config: defaultConfig,
showInternals: false,
};
const hash = encodeStore(store);
await page.goto(`/#${hash}`, {waitUntil: 'networkidle'});
@@ -157,33 +166,170 @@ test('reset button works', async ({page}) => {
// Reset button works
page.on('dialog', dialog => dialog.accept());
await page.getByRole('button', {name: 'Reset'}).click();
await expandConfigs(page);
await page.screenshot({
fullPage: true,
path: 'test-results/02-reset-button-works.png',
});
const text =
(await page.locator('.monaco-editor').nth(1).allInnerTexts()) ?? [];
(await page.locator('.monaco-editor-output').allInnerTexts()) ?? [];
const output = await formatPrint(text);
const configText =
(await page.locator('.monaco-editor-config').allInnerTexts()) ?? [];
const configOutput = configText.join('');
expect(output).not.toEqual('');
expect(output).toMatchSnapshot('02-default-output.txt');
expect(configOutput).not.toEqual('');
expect(configOutput).toMatchSnapshot('default-config.txt');
});
test('defaults load when only source is in Store', async ({page}) => {
// Test for backwards compatibility
const partial = {
source: TEST_SOURCE,
};
const hash = encodeStore(partial as Store);
await page.goto(`/#${hash}`, {waitUntil: 'networkidle'});
await page.waitForFunction(isMonacoLoaded);
await expandConfigs(page);
await page.screenshot({
fullPage: true,
path: 'test-results/03-missing-defaults.png',
});
// Config editor has default config
const configText =
(await page.locator('.monaco-editor-config').allInnerTexts()) ?? [];
const configOutput = configText.join('');
expect(configOutput).not.toEqual('');
expect(configOutput).toMatchSnapshot('default-config.txt');
const checkbox = page.locator('label.show-internals');
await expect(checkbox).not.toBeChecked();
const ssaTab = page.locator('text=SSA');
await expect(ssaTab).not.toBeVisible();
});
test('show internals button toggles correctly', async ({page}) => {
await page.goto(`/`, {waitUntil: 'networkidle'});
await page.waitForFunction(isMonacoLoaded);
// show internals should be off
const checkbox = page.locator('label.show-internals');
await checkbox.click();
await page.screenshot({
fullPage: true,
path: 'test-results/04-show-internals-on.png',
});
await expect(checkbox).toBeChecked();
const ssaTab = page.locator('text=SSA');
await expect(ssaTab).toBeVisible();
});
test('error is displayed when config has syntax error', async ({page}) => {
const store: Store = {
source: TEST_SOURCE,
config: `compilationMode: `,
showInternals: false,
};
const hash = encodeStore(store);
await page.goto(`/#${hash}`, {waitUntil: 'networkidle'});
await page.waitForFunction(isMonacoLoaded);
await expandConfigs(page);
await page.screenshot({
fullPage: true,
path: 'test-results/05-config-syntax-error.png',
});
const text =
(await page.locator('.monaco-editor-output').allInnerTexts()) ?? [];
const output = text.join('');
// Remove hidden chars
expect(output.replace(/\s+/g, ' ')).toContain('Invalid override format');
});
test('error is displayed when config has validation error', async ({page}) => {
const store: Store = {
source: TEST_SOURCE,
config: `import type { PluginOptions } from 'babel-plugin-react-compiler/dist';
({
compilationMode: "123"
} satisfies PluginOptions);`,
showInternals: false,
};
const hash = encodeStore(store);
await page.goto(`/#${hash}`, {waitUntil: 'networkidle'});
await page.waitForFunction(isMonacoLoaded);
await expandConfigs(page);
await page.screenshot({
fullPage: true,
path: 'test-results/06-config-validation-error.png',
});
const text =
(await page.locator('.monaco-editor-output').allInnerTexts()) ?? [];
const output = text.join('');
expect(output.replace(/\s+/g, ' ')).toContain('Unexpected compilationMode');
});
test('error is displayed when source has syntax error', async ({page}) => {
const syntaxErrorSource = `function TestComponent(props) {
const oops = props.
return (
<>{oops}</>
);
}`;
const store: Store = {
source: syntaxErrorSource,
config: defaultConfig,
showInternals: false,
};
const hash = encodeStore(store);
await page.goto(`/#${hash}`);
await page.waitForFunction(isMonacoLoaded);
await expandConfigs(page);
await page.screenshot({
fullPage: true,
path: 'test-results/08-source-syntax-error.png',
});
const text =
(await page.locator('.monaco-editor-output').allInnerTexts()) ?? [];
const output = text.join('');
expect(output.replace(/\s+/g, ' ')).toContain(
'Expected identifier to be defined before being used',
);
});
TEST_CASE_INPUTS.forEach((t, idx) =>
test(`playground compiles: ${t.name}`, async ({page}) => {
const store: Store = {
source: t.input,
config: defaultConfig,
showInternals: false,
};
const hash = encodeStore(store);
await page.goto(`/#${hash}`, {waitUntil: 'networkidle'});
await page.waitForFunction(isMonacoLoaded);
await page.screenshot({
fullPage: true,
path: `test-results/03-0${idx}-${t.name}.png`,
path: `test-results/08-0${idx}-${t.name}.png`,
});
const text =
(await page.locator('.monaco-editor').nth(1).allInnerTexts()) ?? [];
(await page.locator('.monaco-editor-output').allInnerTexts()) ?? [];
let output: string;
if (t.noFormat) {
output = text.join('');

View File

@@ -1,56 +0,0 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {NextPage} from 'next';
import Head from 'next/head';
import {SnackbarProvider} from 'notistack';
import {Editor, Header, StoreProvider} from '../components';
import MessageSnackbar from '../components/Message';
const Home: NextPage = () => {
return (
<div className="flex flex-col w-screen h-screen font-light">
<Head>
<title>
{process.env.NODE_ENV === 'development'
? '[DEV] React Compiler Playground'
: 'React Compiler Playground'}
</title>
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"></meta>
<link rel="icon" href="/favicon.ico" />
<link rel="manifest" href="/site.webmanifest" />
<link
rel="preload"
href="/fonts/Source-Code-Pro-Regular.woff2"
as="font"
type="font/woff2"
crossOrigin="anonymous"
/>
<link
rel="preload"
href="/fonts/Optimistic_Display_W_Lt.woff2"
as="font"
type="font/woff2"
crossOrigin="anonymous"
/>
</Head>
<StoreProvider>
<SnackbarProvider
preventDuplicate
maxSnack={10}
Components={{message: MessageSnackbar}}>
<Header />
<Editor />
</SnackbarProvider>
</StoreProvider>
</div>
);
};
export default Home;

View File

@@ -0,0 +1,126 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {Resizable} from 're-resizable';
import React, {
useId,
unstable_ViewTransition as ViewTransition,
unstable_addTransitionType as addTransitionType,
startTransition,
} from 'react';
import {EXPAND_ACCORDION_TRANSITION} from '../lib/transitionTypes';
type TabsRecord = Map<string, React.ReactNode>;
export default function AccordionWindow(props: {
defaultTab: string | null;
tabs: TabsRecord;
tabsOpen: Set<string>;
setTabsOpen: (newTab: Set<string>) => void;
changedPasses: Set<string>;
}): React.ReactElement {
return (
<div className="flex-1 min-w-[550px] sm:min-w-0">
<div className="flex flex-row h-full">
{Array.from(props.tabs.keys()).map(name => {
return (
<AccordionWindowItem
name={name}
key={name}
tabs={props.tabs}
tabsOpen={props.tabsOpen}
setTabsOpen={props.setTabsOpen}
hasChanged={props.changedPasses.has(name)}
/>
);
})}
</div>
</div>
);
}
function AccordionWindowItem({
name,
tabs,
tabsOpen,
setTabsOpen,
hasChanged,
}: {
name: string;
tabs: TabsRecord;
tabsOpen: Set<string>;
setTabsOpen: (newTab: Set<string>) => void;
hasChanged: boolean;
isFailure: boolean;
}): React.ReactElement {
const id = useId();
const isShow = tabsOpen.has(name);
const transitionName = `accordion-window-item-${id}`;
const toggleTabs = (): void => {
startTransition(() => {
addTransitionType(EXPAND_ACCORDION_TRANSITION);
const nextState = new Set(tabsOpen);
if (nextState.has(name)) {
nextState.delete(name);
} else {
nextState.add(name);
}
setTabsOpen(nextState);
});
};
// Replace spaces with non-breaking spaces
const displayName = name.replace(/ /g, '\u00A0');
return (
<div key={name} className="flex flex-row">
{isShow ? (
<ViewTransition
name={transitionName}
update={{
[EXPAND_ACCORDION_TRANSITION]: 'expand-accordion',
default: 'none',
}}>
<Resizable className="border-r" minWidth={550} enable={{right: true}}>
<h2
title="Minimize tab"
aria-label="Minimize tab"
onClick={toggleTabs}
className={`p-4 duration-150 ease-in border-b cursor-pointer border-grey-200 ${
hasChanged ? 'font-bold' : 'font-light'
} text-secondary hover:text-link`}>
- {displayName}
</h2>
{tabs.get(name) ?? <div>No output for {name}</div>}
</Resizable>
</ViewTransition>
) : (
<ViewTransition
name={transitionName}
update={{
[EXPAND_ACCORDION_TRANSITION]: 'expand-accordion',
default: 'none',
}}>
<div className="relative items-center h-full px-1 py-6 align-middle border-r border-grey-200">
<button
title={`Expand compiler tab: ${name}`}
aria-label={`Expand compiler tab: ${name}`}
style={{transform: 'rotate(90deg) translate(-50%)'}}
onClick={toggleTabs}
className={`flex-grow-0 w-5 transition-colors duration-150 ease-in ${
hasChanged ? 'font-bold' : 'font-light'
} text-secondary hover:text-link`}>
{displayName}
</button>
</div>
</ViewTransition>
)}
</div>
);
}

View File

@@ -0,0 +1,221 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import MonacoEditor, {loader, type Monaco} from '@monaco-editor/react';
import type {editor} from 'monaco-editor';
import * as monaco from 'monaco-editor';
import React, {
useState,
useRef,
unstable_ViewTransition as ViewTransition,
unstable_addTransitionType as addTransitionType,
startTransition,
} from 'react';
import {Resizable} from 're-resizable';
import {useStore, useStoreDispatch} from '../StoreContext';
import {monacoConfigOptions} from './monacoOptions';
import {IconChevron} from '../Icons/IconChevron';
import {CONFIG_PANEL_TRANSITION} from '../../lib/transitionTypes';
// @ts-expect-error - webpack asset/source loader handles .d.ts files as strings
import compilerTypeDefs from 'babel-plugin-react-compiler/dist/index.d.ts';
loader.config({monaco});
export default function ConfigEditor({
formattedAppliedConfig,
}: {
formattedAppliedConfig: string;
}): React.ReactElement {
const [isExpanded, setIsExpanded] = useState(false);
// TODO: Add back <Activity> after upgrading next.js
return (
<>
<div
style={{
display: isExpanded ? 'block' : 'none',
}}>
{/* <Activity mode={isExpanded ? 'visible' : 'hidden'}> */}
<ExpandedEditor
onToggle={() => {
startTransition(() => {
addTransitionType(CONFIG_PANEL_TRANSITION);
setIsExpanded(false);
});
}}
formattedAppliedConfig={formattedAppliedConfig}
/>
</div>
<div
style={{
display: !isExpanded ? 'block' : 'none',
}}>
{/* </Activity>
<Activity mode={isExpanded ? 'hidden' : 'visible'}></Activity> */}
<CollapsedEditor
onToggle={() => {
startTransition(() => {
addTransitionType(CONFIG_PANEL_TRANSITION);
setIsExpanded(true);
});
}}
/>
</div>
{/* </Activity> */}
</>
);
}
function ExpandedEditor({
onToggle,
formattedAppliedConfig,
}: {
onToggle: (expanded: boolean) => void;
formattedAppliedConfig: string;
}): React.ReactElement {
const store = useStore();
const dispatchStore = useStoreDispatch();
const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);
const handleChange: (value: string | undefined) => void = (
value: string | undefined,
) => {
if (value === undefined) return;
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
debounceTimerRef.current = setTimeout(() => {
dispatchStore({
type: 'updateConfig',
payload: {
config: value,
},
});
}, 500); // 500ms debounce delay
};
const handleMount: (
_: editor.IStandaloneCodeEditor,
monaco: Monaco,
) => void = (_, monaco) => {
// Add the babel-plugin-react-compiler type definitions to Monaco
monaco.languages.typescript.typescriptDefaults.addExtraLib(
//@ts-expect-error - compilerTypeDefs is a string
compilerTypeDefs,
'file:///node_modules/babel-plugin-react-compiler/dist/index.d.ts',
);
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
target: monaco.languages.typescript.ScriptTarget.Latest,
allowNonTsExtensions: true,
moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
module: monaco.languages.typescript.ModuleKind.ESNext,
noEmit: true,
strict: false,
esModuleInterop: true,
allowSyntheticDefaultImports: true,
jsx: monaco.languages.typescript.JsxEmit.React,
});
};
return (
<ViewTransition
update={{[CONFIG_PANEL_TRANSITION]: 'slide-in', default: 'none'}}>
{/* enter={{[CONFIG_PANEL_TRANSITION]: 'slide-in', default: 'none'}}
exit={{[CONFIG_PANEL_TRANSITION]: 'slide-out', default: 'none'}}> */}
<Resizable
minWidth={300}
maxWidth={600}
defaultSize={{width: 350}}
enable={{right: true, bottom: false}}>
<div className="bg-blue-10 relative h-full flex flex-col !h-[calc(100vh_-_3.5rem)] border border-gray-300">
<div
className="absolute w-8 h-16 bg-blue-10 rounded-r-full flex items-center justify-center z-[2] cursor-pointer border border-l-0 border-gray-300"
title="Minimize config editor"
onClick={onToggle}
style={{
top: '50%',
marginTop: '-32px',
right: '-32px',
borderTopLeftRadius: 0,
borderBottomLeftRadius: 0,
}}>
<IconChevron displayDirection="left" className="text-blue-50" />
</div>
<div className="flex-1 flex flex-col m-2 mb-2">
<div className="pb-2">
<h2 className="inline-block text-blue-50 py-1.5 px-1.5 xs:px-3 sm:px-4 text-sm">
Config Overrides
</h2>
</div>
<div className="flex-1 border border-gray-300">
<MonacoEditor
path={'config.ts'}
language={'typescript'}
value={store.config}
onMount={handleMount}
onChange={handleChange}
loading={''}
className="monaco-editor-config"
options={monacoConfigOptions}
/>
</div>
</div>
<div className="flex-1 flex flex-col m-2">
<div className="pb-2">
<h2 className="inline-block text-blue-50 py-1.5 px-1.5 xs:px-3 sm:px-4 text-sm">
Applied Configs
</h2>
</div>
<div className="flex-1 border border-gray-300">
<MonacoEditor
path={'applied-config.js'}
language={'javascript'}
value={formattedAppliedConfig}
loading={''}
className="monaco-editor-applied-config"
options={{
...monacoConfigOptions,
readOnly: true,
}}
/>
</div>
</div>
</div>
</Resizable>
</ViewTransition>
);
}
function CollapsedEditor({
onToggle,
}: {
onToggle: () => void;
}): React.ReactElement {
return (
<div
className="w-4 !h-[calc(100vh_-_3.5rem)]"
style={{position: 'relative'}}>
<div
className="absolute w-10 h-16 bg-blue-10 hover:translate-x-2 transition-transform rounded-r-full flex items-center justify-center z-[2] cursor-pointer border border-gray-300"
title="Expand config editor"
onClick={onToggle}
style={{
top: '50%',
marginTop: '-32px',
left: '-8px',
borderTopLeftRadius: 0,
borderBottomLeftRadius: 0,
}}>
<IconChevron displayDirection="right" className="text-blue-50" />
</div>
</div>
);
}

View File

@@ -5,313 +5,30 @@
* LICENSE file in the root directory of this source tree.
*/
import {parse as babelParse, ParseResult} from '@babel/parser';
import * as HermesParser from 'hermes-parser';
import * as t from '@babel/types';
import BabelPluginReactCompiler, {
CompilerError,
import {
CompilerErrorDetail,
CompilerDiagnostic,
Effect,
ErrorSeverity,
parseConfigPragmaForTests,
ValueKind,
type Hook,
PluginOptions,
CompilerPipelineValue,
parsePluginOptions,
printReactiveFunctionWithOutlined,
printFunctionWithOutlined,
} from 'babel-plugin-react-compiler';
import clsx from 'clsx';
import invariant from 'invariant';
import {useSnackbar} from 'notistack';
import {useDeferredValue, useMemo} from 'react';
import {useMountEffect} from '../../hooks';
import {defaultStore} from '../../lib/defaultStore';
import {
createMessage,
initStoreFromUrlOrLocalStorage,
MessageLevel,
MessageSource,
type Store,
} from '../../lib/stores';
import {useStore, useStoreDispatch} from '../StoreContext';
import {useDeferredValue, useMemo, useState} from 'react';
import {useStore} from '../StoreContext';
import ConfigEditor from './ConfigEditor';
import Input from './Input';
import {
CompilerOutput,
CompilerTransformOutput,
default as Output,
PrintedCompilerPipelineValue,
} from './Output';
import {transformFromAstSync} from '@babel/core';
import {LoggerEvent} from 'babel-plugin-react-compiler/dist/Entrypoint';
function parseInput(
input: string,
language: 'flow' | 'typescript',
): ParseResult<t.File> {
// Extract the first line to quickly check for custom test directives
if (language === 'flow') {
return HermesParser.parse(input, {
babel: true,
flow: 'all',
sourceType: 'module',
enableExperimentalComponentSyntax: true,
});
} else {
return babelParse(input, {
plugins: ['typescript', 'jsx'],
sourceType: 'module',
}) as ParseResult<t.File>;
}
}
function invokeCompiler(
source: string,
language: 'flow' | 'typescript',
options: PluginOptions,
): CompilerTransformOutput {
const ast = parseInput(source, language);
let result = transformFromAstSync(ast, source, {
filename: '_playgroundFile.js',
highlightCode: false,
retainLines: true,
plugins: [[BabelPluginReactCompiler, options]],
ast: true,
sourceType: 'module',
configFile: false,
sourceMaps: true,
babelrc: false,
});
if (result?.ast == null || result?.code == null || result?.map == null) {
throw new Error('Expected successful compilation');
}
return {
code: result.code,
sourceMaps: result.map,
language,
};
}
const COMMON_HOOKS: Array<[string, Hook]> = [
[
'useFragment',
{
valueKind: ValueKind.Frozen,
effectKind: Effect.Freeze,
noAlias: true,
transitiveMixedData: true,
},
],
[
'usePaginationFragment',
{
valueKind: ValueKind.Frozen,
effectKind: Effect.Freeze,
noAlias: true,
transitiveMixedData: true,
},
],
[
'useRefetchableFragment',
{
valueKind: ValueKind.Frozen,
effectKind: Effect.Freeze,
noAlias: true,
transitiveMixedData: true,
},
],
[
'useLazyLoadQuery',
{
valueKind: ValueKind.Frozen,
effectKind: Effect.Freeze,
noAlias: true,
transitiveMixedData: true,
},
],
[
'usePreloadedQuery',
{
valueKind: ValueKind.Frozen,
effectKind: Effect.Freeze,
noAlias: true,
transitiveMixedData: true,
},
],
];
function compile(
source: string,
mode: 'compiler' | 'linter',
): [CompilerOutput, 'flow' | 'typescript'] {
const results = new Map<string, Array<PrintedCompilerPipelineValue>>();
const error = new CompilerError();
const otherErrors: Array<CompilerErrorDetail | CompilerDiagnostic> = [];
const upsert: (result: PrintedCompilerPipelineValue) => void = result => {
const entry = results.get(result.name);
if (Array.isArray(entry)) {
entry.push(result);
} else {
results.set(result.name, [result]);
}
};
let language: 'flow' | 'typescript';
if (source.match(/\@flow/)) {
language = 'flow';
} else {
language = 'typescript';
}
let transformOutput;
try {
// Extract the first line to quickly check for custom test directives
const pragma = source.substring(0, source.indexOf('\n'));
const logIR = (result: CompilerPipelineValue): void => {
switch (result.kind) {
case 'ast': {
break;
}
case 'hir': {
upsert({
kind: 'hir',
fnName: result.value.id,
name: result.name,
value: printFunctionWithOutlined(result.value),
});
break;
}
case 'reactive': {
upsert({
kind: 'reactive',
fnName: result.value.id,
name: result.name,
value: printReactiveFunctionWithOutlined(result.value),
});
break;
}
case 'debug': {
upsert({
kind: 'debug',
fnName: null,
name: result.name,
value: result.value,
});
break;
}
default: {
const _: never = result;
throw new Error(`Unhandled result ${result}`);
}
}
};
const parsedOptions = parseConfigPragmaForTests(pragma, {
compilationMode: 'infer',
environment:
mode === 'linter'
? {
// enabled in compiler
validateRefAccessDuringRender: false,
// enabled in linter
validateNoSetStateInRender: true,
validateNoSetStateInEffects: true,
validateNoJSXInTryStatements: true,
validateNoImpureFunctionsInRender: true,
validateStaticComponents: true,
validateNoFreezingKnownMutableFunctions: true,
validateNoVoidUseMemo: true,
}
: {
/* use defaults for compiler mode */
},
});
const opts: PluginOptions = parsePluginOptions({
...parsedOptions,
environment: {
...parsedOptions.environment,
customHooks: new Map([...COMMON_HOOKS]),
},
logger: {
debugLogIRs: logIR,
logEvent: (_filename: string | null, event: LoggerEvent) => {
if (event.kind === 'CompileError') {
otherErrors.push(event.detail);
}
},
},
});
transformOutput = invokeCompiler(source, language, opts);
} catch (err) {
/**
* error might be an invariant violation or other runtime error
* (i.e. object shape that is not CompilerError)
*/
if (err instanceof CompilerError && err.details.length > 0) {
error.merge(err);
} else {
/**
* Handle unexpected failures by logging (to get a stack trace)
* and reporting
*/
console.error(err);
error.details.push(
new CompilerErrorDetail({
severity: ErrorSeverity.Invariant,
reason: `Unexpected failure when transforming input! ${err}`,
loc: null,
suggestions: null,
}),
);
}
}
// Only include logger errors if there weren't other errors
if (!error.hasErrors() && otherErrors.length !== 0) {
otherErrors.forEach(e => error.details.push(e));
}
if (error.hasErrors()) {
return [{kind: 'err', results, error}, language];
}
return [
{kind: 'ok', results, transformOutput, errors: error.details},
language,
];
}
import {CompilerOutput, default as Output} from './Output';
import {compile} from '../../lib/compilation';
import prettyFormat from 'pretty-format';
export default function Editor(): JSX.Element {
const store = useStore();
const deferredStore = useDeferredValue(store);
const dispatchStore = useStoreDispatch();
const {enqueueSnackbar} = useSnackbar();
const [compilerOutput, language] = useMemo(
() => compile(deferredStore.source, 'compiler'),
[deferredStore.source],
const [compilerOutput, language, appliedOptions] = useMemo(
() => compile(deferredStore.source, 'compiler', deferredStore.config),
[deferredStore.source, deferredStore.config],
);
const [linterOutput] = useMemo(
() => compile(deferredStore.source, 'linter'),
[deferredStore.source],
() => compile(deferredStore.source, 'linter', deferredStore.config),
[deferredStore.source, deferredStore.config],
);
useMountEffect(() => {
let mountStore: Store;
try {
mountStore = initStoreFromUrlOrLocalStorage();
} catch (e) {
invariant(e instanceof Error, 'Only Error may be caught.');
enqueueSnackbar(e.message, {
variant: 'warning',
...createMessage(
'Bad URL - fell back to the default Playground.',
MessageLevel.Info,
MessageSource.Playground,
),
});
mountStore = defaultStore;
}
dispatchStore({
type: 'setStore',
payload: {store: mountStore},
});
});
const [formattedAppliedConfig, setFormattedAppliedConfig] = useState('');
let mergedOutput: CompilerOutput;
let errors: Array<CompilerErrorDetail | CompilerDiagnostic>;
@@ -325,13 +42,25 @@ export default function Editor(): JSX.Element {
mergedOutput = compilerOutput;
errors = compilerOutput.error.details;
}
if (appliedOptions) {
const formatted = prettyFormat(appliedOptions, {
printFunctionName: false,
printBasicPrototype: false,
});
if (formatted !== formattedAppliedConfig) {
setFormattedAppliedConfig(formatted);
}
}
return (
<>
<div className="relative flex basis top-14">
<div className={clsx('relative sm:basis-1/4')}>
<Input language={language} errors={errors} />
<div className="relative flex top-14">
<div className="flex-shrink-0">
<ConfigEditor formattedAppliedConfig={formattedAppliedConfig} />
</div>
<div className={clsx('flex sm:flex flex-wrap')}>
<div className="flex flex-1 min-w-0">
<Input language={language} errors={errors} />
<Output store={deferredStore} compilerOutput={mergedOutput} />
</div>
</div>

View File

@@ -6,22 +6,31 @@
*/
import MonacoEditor, {loader, type Monaco} from '@monaco-editor/react';
import {CompilerErrorDetail} from 'babel-plugin-react-compiler';
import {
CompilerErrorDetail,
CompilerDiagnostic,
} from 'babel-plugin-react-compiler';
import invariant from 'invariant';
import type {editor} from 'monaco-editor';
import * as monaco from 'monaco-editor';
import {Resizable} from 're-resizable';
import {useEffect, useState} from 'react';
import {
useEffect,
useState,
unstable_ViewTransition as ViewTransition,
} from 'react';
import {renderReactCompilerMarkers} from '../../lib/reactCompilerMonacoDiagnostics';
import {useStore, useStoreDispatch} from '../StoreContext';
import TabbedWindow from '../TabbedWindow';
import {monacoOptions} from './monacoOptions';
import {CONFIG_PANEL_TRANSITION} from '../../lib/transitionTypes';
// @ts-expect-error TODO: Make TS recognize .d.ts files, in addition to loading them with webpack.
import React$Types from '../../node_modules/@types/react/index.d.ts';
loader.config({monaco});
type Props = {
errors: Array<CompilerErrorDetail>;
errors: Array<CompilerErrorDetail | CompilerDiagnostic>;
language: 'flow' | 'typescript';
};
@@ -42,11 +51,6 @@ export default function Input({errors, language}: Props): JSX.Element {
details: errors,
source: store.source,
});
/**
* N.B. that `tabSize` is a model property, not an editor property.
* So, the tab size has to be set per model.
*/
model.updateOptions({tabSize: 2});
}, [monaco, errors, store.source]);
useEffect(() => {
@@ -79,11 +83,11 @@ export default function Input({errors, language}: Props): JSX.Element {
});
}, [monaco, language]);
const handleChange: (value: string | undefined) => void = value => {
const handleChange: (value: string | undefined) => void = async value => {
if (!value) return;
dispatchStore({
type: 'updateFile',
type: 'updateSource',
payload: {
source: value,
},
@@ -135,30 +139,42 @@ export default function Input({errors, language}: Props): JSX.Element {
});
};
const editorContent = (
<MonacoEditor
path={'index.js'}
/**
* .js and .jsx files are specified to be TS so that Monaco can actually
* check their syntax using its TS language service. They are still JS files
* due to their extensions, so TS language features don't work.
*/
language={'javascript'}
value={store.source}
onMount={handleMount}
onChange={handleChange}
className="monaco-editor-input"
options={monacoOptions}
loading={''}
/>
);
const tabs = new Map([['Input', editorContent]]);
const [activeTab, setActiveTab] = useState('Input');
return (
<div className="relative flex flex-col flex-none border-r border-gray-200">
<Resizable
minWidth={650}
enable={{right: true}}
/**
* Restrict MonacoEditor's height, since the config autoLayout:true
* will grow the editor to fit within parent element
*/
className="!h-[calc(100vh_-_3.5rem)]">
<MonacoEditor
path={'index.js'}
/**
* .js and .jsx files are specified to be TS so that Monaco can actually
* check their syntax using its TS language service. They are still JS files
* due to their extensions, so TS language features don't work.
*/
language={'javascript'}
value={store.source}
onMount={handleMount}
onChange={handleChange}
options={monacoOptions}
/>
</Resizable>
</div>
<ViewTransition
update={{
[CONFIG_PANEL_TRANSITION]: 'container',
default: 'none',
}}>
<div className="flex-1 min-w-[550px] sm:min-w-0">
<div className="flex flex-col h-full !h-[calc(100vh_-_3.5rem)] border-r border-gray-200">
<TabbedWindow
tabs={tabs}
activeTab={activeTab}
onTabChange={setActiveTab}
/>
</div>
</div>
</ViewTransition>
);
}

View File

@@ -19,15 +19,38 @@ import {
import parserBabel from 'prettier/plugins/babel';
import * as prettierPluginEstree from 'prettier/plugins/estree';
import * as prettier from 'prettier/standalone';
import {memo, ReactNode, useEffect, useState} from 'react';
import {type Store} from '../../lib/stores';
import {
memo,
ReactNode,
use,
useState,
Suspense,
unstable_ViewTransition as ViewTransition,
unstable_addTransitionType as addTransitionType,
startTransition,
} from 'react';
import AccordionWindow from '../AccordionWindow';
import TabbedWindow from '../TabbedWindow';
import {monacoOptions} from './monacoOptions';
import {BabelFileResult} from '@babel/core';
import {
CONFIG_PANEL_TRANSITION,
TOGGLE_INTERNALS_TRANSITION,
EXPAND_ACCORDION_TRANSITION,
} from '../../lib/transitionTypes';
import {LRUCache} from 'lru-cache';
const MemoizedOutput = memo(Output);
export default MemoizedOutput;
export const BASIC_OUTPUT_TAB_NAMES = ['Output', 'SourceMap'];
const tabifyCache = new LRUCache<Store, Promise<Map<string, ReactNode>>>({
max: 5,
});
export type PrintedCompilerPipelineValue =
| {
kind: 'hir';
@@ -64,12 +87,16 @@ type Props = {
async function tabify(
source: string,
compilerOutput: CompilerOutput,
showInternals: boolean,
): Promise<Map<string, ReactNode>> {
const tabs = new Map<string, React.ReactNode>();
const reorderedTabs = new Map<string, React.ReactNode>();
const concattedResults = new Map<string, string>();
// Concat all top level function declaration results into a single tab for each pass
for (const [passName, results] of compilerOutput.results) {
if (!showInternals && !BASIC_OUTPUT_TAB_NAMES.includes(passName)) {
continue;
}
for (const result of results) {
switch (result.kind) {
case 'hir': {
@@ -192,6 +219,25 @@ ${code}
return reorderedTabs;
}
function tabifyCached(
store: Store,
compilerOutput: CompilerOutput,
): Promise<Map<string, ReactNode>> {
const cached = tabifyCache.get(store);
if (cached) return cached;
const result = tabify(store.source, compilerOutput, store.showInternals);
tabifyCache.set(store, result);
return result;
}
function Fallback(): JSX.Element {
return (
<div className="w-full h-monaco_small sm:h-monaco flex items-center justify-center">
Loading...
</div>
);
}
function utf16ToUTF8(s: string): string {
return unescape(encodeURIComponent(s));
}
@@ -205,12 +251,18 @@ function getSourceMapUrl(code: string, map: string): string | null {
}
function Output({store, compilerOutput}: Props): JSX.Element {
return (
<Suspense fallback={<Fallback />}>
<OutputContent store={store} compilerOutput={compilerOutput} />
</Suspense>
);
}
function OutputContent({store, compilerOutput}: Props): JSX.Element {
const [tabsOpen, setTabsOpen] = useState<Set<string>>(
() => new Set(['Output']),
);
const [tabs, setTabs] = useState<Map<string, React.ReactNode>>(
() => new Map(),
);
const [activeTab, setActiveTab] = useState<string>('Output');
/*
* Update the active tab back to the output or errors tab when the compilation state
@@ -219,17 +271,19 @@ function Output({store, compilerOutput}: Props): JSX.Element {
const [previousOutputKind, setPreviousOutputKind] = useState(
compilerOutput.kind,
);
const isFailure = compilerOutput.kind !== 'ok';
if (compilerOutput.kind !== previousOutputKind) {
setPreviousOutputKind(compilerOutput.kind);
setTabsOpen(new Set(['Output']));
if (isFailure) {
startTransition(() => {
addTransitionType(EXPAND_ACCORDION_TRANSITION);
setTabsOpen(prev => new Set(prev).add('Output'));
setActiveTab('Output');
});
}
}
useEffect(() => {
tabify(store.source, compilerOutput).then(tabs => {
setTabs(tabs);
});
}, [store.source, compilerOutput]);
const changedPasses: Set<string> = new Set(['Output', 'HIR']); // Initial and final passes should always be bold
let lastResult: string = '';
for (const [passName, results] of compilerOutput.results) {
@@ -244,17 +298,40 @@ function Output({store, compilerOutput}: Props): JSX.Element {
lastResult = currResult;
}
}
const tabs = use(tabifyCached(store, compilerOutput));
if (!store.showInternals) {
return (
<ViewTransition
update={{
[CONFIG_PANEL_TRANSITION]: 'container',
[TOGGLE_INTERNALS_TRANSITION]: '',
default: 'none',
}}>
<TabbedWindow
tabs={tabs}
activeTab={activeTab}
onTabChange={setActiveTab}
/>
</ViewTransition>
);
}
return (
<>
<TabbedWindow
defaultTab="HIR"
<ViewTransition
update={{
[CONFIG_PANEL_TRANSITION]: 'accordion-container',
[TOGGLE_INTERNALS_TRANSITION]: '',
default: 'none',
}}>
<AccordionWindow
defaultTab={store.showInternals ? 'HIR' : 'Output'}
setTabsOpen={setTabsOpen}
tabsOpen={tabsOpen}
tabs={tabs}
changedPasses={changedPasses}
/>
</>
</ViewTransition>
);
}
@@ -306,20 +383,29 @@ function TextTabContent({
<DiffEditor
original={diff}
modified={output}
loading={''}
options={{
...monacoOptions,
scrollbar: {
vertical: 'hidden',
},
dimension: {
width: 0,
height: 0,
},
readOnly: true,
lineNumbers: 'off',
glyphMargin: false,
// Undocumented see https://github.com/Microsoft/vscode/issues/30795#issuecomment-410998882
lineDecorationsWidth: 0,
lineNumbersMinChars: 0,
overviewRulerLanes: 0,
}}
/>
) : (
<MonacoEditor
language={language ?? 'javascript'}
value={output}
loading={''}
className="monaco-editor-output"
options={{
...monacoOptions,
readOnly: true,

View File

@@ -29,4 +29,17 @@ export const monacoOptions: Partial<EditorProps['options']> = {
automaticLayout: true,
wordWrap: 'on',
wrappingIndent: 'same',
tabSize: 2,
};
export const monacoConfigOptions: Partial<EditorProps['options']> = {
...monacoOptions,
lineNumbers: 'off',
renderLineHighlight: 'none',
overviewRulerBorder: false,
overviewRulerLanes: 0,
fontSize: 12,
scrollBeyondLastLine: false,
glyphMargin: false,
};

View File

@@ -10,14 +10,20 @@ import {CheckIcon} from '@heroicons/react/solid';
import clsx from 'clsx';
import Link from 'next/link';
import {useSnackbar} from 'notistack';
import {useState} from 'react';
import {
useState,
startTransition,
unstable_addTransitionType as addTransitionType,
} from 'react';
import {defaultStore} from '../lib/defaultStore';
import {IconGitHub} from './Icons/IconGitHub';
import Logo from './Logo';
import {useStoreDispatch} from './StoreContext';
import {useStore, useStoreDispatch} from './StoreContext';
import {TOGGLE_INTERNALS_TRANSITION} from '../lib/transitionTypes';
export default function Header(): JSX.Element {
const [showCheck, setShowCheck] = useState(false);
const store = useStore();
const dispatchStore = useStoreDispatch();
const {enqueueSnackbar, closeSnackbar} = useSnackbar();
@@ -56,6 +62,32 @@ export default function Header(): JSX.Element {
<p className="hidden select-none sm:block">React Compiler Playground</p>
</div>
<div className="flex items-center text-[15px] gap-4">
<div className="flex items-center gap-2">
<label className="show-internals relative inline-block w-[34px] h-5">
<input
type="checkbox"
checked={store.showInternals}
onChange={() =>
startTransition(() => {
addTransitionType(TOGGLE_INTERNALS_TRANSITION);
dispatchStore({type: 'toggleInternals'});
})
}
className="absolute opacity-0 cursor-pointer h-full w-full m-0"
/>
<span
className={clsx(
'absolute inset-0 rounded-full cursor-pointer transition-all duration-250',
"before:content-[''] before:absolute before:w-4 before:h-4 before:left-0.5 before:bottom-0.5",
'before:bg-white before:rounded-full before:transition-transform before:duration-250',
'focus-within:shadow-[0_0_1px_#2196F3]',
store.showInternals
? 'bg-link before:translate-x-3.5'
: 'bg-gray-300',
)}></span>
</label>
<span className="text-secondary">Show Internals</span>
</div>
<button
title="Reset Playground"
aria-label="Reset Playground"

View File

@@ -0,0 +1,41 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {memo} from 'react';
export const IconChevron = memo<
JSX.IntrinsicElements['svg'] & {
/**
* The direction the arrow should point.
*/
displayDirection: 'right' | 'left';
}
>(function IconChevron({className, displayDirection, ...props}) {
const rotationClass =
displayDirection === 'left' ? 'rotate-90' : '-rotate-90';
const classes = className ? `${rotationClass} ${className}` : rotationClass;
return (
<svg
className={classes}
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 20 20"
{...props}>
<g fill="none" fillRule="evenodd" transform="translate(-446 -398)">
<path
fill="currentColor"
fillRule="nonzero"
d="M95.8838835,240.366117 C95.3957281,239.877961 94.6042719,239.877961 94.1161165,240.366117 C93.6279612,240.854272 93.6279612,241.645728 94.1161165,242.133883 L98.6161165,246.633883 C99.1042719,247.122039 99.8957281,247.122039 100.383883,246.633883 L104.883883,242.133883 C105.372039,241.645728 105.372039,240.854272 104.883883,240.366117 C104.395728,239.877961 103.604272,239.877961 103.116117,240.366117 L99.5,243.982233 L95.8838835,240.366117 Z"
transform="translate(356.5 164.5)"
/>
<polygon points="446 418 466 418 466 398 446 398" />
</g>
</svg>
);
});

View File

@@ -6,10 +6,14 @@
*/
import type {Dispatch, ReactNode} from 'react';
import {useEffect, useReducer} from 'react';
import {useState, useEffect, useReducer} from 'react';
import createContext from '../lib/createContext';
import {emptyStore} from '../lib/defaultStore';
import {saveStore, type Store} from '../lib/stores';
import {emptyStore, defaultStore} from '../lib/defaultStore';
import {
saveStore,
initStoreFromUrlOrLocalStorage,
type Store,
} from '../lib/stores';
const StoreContext = createContext<Store>();
@@ -30,6 +34,20 @@ export const useStoreDispatch = StoreDispatchContext.useContext;
*/
export function StoreProvider({children}: {children: ReactNode}): JSX.Element {
const [store, dispatch] = useReducer(storeReducer, emptyStore);
const [isPageReady, setIsPageReady] = useState<boolean>(false);
useEffect(() => {
let mountStore: Store;
try {
mountStore = initStoreFromUrlOrLocalStorage();
} catch (e) {
console.error('Failed to initialize store from URL or local storage', e);
mountStore = defaultStore;
}
dispatch({type: 'setStore', payload: {store: mountStore}});
setIsPageReady(true);
}, []);
useEffect(() => {
if (store !== emptyStore) {
saveStore(store);
@@ -39,7 +57,7 @@ export function StoreProvider({children}: {children: ReactNode}): JSX.Element {
return (
<StoreContext.Provider value={store}>
<StoreDispatchContext.Provider value={dispatch}>
{children}
{isPageReady ? children : null}
</StoreDispatchContext.Provider>
</StoreContext.Provider>
);
@@ -53,10 +71,19 @@ type ReducerAction =
};
}
| {
type: 'updateFile';
type: 'updateSource';
payload: {
source: string;
};
}
| {
type: 'updateConfig';
payload: {
config: string;
};
}
| {
type: 'toggleInternals';
};
function storeReducer(store: Store, action: ReducerAction): Store {
@@ -65,13 +92,28 @@ function storeReducer(store: Store, action: ReducerAction): Store {
const newStore = action.payload.store;
return newStore;
}
case 'updateFile': {
const {source} = action.payload;
case 'updateSource': {
const source = action.payload.source;
const newStore = {
...store,
source,
};
return newStore;
}
case 'updateConfig': {
const config = action.payload.config;
const newStore = {
...store,
config,
};
return newStore;
}
case 'toggleInternals': {
const newStore = {
...store,
showInternals: !store.showInternals,
};
return newStore;
}
}
}

View File

@@ -4,103 +4,78 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, {
startTransition,
useId,
unstable_ViewTransition as ViewTransition,
unstable_addTransitionType as addTransitionType,
} from 'react';
import clsx from 'clsx';
import {TOGGLE_TAB_TRANSITION} from '../lib/transitionTypes';
import {Resizable} from 're-resizable';
import React, {useCallback} from 'react';
type TabsRecord = Map<string, React.ReactNode>;
export default function TabbedWindow(props: {
defaultTab: string | null;
tabs: TabsRecord;
tabsOpen: Set<string>;
setTabsOpen: (newTab: Set<string>) => void;
changedPasses: Set<string>;
}): React.ReactElement {
if (props.tabs.size === 0) {
return (
<div
className="flex items-center justify-center"
style={{width: 'calc(100vw - 650px)'}}>
No compiler output detected, see errors below
</div>
);
}
return (
<div className="flex flex-row">
{Array.from(props.tabs.keys()).map(name => {
return (
<TabbedWindowItem
name={name}
key={name}
tabs={props.tabs}
tabsOpen={props.tabsOpen}
setTabsOpen={props.setTabsOpen}
hasChanged={props.changedPasses.has(name)}
/>
);
})}
</div>
);
}
function TabbedWindowItem({
name,
export default function TabbedWindow({
tabs,
tabsOpen,
setTabsOpen,
hasChanged,
activeTab,
onTabChange,
}: {
name: string;
tabs: TabsRecord;
tabsOpen: Set<string>;
setTabsOpen: (newTab: Set<string>) => void;
hasChanged: boolean;
tabs: Map<string, React.ReactNode>;
activeTab: string;
onTabChange: (tab: string) => void;
}): React.ReactElement {
const isShow = tabsOpen.has(name);
const id = useId();
const transitionName = `tab-highlight-${id}`;
const toggleTabs = useCallback(() => {
const nextState = new Set(tabsOpen);
if (nextState.has(name)) {
nextState.delete(name);
} else {
nextState.add(name);
}
setTabsOpen(nextState);
}, [tabsOpen, name, setTabsOpen]);
// Replace spaces with non-breaking spaces
const displayName = name.replace(/ /g, '\u00A0');
const handleTabChange = (tab: string): void => {
startTransition(() => {
addTransitionType(TOGGLE_TAB_TRANSITION);
onTabChange(tab);
});
};
return (
<div key={name} className="flex flex-row">
{isShow ? (
<Resizable className="border-r" minWidth={550} enable={{right: true}}>
<h2
title="Minimize tab"
aria-label="Minimize tab"
onClick={toggleTabs}
className={`p-4 duration-150 ease-in border-b cursor-pointer border-grey-200 ${
hasChanged ? 'font-bold' : 'font-light'
} text-secondary hover:text-link`}>
- {displayName}
</h2>
{tabs.get(name) ?? <div>No output for {name}</div>}
</Resizable>
) : (
<div className="relative items-center h-full px-1 py-6 align-middle border-r border-grey-200">
<button
title={`Expand compiler tab: ${name}`}
aria-label={`Expand compiler tab: ${name}`}
style={{transform: 'rotate(90deg) translate(-50%)'}}
onClick={toggleTabs}
className={`flex-grow-0 w-5 transition-colors duration-150 ease-in ${
hasChanged ? 'font-bold' : 'font-light'
} text-secondary hover:text-link`}>
{displayName}
</button>
<div className="flex-1 min-w-[550px] sm:min-w-0">
<div className="flex flex-col h-full max-w-full">
<div className="flex p-2 flex-shrink-0">
{Array.from(tabs.keys()).map(tab => {
const isActive = activeTab === tab;
return (
<button
key={tab}
onClick={() => handleTabChange(tab)}
className={clsx(
'transition-transform py-1.5 px-1.5 xs:px-3 sm:px-4 rounded-full text-sm relative',
isActive ? 'text-link' : 'hover:bg-primary/5',
)}>
{isActive && (
<ViewTransition
name={transitionName}
enter={{default: 'none'}}
exit={{default: 'none'}}
share={{
[TOGGLE_TAB_TRANSITION]: 'tab-highlight',
default: 'none',
}}
update={{default: 'none'}}>
<div className="absolute inset-0 bg-highlight rounded-full" />
</ViewTransition>
)}
<ViewTransition
enter={{default: 'none'}}
exit={{default: 'none'}}
update={{
[TOGGLE_TAB_TRANSITION]: 'tab-text',
default: 'none',
}}>
<span className="relative z-1">{tab}</span>
</ViewTransition>
</button>
);
})}
</div>
)}
<div className="flex-1 overflow-hidden w-full h-full">
{tabs.get(activeTab)}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,308 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {parse as babelParse, ParseResult} from '@babel/parser';
import * as HermesParser from 'hermes-parser';
import * as t from '@babel/types';
import BabelPluginReactCompiler, {
CompilerError,
CompilerErrorDetail,
CompilerDiagnostic,
Effect,
ErrorCategory,
parseConfigPragmaForTests,
ValueKind,
type Hook,
PluginOptions,
CompilerPipelineValue,
parsePluginOptions,
printReactiveFunctionWithOutlined,
printFunctionWithOutlined,
type LoggerEvent,
} from 'babel-plugin-react-compiler';
import {transformFromAstSync} from '@babel/core';
import type {
CompilerOutput,
CompilerTransformOutput,
PrintedCompilerPipelineValue,
} from '../components/Editor/Output';
function parseInput(
input: string,
language: 'flow' | 'typescript',
): ParseResult<t.File> {
// Extract the first line to quickly check for custom test directives
if (language === 'flow') {
return HermesParser.parse(input, {
babel: true,
flow: 'all',
sourceType: 'module',
enableExperimentalComponentSyntax: true,
});
} else {
return babelParse(input, {
plugins: ['typescript', 'jsx'],
sourceType: 'module',
}) as ParseResult<t.File>;
}
}
function invokeCompiler(
source: string,
language: 'flow' | 'typescript',
options: PluginOptions,
): CompilerTransformOutput {
const ast = parseInput(source, language);
let result = transformFromAstSync(ast, source, {
filename: '_playgroundFile.js',
highlightCode: false,
retainLines: true,
plugins: [[BabelPluginReactCompiler, options]],
ast: true,
sourceType: 'module',
configFile: false,
sourceMaps: true,
babelrc: false,
});
if (result?.ast == null || result?.code == null || result?.map == null) {
throw new Error('Expected successful compilation');
}
return {
code: result.code,
sourceMaps: result.map,
language,
};
}
const COMMON_HOOKS: Array<[string, Hook]> = [
[
'useFragment',
{
valueKind: ValueKind.Frozen,
effectKind: Effect.Freeze,
noAlias: true,
transitiveMixedData: true,
},
],
[
'usePaginationFragment',
{
valueKind: ValueKind.Frozen,
effectKind: Effect.Freeze,
noAlias: true,
transitiveMixedData: true,
},
],
[
'useRefetchableFragment',
{
valueKind: ValueKind.Frozen,
effectKind: Effect.Freeze,
noAlias: true,
transitiveMixedData: true,
},
],
[
'useLazyLoadQuery',
{
valueKind: ValueKind.Frozen,
effectKind: Effect.Freeze,
noAlias: true,
transitiveMixedData: true,
},
],
[
'usePreloadedQuery',
{
valueKind: ValueKind.Frozen,
effectKind: Effect.Freeze,
noAlias: true,
transitiveMixedData: true,
},
],
];
function parseOptions(
source: string,
mode: 'compiler' | 'linter',
configOverrides: string,
): PluginOptions {
// Extract the first line to quickly check for custom test directives
const pragma = source.substring(0, source.indexOf('\n'));
const parsedPragmaOptions = parseConfigPragmaForTests(pragma, {
compilationMode: 'infer',
environment:
mode === 'linter'
? {
// enabled in compiler
validateRefAccessDuringRender: false,
// enabled in linter
validateNoSetStateInRender: true,
validateNoSetStateInEffects: true,
validateNoJSXInTryStatements: true,
validateNoImpureFunctionsInRender: true,
validateStaticComponents: true,
validateNoFreezingKnownMutableFunctions: true,
validateNoVoidUseMemo: true,
}
: {
/* use defaults for compiler mode */
},
});
// Parse config overrides from config editor
let configOverrideOptions: any = {};
const configMatch = configOverrides.match(/^\s*import.*?\n\n\((.*)\)/s);
if (configOverrides.trim()) {
if (configMatch && configMatch[1]) {
const configString = configMatch[1].replace(/satisfies.*$/, '').trim();
configOverrideOptions = new Function(`return (${configString})`)();
} else {
throw new Error('Invalid override format');
}
}
const opts: PluginOptions = parsePluginOptions({
...parsedPragmaOptions,
...configOverrideOptions,
environment: {
...parsedPragmaOptions.environment,
...configOverrideOptions.environment,
customHooks: new Map([...COMMON_HOOKS]),
},
});
return opts;
}
export function compile(
source: string,
mode: 'compiler' | 'linter',
configOverrides: string,
): [CompilerOutput, 'flow' | 'typescript', PluginOptions | null] {
const results = new Map<string, Array<PrintedCompilerPipelineValue>>();
const error = new CompilerError();
const otherErrors: Array<CompilerErrorDetail | CompilerDiagnostic> = [];
const upsert: (result: PrintedCompilerPipelineValue) => void = result => {
const entry = results.get(result.name);
if (Array.isArray(entry)) {
entry.push(result);
} else {
results.set(result.name, [result]);
}
};
let language: 'flow' | 'typescript';
if (source.match(/\@flow/)) {
language = 'flow';
} else {
language = 'typescript';
}
let transformOutput;
let baseOpts: PluginOptions | null = null;
try {
baseOpts = parseOptions(source, mode, configOverrides);
} catch (err) {
error.details.push(
new CompilerErrorDetail({
category: ErrorCategory.Config,
reason: `Unexpected failure when transforming configs! \n${err}`,
loc: null,
suggestions: null,
}),
);
}
if (baseOpts) {
try {
const logIR = (result: CompilerPipelineValue): void => {
switch (result.kind) {
case 'ast': {
break;
}
case 'hir': {
upsert({
kind: 'hir',
fnName: result.value.id,
name: result.name,
value: printFunctionWithOutlined(result.value),
});
break;
}
case 'reactive': {
upsert({
kind: 'reactive',
fnName: result.value.id,
name: result.name,
value: printReactiveFunctionWithOutlined(result.value),
});
break;
}
case 'debug': {
upsert({
kind: 'debug',
fnName: null,
name: result.name,
value: result.value,
});
break;
}
default: {
const _: never = result;
throw new Error(`Unhandled result ${result}`);
}
}
};
// Add logger options to the parsed options
const opts = {
...baseOpts,
logger: {
debugLogIRs: logIR,
logEvent: (_filename: string | null, event: LoggerEvent): void => {
if (event.kind === 'CompileError') {
otherErrors.push(event.detail);
}
},
},
};
transformOutput = invokeCompiler(source, language, opts);
} catch (err) {
/**
* error might be an invariant violation or other runtime error
* (i.e. object shape that is not CompilerError)
*/
if (err instanceof CompilerError && err.details.length > 0) {
error.merge(err);
} else {
/**
* Handle unexpected failures by logging (to get a stack trace)
* and reporting
*/
error.details.push(
new CompilerErrorDetail({
category: ErrorCategory.Invariant,
reason: `Unexpected failure when transforming input! \n${err}`,
loc: null,
suggestions: null,
}),
);
}
}
}
// Only include logger errors if there weren't other errors
if (!error.hasErrors() && otherErrors.length !== 0) {
otherErrors.forEach(e => error.details.push(e));
}
if (error.hasErrors() || !transformOutput) {
return [{kind: 'err', results, error}, language, baseOpts];
}
return [
{kind: 'ok', results, transformOutput, errors: error.details},
language,
baseOpts,
];
}

View File

@@ -13,10 +13,21 @@ export default function MyApp() {
}
`;
export const defaultConfig = `\
import type { PluginOptions } from 'babel-plugin-react-compiler/dist';
({
//compilationMode: "all"
} satisfies PluginOptions);`;
export const defaultStore: Store = {
source: index,
config: defaultConfig,
showInternals: false,
};
export const emptyStore: Store = {
source: '',
config: '',
showInternals: false,
};

View File

@@ -10,18 +10,20 @@ import {
compressToEncodedURIComponent,
decompressFromEncodedURIComponent,
} from 'lz-string';
import {defaultStore} from '../defaultStore';
import {defaultStore, defaultConfig} from '../defaultStore';
/**
* Global Store for Playground
*/
export interface Store {
source: string;
config: string;
showInternals: boolean;
}
export function encodeStore(store: Store): string {
return compressToEncodedURIComponent(JSON.stringify(store));
}
export function decodeStore(hash: string): Store {
export function decodeStore(hash: string): any {
return JSON.parse(decompressFromEncodedURIComponent(hash));
}
@@ -62,8 +64,14 @@ export function initStoreFromUrlOrLocalStorage(): Store {
*/
if (!encodedSource) return defaultStore;
const raw = decodeStore(encodedSource);
const raw: any = decodeStore(encodedSource);
invariant(isValidStore(raw), 'Invalid Store');
return raw;
// Make sure all properties are populated
return {
source: raw.source,
config: 'config' in raw && raw['config'] ? raw.config : defaultConfig,
showInternals: 'showInternals' in raw ? raw.showInternals : false,
};
}

View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export const CONFIG_PANEL_TRANSITION = 'config-panel';
export const TOGGLE_TAB_TRANSITION = 'toggle-tab';
export const TOGGLE_INTERNALS_TRANSITION = 'toggle-internals';
export const EXPAND_ACCORDION_TRANSITION = 'open-accordion';

View File

@@ -1,5 +0,0 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

View File

@@ -11,6 +11,7 @@ const path = require('path');
const nextConfig = {
experimental: {
reactCompiler: true,
viewTransition: true,
},
reactStrictMode: true,
webpack: (config, options) => {

View File

@@ -26,34 +26,39 @@
"@babel/traverse": "^7.18.9",
"@babel/types": "7.26.3",
"@heroicons/react": "^1.0.6",
"@monaco-editor/react": "^4.4.6",
"@playwright/test": "^1.51.1",
"@monaco-editor/react": "^4.8.0-rc.2",
"@playwright/test": "^1.56.1",
"@use-gesture/react": "^10.2.22",
"hermes-eslint": "^0.25.0",
"hermes-parser": "^0.25.0",
"invariant": "^2.2.4",
"lru-cache": "^11.2.2",
"lz-string": "^1.5.0",
"monaco-editor": "^0.52.0",
"next": "^15.2.0-canary.64",
"next": "15.5.9",
"notistack": "^3.0.0-alpha.7",
"prettier": "^3.3.3",
"pretty-format": "^29.3.1",
"re-resizable": "^6.9.16",
"react": "^19.0.0",
"react-dom": "^19.0.0"
"react": "19.2.3",
"react-dom": "19.2.3"
},
"devDependencies": {
"@types/node": "18.11.9",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@types/react": "19.2",
"@types/react-dom": "19.2",
"autoprefixer": "^10.4.13",
"clsx": "^1.2.1",
"concurrently": "^7.4.0",
"eslint": "^8.28.0",
"eslint-config-next": "^15.0.1",
"eslint-config-next": "15.5.2",
"monaco-editor-webpack-plugin": "^7.1.0",
"postcss": "^8.4.31",
"tailwindcss": "^3.2.4",
"wait-on": "^7.2.0"
},
"resolutions": {
"@types/react": "19.2",
"@types/react-dom": "19.2"
}
}

View File

@@ -55,12 +55,16 @@ export default defineConfig({
// contextOptions: {
// ignoreHTTPSErrors: true,
// },
viewport: {width: 1920, height: 1080},
},
projects: [
{
name: 'chromium',
use: {...devices['Desktop Chrome']},
use: {
...devices['Desktop Chrome'],
viewport: {width: 1920, height: 1080},
},
},
// {
// name: 'Desktop Firefox',

View File

@@ -69,3 +69,75 @@
scrollbar-width: none; /* Firefox */
}
}
::view-transition-old(.slide-in) {
animation-name: slideOutLeft;
}
::view-transition-new(.slide-in) {
animation-name: slideInLeft;
}
::view-transition-group(.slide-in) {
z-index: 1;
}
::view-transition-old(.slide-out) {
animation-name: slideOutLeft;
}
::view-transition-new(.slide-out) {
animation-name: slideInLeft;
}
::view-transition-group(.slide-out) {
z-index: 1;
}
@keyframes slideOutLeft {
from {
transform: translateX(0);
}
to {
transform: translateX(-100%);
}
}
@keyframes slideInLeft {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
::view-transition-old(.container),
::view-transition-new(.container) {
height: 100%;
}
::view-transition-old(.accordion-container),
::view-transition-new(.accordion-container) {
height: 100%;
object-fit: none;
object-position: left;
}
::view-transition-old(.tab-highlight),
::view-transition-new(.tab-highlight) {
height: 100%;
}
::view-transition-group(.tab-text) {
z-index: 1;
}
::view-transition-old(.expand-accordion),
::view-transition-new(.expand-accordion) {
width: auto;
}
::view-transition-group(.expand-accordion) {
overflow: clip;
}
/**
* For some reason, the original Monaco editor is still visible to the
* left of the DiffEditor. This is a workaround for better visual clarity.
*/
.monaco-diff-editor .editor.original{
visibility: hidden !important;
}

View File

@@ -6,6 +6,9 @@
"dom.iterable",
"esnext"
],
"types": [
"react/experimental"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,

File diff suppressed because it is too large Load Diff

View File

@@ -17,7 +17,32 @@ yarn snap:build
yarn snap --watch
```
`snap` is our custom test runner, which creates "golden" test files that have the expected output for each input fixture, as well as the results of executing a specific input (or sequence of inputs) in both the uncompiled and compiler versions of the input.
`snap` is our custom test runner, which creates "golden" test files that have the expected output for each input fixture, as well as the results of executing a specific input (or sequence of inputs) in both the uncompiled and compiler versions of the input.
### Compiling Arbitrary Files
You can compile any file (not just fixtures) using:
```sh
# Compile a file and see the output
yarn snap compile <path>
# Compile with debug output to see the state after each compiler pass
# This is an alternative to `yarn snap -d -p <pattern>` when you don't have a fixture file yet
yarn snap compile --debug <path>
```
### Minimizing Test Cases
To reduce a failing test case to its minimal reproduction:
```sh
# Minimize a file that causes a compiler error
yarn snap minimize <path>
# Minimize and update the file in-place
yarn snap minimize --update <path>
```
When contributing changes, we prefer to:
* Add one or more fixtures that demonstrate the current compiled output for a particular combination of input and configuration. Send this as a first PR.

View File

@@ -0,0 +1,333 @@
## React Compiler Fault Tolerance
Update React Compiler (@compiler/ directory) to always run all passes and return either the transformed code (if no error) or a list of one or more compilation errors.
## Background
Currently React Compiler runs through a series of passes in Pipeline.ts. If an error occurs in a pass the compiler will generally either throw the error in the pass where it occurs, or return a Result<_, CompilerError> which is then unwrapped in Pipeline.ts, throwing there. This means that a single error that triggers early can prevent later validation from running, meaning the user has to first fix one error in order to see another.
## New Approach
The compiler should always run all passes in the pipeline, up to and including CodegenReactiveFunction. During this process it should accumulate errors. If at the end of compilation there were no accumulated errors, return `Ok(generatedfunction)`. Else, return `Err(CompilerError)` with *all* the accumulated errors.
Note that some errors may continue to cause an eager bailout:
* If an error is not an instanceof CompilerError, throw it as it occurs
* If an error is a CompilerError invariant, throw it as it occurs since this represents a truly exceptional, unexpected case
## Detailed Design
* The Environment needs a way to record errors as compilation proceeds. This should generally store the error (and log, if a logger is configured), but should immediately throw if the error is an invariant (see above).
* BuildHIR should always produce an HIR without error. For syntax forms that are unsupported (currently throwing a Todo error), we should instead construct record the todo error on the environment, and construct a partial HIR. The exact form of the partial HIR can be situation specific:
* `var` is currently unsupported, but we could pretend it was `let`
* `finally` blocks are unsupported, we could just prune them, or move the code after the try/catch (put the finally logic in the consequent)
* This may mean updating the HIR to allow representing partial code
* `eval()` can just be an Unsupported InstructionValue variant
* All of the passes need to be updated to stop returning Result or CompilerError, and instead record their errors on the environment. They should always be able to proceed even in the presence of errors. For example, in InferMutationAliasingEffects if we discover that the code mutates a frozen value, we can record this as an error and then just pretend the mutation didn't happen - ie construct a scope as if the mutating code was not a mutation after all.
* Finally, the end of the pipeline should check for errors and either turn `Ok(GeneratedFunction)` or `Err(aggregatedErrors)`. The code calling into the pipeline then needs to handle this appropriately.
## Detailed Plan
### Phase 1: Environment Error Accumulation Infrastructure
Add error accumulation to the `Environment` class so that any pass can record errors during compilation without halting.
- [x] **1.1 Add error accumulator to Environment** (`src/HIR/Environment.ts`)
- Add a `#errors: CompilerError` field, initialized in the constructor
- Add a `recordError(error: CompilerDiagnostic | CompilerErrorDetail)` method that:
- If an Invariant-category detail, immediately throw it
- Otherwise, push the diagnostic/detail onto `#errors` (and log via `this.logger` if configured)
- Add a `recordErrors(error: CompilerError)` method that calls `recordError()` for each of the details on the given error.
- Add a `hasErrors(): boolean` getter
- Add a `aggregateErrors(): CompilerError` method that returns the accumulated error object
- Consider whether `recordError` should accept the same options as `CompilerError.push()` for convenience (reason, description, severity, loc, etc.)
- [x] **1.2 Add a `tryRecord` helper on Environment** (`src/HIR/Environment.ts`)
- Add a `tryRecord(fn: () => void): void` method that wraps a callback in try/catch:
- If `fn` throws a `CompilerError` that is NOT an invariant, record it via `recordError`
- If `fn` throws a non-CompilerError or a CompilerError invariant, re-throw
- This helper is the migration path for passes that currently throw: wrap their call in `env.tryRecord(() => pass(hir))` so exceptions become recorded errors
### Phase 2: Update Pipeline.ts to Accumulate Errors
Change `runWithEnvironment` to run all passes and check for errors at the end instead of letting exceptions propagate.
- [x] **2.1 Change `runWithEnvironment` return type** (`src/Entrypoint/Pipeline.ts`)
- Change return type from `CodegenFunction` to `Result<CodegenFunction, CompilerError>`
- At the end of the pipeline, check `env.hasErrors()`:
- If no errors: return `Ok(ast)`
- If errors: return `Err(env.aggregateErrors())`
- [x] **2.2 Update `compileFn` to propagate the Result** (`src/Entrypoint/Pipeline.ts`)
- Change `compileFn` return type from `CodegenFunction` to `Result<CodegenFunction, CompilerError>`
- Propagate the Result from `runWithEnvironment`
- [x] **2.3 Update `run` to propagate the Result** (`src/Entrypoint/Pipeline.ts`)
- Same change for the internal `run` function
- [x] **2.4 Update callers in Program.ts** (`src/Entrypoint/Program.ts`)
- In `tryCompileFunction`, change from try/catch around `compileFn` to handling the `Result`:
- If `Ok(codegenFn)`: return the compiled function
- If `Err(compilerError)`: return `{kind: 'error', error: compilerError}`
- Keep the try/catch only for truly unexpected (non-CompilerError) exceptions and invariants
- The existing `handleError`/`logError`/`panicThreshold` logic in `processFn` should continue to work unchanged since it already handles `CompilerError` instances
### Phase 3: Update BuildHIR (lower) to Always Produce HIR
Currently `lower()` returns `Result<HIRFunction, CompilerError>`. It already accumulates errors internally via `builder.errors`, but returns `Err` when errors exist. Change it to always return `Ok(hir)` while recording errors on the environment.
- [x] **3.1 Change `lower` to always return HIRFunction** (`src/HIR/BuildHIR.ts`)
- Change return type from `Result<HIRFunction, CompilerError>` to `HIRFunction`
- Instead of returning `Err(builder.errors)` at line 227-229, record errors on `env` via `env.recordErrors(builder.errors)` and return the (partial) HIR
- Update the pipeline to call `lower(func, env)` directly instead of `lower(func, env).unwrap()`
- Added try/catch around body lowering to catch thrown CompilerErrors (e.g., from `resolveBinding`) and record them
- [x] **3.2 Handle `var` declarations as `let`** (`src/HIR/BuildHIR.ts`, line ~855)
- Record the Todo error, then treat `var` as `let` and continue lowering (instead of skipping the declaration)
- [x] **3.3 Handle `try/finally` by pruning `finally`** (`src/HIR/BuildHIR.ts`, lines ~1281-1296)
- Already handled: `try` without `catch` pushes error and returns; `try` with `finally` pushes error and continues with `try/catch` portion only
- [x] **3.4 Handle `eval()` via UnsupportedNode** (`src/HIR/BuildHIR.ts`, line ~3568)
- Already handled: records error via `builder.errors.push()` and continues
- [x] **3.5 Handle `with` statement via UnsupportedNode** (`src/HIR/BuildHIR.ts`, line ~1382)
- Already handled: records error and emits `UnsupportedNode`
- [x] **3.6 Handle inline `class` declarations** (`src/HIR/BuildHIR.ts`, line ~1402)
- Already handled: records error and emits `UnsupportedNode`
- [x] **3.7 Handle remaining Todo errors in expression lowering** (`src/HIR/BuildHIR.ts`)
- Already handled: all ~60 error sites use `builder.errors.push()` to accumulate errors. The try/catch around body lowering provides a safety net for any that still throw.
- [x] **3.8 Handle `throw` inside `try/catch`** (`src/HIR/BuildHIR.ts`, line ~284)
- Already handled: records error via `builder.errors.push()` and continues
- [x] **3.9 Handle `for` loops with missing test or expression init** (`src/HIR/BuildHIR.ts`, lines ~559, ~632)
- For `for(;;)` (missing test): emit `true` as the test expression and add a branch terminal
- For empty init (`for (; ...)`): add a placeholder instruction to avoid invariant about empty blocks
- For expression init (`for (expr; ...)`): record error and lower the expression as best-effort
- Changed `'unsupported'` terminal to `'goto'` terminal for non-variable init to maintain valid CFG structure
- [x] **3.10 Handle nested function lowering failures** (`src/HIR/BuildHIR.ts`, `lowerFunction` at line ~3504)
- `lowerFunction()` now always returns `LoweredFunction` since `lower()` always returns `HIRFunction`
- Errors from nested functions are recorded on the shared environment
- Removed the `null` return case and the corresponding `UnsupportedNode` fallback in callers
- [x] **3.11 Handle unreachable functions in `build()`** (`src/HIR/HIRBuilder.ts`, `build()`)
- Changed `CompilerError.throwTodo()` for unreachable code with hoisted declarations to `this.errors.push()` to allow HIR construction to complete
- [x] **3.12 Handle duplicate fbt tags** (`src/HIR/BuildHIR.ts`, line ~2279)
- Changed `CompilerError.throwDiagnostic()` to `builder.errors.pushDiagnostic()` to record instead of throw
### Phase 4: Update Validation Passes
All validation passes need to record errors on the environment instead of returning `Result` or throwing. They should still detect the same problems, but the pipeline should continue after each one.
#### Pattern A passes (currently return `Result`, called with `.unwrap()`)
These passes already accumulate errors internally and return `Result<void, CompilerError>`. The change is: instead of returning the Result, record errors on `env` and return void. Remove the `.unwrap()` call in Pipeline.ts.
- [x] **4.1 `validateHooksUsage`** (`src/Validation/ValidateHooksUsage.ts`)
- Change signature from `(fn: HIRFunction): Result<void, CompilerError>` to `(fn: HIRFunction): void`
- Record errors on `fn.env` instead of returning `errors.asResult()`
- Update Pipeline.ts call site (line 211): remove `.unwrap()`
- [x] **4.2 `validateNoCapitalizedCalls`** (`src/Validation/ValidateNoCapitalizedCalls.ts`)
- Change signature to return void
- Fix the hybrid pattern: the direct `CallExpression` path currently throws via `CompilerError.throwInvalidReact()` — change to record on env
- The `MethodCall` path already accumulates — change to record on env
- Update Pipeline.ts call site (line 214): remove `.unwrap()`
- [x] **4.3 `validateUseMemo`** (`src/Validation/ValidateUseMemo.ts`)
- Change signature to return void
- Record hard errors on env instead of returning `errors.asResult()`
- The soft `voidMemoErrors` path already uses `env.logErrors()` — keep as-is or also record
- Update Pipeline.ts call site (line 170): remove `.unwrap()`
- [x] **4.4 `dropManualMemoization`** (`src/Inference/DropManualMemoization.ts`)
- Change signature to return void
- Record errors on env instead of returning `errors.asResult()`
- Update Pipeline.ts call site (line 178): remove `.unwrap()`
- [x] **4.5 `validateNoRefAccessInRender`** (`src/Validation/ValidateNoRefAccessInRender.ts`)
- Change signature to return void
- Record errors on env instead of returning Result
- Update Pipeline.ts call site (line 275): remove `.unwrap()`
- [x] **4.6 `validateNoSetStateInRender`** (`src/Validation/ValidateNoSetStateInRender.ts`)
- Change signature to return void
- Record errors on env
- Update Pipeline.ts call site (line 279): remove `.unwrap()`
- [x] **4.7 `validateNoImpureFunctionsInRender`** (`src/Validation/ValidateNoImpureFunctionsInRender.ts`)
- Change signature to return void
- Record errors on env
- Update Pipeline.ts call site (line 300): remove `.unwrap()`
- [x] **4.8 `validateNoFreezingKnownMutableFunctions`** (`src/Validation/ValidateNoFreezingKnownMutableFunctions.ts`)
- Change signature to return void
- Record errors on env
- Update Pipeline.ts call site (line 303): remove `.unwrap()`
- [x] **4.9 `validateExhaustiveDependencies`** (`src/Validation/ValidateExhaustiveDependencies.ts`)
- Change signature to return void
- Record errors on env
- Update Pipeline.ts call site (line 315): remove `.unwrap()`
- [x] **4.10 `validateMemoizedEffectDependencies`** (`src/Validation/ValidateMemoizedEffectDependencies.ts`)
- Change signature to return void (note: operates on `ReactiveFunction`)
- Record errors on the function's env
- Update Pipeline.ts call site (line 565): remove `.unwrap()`
- [x] **4.11 `validatePreservedManualMemoization`** (`src/Validation/ValidatePreservedManualMemoization.ts`)
- Change signature to return void (note: operates on `ReactiveFunction`)
- Record errors on the function's env
- Update Pipeline.ts call site (line 572): remove `.unwrap()`
- [x] **4.12 `validateSourceLocations`** (`src/Validation/ValidateSourceLocations.ts`)
- Change signature to return void
- Record errors on env
- Update Pipeline.ts call site (line 585): remove `.unwrap()`
#### Pattern B passes (currently use `env.logErrors()`)
These already use a soft-logging pattern and don't block compilation. They can be migrated to `env.recordError()` so all errors are aggregated in one place.
- [ ] **4.13 `validateNoDerivedComputationsInEffects_exp`** — change to record on env directly
- [ ] **4.14 `validateNoSetStateInEffects`** — change to record on env directly
- [ ] **4.15 `validateNoJSXInTryStatement`** — change to record on env directly
- [ ] **4.16 `validateStaticComponents`** — change to record on env directly
#### Pattern D passes (currently throw directly, no Result)
These throw `CompilerError` directly (not via Result). They need the most work.
- [x] **4.17 `validateContextVariableLValues`** (`src/Validation/ValidateContextVariableLValues.ts`)
- Currently throws via `CompilerError.throwTodo()` and `CompilerError.invariant()`
- Change to record Todo errors on env and continue
- Keep invariant throws (those indicate internal bugs)
- [x] **4.18 `validateLocalsNotReassignedAfterRender`** (`src/Validation/ValidateLocalsNotReassignedAfterRender.ts`)
- Currently constructs a `CompilerError` and `throw`s it directly
- Change to record errors on env
- [x] **4.19 `validateNoDerivedComputationsInEffects`** (`src/Validation/ValidateNoDerivedComputationsInEffects.ts`)
- Currently throws directly
- Change to record errors on env
### Phase 5: Update Inference Passes
The inference passes are the most critical to handle correctly because they produce side effects (populating effects on instructions, computing mutable ranges) that downstream passes depend on. They must continue producing valid (even if imprecise) output when errors are encountered.
- [x] **5.1 `inferMutationAliasingEffects`** (`src/Inference/InferMutationAliasingEffects.ts`)
- Currently returns `Result<void, CompilerError>` — errors are about mutation of frozen/global values
- Change to record errors on `fn.env` instead of accumulating internally
- **Key recovery strategy**: When a mutation of a frozen value is detected, record the error but treat the operation as a non-mutating read. This way downstream passes see a consistent (if conservative) view
- When a mutation of a global is detected, record the error but continue with the global unchanged
- Update Pipeline.ts (lines 233-239): remove the conditional `.isErr()` / throw pattern
- [x] **5.2 `inferMutationAliasingRanges`** (`src/Inference/InferMutationAliasingRanges.ts`)
- Currently returns `Result<Array<AliasingEffect>, CompilerError>`
- This pass has a meaningful success value (the function's external aliasing effects)
- Change to: always produce a best-effort effects array, record errors on env
- When errors are encountered, produce conservative effects (e.g., assume no external mutation)
- Update Pipeline.ts (lines 258-267): remove the conditional throw pattern, call directly
### Phase 6: Update Codegen
- [x] **6.1 `codegenFunction`** (`src/ReactiveScopes/CodegenReactiveFunction.ts`)
- Currently returns `Result<CodegenFunction, CompilerError>`
- Change to: always produce a `CodegenFunction`, record errors on env
- If codegen encounters an error (e.g., an instruction it can't generate code for), it should:
- Record the error
- For `UnsupportedNode` values: pass through the original AST node (already works this way)
- For other error cases: emit a placeholder or the original AST where possible
- Update Pipeline.ts (line 575-578): remove `.unwrap()`
### Phase 7: Pipeline.ts Pass-by-Pass Migration
Walk through `runWithEnvironment` and wrap each pass call site. This is the integration work tying Phases 3-6 together.
- [x] **7.1 Wrap `lower()` call** (line 163)
- Change from `lower(func, env).unwrap()` to `lower(func, env)` (direct return after Phase 3.1)
- [x] **7.2 Wrap validation calls that use `.unwrap()`** (lines 169-303)
- Remove `.unwrap()` from all validation calls after they're updated in Phase 4
- For validations guarded by `env.enableValidations`, keep the guard but remove the `.unwrap()`
- [x] **7.3 Wrap inference calls** (lines 233-267)
- After Phase 5, `inferMutationAliasingEffects` and `inferMutationAliasingRanges` record errors directly
- Remove the `mutabilityAliasingErrors` / `mutabilityAliasingRangeErrors` variables and their conditional throw logic
- [x] **7.4 Wrap `env.logErrors()` calls** (lines 286-331)
- After Phase 4.13-4.16, these passes record on env directly
- Remove the `env.logErrors()` wrapper calls
- [x] **7.5 Wrap codegen** (lines 575-578)
- After Phase 6.1, `codegenFunction` returns directly
- Remove the `.unwrap()`
- [x] **7.6 Add final error check** (end of `runWithEnvironment`)
- After all passes complete, check `env.hasErrors()`
- If no errors: return `Ok(ast)`
- If errors: return `Err(env.aggregateErrors())`
- [x] **7.7 Consider wrapping each pass in `env.tryRecord()`** as a safety net
- Even after individual passes are updated, wrapping each pass call in `env.tryRecord()` provides defense-in-depth
- If a pass unexpectedly throws a CompilerError (e.g., from a code path we missed), it gets caught and recorded rather than aborting the pipeline
- Non-CompilerError exceptions and invariants still propagate immediately
### Phase 8: Testing
- [x] **8.1 Update existing `error.todo-*` fixture expectations**
- Currently, fixtures with `error.todo-` prefix expect a single error and bailout
- After fault tolerance, some of these may now produce multiple errors
- Update the `.expect.md` files to reflect the new aggregated error output
- [x] **8.2 Add multi-error test fixtures**
- Create test fixtures that contain multiple independent errors (e.g., both a `var` declaration and a mutation of a frozen value)
- Verify that all errors are reported, not just the first one
- [x] **8.3 Add test for invariant-still-throws behavior**
- Verify that `CompilerError.invariant()` failures still cause immediate abort
- Verify that non-CompilerError exceptions still cause immediate abort
- [x] **8.4 Add test for partial HIR codegen**
- Verify that when BuildHIR produces partial HIR (with `UnsupportedNode` values), later passes handle it gracefully and codegen produces the original AST for unsupported portions
- [x] **8.5 Verify error severity in aggregated output**
- Test that the aggregated `CompilerError` correctly reports `hasErrors()` vs `hasWarning()` vs `hasHints()` based on the mix of accumulated diagnostics
- Verify that `panicThreshold` behavior in Program.ts is correct for aggregated errors
- [x] **8.6 Run full test suite**
- Run `yarn snap` and `yarn snap -u` to update all fixture expectations
- Ensure no regressions in passing tests
### Implementation Notes
**Ordering**: Phases 1 → 2 → 3 → 4/5/6 (parallel) → 7 → 8. Phase 1 (Environment infrastructure) is the foundation. Phase 2 (Pipeline return type) sets up the contract. Phases 3-6 can be done incrementally — each pass can be migrated independently using `env.tryRecord()` as a transitional wrapper. Phase 7 is the integration. Phase 8 validates everything.
**Incremental migration path**: Rather than updating all passes at once, each pass can be individually migrated. During the transition:
1. First add `env.tryRecord()` in Phase 7.7 around all pass calls in the pipeline — this immediately provides fault tolerance by catching any thrown CompilerError
2. Then individually update passes (Phases 3-6) to record errors directly on env, which is cleaner but not required for the basic behavior
3. This means the feature can be landed incrementally: Phase 1 + 2 + 7.7 gives basic fault tolerance, then individual passes can be refined over time
**What NOT to change**:
- `CompilerError.invariant()` must continue to throw immediately — these represent internal bugs
- Non-CompilerError exceptions must continue to throw — these are unexpected JS errors
- The `assertConsistentIdentifiers`, `assertTerminalSuccessorsExist`, `assertTerminalPredsExist`, `assertValidBlockNesting`, `assertValidMutableRanges`, `assertWellFormedBreakTargets`, `assertScopeInstructionsWithinScopes` assertion functions should continue to throw — they are invariant checks on internal data structure consistency
- The `panicThreshold` mechanism in Program.ts should continue to work — it now operates on the aggregated error from the Result rather than a caught exception, but the behavior is the same
## Key Learnings
* **Phase 2+7 (Pipeline tryRecord wrapping) was sufficient for basic fault tolerance.** Wrapping all passes in `env.tryRecord()` immediately enabled the compiler to continue past errors that previously threw. This caused 52 test fixtures to produce additional errors that were previously masked by the first error bailing out. For example, `error.todo-reassign-const` previously reported only "Support destructuring of context variables" but now also reports the immutability violation.
* **Lint-only passes (Pattern B: `env.logErrors()`) should not use `tryRecord()`/`recordError()`** because those errors are intentionally non-blocking. They are reported via the logger only and should not cause the pipeline to return `Err`. The `logErrors` pattern was kept for `validateNoDerivedComputationsInEffects_exp`, `validateNoSetStateInEffects`, `validateNoJSXInTryStatement`, and `validateStaticComponents`.
* **Inference passes that return `Result` with validation errors** (`inferMutationAliasingEffects`, `inferMutationAliasingRanges`) were changed to record errors via `env.recordErrors()` instead of throwing, allowing subsequent passes to proceed.
* **Value-producing passes** (`memoizeFbtAndMacroOperandsInSameScope`, `renameVariables`, `buildReactiveFunction`) need safe default values when wrapped in `tryRecord()` since the callback can't return values. We initialize with empty defaults (e.g., `new Set()`) before the `tryRecord()` call.
* **Phase 3 (BuildHIR) revealed that most error sites already used `builder.errors.push()` for accumulation.** The existing lowering code was designed to accumulate errors rather than throw. The main changes were: (1) changing `lower()` return type from `Result` to `HIRFunction`, (2) recording builder errors on env, (3) adding a try/catch around body lowering to catch thrown CompilerErrors from sub-calls like `resolveBinding()`, (4) treating `var` as `let` instead of skipping declarations, and (5) fixing ForStatement init/test handling to produce valid CFG structure.
* **Partial HIR can trigger downstream invariants.** When lowering skips or partially handles constructs (e.g., unreachable hoisted functions, `var` declarations before the fix), downstream passes like `InferMutationAliasingEffects` may encounter uninitialized identifiers and throw invariants. This is acceptable since the function still correctly bails out of compilation, but error messages may be less specific. The fix for `var` (treating as `let`) demonstrates how to avoid this: continue lowering with a best-effort representation rather than skipping entirely.
* **Errors accumulated on `env` are lost when an invariant propagates out of the pipeline.** Since invariant CompilerErrors always re-throw through `tryRecord()`, they exit the pipeline as exceptions. The caller only sees the invariant error, not any errors previously recorded on `env`. This is a design limitation that could be addressed by aggregating env errors with caught exceptions in `tryCompileFunction()`.
* **Dedicated fault tolerance test fixtures** were added in `__tests__/fixtures/compiler/fault-tolerance/`. Each fixture combines two or more errors from different passes to verify the compiler reports all of them rather than short-circuiting on the first. Coverage includes: `var`+props mutation (BuildHIR→InferMutationAliasingEffects), `var`+ref access (BuildHIR→ValidateNoRefAccessInRender), `try/finally`+props mutation (BuildHIR→InferMutationAliasingEffects), `try/finally`+ref access (BuildHIR→ValidateNoRefAccessInRender), and a 3-error test combining try/finally+ref access+props mutation.
* **Cleanup: consistent `tryRecord()` wrapping in Pipeline.ts.** All validation passes and inference passes are now wrapped in `env.tryRecord()` for defense-in-depth, consistent with the approach used for transform passes. Previously only transform passes were wrapped. Merged duplicate `env.enableValidations` guard blocks. Pattern B lint-only passes (`env.logErrors()`) were intentionally not wrapped since they use a different error recording strategy.
* **Cleanup: normalized validation error recording pattern.** Four validation passes (`ValidateNoDerivedComputationsInEffects`, `ValidateMemoizedEffectDependencies`, `ValidatePreservedManualMemoization`, `ValidateSourceLocations`) were using `for (const detail of errors.details) { env.recordError(detail); }` instead of the simpler `env.recordErrors(errors)`. Normalized to use the batch method.

View File

@@ -19,7 +19,8 @@
"test": "yarn workspaces run test",
"snap": "yarn workspace babel-plugin-react-compiler run snap",
"snap:build": "yarn workspace snap run build",
"npm:publish": "node scripts/release/publish"
"npm:publish": "node scripts/release/publish",
"eslint-docs": "yarn workspace babel-plugin-react-compiler build && node scripts/build-eslint-docs.js"
},
"dependencies": {
"fs-extra": "^4.0.2",

View File

@@ -0,0 +1,157 @@
# lower (BuildHIR)
## File
`src/HIR/BuildHIR.ts`
## Purpose
Converts a Babel AST function node into a High-level Intermediate Representation (HIR), which represents code as a control-flow graph (CFG) with basic blocks, instructions, and terminals. This is the first major transformation pass in the React Compiler pipeline, enabling precise expression-level memoization analysis.
## Input Invariants
- Input must be a valid Babel `NodePath<t.Function>` (FunctionDeclaration, FunctionExpression, or ArrowFunctionExpression)
- The function must be a component or hook (determined by the environment)
- Babel scope analysis must be available for binding resolution
- An `Environment` instance must be provided with compiler configuration
- Optional `bindings` map for nested function lowering (recursive calls)
- Optional `capturedRefs` map for context variables captured from outer scope
## Output Guarantees
- Returns `Result<HIRFunction, CompilerError>` - either a successfully lowered function or compilation errors
- The HIR function contains:
- A complete CFG with basic blocks (`body.blocks: Map<BlockId, BasicBlock>`)
- Each block has an array of instructions and exactly one terminal
- All control flow is explicit (if/else, loops, switch, logical operators, ternary)
- Parameters are converted to `Place` or `SpreadPattern`
- Context captures are tracked in `context` array
- Function metadata (id, async, generator, directives)
- All identifiers get unique `IdentifierId` values
- Instructions have placeholder instruction IDs (set to 0, assigned later)
- Effects are null (populated by later inference passes)
## Algorithm
The lowering algorithm uses a recursive descent pattern with a `HIRBuilder` helper class:
1. **Initialization**: Create an `HIRBuilder` with environment and optional bindings. Process captured context variables.
2. **Parameter Processing**: For each function parameter:
- Simple identifiers: resolve binding and create Place
- Patterns (object/array): create temporary Place, then emit destructuring assignments
- Rest elements: wrap in SpreadPattern
- Unsupported: emit Todo error
3. **Body Processing**:
- Arrow function expressions: lower body expression to temporary, emit implicit return
- Block statements: recursively lower each statement
4. **Statement Lowering** (`lowerStatement`): Handle each statement type:
- **Control flow**: Create separate basic blocks for branches, loops connect back to conditional blocks
- **Variable declarations**: Create `DeclareLocal`/`DeclareContext` or `StoreLocal`/`StoreContext` instructions
- **Expressions**: Lower to temporary and discard result
- **Hoisting**: Detect forward references and emit `DeclareContext` for hoisted identifiers
5. **Expression Lowering** (`lowerExpression`): Convert expressions to `InstructionValue`:
- **Identifiers**: Create `LoadLocal`, `LoadContext`, or `LoadGlobal` based on binding
- **Literals**: Create `Primitive` values
- **Operators**: Create `BinaryExpression`, `UnaryExpression` etc.
- **Calls**: Distinguish `CallExpression` vs `MethodCall` (member expression callee)
- **Control flow expressions**: Create separate value blocks for branches (ternary, logical, optional chaining)
- **JSX**: Lower to `JsxExpression` with lowered tag, props, and children
6. **Block Management**: The builder maintains:
- A current work-in-progress block accumulating instructions
- Completed blocks map
- Scope stack for break/continue resolution
- Exception handler stack for try/catch
7. **Termination**: Add implicit void return at end if no explicit return
## Key Data Structures
### HIRBuilder (from HIRBuilder.ts)
- `#current: WipBlock` - Work-in-progress block being populated
- `#completed: Map<BlockId, BasicBlock>` - Finished blocks
- `#scopes: Array<Scope>` - Stack for break/continue target resolution (LoopScope, LabelScope, SwitchScope)
- `#exceptionHandlerStack: Array<BlockId>` - Stack of catch handlers for try/catch
- `#bindings: Bindings` - Map of variable names to their identifiers
- `#context: Map<t.Identifier, SourceLocation>` - Captured context variables
- Methods: `push()`, `reserve()`, `enter()`, `terminate()`, `terminateWithContinuation()`
### Core HIR Types
- **BasicBlock**: Contains `instructions: Array<Instruction>`, `terminal: Terminal`, `preds: Set<BlockId>`, `phis: Set<Phi>`, `kind: BlockKind`
- **Instruction**: Contains `id`, `lvalue` (Place), `value` (InstructionValue), `effects` (null initially), `loc`
- **Terminal**: Block terminator - `if`, `branch`, `goto`, `return`, `throw`, `for`, `while`, `switch`, `ternary`, `logical`, etc.
- **Place**: Reference to a value - `{kind: 'Identifier', identifier, effect, reactive, loc}`
- **InstructionValue**: The operation - `LoadLocal`, `StoreLocal`, `CallExpression`, `BinaryExpression`, `FunctionExpression`, etc.
### Block Kinds
- `block` - Regular sequential block
- `loop` - Loop header/test block
- `value` - Block that produces a value (ternary/logical branches)
- `sequence` - Sequence expression block
- `catch` - Exception handler block
## Edge Cases
1. **Hoisting**: Forward references to `let`/`const`/`function` declarations emit `DeclareContext` before the reference, enabling correct temporal dead zone handling
2. **Context Variables**: Variables captured by nested functions use `LoadContext`/`StoreContext` instead of `LoadLocal`/`StoreLocal`
3. **For-of/For-in Loops**: Synthesize iterator instructions (`GetIterator`, `IteratorNext`, `NextPropertyOf`)
4. **Optional Chaining**: Creates nested `OptionalTerminal` structures with short-circuit branches
5. **Logical Expressions**: Create branching structures where left side stores to temporary, right side only evaluated if needed
6. **Try/Catch**: Adds `MaybeThrowTerminal` after each instruction in try block, modeling potential control flow to handler
7. **JSX in fbt**: Tracks `fbtDepth` counter to handle whitespace differently in fbt/fbs tags
8. **Unsupported Syntax**: `var` declarations, `with` statements, inline `class` declarations, `eval` - emit appropriate errors
## TODOs
- `returnTypeAnnotation: null, // TODO: extract the actual return type node if present`
- `TODO(gsn): In the future, we could only pass in the context identifiers that are actually used by this function and its nested functions`
- Multiple `// TODO remove type cast` in destructuring pattern handling
- `// TODO: should JSX namespaced names be handled here as well?`
## Example
Input JavaScript:
```javascript
export default function foo(x, y) {
if (x) {
return foo(false, y);
}
return [y * 10];
}
```
Output HIR (simplified):
```
foo(<unknown> x$0, <unknown> y$1): <unknown> $12
bb0 (block):
[1] <unknown> $6 = LoadLocal <unknown> x$0
[2] If (<unknown> $6) then:bb2 else:bb1 fallthrough=bb1
bb2 (block):
predecessor blocks: bb0
[3] <unknown> $2 = LoadGlobal(module) foo
[4] <unknown> $3 = false
[5] <unknown> $4 = LoadLocal <unknown> y$1
[6] <unknown> $5 = Call <unknown> $2(<unknown> $3, <unknown> $4)
[7] Return Explicit <unknown> $5
bb1 (block):
predecessor blocks: bb0
[8] <unknown> $7 = LoadLocal <unknown> y$1
[9] <unknown> $8 = 10
[10] <unknown> $9 = Binary <unknown> $7 * <unknown> $8
[11] <unknown> $10 = Array [<unknown> $9]
[12] Return Explicit <unknown> $10
```
Key observations:
- The function has 3 basic blocks: entry (bb0), consequent (bb2), alternate/fallthrough (bb1)
- The if statement creates an `IfTerminal` at the end of bb0
- Each branch ends with its own `ReturnTerminal`
- All values are stored in temporaries (`$N`) or named identifiers (`x$0`, `y$1`)
- Instructions have sequential IDs within blocks
- Types and effects are `<unknown>` at this stage (populated by later passes)

View File

@@ -0,0 +1,182 @@
# enterSSA
## File
`src/SSA/EnterSSA.ts`
## Purpose
Converts the HIR from a non-SSA form (where variables can be reassigned) into Static Single Assignment (SSA) form, where each variable is defined exactly once and phi nodes are inserted at control flow join points to merge values from different paths.
## Input Invariants
- The HIR must have blocks in reverse postorder (predecessors visited before successors, except for back-edges)
- Block predecessor information (`block.preds`) must be populated correctly
- The function's `context` array must be empty for the root function (outer function declarations)
- Identifiers may be reused across multiple definitions/assignments (non-SSA form)
## Output Guarantees
- Each identifier has a unique `IdentifierId` - no identifier is defined more than once
- All operand references use the SSA-renamed identifiers
- Phi nodes are inserted at join points where values from different control flow paths converge
- Function parameters are SSA-renamed
- Nested functions (FunctionExpression, ObjectMethod) are recursively converted to SSA form
- Context variables (captured from outer scopes) are handled specially and not redefined
## Algorithm
The pass uses the Braun et al. algorithm ("Simple and Efficient Construction of Static Single Assignment Form") with adaptations for handling loops and nested functions.
### Key Steps:
1. **Block Traversal**: Iterate through blocks in order (assumed reverse postorder from previous passes)
2. **Definition Tracking**: Maintain a per-block `defs` map from original identifiers to their SSA-renamed versions
3. **Renaming**:
- When a value is **defined** (lvalue), create a new SSA identifier with fresh `IdentifierId`
- When a value is **used** (operand), look up the current SSA identifier via `getIdAt`
4. **Phi Node Insertion**: When looking up an identifier at a block with multiple predecessors:
- If all predecessors have been visited, create a phi node collecting values from each predecessor
- If some predecessors are unvisited (back-edge/loop), create an "incomplete phi" that will be fixed later
5. **Incomplete Phi Resolution**: When all predecessors of a block are finally visited, fix any incomplete phi nodes by populating their operands
6. **Nested Function Handling**: Recursively apply SSA transformation to nested functions, temporarily adding a fake predecessor edge to enable identifier lookup from the enclosing scope
### Phi Node Placement Logic (`getIdAt`):
- If the identifier is defined locally in the current block, return it
- If at entry block with no predecessors and not found, mark as unknown (global)
- If some predecessors are unvisited (loop), create incomplete phi
- If exactly one predecessor, recursively look up in that predecessor
- If multiple predecessors, create phi node with operands from all predecessors
## Key Data Structures
- **SSABuilder**: Main class managing the transformation
- `#states: Map<BasicBlock, State>` - Per-block state (defs map and incomplete phis)
- `unsealedPreds: Map<BasicBlock, number>` - Count of unvisited predecessors per block
- `#unknown: Set<Identifier>` - Identifiers assumed to be globals
- `#context: Set<Identifier>` - Context variables that should not be redefined
- **State**: Per-block state containing:
- `defs: Map<Identifier, Identifier>` - Maps original identifiers to SSA-renamed versions
- `incompletePhis: Array<IncompletePhi>` - Phi nodes waiting for predecessor values
- **IncompletePhi**: Tracks a phi node created before all predecessors were visited
- `oldPlace: Place` - Original place being phi'd
- `newPlace: Place` - SSA-renamed phi result place
- **Phi**: The actual phi node in the HIR
- `place: Place` - The result of the phi
- `operands: Map<BlockId, Place>` - Maps predecessor block to the place providing the value
## Edge Cases
- **Loops (back-edges)**: When a variable is used in a loop header before the loop body assigns it, an incomplete phi is created and later fixed when the loop body block is visited
- **Globals**: If an identifier is used but never defined (reaching the entry block without a definition), it's assumed to be a global and not renamed
- **Context variables**: Variables captured from an outer function scope are tracked specially and not redefined when reassigned
- **Nested functions**: Function expressions and object methods are processed recursively with a temporary predecessor edge linking them to the enclosing block
## TODOs
- `[hoisting] EnterSSA: Expected identifier to be defined before being used` - Handles cases where hoisting causes an identifier to be used before definition (throws a Todo error for graceful bailout)
## Example
### Input (simple reassignment with control flow):
```javascript
function foo() {
let y = 2;
if (y > 1) {
y = 1;
} else {
y = 2;
}
let x = y;
}
```
### Before SSA (HIR):
```
bb0 (block):
[1] $0 = 2
[2] $2 = StoreLocal Let y$1 = $0
[3] $7 = LoadLocal y$1
[4] $8 = 1
[5] $9 = Binary $7 > $8
[6] If ($9) then:bb2 else:bb3 fallthrough=bb1
bb2 (block):
predecessor blocks: bb0
[7] $3 = 1
[8] $4 = StoreLocal Reassign y$1 = $3 // Same y$1 reassigned
[9] Goto bb1
bb3 (block):
predecessor blocks: bb0
[10] $5 = 2
[11] $6 = StoreLocal Reassign y$1 = $5 // Same y$1 reassigned
[12] Goto bb1
bb1 (block):
predecessor blocks: bb2 bb3
[13] $10 = LoadLocal y$1 // Which y$1?
[14] $12 = StoreLocal Let x$11 = $10
```
### After SSA:
```
bb0 (block):
[1] $15 = 2
[2] $17 = StoreLocal Let y$16 = $15 // y$16: initial definition
[3] $18 = LoadLocal y$16
[4] $19 = 1
[5] $20 = Binary $18 > $19
[6] If ($20) then:bb2 else:bb3 fallthrough=bb1
bb2 (block):
predecessor blocks: bb0
[7] $21 = 1
[8] $23 = StoreLocal Reassign y$22 = $21 // y$22: new SSA name
[9] Goto bb1
bb3 (block):
predecessor blocks: bb0
[10] $24 = 2
[11] $26 = StoreLocal Reassign y$25 = $24 // y$25: new SSA name
[12] Goto bb1
bb1 (block):
predecessor blocks: bb2 bb3
y$27: phi(bb2: y$22, bb3: y$25) // PHI NODE: merges y$22 and y$25
[13] $28 = LoadLocal y$27 // Uses phi result
[14] $30 = StoreLocal Let x$29 = $28
```
### Loop Example (while loop with back-edge):
```javascript
function foo() {
let x = 1;
while (x < 10) {
x = x + 1;
}
return x;
}
```
### After SSA:
```
bb0 (block):
[1] $13 = 1
[2] $15 = StoreLocal Let x$14 = $13 // x$14: initial definition
[3] While test=bb1 loop=bb3 fallthrough=bb2
bb1 (loop):
predecessor blocks: bb0 bb3
x$16: phi(bb0: x$14, bb3: x$23) // PHI merges initial and loop-updated values
[4] $17 = LoadLocal x$16
[5] $18 = 10
[6] $19 = Binary $17 < $18
[7] Branch ($19) then:bb3 else:bb2
bb3 (block):
predecessor blocks: bb1
[8] $20 = LoadLocal x$16 // Uses phi result
[9] $21 = 1
[10] $22 = Binary $20 + $21
[11] $24 = StoreLocal Reassign x$23 = $22 // x$23: new SSA name in loop body
[12] Goto(Continue) bb1
bb2 (block):
predecessor blocks: bb1
[13] $25 = LoadLocal x$16 // Uses phi result
[14] Return Explicit $25
```
The phi node at `bb1` (the loop header) is initially created as an "incomplete phi" when first visited because `bb3` (the loop body) hasn't been visited yet. Once `bb3` is processed and its terminal is handled, the incomplete phi is fixed by calling `fixIncompletePhis` to populate the operand from `bb3`.

View File

@@ -0,0 +1,90 @@
# eliminateRedundantPhi
## File
`src/SSA/EliminateRedundantPhi.ts`
## Purpose
Eliminates phi nodes whose operands are trivially the same, replacing all usages of the phi's output identifier with the single source identifier. This simplifies the HIR by removing unnecessary join points that do not actually merge distinct values.
## Input Invariants
- The function must be in SSA form (i.e., `enterSSA` has already run)
- Blocks are in reverse postorder (guaranteed by the HIR structure)
- Phi nodes exist at the start of blocks where control flow merges
## Output Guarantees
- All redundant phi nodes are removed from the HIR
- All references to eliminated phi identifiers are rewritten to the source identifier
- Non-redundant phi nodes (those merging two or more distinct values) are preserved
- Nested function expressions (FunctionExpression, ObjectMethod) also have their redundant phis eliminated and contexts rewritten
## Algorithm
A phi node is considered redundant when:
1. **All operands are the same identifier**: e.g., `x2 = phi(x1, x1, x1)` - the phi is replaced with `x1`
2. **All operands are either the same identifier OR the phi's output**: e.g., `x2 = phi(x1, x2, x1, x2)` - this handles loop back-edges where the phi references itself
The algorithm works as follows:
1. Visit blocks in reverse postorder, building a rewrite table (`Map<Identifier, Identifier>`)
2. For each phi node in a block:
- First rewrite operands using any existing rewrites (to handle cascading eliminations)
- Check if all operands (excluding self-references) point to the same identifier
- If so, add a mapping from the phi's output to that identifier and delete the phi
3. After processing phis, rewrite all instruction lvalues, operands, and terminal operands
4. For nested functions, recursively call `eliminateRedundantPhi` with shared rewrites
5. If the CFG has back-edges (loops) and new rewrites were added, repeat the entire process
The loop termination condition `rewrites.size > size && hasBackEdge` ensures:
- Without loops: completes in a single pass (reverse postorder guarantees forward propagation)
- With loops: repeats until no new rewrites are found (fixpoint)
## Key Data Structures
- **`Phi`** (from `src/HIR/HIR.ts`): Represents a phi node with:
- `place: Place` - the output identifier
- `operands: Map<BlockId, Place>` - maps predecessor block IDs to source places
- **`rewrites: Map<Identifier, Identifier>`**: Maps eliminated phi outputs to their replacement identifier
- **`visited: Set<BlockId>`**: Tracks visited blocks to detect back-edges (loops)
## Edge Cases
- **Loop back-edges**: When a block has a predecessor that hasn't been visited yet (in reverse postorder), that predecessor is a back-edge. The algorithm handles self-referential phis like `x2 = phi(x1, x2)` by ignoring operands equal to the phi's output.
- **Cascading eliminations**: When one phi's output is used in another phi's operands, the algorithm rewrites operands before checking redundancy, enabling transitive elimination in a single pass (for non-loop cases).
- **Nested functions**: FunctionExpression and ObjectMethod values contain nested HIR that may have their own phis. The algorithm recursively processes these with a shared rewrite table, ensuring context captures are also rewritten.
- **Empty phi check**: The algorithm includes an invariant check that phi operands are never empty (which would be invalid HIR).
## TODOs
(None found in the source code)
## Example
Consider this fixture from `rewrite-phis-in-lambda-capture-context.js`:
```javascript
function Component() {
const x = 4;
const get4 = () => {
while (bar()) {
if (baz) { bar(); }
}
return () => x;
};
return get4;
}
```
**After SSA pass**, the inner function has redundant phis due to the loop:
```
bb2 (loop):
predecessor blocks: bb1 bb5
x$29: phi(bb1: x$21, bb5: x$30) // Loop header phi
...
bb5 (block):
predecessor blocks: bb6 bb4
x$30: phi(bb6: x$29, bb4: x$29) // Redundant: both operands are x$29
...
```
**After EliminateRedundantPhi**:
- `x$30 = phi(x$29, x$29)` is eliminated because both operands are `x$29`
- `x$29 = phi(x$21, x$30)` becomes `x$29 = phi(x$21, x$29)` after rewriting, which is also redundant (one operand is the phi itself, the other is `x$21`)
- Both phis are eliminated, and all uses of `x$29` and `x$30` are rewritten to `x$21`
The result: the context capture `@context[x$29]` becomes `@context[x$21]`, correctly propagating that `x` is never modified inside the loop.

View File

@@ -0,0 +1,110 @@
# constantPropagation
## File
`src/Optimization/ConstantPropagation.ts`
## Purpose
Applies Sparse Conditional Constant Propagation (SCCP) to fold compile-time evaluable expressions to constant values, propagate those constants through the program, and eliminate unreachable branches when conditionals have known constant values.
## Input Invariants
- HIR must be in SSA form (runs after `enterSSA`)
- Redundant phi nodes should be eliminated (runs after `eliminateRedundantPhi`)
- Consistent identifiers must be ensured (`assertConsistentIdentifiers`)
- Terminal successors must exist (`assertTerminalSuccessorsExist`)
## Output Guarantees
- Instructions with compile-time evaluable operands are replaced with `Primitive` constants
- `ComputedLoad`/`ComputedStore` with constant string/number properties are converted to `PropertyLoad`/`PropertyStore`
- `LoadLocal` and `StoreLocal` propagate known constant values
- `IfTerminal` with constant boolean test values are replaced with `goto` terminals
- Unreachable blocks are removed and the CFG is minimized
- Phi nodes with unreachable predecessor operands are pruned
- Nested functions (`FunctionExpression`, `ObjectMethod`) are recursively processed
## Algorithm
The pass uses Sparse Conditional Constant Propagation (SCCP) with fixpoint iteration:
1. **Data Structure**: A `Constants` map (`Map<IdentifierId, Constant>`) tracks known constant values (either `Primitive` or `LoadGlobal`)
2. **Single Pass per Iteration**: Visits all blocks in order:
- Evaluates phi nodes - if all operands have the same constant value, the phi result is constant
- Evaluates instructions - replaces evaluable expressions with constants
- Evaluates terminals - if an `IfTerminal` test is a constant, replaces it with a `goto`
3. **Fixpoint Loop**: If any terminals changed (branch elimination):
- Recomputes block ordering (`reversePostorderBlocks`)
- Removes unreachable code (`removeUnreachableForUpdates`, `removeDeadDoWhileStatements`, `removeUnnecessaryTryCatch`)
- Renumbers instructions (`markInstructionIds`)
- Updates predecessors (`markPredecessors`)
- Prunes phi operands from unreachable predecessors
- Eliminates newly-redundant phis (`eliminateRedundantPhi`)
- Merges consecutive blocks (`mergeConsecutiveBlocks`)
- Repeats until no more changes
4. **Instruction Evaluation**: Handles various instruction types:
- **Primitives/LoadGlobal**: Directly constant
- **BinaryExpression**: Folds arithmetic (`+`, `-`, `*`, `/`, `%`, `**`), bitwise (`|`, `&`, `^`, `<<`, `>>`, `>>>`), and comparison (`<`, `<=`, `>`, `>=`, `==`, `===`, `!=`, `!==`) operators
- **UnaryExpression**: Folds `!` (boolean negation) and `-` (numeric negation)
- **PostfixUpdate/PrefixUpdate**: Folds `++`/`--` on constant numbers
- **PropertyLoad**: Folds `.length` on constant strings
- **TemplateLiteral**: Folds template strings with constant interpolations
- **ComputedLoad/ComputedStore**: Converts to property access when property is constant string/number
## Key Data Structures
- `Constant = Primitive | LoadGlobal` - The lattice values (no top/bottom, absence means unknown)
- `Constants = Map<IdentifierId, Constant>` - Maps identifier IDs to their known constant values
- Uses HIR types: `Instruction`, `Phi`, `Place`, `Primitive`, `LoadGlobal`, `InstructionValue`
## Edge Cases
- **Last instruction of sequence blocks**: Skipped to preserve evaluation order
- **Phi nodes with back-edges**: Single-pass analysis means loop back-edges won't have constant values propagated
- **Template literals with Symbol**: Not folded (would throw at runtime)
- **Template literals with objects/arrays**: Not folded (custom toString behavior)
- **Division results**: Computed at compile time (may produce `NaN`, `Infinity`, etc.)
- **LoadGlobal in phis**: Only propagated if all operands reference the same global name
- **Nested functions**: Constants from outer scope are propagated into nested function expressions
## TODOs
- `// TODO: handle more cases` - The default case in `evaluateInstruction` has room for additional instruction types
## Example
**Input:**
```javascript
function Component() {
let a = 1;
let b;
if (a === 1) {
b = true;
} else {
b = false;
}
let c;
if (b) {
c = 'hello';
} else {
c = null;
}
return c;
}
```
**After ConstantPropagation:**
- `a === 1` evaluates to `true`
- The `if (a === 1)` branch is eliminated, only consequent remains
- `b` is known to be `true`
- `if (b)` branch is eliminated, only consequent remains
- `c` is known to be `'hello'`
- All intermediate blocks are merged
**Output:**
```javascript
function Component() {
return "hello";
}
```
The pass performs iterative simplification: first iteration determines `a === 1` is `true` and eliminates that branch. The CFG is updated, phi for `b` is pruned to single operand making `b = true`. Second iteration uses `b = true` to eliminate the next branch. This continues until no more branches can be eliminated.

View File

@@ -0,0 +1,109 @@
# deadCodeElimination
## File
`src/Optimization/DeadCodeElimination.ts`
## Purpose
Eliminates instructions whose values are unused, reducing generated code size. The pass performs mark-and-sweep analysis to identify and remove dead code while preserving side effects and program semantics.
## Input Invariants
- Must run after `InferMutationAliasingEffects` because "dead" code may still affect effect inference
- HIR is in SSA form with phi nodes
- Unreachable blocks are already pruned during HIR construction
## Output Guarantees
- All instructions with unused lvalues (that are safe to prune) are removed
- Unused phi nodes are deleted
- Unused context variables are removed from `fn.context`
- Destructuring patterns are rewritten to remove unused bindings
- `StoreLocal` instructions with unused initializers are converted to `DeclareLocal`
## Algorithm
Two-phase mark-and-sweep with fixed-point iteration for loops:
**Phase 1: Mark (findReferencedIdentifiers)**
1. Detect if function has back-edges (loops)
2. Iterate blocks in reverse postorder (successors before predecessors) to visit usages before declarations
3. For each block:
- Mark all terminal operands as referenced
- Process instructions in reverse order:
- If lvalue is used OR instruction is not pruneable, mark the lvalue and all operands as referenced
- Special case for `StoreLocal`: only mark initializer if the SSA lvalue is actually read
- Mark phi operands if the phi result is used
4. If loops exist and new identifiers were marked, repeat until fixed point
**Phase 2: Sweep**
1. Remove unused phi nodes from each block
2. Remove instructions with unused lvalues using `retainWhere`
3. Rewrite retained instructions:
- **Array destructuring**: Replace unused elements with holes, truncate trailing holes
- **Object destructuring**: Remove unused properties (only if rest element is unused or absent)
- **StoreLocal**: Convert to `DeclareLocal` if initializer value is never read
4. Remove unused context variables
## Key Data Structures
- **State class**: Tracks referenced identifiers
- `identifiers: Set<IdentifierId>` - SSA-specific usages
- `named: Set<string>` - Named variable usages (any version)
- `isIdOrNameUsed()` - Checks if identifier or any version of named variable is used
- `isIdUsed()` - Checks if specific SSA id is used
- **hasBackEdge/findBlocksWithBackEdges**: Detect loops requiring fixed-point iteration
## Edge Cases
- **Preserved even if unused:**
- `debugger` statements (to not break debugging workflows)
- Call expressions and method calls (may have side effects)
- Await expressions
- Store operations (ComputedStore, PropertyStore, StoreGlobal)
- Delete operations (ComputedDelete, PropertyDelete)
- Iterator operations (GetIterator, IteratorNext, NextPropertyOf)
- Context operations (LoadContext, DeclareContext, StoreContext)
- Memoization markers (StartMemoize, FinishMemoize)
- **SSR mode special case:**
- In SSR mode, unused `useState`, `useReducer`, and `useRef` hooks can be removed
- **Object destructuring with rest:**
- Cannot remove unused properties if rest element is used (would change rest's value)
- **Block value instructions:**
- Last instruction of value blocks (not 'block' kind) is never pruned as it's the block's value
## TODOs
- "TODO: we could be more precise and make this conditional on whether any arguments are actually modified" (for mutating instructions)
## Example
**Input:**
```javascript
function Component(props) {
const _ = 42;
return props.value;
}
```
**After DeadCodeElimination:**
The `const _ = 42` assignment is removed since `_` is never used:
```javascript
function Component(props) {
return props.value;
}
```
**Array destructuring example:**
Input:
```javascript
function foo(props) {
const [x, unused, y] = props.a;
return x + y;
}
```
Output (middle element becomes a hole):
```javascript
function foo(props) {
const [x, , y] = props.a;
return x + y;
}
```

View File

@@ -0,0 +1,124 @@
# inferTypes
## File
`src/TypeInference/InferTypes.ts`
## Purpose
Infers types for all identifiers in the HIR by generating type equations and solving them using unification. This pass annotates identifiers with concrete types (Primitive, Object, Function) based on the operations performed on them and the types of globals/hooks they interact with.
## Input Invariants
- The HIR must be in SSA form (the pass runs after `enterSSA` and `eliminateRedundantPhi`)
- Constant propagation has already run
- Global declarations and hook shapes are available via the Environment
## Output Guarantees
- All identifier types are resolved from type variables (`Type`) to concrete types where possible
- Phi nodes have their operand types unified to produce a single result type
- Function return types are inferred from the unified types of all return statements
- Property accesses on known objects/hooks resolve to the declared property types
- Component props parameters are typed as `TObject<BuiltInProps>`
- Component ref parameters are typed as `TObject<BuiltInUseRefId>`
## Algorithm
The pass uses a classic constraint-based type inference approach with three phases:
1. **Constraint Generation (`generate`)**: Traverses all instructions and generates type equations:
- Primitives, literals, unary/binary operations -> `Primitive` type
- Hook/function calls -> Function type with fresh return type variable
- Property loads -> `Property` type that defers to object shape lookup
- Destructuring -> Property types for each extracted element
- Phi nodes -> `Phi` type with all operand types as candidates
- JSX -> `Object<BuiltInJsx>`
- Arrays -> `Object<BuiltInArray>`
- Objects -> `Object<BuiltInObject>`
2. **Unification (`Unifier.unify`)**: Solves constraints by unifying type equations:
- Type variables are bound to concrete types via substitution
- Property types are resolved by looking up the object's shape
- Phi types are resolved by finding a common type among operands (or falling back to `Phi` if incompatible)
- Function types are unified by unifying their return types
- Occurs check prevents infinite types (cycles in type references)
3. **Application (`apply`)**: Applies the computed substitutions to all identifiers in the HIR, replacing type variables with their resolved types.
## Key Data Structures
- **TypeVar** (`kind: 'Type'`): A type variable with a unique TypeId, used for unknowns
- **Unifier**: Maintains a substitution map from TypeId to Type, with methods for unification and cycle detection
- **TypeEquation**: A pair of types that should be equal, used as constraints
- **PhiType** (`kind: 'Phi'`): Represents the join of multiple types from control flow merge points
- **PropType** (`kind: 'Property'`): Deferred property lookup that resolves based on object shape
- **FunctionType** (`kind: 'Function'`): Callable type with optional shapeId and return type
- **ObjectType** (`kind: 'Object'`): Object with optional shapeId for shape lookup
## Edge Cases
### Phi Type Resolution
When phi operands have incompatible types, the pass attempts to find a union:
- `Union(Primitive | MixedReadonly) = MixedReadonly`
- `Union(Array | MixedReadonly) = Array`
- If no union is possible, the type remains as `Phi`
### Ref-like Name Inference
When `enableTreatRefLikeIdentifiersAsRefs` is enabled, property access on variables matching the pattern `/^(?:[a-zA-Z$_][a-zA-Z$_0-9]*)Ref$|^ref$/` with property name `current` infers:
- Object type as `TObject<BuiltInUseRefId>`
- Property type as `TObject<BuiltInRefValue>`
### Cycle Detection
The `occursCheck` method prevents infinite types by detecting when a type variable appears in its own substitution. When a cycle is detected, `tryResolveType` removes the cyclic reference from Phi operands.
### Context Variables
- `DeclareContext` and `LoadContext` generate no type equations (intentionally untyped)
- `StoreContext` with `Const` kind does propagate the rvalue type to enable ref inference through context variables
## TODOs
1. **Hook vs Function type ambiguity**:
> "TODO: callee could be a hook or a function, so this type equation isn't correct. We should change Hook to a subtype of Function or change unifier logic."
2. **PropertyStore rvalue inference**:
> "TODO: consider using the rvalue type here" - Currently uses a dummy type for PropertyStore to avoid inferring rvalue types from lvalue assignments.
## Example
**Input (infer-phi-primitive.js):**
```javascript
function foo(a, b) {
let x;
if (a) {
x = 1;
} else {
x = 2;
}
let y = x;
return y;
}
```
**Before InferTypes (SSA form):**
```
<unknown> x$26: phi(bb2: <unknown> x$21, bb3: <unknown> x$24)
[10] <unknown> $27 = LoadLocal <unknown> x$26
[11] <unknown> $29 = StoreLocal Let <unknown> y$28 = <unknown> $27
```
**After InferTypes:**
```
<unknown> x$26:TPrimitive: phi(bb2: <unknown> x$21:TPrimitive, bb3: <unknown> x$24:TPrimitive)
[10] <unknown> $27:TPrimitive = LoadLocal <unknown> x$26:TPrimitive
[11] <unknown> $29:TPrimitive = StoreLocal Let <unknown> y$28:TPrimitive = <unknown> $27:TPrimitive
```
The pass infers that:
- Literals `1` and `2` are `TPrimitive`
- The phi of two primitives is `TPrimitive`
- Variables `x` and `y` are `TPrimitive`
- The function return type is `TPrimitive`
**Hook type inference example (useState):**
```javascript
const [x, setX] = useState(initialValue);
```
After InferTypes:
- `useState` -> `TFunction<BuiltInUseState>:TObject<BuiltInUseState>`
- Return value `$27` -> `TObject<BuiltInUseState>`
- Destructured `setX` -> `TFunction<BuiltInSetState>:TPrimitive`

View File

@@ -0,0 +1,84 @@
# analyseFunctions
## File
`src/Inference/AnalyseFunctions.ts`
## Purpose
Recursively analyzes all nested function expressions and object methods in a function to infer their aliasing effect signatures, which describe how the function affects its captured variables when invoked.
## Input Invariants
- The HIR has been through SSA conversion and type inference
- FunctionExpression and ObjectMethod instructions have an empty `aliasingEffects` array (`@aliasingEffects=[]`)
- Context variables (captured variables from outer scope) exist on `fn.context` but do not have their effect populated
## Output Guarantees
- Every FunctionExpression and ObjectMethod has its `aliasingEffects` array populated with the effects the function performs when called (mutations, captures, aliasing to return value, etc.)
- Each context variable's `effect` property is set to either `Effect.Capture` (if the variable is captured or mutated by the inner function) or `Effect.Read` (if only read)
- Context variable mutable ranges are reset to `{start: 0, end: 0}` and scopes are set to `null` to prepare for the outer function's subsequent `inferMutationAliasingRanges` pass
## Algorithm
1. **Recursive traversal**: Iterates through all blocks and instructions looking for `FunctionExpression` or `ObjectMethod` instructions
2. **Depth-first processing**: For each function expression found, calls `lowerWithMutationAliasing()` which:
- Recursively calls `analyseFunctions()` on the inner function (handles nested functions)
- Runs `inferMutationAliasingEffects()` on the inner function to determine effects
- Runs `deadCodeElimination()` to clean up
- Runs `inferMutationAliasingRanges()` to compute mutable ranges and extract externally-visible effects
- Runs `rewriteInstructionKindsBasedOnReassignment()` and `inferReactiveScopeVariables()`
- Stores the computed effects in `fn.aliasingEffects`
3. **Context variable effect classification**: Scans the computed effects to determine which context variables are captured/mutated vs only read:
- Effects like `Capture`, `Alias`, `Assign`, `MaybeAlias`, `CreateFrom` mark the source as captured
- Mutation effects (`Mutate`, `MutateTransitive`, etc.) mark the target as captured
- Sets `operand.effect = Effect.Capture` or `Effect.Read` accordingly
4. **Range reset**: Resets mutable ranges and scopes on context variables to prepare for outer function analysis
## Key Data Structures
- **HIRFunction.aliasingEffects**: Array of `AliasingEffect` storing the externally-visible behavior of a function when called
- **Place.effect**: Effect enum value (`Capture` or `Read`) describing how a context variable is used
- **AliasingEffect**: Union type describing data flow (Capture, Alias, Assign, etc.) and mutations (Mutate, MutateTransitive, etc.)
- **FunctionExpression/ObjectMethod.loweredFunc.func**: The inner HIRFunction to analyze
## Edge Cases
- **Nested functions**: Handled via recursive call to `analyseFunctions()` before processing the current function - innermost functions are analyzed first
- **ObjectMethod**: Treated identically to FunctionExpression
- **Apply effects invariant**: The pass asserts that no `Apply` effects remain in the function's signature - these should have been resolved to more precise effects by `inferMutationAliasingRanges()`
- **Conditional mutations**: Effects like `MutateTransitiveConditionally` are tracked - a function that conditionally mutates a captured variable will have that effect in its signature
- **Immutable captures**: `ImmutableCapture`, `Freeze`, `Create`, `Impure`, `Render` effects do not contribute to marking context variables as `Capture`
## TODOs
- No TODO comments in the pass itself
## Example
Consider a function that captures and conditionally mutates a variable:
```javascript
function useHook(a, b) {
let z = {a};
let y = b;
let x = function () {
if (y) {
maybeMutate(z); // Unknown function, may mutate z
}
};
return x;
}
```
**Before AnalyseFunctions:**
```
Function @context[y$28, z$25] @aliasingEffects=[]
```
**After AnalyseFunctions:**
```
Function @context[read y$28, capture z$25] @aliasingEffects=[
MutateTransitiveConditionally z$25,
Create $14 = primitive
]
```
The pass infers:
- `y` is only read (used in the condition)
- `z` is captured into the function and conditionally mutated transitively (because `maybeMutate()` is unknown)
- The inner function's signature includes `MutateTransitiveConditionally z$25` to indicate this potential mutation
This signature is then used by `InferMutationAliasingEffects` on the outer function to understand that creating this function captures `z`, and calling the function may mutate `z`.

View File

@@ -0,0 +1,144 @@
# inferMutationAliasingEffects
## File
`src/Inference/InferMutationAliasingEffects.ts`
## Purpose
Infers the mutation and aliasing effects for all instructions and terminals in the HIR, making the effects of built-in instructions/functions as well as user-defined functions explicit. These effects form the basis for subsequent analysis to determine the mutable range of each value in the program and for validation against invalid code patterns like mutating frozen values.
## Input Invariants
- HIR must be in SSA form (run after SSA pass)
- Types must be inferred (run after InferTypes pass)
- Functions must be analyzed (run after AnalyseFunctions pass) - this provides `aliasingEffects` on FunctionExpressions
- Each instruction must have an lvalue (destination place)
## Output Guarantees
- Every instruction has an `effects` array (or null if no effects) containing `AliasingEffect` objects
- Terminals that affect data flow (return, try/catch) have their `effects` populated
- Each instruction's lvalue is guaranteed to be defined in the inference state after visiting
- Effects describe: creation of values, data flow (Assign, Alias, Capture), mutations (Mutate, MutateTransitive), freezing, and errors (MutateFrozen, MutateGlobal, Impure)
## Algorithm
The pass uses abstract interpretation with the following key phases:
1. **Initialization**:
- Create initial `InferenceState` mapping identifiers to abstract values
- Initialize context variables as `ValueKind.Context`
- Initialize parameters as `ValueKind.Frozen` (for top-level components/hooks) or `ValueKind.Mutable` (for function expressions)
2. **Two-Phase Effect Processing**:
- **Phase 1 - Signature Computation**: For each instruction, compute a "candidate signature" based purely on instruction semantics and types (cached per instruction via `computeSignatureForInstruction`)
- **Phase 2 - Effect Application**: Apply the signature to the current abstract state via `applySignature`, which refines effects based on the actual runtime kinds of values
3. **Fixed-Point Iteration**:
- Process blocks in a worklist, queuing successors after each block
- Merge states at control flow join points using lattice operations
- Iterate until no changes occur (max 100 iterations as safety limit)
- Phi nodes are handled by unioning the abstract values from all predecessors
4. **Effect Refinement** (in `applyEffect`):
- `MutateConditionally` effects are dropped if value is not mutable
- `Capture` effects are downgraded to `ImmutableCapture` if source is frozen
- `Mutate` on frozen values becomes `MutateFrozen` error
- `Assign` from primitives/globals creates new values rather than aliasing
## Key Data Structures
### InferenceState
Maintains two maps:
- `#values: Map<InstructionValue, AbstractValue>` - Maps allocation sites to their abstract kind
- `#variables: Map<IdentifierId, Set<InstructionValue>>` - Maps identifiers to the set of values they may point to (set to handle phi joins)
### AbstractValue
```typescript
type AbstractValue = {
kind: ValueKind;
reason: ReadonlySet<ValueReason>;
};
```
### ValueKind (lattice)
```
MaybeFrozen <- top (unknown if frozen or mutable)
|
Frozen <- immutable, cannot be mutated
Mutable <- can be mutated locally
Context <- mutable box (context variables)
|
Global <- global value
Primitive <- copy-on-write semantics
```
The `mergeValueKinds` function implements the lattice join:
- `Frozen | Mutable -> MaybeFrozen`
- `Context | Mutable -> Context`
- `Context | Frozen -> MaybeFrozen`
### AliasingEffect Types
Key effect kinds handled:
- **Create**: Creates a new value at a place
- **Assign**: Direct assignment (pointer copy)
- **Alias**: Mutation of destination implies mutation of source
- **Capture**: Information flow (MutateTransitive propagates through)
- **MaybeAlias**: Possible aliasing for unknown function returns
- **Mutate/MutateTransitive**: Direct/transitive mutation
- **MutateConditionally/MutateTransitiveConditionally**: Conditional versions
- **Freeze**: Marks value as immutable
- **Apply**: Function call with complex data flow
## Edge Cases
1. **Spread Destructuring from Props**: The `findNonMutatedDestructureSpreads` pre-pass identifies spread patterns from frozen values that are never mutated, allowing them to be treated as frozen.
2. **Hoisted Context Declarations**: Special handling for variables declared with hoisting (`HoistedConst`, `HoistedFunction`, `HoistedLet`) to detect access before declaration.
3. **Try-Catch Aliasing**: When a `maybe-throw` terminal is reached, call return values are aliased into the catch binding since exceptions can throw return values.
4. **Function Expressions**: Functions are considered mutable only if they have mutable captures or tracked side effects (MutateFrozen, MutateGlobal, Impure).
5. **Iterator Mutation**: Non-builtin iterators may alias their collection and mutation of the iterator is conditional.
6. **Array.push and Similar**: Uses legacy signature system with `Store` effect on receiver and `Capture` of arguments.
## TODOs
- `// TODO: using InstructionValue as a bit of a hack, but it's pragmatic` - context variable initialization
- `// TODO: call applyEffect() instead` - try-catch aliasing
- `// TODO: make sure we're also validating against global mutations somewhere` - global mutation validation for effects/event handlers
- `// TODO; include "render" here?` - whether to track Render effects in function hasTrackedSideEffects
- `// TODO: consider using persistent data structures to make clone cheaper` - performance optimization for state cloning
- `// TODO check this` and `// TODO: what kind here???` - DeclareLocal value kinds
## Example
For the code:
```javascript
const arr = [];
arr.push({});
arr.push(x, y);
```
After `InferMutationAliasingEffects`, the effects are:
```
[10] $39 = Array []
Create $39 = mutable // Array literal creates mutable value
[11] $41 = StoreLocal arr$40 = $39
Assign arr$40 = $39 // arr points to the array value
Assign $41 = $39
[15] $45 = MethodCall $42.push($44)
Apply $45 = $42.$43($44) // Records the call
Mutate $42 // push mutates the array
Capture $42 <- $44 // {} is captured into array
Create $45 = primitive // push returns number (length)
[20] $50 = MethodCall $46.push($48, $49)
Apply $50 = $46.$47($48, $49)
Mutate $46 // push mutates the array
Capture $46 <- $48 // x captured into array
Capture $46 <- $49 // y captured into array
Create $50 = primitive
```
The key insight is that `Mutate` effects extend the mutable range of the array, and `Capture` effects record data flow so that if the array is later frozen (e.g., returned from a component), the captured values are also considered frozen for validation purposes.

View File

@@ -0,0 +1,149 @@
# inferMutationAliasingRanges
## File
`src/Inference/InferMutationAliasingRanges.ts`
## Purpose
This pass builds an abstract model of the heap and interprets the effects of the given function to determine: (1) the mutable ranges of all identifiers, (2) the externally-visible effects of the function (mutations of params/context-vars, aliasing relationships), and (3) the legacy `Effect` annotation for each Place.
## Input Invariants
- InferMutationAliasingEffects must have already run, populating `instr.effects` on each instruction with aliasing/mutation effects
- SSA form must be established (identifiers are in SSA)
- Type inference has been run (InferTypes)
- Functions have been analyzed (AnalyseFunctions)
- Dead code elimination has been performed
## Output Guarantees
- Every identifier has a populated `mutableRange` (start:end instruction IDs)
- Every Place has a legacy `Effect` annotation (Read, Capture, Store, Freeze, etc.)
- The function's `aliasingEffects` array is populated with externally-visible effects (mutations of params/context-vars, aliasing between params/context-vars/return)
- Validation errors are collected for invalid effects like `MutateFrozen` or `MutateGlobal`
## Algorithm
The pass operates in three main phases:
**Part 1: Build Data Flow Graph and Infer Mutable Ranges**
1. Creates an `AliasingState` which maintains a `Node` for each identifier
2. Iterates through all blocks and instructions, processing effects in program order
3. For each effect:
- `Create`/`CreateFunction`: Creates a new node in the graph
- `CreateFrom`/`Assign`/`Alias`: Adds alias edges between nodes (with ordering index)
- `MaybeAlias`: Adds conditional alias edges
- `Capture`: Adds capture edges (for transitive mutations)
- `Mutate*`: Queues mutations for later processing
- `Render`: Queues render effects for later processing
4. Phi node operands are connected once their predecessor blocks have been visited
5. After the graph is built, mutations are processed:
- Mutations propagate both forward (via edges) and backward (via aliases/captures)
- Each mutation extends the `mutableRange.end` of affected identifiers
- Transitive mutations also traverse capture edges backward
- `MaybeAlias` edges downgrade mutations to `Conditional`
6. Render effects are processed to mark values as rendered
**Part 2: Populate Legacy Per-Place Effects**
- Sets legacy effects on lvalues and operands based on instruction effects and mutable ranges
- Fixes up mutable range start values for identifiers that are mutated after creation
**Part 3: Infer Externally-Visible Function Effects**
- Creates a `Create` effect for the return value
- Simulates transitive mutations of each param/context-var/return to detect capture relationships
- Produces `Alias`/`Capture` effects showing data flow between params/context-vars/return
## Key Data Structures
### `AliasingState`
The main state class maintaining the data flow graph:
- `nodes: Map<Identifier, Node>` - Maps identifiers to their graph nodes
### `Node`
Represents an identifier in the data flow graph:
```typescript
type Node = {
id: Identifier;
createdFrom: Map<Identifier, number>; // CreateFrom edges (source -> index)
captures: Map<Identifier, number>; // Capture edges (source -> index)
aliases: Map<Identifier, number>; // Alias/Assign edges (source -> index)
maybeAliases: Map<Identifier, number>; // MaybeAlias edges (source -> index)
edges: Array<{index, node, kind}>; // Forward edges to other nodes
transitive: {kind: MutationKind; loc} | null; // Transitive mutation info
local: {kind: MutationKind; loc} | null; // Local mutation info
lastMutated: number; // Index of last mutation affecting this node
mutationReason: MutationReason | null; // Reason for mutation
value: {kind: 'Object'} | {kind: 'Phi'} | {kind: 'Function'; function: HIRFunction};
render: Place | null; // Render context if used in JSX
};
```
### `MutationKind`
Enum describing mutation certainty:
```typescript
enum MutationKind {
None = 0,
Conditional = 1, // May mutate (e.g., via MaybeAlias or MutateConditionally)
Definite = 2, // Definitely mutates
}
```
## Edge Cases
### Phi Nodes
- Phi nodes are created as special `{kind: 'Phi'}` nodes
- Phi operands from predecessor blocks are processed with pending edges until the predecessor is visited
- When traversing "forwards" through edges and encountering a phi, backward traversal is stopped (prevents mutation from one phi input affecting other inputs)
### Transitive vs Local Mutations
- Local mutations (`Mutate`) only affect alias/assign edges backward
- Transitive mutations (`MutateTransitive`) also affect capture edges backward
- Both affect all forward edges
### MaybeAlias
- Mutations through MaybeAlias edges are downgraded to `Conditional`
- This prevents false positive errors when we cannot be certain about aliasing
### Function Values
- Functions are tracked specially as `{kind: 'Function'}` nodes
- When a function is mutated (transitively), errors from the function body are propagated
- This handles cases where mutating a captured value in a function affects render safety
### Render Effect Propagation
- Render effects traverse backward through alias/capture/createFrom edges
- Functions that have not been mutated are skipped during render traversal (except for JSX-returning functions)
- Ref types (`isUseRefType`) stop render traversal
## TODOs
1. Assign effects should have an invariant that the node is not initialized yet. Currently `InferFunctionExpressionAliasingEffectSignatures` infers Assign effects that should be Alias, causing reinitialization.
2. Phi place effects are not properly set today.
3. Phi mutable range start calculation is imprecise - currently just sets it to the instruction before the block rather than computing the exact start.
## Example
Consider the following code:
```javascript
function foo() {
let a = {}; // Create a (instruction 1)
let b = {}; // Create b (instruction 3)
a = b; // Assign a <- b (instruction 8)
mutate(a, b); // MutateTransitiveConditionally a, b (instruction 16)
return a;
}
```
The pass builds a graph:
1. Creates node for `{}` at instruction 1 (initially assigned to `a`)
2. Creates node for `{}` at instruction 3 (initially assigned to `b`)
3. At instruction 8, creates alias edge: `b -> a` with index 8
4. At instruction 16, mutations are queued for `a` and `b`
When processing the mutation of `a` at instruction 16:
- Extends `a`'s mutableRange.end to 17
- Traverses backward through alias edge to `b`, extends `b`'s mutableRange.end to 17
- Since `a = b`, both objects must be considered mutable until instruction 17
The output shows identifiers with range annotations like `$25[3:17]` meaning:
- `$25` is the identifier
- `3` is the instruction where it was created
- `17` is the instruction after which it is no longer mutated
For aliased values, the ranges are unified - all values that could be affected by a mutation have their ranges extended to include that mutation point.

View File

@@ -0,0 +1,169 @@
# inferReactivePlaces
## File
`src/Inference/InferReactivePlaces.ts`
## Purpose
Determines which `Place`s (identifiers and temporaries) in the HIR are **reactive** - meaning they may *semantically* change over the course of the component or hook's lifetime. This information is critical for memoization: reactive places form the dependencies that, when changed, should invalidate cached values.
A place is reactive if it derives from any source of reactivity:
1. **Props** - Component parameters may change between renders
2. **Hooks** - Hooks can access state or context which can change
3. **`use` operator** - Can access context which may change
4. **Mutation with reactive operands** - Values mutated in instructions that have reactive operands become reactive themselves
5. **Conditional assignment based on reactive control flow** - Values assigned in branches controlled by reactive conditions become reactive
## Input Invariants
- HIR is in SSA form with phi nodes at join points
- `inferMutationAliasingEffects` and `inferMutationAliasingRanges` have run, establishing:
- Effect annotations on operands (Effect.Capture, Effect.Store, Effect.Mutate, etc.)
- Mutable ranges on identifiers
- Aliasing relationships captured by `findDisjointMutableValues`
- All operands have known effects (asserts on `Effect.Unknown`)
## Output Guarantees
- Every reactive Place has `place.reactive = true`
- Reactivity is transitively complete (derived from reactive → reactive)
- All identifiers in a mutable alias group share reactivity
- Reactivity is propagated to operands used within nested function expressions
## Algorithm
The algorithm uses **fixpoint iteration** to propagate reactivity forward through the control-flow graph:
### Initialization
1. Create a `ReactivityMap` backed by disjoint sets of mutably-aliased identifiers
2. Mark all function parameters as reactive (props are reactive by definition)
3. Create a `ControlDominators` helper to identify blocks controlled by reactive conditions
### Fixpoint Loop
Iterate until no changes occur:
For each block:
1. **Phi Nodes**: Mark phi nodes reactive if:
- Any operand is reactive, OR
- Any predecessor block is controlled by a reactive condition (control-flow dependency)
2. **Instructions**: For each instruction:
- Track stable identifier sources (for hooks like `useRef`, `useState` dispatch)
- Check if any operand is reactive
- Hook calls and `use` operator are sources of reactivity
- If instruction has reactive input:
- Mark lvalues reactive (unless they are known-stable like `setState` functions)
- If instruction has reactive input OR is in reactive-controlled block:
- Mark mutable operands (Capture, Store, Mutate effects) as reactive
3. **Terminals**: Check terminal operands for reactivity
### Post-processing
Propagate reactivity to inner functions (nested `FunctionExpression` and `ObjectMethod`).
## Key Data Structures
### ReactivityMap
```typescript
class ReactivityMap {
hasChanges: boolean = false; // Tracks if fixpoint changed
reactive: Set<IdentifierId> = new Set(); // Set of reactive identifiers
aliasedIdentifiers: DisjointSet<Identifier>; // Mutable alias groups
}
```
- Uses disjoint sets so that when one identifier in an alias group becomes reactive, they all are effectively reactive
- `isReactive(place)` checks and marks `place.reactive = true` as a side effect
- `snapshot()` resets change tracking and returns whether changes occurred
### StableSidemap
```typescript
class StableSidemap {
map: Map<IdentifierId, {isStable: boolean}> = new Map();
}
```
Tracks sources of stability (e.g., `useState()[1]` dispatch function). Forward data-flow analysis that:
- Records hook calls that return stable types
- Propagates stability through PropertyLoad and Destructure from stable containers
- Propagates through LoadLocal and StoreLocal
### ControlDominators
Uses post-dominator frontier analysis to determine which blocks are controlled by reactive branch conditions.
## Edge Cases
### Backward Reactivity Propagation via Mutable Aliasing
```javascript
const x = [];
const z = [x];
x.push(props.input);
return <div>{z}</div>;
```
Here `z` aliases `x` which is later mutated with reactive data. The disjoint set ensures `z` becomes reactive even though the mutation happens after its creation.
### Stable Types Are Not Reactive
```javascript
const [state, setState] = useState();
// setState is stable - not marked reactive despite coming from reactive hook
```
The `StableSidemap` tracks these and skips marking them reactive.
### Ternary with Stable Values Still Reactive
```javascript
props.cond ? setState1 : setState2
```
Even though both branches are stable types, the result depends on reactive control flow, so it cannot be marked non-reactive just based on type.
### Phi Nodes with Reactive Predecessors
When a phi's predecessor block is controlled by a reactive condition, the phi becomes reactive even if its operands are all non-reactive constants.
## TODOs
No explicit TODO comments are present in the source file. However, comments note:
- **ComputedLoads not handled for stability**: Only PropertyLoad propagates stability from containers, not ComputedLoad. The comment notes this is safe because stable containers have differently-typed elements, but ComputedLoad handling could be added.
## Example
### Fixture: `reactive-dependency-fixpoint.js`
**Input:**
```javascript
function Component(props) {
let x = 0;
let y = 0;
while (x === 0) {
x = y;
y = props.value;
}
return [x];
}
```
**Before InferReactivePlaces:**
```
bb1 (loop):
store x$26:TPhi:TPhi: phi(bb0: read x$21:TPrimitive, bb3: read x$32:TPhi)
store y$30:TPhi:TPhi: phi(bb0: read y$24:TPrimitive, bb3: read y$37)
...
bb3 (block):
[12] mutate? $35 = LoadLocal read props$19
[13] mutate? $36 = PropertyLoad read $35.value
[14] mutate? $38 = StoreLocal Reassign mutate? y$37 = read $36
```
**After InferReactivePlaces:**
```
bb1 (loop):
store x$26:TPhi{reactive}:TPhi: phi(bb0: read x$21:TPrimitive, bb3: read x$32:TPhi{reactive})
store y$30:TPhi{reactive}:TPhi: phi(bb0: read y$24:TPrimitive, bb3: read y$37{reactive})
[6] mutate? $27:TPhi{reactive} = LoadLocal read x$26:TPhi{reactive}
...
bb3 (block):
[12] mutate? $35{reactive} = LoadLocal read props$19{reactive}
[13] mutate? $36{reactive} = PropertyLoad read $35{reactive}.value
[14] mutate? $38{reactive} = StoreLocal Reassign mutate? y$37{reactive} = read $36{reactive}
```
**Key observations:**
- `props$19` is marked `{reactive}` as a function parameter
- The reactivity propagates through the loop:
- First iteration: `y$37` becomes reactive from `props.value`
- Second iteration: `x$32` becomes reactive from `y$30` (which is reactive via the phi from `y$37`)
- The phi nodes `x$26` and `y$30` become reactive because their bb3 operands are reactive
- The fixpoint algorithm handles this backward propagation through the loop correctly
- The final output `$40` is reactive, so the array `[x]` will be memoized with `x` as a dependency

View File

@@ -0,0 +1,176 @@
# inferReactiveScopeVariables
## File
`src/ReactiveScopes/InferReactiveScopeVariables.ts`
## Purpose
This is the **1st of 4 passes** that determine how to break a React function into discrete reactive scopes (independently memoizable units of code). Its specific responsibilities are:
1. **Identify operands that mutate together** - Variables that are mutated in the same instruction must be placed in the same reactive scope
2. **Assign a unique ReactiveScope to each group** - Each disjoint set of co-mutating identifiers gets assigned a unique ScopeId
3. **Compute the mutable range** - The scope's range is computed as the union of all member identifiers' mutable ranges
The pass does NOT determine which instructions compute each scope, only which variables belong together.
## Input Invariants
- `InferMutationAliasingEffects` has run - Effects describe mutations, captures, and aliasing
- `InferMutationAliasingRanges` has run - Each identifier has a valid `mutableRange` property
- `InferReactivePlaces` has run - Places are marked as reactive or not
- `RewriteInstructionKindsBasedOnReassignment` has run - Let/Const properly determined
- All instructions have been numbered with valid `InstructionId` values
- Phi nodes are properly constructed at block join points
## Output Guarantees
- Each identifier that is part of a mutable group has its `identifier.scope` property set to a `ReactiveScope` object
- All identifiers in the same scope share the same `ReactiveScope` reference
- The scope's `range` is the union (min start, max end) of all member mutable ranges
- The scope's `range` is validated to be within [1, maxInstruction+1]
- Identifiers that only have single-instruction lifetimes (read once) may not be assigned to a scope unless they allocate
## Algorithm
### Phase 1: Find Disjoint Mutable Values (`findDisjointMutableValues`)
Uses a Union-Find (Disjoint Set) data structure to group identifiers that mutate together:
1. **Handle Phi Nodes**: For each phi in each block:
- If the phi's result is mutated after creation (mutableRange.end > first instruction in block), union the phi with all its operands
- This ensures values that flow through control flow and are later mutated are grouped together
2. **Handle Instructions**: For each instruction:
- Collect mutable operands based on instruction type:
- If lvalue has extended mutable range OR instruction may allocate, include lvalue
- For StoreLocal/StoreContext: Include lvalue if it has extended mutable range, include value if mutable
- For Destructure: Include each pattern operand with extended range, include source if mutable
- For MethodCall: Include all mutable operands plus the computed property (to keep method resolution in same scope)
- For other instructions: Include all mutable operands
- Exclude global variables (mutableRange.start === 0) since they cannot be recreated
- Union all collected operands together
### Phase 2: Assign Scopes
1. Iterate over all identifiers in the disjoint set using `forEach(item, groupIdentifier)`
2. For each unique group, create a new ReactiveScope:
- Generate a unique ScopeId from the environment
- Initialize range from the first member's mutableRange
- Set up empty dependencies, declarations, reassignments sets
3. For subsequent members of the same group:
- Expand the scope's range to encompass the member's mutableRange
- Merge source locations
4. Assign the scope to each identifier: `identifier.scope = scope`
5. Update each identifier's mutableRange to match the scope's range
**Validation**: After scope assignment, validate that all scopes have valid ranges within [1, maxInstruction+1].
## Key Data Structures
### DisjointSet<Identifier>
A Union-Find data structure optimized for grouping items into disjoint sets:
```typescript
class DisjointSet<T> {
#entries: Map<T, T>; // Maps each item to its parent (root points to self)
union(items: Array<T>): void; // Merge items into one set
find(item: T): T | null; // Find the root of item's set (with path compression)
forEach(fn: (item, group) => void): void; // Iterate all items with their group root
}
```
Path compression is used during `find()` to flatten the tree structure, improving subsequent lookup performance.
### ReactiveScope
```typescript
type ReactiveScope = {
id: ScopeId;
range: MutableRange; // [start, end) instruction range
dependencies: Set<ReactiveScopeDependency>; // Inputs (populated later)
declarations: Map<IdentifierId, ReactiveScopeDeclaration>; // Outputs (populated later)
reassignments: Set<Identifier>; // Reassigned variables (populated later)
earlyReturnValue: {...} | null; // For scopes with early returns
merged: Set<ScopeId>; // IDs of scopes merged into this one
loc: SourceLocation;
};
```
## Edge Cases
### Global Variables
Excluded from scopes (mutableRange.start === 0) since they cannot be recreated during memoization.
### Phi Nodes After Mutation
When a phi's result is mutated after the join point, all phi operands must be in the same scope to ensure the mutation can be recomputed correctly.
### MethodCall Property Resolution
The computed property load for a method call is explicitly added to the same scope as the call itself.
### Allocating Instructions
Instructions that allocate (Array, Object, JSX, etc.) add their lvalue to the scope even if the lvalue has a single-instruction range.
### Single-Instruction Ranges
Values with range `[n, n+1)` (used exactly once) are only included if they allocate, otherwise they're just read.
### enableForest Config
When enabled, phi operands are unconditionally unioned with the phi result (even without mutation after the phi).
## TODOs
1. `// TODO: improve handling of module-scoped variables and globals` - The current approach excludes globals entirely, but a more nuanced handling could be beneficial.
2. Known issue with aliasing and mutable lifetimes (from header comments):
```javascript
let x = {};
let y = [];
x.y = y; // RHS is not considered mutable here bc not further mutation
mutate(x); // bc y is aliased here, it should still be considered mutable above
```
This suggests the pass may miss some co-mutation relationships when aliasing is involved.
## Example
### Fixture: `reactive-scope-grouping.js`
**Input:**
```javascript
function foo() {
let x = {};
let y = [];
let z = {};
y.push(z); // y and z co-mutate (z captured into y)
x.y = y; // x and y co-mutate (y captured into x)
return x;
}
```
**After InferReactiveScopeVariables:**
```
[1] mutate? $19_@0[1:14] = Object { } // x's initial object, scope @0
[2] store $21_@0[1:14] = StoreLocal x // x in scope @0
[3] mutate? $22_@1[3:11] = Array [] // y's array, scope @1
[4] store $24_@1[3:11] = StoreLocal y // y in scope @1
[5] mutate? $25_@2 = Object { } // z's object, scope @2
[10] MethodCall y.push(z) // Mutates y, captures z
[13] PropertyStore x.y = y // Mutates x, captures y
```
The `y.push(z)` joins y and z into scope @1, and `x.y = y` joins x and y into scope @0. Because y is now in @0, and z was captured into y, ultimately x, y, and z all end up in the same scope @0.
**Compiled Output:**
```javascript
function foo() {
const $ = _c(1);
let x;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
x = {};
const y = [];
const z = {};
y.push(z);
x.y = y;
$[0] = x;
} else {
x = $[0];
}
return x;
}
```
All three objects (x, y, z) are created within the same memoization block because they co-mutate and could potentially alias each other.

View File

@@ -0,0 +1,151 @@
# rewriteInstructionKindsBasedOnReassignment
## File
`src/SSA/RewriteInstructionKindsBasedOnReassignment.ts`
## Purpose
Rewrites the `InstructionKind` of variable declaration and assignment instructions to correctly reflect whether variables should be declared as `const` or `let` in the final output. It determines this based on whether a variable is subsequently reassigned after its initial declaration.
The key insight is that this pass runs **after dead code elimination (DCE)**, so a variable that was originally declared with `let` in the source (because it was reassigned) may be converted to `const` if the reassignment was removed by DCE. However, variables originally declared as `const` cannot become `let`.
## Input Invariants
- SSA form: Each identifier has a unique `IdentifierId` and `DeclarationId`
- Dead code elimination has run: Unused assignments have been removed
- Mutation/aliasing inference complete: Runs after `InferMutationAliasingRanges` and `InferReactivePlaces` in the main pipeline
- All instruction kinds are initially set (typically `Let` for variables that may be reassigned)
## Output Guarantees
- **First declaration gets `Const` or `Let`**: The first `StoreLocal` for a named variable is marked as:
- `InstructionKind.Const` if the variable is never reassigned after
- `InstructionKind.Let` if the variable has subsequent reassignments
- **Reassignments marked as `Reassign`**: Any subsequent `StoreLocal` to the same `DeclarationId` is marked as `InstructionKind.Reassign`
- **Destructure consistency**: All places in a destructuring pattern must have consistent kinds (all Const or all Reassign)
- **Update operations trigger Let**: `PrefixUpdate` and `PostfixUpdate` operations (like `++x` or `x--`) mark the original declaration as `Let`
## Algorithm
1. **Initialize declarations map**: Create a `Map<DeclarationId, LValue | LValuePattern>` to track declared variables.
2. **Seed with parameters and context**: Add all named function parameters and captured context variables to the map with kind `Let` (since they're already "declared" outside the function body).
3. **Process blocks in order**: Iterate through all blocks and instructions:
- **DeclareLocal**: Record the declaration in the map (invariant: must not already exist)
- **StoreLocal**:
- If not in map: This is the first store, add to map with `kind = Const`
- If already in map: This is a reassignment. Update original declaration to `Let`, set current instruction to `Reassign`
- **Destructure**:
- For each operand in the pattern, check if it's already declared
- All operands must be consistent (all new declarations OR all reassignments)
- Set pattern kind to `Const` for new declarations, `Reassign` for existing ones
- **PrefixUpdate / PostfixUpdate**: Look up the declaration and mark it as `Let` (these always imply reassignment)
## Key Data Structures
```typescript
// Main tracking structure
const declarations = new Map<DeclarationId, LValue | LValuePattern>();
// InstructionKind enum (from HIR.ts)
enum InstructionKind {
Const = 'Const', // const declaration
Let = 'Let', // let declaration
Reassign = 'Reassign', // reassignment to existing binding
Catch = 'Catch', // catch clause binding
HoistedLet = 'HoistedLet', // hoisted let
HoistedConst = 'HoistedConst', // hoisted const
HoistedFunction = 'HoistedFunction', // hoisted function
Function = 'Function', // function declaration
}
```
## Edge Cases
### DCE Removes Reassignment
A `let x = 0; x = 1;` where `x = 1` is unused becomes `const x = 0;` after DCE.
### Destructuring with Mixed Operands
The invariant checks ensure all operands in a destructure pattern are either all new declarations or all reassignments. Mixed cases cause a compiler error.
### Value Blocks with DCE
There's a TODO for handling reassignment in value blocks where the original declaration was removed by DCE.
### Parameters and Context Variables
These are pre-seeded as `Let` in the declarations map since they're conceptually "declared" at function entry.
### Update Expressions
`++x` and `x--` always mark the variable as `Let`, even if used inline.
## TODOs
```typescript
CompilerError.invariant(block.kind !== 'value', {
reason: `TODO: Handle reassignment in a value block where the original
declaration was removed by dead code elimination (DCE)`,
...
});
```
This indicates an edge case where a destructuring reassignment occurs in a value block but the original declaration was eliminated by DCE. This is currently an invariant violation rather than handled gracefully.
## Example
### Fixture: `reassignment.js`
**Input Source:**
```javascript
function Component(props) {
let x = [];
x.push(props.p0);
let y = x;
x = [];
let _ = <Component x={x} />;
y.push(props.p1);
return <Component x={x} y={y} />;
}
```
**Before Pass (InferReactivePlaces output):**
```
[2] StoreLocal Let x$32 = $31 // x is initially marked Let
[9] StoreLocal Let y$40 = $39 // y is initially marked Let
[11] StoreLocal Reassign x$43 = $42 // reassignment already marked
```
**After Pass:**
```
[2] StoreLocal Let x$32 = $31 // x stays Let (has reassignment at line 11)
[9] StoreLocal Const y$40 = $39 // y becomes Const (never reassigned)
[11] StoreLocal Reassign x$43 = $42 // stays Reassign
```
**Final Generated Code:**
```javascript
function Component(props) {
const $ = _c(4);
let t0;
if ($[0] !== props.p0 || $[1] !== props.p1) {
let x = []; // let because reassigned
x.push(props.p0);
const y = x; // const because never reassigned
// ... x = t1; (reassignment)
y.push(props.p1);
t0 = <Component x={x} y={y} />;
// ...
}
return t0;
}
```
The pass correctly identified that `x` needs `let` (since it's reassigned on line 6 of the source) while `y` can use `const` (it's never reassigned after initialization).
## Where This Pass is Called
1. **Main Pipeline** (`src/Entrypoint/Pipeline.ts:322`): Called after `InferReactivePlaces` and before `InferReactiveScopeVariables`.
2. **AnalyseFunctions** (`src/Inference/AnalyseFunctions.ts:58`): Called when lowering inner function expressions as part of the function analysis phase.

View File

@@ -0,0 +1,131 @@
# alignMethodCallScopes
## File
`src/ReactiveScopes/AlignMethodCallScopes.ts`
## Purpose
Ensures that `MethodCall` instructions and their associated `PropertyLoad` instructions (which load the method being called) have consistent scope assignments. The pass enforces one of two invariants:
1. Both the MethodCall lvalue and the property have the **same** reactive scope
2. **Neither** has a reactive scope
This alignment is critical because the PropertyLoad and MethodCall are semantically a single operation (`receiver.method(args)`) and must be memoized together as a unit. If they had different scopes, the generated code would incorrectly try to memoize the property load separately from the method call, which could break correctness.
## Input Invariants
- The function has been converted to HIR form
- `inferReactiveScopeVariables` has already run, assigning initial reactive scopes to identifiers based on mutation analysis
- Each instruction's lvalue has an `identifier.scope` that is either a `ReactiveScope` or `null`
- For `MethodCall` instructions, the `value.property` field contains a `Place` referencing the loaded method
## Output Guarantees
After this pass runs:
- For every `MethodCall` instruction in the function:
- If the lvalue has a scope AND the property has a scope, they point to the **same merged scope**
- If only the lvalue has a scope, the property's scope is set to match the lvalue's scope
- If only the property has a scope, the property's scope is set to `null` (so neither has a scope)
- Merged scopes have their `range` extended to cover the union of the original scopes' ranges
- Nested functions (FunctionExpression, ObjectMethod) are recursively processed
## Algorithm
### Phase 1: Collect Scope Relationships
```
For each instruction in all blocks:
If instruction is a MethodCall:
lvalueScope = instruction.lvalue.identifier.scope
propertyScope = instruction.value.property.identifier.scope
If both have scopes:
Record that these scopes should be merged (using DisjointSet.union)
Else if only lvalue has scope:
Record that property should be assigned to lvalueScope
Else if only property has scope:
Record that property should be assigned to null (no scope)
If instruction is FunctionExpression or ObjectMethod:
Recursively process the nested function
```
### Phase 2: Merge Scopes
```
For each merged scope group:
Pick a "root" scope
Extend root's range to cover all merged scopes:
root.range.start = min(all scope start points)
root.range.end = max(all scope end points)
```
### Phase 3: Apply Changes
```
For each instruction:
If lvalue was recorded for remapping:
Set identifier.scope to the mapped value
Else if identifier has a scope that was merged:
Set identifier.scope to the merged root scope
```
## Key Data Structures
1. **`scopeMapping: Map<IdentifierId, ReactiveScope | null>`**
- Maps property identifier IDs to their new scope assignment
- Value of `null` means the scope should be removed
2. **`mergedScopes: DisjointSet<ReactiveScope>`**
- Union-find data structure tracking scopes that need to be merged
- Used when both MethodCall and property have different scopes
3. **`ReactiveScope`** (from HIR)
- Contains `range: { start: InstructionId, end: InstructionId }`
- The range defines which instructions are part of the scope
## Edge Cases
### Both Have the Same Scope Already
No action needed (implicit in the logic).
### Nested Functions
The pass recursively processes `FunctionExpression` and `ObjectMethod` instructions to handle closures.
### Multiple MethodCalls Sharing Scopes
The DisjointSet handles transitive merging - if A merges with B, and B merges with C, all three end up in the same scope.
### Property Without Scope, MethodCall Without Scope
No action needed (both already aligned at `null`).
## TODOs
There are no explicit TODO comments in the source code.
## Example
### Fixture: `alias-capture-in-method-receiver.js`
**Source code:**
```javascript
function Component() {
let a = someObj();
let x = [];
x.push(a);
return [x, a];
}
```
**Before AlignMethodCallScopes:**
```
[7] store $24_@1[4:10]:TFunction = PropertyLoad capture $23_@1.push
[9] mutate? $26:TPrimitive = MethodCall store $23_@1.read $24_@1(capture $25)
```
- PropertyLoad result `$24_@1` has scope `@1`
- MethodCall result `$26` has no scope (`null`)
**After AlignMethodCallScopes:**
```
[7] store $24[4:10]:TFunction = PropertyLoad capture $23_@1.push
[9] mutate? $26:TPrimitive = MethodCall store $23_@1.read $24(capture $25)
```
- PropertyLoad result `$24` now has **no scope** (the `_@1` suffix removed)
- MethodCall result `$26` still has no scope
**Why this matters:**
Without this alignment, later passes might try to memoize the `.push` property load separately from the actual `push()` call. This would be incorrect because:
1. Reading a method from an object and calling it are semantically one operation
2. The property load's value (the bound method) is only valid immediately when called on the same receiver
3. Separate memoization could lead to stale method references or incorrect this-binding

View File

@@ -0,0 +1,128 @@
# alignObjectMethodScopes
## File
`src/ReactiveScopes/AlignObjectMethodScopes.ts`
## Purpose
Ensures that object method values and their enclosing object expressions share the same reactive scope. This is critical for code generation because JavaScript requires object method definitions to be inlined within their containing object literals. If the object method and object expression were in different reactive scopes (which map to different memoization blocks), the generated code would be invalid since you cannot reference an object method defined in one block from an object literal in a different block.
From the file's documentation:
> "To produce a well-formed JS program in Codegen, object methods and object expressions must be in the same ReactiveBlock as object method definitions must be inlined."
## Input Invariants
- Reactive scopes have been inferred: This pass runs after `InferReactiveScopeVariables`
- ObjectMethod and ObjectExpression have non-null scopes: The pass asserts this with an invariant check
- Scopes are disjoint across functions: The pass assumes that scopes do not overlap between parent and nested functions
## Output Guarantees
- ObjectMethod and ObjectExpression share the same scope: Any ObjectMethod used as a property in an ObjectExpression will have its scope merged with the ObjectExpression's scope
- Merged scope covers both ranges: The resulting merged scope's range is expanded to cover the minimum start and maximum end of all merged scopes
- All identifiers are repointed: All identifiers whose scopes were merged are updated to point to the canonical root scope
- Inner functions are also processed: The pass recursively handles nested ObjectMethod and FunctionExpression values
## Algorithm
### Phase 1: Find Scopes to Merge (`findScopesToMerge`)
1. Iterate through all blocks and instructions in the function
2. Track all ObjectMethod declarations in a set by their lvalue identifier
3. When encountering an ObjectExpression, check each operand:
- If an operand's identifier was previously recorded as an ObjectMethod declaration
- Get the scope of both the ObjectMethod operand and the ObjectExpression lvalue
- Assert both scopes are non-null
- Union these two scopes together in a DisjointSet data structure
### Phase 2: Merge and Repoint Scopes (`alignObjectMethodScopes`)
1. Recursively process inner functions first (ObjectMethod and FunctionExpression values)
2. Canonicalize the DisjointSet to get a mapping from each scope to its root
3. **Step 1 - Merge ranges**: For each scope that maps to a different root:
- Expand the root's range to encompass both the original range and the merged scope's range
- `root.range.start = min(scope.range.start, root.range.start)`
- `root.range.end = max(scope.range.end, root.range.end)`
4. **Step 2 - Repoint identifiers**: For each instruction's lvalue:
- If the identifier has a scope that was merged
- Update the identifier's scope reference to point to the canonical root
## Key Data Structures
1. **DisjointSet<ReactiveScope>** - A union-find data structure that tracks which scopes should be merged together. Uses path compression for efficient `find()` operations.
2. **Set<Identifier>** - Tracks which identifiers are ObjectMethod declarations, used to identify when an ObjectExpression operand is an object method.
3. **ReactiveScope** - Contains:
- `id: ScopeId` - Unique identifier
- `range: MutableRange` - Start and end instruction IDs
- `dependencies` - Inputs to the scope
- `declarations` - Values produced by the scope
4. **MutableRange** - Has `start` and `end` InstructionId fields that define the scope's extent.
## Edge Cases
### Nested Object Methods
When an object method itself contains another object with methods, the pass recursively processes inner functions first before handling the outer function's scopes.
### Multiple Object Methods in Same Object
If an object has multiple method properties, all their scopes will be merged with the object's scope through the DisjointSet.
### Object Methods in Conditional Expressions
Object methods inside ternary expressions still need scope alignment to ensure the method and its containing object are in the same reactive block.
### Method Call After Object Creation
The pass works in conjunction with `AlignMethodCallScopes` (which runs immediately before) to ensure that method calls on objects with object methods are also properly scoped.
## TODOs
None explicitly marked in the source file.
## Example
### Fixture: `object-method-shorthand.js`
**Input:**
```javascript
function Component() {
let obj = {
method() {
return 1;
},
};
return obj.method();
}
```
**Before AlignObjectMethodScopes:**
```
InferReactiveScopeVariables:
[1] mutate? $12_@0:TObjectMethod = ObjectMethod ... // scope @0
[2] mutate? $14_@1[2:7]:TObject = Object { method: ... } // scope @1 (range 2:7)
```
The ObjectMethod `$12` is in scope `@0` while the ObjectExpression `$14` is in scope `@1` with range `[2:7]`.
**After AlignObjectMethodScopes:**
```
AlignObjectMethodScopes:
[1] mutate? $12_@0[1:7]:TObjectMethod = ObjectMethod ... // scope @0, range now 1:7
[2] mutate? $14_@0[1:7]:TObject = Object { method: ... } // also scope @0, range 1:7
```
Both identifiers are in the same scope `@0`, and the scope's range has been expanded to `[1:7]` to cover both instructions.
**Final Generated Code:**
```javascript
function Component() {
const $ = _c(1);
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
const obj = {
method() {
return 1;
},
};
t0 = obj.method();
$[0] = t0;
} else {
t0 = $[0];
}
return t0;
}
```
The object literal with its method and the subsequent method call are all inside the same memoization block, producing valid JavaScript where the method definition is inlined within the object literal.

View File

@@ -0,0 +1,177 @@
# alignReactiveScopesToBlockScopesHIR
## File
`src/ReactiveScopes/AlignReactiveScopesToBlockScopesHIR.ts`
## Purpose
This is the **2nd of 4 passes** that determine how to break a function into discrete reactive scopes (independently memoizable units of code). The pass aligns reactive scope boundaries to control flow (block scope) boundaries.
The problem it solves: Prior inference passes assign reactive scopes to operands based on mutation ranges at arbitrary instruction points in the control-flow graph. However, to generate memoization blocks around instructions, scopes must be aligned to block-scope boundaries -- you cannot memoize half of a loop or half of an if-block.
**Example from the source code comments:**
```javascript
function foo(cond, a) {
// original scope end
// expanded scope end
const x = []; | |
if (cond) { | |
... | |
x.push(a); <--- original scope ended here
... |
} <--- scope must extend to here
}
```
## Input Invariants
- `InferReactiveScopeVariables` has run: Each identifier has been assigned a `ReactiveScope` with a `range` (start/end instruction IDs) based on mutation analysis
- The HIR is in SSA form: Blocks have unique IDs, instructions have unique IDs, and control flow is represented with basic blocks
- Each block has a terminal with possible successors and fallthroughs
- Each scope has a mutable range `{start: InstructionId, end: InstructionId}` indicating when the scope is active
## Output Guarantees
- **Scopes end at valid block boundaries**: A reactive scope may only end at the same block scope level as it began. The scope's `range.end` is updated to the first instruction of the fallthrough block after any control flow structure that the scope overlaps
- **Scopes start at valid block boundaries**: For labeled breaks (gotos to a label), scopes that extend beyond the goto have their `range.start` extended back to include the label
- **Value blocks (ternary, logical, optional) are handled specially**: Scopes inside value blocks are extended to align with the outer block scope's instruction range
## Algorithm
The pass performs a single forward traversal over all blocks:
### 1. Tracking Active Scopes
- Maintains `activeScopes: Set<ReactiveScope>` - scopes whose range overlaps the current block
- Maintains `activeBlockFallthroughRanges: Array<{range, fallthrough}>` - stack of pending block-fallthrough ranges
### 2. Per-Block Processing
For each block:
- Prune `activeScopes` to only those that extend past the current block's start
- If this block is a fallthrough target, pop the range from the stack and extend all active scopes' start to the range start
### 3. Recording Places
For each instruction lvalue and operand:
- If the place has a scope, add it to `activeScopes`
- If inside a value block, extend the scope's range to match the value block's outer range
### 4. Handling Block Fallthroughs
When a terminal has a fallthrough (not a simple branch):
- Extend all active scopes whose `range.end > terminal.id` to at least the first instruction of the fallthrough block
- Push the fallthrough range onto the stack for future scopes
### 5. Handling Labeled Breaks (Goto)
When encountering a goto to a label (not the natural fallthrough):
- Find the corresponding fallthrough range on the stack
- Extend all active scopes to span from the label start to its fallthrough end
### 6. Value Block Handling
For ternary, logical, and optional terminals:
- Create `ValueBlockNode` to track the outer block's instruction range
- Scopes inside value blocks inherit this range, ensuring they align to the outer block scope
## Key Data Structures
```typescript
type ValueBlockNode = {
kind: 'node';
id: InstructionId;
valueRange: MutableRange; // Range of outer block scope
children: Array<ValueBlockNode | ReactiveScopeNode>;
};
type ReactiveScopeNode = {
kind: 'scope';
id: InstructionId;
scope: ReactiveScope;
};
// Tracked during traversal:
activeBlockFallthroughRanges: Array<{
range: InstructionRange;
fallthrough: BlockId;
}>;
activeScopes: Set<ReactiveScope>;
valueBlockNodes: Map<BlockId, ValueBlockNode>;
```
## Edge Cases
### Labeled Breaks
When a `goto` jumps to a label (not the natural fallthrough), scopes must be extended to include the entire labeled block range, preventing the break from jumping out of the scope.
### Value Blocks (Ternary/Logical/Optional)
These create nested "value" contexts. Scopes inside must be aligned to the outer block scope's boundaries, not the value block's boundaries.
### Nested Control Flow
Deeply nested if-statements require the scope to be extended through all levels back to the outermost block where the scope started.
### do-while and try/catch
The terminal's successor might be a block (not value block), which is handled specially.
## TODOs
1. `// TODO: consider pruning activeScopes per instruction` - Currently, `activeScopes` is only pruned at block start points. Some scopes may no longer be active by the time a goto is encountered.
2. `// TODO: add a variant of eachTerminalSuccessor() that visits _all_ successors, not just those that are direct successors for normal control-flow ordering.` - The current implementation uses `mapTerminalSuccessors` which may not visit all successors in all cases.
## Example
### Fixture: `extend-scopes-if.js`
**Input:**
```javascript
function foo(a, b, c) {
let x = [];
if (a) {
if (b) {
if (c) {
x.push(0); // Mutation of x ends here (instruction 12-13)
}
}
}
if (x.length) { // instruction 16
return x;
}
return null;
}
```
**Before AlignReactiveScopesToBlockScopesHIR:**
```
x$23_@0[1:13] // Scope range 1-13
```
The scope for `x` ends at instruction 13 (inside the innermost if block).
**After AlignReactiveScopesToBlockScopesHIR:**
```
x$23_@0[1:16] // Scope range extended to 1-16
```
The scope is extended to instruction 16 (the first instruction after all the nested if-blocks), aligning to the block scope boundary.
**Generated Code:**
```javascript
function foo(a, b, c) {
const $ = _c(4);
let x;
if ($[0] !== a || $[1] !== b || $[2] !== c) {
x = [];
if (a) {
if (b) {
if (c) {
x.push(0);
}
}
}
// Scope ends here, after ALL the if-blocks
$[0] = a;
$[1] = b;
$[2] = c;
$[3] = x;
} else {
x = $[3];
}
// Code outside the scope
if (x.length) {
return x;
}
return null;
}
```
The memoization block correctly wraps the entire nested if-structure, not just part of it.

View File

@@ -0,0 +1,134 @@
# mergeOverlappingReactiveScopesHIR
## File
`src/HIR/MergeOverlappingReactiveScopesHIR.ts`
## Purpose
This pass ensures that reactive scope ranges form valid, non-overlapping blocks in the output JavaScript program. It merges reactive scopes that would otherwise be inconsistent with each other due to:
1. **Overlapping ranges**: Scopes whose instruction ranges partially overlap (not disjoint and not nested) must be merged because the compiler cannot produce valid `if-else` memo blocks for overlapping scopes.
2. **Cross-scope mutations**: When an instruction within one scope mutates a value belonging to a different (outer) scope, those scopes must be merged to maintain correctness.
The pass guarantees that after execution, any two reactive scopes are either:
- Entirely disjoint (no common instructions)
- Properly nested (one scope is completely contained within the other)
## Input Invariants
- Reactive scope variables have been inferred (`InferReactiveScopeVariables` pass has run)
- Scopes have been aligned to block scopes (`AlignReactiveScopesToBlockScopesHIR` pass has run)
- Each `Place` may have an associated `ReactiveScope` with a `range` (start/end instruction IDs)
- Scopes may still have overlapping ranges or contain instructions that mutate outer scopes
## Output Guarantees
- **No overlapping scopes**: All reactive scopes either are disjoint or properly nested
- **Consistent mutation boundaries**: Instructions only mutate their "active" scope (the innermost containing scope)
- **Merged scope ranges**: Merged scopes have their ranges extended to cover the union of all constituent scopes
- **Updated references**: All `Place` references have their `identifier.scope` updated to point to the merged scope
## Algorithm
### Phase 1: Collect Scope Information (`collectScopeInfo`)
- Iterates through all instructions and terminals in the function
- Records for each `Place`:
- The scope it belongs to (`placeScopes` map)
- When scopes start and end (`scopeStarts` and `scopeEnds` arrays, sorted in descending order by ID)
- Only records scopes with non-empty ranges (`range.start !== range.end`)
### Phase 2: Detect Overlapping Scopes (`getOverlappingReactiveScopes`)
Uses a stack-based traversal to track "active" scopes at each instruction:
1. **For each instruction/terminal**:
- **Handle scope endings**: Pop completed scopes from the active stack. If a scope ends while other scopes that started later are still active (detected by finding the scope is not at the top of the stack), those scopes overlap and must be merged via `DisjointSet.union()`.
- **Handle scope starts**: Push new scopes onto the active stack (sorted by end time descending so earlier-ending scopes are at the top). Merge any scopes that have identical start/end ranges.
- **Handle mutations**: For each operand/lvalue, if it:
- Has an associated scope
- Is mutable at the current instruction
- The scope is active but not at the top of the stack (i.e., an outer scope)
Then merge all scopes from the mutated outer scope to the top of the stack.
2. **Special case**: Primitive operands in `FunctionExpression` and `ObjectMethod` are skipped.
### Phase 3: Merge Scopes and Rewrite References
1. For each scope in the disjoint set, compute the merged range as the union (min start, max end)
2. Update all `Place.identifier.scope` references to point to the merged "group" scope
## Key Data Structures
### ScopeInfo
```typescript
type ScopeInfo = {
scopeStarts: Array<{id: InstructionId; scopes: Set<ReactiveScope>}>;
scopeEnds: Array<{id: InstructionId; scopes: Set<ReactiveScope>}>;
placeScopes: Map<Place, ReactiveScope>;
};
```
### TraversalState
```typescript
type TraversalState = {
joined: DisjointSet<ReactiveScope>; // Union-find for merged scopes
activeScopes: Array<ReactiveScope>; // Stack of currently active scopes
};
```
### DisjointSet<ReactiveScope>
A union-find data structure that tracks which scopes should be merged into the same group.
## Edge Cases
### Identical Scope Ranges
When multiple scopes have the exact same start and end, they are automatically merged since they would produce the same reactive block.
### Empty Scopes
Scopes where `range.start === range.end` are skipped entirely.
### Primitive Captures in Functions
When a `FunctionExpression` or `ObjectMethod` captures a primitive operand, it's excluded from scope merging analysis.
### JSX Single-Instruction Scopes
The comment in the code notes this isn't perfect - mutating scopes may get merged with JSX single-instruction scopes.
### Non-Mutating Captures
The pass records both mutating and non-mutating scopes to handle cases where still-mutating values are aliased by inner scopes.
## TODOs
From the comments in the source file, the design constraints arise from the current compiler output design:
- **Instruction ordering is preserved**: If reordering were allowed, disjoint ranges could be produced by reordering mutating instructions
- **One if-else block per scope**: The current design doesn't allow composing a reactive scope from disconnected instruction ranges
## Example
### Fixture: `overlapping-scopes-interleaved.js`
**Input Code:**
```javascript
function foo(a, b) {
let x = [];
let y = [];
x.push(a);
y.push(b);
}
```
**Before MergeOverlappingReactiveScopesHIR:**
```
[1] $20_@0[1:9] = Array [] // x belongs to scope @0, range [1:9]
[2] x$21_@0[1:9] = StoreLocal...
[3] $23_@1[3:13] = Array [] // y belongs to scope @1, range [3:13]
[4] y$24_@1[3:13] = StoreLocal...
```
Scopes @0 [1:9] and @1 [3:13] overlap: @0 starts at 1, @1 starts at 3, @0 ends at 9, @1 ends at 13. This is invalid.
**After MergeOverlappingReactiveScopesHIR:**
```
[1] $20_@0[1:13] = Array [] // Merged scope @0, range [1:13]
[2] x$21_@0[1:13] = StoreLocal...
[3] $23_@0[1:13] = Array [] // Now also scope @0
[4] y$24_@0[1:13] = StoreLocal...
```
Both `x` and `y` now belong to the same merged scope @0 with range [1:13], producing a single `if-else` memo block in the output.

View File

@@ -0,0 +1,161 @@
# buildReactiveScopeTerminalsHIR
## File
`src/HIR/BuildReactiveScopeTerminalsHIR.ts`
## Purpose
This pass transforms the HIR by inserting `ReactiveScopeTerminal` nodes to explicitly demarcate the boundaries of reactive scopes within the control flow graph. It converts the implicit scope ranges (stored on identifiers as `identifier.scope.range`) into explicit control flow structure by:
1. Inserting a `scope` terminal at the **start** of each reactive scope
2. Inserting a `goto` terminal at the **end** of each reactive scope
3. Creating fallthrough blocks to properly connect the scopes to the rest of the CFG
This transformation makes scope boundaries first-class elements in the CFG, which is essential for later passes that generate the memoization code (the `if ($[n] !== dep)` checks).
## Input Invariants
- **Properly nested scopes and blocks**: The pass assumes `assertValidBlockNesting` has passed, meaning all program blocks and reactive scopes form a proper tree hierarchy
- **Aligned scope ranges**: Reactive scope ranges have been correctly aligned and merged by previous passes
- **Valid instruction IDs**: All instructions have sequential IDs that define the scope boundaries
- **Scopes attached to identifiers**: Reactive scopes are found by traversing all `Place` operands and collecting unique non-empty scopes
## Output Guarantees
- **Explicit scope terminals**: Each reactive scope is represented in the CFG as a `ReactiveScopeTerminal` with:
- `block` - The BlockId containing the scope's instructions
- `fallthrough` - The BlockId that executes after the scope
- **Proper block structure**: Original blocks are split at scope boundaries
- **Restored HIR invariants**: The pass restores RPO ordering, predecessor sets, instruction IDs, and scope/identifier ranges
- **Updated phi nodes**: Phi operands are repointed when their source blocks are split
## Algorithm
### Step 1: Collect Scope Rewrites
```
for each reactive scope (in range pre-order):
push StartScope rewrite at scope.range.start
push EndScope rewrite at scope.range.end
```
The `recursivelyTraverseItems` helper traverses scopes in pre-order (outer scopes before inner scopes).
### Step 2: Apply Rewrites by Splitting Blocks
```
reverse queuedRewrites (to pop in ascending instruction order)
for each block:
for each instruction (or terminal):
while there are rewrites <= current instruction ID:
split block at current index
insert scope terminal (for start) or goto terminal (for end)
emit final block segment with original terminal
```
### Step 3: Repoint Phi Nodes
When a block is split, its final segment gets a new BlockId. Phi operands that referenced the original block are updated to reference the new final block.
### Step 4: Restore HIR Invariants
- Recompute RPO (reverse post-order) block traversal
- Recalculate predecessor sets
- Renumber instruction IDs
- Fix scope and identifier ranges to match new instruction IDs
## Key Data Structures
### TerminalRewriteInfo
```typescript
type TerminalRewriteInfo =
| {
kind: 'StartScope';
blockId: BlockId; // New block for scope content
fallthroughId: BlockId; // Block after scope ends
instrId: InstructionId; // Where to insert
scope: ReactiveScope; // The scope being created
}
| {
kind: 'EndScope';
instrId: InstructionId; // Where to insert
fallthroughId: BlockId; // Same as corresponding StartScope
};
```
### RewriteContext
```typescript
type RewriteContext = {
source: BasicBlock; // Original block being split
instrSliceIdx: number; // Current slice start index
nextPreds: Set<BlockId>; // Predecessors for next emitted block
nextBlockId: BlockId; // BlockId for next emitted block
rewrites: Array<BasicBlock>; // Accumulated split blocks
};
```
### ScopeTraversalContext
```typescript
type ScopeTraversalContext = {
fallthroughs: Map<ScopeId, BlockId>; // Cache: scope -> its fallthrough block
rewrites: Array<TerminalRewriteInfo>;
env: Environment;
};
```
## Edge Cases
### Multiple Rewrites at Same Instruction ID
The while loop in Step 2 handles multiple scope start/ends at the same instruction ID.
### Nested Scopes
The pre-order traversal ensures outer scopes are processed before inner scopes, creating proper nesting in the CFG.
### Empty Blocks After Split
When a scope boundary falls at the start of a block, the split may create a block with no instructions (only a terminal).
### Control Flow Within Scopes
The pass preserves existing control flow (if/else, loops) within scopes; it only adds scope entry/exit points.
### Early Returns
When a return occurs within a scope, the scope terminal still has a fallthrough block, but that block may contain `Unreachable` terminal.
## TODOs
Line 283-284:
```typescript
// TODO make consistent instruction IDs instead of reusing
```
## Example
### Fixture: `reactive-scopes-if.js`
**Before BuildReactiveScopeTerminalsHIR:**
```
bb0 (block):
[1] $29_@0[1:22] = Array [] // x with scope @0 range [1:22]
[2] StoreLocal x$30_@0 = $29_@0
[3] $32 = LoadLocal a$26
[4] If ($32) then:bb2 else:bb3 fallthrough=bb1
bb2:
[5] $33_@1[5:11] = Array [] // y with scope @1 range [5:11]
...
```
**After BuildReactiveScopeTerminalsHIR:**
```
bb0 (block):
[1] Scope @0 [1:28] block=bb9 fallthrough=bb10 // <-- scope terminal inserted
bb9:
[2] $29_@0 = Array []
[3] StoreLocal x$30_@0 = $29_@0
[4] $32 = LoadLocal a$26
[5] If ($32) then:bb2 else:bb3 fallthrough=bb1
bb2:
[6] Scope @1 [6:14] block=bb11 fallthrough=bb12 // <-- nested scope terminal
bb11:
[7] $33_@1 = Array []
...
[13] Goto bb12 // <-- scope end goto
bb12:
...
bb1:
[27] Goto bb10 // <-- scope @0 end goto
bb10:
[28] $50 = LoadLocal x$30_@0
[29] Return $50
```
The key transformation is that scope boundaries become explicit control flow: a `Scope` terminal enters the scope content block, and a `Goto` terminal exits to the fallthrough block. This structure is later used to generate the memoization checks.

View File

@@ -0,0 +1,158 @@
# flattenReactiveLoopsHIR
## File
`src/ReactiveScopes/FlattenReactiveLoopsHIR.ts`
## Purpose
This pass **prunes reactive scopes that are nested inside loops** (for, for-in, for-of, while, do-while). The compiler does not yet support memoization within loops because:
1. Loop iterations would require reconciliation across runs (similar to how `key` is used in JSX for lists)
2. There is no way to identify values across iterations
3. The current approach is to memoize *around* the loop rather than *within* it
When a reactive scope is found inside a loop body, the pass converts its terminal from `scope` to `pruned-scope`. A `pruned-scope` terminal is later treated specially during codegen - its instructions are emitted inline without any memoization guards.
## Input Invariants
- The HIR has been through `buildReactiveScopeTerminalsHIR`, which creates `scope` terminal nodes for reactive scopes
- The HIR is in valid block form with proper terminal kinds
- The block ordering respects control flow (blocks are iterated in order, with loop fallthroughs appearing after loop bodies)
## Output Guarantees
- All `scope` terminals that appear inside any loop body are converted to `pruned-scope` terminals
- Scopes outside of loops remain unchanged as `scope` terminals
- The structure of blocks is preserved; only the terminal kind is mutated
- The `pruned-scope` terminal retains all the same fields as `scope` (block, fallthrough, scope, id, loc)
## Algorithm
The algorithm uses a **linear scan with a stack-based loop tracking** approach:
```
1. Initialize an empty array `activeLoops` to track which loop(s) we are currently inside
2. For each block in the function body (in order):
a. Remove the current block ID from activeLoops (if present)
- This happens when we reach a loop's fallthrough block, exiting the loop
b. Examine the block's terminal:
- If it's a loop terminal (do-while, for, for-in, for-of, while):
Push the loop's fallthrough block ID onto activeLoops
- If it's a scope terminal AND activeLoops is non-empty:
Convert the terminal to pruned-scope (keeping all other fields)
- All other terminal kinds are ignored
```
Key insight: The algorithm tracks when we "enter" a loop by pushing the fallthrough ID when encountering a loop terminal, and "exits" the loop when that fallthrough block is visited.
## Key Data Structures
### activeLoops: Array<BlockId>
A stack of block IDs representing loop fallthroughs. When non-empty, we are inside one or more nested loops.
### PrunedScopeTerminal
```typescript
export type PrunedScopeTerminal = {
kind: 'pruned-scope';
fallthrough: BlockId;
block: BlockId;
scope: ReactiveScope;
id: InstructionId;
loc: SourceLocation;
};
```
### retainWhere
Utility from utils.ts - an in-place array filter that removes elements not matching the predicate.
## Edge Cases
### Nested Loops
The algorithm handles nested loops correctly because `activeLoops` is an array that can contain multiple fallthrough IDs. A scope deep inside multiple nested loops will still be pruned.
### Scope Spanning the Loop
If a scope terminal appears before the loop terminal but its body contains the loop, it is NOT pruned because the scope terminal itself is not inside the loop.
### Multiple Loops in Sequence
When exiting one loop (reaching its fallthrough) and entering another, `activeLoops` correctly clears the first loop before potentially adding the second.
### Control Flow That Exits Loops (break/return)
The algorithm relies on block ordering and fallthrough IDs. Early exits via break/return don't affect the tracking since we track by fallthrough block ID.
## TODOs
No explicit TODOs in this file. However, the docstring mentions future improvements:
> "Eventually we may integrate more deeply into the runtime so that we can do a single level of reconciliation"
This suggests a potential future feature to support memoization within loops via runtime integration.
## Example
### Fixture: `repro-memoize-for-of-collection-when-loop-body-returns.js`
**Input:**
```javascript
function useHook(nodeID, condition) {
const graph = useContext(GraphContext);
const node = nodeID != null ? graph[nodeID] : null;
for (const key of Object.keys(node?.fields ?? {})) {
if (condition) {
return new Class(node.fields?.[field]); // <-- Scope @4 is here
}
}
return new Class(); // <-- Scope @5 is here (outside loop)
}
```
**Before FlattenReactiveLoopsHIR:**
```
[45] Scope scope @3 [45:72] ... block=bb35 fallthrough=bb36
bb35:
[46] ForOf init=bb6 test=bb7 loop=bb8 fallthrough=bb5
...
[66] Scope scope @4 [66:69] ... block=bb37 fallthrough=bb38 <-- Inside loop
...
[73] Scope scope @5 [73:76] ... block=bb39 fallthrough=bb40 <-- Outside loop
```
**After FlattenReactiveLoopsHIR:**
```
[45] Scope scope @3 [45:72] ... block=bb35 fallthrough=bb36 <-- Unchanged
...
[66] <pruned> Scope scope @4 [66:69] ... block=bb37 fallthrough=bb38 <-- PRUNED!
...
[73] Scope scope @5 [73:76] ... block=bb39 fallthrough=bb40 <-- Unchanged
```
**Final Codegen Result:**
```javascript
function useHook(nodeID, condition) {
const $ = _c(7);
// ... memoized Object.keys call (scope @2)
let t1;
if ($[2] !== condition || $[3] !== node || $[4] !== t0) {
// Scope @3 wraps the loop
t1 = Symbol.for("react.early_return_sentinel");
bb0: for (const key of t0) {
if (condition) {
t1 = new Class(node.fields?.[field]); // Scope @4 was PRUNED - no memoization
break bb0;
}
}
$[2] = condition;
$[3] = node;
$[4] = t0;
$[5] = t1;
} else {
t1 = $[5];
}
// ...
// Scope @5 - memoized (sentinel check)
if ($[6] === Symbol.for("react.memo_cache_sentinel")) {
t2 = new Class();
$[6] = t2;
}
return t2;
}
```
The `new Class(...)` inside the loop has no memoization guards because scope @4 was pruned. The `new Class()` outside the loop retains its memoization via scope @5.

View File

@@ -0,0 +1,143 @@
# flattenScopesWithHooksOrUseHIR
## File
`src/ReactiveScopes/FlattenScopesWithHooksOrUseHIR.ts`
## Purpose
This pass removes (flattens) reactive scopes that transitively contain hook calls or `use()` operator calls. The key insight is that:
1. **Hooks cannot be called conditionally** - wrapping them in a memoized scope would make them conditionally called based on whether the cache is valid
2. **The `use()` operator** - while it can be called conditionally in source code, React requires it to be called consistently if the component needs the returned value. Memoizing a scope containing `use()` would also make it conditionally called.
By running reactive scope inference first (agnostic of hooks), the compiler knows which values "construct together" in the same scope. The pass then removes ALL memoization for scopes containing hook/use calls to ensure they are always executed unconditionally.
## Input Invariants
- HIR must have reactive scope terminals already built (pass runs after `BuildReactiveScopeTerminalsHIR`)
- Blocks are visited in order (the pass iterates through `fn.body.blocks`)
- Scope terminals have a `block` (body of the scope) and `fallthrough` (block after the scope)
- Type inference has run so that `getHookKind()` and `isUseOperator()` can identify hooks and use() calls
## Output Guarantees
- All scopes that transitively contained a hook or `use()` call are either:
- Converted to `LabelTerminal` - if the scope body is trivial (just the hook call and a goto)
- Converted to `PrunedScopeTerminal` - if the scope body contains other instructions besides the hook call
- The `PrunedScopeTerminal` still tracks the original scope information for downstream passes but will not generate memoization code
- The control flow structure is preserved (same blocks, same fallthroughs)
## Algorithm
### Phase 1: Identify Scopes Containing Hook/Use Calls
1. Maintain a stack `activeScopes` of currently "open" reactive scopes
2. Iterate through all blocks in order
3. When entering a block:
- Remove any scopes from `activeScopes` whose fallthrough equals the current block (those scopes have ended)
4. For each instruction in the block:
- If it's a `CallExpression` or `MethodCall` and the callee is a hook or use operator:
- Add all currently active scopes to the `prune` list
- Clear `activeScopes` (these scopes are now marked for pruning)
5. If the block's terminal is a `scope`:
- Push it onto `activeScopes`
### Phase 2: Prune Identified Scopes
For each block ID in `prune`:
1. Get the scope terminal
2. Check if the scope body is trivial (single instruction + goto to fallthrough):
- If trivial: Convert to `LabelTerminal` (will be removed by `PruneUnusedLabels`)
- If non-trivial: Convert to `PrunedScopeTerminal` (preserves scope info but skips memoization)
## Key Data Structures
```typescript
// Stack tracking currently open scopes
activeScopes: Array<{block: BlockId; fallthrough: BlockId}>
// List of block IDs whose scope terminals should be pruned
prune: Array<BlockId>
// Terminal types used
LabelTerminal: {kind: 'label', block, fallthrough, id, loc}
PrunedScopeTerminal: {kind: 'pruned-scope', block, fallthrough, scope, id, loc}
ReactiveScopeTerminal: {kind: 'scope', block, fallthrough, scope, id, loc}
```
## Edge Cases
### Nested Scopes
When a hook is found in an inner scope, ALL enclosing scopes are also pruned (the hook call would become conditional if any outer scope were memoized).
### Method Call Hooks
Handles both `CallExpression` (e.g., `useHook(...)`) and `MethodCall` (e.g., `obj.useHook(...)`).
### Trivial Hook-Only Scopes
If a scope exists just for a hook call (single instruction + goto), it's converted to a `LabelTerminal` which is a simpler structure that gets cleaned up by later passes.
### Multiple Hooks in Sequence
Once the first hook is encountered, all active scopes are pruned and cleared, so subsequent hooks in outer scopes still work correctly.
## TODOs
None explicitly marked in the source file.
## Example
### Fixture: `nested-scopes-hook-call.js`
**Input:**
```javascript
function component(props) {
let x = [];
let y = [];
y.push(useHook(props.foo));
x.push(y);
return x;
}
```
**Before FlattenScopesWithHooksOrUseHIR:**
```
bb0:
[1] Scope @0 [1:22] block=bb6 fallthrough=bb7 // Outer scope for x
bb6:
[2] $22 = Array [] // x = []
[3] StoreLocal x = $22
[4] Scope @1 [4:17] block=bb8 fallthrough=bb9 // Inner scope for y
bb8:
[5] $25 = Array [] // y = []
[6] StoreLocal y = $25
...
[10] $33 = Call useHook(...) // <-- Hook call here!
[11] MethodCall y.push($33)
```
**After FlattenScopesWithHooksOrUseHIR:**
```
bb0:
[1] <pruned> Scope @0 [1:22] block=bb6 fallthrough=bb7 // PRUNED
bb6:
[2] $22 = Array []
[3] StoreLocal x = $22
[4] <pruned> Scope @1 [4:17] block=bb8 fallthrough=bb9 // PRUNED
bb8:
[5] $25 = Array []
[6] StoreLocal y = $25
...
[12] Label block=bb10 fallthrough=bb11 // Hook call converted to label
bb10:
[13] $33 = Call useHook(...)
[14] Goto bb11
...
```
**Final Output (no memoization):**
```javascript
function component(props) {
const x = [];
const y = [];
y.push(useHook(props.foo));
x.push(y);
return x;
}
```
Notice that:
1. Both scope @0 and scope @1 are marked as `<pruned>` because the hook call is inside scope @1, which is inside scope @0
2. The final output has no memoization wrappers - just the raw code

View File

@@ -0,0 +1,158 @@
# propagateScopeDependenciesHIR
## File
`src/HIR/PropagateScopeDependenciesHIR.ts`
## Purpose
The `propagateScopeDependenciesHIR` pass is responsible for computing and assigning the **dependencies** for each reactive scope in the compiled function. Dependencies are the external values that a scope reads, which determine when the scope needs to re-execute. This is a critical step for memoization correctness - the compiler must track exactly which values a scope depends on so it can generate proper cache invalidation checks.
The pass also populates:
- `scope.dependencies` - The set of `ReactiveScopeDependency` objects the scope reads
- `scope.declarations` - Values declared within the scope that are used outside it
## Input Invariants
- Reactive scopes must be established (pass runs after `BuildReactiveScopeTerminalsHIR`)
- The function must be in SSA form
- `InferMutationAliasingRanges` must have run to establish when values are being mutated
- `InferReactivePlaces` marks which identifiers are reactive
- Scope ranges have been aligned and normalized by earlier passes
## Output Guarantees
After this pass completes:
1. Each `ReactiveScope.dependencies` contains the minimal set of dependencies that:
- Were declared before the scope started
- Are read within the scope
- Are not ref values (which are always mutable)
- Are not object methods (which get codegen'd back into object literals)
2. Each `ReactiveScope.declarations` contains identifiers that:
- Are assigned within the scope
- Are used outside the scope (need to be exposed as scope outputs)
3. Property load chains are resolved to their root identifiers with paths (e.g., `props.user.name` becomes `{identifier: props, path: ["user", "name"]}`)
4. Optional chains are handled correctly, distinguishing between `a?.b` and `a.b` access types
## Algorithm
### Phase 1: Build Sidemaps
1. **findTemporariesUsedOutsideDeclaringScope**: Identifies temporaries that are used outside the scope where they were declared (cannot be hoisted/reordered safely)
2. **collectTemporariesSidemap**: Creates a mapping from temporary IdentifierIds to their source `ReactiveScopeDependency`. For example:
```
$0 = LoadLocal 'a'
$1 = PropertyLoad $0.'b'
```
Maps `$1.id` to `{identifier: a, path: [{property: 'b', optional: false}]}`
3. **collectOptionalChainSidemap**: Traverses optional chain blocks to map temporaries within optional chains to their full optional dependency path
4. **collectHoistablePropertyLoads**: Uses CFG analysis to determine which property loads can be safely hoisted
### Phase 2: Collect Dependencies
The `collectDependencies` function traverses the HIR, maintaining a stack of active scopes:
1. **Scope Entry/Exit**: When entering a scope terminal, push a new dependency array. When exiting, propagate collected dependencies to parent scopes if valid.
2. **Instruction Processing**: For each instruction:
- Declare the lvalue with its instruction id and current scope
- Visit operands to record them as potential dependencies
- Handle special cases like `StoreLocal` (tracks reassignments), `Destructure`, `PropertyLoad`, etc.
3. **Dependency Validation** (`#checkValidDependency`):
- Skip ref values (`isRefValueType`)
- Skip object methods (`isObjectMethodType`)
- Only include if declared before scope start
### Phase 3: Derive Minimal Dependencies
For each scope, use `ReactiveScopeDependencyTreeHIR` to:
1. Build a tree from hoistable property loads
2. Add all collected dependencies to the tree
3. Truncate dependencies at their maximal safe-to-evaluate subpath
4. Derive the minimal set (removing redundant nested dependencies)
## Key Data Structures
### ReactiveScopeDependency
```typescript
type ReactiveScopeDependency = {
identifier: Identifier; // Root identifier
reactive: boolean; // Whether the value is reactive
path: DependencyPathEntry[]; // Chain of property accesses
}
```
### DependencyPathEntry
```typescript
type DependencyPathEntry = {
property: PropertyLiteral; // Property name
optional: boolean; // Is this `?.` access?
}
```
### DependencyCollectionContext
Maintains:
- `#declarations`: Map of DeclarationId to {id, scope} recording where each value was declared
- `#reassignments`: Map of Identifier to latest assignment info
- `#scopes`: Stack of currently active ReactiveScopes
- `#dependencies`: Stack of dependency arrays (one per active scope)
- `#temporaries`: Sidemap for resolving property loads
### ReactiveScopeDependencyTreeHIR
A tree structure for efficient dependency deduplication that stores hoistable objects, tracks access types, and computes minimal dependencies.
## Edge Cases
### Values Used Outside Declaring Scope
If a temporary is used outside its declaring scope, it cannot be tracked in the sidemap because reordering the read would be invalid.
### Ref.current Access
Accessing `ref.current` is treated specially - the dependency is truncated to just `ref`.
### Optional Chains
Optional chains like `a?.b?.c` produce different dependency paths than `a.b.c`. The pass distinguishes them and may merge optional loads into unconditional ones when control flow proves the object is non-null.
### Inner Functions
Dependencies from inner functions are collected recursively but with special handling for context variables.
### Phi Nodes
When a value comes from multiple control flow paths, optional chain dependencies from phi operands are also visited.
## TODOs
1. Line 374-375: `// TODO(mofeiZ): understand optional chaining` - More documentation needed for optional chain handling
## Example
### Fixture: `reactive-control-dependency-if.js`
**Input:**
```javascript
function Component(props) {
let x;
if (props.cond) {
x = 1;
} else {
x = 2;
}
return [x];
}
```
**Before PropagateScopeDependenciesHIR:**
```
Scope scope @0 [12:15] dependencies=[] declarations=[] reassignments=[] block=bb9
```
**After PropagateScopeDependenciesHIR:**
```
Scope scope @0 [12:15] dependencies=[x$24:TPrimitive] declarations=[$26_@0] reassignments=[] block=bb9
```
The pass identified that:
- The scope at `[x]` depends on `x$24` (the phi node result from the if/else branches)
- Even though `x` is assigned to constants (1 or 2), its value depends on the reactive control flow condition `props.cond`
- The scope declares `$26_@0` (the array output)

View File

@@ -0,0 +1,180 @@
# buildReactiveFunction
## File
`src/ReactiveScopes/BuildReactiveFunction.ts`
## Purpose
The `buildReactiveFunction` pass converts the compiler's HIR (High-level Intermediate Representation) from a **Control Flow Graph (CFG)** representation to a **tree-based ReactiveFunction** representation that is closer to an AST. This is a critical transformation in the React Compiler pipeline that:
1. **Restores control flow constructs** - Reconstructs `if`, `while`, `for`, `switch`, and other control flow statements from the CFG's basic blocks and terminals
2. **Eliminates phi nodes** - Replaces SSA phi nodes with compound value expressions (ternaries, logical expressions, sequence expressions)
3. **Handles labeled break/continue** - Tracks control flow targets to emit explicit labeled `break` and `continue` statements when needed
4. **Preserves reactive scope information** - Scope terminals are converted to `ReactiveScopeBlock` nodes in the tree
## Input Invariants
- HIR is in SSA form (variables have been renamed with unique identifiers)
- Basic blocks are connected (valid predecessor/successor relationships)
- Each block ends with a valid terminal
- Phi nodes exist at merge points for values from different control flow paths
- Reactive scopes have been constructed (`scope` terminals exist)
- Scope dependencies are computed (`PropagateScopeDependenciesHIR` has run)
## Output Guarantees
- **Tree structure** - The output is a `ReactiveFunction` with a `body: ReactiveBlock` containing a tree of `ReactiveStatement` nodes
- **No CFG structure** - Basic blocks are eliminated; control flow is represented through nested reactive terminals
- **No phi nodes** - Value merges are represented as `ConditionalExpression`, `LogicalExpression`, or `SequenceExpression` values
- **Labels emitted for all control flow** - Every terminal that can be a break/continue target has a label; unnecessary labels are removed by subsequent `PruneUnusedLabels` pass
- **Each block emitted exactly once** - A block cannot be generated twice
- **Scope blocks preserved** - `scope` terminals become `ReactiveScopeBlock` nodes
## Algorithm
### Core Classes
1. **`Driver`** - Traverses blocks and emits ReactiveBlock arrays
2. **`Context`** - Tracks state:
- `emitted: Set<BlockId>` - Which blocks have been generated
- `#scheduled: Set<BlockId>` - Blocks that will be emitted by parent constructs
- `#controlFlowStack: Array<ControlFlowTarget>` - Stack of active break/continue targets
- `scopeFallthroughs: Set<BlockId>` - Fallthroughs for scope blocks
### Traversal Strategy
1. Start at the entry block and call `traverseBlock(entryBlock)`
2. For each block:
- Emit all instructions as `ReactiveInstructionStatement`
- Process the terminal based on its kind
### Terminal Processing
**Simple Terminals:**
- `return`, `throw` - Emit directly as `ReactiveTerminal`
- `unreachable` - No-op
**Control Flow Terminals:**
- `if` - Schedule fallthrough, recursively traverse consequent/alternate, emit `ReactiveIfTerminal`
- `while`, `do-while`, `for`, `for-of`, `for-in` - Use `scheduleLoop()` which tracks continue targets
- `switch` - Process cases in reverse order
- `label` - Schedule fallthrough, traverse inner block
**Value Terminals (expressions that produce values):**
- `ternary`, `logical`, `optional`, `sequence` - Produce `ReactiveValue` compound expressions
**Break/Continue:**
- `goto` with `GotoVariant.Break` - Determine if break is implicit, unlabeled, or labeled
- `goto` with `GotoVariant.Continue` - Determine continue type
**Scope Terminals:**
- `scope`, `pruned-scope` - Schedule fallthrough, traverse inner block, emit as `ReactiveScopeBlock`
## Key Data Structures
### ReactiveFunction
```typescript
type ReactiveFunction = {
loc: SourceLocation;
id: ValidIdentifierName | null;
params: Array<Place | SpreadPattern>;
generator: boolean;
async: boolean;
body: ReactiveBlock;
env: Environment;
directives: Array<string>;
};
```
### ReactiveBlock
```typescript
type ReactiveBlock = Array<ReactiveStatement>;
```
### ReactiveStatement
```typescript
type ReactiveStatement =
| ReactiveInstructionStatement // {kind: 'instruction', instruction}
| ReactiveTerminalStatement // {kind: 'terminal', terminal, label}
| ReactiveScopeBlock // {kind: 'scope', scope, instructions}
| PrunedReactiveScopeBlock; // {kind: 'pruned-scope', ...}
```
### ReactiveValue (for compound expressions)
```typescript
type ReactiveValue =
| InstructionValue // Regular instruction values
| ReactiveLogicalValue // a && b, a || b, a ?? b
| ReactiveSequenceValue // (a, b, c)
| ReactiveTernaryValue // a ? b : c
| ReactiveOptionalCallValue; // a?.b()
```
### ControlFlowTarget
```typescript
type ControlFlowTarget =
| {type: 'if'; block: BlockId; id: number}
| {type: 'switch'; block: BlockId; id: number}
| {type: 'case'; block: BlockId; id: number}
| {type: 'loop'; block: BlockId; continueBlock: BlockId; ...};
```
## Edge Cases
### Nested Control Flow
The scheduling mechanism handles arbitrarily nested control flow by pushing/popping from the control flow stack.
### Value Blocks with Complex Expressions
`SequenceExpression` handles cases where value blocks contain multiple instructions.
### Scope Fallthroughs
Breaks to scope fallthroughs are treated as implicit (no explicit break needed).
### Catch Handlers
Scheduled specially via `scheduleCatchHandler()` to prevent re-emission.
### Unreachable Blocks
The `reachable()` check prevents emitting unreachable blocks.
## TODOs
The code contains several `CompilerError.throwTodo()` calls for unsupported patterns:
1. Optional chaining test blocks must end in `branch`
2. Logical expression test blocks must end in `branch`
3. Support for value blocks within try/catch statements
4. Support for labeled statements combined with value blocks
## Example
### Fixture: `ternary-expression.js`
**Input:**
```javascript
function ternary(props) {
const a = props.a && props.b ? props.c || props.d : (props.e ?? props.f);
const b = props.a ? (props.b && props.c ? props.d : props.e) : props.f;
return a ? b : null;
}
```
**HIR (CFG with many basic blocks):**
The HIR contains 33 basic blocks with `Ternary`, `Logical`, `Branch`, and `Goto` terminals, plus phi nodes at merge points.
**ReactiveFunction Output (Tree):**
```
function ternary(props$62{reactive}) {
[1] $84 = Ternary
Sequence
[2] $66 = Logical
Sequence [...]
&& Sequence [...]
?
Sequence [...] // props.c || props.d
:
Sequence [...] // props.e ?? props.f
[40] StoreLocal a$99 = $98
...
[82] return $145
}
```
The transformation eliminates:
- 33 basic blocks reduced to a single tree
- Phi nodes replaced with nested `Ternary` and `Logical` value expressions
- CFG edges replaced with tree nesting

View File

@@ -0,0 +1,145 @@
# pruneUnusedLabels
## File
`src/ReactiveScopes/PruneUnusedLabels.ts`
## Purpose
The `pruneUnusedLabels` pass optimizes control flow by:
1. **Flattening labeled terminals** where the label is not reachable via a `break` or `continue` statement
2. **Marking labels as implicit** for terminals where the label exists but is never targeted
This pass removes unnecessary labeled blocks that were introduced during compilation but serve no control flow purpose in the final output. JavaScript labeled statements are only needed when there is a corresponding `break label` or `continue label` that targets them.
## Input Invariants
- The input is a `ReactiveFunction` (after conversion from HIR)
- All `break` and `continue` terminals have:
- A `target` (BlockId) indicating which label they jump to
- A `targetKind` that is one of: `'implicit'`, `'labeled'`, or `'unlabeled'`
- Each `ReactiveTerminalStatement` has an optional `label` field containing `id` and `implicit`
- The pass runs after `assertWellFormedBreakTargets` which validates break/continue targets
## Output Guarantees
- Labeled terminals where the label is unreachable are flattened into their parent block
- When flattening, trailing unlabeled `break` statements (that would just fall through) are removed
- Labels that exist but are never targeted have their `implicit` flag set to `true`
- Control flow semantics are preserved - only structurally unnecessary labels are removed
## Algorithm
The pass uses a two-phase approach with a single traversal:
**Phase 1: Collect reachable labels**
```typescript
if ((terminal.kind === 'break' || terminal.kind === 'continue') &&
terminal.targetKind === 'labeled') {
state.add(terminal.target); // Mark this label as reachable
}
```
**Phase 2: Transform terminals**
```typescript
const isReachableLabel = stmt.label !== null && state.has(stmt.label.id);
if (stmt.terminal.kind === 'label' && !isReachableLabel) {
// Flatten: extract block contents, removing trailing unlabeled break
const block = [...stmt.terminal.block];
const last = block.at(-1);
if (last?.kind === 'terminal' && last.terminal.kind === 'break' &&
last.terminal.target === null) {
block.pop(); // Remove trailing break
}
return {kind: 'replace-many', value: block};
} else {
if (!isReachableLabel && stmt.label != null) {
stmt.label.implicit = true; // Mark as implicit
}
return {kind: 'keep'};
}
```
## Edge Cases
### Trailing Break Removal
When flattening a labeled block, if the last statement is an unlabeled break (`target === null`), it is removed since it would just fall through anyway.
### Implicit vs Labeled Breaks
Only breaks with `targetKind === 'labeled'` count toward label reachability. Implicit breaks (fallthrough) and unlabeled breaks don't make a label "used".
### Continue Statements
Both `break` and `continue` with labeled targets mark the label as reachable.
### Non-Label Terminals with Labels
Other terminal types (like `if`, `while`, `for`) can also have labels. If unreachable, these labels are marked implicit but the terminal is not flattened.
## TODOs
None in the source file.
## Example
### Fixture: `unconditional-break-label.js`
**Input:**
```javascript
function foo(a) {
let x = 0;
bar: {
x = 1;
break bar;
}
return a + x;
}
```
**Output (after full compilation):**
```javascript
function foo(a) {
return a + 1;
}
```
The labeled block `bar: { ... }` is removed because after the pass runs, constant propagation and dead code elimination further simplify the code.
### Fixture: `conditional-break-labeled.js`
**Input:**
```javascript
function Component(props) {
const a = [];
a.push(props.a);
label: {
if (props.b) {
break label;
}
a.push(props.c);
}
a.push(props.d);
return a;
}
```
**Output:**
```javascript
function Component(props) {
const $ = _c(5);
let a;
if ($[0] !== props.a || $[1] !== props.b ||
$[2] !== props.c || $[3] !== props.d) {
a = [];
a.push(props.a);
bb0: {
if (props.b) {
break bb0;
}
a.push(props.c);
}
a.push(props.d);
// ... cache updates
} else {
a = $[4];
}
return a;
}
```
The labeled block `bb0: { ... }` is preserved because the `break bb0` inside the conditional targets this label.

View File

@@ -0,0 +1,130 @@
# pruneNonEscapingScopes
## File
`src/ReactiveScopes/PruneNonEscapingScopes.ts`
## Purpose
This pass prunes (removes) reactive scopes whose outputs do not "escape" the component and therefore do not need to be memoized. A value "escapes" in two ways:
1. **Returned from the function** - The value is directly returned or transitively aliased by a return value
2. **Passed to a hook** - Any value passed as an argument to a hook may be stored by React internally (e.g., the closure passed to `useEffect`)
The key insight is that values which never escape the component boundary can be safely recreated on each render without affecting the behavior of consumers.
## Input Invariants
- The input is a `ReactiveFunction` after scope blocks have been identified
- Reactive scopes have been assigned to instructions
- The pass runs after `BuildReactiveFunction` and `PruneUnusedLabels`, before `PruneNonReactiveDependencies`
## Output Guarantees
- **Scopes with non-escaping outputs are removed** - Their instructions are inlined back into the parent scope/function body
- **Scopes with escaping outputs are retained** - Values that escape via return or hook arguments remain memoized
- **Transitive dependencies of escaping scopes are preserved** - If an escaping scope depends on a non-escaping value, that value's scope is also retained to prevent unnecessary invalidation
- **`FinishMemoize` instructions are marked `pruned=true`** - When a scope is pruned, the associated memoization instructions are flagged
## Algorithm
### Phase 1: Build the Dependency Graph
Using `CollectDependenciesVisitor`, build:
- **Identifier nodes** - Each node tracks memoization level, dependencies, scopes, and whether ultimately memoized
- **Scope nodes** - Each scope tracks its dependencies
- **Escaping values** - Identifiers that escape via return or hook arguments
### Phase 2: Classify Memoization Levels
Each instruction value is classified:
- `Memoized`: Arrays, objects, function calls, `new` expressions - always potentially aliasing
- `Conditional`: Conditional/logical expressions, property loads - memoized only if dependencies are memoized
- `Unmemoized`: JSX elements (when `memoizeJsxElements` is false), DeclareLocal
- `Never`: Primitives, LoadGlobal, binary/unary expressions - can be cheaply compared
### Phase 3: Compute Memoized Identifiers
`computeMemoizedIdentifiers()` performs a graph traversal starting from escaping values:
- For each escaping value, recursively visit its dependencies
- Mark values and their scopes based on memoization level
- When marking a scope, force-memoize all its dependencies
### Phase 4: Prune Scopes
`PruneScopesTransform` visits each scope block:
- If any scope output is in the memoized set, keep the scope
- If no outputs are memoized, replace the scope block with its inlined instructions
## Edge Cases
### Interleaved Mutations
```javascript
const a = [props.a]; // independently memoizable, non-escaping
const b = [];
const c = {};
c.a = a; // c captures a, but c doesn't escape
b.push(props.b); // b escapes via return
return b;
```
Here `a` does not directly escape, but it is a dependency of the scope containing `b`. The algorithm correctly identifies that `a`'s scope must be preserved.
### Hook Arguments Escape
Values passed to hooks are treated as escaping because hooks may store references internally.
### JSX Special Handling
JSX elements are marked as `Unmemoized` by default because React.memo() can handle dynamic memoization.
### noAlias Functions
If a function signature indicates `noAlias === true`, its arguments are not treated as escaping.
### Reassignments
When a scope reassigns a variable, the scope is added as a dependency of that variable.
## TODOs
None explicitly in the source file.
## Example
### Fixture: `escape-analysis-non-escaping-interleaved-allocating-dependency.js`
**Input:**
```javascript
function Component(props) {
const a = [props.a];
const b = [];
const c = {};
c.a = a;
b.push(props.b);
return b;
}
```
**Output:**
```javascript
function Component(props) {
const $ = _c(5);
let t0;
if ($[0] !== props.a) {
t0 = [props.a];
$[0] = props.a;
$[1] = t0;
} else {
t0 = $[1];
}
const a = t0; // a is memoized even though it doesn't escape directly
let b;
if ($[2] !== a || $[3] !== props.b) {
b = [];
const c = {}; // c is NOT memoized - it doesn't escape
c.a = a;
b.push(props.b);
$[2] = a;
$[3] = props.b;
$[4] = b;
} else {
b = $[4];
}
return b;
}
```
Key observations:
- `a` is memoized because it's a dependency of the scope containing `b`
- `c` is not separately memoized because it doesn't escape
- `b` is memoized because it's returned

View File

@@ -0,0 +1,138 @@
# pruneNonReactiveDependencies
## File
`src/ReactiveScopes/PruneNonReactiveDependencies.ts`
## Purpose
This pass removes dependencies from reactive scopes that are guaranteed to be **non-reactive** (i.e., their values cannot change between renders). This optimization reduces unnecessary memoization invalidations by ensuring scopes only depend on values that can actually change.
The pass complements `PropagateScopeDependencies`, which infers dependencies without considering reactivity. This subsequent pruning step filters out dependencies that are semantically constant.
## Input Invariants
- The function has been converted to a ReactiveFunction structure
- `InferReactivePlaces` has annotated places with `{reactive: true}` where values can change
- Each `ReactiveScopeBlock` has a `scope.dependencies` set populated by `PropagateScopeDependenciesHIR`
- Type inference has run, so identifiers have type information for `isStableType` checks
## Output Guarantees
- **Non-reactive dependencies removed**: All dependencies in `scope.dependencies` are reactive after this pass
- **Scope outputs marked reactive if needed**: If a scope has any reactive dependencies remaining, all its outputs are marked reactive
- **Stable types remain non-reactive through property loads**: When loading properties from stable types (like `useReducer` dispatch functions), the result is not added to the reactive set
## Algorithm
### Phase 1: Collect Reactive Identifiers
The `collectReactiveIdentifiers` helper builds the initial set of reactive identifiers by:
1. Visiting all places in the ReactiveFunction
2. Adding any place marked `{reactive: true}` to the set
3. For pruned scopes, adding declarations that are not primitives and not stable ref types
### Phase 2: Propagate Reactivity and Prune Dependencies
The main `Visitor` class traverses the ReactiveFunction and:
1. **For Instructions** - Propagates reactivity through data flow:
- `LoadLocal`: If source is reactive, mark the lvalue as reactive
- `StoreLocal`: If source value is reactive, mark both the local variable and lvalue as reactive
- `Destructure`: If source is reactive, mark all pattern operands as reactive (except stable types)
- `PropertyLoad`: If object is reactive AND result is not a stable type, mark result as reactive
- `ComputedLoad`: If object OR property is reactive, mark result as reactive
2. **For Scopes** - Prunes non-reactive dependencies and propagates outputs:
- Delete each dependency from `scope.dependencies` if its identifier is not in the reactive set
- If any dependencies remain after pruning, mark all scope outputs as reactive
### Key Insight: Stable Types
The pass leverages `isStableType` to prevent reactivity from flowing through certain React-provided stable values:
```typescript
function isStableType(id: Identifier): boolean {
return (
isSetStateType(id) || // useState setter
isSetActionStateType(id) || // useActionState setter
isDispatcherType(id) || // useReducer dispatcher
isUseRefType(id) || // useRef result
isStartTransitionType(id) ||// useTransition startTransition
isSetOptimisticType(id) // useOptimistic setter
);
}
```
## Edge Cases
### Unmemoized Values Spanning Hook Calls
A value created before a hook call and mutated after cannot be memoized. However, if it's non-reactive, it still should not appear as a dependency of downstream scopes.
### Stable Types from Reactive Containers
When `useReducer` returns `[state, dispatch]`, `state` is reactive but `dispatch` is stable. The pass correctly handles this.
### Pruned Scopes with Reactive Content
The `CollectReactiveIdentifiers` pass also examines pruned scopes and adds their non-primitive, non-stable-ref declarations to the reactive set.
### Transitive Reactivity Through Scopes
When a scope retains at least one reactive dependency, ALL its outputs become reactive.
## TODOs
None in the source file.
## Example
### Fixture: `unmemoized-nonreactive-dependency-is-pruned-as-dependency.js`
**Input:**
```javascript
function Component(props) {
const x = [];
useNoAlias();
mutate(x);
return <div>{x}</div>;
}
```
**Before PruneNonReactiveDependencies:**
```
scope @2 dependencies=[x$15_@0:TObject<BuiltInArray>] declarations=[$23_@2]
```
**After PruneNonReactiveDependencies:**
```
scope @2 dependencies=[] declarations=[$23_@2]
```
The dependency on `x` is removed because `x` is created locally and therefore non-reactive.
### Fixture: `useReducer-returned-dispatcher-is-non-reactive.js`
**Input:**
```javascript
function f() {
const [state, dispatch] = useReducer();
const onClick = () => {
dispatch();
};
return <div onClick={onClick} />;
}
```
**Generated Code:**
```javascript
function f() {
const $ = _c(1);
const [, dispatch] = useReducer();
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
const onClick = () => {
dispatch();
};
t0 = <div onClick={onClick} />;
$[0] = t0;
} else {
t0 = $[0];
}
return t0;
}
```
The `onClick` function only captures `dispatch`, which is a stable type. Therefore, `onClick` is non-reactive, and the JSX element can be memoized with zero dependencies.

View File

@@ -0,0 +1,111 @@
# pruneUnusedScopes
## File
`src/ReactiveScopes/PruneUnusedScopes.ts`
## Purpose
This pass converts reactive scopes that have no meaningful outputs into "pruned scopes". A pruned scope is no longer memoized - its instructions are executed unconditionally on every render. This optimization removes unnecessary memoization overhead for scopes that don't produce values that need to be cached.
## Input Invariants
- The input is a `ReactiveFunction` that has already been transformed into reactive scope form
- Scopes have been created and have `declarations`, `reassignments`, and potentially `earlyReturnValue` populated
- The pass is called after:
- `pruneUnusedLabels` - cleans up unnecessary labels
- `pruneNonEscapingScopes` - removes scopes whose outputs don't escape
- `pruneNonReactiveDependencies` - removes non-reactive dependencies from scopes
- Scopes may already be marked as pruned by earlier passes
## Output Guarantees
Scopes that meet ALL of the following criteria are converted to `pruned-scope`:
- No return statement within the scope
- No reassignments (`scope.reassignments.size === 0`)
- Either no declarations (`scope.declarations.size === 0`), OR all declarations "bubbled up" from inner scopes
Pruned scopes:
- Keep their original scope metadata (for debugging/tracking)
- Keep their instructions intact
- Will be executed unconditionally during codegen (no memoization check)
## Algorithm
The pass uses the visitor pattern with `ReactiveFunctionTransform`:
1. **State Tracking**: A `State` object tracks whether a return statement was encountered:
```typescript
type State = {
hasReturnStatement: boolean;
};
```
2. **Terminal Visitor** (`visitTerminal`): Checks if any terminal is a `return` statement
3. **Scope Transform** (`transformScope`): For each scope:
- Creates a fresh state for this scope
- Recursively visits the scope's contents
- Checks pruning criteria:
- `!scopeState.hasReturnStatement` - no early return
- `scope.reassignments.size === 0` - no reassignments
- `scope.declarations.size === 0` OR `!hasOwnDeclaration(scopeBlock)` - no outputs
4. **hasOwnDeclaration Helper**: Determines if a scope has "own" declarations vs declarations propagated from nested scopes
## Edge Cases
### Return Statements
Scopes containing return statements are preserved because early returns need memoization to avoid re-executing the return check on every render.
### Bubbled-Up Declarations
When nested scopes are flattened or merged, their declarations may be propagated to parent scopes. The `hasOwnDeclaration` check ensures that parent scopes with only inherited declarations can still be pruned.
### Reassignments
Scopes with reassignments are kept because the reassignment represents a side effect that needs to be tracked for memoization.
### Already-Pruned Scopes
The pass operates on `ReactiveScopeBlock` (kind: 'scope'), not `PrunedReactiveScopeBlock`. Scopes already pruned by earlier passes are not revisited.
### Interaction with Subsequent Passes
The `MergeReactiveScopesThatInvalidateTogether` pass explicitly handles pruned scopes - it does not merge across them.
## TODOs
None in the source file.
## Example
### Fixture: `prune-scopes-whose-deps-invalidate-array.js`
**Input:**
```javascript
function Component(props) {
const x = [];
useHook();
x.push(props.value);
const y = [x];
return [y];
}
```
What happens:
- The scope for `x` cannot be memoized because `useHook()` is called inside it
- `FlattenScopesWithHooksOrUseHIR` marks scope @0 as `pruned-scope`
- `PruneUnusedScopes` doesn't change it further since it's already pruned
**Output (no memoization for x):**
```javascript
function Component(props) {
const x = [];
useHook();
x.push(props.value);
const y = [x];
return [y];
}
```
### Key Insight
The `pruneUnusedScopes` pass is part of a multi-pass pruning strategy:
1. `FlattenScopesWithHooksOrUseHIR` - Prunes scopes that contain hook/use calls
2. `pruneNonEscapingScopes` - Prunes scopes whose outputs don't escape
3. `pruneNonReactiveDependencies` - Removes non-reactive dependencies
4. **`pruneUnusedScopes`** - Prunes scopes with no remaining outputs
This pass acts as a cleanup for scopes that became "empty" after previous pruning passes removed their outputs.

View File

@@ -0,0 +1,213 @@
# mergeReactiveScopesThatInvalidateTogether
## File
`src/ReactiveScopes/MergeReactiveScopesThatInvalidateTogether.ts`
## Purpose
This pass is an optimization that reduces memoization overhead in the compiled output by merging reactive scopes that will always invalidate together. The pass operates on the ReactiveFunction representation and works in two main scenarios:
1. **Consecutive Scopes**: When two scopes appear sequentially in the same reactive block with identical dependencies (or where the output of the first scope is the sole input to the second), they are merged into a single scope. This reduces the number of memo cache slots used and eliminates redundant dependency comparisons.
2. **Nested Scopes**: When an inner scope has the same dependencies as its parent scope, the inner scope is flattened into the parent. Since PropagateScopeDependencies propagates dependencies upward, nested scopes can only have equal or fewer dependencies than their parents, never more. When they're equal, the inner scope always invalidates with the parent, making it safe and beneficial to flatten.
## Input Invariants
- The ReactiveFunction has already undergone scope dependency propagation (via `PropagateScopeDependencies`)
- The function has been pruned of unused scopes (via `pruneNonReactiveDependencies` and `pruneUnusedScopes`)
- Scopes have valid `dependencies`, `declarations`, `range`, and `reassignments` fields
- The ReactiveFunction is in a valid structural state with properly formed blocks and instructions
## Output Guarantees
- **Fewer scopes**: Consecutive and nested scopes with identical dependencies are merged
- **Valid scope ranges**: Merged scopes have their `range.end` updated to cover all merged instructions
- **Updated declarations**: Scope declarations are updated to remove any that are no longer used after the merged scope
- **Merged scope tracking**: The `scope.merged` set tracks which scope IDs were merged into each surviving scope
- **Preserved semantics**: Only safe-to-memoize intermediate instructions are absorbed into merged scopes
## Algorithm
The pass operates in multiple phases:
### Phase 1: Find Last Usage
A visitor (`FindLastUsageVisitor`) collects the last usage instruction ID for each declaration:
```typescript
class FindLastUsageVisitor extends ReactiveFunctionVisitor<void> {
lastUsage: Map<DeclarationId, InstructionId> = new Map();
override visitPlace(id: InstructionId, place: Place, _state: void): void {
const previousUsage = this.lastUsage.get(place.identifier.declarationId);
const lastUsage =
previousUsage !== undefined
? makeInstructionId(Math.max(previousUsage, id))
: id;
this.lastUsage.set(place.identifier.declarationId, lastUsage);
}
}
```
### Phase 2: Transform (Nested Scope Flattening)
The `transformScope` method flattens nested scopes with identical dependencies:
```typescript
override transformScope(
scopeBlock: ReactiveScopeBlock,
state: ReactiveScopeDependencies | null,
): Transformed<ReactiveStatement> {
this.visitScope(scopeBlock, scopeBlock.scope.dependencies);
if (
state !== null &&
areEqualDependencies(state, scopeBlock.scope.dependencies)
) {
return {kind: 'replace-many', value: scopeBlock.instructions};
} else {
return {kind: 'keep'};
}
}
```
### Phase 3: Visit Block (Consecutive Scope Merging)
Within `visitBlock`, the pass:
1. First traverses nested blocks recursively
2. Iterates through instructions, tracking merge candidates
3. Determines if consecutive scopes can merge based on:
- Identical dependencies, OR
- Output of first scope is input to second scope (with always-invalidating types)
4. Collects intermediate lvalues and ensures they're only used by the next scope
5. Merges eligible scopes by combining instructions and updating range/declarations
### Key Merging Conditions (`canMergeScopes`):
```typescript
function canMergeScopes(
current: ReactiveScopeBlock,
next: ReactiveScopeBlock,
temporaries: Map<DeclarationId, DeclarationId>,
): boolean {
// Don't merge scopes with reassignments
if (current.scope.reassignments.size !== 0 || next.scope.reassignments.size !== 0) {
return false;
}
// Merge scopes whose dependencies are identical
if (areEqualDependencies(current.scope.dependencies, next.scope.dependencies)) {
return true;
}
// Merge scopes where outputs of previous are inputs of next
// (with always-invalidating type check)
// ...
}
```
### Always-Invalidating Types:
```typescript
export function isAlwaysInvalidatingType(type: Type): boolean {
switch (type.kind) {
case 'Object': {
switch (type.shapeId) {
case BuiltInArrayId:
case BuiltInObjectId:
case BuiltInFunctionId:
case BuiltInJsxId: {
return true;
}
}
break;
}
case 'Function': {
return true;
}
}
return false;
}
```
## Edge Cases
### Terminals
The pass does not merge across terminals (control flow boundaries).
### Pruned Scopes
Merging stops at pruned scopes.
### Reassignments
Scopes containing reassignments cannot be merged (side-effect ordering concerns).
### Intermediate Reassignments
Non-const StoreLocal instructions between scopes prevent merging.
### Safe Intermediate Instructions
Only certain instruction types are allowed between merged scopes: `BinaryExpression`, `ComputedLoad`, `JSXText`, `LoadGlobal`, `LoadLocal`, `Primitive`, `PropertyLoad`, `TemplateLiteral`, `UnaryExpression`, and const `StoreLocal`.
### Lvalue Usage
Intermediate values must be last-used at or before the next scope to allow merging.
### Non-Invalidating Outputs
If a scope's output may not change when inputs change (e.g., `foo(x) { return x < 10 }` returns same boolean for different x values), that scope cannot be a merge candidate for subsequent scopes.
## TODOs
```typescript
/*
* TODO LeaveSSA: use IdentifierId for more precise tracking
* Using DeclarationId is necessary for compatible output but produces suboptimal results
* in cases where a scope defines a variable, but that version is never read and always
* overwritten later.
* see reassignment-separate-scopes.js for example
*/
lastUsage: Map<DeclarationId, InstructionId> = new Map();
```
## Example
### Fixture: `merge-consecutive-scopes-deps-subset-of-decls.js`
**Input:**
```javascript
import {useState} from 'react';
function Component() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(count - 1)}>Decrement</button>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
```
**After MergeReactiveScopesThatInvalidateTogether** (from `yarn snap -p merge-consecutive-scopes-deps-subset-of-decls.js -d`):
```
scope @1 [7:24] dependencies=[count$32:TPrimitive] declarations=[$51_@5] reassignments=[] {
[8] $35_@1 = Function @context[setCount$33, count$32] // decrement callback
[10] $41 = JSXText "Decrement"
[12] $42_@2 = JSX <button onClick={$35_@1}>{$41}</button>
[15] $43_@3 = Function @context[setCount$33, count$32] // increment callback
[17] $49 = JSXText "Increment"
[19] $50_@4 = JSX <button onClick={$43_@3}>{$49}</button>
[22] $51_@5 = JSX <div>{$42_@2}{$50_@4}</div>
}
```
All scopes are merged because they share `count` as a dependency. Without merging, this would have separate scopes for each callback and button element.
**Generated Code:**
```javascript
function Component() {
const $ = _c(2);
const [count, setCount] = useState(0);
let t0;
if ($[0] !== count) {
t0 = (
<div>
<button onClick={() => setCount(count - 1)}>Decrement</button>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
$[0] = count;
$[1] = t0;
} else {
t0 = $[1];
}
return t0;
}
```
The merged version uses only 2 cache slots instead of potentially 6-8.

View File

@@ -0,0 +1,143 @@
# pruneAlwaysInvalidatingScopes
## File
`src/ReactiveScopes/PruneAlwaysInvalidatingScopes.ts`
## Purpose
This pass identifies and prunes reactive scopes whose dependencies will *always* invalidate on every render, making memoization pointless. Specifically, it tracks values that are guaranteed to be new allocations (arrays, objects, JSX, new expressions) and checks if those values are used outside of any memoization scope. When a downstream scope depends on such an unmemoized always-invalidating value, the scope is pruned because it would re-execute on every render anyway.
The optimization avoids wasted comparisons in the generated code. Without this pass, the compiler would emit dependency checks for scopes that will never cache-hit, adding runtime overhead with no benefit. By converting these scopes to `pruned-scope` nodes, the codegen emits the instructions inline without memoization guards.
## Input Invariants
- The pass expects a `ReactiveFunction` with scopes already formed
- Scopes should have their `dependencies` populated with the identifiers they depend on
- The pass runs after `MergeReactiveScopesThatInvalidateTogether`
- Hook calls have already caused scope flattening via `FlattenScopesWithHooksOrUseHIR`
## Output Guarantees
- Scopes that depend on unmemoized always-invalidating values are converted to `pruned-scope` nodes
- The `unmemoizedValues` set correctly propagates through `StoreLocal`/`LoadLocal` instructions
- All declarations and reassignments within pruned scopes that are themselves always-invalidating are added to `unmemoizedValues`, enabling cascading pruning of downstream scopes
## Algorithm
The pass uses a `ReactiveFunctionTransform` visitor with two key methods:
### 1. `transformInstruction` - Tracks always-invalidating values:
```typescript
switch (value.kind) {
case 'ArrayExpression':
case 'ObjectExpression':
case 'JsxExpression':
case 'JsxFragment':
case 'NewExpression': {
if (lvalue !== null) {
this.alwaysInvalidatingValues.add(lvalue.identifier);
if (!withinScope) {
this.unmemoizedValues.add(lvalue.identifier); // Key: only if outside a scope
}
}
break;
}
// Also propagates through StoreLocal and LoadLocal
}
```
### 2. `transformScope` - Prunes scopes with unmemoized dependencies:
```typescript
for (const dep of scopeBlock.scope.dependencies) {
if (this.unmemoizedValues.has(dep.identifier)) {
// Propagate unmemoized status to scope outputs
for (const [_, decl] of scopeBlock.scope.declarations) {
if (this.alwaysInvalidatingValues.has(decl.identifier)) {
this.unmemoizedValues.add(decl.identifier);
}
}
return {
kind: 'replace',
value: {
kind: 'pruned-scope',
scope: scopeBlock.scope,
instructions: scopeBlock.instructions,
},
};
}
}
```
## Edge Cases
### Function Calls Not Considered Always-Invalidating
The pass optimistically assumes function calls may return primitives, so `makeArray()` doesn't trigger pruning even though it might return a new array.
### Conditional Allocations
Code like `x = cond ? [] : 42` doesn't trigger pruning because the value might be a primitive.
### Propagation Through Locals
The pass correctly tracks values through `StoreLocal` and `LoadLocal` to handle variable reassignments and loads.
### Cascading Pruning
When a scope is pruned, its always-invalidating outputs become unmemoized, potentially causing downstream scopes to be pruned as well.
## TODOs
None in the source file.
## Example
### Fixture: `prune-scopes-whose-deps-invalidate-array.js`
**Input:**
```javascript
function Component(props) {
const x = [];
useHook();
x.push(props.value);
const y = [x];
return [y];
}
```
**After PruneAlwaysInvalidatingScopes** (from `yarn snap -p prune-scopes-whose-deps-invalidate-array.js -d`):
```
<pruned> scope @0 [1:14] dependencies=[] declarations=[x$21_@0] reassignments=[] {
[2] $20_@0 = Array []
[3] StoreLocal Const x$21_@0 = $20_@0
[4] $23 = LoadGlobal import { useHook }
[6] $24_@1 = Call $23() // Hook flattens scope
[7] break bb9 (implicit)
[8] $25_@0 = LoadLocal x$21_@0
[9] $26 = PropertyLoad $25_@0.push
[10] $27 = LoadLocal props$19
[11] $28 = PropertyLoad $27.value
[12] $29 = MethodCall $25_@0.$26($28)
}
[14] $30 = LoadLocal x$21_@0
<pruned> scope @2 [15:23] dependencies=[x$21_@0:TObject<BuiltInArray>] declarations=[$35_@3] {
[16] $31_@2 = Array [$30]
[18] StoreLocal Const y$32 = $31_@2
[19] $34 = LoadLocal y$32
[21] $35_@3 = Array [$34]
}
[23] return $35_@3
```
Key observations:
- Scope @0 is pruned because the hook call (`useHook()`) flattens it (hook rules prevent memoization around hooks)
- `x` is an `ArrayExpression` created in the pruned scope @0, making it unmemoized
- Scope @2 depends on `x$21_@0` which is unmemoized and always-invalidating (it's an array)
- Therefore, scope @2 is also pruned - cascading pruning
**Generated Code:**
```javascript
function Component(props) {
const x = [];
useHook();
x.push(props.value);
const y = [x];
return [y];
}
```
The output matches the input because all memoization was pruned - the code runs unconditionally on every render.

View File

@@ -0,0 +1,183 @@
# propagateEarlyReturns
## File
`src/ReactiveScopes/PropagateEarlyReturns.ts`
## Purpose
The `propagateEarlyReturns` pass ensures that reactive scopes (memoization blocks) correctly honor the control flow behavior of the original code, particularly when a function returns early from within a reactive scope. Without this transformation, if a component returned early on the previous render and the inputs have not changed, the cached memoization block would be skipped entirely, but the early return would not occur, causing incorrect behavior.
The pass solves this by transforming `return` statements inside reactive scopes into assignments to a temporary variable followed by a labeled `break`. After the reactive scope completes, generated code checks whether the early return sentinel value was replaced with an actual return value; if so, the function returns that value.
## Input Invariants
1. **ReactiveFunction structure**: The input must be a `ReactiveFunction` with scopes already inferred (reactive scope blocks are already established)
2. **Scope earlyReturnValue not set**: The pass expects `scopeBlock.scope.earlyReturnValue === null` for scopes it processes
3. **Return statements within reactive scopes**: The pass specifically targets `return` terminal statements that appear within a `withinReactiveScope` context
## Output Guarantees
1. **Labeled scope blocks**: Top-level reactive scopes containing early returns are wrapped in a labeled block (e.g., `bb14: { ... }`)
2. **Sentinel initialization**: At the start of each such scope, a temporary variable is initialized to `Symbol.for("react.early_return_sentinel")`
3. **Return-to-break transformation**: All `return` statements inside the scope are replaced with:
- An assignment of the return value to the early return temporary
- A `break` to the scope's label
4. **Early return declaration**: The temporary variable is registered as a declaration of the scope so it gets memoized
5. **Post-scope check**: During codegen, an if-statement is added after the scope to check if the temporary differs from the sentinel and return it if so
## Algorithm
The pass uses a visitor pattern with a `ReactiveFunctionTransform` that tracks two pieces of state:
```typescript
type State = {
withinReactiveScope: boolean; // Are we inside a reactive scope?
earlyReturnValue: ReactiveScope['earlyReturnValue']; // Bubble up early return info
};
```
### Key Steps:
1. **visitScope** - When entering a reactive scope:
- Create an inner state with `withinReactiveScope: true`
- Traverse the scope's contents
- If any early returns were found (`earlyReturnValue !== null`):
- If this is the **outermost** scope (parent's `withinReactiveScope` is false):
- Store the early return info on the scope
- Add the temporary as a scope declaration
- Prepend sentinel initialization instructions
- Wrap the original instructions in a labeled block
- Otherwise, propagate the early return info to the parent scope
2. **transformTerminal** - When encountering a `return` inside a reactive scope:
- Create or reuse an early return value identifier
- Replace the return with:
```typescript
[
{kind: 'instruction', /* StoreLocal: reassign earlyReturnValue = returnValue */},
{kind: 'terminal', /* break to earlyReturnValue.label */}
]
```
### Sentinel Initialization Code (synthesized at scope start):
```typescript
// Load Symbol.for and call it with the sentinel string
let t0 = Symbol.for("react.early_return_sentinel");
```
## Edge Cases
### Nested Reactive Scopes
When early returns occur in nested scopes, only the **outermost** scope gets the labeled block wrapper. Inner scopes bubble their early return information up via `parentState.earlyReturnValue`.
### Multiple Early Returns in Same Scope
All returns share the same temporary variable and label. The first return found creates the identifier, subsequent returns reuse it.
### Partial Early Returns
When only some control flow paths return early (e.g., one branch returns, the other falls through), the sentinel check after the scope allows normal execution to continue if no early return occurred.
### Already Processed Scopes
If `scopeBlock.scope.earlyReturnValue !== null` on entry, the pass exits early without modification.
### Returns Outside Reactive Scopes
The pass only transforms returns where `state.withinReactiveScope === true`. Returns outside scopes are left unchanged.
## TODOs
None in the source file.
## Example
### Fixture: `early-return-within-reactive-scope.js`
**Input:**
```javascript
function Component(props) {
let x = [];
if (props.cond) {
x.push(props.a);
return x;
} else {
return makeArray(props.b);
}
}
```
**After PropagateEarlyReturns** (from `yarn snap -p early-return-within-reactive-scope.js -d`):
```
scope @0 [...] earlyReturn={id: #t34$34, label: 14} {
[0] $36 = LoadGlobal(global) Symbol
[0] $37 = PropertyLoad $36.for
[0] $38 = "react.early_return_sentinel"
[0] $35 = MethodCall $36.$37($38)
[0] StoreLocal Let #t34$34{reactive} = $35 // Initialize sentinel
bb14: {
[2] $19_@0 = Array []
[3] StoreLocal Const x$20_@0 = $19_@0
[4] $22{reactive} = LoadLocal props$18
[5] $23{reactive} = PropertyLoad $22.cond
[6] if ($23) {
[7] $24_@0 = LoadLocal x$20_@0
[8] $25 = PropertyLoad $24_@0.push
[9] $26 = LoadLocal props$18
[10] $27 = PropertyLoad $26.a
[11] $28 = MethodCall $24_@0.$25($27)
[12] $29 = LoadLocal x$20_@0
[0] StoreLocal Reassign #t34$34 = $29 // was: return x
[0] break bb14 (labeled)
} else {
[14] $30 = LoadGlobal import { makeArray }
[15] $31 = LoadLocal props$18
[16] $32 = PropertyLoad $31.b
scope @1 [...] {
[18] $33_@1 = Call $30($32)
}
[0] StoreLocal Reassign #t34$34 = $33_@1 // was: return makeArray(props.b)
[0] break bb14 (labeled)
}
}
}
```
Key observations:
- Scope @0 now has `earlyReturn={id: #t34$34, label: 14}`
- Sentinel initialization code is prepended to the scope
- The scope body is wrapped in `bb14: { ... }`
- Both `return x` and `return makeArray(props.b)` are transformed to `StoreLocal Reassign + break bb14`
**Generated Code:**
```javascript
function Component(props) {
const $ = _c(6);
let t0;
if ($[0] !== props.a || $[1] !== props.b || $[2] !== props.cond) {
t0 = Symbol.for("react.early_return_sentinel");
bb0: {
const x = [];
if (props.cond) {
x.push(props.a);
t0 = x;
break bb0;
} else {
let t1;
if ($[4] !== props.b) {
t1 = makeArray(props.b);
$[4] = props.b;
$[5] = t1;
} else {
t1 = $[5];
}
t0 = t1;
break bb0;
}
}
$[0] = props.a;
$[1] = props.b;
$[2] = props.cond;
$[3] = t0;
} else {
t0 = $[3];
}
if (t0 !== Symbol.for("react.early_return_sentinel")) {
return t0;
}
}
```
This transformation ensures that when inputs don't change, the cached return value is used and returned, preserving referential equality and correct early return behavior.

View File

@@ -0,0 +1,203 @@
# promoteUsedTemporaries
## File
`src/ReactiveScopes/PromoteUsedTemporaries.ts`
## Purpose
This pass promotes temporary variables (identifiers with no name) to named variables when they need to be referenced across scope boundaries or in code generation. Temporaries are intermediate values that the compiler creates during lowering; they are typically inlined at their use sites during codegen. However, some temporaries must be emitted as separate declarations - this pass identifies and names them.
The pass ensures that:
1. Scope dependencies and declarations have proper names for codegen
2. Variables referenced across reactive scope boundaries are named
3. JSX tag identifiers get special naming (`T0`, `T1`, etc.)
4. Temporaries with interposing side-effects are promoted to preserve ordering
## Input Invariants
- The ReactiveFunction has undergone scope construction and dependency propagation
- Identifiers may have `name === null` (temporaries) or be named
- Scopes have `dependencies`, `declarations`, and `reassignments` populated
- Pruned scopes are properly marked with `kind: 'pruned-scope'`
## Output Guarantees
- All scope dependencies have non-null names
- All scope declarations have non-null names
- JSX tag temporaries use uppercase naming (`T0`, `T1`, ...)
- Regular temporaries use lowercase naming (`#t{id}`)
- All instances of a promoted identifier share the same name (via DeclarationId tracking)
- Temporaries with interposing mutating instructions are promoted to preserve source ordering
## Algorithm
The pass operates in four phases using visitor classes:
### Phase 1: CollectPromotableTemporaries
Collects information about which temporaries may need promotion:
```typescript
class CollectPromotableTemporaries {
// Tracks pruned scope declarations and whether they're used outside their scope
pruned: Map<DeclarationId, {activeScopes: Array<ScopeId>; usedOutsideScope: boolean}>
// Tracks identifiers used as JSX tags (need uppercase names)
tags: Set<DeclarationId>
}
```
- When visiting a `JsxExpression`, adds the tag identifier to `tags`
- When visiting a `PrunedScope`, records its declarations
- Tracks when pruned declarations are used in different scopes
### Phase 2: PromoteTemporaries
Promotes temporaries that appear in positions requiring names:
```typescript
override visitScope(scopeBlock: ReactiveScopeBlock, state: State): void {
// Promote all dependencies without names
for (const dep of scopeBlock.scope.dependencies) {
if (identifier.name == null) {
promoteIdentifier(identifier, state);
}
}
// Promote all declarations without names
for (const [, declaration] of scopeBlock.scope.declarations) {
if (declaration.identifier.name == null) {
promoteIdentifier(declaration.identifier, state);
}
}
}
```
Also promotes:
- Function parameters without names
- Pruned scope declarations used outside their scope
### Phase 3: PromoteInterposedTemporaries
Handles ordering-sensitive promotion:
```typescript
class PromoteInterposedTemporaries {
// Instructions that emit as statements can interpose between temp defs and uses
// If such an instruction occurs, mark pending temporaries as needing promotion
override visitInstruction(instruction: ReactiveInstruction, state: InterState): void {
// For instructions that become statements (calls, stores, etc.):
if (willBeStatement && !constStore) {
// Mark all pending temporaries as needing promotion
for (const [key, [ident, _]] of state.entries()) {
state.set(key, [ident, true]); // Mark as needing promotion
}
}
}
}
```
This preserves source ordering when side-effects occur between a temporary's definition and use.
### Phase 4: PromoteAllInstancesOfPromotedTemporaries
Ensures all instances of a promoted identifier share the same name:
```typescript
class PromoteAllInstancesOfPromotedTemporaries {
override visitPlace(_id: InstructionId, place: Place, state: State): void {
if (place.identifier.name === null &&
state.promoted.has(place.identifier.declarationId)) {
promoteIdentifier(place.identifier, state);
}
}
}
```
### Naming Convention
```typescript
function promoteIdentifier(identifier: Identifier, state: State): void {
if (state.tags.has(identifier.declarationId)) {
promoteTemporaryJsxTag(identifier); // Uses #T{id} for JSX tags
} else {
promoteTemporary(identifier); // Uses #t{id} for regular temps
}
state.promoted.add(identifier.declarationId);
}
```
## Edge Cases
### JSX Tag Temporaries
JSX tags require uppercase names to be valid JSX syntax. The pass tracks which temporaries are used as JSX tags and uses `T0`, `T1`, etc. instead of `t0`, `t1`.
### Pruned Scope Declarations
Declarations in pruned scopes are only promoted if they're actually used outside the pruned scope, avoiding unnecessary variable declarations.
### Const vs Let Temporaries
The pass tracks const identifiers specially - they don't need promotion for ordering purposes since they can't be mutated by interposing instructions.
### Global Loads
Values loaded from globals (and their property loads) are treated as const-like for promotion purposes.
### Method Call Properties
The property identifier in a method call is treated as const-like to avoid unnecessary promotion.
## TODOs
None in the source file.
## Example
### Fixture: `simple.js`
**Input:**
```javascript
export default function foo(x, y) {
if (x) {
return foo(false, y);
}
return [y * 10];
}
```
**Before PromoteUsedTemporaries:**
```
scope @0 [...] dependencies=[y$14] declarations=[$19_@0]
scope @1 [...] dependencies=[$22] declarations=[$23_@1]
```
**After PromoteUsedTemporaries:**
```
scope @0 [...] dependencies=[y$14] declarations=[#t5$19_@0]
scope @1 [...] dependencies=[#t9$22] declarations=[#t10$23_@1]
```
Key observations:
- `$19_@0` is promoted to `#t5$19_@0` because it's a scope declaration
- `$22` is promoted to `#t9$22` because it's a scope dependency
- `$23_@1` is promoted to `#t10$23_@1` because it's a scope declaration
- The `#t` prefix indicates this is a promoted temporary (later renamed by `renameVariables`)
**Generated Code:**
```javascript
import { c as _c } from "react/compiler-runtime";
export default function foo(x, y) {
const $ = _c(4);
if (x) {
let t0;
if ($[0] !== y) {
t0 = foo(false, y);
$[0] = y;
$[1] = t0;
} else {
t0 = $[1];
}
return t0;
}
const t0 = y * 10;
let t1;
if ($[2] !== t0) {
t1 = [t0];
$[2] = t0;
$[3] = t1;
} else {
t1 = $[3];
}
return t1;
}
```
The promoted temporaries (`#t5`, `#t9`, `#t10`) become the named variables (`t0`, `t1`) in the output after `renameVariables` runs.

View File

@@ -0,0 +1,200 @@
# renameVariables
## File
`src/ReactiveScopes/RenameVariables.ts`
## Purpose
This pass ensures that every named variable in the function has a unique name that doesn't conflict with other variables in the same block scope or with global identifiers. After scope construction and temporary promotion, variables from different source scopes may end up in the same reactive block - this pass resolves any naming conflicts.
The pass also converts the `#t{id}` promoted temporary names into clean output names like `t0`, `t1`, etc.
## Input Invariants
- The ReactiveFunction has been through `promoteUsedTemporaries`
- Variables may have names that conflict with:
- Other variables in the same or ancestor block scope
- Global identifiers referenced by the function
- Promoted temporaries with `#t{id}` or `#T{id}` naming
- The function parameters have names (either from source or promoted)
## Output Guarantees
- Every named variable has a unique name within its scope
- No variable shadows a global identifier referenced by the function
- Promoted temporaries are renamed to `t0`, `t1`, ... (for regular temps)
- Promoted JSX temporaries are renamed to `T0`, `T1`, ... (for JSX tags)
- Conflicting source names get disambiguated with `$` suffix (e.g., `foo$0`, `foo$1`)
- Returns a `Set<string>` of all unique variable names in the function
## Algorithm
### Phase 1: Collect Referenced Globals
Uses `collectReferencedGlobals(fn)` to build a set of all global identifiers referenced by the function. Variable names must not conflict with these.
### Phase 2: Rename with Scope Stack
The `Scopes` class maintains:
```typescript
class Scopes {
#seen: Map<DeclarationId, IdentifierName> = new Map(); // Canonical name for each declaration
#stack: Array<Map<string, DeclarationId>> = [new Map()]; // Block scope stack
#globals: Set<string>; // Global names to avoid
names: Set<ValidIdentifierName> = new Set(); // All assigned names
}
```
### Renaming Logic
```typescript
visit(identifier: Identifier): void {
// Skip unnamed identifiers
if (originalName === null) return;
// If we've already named this declaration, reuse that name
const mappedName = this.#seen.get(identifier.declarationId);
if (mappedName !== undefined) {
identifier.name = mappedName;
return;
}
// Find a unique name
let name = originalName.value;
let id = 0;
// Promoted temporaries start with t0/T0
if (isPromotedTemporary(originalName.value)) {
name = `t${id++}`;
} else if (isPromotedJsxTemporary(originalName.value)) {
name = `T${id++}`;
}
// Increment until we find a unique name
while (this.#lookup(name) !== null || this.#globals.has(name)) {
if (isPromotedTemporary(...)) {
name = `t${id++}`;
} else if (isPromotedJsxTemporary(...)) {
name = `T${id++}`;
} else {
name = `${originalName.value}$${id++}`; // foo$0, foo$1, etc.
}
}
identifier.name = makeIdentifierName(name);
this.#seen.set(identifier.declarationId, identifier.name);
}
```
### Scope Management
```typescript
enter(fn: () => void): void {
this.#stack.push(new Map());
fn();
this.#stack.pop();
}
#lookup(name: string): DeclarationId | null {
// Search from innermost to outermost scope
for (let i = this.#stack.length - 1; i >= 0; i--) {
const entry = this.#stack[i].get(name);
if (entry !== undefined) return entry;
}
return null;
}
```
### Visitor Pattern
```typescript
class Visitor extends ReactiveFunctionVisitor<Scopes> {
override visitBlock(block: ReactiveBlock, state: Scopes): void {
state.enter(() => {
this.traverseBlock(block, state);
});
}
override visitScope(scope: ReactiveScopeBlock, state: Scopes): void {
// Visit scope declarations first
for (const [_, declaration] of scope.scope.declarations) {
state.visit(declaration.identifier);
}
this.traverseScope(scope, state);
}
override visitPlace(id: InstructionId, place: Place, state: Scopes): void {
state.visit(place.identifier);
}
}
```
## Edge Cases
### Shadowed Variables
When the compiler merges scopes that had shadowing in the source:
```javascript
function foo() {
const x = 1;
{
const x = 2; // Shadowed in source
}
}
```
If both `x` declarations end up in the same compiled scope, they become `x` and `x$0`.
### Global Name Conflicts
If a local variable would conflict with a referenced global:
```javascript
function foo() {
const Math = 1; // Conflicts with global Math if used
}
```
The local gets renamed to `Math$0` if `Math` global is referenced.
### Nested Functions
The pass recursively processes nested function expressions, entering a new scope for each function body.
### Pruned Scopes
Pruned scopes don't create a new block scope in the output - the pass traverses their instructions without entering a new scope level.
### DeclarationId Consistency
The pass uses `DeclarationId` to track which identifiers refer to the same variable, ensuring all references get the same renamed name.
## TODOs
None in the source file.
## Example
### Fixture: `simple.js`
**Before RenameVariables:**
```
scope @0 [...] declarations=[#t5$19_@0]
scope @1 [...] dependencies=[#t9$22] declarations=[#t10$23_@1]
```
**After RenameVariables:**
```
scope @0 [...] declarations=[t0$19_@0]
scope @1 [...] dependencies=[t0$22] declarations=[t1$23_@1]
```
Key observations:
- `#t5$19_@0` becomes `t0$19_@0` (first temporary in scope)
- `#t9$22` becomes `t0$22` (first temporary in a different block scope)
- `#t10$23_@1` becomes `t1$23_@1` (second temporary in that block)
- The `#t` prefix is removed and sequential numbering is applied
**Generated Code:**
```javascript
export default function foo(x, y) {
const $ = _c(4);
if (x) {
let t0; // Was #t5
if ($[0] !== y) {
t0 = foo(false, y);
// ...
}
return t0;
}
const t0 = y * 10; // Was #t9, reuses t0 since different block scope
let t1; // Was #t10
// ...
}
```
The pass produces clean, readable output with minimal variable names while avoiding conflicts.

View File

@@ -0,0 +1,286 @@
# codegenReactiveFunction
## File
`src/ReactiveScopes/CodegenReactiveFunction.ts`
## Purpose
This is the final pass that converts the ReactiveFunction representation back into a Babel AST. It generates the memoization code that makes React components and hooks efficient by:
1. Creating the `useMemoCache` call to allocate cache slots
2. Generating dependency comparisons to check if values have changed
3. Emitting conditional blocks that skip computation when cached values are valid
4. Storing computed values in the cache
5. Loading cached values when dependencies haven't changed
## Input Invariants
- The ReactiveFunction has been through all prior passes
- All identifiers that need names have been promoted and renamed
- Reactive scopes have finalized `dependencies`, `declarations`, and `reassignments`
- Early returns have been transformed with sentinel values (via `propagateEarlyReturns`)
- Pruned scopes are marked with `kind: 'pruned-scope'`
- Unique identifiers set is available to avoid naming conflicts
## Output Guarantees
- Returns a `CodegenFunction` with Babel AST `body`
- All reactive scopes become if-else blocks checking dependencies
- The `$` cache array is properly sized with `useMemoCache(n)`
- Each dependency and output gets its own cache slot
- Pruned scopes emit their instructions inline without memoization
- Early returns use the sentinel pattern with post-scope checks
- Statistics are collected: `memoSlotsUsed`, `memoBlocks`, `memoValues`, etc.
## Algorithm
### Entry Point: codegenFunction
```typescript
export function codegenFunction(fn: ReactiveFunction): Result<CodegenFunction, CompilerError> {
const cx = new Context(...);
// Optional: Fast Refresh source hash tracking
if (enableResetCacheOnSourceFileChanges) {
fastRefreshState = { cacheIndex: cx.nextCacheIndex, hash: sha256(source) };
}
const compiled = codegenReactiveFunction(cx, fn);
// Prepend useMemoCache call if any cache slots used
if (cacheCount !== 0) {
body.unshift(
t.variableDeclaration('const', [
t.variableDeclarator(
t.identifier('$'),
t.callExpression(t.identifier('useMemoCache'), [t.numericLiteral(cacheCount)])
)
])
);
}
return compiled;
}
```
### Context Class
Tracks state during codegen:
```typescript
class Context {
#nextCacheIndex: number = 0; // Allocates cache slots
#declarations: Set<DeclarationId> = new Set(); // Tracks declared variables
temp: Temporaries; // Maps identifiers to their expressions
errors: CompilerError;
get nextCacheIndex(): number {
return this.#nextCacheIndex++; // Returns and increments
}
}
```
### codegenReactiveScope
The core of memoization code generation:
```typescript
function codegenReactiveScope(cx: Context, statements: Array<t.Statement>,
scope: ReactiveScope, block: ReactiveBlock): void {
const changeExpressions: Array<t.Expression> = [];
const cacheStoreStatements: Array<t.Statement> = [];
const cacheLoadStatements: Array<t.Statement> = [];
// 1. Generate dependency checks
for (const dep of scope.dependencies) {
const index = cx.nextCacheIndex;
changeExpressions.push(
t.binaryExpression('!==',
t.memberExpression(t.identifier('$'), t.numericLiteral(index), true),
codegenDependency(cx, dep)
)
);
cacheStoreStatements.push(
t.assignmentExpression('=', $[index], dep)
);
}
// 2. Generate output cache slots
for (const {identifier} of scope.declarations) {
const index = cx.nextCacheIndex;
// Declare variable if not already declared
if (!cx.hasDeclared(identifier)) {
statements.push(t.variableDeclaration('let', [t.variableDeclarator(name, null)]));
}
cacheLoads.push({name, index, value: name});
}
// 3. Build test condition
let testCondition = changeExpressions.reduce((acc, expr) =>
t.logicalExpression('||', acc, expr)
);
// 4. If no dependencies, use sentinel check
if (testCondition === null) {
testCondition = t.binaryExpression('===',
$[firstOutputIndex],
t.callExpression(Symbol.for, ['react.memo_cache_sentinel'])
);
}
// 5. Generate the memoization if-else
statements.push(
t.ifStatement(
testCondition,
computationBlock, // Compute + store in cache
cacheLoadBlock // Load from cache
)
);
}
```
### Generated Structure
For a scope with dependencies `[a, b]` and output `result`:
```javascript
let result;
if ($[0] !== a || $[1] !== b) {
// Computation block
result = compute(a, b);
// Store dependencies
$[0] = a;
$[1] = b;
// Store output
$[2] = result;
} else {
// Load from cache
result = $[2];
}
```
### Early Return Handling
When a scope has an early return (from `propagateEarlyReturns`):
```typescript
// Before scope: initialize sentinel
t0 = Symbol.for("react.early_return_sentinel");
// Scope generates labeled block
bb0: {
// ... computation ...
if (cond) {
t0 = returnValue;
break bb0;
}
}
// After scope: check for early return
if (t0 !== Symbol.for("react.early_return_sentinel")) {
return t0;
}
```
### Pruned Scopes
Pruned scopes emit their instructions inline without memoization:
```typescript
case 'pruned-scope': {
const scopeBlock = codegenBlockNoReset(cx, item.instructions);
statements.push(...scopeBlock.body); // Inline, no memoization
break;
}
```
## Edge Cases
### Zero Dependencies
Scopes with no dependencies use a sentinel value check instead:
```javascript
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
// First render only
}
```
### Fast Refresh / HMR
When `enableResetCacheOnSourceFileChanges` is enabled, the generated code includes a source hash check that resets the cache when the source changes:
```javascript
if ($[0] !== "source_hash_abc123") {
for (let $i = 0; $i < cacheCount; $i++) {
$[$i] = Symbol.for("react.memo_cache_sentinel");
}
$[0] = "source_hash_abc123";
}
```
### Labeled Breaks
Control flow with labeled breaks (for early returns or loop exits) uses `codegenLabel` to generate consistent label names:
```typescript
function codegenLabel(id: BlockId): string {
return `bb${id}`; // e.g., "bb0", "bb1"
}
```
### Nested Functions
Function expressions and object methods are recursively processed with their own contexts.
### FBT/Internationalization
Special handling for FBT operands ensures they're memoized in the same scope for correct internationalization behavior.
## Statistics Collected
```typescript
type CodegenFunction = {
memoSlotsUsed: number; // Total cache slots allocated
memoBlocks: number; // Number of reactive scopes
memoValues: number; // Total memoized values
prunedMemoBlocks: number; // Scopes that were pruned
prunedMemoValues: number; // Values in pruned scopes
hasInferredEffect: boolean;
};
```
## TODOs
None in the source file.
## Example
### Fixture: `simple.js`
**Input:**
```javascript
export default function foo(x, y) {
if (x) {
return foo(false, y);
}
return [y * 10];
}
```
**Generated Code:**
```javascript
import { c as _c } from "react/compiler-runtime";
export default function foo(x, y) {
const $ = _c(4); // Allocate 4 cache slots
if (x) {
let t0;
if ($[0] !== y) { // Check dependency
t0 = foo(false, y); // Compute
$[0] = y; // Store dependency
$[1] = t0; // Store output
} else {
t0 = $[1]; // Load from cache
}
return t0;
}
const t0 = y * 10;
let t1;
if ($[2] !== t0) { // Check dependency
t1 = [t0]; // Compute
$[2] = t0; // Store dependency
$[3] = t1; // Store output
} else {
t1 = $[3]; // Load from cache
}
return t1;
}
```
Key observations:
- `_c(4)` allocates 4 cache slots total
- First scope uses slots 0-1: slot 0 for `y` dependency, slot 1 for `t0` output
- Second scope uses slots 2-3: slot 2 for `t0` (the computed `y * 10`), slot 3 for `t1` (the array)
- Each scope has an if-else structure: compute/store vs load
- The memoization ensures referential equality of the returned array when `y` hasn't changed

View File

@@ -0,0 +1,132 @@
# optimizePropsMethodCalls
## File
`src/Optimization/OptimizePropsMethodCalls.ts`
## Purpose
This pass converts method calls on the props object to regular function calls. Method calls like `props.onClick()` are transformed to `const t0 = props.onClick; t0()`. This normalization enables better analysis and optimization by the compiler.
The transformation is important because method calls have different semantics than regular calls - the receiver (`props`) would normally be passed as `this` to the method. For React props, methods are typically just callback functions where `this` binding doesn't matter, so converting them to regular calls is safe and enables better memoization.
## Input Invariants
- The function has been through type inference
- Props parameters are typed as `TObject<BuiltInProps>`
## Output Guarantees
- All `MethodCall` instructions where the receiver has props type are converted to `CallExpression`
- The method property becomes the callee of the call
- Arguments are preserved exactly
## Algorithm
```typescript
export function optimizePropsMethodCalls(fn: HIRFunction): void {
for (const [, block] of fn.body.blocks) {
for (let i = 0; i < block.instructions.length; i++) {
const instr = block.instructions[i]!;
if (
instr.value.kind === 'MethodCall' &&
isPropsType(instr.value.receiver.identifier)
) {
// Transform: props.onClick(arg)
// To: const t0 = props.onClick; t0(arg)
instr.value = {
kind: 'CallExpression',
callee: instr.value.property, // The method becomes the callee
args: instr.value.args,
loc: instr.value.loc,
};
}
}
}
}
function isPropsType(identifier: Identifier): boolean {
return (
identifier.type.kind === 'Object' &&
identifier.type.shapeId === BuiltInPropsId
);
}
```
## Edge Cases
### Non-Props Method Calls
Method calls on non-props objects are left unchanged:
```javascript
// Unchanged - array.map is not on props
array.map(x => x * 2)
// Unchanged - obj is not props
obj.method()
```
### Props Type Detection
The pass uses type information to identify props:
```javascript
function Component(props) {
// props has type TObject<BuiltInProps>
props.onClick(); // Transformed
}
function Regular(obj) {
// obj has unknown type
obj.onClick(); // Not transformed
}
```
### Nested Props Access
Only direct method calls on props are transformed:
```javascript
props.onClick(); // Transformed
props.nested.onClick(); // Not transformed (receiver is props.nested, not props)
```
### Arrow Function Callbacks
Works with any method on props:
```javascript
props.onChange(value); // Transformed
props.onSubmit(data); // Transformed
props.validate(input); // Transformed
```
## TODOs
None in the source file.
## Example
### Fixture: Using props method
**Input:**
```javascript
function Component(props) {
return <button onClick={() => props.onClick()} />;
}
```
**Before OptimizePropsMethodCalls:**
```
[1] $5 = Function @context[props$1] ...
<<anonymous>>():
[1] $2 = LoadLocal props$1
[2] $3 = PropertyLoad $2.onClick
[3] $4 = MethodCall $2.$3() // Method call on props
[4] Return Void
```
**After OptimizePropsMethodCalls:**
```
[1] $5 = Function @context[props$1] ...
<<anonymous>>():
[1] $2 = LoadLocal props$1
[2] $3 = PropertyLoad $2.onClick
[3] $4 = Call $3() // Now a regular call
[4] Return Void
```
Key observations:
- `MethodCall $2.$3()` becomes `Call $3()`
- The property load (`$3 = PropertyLoad $2.onClick`) is preserved
- The receiver (`$2`) is no longer part of the call
- This enables the compiler to analyze `onClick` as a regular function

View File

@@ -0,0 +1,187 @@
# optimizeForSSR
## File
`src/Optimization/OptimizeForSSR.ts`
## Purpose
This pass applies Server-Side Rendering (SSR) specific optimizations. During SSR, React renders components to HTML strings without mounting them in the DOM. This means:
1. **Effects don't run** - `useEffect` and `useLayoutEffect` are no-ops
2. **Event handlers aren't needed** - There's no DOM to attach handlers to
3. **State is never updated** - Components render once with initial state
4. **Refs aren't attached** - There's no DOM to ref
The pass leverages these SSR characteristics to inline and simplify code, removing unnecessary runtime overhead.
## Input Invariants
- The function has been through type inference
- Hook types are properly identified (useState, useReducer, useEffect, etc.)
- Function types for callbacks are properly inferred
## Output Guarantees
- `useState(initialValue)` is inlined to just `[initialValue, noop]`
- `useReducer(reducer, initialArg, init?)` is inlined to `[init ? init(initialArg) : initialArg, noop]`
- `useEffect` and `useLayoutEffect` calls are removed entirely
- Event handler functions (functions that call setState) are replaced with empty functions
- Ref-typed values are removed from JSX props
## Algorithm
### Phase 1: Identify Inlinable State
```typescript
const inlinedState = new Map<IdentifierId, InstructionValue>();
for (const instr of block.instructions) {
if (isUseStateCall(instr)) {
// Store the initial value for inlining
inlinedState.set(instr.lvalue.id, {
kind: 'ArrayExpression',
elements: [initialValue, noopFunction],
});
}
if (isUseReducerCall(instr)) {
// Compute initial state and store for inlining
const initialState = init ? callInit(initialArg) : initialArg;
inlinedState.set(instr.lvalue.id, {
kind: 'ArrayExpression',
elements: [initialState, noopFunction],
});
}
}
```
### Phase 2: Inline State Hooks
Replace useState/useReducer with their computed initial values:
```typescript
// Before:
$0 = useState(0)
[state, setState] = $0
// After (inlined):
$0 = [0, () => {}]
[state, setState] = $0
```
### Phase 3: Remove Effects
```typescript
if (isUseEffectCall(instr) || isUseLayoutEffectCall(instr)) {
// Remove the instruction entirely
block.instructions.splice(i, 1);
}
```
### Phase 4: Identify and Neuter Event Handlers
```typescript
// Functions that capture and call setState are event handlers
if (capturesSetState(functionExpr)) {
// Replace with empty function
instr.value = {
kind: 'FunctionExpression',
params: originalParams,
body: emptyBody,
};
}
```
### Phase 5: Remove Ref Props
```typescript
if (isJSX(instr) && hasRefProp(instr)) {
// Remove ref={...} from JSX props
removeRefProp(instr.value);
}
```
## Edge Cases
### useState with Function Initializer
When `useState` receives a function initializer, it must be called:
```javascript
// useState(() => expensive())
// SSR: Call the initializer to get the value
const [state] = [expensiveComputation(), noop];
```
### useReducer with Init Function
The optional `init` function is called with `initialArg`:
```javascript
// useReducer(reducer, arg, init)
// SSR: [init(arg), noop]
```
### Nested State Setters
Functions that transitively call setState are also event handlers:
```javascript
function outer() {
function inner() {
setState(x); // inner is event handler
}
inner(); // outer is also event handler
}
```
### Conditional Event Handlers
Event handler detection is conservative - if a function might call setState, it's treated as an event handler.
### Refs in Nested Objects
Only direct `ref` props on JSX are removed:
```javascript
<div ref={myRef} /> // ref removed
<div config={{ref: myRef}} /> // ref NOT removed (nested)
```
## TODOs
None in the source file.
## Example
### Fixture: `ssr/optimize-ssr.js`
**Input:**
```javascript
function Component() {
const [state, setState] = useState(0);
const ref = useRef(null);
const onChange = (e) => {
setState(e.target.value);
};
useEffect(() => {
log(ref.current.value);
});
return <input value={state} onChange={onChange} ref={ref} />;
}
```
**After SSR Optimization:**
```javascript
function Component() {
const $ = _c(1);
// useState inlined to [initialValue, noop]
const [state] = [0, () => {}];
// useRef returns object with current: null
const ref = { current: null };
// Event handler replaced with noop (it calls setState)
const onChange = () => {};
// useEffect removed entirely (no-op on SSR)
// ref prop removed from JSX
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = <input value={state} onChange={onChange} />;
$[0] = t0;
} else {
t0 = $[0];
}
return t0;
}
```
Key observations:
- `useState(0)` becomes `[0, () => {}]` - no hook call
- `useEffect(...)` is removed entirely
- `onChange` is replaced with empty function since it called `setState`
- `ref={ref}` prop is removed from JSX
- SSR output is simpler and has less runtime overhead

View File

@@ -0,0 +1,224 @@
# outlineJSX
## File
`src/Optimization/OutlineJsx.ts`
## Purpose
This pass outlines nested JSX elements into separate component functions. When a callback function contains JSX, this pass can extract that JSX into a new component, which enables:
1. **Better code splitting** - Outlined components can be lazily loaded
2. **Memoization at component boundaries** - React's reconciliation can skip unchanged subtrees
3. **Reduced closure captures** - Outlined components receive props explicitly
The pass specifically targets JSX within callbacks (like `.map()` callbacks) rather than top-level component returns.
## Input Invariants
- The `enableJsxOutlining` feature flag must be enabled
- The function must be a React component or hook
- JSX must appear within a nested function expression (callback)
## Output Guarantees
- Nested functions containing only JSX returns are extracted as separate components
- The original callback is replaced with a call to the outlined component
- Captured variables become explicit props to the outlined component
- The outlined component is registered with the environment for emission
## Algorithm
### Phase 1: Identify Outlinable JSX
```typescript
function outlineJsxImpl(fn: HIRFunction, outlinedFns: Array<HIRFunction>): void {
for (const [, block] of fn.body.blocks) {
for (const instr of block.instructions) {
if (instr.value.kind === 'FunctionExpression') {
const innerFn = instr.value.loweredFunc.func;
// Check if function only returns JSX
if (canOutline(innerFn)) {
const outlined = createOutlinedComponent(innerFn);
outlinedFns.push(outlined);
replaceWithComponentCall(instr, outlined);
}
}
}
}
}
```
### Phase 2: Check Outlinability
```typescript
function canOutline(fn: HIRFunction): boolean {
// Must have exactly one block with only JSX-related instructions
// Must end with returning JSX
// Must not have complex control flow
return (
fn.body.blocks.size === 1 &&
returnsJSX(fn) &&
!hasComplexControlFlow(fn)
);
}
```
### Phase 3: Create Outlined Component
```typescript
function createOutlinedComponent(fn: HIRFunction): HIRFunction {
// Convert captured context to props
const props = fn.context.map(capture => ({
name: capture.identifier.name,
type: capture.identifier.type,
}));
// Create new component function
return {
...fn,
params: [{kind: 'Identifier', name: 'props', ...}],
context: [], // No captures - all via props
};
}
```
### Phase 4: Replace Original Callback
```typescript
function replaceWithComponentCall(instr: Instruction, outlined: HIRFunction): void {
// Original: items.map(item => <Stringify item={item} />)
// Becomes: items.map(item => <OutlinedComponent item={item} />)
instr.value = {
kind: 'JSX',
tag: {kind: 'LoadGlobal', name: outlined.id},
props: capturedVariablesToProps(instr.value.context),
};
}
```
### Phase 5: Register Outlined Functions
```typescript
export function outlineJSX(fn: HIRFunction): void {
const outlinedFns: Array<HIRFunction> = [];
outlineJsxImpl(fn, outlinedFns);
for (const outlinedFn of outlinedFns) {
fn.env.outlineFunction(outlinedFn, 'Component');
}
}
```
## Edge Cases
### Context Captures
Variables captured by the callback become props:
```javascript
// Before:
items.map(item => <Card key={item.id} user={currentUser} item={item} />)
// After (outlined):
function OutlinedCard(props) {
return <Card key={props.item.id} user={props.currentUser} item={props.item} />;
}
items.map(item => <OutlinedCard currentUser={currentUser} item={item} />)
```
### Complex Control Flow
Callbacks with conditionals or loops are not outlined:
```javascript
// Not outlined - has conditional
items.map(item => item.show ? <Card item={item} /> : null)
```
### Multiple JSX Returns
Only single-JSX-return callbacks are outlined:
```javascript
// Not outlined - multiple potential returns
items.map(item => {
if (item.type === 'a') return <TypeA item={item} />;
return <TypeB item={item} />;
})
```
### Top-Level JSX
Only JSX in nested callbacks is outlined, not component return values:
```javascript
function Component() {
return <div />; // Not outlined - this is the component's return
}
```
### Recursive Outlining
The pass recursively processes outlined components to outline their nested JSX.
## TODOs
None in the source file.
## Example
### Fixture: `outlined-helper.js`
**Input:**
```javascript
// @enableFunctionOutlining
function Component(props) {
return (
<div>
{props.items.map(item => (
<Stringify key={item.id} item={item.name} />
))}
</div>
);
}
```
**After OutlineJSX:**
```
// Outlined component:
function _outlined_Component$1(props) {
return <Stringify key={props.item.id} item={props.item.name} />;
}
// Original component modified:
function Component(props) {
return (
<div>
{props.items.map(item => (
<_outlined_Component$1 item={item} />
))}
</div>
);
}
```
**Generated Code:**
```javascript
function _outlined_Component$1(props) {
const $ = _c(2);
const item = props.item;
let t0;
if ($[0] !== item.id || $[1] !== item.name) {
t0 = <Stringify key={item.id} item={item.name} />;
$[0] = item.id;
$[1] = item.name;
} else {
t0 = $[1];
}
return t0;
}
function Component(props) {
const $ = _c(2);
let t0;
if ($[0] !== props.items) {
t0 = props.items.map((item) => <_outlined_Component$1 item={item} />);
$[0] = props.items;
$[1] = t0;
} else {
t0 = $[1];
}
return <div>{t0}</div>;
}
```
Key observations:
- The map callback JSX is extracted into `_outlined_Component$1`
- The `item` variable becomes a prop instead of a closure capture
- The outlined component gets its own memoization cache
- This enables React to skip re-rendering unchanged list items

View File

@@ -0,0 +1,169 @@
# outlineFunctions
## File
`src/Optimization/OutlineFunctions.ts`
## Purpose
This pass outlines pure function expressions that have no captured context into top-level helper functions. By moving these functions outside the component, they become truly static and can be shared across renders without any memoization overhead.
A function with no captured context is completely self-contained - it only uses its parameters and globals. Such functions don't need to be recreated on each render and can be hoisted to module scope.
## Input Invariants
- The `enableFunctionOutlining` feature flag must be enabled
- Functions must have `context.length === 0` (no captured variables)
- Functions must be anonymous (no `id` property)
- Functions must not be FBT macro operands (tracked by `fbtOperands` parameter)
## Output Guarantees
- Pure function expressions are replaced with `LoadGlobal` of the outlined function
- Outlined functions are registered with the environment for emission
- The original instruction is transformed to load the global
## Algorithm
```typescript
export function outlineFunctions(
fn: HIRFunction,
fbtOperands: Set<IdentifierId>,
): void {
for (const [, block] of fn.body.blocks) {
for (let i = 0; i < block.instructions.length; i++) {
const instr = block.instructions[i]!;
if (
instr.value.kind === 'FunctionExpression' &&
instr.value.loweredFunc.func.context.length === 0 &&
instr.value.loweredFunc.func.id === null &&
!fbtOperands.has(instr.lvalue.identifier.id)
) {
// Outline this function
const outlinedId = fn.env.outlineFunction(
instr.value.loweredFunc.func,
'helper',
);
// Replace with LoadGlobal
instr.value = {
kind: 'LoadGlobal',
binding: {
kind: 'ModuleLocal',
name: outlinedId,
},
loc: instr.value.loc,
};
}
}
}
}
```
## Edge Cases
### Functions with Context
Functions that capture variables are not outlined:
```javascript
function Component(props) {
const x = props.value;
const fn = () => x * 2; // Captures x, not outlined
}
```
### Named Functions
Functions with explicit names are not outlined:
```javascript
const foo = function namedFn() { ... }; // Has id, not outlined
```
### FBT Operands
Functions used as FBT operands cannot be outlined due to translation requirements:
```javascript
<fbt>
Hello <fbt:param name="user">{() => getName()}</fbt:param>
</fbt>
// The function cannot be outlined - FBT needs it inline
```
### Arrow Functions vs Function Expressions
Both arrow functions and function expressions are candidates:
```javascript
const a = () => 1; // Outlined if no context
const b = function() {}; // Outlined if no context
```
### Recursive Functions
Self-referencing functions cannot be outlined (they would have themselves in context):
```javascript
const fib = (n) => n <= 1 ? n : fib(n-1) + fib(n-2); // References self
```
## TODOs
None in the source file.
## Example
### Fixture: `outlined-helper.js`
**Input:**
```javascript
// @enableFunctionOutlining
function Component(props) {
return (
<div>
{props.items.map(item => (
<Stringify key={item.id} item={item.name} />
))}
</div>
);
}
```
**Analysis:**
The map callback `item => <Stringify .../>` has one captured variable: nothing from the component (only uses `item` parameter). However, it receives `item` as a parameter, not from context.
If we have a truly pure helper:
```javascript
// @enableFunctionOutlining
function Component(props) {
const double = (x) => x * 2; // No context, pure
return <div>{double(props.value)}</div>;
}
```
**After OutlineFunctions:**
```
// Outlined to module scope:
function _outlined_double$1(x) {
return x * 2;
}
// In component:
[1] $1 = LoadGlobal _outlined_double$1 // Instead of FunctionExpression
[2] StoreLocal Const double = $1
```
**Generated Code:**
```javascript
function _outlined_double$1(x) {
return x * 2;
}
function Component(props) {
const $ = _c(2);
const double = _outlined_double$1; // Just a reference, no recreation
let t0;
if ($[0] !== props.value) {
t0 = <div>{double(props.value)}</div>;
$[0] = props.value;
$[1] = t0;
} else {
t0 = $[1];
}
return t0;
}
```
Key observations:
- The pure function is hoisted to module scope
- The component just references the outlined function
- No memoization needed for the function itself
- Reduces runtime overhead by avoiding function recreation

View File

@@ -0,0 +1,231 @@
# memoizeFbtAndMacroOperandsInSameScope
## File
`src/ReactiveScopes/MemoizeFbtAndMacroOperandsInSameScope.ts`
## Purpose
This pass ensures that FBT (Facebook Translation) expressions and their operands are memoized within the same reactive scope. FBT is Facebook's internationalization system that requires special handling to ensure translations work correctly.
The key insight is that FBT operands must be computed and frozen together with the FBT call itself. If operands were memoized in separate scopes, the translation system could receive stale operand values when only some inputs change.
## Input Invariants
- The function has been through type inference
- FBT calls (`fbt`, `fbt.c`, `fbt:param`, etc.) are properly identified
- Custom macros are configured in `fn.env.config.customMacros`
- Reactive scope variables have been inferred
## Output Guarantees
- All operands of FBT calls are assigned to the same reactive scope as the FBT call
- The `fbtOperands` set is returned for use by other passes (e.g., `outlineFunctions`)
- Operand scope assignments use either transitive or shallow inlining based on macro definition
## Algorithm
### Phase 1: Collect Macro Kinds
```typescript
const macroKinds = new Map<Macro, MacroDefinition>([
...Array.from(FBT_TAGS.entries()), // Built-in fbt tags
...(fn.env.config.customMacros ?? []).map(([name, def]) => [name, def]),
]);
```
### Phase 2: Populate Macro Tags
```typescript
function populateMacroTags(
fn: HIRFunction,
macroKinds: Map<Macro, MacroDefinition>,
): Map<IdentifierId, MacroDefinition> {
const macroTags = new Map();
for (const instr of allInstructions(fn)) {
if (isLoadGlobal(instr) || isPropertyLoad(instr)) {
const name = getName(instr);
if (macroKinds.has(name)) {
macroTags.set(instr.lvalue.id, macroKinds.get(name));
}
}
}
return macroTags;
}
```
### Phase 3: Merge Macro Arguments
```typescript
function mergeMacroArguments(
fn: HIRFunction,
macroTags: Map<IdentifierId, MacroDefinition>,
macroKinds: Map<Macro, MacroDefinition>,
): Set<IdentifierId> {
const macroValues = new Set<IdentifierId>();
for (const instr of allInstructions(fn)) {
if (isCall(instr) || isMethodCall(instr) || isJSX(instr)) {
const callee = getCallee(instr);
const macroDef = macroTags.get(callee.id);
if (macroDef !== undefined) {
// Mark all operands to be in same scope
for (const operand of getOperands(instr)) {
macroValues.add(operand.id);
// Merge scope to match macro call scope
if (macroDef.inlineLevel === InlineLevel.Transitive) {
mergeScopesTransitively(operand, instr.lvalue);
} else {
mergeScopes(operand, instr.lvalue);
}
}
}
}
}
return macroValues;
}
```
### InlineLevel Types
```typescript
enum InlineLevel {
Shallow, // Only merge direct operands
Transitive, // Merge operands and their dependencies
}
```
## Edge Cases
### Nested FBT Params
FBT params can be nested, and all levels must be in the same scope:
```javascript
<fbt>
Hello <fbt:param name="user">
<fbt:param name="firstName">{user.firstName}</fbt:param>
</fbt:param>
</fbt>
```
### FBT with Complex Expressions
Complex expressions as operands have their entire dependency chain merged:
```javascript
<fbt>
Count: <fbt:param name="count">{items.length * multiplier}</fbt:param>
</fbt>
// Both items.length and multiplier expressions are merged into fbt scope
```
### Custom Macros
User-defined macros can specify their inlining behavior:
```typescript
customMacros: [
['myMacro', { inlineLevel: InlineLevel.Transitive }],
]
```
### Method Calls on FBT
`fbt.param()`, `fbt.plural()`, etc. are handled as method calls:
```javascript
fbt(
fbt.param('count', items.length), // MethodCall on fbt
'description'
)
```
### JSX vs Call Syntax
Both JSX and call syntax for FBT are handled:
```javascript
// JSX syntax
<fbt desc="greeting">Hello</fbt>
// Call syntax
fbt('Hello', 'greeting')
```
## Built-in FBT Tags
The pass recognizes these FBT constructs:
- `fbt` / `fbt.c` - Main translation functions
- `fbt:param` - Parameter substitution
- `fbt:plural` - Plural handling
- `fbt:enum` - Enumeration values
- `fbt:name` - Name parameters
- `fbt:pronoun` - Pronoun handling
- `fbs` - Simple string translation
## TODOs
None in the source file.
## Example
### Fixture: `fbt/fbt-call.js`
**Input:**
```javascript
function Component(props) {
const text = fbt(
`${fbt.param('count', props.count)} items`,
'Number of items'
);
return <div>{text}</div>;
}
```
**Before MemoizeFbtAndMacroOperandsInSameScope:**
```
[1] $18 = LoadGlobal import fbt from 'fbt'
[2] $19 = LoadGlobal import fbt from 'fbt'
[3] $20_@0[3:8] = PropertyLoad $19.param
[4] $21 = "(key) count"
[5] $22 = LoadLocal props$17
[6] $23 = PropertyLoad $22.count
[7] $24_@0[3:8] = MethodCall $19.$20_@0($21, $23) // fbt.param call
[8] $25 = `${$24_@0} items`
[9] $26 = "(description) Number of items"
[10] $27_@1 = Call $18($25, $26) // fbt call
```
**After MemoizeFbtAndMacroOperandsInSameScope:**
```
[1] $18_@1[1:11] = LoadGlobal import fbt from 'fbt' // Merged to @1
[2] $19 = LoadGlobal import fbt from 'fbt'
[3] $20_@0[3:8] = PropertyLoad $19.param
[4] $21 = "(key) count"
[5] $22 = LoadLocal props$17
[6] $23 = PropertyLoad $22.count
[7] $24_@1[1:11] = MethodCall $19.$20_@0($21, $23) // Merged to @1
[8] $25_@1[1:11] = `${$24_@1} items` // Merged to @1
[9] $26_@1[1:11] = "(description) Number of items" // Merged to @1
[10] $27_@1[1:11] = Call $18_@1($25_@1, $26_@1) // Main fbt scope @1
```
**Generated Code:**
```javascript
function Component(props) {
const $ = _c(3);
let t0;
if ($[0] !== props.count) {
// All fbt operands computed in same memoization block
t0 = fbt(
`${fbt.param("count", props.count)} items`,
"Number of items"
);
$[0] = props.count;
$[1] = t0;
} else {
t0 = $[1];
}
const text = t0;
let t1;
if ($[2] === Symbol.for("react.memo_cache_sentinel")) {
t1 = <div>{text}</div>;
$[2] = t1;
} else {
t1 = $[2];
}
return t1;
}
```
Key observations:
- All FBT-related operations are in the same memoization scope `@1`
- `fbt.param`, template literal, and `fbt` call are memoized together
- This ensures the translation system receives consistent operand values
- The entire translation is recomputed when any operand (`props.count`) changes

Some files were not shown because too many files have changed in this diff Show More