Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

lint(no-nullish-jsx-guard): catch isRenderable written out by hand, and enforce with a baseline (#9147)

Cindy Zhangf67d5fa7ee97
diff --git a/eslint.config.js b/eslint.config.js
index a79a6880a8..e2e569879b 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -10,6 +10,7 @@ import eslintReact from '@eslint-react/eslint-plugin';
import reactCompiler from 'eslint-plugin-react-compiler';
import astryxPlugin from './internal/eslint-plugin-astryx/index.js';
import {scope as internalBarrelScope} from './internal/eslint-plugin-astryx/no-internal-barrel-import.js';
+import {scope as nullishGuardScope} from './internal/eslint-plugin-astryx/no-nullish-jsx-guard.js';
/* global process */
@@ -45,6 +46,19 @@ const internalBarrelBaseline = JSON.parse(
),
);
+// Guarded values whose bare nullish JSX guard or hand-written isRenderable
+// check predates making `@astryx/no-nullish-jsx-guard` fail strict lint, by
+// repo-relative file, once per check. The list only shrinks.
+const nullishGuardBaseline = JSON.parse(
+ readFileSync(
+ path.join(
+ import.meta.dirname,
+ 'internal/eslint-plugin-astryx/no-nullish-jsx-guard.baseline.json',
+ ),
+ 'utf8',
+ ),
+);
+
// The internal plugin is plain untyped JS (kept out of the lint/type surface),
// so its inferred shape doesn't satisfy ESLint's strict `Plugin` type. One
// localized assertion here keeps every `plugins` entry below type-checked.
@@ -883,6 +897,25 @@ export default defineConfig(
],
},
},
+ // A slot's presence is decided by `isRenderable`, never a bare `!= null`
+ // guard or a hand-written copy of its checks. The checks that predate this
+ // block are listed in the baseline, once per check of each value, and that
+ // many stay allowed until migrated; one more is reported (an error in
+ // strict mode, so a pull request that adds one fails lint, while main stays
+ // green).
+ {
+ files: nullishGuardScope.files,
+ ignores: nullishGuardScope.ignores,
+ plugins: {
+ '@astryx': astryxEslintPlugin,
+ },
+ rules: {
+ '@astryx/no-nullish-jsx-guard': [
+ reactSeverity,
+ {baseline: nullishGuardBaseline, root: import.meta.dirname},
+ ],
+ },
+ },
// richtext — the pre-existing backlog, held at `warn` while it is worked
// off. Must come last so it overrides the blocks above.
//
diff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.md
index 0814f704f3..6bee9f3af2 100644
--- a/internal/eslint-plugin-astryx/README.md
+++ b/internal/eslint-plugin-astryx/README.md
@@ -539,7 +539,15 @@ import {isRenderable} from '@astryxdesign/core/utils';
}
```
-Ships as a **warning in both tiers** while core migrates its existing call sites; promote to `error` in strict mode once migrated. Provides an ESLint suggestion that rewrites the comparison to `isRenderable(value)` (add the import manually).
+It also flags `isRenderable` written out by hand anywhere (an assignment, a condition, a return): a chain that tests one value for nullishness or the empty string and for a boolean.
+
+```ts
+const hasLabel = label !== '' && label != null && typeof label !== 'boolean'; // flagged
+if (rendered == null || typeof rendered === 'boolean') return null; // flagged
+const hasLabel = isRenderable(label); // good
+```
+
+The presets ship it as a warning. The repository config enforces it in core and richtext with `{baseline, root}`: each value's checks that predated enforcement are listed per file in `no-nullish-jsx-guard.baseline.json`, once per check, and that many stay allowed until migrated; one more check of a value in that file is an error in strict mode. A chain that also tests the value against another type (`typeof value === 'string'`, `isValidElement`, `Array.isArray`, `instanceof`) is a type switch and is not flagged. After migrating call sites, rewrite the baseline with `node internal/eslint-plugin-astryx/no-nullish-jsx-guard.baseline.mjs` (`--check` verifies it). For a JSX guard, the rule also provides an ESLint suggestion that rewrites the comparison to `isRenderable(value)` (add the import manually).
See: https://github.com/meta/astryx/issues/2538
diff --git a/internal/eslint-plugin-astryx/no-internal-barrel-import.baseline.mjs b/internal/eslint-plugin-astryx/no-internal-barrel-import.baseline.mjs
index 1b267bef86..01656bb015 100644
--- a/internal/eslint-plugin-astryx/no-internal-barrel-import.baseline.mjs
+++ b/internal/eslint-plugin-astryx/no-internal-barrel-import.baseline.mjs
@@ -14,74 +14,23 @@
import fs from 'node:fs';
import path from 'node:path';
-import {ESLint} from 'eslint';
import {scope} from './no-internal-barrel-import.js';
+import {runRuleBaseline} from './rule-baseline.mjs';
const root = path.resolve(import.meta.dirname, '../..');
-const baselineFile = path.join(
- import.meta.dirname,
- 'no-internal-barrel-import.baseline.json',
-);
-const ruleId = '@astryx/no-internal-barrel-import';
-// Lint with the repo config, but with an empty baseline, so every barrel
-// import in scope is reported once.
-const eslint = new ESLint({
- cwd: root,
- // Some packages' sources are ignored by the repo config entirely.
- errorOnUnmatchedPattern: false,
- ruleFilter: ({ruleId: id}) => id === ruleId,
- overrideConfig: [
- {
- files: scope.files,
- ignores: scope.ignores,
- rules: {[ruleId]: ['error', {baseline: {}, root}]},
- },
- ],
+await runRuleBaseline({
+ ruleId: '@astryx/no-internal-barrel-import',
+ scope,
+ targets: fs
+ .readdirSync(path.join(root, 'packages'))
+ .filter(name => fs.existsSync(path.join(root, 'packages', name, 'src')))
+ .map(name => `packages/${name}/src`),
+ baselineFile: path.join(
+ import.meta.dirname,
+ 'no-internal-barrel-import.baseline.json',
+ ),
+ entryFromMessage: message => /'([^']+)'/.exec(message)?.[1] ?? null,
+ unique: true,
+ noun: 'barrel imports',
});
-const packages = fs
- .readdirSync(path.join(root, 'packages'))
- .filter(name => fs.existsSync(path.join(root, 'packages', name, 'src')))
- .map(name => `packages/${name}/src`);
-const results = await eslint.lintFiles(packages);
-
-const found = new Map();
-for (const result of results) {
- for (const message of result.messages) {
- if (message.ruleId !== ruleId) {
- continue;
- }
- const source = /'([^']+)'/.exec(message.message)?.[1];
- const file = path.relative(root, result.filePath).split(path.sep).join('/');
- if (source != null) {
- if (!found.has(file)) {
- found.set(file, new Set());
- }
- found.get(file).add(source);
- }
- }
-}
-const baseline = Object.fromEntries(
- [...found.keys()].sort().map(file => [file, [...found.get(file)].sort()]),
-);
-const text = `${JSON.stringify(baseline, null, 2)}\n`;
-
-if (process.argv.includes('--check')) {
- const current = fs.readFileSync(baselineFile, 'utf8');
- if (JSON.stringify(JSON.parse(current)) !== JSON.stringify(baseline)) {
- console.error(
- 'no-internal-barrel-import baseline is out of date; run this script without --check.',
- );
- process.exit(1);
- }
- console.log('no-internal-barrel-import baseline is up to date.');
-} else {
- fs.writeFileSync(baselineFile, text);
- const imports = Object.values(baseline).reduce(
- (n, list) => n + list.length,
- 0,
- );
- console.log(
- `Wrote ${imports} barrel imports in ${found.size} files to ${path.relative(root, baselineFile)}.`,
- );
-}
diff --git a/internal/eslint-plugin-astryx/no-nullish-jsx-guard.baseline.json b/internal/eslint-plugin-astryx/no-nullish-jsx-guard.baseline.json
new file mode 100644
index 0000000000..9a30b4ae8d
--- /dev/null
+++ b/internal/eslint-plugin-astryx/no-nullish-jsx-guard.baseline.json
@@ -0,0 +1,47 @@
+{
+ "packages/core/src/Badge/Badge.tsx": ["label"],
+ "packages/core/src/Chat/ChatLayout.tsx": ["children"],
+ "packages/core/src/Chat/ChatMessageList.tsx": ["children"],
+ "packages/core/src/Chat/ChatSystemMessage.tsx": ["icon"],
+ "packages/core/src/Chat/ChatToolCalls.tsx": [
+ "call.additions",
+ "call.deletions",
+ "call.duration",
+ "call.target",
+ "latestCall.target"
+ ],
+ "packages/core/src/DropdownMenu/DropdownMenuGroup.tsx": ["title"],
+ "packages/core/src/Item/Item.tsx": [
+ "description",
+ "endContent",
+ "startContent"
+ ],
+ "packages/core/src/Markdown/Markdown.tsx": ["rendered"],
+ "packages/core/src/MetadataList/MetadataList.tsx": ["title"],
+ "packages/core/src/MetadataList/MetadataListItem.tsx": ["icon"],
+ "packages/core/src/OverflowList/OverflowList.tsx": ["measureIndicator"],
+ "packages/core/src/Pagination/Pagination.tsx": ["computedTotalPages"],
+ "packages/core/src/PowerSearch/PowerSearch.tsx": ["resultCountText"],
+ "packages/core/src/Table/BaseTable.tsx": ["after"],
+ "packages/core/src/Table/plugins/sortable/useTableSortable.tsx": [
+ "rank",
+ "rank"
+ ],
+ "packages/core/src/TextArea/TextArea.tsx": ["maxLength"],
+ "packages/core/src/ToggleButton/ToggleButton.tsx": ["children"],
+ "packages/core/src/TopNav/TopNavMegaMenu.tsx": [
+ "featured",
+ "featured",
+ "items"
+ ],
+ "packages/core/src/TreeList/TreeList.tsx": ["header"],
+ "packages/core/src/TreeList/TreeListItem.tsx": [
+ "description",
+ "endContent",
+ "renderedChildren",
+ "startContent"
+ ],
+ "packages/core/src/utils/getNodeText.ts": ["node"],
+ "packages/richtext/src/RichTextEditor.tsx": ["maxLength", "toolbar"],
+ "packages/richtext/src/RichTextEditorToolbar.tsx": ["endContent"]
+}
diff --git a/internal/eslint-plugin-astryx/no-nullish-jsx-guard.baseline.mjs b/internal/eslint-plugin-astryx/no-nullish-jsx-guard.baseline.mjs
new file mode 100644
index 0000000000..8141616036
--- /dev/null
+++ b/internal/eslint-plugin-astryx/no-nullish-jsx-guard.baseline.mjs
@@ -0,0 +1,31 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file no-nullish-jsx-guard.baseline.mjs
+ * @description Writes (or, with --check, verifies) the baseline that
+ * `@astryx/no-nullish-jsx-guard` allows: each guarded value, per file, once
+ * per bare nullish JSX guard or hand-written isRenderable check of it today.
+ * Run it after migrating checks to isRenderable, or after merging main into a
+ * branch that changes the rule, so the list only names checks that still
+ * exist.
+ *
+ * node internal/eslint-plugin-astryx/no-nullish-jsx-guard.baseline.mjs [--check]
+ */
+
+import path from 'node:path';
+import {scope} from './no-nullish-jsx-guard.js';
+import {runRuleBaseline} from './rule-baseline.mjs';
+
+await runRuleBaseline({
+ ruleId: '@astryx/no-nullish-jsx-guard',
+ scope,
+ targets: ['packages/core/src', 'packages/richtext/src'],
+ baselineFile: path.join(
+ import.meta.dirname,
+ 'no-nullish-jsx-guard.baseline.json',
+ ),
+ entryFromMessage: message =>
+ /`!?isRenderable\(([^`]*)\)`/.exec(message)?.[1] ?? null,
+ unique: false,
+ noun: 'guarded-value checks',
+});
diff --git a/internal/eslint-plugin-astryx/no-nullish-jsx-guard.js b/internal/eslint-plugin-astryx/no-nullish-jsx-guard.js
index 136204c822..2d82bad41f 100644
--- a/internal/eslint-plugin-astryx/no-nullish-jsx-guard.js
+++ b/internal/eslint-plugin-astryx/no-nullish-jsx-guard.js
@@ -40,6 +40,26 @@
* {user != null && <Profile user={user} />} // NOT flagged — `user` is a
* // data object, only a prop
*
+ * Hand-rolled isRenderable: a chain that tests one value for nullishness or
+ * the empty string AND for a boolean is `isRenderable` written out, wherever
+ * it appears (an assignment, a condition, a return):
+ *
+ * const hasLabel = label !== '' && label != null && typeof label !== 'boolean';
+ * if (rendered == null || typeof rendered === 'boolean') return null;
+ *
+ * The boolean test is what marks the value as a rendered node, so these are
+ * flagged even outside JSX; the one definition is
+ * packages/core/src/utils/isRenderable.ts. A chain that also tests the value
+ * against another type (`typeof value === 'string'`, `isValidElement(value)`,
+ * `Array.isArray(value)`, `instanceof`) is a type switch, not a presence test,
+ * and is left alone.
+ *
+ * Options: `{baseline: {[repoRelativeFile]: string[]}, root: string}`. The
+ * baseline lists, per file, each guarded value once per check that predates
+ * enforcement. That many checks of the value stay allowed until migrated;
+ * one more is reported.
+ * `no-nullish-jsx-guard.baseline.mjs` writes it.
+ *
* Known limitations (intentional, to keep precision high):
* - Bare assignments like `const hasFoo = foo != null` are not flagged;
* distinguishing a `ReactNode` slot from any other nullable value needs
@@ -48,6 +68,20 @@
* are not flagged — the guarded branch is not a JSX element.
*/
+import path from 'node:path';
+
+/**
+ * Where the repository config enforces the rule with its baseline; the
+ * baseline script lints the same files.
+ */
+export const scope = {
+ files: [
+ 'packages/core/src/**/*.{ts,tsx}',
+ 'packages/richtext/src/**/*.{ts,tsx}',
+ ],
+ ignores: ['packages/core/src/theme/**'],
+};
+
// `!= null` / `!== null` / `!== undefined` — the "render when present" polarity.
const NOT_EQUAL_OPERATORS = new Set(['!=', '!==']);
// `== null` / `=== null` / `=== undefined` — the "render in the else branch"
@@ -202,6 +236,106 @@ function flattenAnd(node) {
return [node];
}
+/** `typeof X !== 'boolean'` (or `===` when `equal`): the value, else null. */
+function parseBooleanTypeof(node, equal) {
+ if (node?.type !== 'BinaryExpression') {
+ return null;
+ }
+ const ops = equal ? EQUAL_OPERATORS : NOT_EQUAL_OPERATORS;
+ if (!ops.has(node.operator)) {
+ return null;
+ }
+ const [left, right] = [node.left, node.right];
+ const typeofSide =
+ left.type === 'UnaryExpression' && left.operator === 'typeof'
+ ? left
+ : right.type === 'UnaryExpression' && right.operator === 'typeof'
+ ? right
+ : null;
+ const other = typeofSide === left ? right : left;
+ if (
+ typeofSide == null ||
+ other.type !== 'Literal' ||
+ other.value !== 'boolean'
+ ) {
+ return null;
+ }
+ return typeofSide.argument;
+}
+
+/** `X !== <literal>` (or `===` when `equal`) for a literal in `values`. */
+function parseLiteralComparison(node, equal, values) {
+ if (node?.type !== 'BinaryExpression') {
+ return null;
+ }
+ const ops = equal ? EQUAL_OPERATORS : NOT_EQUAL_OPERATORS;
+ if (!ops.has(node.operator)) {
+ return null;
+ }
+ const isWanted = side => side?.type === 'Literal' && values.has(side.value);
+ if (isWanted(node.right) && !isWanted(node.left)) return node.left;
+ if (isWanted(node.left) && !isWanted(node.right)) return node.right;
+ return null;
+}
+
+const TYPE_TEST_CALLS = new Set(['isValidElement', 'isArray']);
+
+/**
+ * The value an operand tests against a type other than boolean
+ * (`typeof x === 'string'`, `isValidElement(x)`, `Array.isArray(x)`,
+ * `x instanceof Y`), negated or not; otherwise null.
+ */
+function otherTypeTestValue(node) {
+ let current = node;
+ while (current?.type === 'UnaryExpression' && current.operator === '!') {
+ current = current.argument;
+ }
+ if (current?.type === 'BinaryExpression') {
+ if (current.operator === 'instanceof') {
+ return current.left;
+ }
+ for (const [typeofSide, other] of [
+ [current.left, current.right],
+ [current.right, current.left],
+ ]) {
+ if (
+ typeofSide.type === 'UnaryExpression' &&
+ typeofSide.operator === 'typeof' &&
+ other.type === 'Literal' &&
+ typeof other.value === 'string' &&
+ other.value !== 'boolean'
+ ) {
+ return typeofSide.argument;
+ }
+ }
+ return null;
+ }
+ if (current?.type === 'CallExpression' && current.arguments.length > 0) {
+ const callee = current.callee;
+ const name =
+ callee.type === 'Identifier'
+ ? callee.name
+ : callee.type === 'MemberExpression' && !callee.computed
+ ? callee.property.name
+ : null;
+ if (name != null && TYPE_TEST_CALLS.has(name)) {
+ return current.arguments[0];
+ }
+ }
+ return null;
+}
+
+/** Flatten a chain of one logical operator into its operands. */
+function flattenLogical(node, operator) {
+ if (node?.type === 'LogicalExpression' && node.operator === operator) {
+ return [
+ ...flattenLogical(node.left, operator),
+ ...flattenLogical(node.right, operator),
+ ];
+ }
+ return [node];
+}
+
const rule = {
meta: {
type: 'problem',
@@ -219,8 +353,24 @@ const rule = {
'`true`, and `""` all pass `!= null` — leaking an empty wrapper into the ' +
'DOM. Use `isRenderable({{value}})` from `@astryxdesign/core/utils`, which ' +
'also excludes boolean and empty-string values (0 stays renderable).',
+ handRolledRenderable:
+ '`{{code}}` writes out `isRenderable({{value}})` by hand. Call ' +
+ '`isRenderable` from `@astryxdesign/core/utils` so every slot ' +
+ 'agrees on what renders nothing (null, undefined, true, false, "").',
},
- schema: [],
+ schema: [
+ {
+ type: 'object',
+ properties: {
+ baseline: {
+ type: 'object',
+ additionalProperties: {type: 'array', items: {type: 'string'}},
+ },
+ root: {type: 'string'},
+ },
+ additionalProperties: false,
+ },
+ ],
},
create(context) {
const filename = context.filename ?? context.getFilename();
@@ -228,10 +378,115 @@ const rule = {
if (filename.includes('.test.') || filename.includes('.stories.')) {
return {};
}
+ // The shared utility itself is the one place the checks are written out.
+ if (/(?:^|[\\/])isRenderable\.[cm]?[jt]sx?$/.test(filename)) {
+ return {};
+ }
const sourceCode = context.sourceCode ?? context.getSourceCode();
+ const options = context.options[0] ?? {};
+ const root = options.root ?? context.cwd;
+ const relative = path.relative(root, filename).split(path.sep).join('/');
+ // Each listed value allows as many checks as it is listed; the next one
+ // is reported.
+ const allowance = new Map();
+ for (const value of options.baseline?.[relative] ?? []) {
+ allowance.set(value, (allowance.get(value) ?? 0) + 1);
+ }
+ function isAllowed(valueText) {
+ const left = allowance.get(valueText) ?? 0;
+ if (left === 0) {
+ return false;
+ }
+ allowance.set(valueText, left - 1);
+ return true;
+ }
+
+ function reportHandRolled(chain, value) {
+ const valueText = sourceCode.getText(value);
+ if (isAllowed(valueText)) {
+ return;
+ }
+ context.report({
+ node: chain,
+ messageId: 'handRolledRenderable',
+ data: {code: sourceCode.getText(chain), value: valueText},
+ });
+ }
+
+ /**
+ * The text of the value an operand tests against another type, including
+ * a parenthesised group of such tests on one value
+ * (`isValidElement(x) || typeof x === 'string'`); otherwise null.
+ */
+ function groupTypeTestValue(operand) {
+ if (operand?.type === 'LogicalExpression') {
+ const leaves = flattenLogical(operand, operand.operator);
+ const values = leaves.map(leaf => groupTypeTestValue(leaf));
+ if (values.every(value => value != null && value === values[0])) {
+ return values[0];
+ }
+ return null;
+ }
+ const value = otherTypeTestValue(operand);
+ return value == null ? null : sourceCode.getText(value);
+ }
+
+ /**
+ * `x != null && typeof x !== 'boolean'` (render when present) and
+ * `x == null || typeof x === 'boolean'` (nothing to render): a presence
+ * test (nullish or '') and a boolean test on the same value.
+ */
+ function checkHandRolled(node) {
+ if (node.operator !== '&&' && node.operator !== '||') {
+ return false;
+ }
+ if (
+ node.parent?.type === 'LogicalExpression' &&
+ node.parent.operator === node.operator
+ ) {
+ return false;
+ }
+ const equal = node.operator === '||';
+ const presence = new Set();
+ const booleans = new Map();
+ const otherTypes = new Set();
+ for (const operand of flattenLogical(node, node.operator)) {
+ const typed = groupTypeTestValue(operand);
+ if (typed != null) {
+ otherTypes.add(typed);
+ continue;
+ }
+ const nullish = parseNullishComparison(operand);
+ if (nullish && nullish.equal === equal) {
+ presence.add(sourceCode.getText(nullish.value));
+ continue;
+ }
+ const empty = parseLiteralComparison(operand, equal, new Set(['']));
+ if (empty) {
+ presence.add(sourceCode.getText(empty));
+ continue;
+ }
+ const boolean =
+ parseBooleanTypeof(operand, equal) ??
+ parseLiteralComparison(operand, equal, new Set([true, false]));
+ if (boolean) {
+ booleans.set(sourceCode.getText(boolean), boolean);
+ }
+ }
+ for (const [text, value] of booleans) {
+ if (presence.has(text) && !otherTypes.has(text)) {
+ reportHandRolled(node, value);
+ return true;
+ }
+ }
+ return false;
+ }
function report(comparison, value, negate) {
const valueText = sourceCode.getText(value);
+ if (isAllowed(valueText)) {
+ return;
+ }
const replacement = `${negate ? '!' : ''}isRenderable(${valueText})`;
context.report({
node: comparison,
@@ -254,6 +509,11 @@ const rule = {
return {
// `{value != null && <El>{value}</El>}`
LogicalExpression(node) {
+ // One report per chain: a hand-written check that also guards JSX is
+ // reported (and spends a baseline allowance) once.
+ if (checkHandRolled(node)) {
+ return;
+ }
if (node.operator !== '&&' || !isJSX(node.right)) {
return;
}
diff --git a/internal/eslint-plugin-astryx/no-nullish-jsx-guard.test.mjs b/internal/eslint-plugin-astryx/no-nullish-jsx-guard.test.mjs
index b56d915c44..129d40e43d 100644
--- a/internal/eslint-plugin-astryx/no-nullish-jsx-guard.test.mjs
+++ b/internal/eslint-plugin-astryx/no-nullish-jsx-guard.test.mjs
@@ -24,14 +24,58 @@ const tester = new RuleTester({
// at the top level (Vitest 4 forbids calling suite functions inside an it()).
tester.run('no-nullish-jsx-guard', rule, {
valid: [
+ // ✅ The shared utility, or a presence test without a boolean test.
+ {code: `const hasLabel = isRenderable(label);`},
+ {code: `const hasValue = value != null && value !== '';`},
+ {code: `const isFlag = typeof flag === 'boolean' && flag;`},
+ // ✅ Different values in the presence and boolean tests.
+ {code: `const ok = a != null && typeof b !== 'boolean';`},
+ // ✅ Type switches test the value against another type too.
+ {
+ code: `function f(value) { return value == null || typeof value === 'boolean' || typeof value === 'number'; }`,
+ },
+ {
+ code: `const isMenu = mobileNav != null && mobileNav !== false && !isValidElement(mobileNav);`,
+ },
+ {
+ code: `const isList = items != null && items !== false && Array.isArray(items);`,
+ },
+ // ✅ A grouped type switch (AppShell's mobileNav).
+ {
+ code: `const isNode = mobileNav != null && mobileNav !== false && (isValidElement(mobileNav) || typeof mobileNav === 'string');`,
+ },
+ // ✅ The utility's own definition.
+ {
+ code: `export function isRenderable(node) { return node != null && typeof node !== 'boolean' && node !== ''; }`,
+ filename: '/repo/packages/core/src/utils/isRenderable.ts',
+ },
+ // ✅ Baselined values in their own file, for both checks.
+ {
+ code: `const hasLabel = label != null && typeof label !== 'boolean'; const C = () => <div>{slot != null && <b>{slot}</b>}</div>;`,
+ filename: '/repo/packages/core/src/Badge/Badge.tsx',
+ options: [
+ {
+ baseline: {'packages/core/src/Badge/Badge.tsx': ['label', 'slot']},
+ root: '/repo',
+ },
+ ],
+ },
// ✅ Already using isRenderable — the shipped fix.
- {code: `const C = () => <div>{isRenderable(sideNav) && <aside>{sideNav}</aside>}</div>;`},
- {code: `const C = () => <div>{isRenderable(label) ? <span>{label}</span> : null}</div>;`},
+ {
+ code: `const C = () => <div>{isRenderable(sideNav) && <aside>{sideNav}</aside>}</div>;`,
+ },
+ {
+ code: `const C = () => <div>{isRenderable(label) ? <span>{label}</span> : null}</div>;`,
+ },
// ✅ Guarded value is a data object used only as a prop, not rendered as a
// child — `!= null` is the correct guard, do not flag.
- {code: `const C = () => <div>{user != null && <Profile user={user} />}</div>;`},
- {code: `const C = () => <div>{config !== undefined ? <Widget config={config} /> : null}</div>;`},
+ {
+ code: `const C = () => <div>{user != null && <Profile user={user} />}</div>;`,
+ },
+ {
+ code: `const C = () => <div>{config !== undefined ? <Widget config={config} /> : null}</div>;`,
+ },
// ✅ Boolean-style guard with no nullish comparison at all.
{code: `const C = () => <div>{isOpen && <Menu />}</div>;`},
@@ -43,13 +87,19 @@ tester.run('no-nullish-jsx-guard', rule, {
// ✅ Nullish comparison guarding JSX, but the guarded value is NOT the
// thing being rendered (a sibling value is).
- {code: `const C = () => <div>{count != null && <Badge>{label}</Badge>}</div>;`},
+ {
+ code: `const C = () => <div>{count != null && <Badge>{label}</Badge>}</div>;`,
+ },
// ✅ Non-nullish comparison (numeric) — out of scope.
- {code: `const C = () => <div>{items.length > 0 && <List>{items}</List>}</div>;`},
+ {
+ code: `const C = () => <div>{items.length > 0 && <List>{items}</List>}</div>;`,
+ },
// ✅ Equality nullish check whose rendered branch does not contain the value.
- {code: `const C = () => <div>{value == null ? <Empty /> : <Filled />}</div>;`},
+ {
+ code: `const C = () => <div>{value == null ? <Empty /> : <Filled />}</div>;`,
+ },
// ✅ Test fixtures are skipped.
{
@@ -59,6 +109,53 @@ tester.run('no-nullish-jsx-guard', rule, {
],
invalid: [
+ // ❌ isRenderable written out by hand (Badge's form), outside JSX.
+ {
+ code: `const hasLabel = label !== '' && label != null && typeof label !== 'boolean';`,
+ errors: [{messageId: 'handRolledRenderable'}],
+ },
+ {
+ code: `const hasTitle = title != null && title !== '' && title !== false;`,
+ errors: [{messageId: 'handRolledRenderable'}],
+ },
+ {
+ code: `const hasToolbar = props.toolbar != null && typeof props.toolbar !== 'boolean';`,
+ errors: [{messageId: 'handRolledRenderable'}],
+ },
+ // ❌ The negated form: nothing to render.
+ {
+ code: `function f(rendered) { if (rendered == null || typeof rendered === 'boolean') { return null; } return rendered; }`,
+ errors: [{messageId: 'handRolledRenderable'}],
+ },
+ // ❌ A hand-written check that also guards JSX is one report, not two.
+ {
+ code: `const C = () => <div>{label != null && typeof label !== 'boolean' && <span>{label}</span>}</div>;`,
+ errors: [{messageId: 'handRolledRenderable'}],
+ },
+ // ❌ One more check of a listed value than the baseline allows.
+ {
+ code: `const a = label != null && typeof label !== 'boolean'; const b = label != null && typeof label !== 'boolean';`,
+ filename: '/repo/packages/core/src/Badge/Badge.tsx',
+ options: [
+ {
+ baseline: {'packages/core/src/Badge/Badge.tsx': ['label']},
+ root: '/repo',
+ },
+ ],
+ errors: [{messageId: 'handRolledRenderable'}],
+ },
+ // ❌ A baseline for another file or another value does not cover it.
+ {
+ code: `const hasLabel = label != null && typeof label !== 'boolean';`,
+ filename: '/repo/packages/core/src/Badge/Badge.tsx',
+ options: [
+ {
+ baseline: {'packages/core/src/Badge/Badge.tsx': ['title']},
+ root: '/repo',
+ },
+ ],
+ errors: [{messageId: 'handRolledRenderable'}],
+ },
// ❌ Canonical slot leak: `x != null && <El>{x}</El>`.
{
code: `const C = () => <div>{sideNav != null && <aside>{sideNav}</aside>}</div>;`,
diff --git a/internal/eslint-plugin-astryx/rule-baseline.mjs b/internal/eslint-plugin-astryx/rule-baseline.mjs
new file mode 100644
index 0000000000..0d2675ac2b
--- /dev/null
+++ b/internal/eslint-plugin-astryx/rule-baseline.mjs
@@ -0,0 +1,96 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file rule-baseline.mjs
+ * @description Writes (or, with --check, verifies) a rule's baseline: the
+ * violations, per repo-relative file, that existed when the repository config
+ * began enforcing it. The rule takes the baseline as `{baseline, root}` and
+ * reports only what it does not list. Shared by each rule's
+ * `<rule>.baseline.mjs` so the write and `--check` flows stay one.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {ESLint} from 'eslint';
+
+/**
+ * Lint `targets` with the repository config and an empty baseline, so every
+ * violation in `scope` is reported, then write or check `baselineFile`.
+ *
+ * `entryFromMessage` turns a report into its baseline entry. With `unique`,
+ * an entry is listed once per file; without it, once per report, so the rule
+ * can allow exactly that many.
+ */
+export async function runRuleBaseline({
+ ruleId,
+ scope,
+ targets,
+ baselineFile,
+ entryFromMessage,
+ unique,
+ noun,
+ argv = process.argv,
+}) {
+ const root = path.resolve(import.meta.dirname, '../..');
+ const name = ruleId.replace(/^@astryx\//, '');
+ const eslint = new ESLint({
+ cwd: root,
+ // Some packages' sources are ignored by the repo config entirely.
+ errorOnUnmatchedPattern: false,
+ ruleFilter: ({ruleId: id}) => id === ruleId,
+ overrideConfig: [
+ {
+ files: scope.files,
+ ignores: scope.ignores,
+ rules: {[ruleId]: ['error', {baseline: {}, root}]},
+ },
+ ],
+ });
+ const results = await eslint.lintFiles(targets);
+
+ const found = new Map();
+ for (const result of results) {
+ for (const message of result.messages) {
+ if (message.ruleId !== ruleId) {
+ continue;
+ }
+ const entry = entryFromMessage(message.message);
+ if (entry == null) {
+ continue;
+ }
+ const file = path
+ .relative(root, result.filePath)
+ .split(path.sep)
+ .join('/');
+ if (!found.has(file)) {
+ found.set(file, []);
+ }
+ found.get(file).push(entry);
+ }
+ }
+ const baseline = Object.fromEntries(
+ [...found.keys()]
+ .sort()
+ .map(file => [
+ file,
+ (unique ? [...new Set(found.get(file))] : found.get(file)).sort(),
+ ]),
+ );
+
+ if (argv.includes('--check')) {
+ const current = fs.readFileSync(baselineFile, 'utf8');
+ if (JSON.stringify(JSON.parse(current)) !== JSON.stringify(baseline)) {
+ console.error(
+ `${name} baseline is out of date; run this script without --check.`,
+ );
+ process.exit(1);
+ }
+ console.log(`${name} baseline is up to date.`);
+ return;
+ }
+ fs.writeFileSync(baselineFile, `${JSON.stringify(baseline, null, 2)}\n`);
+ const count = Object.values(baseline).reduce((n, list) => n + list.length, 0);
+ console.log(
+ `Wrote ${count} ${noun} in ${found.size} files to ${path.relative(root, baselineFile)}.`,
+ );
+}