mirror of
https://github.com/vercel/next.js.git
synced 2026-09-20 02:25:18 +08:00
94327e8ade
The test suite has accumulated a bunch of patterns for disabling tests
that are known to fail under some configuration: `it.skip`, `if
(isNextDev) { test('skipped in dev mode', () => {}); return }`, whole
describes toggled off by checking `process.env.__NEXT_CACHE_COMPONENTS`.
These all have the same flaw: nothing tells you when the thing you
skipped starts working. The test stays disabled forever, and the
workaround it was guarding rots along with it.
React solves this with the `@gate` pragma, and this PR ports it to the
Next.js e2e harness:
```ts
// Blocked on the optimization that marks a route as fully static when
// no dynamic params are referenced in Server Components.
// @gate !cacheComponents
it('navigates to a page with a lazily-generated static param', async () => {
// body unchanged
})
```
The test still runs. If the condition is false and the test fails, the
failure is absorbed and the suite stays green. If it _passes_, the suite
fails: the gate is stale, delete it. So instead of a skip that hides a
fixed bug indefinitely, you get a CI failure the day the fix lands.
When the condition is static, the inversion is Jest's own `test.failing`
under the hood. A lazy condition isn't known until the fixture's
resolved config is read inside the body, so those tests invert at
runtime instead.
`// @force-gate <condition>` skips for real — for tests that can't even
be attempted (prefetching is disabled in dev, deploy has no local build
output, the fixture won't build under the condition), and for tests of a
new API, where the disabled state can only throw and running it proves
nothing:
```ts
// Prefetching is disabled in dev, so this suite has nothing to test.
// @force-gate prefetching
describe('segment cache prefetch scheduling', () => {
// ...
})
```
There's no staleness check in that case, so this is a judgment call:
prefer `@gate` when the off state fails for a meaningful reason — the
flag changes behavior that already exists — and `@force-gate` when the
body can only throw because the API doesn't exist. A static condition
(mode, bundler) resolves at collection time into a normal Jest skip. A
lazy condition resolves at runtime, and when a lazy force-gate on a
describe is false, we skip the fixture build entirely — that's what
makes it usable for suites whose fixtures are build-incompatible with
the condition. (One caveat: Jest has no way to skip a test that's
already running, so these report as passing with a warning in the log,
not as skipped.)
Conditions live in a hand-written registry. I considered deriving the
lazy ones from the config schema automatically, but a gate is a claim
about which dimension of the test matrix explains a failure, and I'd
rather each of those claims be spelled out with a description.
Referencing an undeclared name fails the suite at collection time, so a
typo can't silently disable a gate.
The important design decision for lazy conditions is that they read the
fixture's _resolved_ config, never `process.env`. The env var isn't the
truth: `__NEXT_CACHE_COMPONENTS=true` only applies when the fixture
doesn't set `cacheComponents` itself, and config resolution implies
flags the fixture never mentions (`cacheComponents: true` alone turns on
`experimental.ppr`). Resolution happens in a child process, because
in-process `loadConfig` would leak the fixture's `.env` files into the
Jest worker. Suites with no lazy gate never pay for any of this.
The condition expression is parsed using a small grammar (also ported
from the React repo). An expression that doesn't parse fails the suite:
```ts
// @gate mode === 'start' && !cacheComponents
// @gate !(turbopack || rspack)
```
There's also a runtime version, mirroring React's `gate(flags =>
flags.enableFoo)`, for tests that run under both states but assert
differently (and for `it.each`, where the pragma can't attach):
```ts
import { gate } from 'next-test-utils'
it('renders the fallback', async () => {
if (await gate((conditions) => conditions.cacheComponents)) {
// PPR: the fallback is part of the static shell
} else {
// fully dynamic: the fallback streams in
}
})
```
It also accepts the pragma expression language as a string: `await
gate('cacheComponents && !dev')`.
Docs are in `test/lib/gate/README.md`; `test/unit/gate/` covers the
transform, the expression language, and the runtime.
233 lines
6.2 KiB
TypeScript
233 lines
6.2 KiB
TypeScript
/**
|
|
* The tiny expression language used inside a `// @gate` pragma.
|
|
*
|
|
* ```
|
|
* expression → binary ( ( "||" | "&&" ) binary )* ;
|
|
* binary → unary ( ( "==" | "!=" | "===" | "!==" ) unary )* ;
|
|
* unary → "!" unary | primary ;
|
|
* primary → NAME | STRING | BOOLEAN | "(" expression ")" ;
|
|
* ```
|
|
*
|
|
* This mirrors the grammar React uses for its own `@gate` pragmas
|
|
* (`scripts/babel/transform-test-gate-pragma.js` in facebook/react), so
|
|
* pragmas read the same in both repos:
|
|
*
|
|
* ```
|
|
* // @gate !dev
|
|
* // @gate mode === 'start' && !cacheComponents
|
|
* ```
|
|
*
|
|
* `NAME` is a condition declared in `./conditions.ts`. Unlike React, the
|
|
* expression is parsed at *runtime* rather than compiled by the transform,
|
|
* which keeps the source rewrite trivial and lets the runtime report the
|
|
* pragma text verbatim in error messages.
|
|
*/
|
|
|
|
export type ExprNode =
|
|
| { type: 'literal'; value: string | boolean }
|
|
| { type: 'condition'; name: string }
|
|
| { type: 'not'; argument: ExprNode }
|
|
| { type: 'logical'; op: '&&' | '||'; left: ExprNode; right: ExprNode }
|
|
| { type: 'compare'; op: '=='; left: ExprNode; right: ExprNode }
|
|
| { type: 'compare'; op: '!='; left: ExprNode; right: ExprNode }
|
|
|
|
export type ParsedExpression = {
|
|
node: ExprNode
|
|
/** Every condition name referenced by the expression, deduplicated. */
|
|
names: string[]
|
|
}
|
|
|
|
type Token =
|
|
| { type: 'name'; name: string }
|
|
| { type: 'string'; value: string }
|
|
| { type: 'boolean'; value: boolean }
|
|
| { type: '&&' | '||' | '==' | '!=' | '!' | '(' | ')' }
|
|
|
|
const NAME_RE = /[a-zA-Z_$][0-9a-zA-Z_$]*/y
|
|
|
|
function tokenize(source: string): Token[] {
|
|
const tokens: Token[] = []
|
|
let i = 0
|
|
while (i < source.length) {
|
|
const char = source[i]
|
|
|
|
if (char === '"' || char === "'") {
|
|
let value = ''
|
|
i++
|
|
while (i < source.length && source[i] !== char) value += source[i++]
|
|
if (source[i] !== char) {
|
|
throw new SyntaxError(
|
|
`Unterminated string in \`${source}\` (missing closing ${char}).`
|
|
)
|
|
}
|
|
i++
|
|
tokens.push({ type: 'string', value })
|
|
continue
|
|
}
|
|
|
|
if (/\s/.test(char)) {
|
|
i++
|
|
continue
|
|
}
|
|
|
|
const next3 = source.slice(i, i + 3)
|
|
if (next3 === '===') {
|
|
tokens.push({ type: '==' })
|
|
i += 3
|
|
continue
|
|
}
|
|
if (next3 === '!==') {
|
|
tokens.push({ type: '!=' })
|
|
i += 3
|
|
continue
|
|
}
|
|
|
|
const next2 = source.slice(i, i + 2)
|
|
if (next2 === '&&' || next2 === '||' || next2 === '==' || next2 === '!=') {
|
|
tokens.push({ type: next2 })
|
|
i += 2
|
|
continue
|
|
}
|
|
|
|
if (char === '(' || char === ')' || char === '!') {
|
|
tokens.push({ type: char })
|
|
i++
|
|
continue
|
|
}
|
|
|
|
NAME_RE.lastIndex = i
|
|
const match = NAME_RE.exec(source)
|
|
if (match) {
|
|
const name = match[0]
|
|
if (name === 'true' || name === 'false') {
|
|
tokens.push({ type: 'boolean', value: name === 'true' })
|
|
} else {
|
|
tokens.push({ type: 'name', name })
|
|
}
|
|
i += name.length
|
|
continue
|
|
}
|
|
|
|
throw new SyntaxError(
|
|
`Unexpected character ${JSON.stringify(char)} in \`${source}\`.`
|
|
)
|
|
}
|
|
return tokens
|
|
}
|
|
|
|
/** Parses a pragma condition, collecting the condition names it references. */
|
|
export function parse(source: string): ParsedExpression {
|
|
const tokens = tokenize(source)
|
|
const names = new Set<string>()
|
|
let i = 0
|
|
|
|
function expression(): ExprNode {
|
|
let left = binary()
|
|
for (;;) {
|
|
const token = tokens[i]
|
|
if (token && (token.type === '&&' || token.type === '||')) {
|
|
i++
|
|
left = { type: 'logical', op: token.type, left, right: binary() }
|
|
continue
|
|
}
|
|
return left
|
|
}
|
|
}
|
|
|
|
function binary(): ExprNode {
|
|
let left = unary()
|
|
for (;;) {
|
|
const token = tokens[i]
|
|
if (token && (token.type === '==' || token.type === '!=')) {
|
|
i++
|
|
left = { type: 'compare', op: token.type, left, right: unary() }
|
|
continue
|
|
}
|
|
return left
|
|
}
|
|
}
|
|
|
|
function unary(): ExprNode {
|
|
if (tokens[i]?.type === '!') {
|
|
i++
|
|
return { type: 'not', argument: unary() }
|
|
}
|
|
return primary()
|
|
}
|
|
|
|
function primary(): ExprNode {
|
|
const token = tokens[i]
|
|
if (!token) {
|
|
throw new SyntaxError(`Unexpected end of expression in \`${source}\`.`)
|
|
}
|
|
switch (token.type) {
|
|
case 'boolean':
|
|
case 'string':
|
|
i++
|
|
return { type: 'literal', value: token.value }
|
|
case 'name':
|
|
i++
|
|
names.add(token.name)
|
|
return { type: 'condition', name: token.name }
|
|
case '(': {
|
|
i++
|
|
const inner = expression()
|
|
if (tokens[i]?.type !== ')') {
|
|
throw new SyntaxError(`Missing closing \`)\` in \`${source}\`.`)
|
|
}
|
|
i++
|
|
return inner
|
|
}
|
|
default:
|
|
throw new SyntaxError(`Unexpected \`${token.type}\` in \`${source}\`.`)
|
|
}
|
|
}
|
|
|
|
const node = expression()
|
|
if (i !== tokens.length) {
|
|
throw new SyntaxError(
|
|
`Unexpected \`${tokens[i].type}\` after a complete expression in ` +
|
|
`\`${source}\`.`
|
|
)
|
|
}
|
|
return { node, names: [...names] }
|
|
}
|
|
|
|
function evaluateNode(
|
|
node: ExprNode,
|
|
read: (name: string) => unknown
|
|
): unknown {
|
|
switch (node.type) {
|
|
case 'literal':
|
|
return node.value
|
|
case 'condition':
|
|
return read(node.name)
|
|
case 'not':
|
|
return !evaluateNode(node.argument, read)
|
|
case 'logical':
|
|
return node.op === '&&'
|
|
? evaluateNode(node.left, read) && evaluateNode(node.right, read)
|
|
: evaluateNode(node.left, read) || evaluateNode(node.right, read)
|
|
case 'compare': {
|
|
const left = evaluateNode(node.left, read)
|
|
const right = evaluateNode(node.right, read)
|
|
return node.op === '==' ? left === right : left !== right
|
|
}
|
|
default:
|
|
throw new Error(`Unknown @gate expression node: ${JSON.stringify(node)}`)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Evaluates a parsed expression. Condition values are coerced by truthiness in
|
|
* boolean position, so `@gate prefetchInlining` works for a condition whose
|
|
* value is `false | {maxSize: number}`, and `@gate output === 'export'` works
|
|
* for string-valued conditions.
|
|
*/
|
|
export function evaluate(
|
|
node: ExprNode,
|
|
read: (name: string) => unknown
|
|
): boolean {
|
|
return Boolean(evaluateNode(node, read))
|
|
}
|