Commit Graph

71 Commits

Author SHA1 Message Date
Sophie Alpert 767f52237c
Use .slice() for all substring-ing (#26677)
- substr is Annex B
- substring silently flips its arguments if they're in the "wrong order", which is confusing
- slice is better than sliced bread (no pun intended) and also it works the same way on Arrays so there's less to remember

---

> I'd be down to just lint and enforce a single form just for the potential compression savings by using a repeated string.

_Originally posted by @sebmarkbage in https://github.com/facebook/react/pull/26663#discussion_r1170455401_
2023-04-19 14:26:01 -07:00
Sebastian Silbermann fd0511c728
[Flight] Add support BigInt support (#26479)
## Summary

Adds support for sending `BigInt` to Flight and Flight Reply

## How did you test this change?

- added tests
2023-03-29 18:23:43 +02:00
Andrew Clark e524467338
New internal testing helpers: waitFor, waitForAll, waitForPaint (#26285)
Over the years, we've gradually aligned on a set of best practices for
for testing concurrent React features in this repo. The default in most
cases is to use `act`, the same as you would do when testing a real
React app. However, because we're testing React itself, as opposed to an
app that uses React, our internal tests sometimes need to make
assertions on intermediate states that `act` intentionally disallows.

For those cases, we built a custom set of Jest assertion matchers that
provide greater control over the concurrent work queue. It works by
mocking the Scheduler package. (When we eventually migrate to using
native postTask, it would probably work by stubbing that instead.)

A problem with these helpers that we recently discovered is, because
they are synchronous function calls, they aren't sufficient if the work
you need to flush is scheduled in a microtask — we don't control the
microtask queue, and can't mock it.

`act` addresses this problem by encouraging you to await the result of
the `act` call. (It's not currently required to await, but in future
versions of React it likely will be.) It will then continue flushing
work until both the microtask queue and the Scheduler queue is
exhausted.

We can follow a similar strategy for our custom test helpers, by
replacing the current set of synchronous helpers with a corresponding
set of async ones:

- `expect(Scheduler).toFlushAndYield(log)` -> `await waitForAll(log)`
- `expect(Scheduler).toFlushAndYieldThrough(log)` -> `await
waitFor(log)`
- `expect(Scheduler).toFlushUntilNextPaint(log)` -> `await
waitForPaint(log)`

These APIs are inspired by the existing best practice for writing e2e
React tests. Rather than mock all task queues, in an e2e test you set up
a timer loop and wait for the UI to match an expecte condition. Although
we are mocking _some_ of the task queues in our tests, the general
principle still holds: it makes it less likely that our tests will
diverge from real world behavior in an actual browser.

In this commit, I've implemented the new testing helpers and converted
one of the Suspense tests to use them. In subsequent steps, I'll codemod
the rest of our test suite.
2023-03-02 21:58:11 -05:00
Ming Ye 71cace4d32
Migrate testRunner from jasmine2 to jest-circus (#26144)
## Summary

In jest v27, jest-circus as default test runner
(https://github.com/facebook/jest/pull/10686)

## How did you test this change?

ci green
2023-02-10 13:39:14 -05:00
Jan Kassens 2b1fb91a55
ESLint upgrade to use hermes-eslint (#25915)
Hermes parser is the preferred parser for Flow code going forward. We
need to upgrade to this parser to support new Flow syntax like function
`this` context type annotations or `ObjectType['prop']` syntax.

Unfortunately, there's quite a few upgrades here to make it work somehow
(dependencies between the changes)

- ~Upgrade `eslint` to `8.*`~ reverted this as the React eslint plugin
tests depend on the older version and there's a [yarn
bug](https://github.com/yarnpkg/yarn/issues/6285) that prevents
`devDependencies` and `peerDependencies` to different versions.
- Remove `eslint-config-fbjs` preset dependency and inline the rules,
imho this makes it a lot clearer what the rules are.
- Remove the turned off `jsx-a11y/*` rules and it's dependency instead
of inlining those from the `fbjs` config.
- Update parser and dependency from `babel-eslint` to `hermes-eslint`.
- `ft-flow/no-unused-expressions` rule replaces `no-unused-expressions`
which now allows standalone type asserts, e.g. `(foo: number);`
- Bunch of globals added to the eslint config
- Disabled `no-redeclare`, seems like the eslint upgrade started making
this more precise and warn against re-defined globals like
`__EXPERIMENTAL__` (in rollup scripts) or `fetch` (when importing fetch
from node-fetch).
- Minor lint fixes like duplicate keys in objects.
2022-12-20 14:27:01 -05:00
Jan Kassens 420f0b7fa1
Remove Reconciler fork (1/2) (#25774)
We've heard from multiple contributors that the Reconciler forking
mechanism was confusing and/or annoying to deal with. Since it's
currently unused and there's no immediate plans to start using it again,
this removes the forking.

Fully removing the fork is split into 2 steps to preserve file history:

**This PR**
- remove `enableNewReconciler` feature flag.
- remove `unstable_isNewReconciler` export
- remove eslint rules for cross fork imports
- remove `*.new.js` files and update imports
- merge non-suffixed files into `*.old` files where both exist
(sometimes types were defined there)

**#25775**
- rename `*.old` files
2022-12-01 23:06:25 -05:00
Sebastian Markbåge cf3932be5c
Remove old react-fetch, react-fs and react-pg libraries (#25577)
To avoid confusion. We are patching `fetch`, and only `fetch`, for a
small fix scoped to react renders elsewhere, but this code is not it.

This code was for the strategy used in the original [React Server
Components demo](https://github.com/reactjs/server-components-demo).
Which [we
announced](https://reactjs.org/blog/2022/06/15/react-labs-what-we-have-been-working-on-june-2022.html)
that we're moving away from in favor of [First class support for
promises and async/await](https://github.com/reactjs/rfcs/pull/229).

We might explore using these package for other instrumentation in the
future but not now and not like this.
2022-10-27 17:52:53 -04:00
Sebastian Markbåge 28a574ea8f
Try assigning fetch to globalThis if global assignment fails (#25571)
In case it's a more modern yet rigid environment.
2022-10-27 02:43:17 -04:00
Sebastian Markbåge cce18e3504
[Flight] Use AsyncLocalStorage to extend the scope of the cache to micro tasks (#25542)
This extends the scope of the cache and fetch instrumentation using
AsyncLocalStorage for microtasks. This is an intermediate step. It sets
up the dispatcher only once. This is unique to RSC because it uses the
react.shared-subset module for its shared state.

Ideally we should support multiple renderers. We should also have this
take over from an outer SSR's instrumented fetch. We should also be able
to have a fallback to global state per request where AsyncLocalStorage
doesn't exist and then the whole client-side solutions. I'm still
figuring out the right wiring for that so this is a temporary hack.
2022-10-23 01:06:58 -04:00
Vic Graf 5b59dd6400
Fix duplicate words tests (#25333)
* refactor: removed duplicated words in comments
* refactor: removed duplicate words in tests
2022-09-27 10:07:06 -04:00
Esteban 09d9b17757
Update deprecated features in ESLint configuration files. (#22767) 2021-11-23 22:53:26 +00:00
Esteban afbc2d08f4
Remove unused react-internal/invariant-args ESLint rule. (#22778) 2021-11-16 20:11:20 +00:00
Brian Vaughn 1bf6deb865
Renamed packages/react-devtools-scheduling-profiler to packages/react-devtools-timeline (#22691) 2021-11-04 10:02:06 -04:00
Andrew Clark 163e81c1f8
Support disabling spurious act warnings with a global environment flag (#22561)
* Extract `act` environment check into function

`act` checks the environment to determine whether to fire a warning.
We're changing how this check works in React 18. As a first step, this
refactors the logic into a single function. No behavior changes yet.

* Use IS_REACT_ACT_ENVIRONMENT to disable warnings

If `IS_REACT_ACT_ENVIRONMENT` is set to `false`, we will suppress
any `act` warnings. Otherwise, the behavior of `act` is the same as in
React 17: if `jest` is defined, it warns.

In concurrent mode, the plan is to remove the `jest` check and only warn
if `IS_REACT_ACT_ENVIRONMENT` is true. I have not implemented that
part yet.
2021-10-18 08:27:26 -07:00
Andrew Clark a724a3b578
[RFC] Codemod invariant -> throw new Error (#22435)
* Hoist error codes import to module scope

When this code was written, the error codes map (`codes.json`) was
created on-the-fly, so we had to lazily require from inside the visitor.

Because `codes.json` is now checked into source, we can import it a
single time in module scope.

* Minify error constructors in production

We use a script to minify our error messages in production. Each message
is assigned an error code, defined in `scripts/error-codes/codes.json`.
Then our build script replaces the messages with a link to our
error decoder page, e.g. https://reactjs.org/docs/error-decoder.html/?invariant=92

This enables us to write helpful error messages without increasing the
bundle size.

Right now, the script only works for `invariant` calls. It does not work
if you throw an Error object. This is an old Facebookism that we don't
really need, other than the fact that our error minification script
relies on it.

So, I've updated the script to minify error constructors, too:

Input:
  Error(`A ${adj} message that contains ${noun}`);
Output:
  Error(formatProdErrorMessage(ERR_CODE, adj, noun));

It only works for constructors that are literally named Error, though we
could add support for other names, too.

As a next step, I will add a lint rule to enforce that errors written
this way must have a corresponding error code.

* Minify "no fallback UI specified" error in prod

This error message wasn't being minified because it doesn't use
invariant. The reason it didn't use invariant is because this particular
error is created without begin thrown — it doesn't need to be thrown
because it's located inside the error handling part of the runtime.

Now that the error minification script supports Error constructors, we
can minify it by assigning it a production error code in
`scripts/error-codes/codes.json`.

To support the use of Error constructors more generally, I will add a
lint rule that enforces each message has a corresponding error code.

* Lint rule to detect unminified errors

Adds a lint rule that detects when an Error constructor is used without
a corresponding production error code.

We already have this for `invariant`, but not for regular errors, i.e.
`throw new Error(msg)`. There's also nothing that enforces the use of
`invariant` besides convention.

There are some packages where we don't care to minify errors. These are
packages that run in environments where bundle size is not a concern,
like react-pg. I added an override in the ESLint config to ignore these.

* Temporarily add invariant codemod script

I'm adding this codemod to the repo temporarily, but I'll revert it
in the same PR. That way we don't have to check it in but it's still
accessible (via the PR) if we need it later.

* [Automated] Codemod invariant -> Error

This commit contains only automated changes:

npx jscodeshift -t scripts/codemod-invariant.js packages --ignore-pattern="node_modules/**/*"
yarn linc --fix
yarn prettier

I will do any manual touch ups in separate commits so they're easier
to review.

* Remove temporary codemod script

This reverts the codemod script and ESLint config I added temporarily
in order to perform the invariant codemod.

* Manual touch ups

A few manual changes I made after the codemod ran.

* Enable error code transform per package

Currently we're not consistent about which packages should have their
errors minified in production and which ones should.

This adds a field to the bundle configuration to control whether to
apply the transform. We should decide what the criteria is going
forward. I think it's probably a good idea to minify any package that
gets sent over the network. So yes to modules that run in the browser,
and no to modules that run on the server and during development only.
2021-09-30 12:01:28 -07:00
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
Michaël De Boey b394c38e88
feat(eslint-plugin-react-internal): support ESLint 8.x (#22249)
Co-authored-by: Dan Abramov <dan.abramov@gmail.com>
2021-09-06 20:42:40 +01:00
Michaël De Boey 0c0d1ddae4
feat(eslint-plugin-react-hooks): support ESLint 8.x (#22248) 2021-09-06 20:17:51 +01:00
Henry Q. Dineen 82ef450e0e
remove obsolete SharedArrayBuffer ESLint config (#21259) 2021-04-14 12:55:23 -04:00
Andrew Clark 0fd6805c6d
Land rest of effects refactor in main fork (#20644) 2021-01-22 14:49:33 -05:00
Andrew Clark fceb75e899
Delete remaining references to effect list (#20625)
I think that's it!
2021-01-20 10:24:01 -08:00
Sebastian Markbåge 5fd9db732d
[Flight] Rename react-transport-... packages to react-server-... (#20403)
* Move files

* Update paths

* Rename import variables

* Rename /server to /writer

This is mainly because "React Server Server" is weird so we need another
dimension.

* Use "react-server" convention to enforce that writer is only loaded in a server
2020-12-08 08:08:57 -05:00
Andrew Clark 3ebf05183d
Add new effect fields to old fork, and vice versa (#20246)
* Add new effect fields to old fork

So that when comparing relative performance, we don't penalize the new
fork for using more memory.

* Add firstEffect, et al fields to new fork

We need to bisect the changes to the recent commit phase refactor. To
do this, we'll need to add back the effect list temporarily.

This only adds them to the Fiber type so that the memory is the same
as the old fork.
2020-11-13 08:09:48 -08:00
Sebastian Markbåge c3e20f18fe
Add Relay specific React Native build of Flight (#20149)
This adds a new dimension similar to dom-relay. It's different from
"native" which would be Flight for RN without Relay.

This has some copy-pasta that's the same between the two Relay builds but
the key difference will be Metro and we're not quite sure what other
differences there will be yet.
2020-11-02 18:49:48 -08:00
oltrep f668b6c351
Bump to latest eslint-config-fbjs (#20029)
* bump package to latest

* update files to respect lint

* disable object-type-delimiter rule to work with prettier

* disable rule to let flow check pass
2020-10-16 16:06:08 +01:00
Nick Reiley 7e405d458d
[DevTools] Add DevTools forked Feature flags (#18994)
Also resolve an uncaught error in extension build (#18843).

Co-authored-by: Brian Vaughn <brian.david.vaughn@gmail.com>
Co-authored-by: Brian Vaughn <bvaughn@fb.com>
2020-10-12 13:07:10 -04:00
Andrew Clark 1665443603
Rename effect fields (#19755)
- `effectTag` -> `flags`
- `subtreeTag` -> `subtreeFlags`
2020-09-04 14:34:07 -07:00
Bhumij Gupta 53e622ca7f
Fix instances of function declaration after return (#19733)
* Add ESLint plugin to check for any function declare after return
* Refactor code to move function declarations before return and fix failing lint
2020-09-01 08:55:10 -04:00
Andrew Clark af219cc6e6
Lint rule to forbid access of cross-fork fields (#19679)
* Lint rule to forbid access of cross-fork fields

We use a shared Fiber type for both reconciler forks (old and new). It
is a superset of all the fields used by both forks. However, there are
some fields that should only be used in the new fork, and others that
should only be used in the old fork.

Ideally we would enforce this with separate Flow types for each fork.
The problem is that the Fiber type is accessed by some packages outside
the reconciler (like React DOM), and get passed into the reconciler as
arguments. So there's no way to fork the Fiber type without also forking
the packages where they are used. FiberRoot has the same issue.

Instead, I've added a lint rule that forbids cross-fork access of
fork-specific fields. Fields that end in `_old` or `_new` are forbidden
from being used inside the new or old fork respectively. Or you can
specific custom fields using the ESLint plugin options.

I used this plugin to find and remove references to the effect list
in d2e914a.

* Mark effect list fields as old

And `subtreeTag` as new.

I didn't mark `lastEffect` because that name is also used by the
Hook type. Not super important; could rename to `lastEffect_old` but
idk if it's worth the effort.
2020-08-24 10:07:11 -07:00
Andrew Clark b8ed6a1aa5
[Scheduler] Call postTask directly (#19551)
This updates the experimental Scheduler postTask build to call postTask
directly, instead of managing our own custom queue and work loop.

We still use a deadline 5ms mechanism to implement `shouldYield`.

The main thing that postTask is currently missing is the continuation
feature — when yielding to the main thread, the yielding task is sent
to the back of the queue, instead of maintaining its position.

While this would be nice to have, even without it, postTask may be good
enough to replace our userspace implementation.

We'll run some tests to see.
2020-08-12 08:39:47 -05:00
Sebastian Markbåge 64d4b84204
Rename Flight to Transport (#18808)
* Rename Flight to Transport

Flight is still the codename for the implementation details (like Fiber).

However, now the public package is react-transport-... which is only
intended to be used directly by integrators.

* Rename names
2020-05-03 11:33:48 -07:00
Andrew Clark 42d7c2e8f7
Add pragma for feature testing: @gate (#18581)
* Add pragma for feature testing: @gate

The `@gate` pragma declares under which conditions a test is expected to
pass.

If the gate condition passes, then the test runs normally (same as if
there were no pragma).

If the conditional fails, then the test runs and is *expected to fail*.

An alternative to `it.experimental` and similar proposals.

Examples
--------

Basic:

```js
// @gate enableBlocksAPI
test('passes only if Blocks API is available', () => {/*...*/})
```

Negation:

```js
// @gate !disableLegacyContext
test('depends on a deprecated feature', () => {/*...*/})
```

Multiple flags:

```js
// @gate enableNewReconciler
// @gate experimental
test('needs both useEvent and Blocks', () => {/*...*/})
```

Logical operators (yes, I'm sorry):

```js
// @gate experimental && (enableNewReconciler || disableSchedulerTimeoutBasedOnReactExpirationTime)
test('concurrent mode, doesn\'t work in old fork unless Scheduler timeout flag is disabled', () => {/*...*/})
```

Strings, and comparion operators

No use case yet but I figure eventually we'd use this to gate on
different release channels:

```js
// @gate channel ===  "experimental" || channel === "modern"
test('works in OSS experimental or www modern', () => {/*...*/})
```

How does it work?

I'm guessing those last two examples might be controversial. Supporting
those cases did require implementing a mini-parser.

The output of the transform is very straightforward, though.

Input:
```js
// @gate a && (b || c)
test('some test', () => {/*...*/})
```

Output:

```js
_test_gate(ctx => ctx.a && (ctx.b || ctx.c, 'some test'), () => {/*...*/});
```

It also works  with `it`, `it.only`, and `fit`. It leaves `it.skip` and
`xit` alone because those tests are disabled anyway.

`_test_gate` is a global method that I set up in our Jest config. It
works about the same as the existing `it.experimental` helper.

The context (`ctx`) argument is whatever we want it to be. I set it up
so that it throws if you try to access a flag that doesn't exist. I also
added some shortcuts for common gating conditions, like `old`
and `new`:

```js
// @gate experimental
test('experimental feature', () => {/*...*/})

// @gate new
test('only passes in new reconciler', () => {/*...*/})
```

Why implement this as a pragma instead of a runtime API?

- Doesn't require monkey patching built-in Jest methods. Instead it
  compiles to a runtime function that composes Jest's API.
- Will be easy to upgrade if Jest ever overhauls their API or we switch
  to a different testing framework (unlikely but who knows).
- It feels lightweight so hopefully people won't feel gross using it.
  For example, adding or removing a gate pragma will never affect the
  indentation of the test, unlike if you wrapped the test in a
  conditional block.

* Compatibility with console error/warning tracking

We patch console.error and console.warning to track unexpected calls
in our tests. If there's an unexpected call, we usually throw inside
an `afterEach` hook. However, that's too late for tests that we
expect to fail, because our `_test_gate` runtime can't capture the
error. So I also check for unexpected calls inside `_test_gate`.

* Move test flags to dedicated file

Added some instructions for how the flags are set up and how to
use them.

* Add dynamic version of gate API

Receives same flags as the pragma.

If we ever decide to revert the pragma, we can codemod them to use
this instead.
2020-04-13 10:14:34 -07:00
Andrew Clark af1b039bdd
ESLint rule to forbid cross fork imports (#18568)
Modules that belong to one fork should not import modules that belong to
the other fork.

Helps make sure you correctly update imports when syncing changes across
implementations.

Also could help protect against code size regressions that might happen
if one of the forks accidentally depends on two copies of the same
module.
2020-04-09 18:11:34 -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
Sebastian Markbåge 8206b4b864
Wire up bundler configs (#18334)
This allows different flight server and clients to have different configs
depending on bundler to serialize and resolve modules.
2020-03-18 12:18:34 -07:00
Andrew Clark 115cd12d9b
Add test run that uses www feature flags (#18234)
In CI, we run our test suite against multiple build configurations. For
example, we run our tests in both dev and prod, and in both the
experimental and stable release channels. This is to prevent accidental
deviations in behavior between the different builds. If there's an
intentional deviation in behavior, the test author must account
for them.

However, we currently don't run tests against the www builds. That's
a problem, because it's common for features to land in www before they
land anywhere else, including the experimental release channel.
Typically we do this so we can gradually roll out the feature behind
a flag before deciding to enable it.

The way we test those features today is by mutating the
`shared/ReactFeatureFlags` module. There are a few downsides to this
approach, though. The flag is only overridden for the specific tests or
test suites where you apply the override. But usually what you want is
to run *all* tests with the flag enabled, to protect against unexpected
regressions.

Also, mutating the feature flags module only works when running the
tests against source, not against the final build artifacts, because the
ReactFeatureFlags module is inlined by the build script.

Instead, we should run the test suite against the www configuration,
just like we do for prod, experimental, and so on. I've added a new
command, `yarn test-www`. It automatically runs in CI.

Some of the www feature flags are dynamic; that is, they depend on
a runtime condition (i.e. a GK). These flags are imported from an
external module that lives in www. Those flags will be enabled for some
clients and disabled for others, so we should run the tests against
*both* modes.

So I've added a new global `__VARIANT__`, and a new test command `yarn
test-www-variant`. `__VARIANT__` is set to false by default; when
running `test-www-variant`, it's set to true.

If we were going for *really* comprehensive coverage, we would run the
tests against every possible configuration of feature flags: 2 ^
numberOfFlags total combinations. That's not practical, though, so
instead we only run against two combinations: once with `__VARIANT__`
set to `true`, and once with it set to `false`. We generally assume that
flags can be toggled independently, so in practice this should
be enough.

You can also refer to `__VARIANT__` in tests to detect which mode you're
running in. Or, you can import `shared/ReactFeatureFlags` and read the
specific flag you can about. However, we should stop mutating that
module going forward. Treat it as read-only.

In this commit, I have only setup the www tests to run against source.
I'll leave running against build for a follow up.

Many of our tests currently assume they run only in the default
configuration, and break when certain flags are toggled. Rather than fix
these all up front, I've hard-coded the relevant flags to the default
values. We can incrementally migrate those tests later.
2020-03-06 09:29:05 -08:00
Sunil Pai a8643e905e
add no-restricted-globals to eslint config (#18076)
Our current lint config assumes a browser environment, which means it won't warn you if you use a variable like `name` without declaring it earlier. This imports the same list as the one used by create-react-app, and enables it against our codebase.
2020-02-19 17:14:53 +00:00
Nicolas Gallagher 50eafef07e
Update babel-eslint and eslint packages (#17829) 2020-01-14 09:26:44 -08:00
Nicolas Gallagher 72592310a8
Create packages/dom-event-testing-library (#17660)
Moves the unit testing library for events into the `packages` directory so it can more easily be used in tests for other react packages, and mirrored internally to help with testing of event hooks we prototype in www.
2019-12-19 16:51:25 +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
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
Andrew Clark d364d8555f
Set up experimental builds (#17071)
* Don't bother including `unstable_` in error

The method names don't get stripped out of the production bundles
because they are passed as arguments to the error decoder.

Let's just always use the unprefixed APIs in the messages.

* Set up experimental builds

The experimental builds are packaged exactly like builds in the stable
release channel: same file structure, entry points, and npm package
names. The goal is to match what will eventually be released in stable
as closely as possible, but with additional features turned on.

Versioning and Releasing
------------------------

The experimental builds will be published to the same registry and
package names as the stable ones. However, they will be versioned using
a separate scheme. Instead of semver versions, experimental releases
will receive arbitrary version strings based on their content hashes.
The motivation is to thwart attempts to use a version range to match
against future experimental releases. The only way to install or depend
on an experimental release is to refer to the specific version number.

Building
--------

I did not use the existing feature flag infra to configure the
experimental builds. The reason is because feature flags are designed
to configure a single package. They're not designed to generate multiple
forks of the same package; for each set of feature flags, you must
create a separate package configuration.

Instead, I've added a new build dimension called the **release
channel**. By default, builds use the **stable** channel. There's
also an **experimental** release channel. We have the option to add more
in the future.

There are now two dimensions per artifact: build type (production,
development, or profiling), and release channel (stable or
experimental). These are separate dimensions because they are
combinatorial: there are stable and experimental production builds,
stable and experimental developmenet builds, and so on.

You can add something to an experimental build by gating on
`__EXPERIMENTAL__`, similar to how we use `__DEV__`. Anything inside
these branches will be excluded from the stable builds.
This gives us a low effort way to add experimental behavior in any
package without setting up feature flags or configuring a new package.
2019-10-14 10:46:42 -07:00
Emanuel Tesař b8d079b413 Add trusted types to react on client side (#16157)
* Add trusted types to react on client side

* Implement changes according to review

* Remove support for trusted URLs, change TrustedTypes to trustedTypes

* Add support for deprecated trusted URLs

* Apply PR suggesstions

* Warn only once, remove forgotten check, put it behind a flag

* Move comment

* Fix PR comments

* Fix html toString concatenation

* Fix forgotten else branch

* Fix PR comments
2019-09-16 13:43:22 +01:00
Dan Abramov 0f6e3cd61c [Scheduler] Profiler Features (second try) (#16542)
* Revert "Revert "[Scheduler] Profiling features (#16145)" (#16392)"

This reverts commit 4ba1412305.

* Fix copy paste mistake

* Remove init path dependency on ArrayBuffer

* Add a regression test for cancelling multiple tasks

* Prevent deopt from adding isQueued later

* Remove pop() calls that were added for profiling

* Verify that Suspend/Unsuspend events match up in tests

This currently breaks tests.

* Treat Suspend and Resume as exiting and entering work loop

Their definitions used to be more fuzzy. For example, Suspend didn't always fire on exit, and sometimes fired when we did _not_ exit (such as at task enqueue).

I chatted to Boone, and he's saying treating Suspend and Resume as strictly exiting and entering the loop is fine for their use case.

* Revert "Prevent deopt from adding isQueued later"

This reverts commit 9c30b0b695.

Unnecessary because GCC

* Start counter with 1

* Group exports into unstable_Profiling namespace

* No catch in PROD codepath

* No label TODO

* No null checks
2019-08-22 13:58:12 -07:00
Dan Abramov 4ba1412305
Revert "[Scheduler] Profiling features (#16145)" (#16392)
This reverts commit a34ca7bce6.
2019-08-14 20:02:41 +01:00
Simen Bekkhus 5fa99b5aa6 chore: add eslint-plugin-jest's valid-expect rule (#16332)
* chore: add eslint-plugin-jest's valid-expect rule

* update assertion
2019-08-14 11:51:01 +01:00
Andrew Clark a34ca7bce6
[Scheduler] Profiling features (#16145)
* [Scheduler] Mark user-timing events

Marks when Scheduler starts and stops running a task. Also marks when
a task is initially scheduled, and when Scheduler is waiting for a
callback, which can't be inferred from a sample-based JavaScript CPU
profile alone.

The plan is to use the user-timing events to build a Scheduler profiler
that shows how the lifetime of tasks interact with each other and
with unscheduled main thread work.

The test suite works by printing an text representation of a
Scheduler flamegraph.

* Expose shared array buffer with profiling info

Array contains

- the priority Scheduler is currently running
- the size of the queue
- the id of the currently running task

* Replace user-timing calls with event log

Events are written to an array buffer using a custom instruction format.
For now, this is only meant to be used during page start up, before the
profiler worker has a chance to start up. Once the worker is ready, call
`stopLoggingProfilerEvents` to return the log up to that point, then
send the array buffer to the worker.

Then switch to the sampling based approach.

* Record the current run ID

Each synchronous block of Scheduler work is given a unique run ID. This
is different than a task ID because a single task will have more than
one run if it yields with a continuation.
2019-08-13 19:01:17 -07:00
Andrew Clark 0bd0c5269f
Upgrade ESLint so we can use JSX Fragment syntax (#16328)
Now that we're using Babel 7, this is the last blocker.
2019-08-09 12:59:02 -07:00
Eli White 12e5a13cf2
[React Native] Inline calls to FabricUIManager in shared code (#15490)
* [React Native] Inline calls to FabricUIManager in shared code

* Call global.nativeFabricUIManager directly as short term fix

* Add flow types

* Add nativeFabricUIManager global to eslint config

* Adding eslint global to bundle validation script
2019-04-29 14:31:16 -07:00