Commit Graph

137 Commits

Author SHA1 Message Date
Justin Grant
c88fb49d37
Improve DEV errors if string coercion throws (Temporal.*, Symbol, etc.) (#22064)
* Revise ESLint rules for string coercion

Currently, react uses `'' + value` to coerce mixed values to strings.
This code will throw for Temporal objects or symbols.

To make string-coercion safer and to improve user-facing error messages,
This commit adds a new ESLint rule called `safe-string-coercion`.

This rule has two modes: a production mode and a non-production mode.
* If the `isProductionUserAppCode` option is true, then `'' + value`
  coercions are allowed (because they're faster, although they may
  throw) and `String(value)` coercions are disallowed. Exception:
  when building error messages or running DEV-only code in prod
  files, `String()` should be used because it won't throw.
* If the `isProductionUserAppCode` option is false, then `'' + value`
  coercions are disallowed (because they may throw, and in non-prod
  code it's not worth the risk) and `String(value)` are allowed.

Production mode is used for all files which will be bundled with
developers' userland apps. Non-prod mode is used for all other React
code: tests, DEV blocks, devtools extension, etc.

In production mode, in addiiton to flagging `String(value)` calls,
the rule will also flag `'' + value` or `value + ''` coercions that may
throw. The rule is smart enough to silence itself in the following
"will never throw" cases:
* When the coercion is wrapped in a `typeof` test that restricts to safe
  (non-symbol, non-object) types. Example:
    if (typeof value === 'string' || typeof value === 'number') {
      thisWontReport('' + value);
    }
* When what's being coerced is a unary function result, because unary
   functions never return an object or a symbol.
* When the coerced value is a commonly-used numeric identifier:
  `i`, `idx`, or `lineNumber`.
* When the statement immeidately before the coercion is a DEV-only
  call to a function from shared/CheckStringCoercion.js. This call is a
  no-op in production, but in DEV it will show a console error
  explaining the problem, then will throw right after a long explanatory
  code comment so that debugger users will have an idea what's going on.
  The check function call must be in the following format:
    if (__DEV__) {
      checkXxxxxStringCoercion(value);
    };

Manually disabling the rule is usually not necessary because almost all
prod use of the `'' + value` pattern falls into one of the categories
above. But in the rare cases where the rule isn't smart enough to detect
safe usage (e.g. when a coercion is inside a nested ternary operator),
manually disabling the rule will be needed.

The rule should also be manually disabled in prod error handling code
where `String(value)` should be used for coercions, because it'd be
bad to throw while building an error message or stack trace!

The prod and non-prod modes have differentiated error messages to
explain how to do a proper coercion in that mode.

If a production check call is needed but is missing or incorrect
(e.g. not in a DEV block or not immediately before the coercion), then
a context-sensitive error message will be reported so that developers
can figure out what's wrong and how to fix the problem.

Because string coercions are now handled by the `safe-string-coercion`
rule, the `no-primitive-constructor` rule no longer flags `String()`
usage. It still flags `new String(value)` because that usage is almost
always a bug.

* Add DEV-only string coercion check functions

This commit adds DEV-only functions to check whether coercing
values to strings using the `'' + value` pattern will throw. If it will
throw, these functions will:
1. Display a console error with a friendly error message describing
   the problem and the developer can fix it.
2. Perform the coercion, which will throw. Right before the line where
   the throwing happens, there's a long code comment that will help
   debugger users (or others looking at the exception call stack) figure
   out what happened and how to fix the problem.

One of these check functions should be called before all string coercion
of user-provided values, except when the the coercion is guaranteed not
to throw, e.g.
* if inside a typeof check like `if (typeof value === 'string')`
* if coercing the result of a unary function like `+value` or `value++`
* if coercing a variable named in a whitelist of numeric identifiers:
  `i`, `idx`, or `lineNumber`.

The new `safe-string-coercion` internal ESLint rule enforces that
these check functions are called when they are required.

Only use these check functions in production code that will be bundled
with user apps.  For non-prod code (and for production error-handling
code), use `String(value)` instead which may be a little slower but will
never throw.

* Add failing tests for string coercion

Added failing tests to verify:
* That input, select, and textarea elements with value and defaultValue
  set to Temporal-like objects which will throw when coerced to string
  using the `'' + value` pattern.
* That text elements will throw for Temporal-like objects
* That dangerouslySetInnerHTML will *not* throw for Temporal-like
  objects because this value is not cast to a string before passing to
  the DOM.
* That keys that are Temporal-like objects will throw

All tests above validate the friendly error messages thrown.

* Use `String(value)` for coercion in non-prod files

This commit switches non-production code from `'' + value` (which
throws for Temporal objects and symbols) to instead use `String(value)`
which won't throw for these or other future plus-phobic types.

"Non-produciton code" includes anything not bundled into user apps:
* Tests and test utilities. Note that I didn't change legacy React
  test fixtures because I assumed it was good for those files to
  act just like old React, including coercion behavior.
* Build scripts
* Dev tools package - In addition to switching to `String`, I also
  removed special-case code for coercing symbols which is now
  unnecessary.

* Add DEV-only string coercion checks to prod files

This commit adds DEV-only function calls to to check if string coercion
using `'' + value` will throw, which it will if the value is a Temporal
object or a symbol because those types can't be added with `+`.

If it will throw, then in DEV these checks will show a console error
to help the user undertsand what went wrong and how to fix the
problem. After emitting the console error, the check functions will
retry the coercion which will throw with a call stack that's easy (or
at least easier!) to troubleshoot because the exception happens right
after a long comment explaining the issue. So whether the user is in
a debugger, looking at the browser console, or viewing the in-browser
DEV call stack, it should be easy to understand and fix the problem.

In most cases, the safe-string-coercion ESLint rule is smart enough to
detect when a coercion is safe. But in rare cases (e.g. when a coercion
is inside a ternary) this rule will have to be manually disabled.

This commit also switches error-handling code to use `String(value)`
for coercion, because it's bad to crash when you're trying to build
an error message or a call stack!  Because `String()` is usually
disallowed by the `safe-string-coercion` ESLint rule in production
code, the rule must be disabled when `String()` is used.
2021-09-27 10:05:07 -07:00
Andrew Clark
51e017c523
Revert "[Old server renderer] Retry error on client (#22399)"
Going to revert this until we figure out error reporting. It looks like
our downstream infra already supports some type of error recovery so
we might not need it here.
2021-09-22 12:32:28 -04:00
Andrew Clark
5a06072780
[Old server renderer] Retry error on client (#22399)
We're still in the process of migrating to the Fizz server renderer. In
the meantime, this makes the error semantics on the old server renderer
match the behavior of the new one: if an error is thrown, it triggers a
Suspense fallback, just as if it suspended (this part was already
implemented). Then the errored tree is retried on the client, where it
may recover and finish successfully.
2021-09-22 08:45:55 -07:00
Ricky
14bac6193a
Allow components to render undefined (#21869) 2021-07-13 15:48:11 -04:00
Ricky
c2c6ea1fde
Capture suspense boundaries with undefined fallbacks (#21854) 2021-07-12 14:50:33 -04:00
Sebastian Markbåge
e0d9b28999
[Fizz] Minor Fixes for Warning Parity (#21618) 2021-06-03 19:54:31 -04:00
Sebastian Markbåge
5890e0e692
Remove data-reactroot from server rendering and hydration heuristic (#20996)
This was used to implicitly hydrate if you call ReactDOM.render.

We've had a warning to explicitly use ReactDOM.hydrate(...) instead of
ReactDOM.render(...). We can now remove this from the generated markup.
(And avoid adding it to Fizz.)

This is a little strange to do now since we're trying hard to make the
root API work the same.

But if we kept it, we'd need to keep it in the generated output which adds
unnecessary bytes. It also risks people relying on it, in the Fizz world
where as this is an opportunity to create that clean state.

We could possibly only keep it in the old server rendering APIs but then
that creates an implicit dependency between which server API and which
client API that you use. Currently you can really mix and match either way.
2021-05-13 10:18:21 -07:00
Sebastian Markbåge
8ea11306ad
Allow complex objects as children of option only if value is provided (#21431) 2021-05-05 08:40:54 -07:00
Sebastian Markbåge
172e89b4bf
Reland Remove redundant initial of isArray (#21188)
* Remove redundant initial of isArray (#21163)

* Reapply prettier

* Type the isArray function with refinement support

This ensures that an argument gets refined just like it does if isArray is
used directly.

I'm not sure how to express with just a direct reference so I added a
function wrapper and confirmed that this does get inlined properly by
closure compiler.

* A few more

* Rename unit test to internal

This is not testing a bundle.

Co-authored-by: Behnam Mohammadi <itten@live.com>
2021-04-07 07:57:43 -07:00
Sebastian Markbage
b4f119cdf1 Revert "Remove redundant initial of isArray (#21163)"
This reverts commit b130a0f5cd.
2021-04-01 15:19:00 -04:00
Behnam Mohammadi
b130a0f5cd
Remove redundant initial of isArray (#21163) 2021-04-01 10:50:48 -07:00
Behnam Mohammadi
2c9fef32db
Remove redundant initial of hasOwnProperty (#21134)
* remove redundant initial of hasOwnProperty

* remove redundant initial of hasOwnProperty part 2

* remove redundant initial of hasOwnProperty part 3
2021-04-01 09:05:10 -07:00
Sebastian Markbåge
588db2e1fc
Don't warn for casing if it's a custom element (#21156)
This replicates what we do on the client.
2021-03-31 18:10:27 -07:00
Sebastian Markbåge
9ed0167945
Don't lower case HTML tags in comparison for built-ins (#21155) 2021-03-31 18:00:22 -07:00
Sebastian Markbåge
fb8c1917e9
Don't use nested objects to "namespace" namespace constants (#21073) 2021-03-24 09:58:23 -07:00
Brian Vaughn
7df65725ba
Split getComponentName into getComponentNameFromFiber and getComponentNameFromType (#20940)
Split getComponentName into getComponentNameFromFiber and getComponentNameFromType
2021-03-05 16:02:02 -05:00
Dan Abramov
4ecf11977c
Remove the Fundamental internals (#20745) 2021-02-05 20:36:55 +00:00
CY Lim
702fad4b1b
refactor fb.me redirect link to reactjs.org/link (#19598)
* refactor fb.me url to reactjs.org/link

* Update ESLintRuleExhaustiveDeps-test.js

* Update ReactDOMServerIntegrationUntrustedURL-test.internal.js

* Update createReactClassIntegration-test.js

* Update ReactDOMServerIntegrationUntrustedURL-test.internal.js

Co-authored-by: Dan Abramov <dan.abramov@gmail.com>
2020-08-17 13:25:50 +01:00
Dominic Gannaway
b61174fb7b
Remove the deprecated React Flare event system (#19520) 2020-08-05 15:13:29 +01:00
Dominic Gannaway
9102719baa
Tidy up React Scope API (#19352) 2020-07-16 16:21:21 +01:00
Phil MacCart
b85b47630b
Fix state leaking when a function component throws on server render (#19212)
* add unit test asserting internal hooks state is reset

* Reset internal hooks state before rendering

* reset hooks state on error

* Use expect...toThrow instead of try/catch in test

* reset dev-only hooks state inside resetHooksState

* reset currentlyRenderingComponent to null
2020-07-08 03:10:23 +01:00
Dan Abramov
75b6921d64
Remove dead code from modern event system (#19233)
* Remove dead code from modern event system

* Remove SSR dependency on EventPluginRegistry
2020-07-01 21:04:14 +01:00
Brian Vaughn
a012858ba9
Move isCustomComponent() function call outside of loop (#19007) 2020-05-26 13:41:27 -07:00
Andrew Clark
03e6b8ba2f
Make LegacyHidden match semantics of old fork (#18998)
Facebook currently relies on being able to hydrate hidden HTML. So
skipping those trees is a regression.

We don't have a proper solution for this in the new API yet. So I'm
reverting it to match the old behavior.

Now the server renderer will treat LegacyHidden the same as a fragment,
with no other special behavior. We can only get away with this because
we assume that every instance of LegacyHidden is accompanied by a host
component wrapper. In the hidden mode, the host component is given a
`hidden` attribute, which ensures that the initial HTML is not visible.
To support the use of LegacyHidden as a true fragment, without an extra
DOM node, we will have to hide the initial HTML in some other way.
2020-05-25 18:16:53 -07:00
Andrew Clark
0fb747f368
Add LegacyHidden to server renderer (#18919)
* Add LegacyHidden to server renderer

When the tree is hidden, the server renderer renders nothing. The
contents will be completely client rendered.

When the tree is visible it acts like a fragment.

The future streaming server renderer may want to pre-render these trees
and send them down in chunks, as with Suspense boundaries.

* Force client render, even at Offscreen pri
2020-05-14 11:28:11 -07:00
Luna Ruan
df14b5bcc1
add new IDs for each each server renderer instance and prefixes to distinguish between each server render (#18576)
There is a worry that `useOpaqueIdentifier` might run out of unique IDs if running for long enough. This PR moves the unique ID counter so it's generated per server renderer object instead. For people who render different subtrees, this PR adds a prefix option to `renderToString`, `renderToStaticMarkup`, `renderToNodeStream`, and `renderToStaticNodeStream` so identifiers can be differentiated for each individual subtree.
2020-05-07 20:46:27 -07:00
Brian Vaughn
22dc2e42bd
Add experimental DebugTracing logger for internal use (#18531) 2020-04-15 19:10:15 -07:00
Sebastian Markbåge
4169420198
Refactor Component Stack Traces (#18495)
* Add feature flag

* Split stack from current fiber

You can get stack from any fiber, not just current.

* Refactor description of component frames

These should use fiber tags for switching. This also puts the relevant code
behind DEV flags.

* We no longer expose StrictMode in component stacks

They're not super useful and will go away later anyway.

* Update tests

Context is no longer part of SSR stacks. This was already the case on the
client.

forwardRef no longer is wrapped on the stack. It's still in getComponentName
but it's probably just noise in stacks. Eventually we'll remove the wrapper
so it'll go away anyway. If we use native stack frames they won't have this
extra wrapper.

It also doesn't pick up displayName from the outer wrapper. We could maybe
transfer it but this will also be fixed by removing the wrapper.

* Forward displayName onto the inner function for forwardRef and memo in DEV

This allows them to show up in stack traces.

I'm not doing this for lazy because lazy is supposed to be called on the
consuming side so you shouldn't assign it a name on that end. Especially
not one that mutates the inner.

* Use multiple instances of the fake component

We mutate the inner component for its name so we need multiple copies.
2020-04-06 15:43:39 -07:00
Sebastian Markbåge
1fd45437d7
Don't use checkPropTypes for internals (#18488)
We use console.error for internal warnings.
2020-04-04 15:10:46 -07:00
Sebastian Markbåge
3e94bce765
Enable prefer-const lint rules (#18451)
* Enable prefer-const rule

Stylistically I don't like this but Closure Compiler takes advantage of
this information.

* Auto-fix lints

* Manually fix the remaining callsites
2020-04-01 12:35:52 -07:00
Dan Abramov
d8d2b6e89c
Disable module components dynamically for WWW (#18446)
* Make disableModulePatternComponents dynamic for WWW

* Run both flags and tests and respect the flag in SSR
2020-04-01 18:31:59 +01:00
Sebastian Markbåge
e2c6702fca
Remove ConcurrentMode and AsyncMode symbols (#18450)
This API was never released.
2020-04-01 10:18:52 -07:00
Dan Abramov
6498f62edc
Fix a mistake in ReactChildren refactor (#18380)
* Regression test for map() returning an array

* Add forgotten argument

This fixes the bug.

* Remove unused arg and retval

These aren't directly observable. The arg wasn't used, it's accidental and I forgot to remove. The retval was triggering a codepath that was unnecessary (pushing to array) so I removed that too.

* Flowify ReactChildren

* Tighten up types

* Rename getComponentKey to getElementKey
2020-03-25 09:20:46 +00:00
Sebastian Markbåge
fd61f7ea53
Refactor Lazy Components to use teh Suspense (and wrap Blocks in Lazy) (#18362)
* Refactor Lazy Components

* Switch Blocks to using a Lazy component wrapper

Then resolve to a true Block inside.

* Test component names of lazy Blocks
2020-03-22 21:53:05 -07:00
Sebastian Markbåge
fa03206ee4
Remove _ctor field from Lazy components (#18217)
* This type is all wrong and nothing cares because it's all any

* Refine Flow types of Lazy Components

We can type each condition.

* Remove _ctor field from Lazy components

This field is not needed because it's only used before we've initialized,
and we don't have anything else to store before we've initialized.

* Check for _ctor in case it's an older isomorphic that created it

We try not to break across minors but it's no guarantee.

* Move types and constants from shared to isomorphic

The "react" package owns the data structure of the Lazy component. It
creates it and decides how any downstream renderer may use it.

* Move constants to shared

Apparently we can't depend on react/src/ because the whole package is
considered "external" as far as rollup is concerned.
2020-03-04 20:52:48 -08:00
Sebastian Markbåge
09348798a9
Codemod to import * as React from "react"; (#18102)
* import * as React from "react";

This is the correct way to import React from an ES module since the ES
module will not have a default export. Only named exports.

* import * as ReactDOM from "react-dom"
2020-02-21 19:45:20 -08:00
Dan Abramov
e706721490
Update Flow to 0.84 (#17805)
* Update Flow to 0.84

* Fix violations

* Use inexact object syntax in files from fbsource

* Fix warning extraction to use a modern parser

* Codemod inexact objects to new syntax

* Tighten types that can be exact

* Revert unintentional formatting changes from codemod
2020-01-09 14:50:44 +00:00
Dominic Gannaway
9fe1031244
[react-interactions] Rename Flare APIs to deprecated and remove from RN (#17644) 2019-12-18 10:24:46 +00:00
Dan Abramov
0cf22a56a1
Use console directly instead of warning() modules (#17599)
* Replace all warning/lowPriWarning with console calls

* Replace console.warn/error with a custom wrapper at build time

* Fail the build for console.error/warn() where we can't read the stack
2019-12-14 18:09:25 +00:00
Dan Abramov
b15bf36750
Add component stacks to (almost) all warnings (#17586) 2019-12-12 23:47:55 +00:00
Laura buns
9ac42dd074 Remove the condition argument from warning() (#17568)
* prep for codemod

* prep warnings

* rename lint rules

* codemod for ifs

* shim www functions

* Handle more cases in the transform

* Thanks De Morgan

* Run the codemod

* Delete the transform

* Fix up confusing conditions manually

* Fix up www shims to match expected API

* Also check for low-pri warning in the lint rule
2019-12-11 03:28:14 +00:00
Laura buns
b43eec7eaa Replace wrap-warning-with-env-check with an eslint plugin (#17540)
* Replace Babel plugin with an ESLint plugin

* Fix ESLint rule violations

* Move shared conditions higher

* Test formatting nits

* Tweak ESLint rule

* Bugfix: inside else branch, 'if' tests are not satisfactory

* Use a stricter check for exactly if (__DEV__)

This makes it easier to see what's going on and matches dominant style in the codebase.

* Fix remaining files after stricter check
2019-12-06 18:25:54 +00:00
Dominic Gannaway
a7d07ff24d
[react-interactions] Rename Flare listeners prop to DEPRECATED_flareListeners (#17394) 2019-11-18 13:32:50 +00:00
Jessica Franco
18d2e0c03e Warning system refactoring (part 1) (#16799)
* Rename lowPriorityWarning to lowPriorityWarningWithoutStack

This maintains parity with the other warning-like functions.

* Duplicate the toWarnDev tests to test toLowPriorityWarnDev

* Make a lowPriorityWarning version of warning.js

* Extract both variants in print-warning

Avoids parsing lowPriorityWarning.js itself as the way it forwards the
call to lowPriorityWarningWithoutStack is not analyzable.
2019-09-24 13:45:38 +01:00
Dominic Gannaway
46f912fd57
[react-core] Add more support for experimental React Scope API (#16621) 2019-08-30 18:27:14 +01:00
Dan Abramov
56f93a7f38
Throw on unhandled SSR suspending (#16460)
* Throw on unhandled SSR suspending

* Add a nicer message when the flag is off

* Tweak internal refinement error message
2019-08-19 19:53:02 +01:00
Lee Byron
56636353d8 Partial support for React.lazy() in server renderer. (#16383)
Provides partial support for React.lazy() components from the existing PartialRenderer server-side renderer.

Lazy components which are already resolved (or rejected), perhaps with something like `react-ssr-prepass`, can be continued into synchronously. If they have not yet been initialized, they'll be initialized before checking, opening the possibility to exploit this capability with a babel transform. If they're pending (which will typically be the case for a just initialized async ctor) then the existing invariant continues to be thrown.
2019-08-13 18:51:20 -07:00
Sunil Pai
66a474227b
use a different link in the UNSAFE_ component warnings (#16321)
When React detects a deprectated/unsafe lifecycle method, the warning points to a page with more details on the why/what of the warning. However, the actual link (https://fb.me/react-async-component-lifecycle-hooks) uses the phrase "lifecycle-hooks" which is confusing since it doesn't have anything to do with hooks. This PR changes the link to something less confusing - https://fb.me/react-unsafe-component-lifecycles.
2019-08-09 12:18:39 +01:00
Dan Abramov
0c1ec049f8
Add a feature flag to disable legacy context (#16269)
* Add a feature flag to disable legacy context

* Address review

- invariant -> warning
- Make this.context and context argument actually undefined

* Increase test coverage for lifecycles

* Also disable it on the server is flag is on

* Make this.context {} when disabled, but function context is undefined

* Move checks inside
2019-08-02 01:21:32 +01:00
Dominic Gannaway
42794557ca
[Flare] Tweaks to Flare system design and API (#16264) 2019-08-01 19:08:54 +01:00