diff --git a/contributingGuides/LINTING.md b/contributingGuides/LINTING.md index e1aeeb21e6ab..97b52cc124fa 100644 --- a/contributingGuides/LINTING.md +++ b/contributingGuides/LINTING.md @@ -185,5 +185,6 @@ The env-var names and TSV format are unchanged from the previous `eslint-seatbel - [Ratcheting errors](https://www.notion.com/blog/how-we-evolved-our-code-notions-ratcheting-system-using-custom-eslint-rules). - [`CONSISTENCY-5`: Justify lint rule disables](../.claude/skills/app-coding-standards/rules/consistency-5-justify-eslint-disable.md) — when `eslint-disable` is acceptable, and how to document it. - `rulesdir/no-manual-memoization` forbids `React.memo`, `useMemo`, and `useCallback` when React Compiler memoizes the file. Callbacks passed to `useFocusEffect` may retain `useCallback`, which React Navigation requires. +- `rulesdir/no-opaque-namespace-usage` forbids the `import * as NS` usages of an internal module that knip cannot track: a computed key (`NS[key]`), enumeration (`Object.keys(NS)`, `for...in`, `for...of`), rest destructuring (`const {a, ...rest} = NS`), a destructuring default (`const {a = NS} = obj`) and a namespace assigned to a variable that is never member-accessed (`const alias = NS`, `const x = cond ? NS : other`). Knip then treats every export of the module as used, so unused exports stay hidden. Import the members by name, or access them as `NS.member`. - [`STYLE.md`](./STYLE.md) — the coding style rules many of our ESLint rules enforce. - [`REACT_COMPILER.md`](./REACT_COMPILER.md) — separate compiler-compliance CI check that runs alongside lint. diff --git a/eslint-plugin-local-rules/no-opaque-namespace-usage.js b/eslint-plugin-local-rules/no-opaque-namespace-usage.js new file mode 100644 index 000000000000..8447c652547e --- /dev/null +++ b/eslint-plugin-local-rules/no-opaque-namespace-usage.js @@ -0,0 +1,296 @@ +const name = 'no-opaque-namespace-usage'; + +const meta = { + type: 'problem', + docs: { + description: 'Disallow the namespace import usages of an internal module that knip cannot track, which hide the unused exports of the module.', + recommended: 'error', + }, + schema: [], + messages: { + opaqueNamespaceUsage: + 'Using the namespace `{{name}}` this way ({{usage}}) makes knip treat every export of the module as used, so unused exports stay hidden. Import the members you need by name, or access them as `{{name}}.member`.', + }, +}; + +// The forms checked here are the namespace usages that knip 6.34 treats as "every export of the module is used" (its internal OPAQUE mark), so unused exports of the module are not reported. +// Verified by running knip with `include: ["nsExports", "nsTypes"]`. Every other whole-namespace use (`f(NS)`, `console.log(NS)`, `typeof NS`, `Reflect.ownKeys(NS)`, `Object.assign({}, NS)`, spread into a call, an array or JSX, return, export, `in`, ...) +// does not hide anything: knip either does not see the use or sees only a bare reference, and then it reports the exports it cannot attribute (as `nsExports` when no importer of the module accesses `NS.member`, otherwise as `exports`). +// Re-verify the forms when knip is upgraded. +// Known differences from knip that are not worth the complexity (found by a differential fuzz of the rule against knip 6.34, none occurs in the repo): knip ignores scope, so an alias of a shadowed +// or parenthesized namespace (`function f(NS) {const a = NS}`, `const a = (NS)`) and two `{key: NS}` declarations with the same variable and key are handled differently by it; type-only namespaces used as values are invalid TypeScript. +// Knip only matches a bare identifier, so TypeScript wrappers such as `NS as T` or `NS!` make a usage tracked, and the rule does not look through them. + +// Namespace imports of packages are out of scope: knip only reports unused exports of the repo's own modules. +// Knip registers an alias (`const A = X`, `cond ? X : y`, `{...X}`) for every import that resolves to a file of the repo, whatever the kind: named, default, namespace, type-only +// (`import type`, `import {type X}`), `import X = require()`, JSON and asset files, re-exports, path aliases and files its config ignores. An import of a package (including `node:` modules) +// or an unresolvable one is not registered. The rule has no resolver, so INTERNAL_SOURCE_PATTERN stands in for "resolves to a file of the repo". +// Keep the aliases in sync with `paths` in tsconfig.base.json. +const INTERNAL_SOURCE_PATTERN = /^(@(assets|components|hooks|libs|navigation|pages|prompts|styles|src|userActions|github|scripts|selectors|server)(\/|$)|tests\/|\.{1,2}(\/|$))/; +const ENUMERATION_METHODS = new Set(['keys', 'values', 'entries', 'getOwnPropertyNames']); + +/** + * @param {import('estree').Node} property + * @returns {boolean} Whether a computed key is a string that knip resolves statically: `NS['a']` or a template without substitutions. A numeric key is not. + */ +function isStaticStringKey(property) { + return (property.type === 'Literal' && typeof property.value === 'string') || (property.type === 'TemplateLiteral' && property.expressions.length === 0); +} + +/** + * @param {import('estree').Node} node + * @param {string} objectName + * @returns {boolean} Whether the node is a member access on the identifier with the given name. + */ +function isMemberAccessOn(node, objectName) { + return node.type === 'MemberExpression' && node.object.type === 'Identifier' && node.object.name === objectName; +} + +/** + * @param {import('estree').Node} pattern + * @returns {boolean} Whether the node is an object pattern with a rest element, such as `{a, ...rest}`. + */ +function hasRestElement(pattern) { + return pattern.type === 'ObjectPattern' && pattern.properties.some((property) => property.type === 'RestElement'); +} + +/** + * @param {import('estree').Node} callee + * @returns {boolean} Whether the callee is `Object.keys`, `Object.values`, `Object.entries` or `Object.getOwnPropertyNames`. + */ +function isObjectEnumerationCallee(callee) { + return isMemberAccessOn(callee, 'Object') && !callee.computed && ENUMERATION_METHODS.has(callee.property.name); +} + +/** + * @param {import('estree').Node} node The parent of the reference. + * @returns {boolean} Whether the node is a default value in `const {a = NS} = obj`, a destructured property of a declarator that has an initializer. + */ +function isTopLevelDestructuringDefault(node) { + if (node.type !== 'AssignmentPattern' || node.parent.type !== 'Property') { + return false; + } + const pattern = node.parent.parent; + const declarator = pattern.parent; + return declarator.type === 'VariableDeclarator' && !!declarator.init; +} + +/** + * @param {import('estree').Node} reference The identifier that references the namespace. + * @returns {string | undefined} The label of the usage that makes knip treat the whole module as used, or undefined when knip tracks the usage. + */ +function getOpaqueUsage(reference) { + const {parent} = reference; + + // Knip cannot tell which export is read by `NS[key]`, `NS?.[key]` or `NS[0]`. A string key or a template without substitutions is resolved statically. + if (parent.type === 'MemberExpression' && parent.object === reference && parent.computed && !isStaticStringKey(parent.property)) { + return 'computed key'; + } + + // Knip treats `Object.keys(NS)`, `Object.values(NS)`, `Object.entries(NS)` and `Object.getOwnPropertyNames(NS)` as reading every export, + // in any argument position. Other calls such as `Reflect.ownKeys(NS)`, `Object['keys'](NS)` or `_.keys(NS)` are not recognized, so they are tracked. + if (parent.type === 'CallExpression' && isObjectEnumerationCallee(parent.callee)) { + return 'enumeration'; + } + + // Knip treats `for (key in NS)` and `for (value of NS)` as reading every export. + if (parent.type === 'ForInStatement' || parent.type === 'ForOfStatement') { + return 'enumeration'; + } + + // Knip cannot tell which exports end up in the rest object of `const {a, ...rest} = NS`. An assignment `({a, ...rest} = NS)` is tracked. + if (parent.type === 'VariableDeclarator' && hasRestElement(parent.id)) { + return 'rest destructuring'; + } + + // In a declarator with an initializer, knip treats the default value of a top-level destructured property, `const {a = NS} = obj`, as an opaque use. + // A nested pattern, a parameter default and a declarator without an initializer, such as the head of `for (const {a = NS} of list)`, are tracked. + if (isTopLevelDestructuringDefault(parent)) { + return 'destructuring default'; + } + + return undefined; +} + +/** + * @param {import('estree').Node} node + * @returns {boolean} Whether the node is a declarator of an exported declaration, such as `export const a = ...`. + */ +function isExportedDeclarator(node) { + const declaration = node.parent; + return declaration.parent.type === 'ExportNamedDeclaration'; +} + +/** + * Knip follows a namespace assigned to a variable only through the member accesses of that variable, so these forms are opaque + * unless the alias is member-accessed somewhere in the file (knip stops hiding them only when no importer of the module accesses `NS.member` in any file, a condition a per-file rule cannot see, so the rule is stricter): `const a = NS`, `const a = cond ? NS : other`, `const a = {...NS}` and `const a = {key: NS}`. + * Passing or exporting the alias does not count as an access. An exported `const a = {...NS}` is tracked. + * @param {import('estree').Node} reference The identifier that references the namespace. + * @returns {{aliasName: string, key?: string, declaratorStart: number} | undefined} The variable the namespace is assigned to, the object key for the `{key: NS}` form, and where the declaration starts. + */ +function getAssignedAlias(reference) { + const {parent} = reference; + let declarator; + let key; + + // Knip registers `const {value: Alias = X} = init` (a default of a property of the top-level pattern) as an alias named `Alias`. + if (parent.type === 'AssignmentPattern' && parent.right === reference && parent.left.type === 'Identifier' && isTopLevelDestructuringDefault(parent)) { + return {aliasName: parent.left.name, key: undefined, declaratorStart: parent.parent.parent.parent.range[0]}; + } + + if (parent.type === 'VariableDeclarator') { + declarator = parent; + } else if (parent.type === 'ConditionalExpression' && parent.test !== reference && parent.parent.type === 'VariableDeclarator') { + declarator = parent.parent; + } else if (parent.type === 'SpreadElement' && parent.parent.type === 'ObjectExpression' && parent.parent.parent.type === 'VariableDeclarator') { + declarator = isExportedDeclarator(parent.parent.parent) ? undefined : parent.parent.parent; + } else if ( + parent.type === 'Property' && + !parent.computed && + parent.key.type === 'Identifier' && + parent.parent.type === 'ObjectExpression' && + parent.parent.parent.type === 'VariableDeclarator' + ) { + declarator = parent.parent.parent; + key = parent.key.name; + } + + if (!declarator || declarator.id.type !== 'Identifier') { + return undefined; + } + return {aliasName: declarator.id.name, key, declaratorStart: declarator.range[0]}; +} + +/** + * Knip counts `export const a = {...X}` (also nested in an object, `{k: {...X}}`) of any import of the repo as an access to every alias named `a`, in any scope and in any order. + * @param {import('estree').Node} reference The identifier that references the import. + * @returns {string | undefined} The name of the exported variable the import is spread into. + */ +function getExportedSpreadName(reference) { + if (reference.parent.type !== 'SpreadElement') { + return undefined; + } + let node = reference.parent.parent; + // Knip descends only through properties with an identifier key, so `{'nested': {...X}}` is not followed. + while (node.type === 'ObjectExpression' && node.parent.type === 'Property' && node.parent.key.type === 'Identifier') { + node = node.parent.parent; + } + if (node.type !== 'ObjectExpression' || node.parent.type !== 'VariableDeclarator' || node.parent.id.type !== 'Identifier' || !isExportedDeclarator(node.parent)) { + return undefined; + } + return node.parent.id.name; +} + +/** @type {import('eslint').Rule.RuleModule['create']} */ +function create(context) { + // Knip matches aliases by name and ignores scopes, so the rule collects names the same way. Knip also registers an alias when it reaches the declaration + // and counts only the member accesses it reaches afterwards, in source order, whatever the scope. So an access is stored as the position of its latest occurrence. + const lastMemberAccessStart = new Map(); + const pendingAliases = []; + const otherAliasDeclarations = []; + const exportedSpreadNames = new Set(); + + /** + * @param {string} readKey `alias` or `alias.key` + * @param {import('estree').Node} node + */ + function recordMemberAccess(readKey, node) { + lastMemberAccessStart.set(readKey, Math.max(lastMemberAccessStart.get(readKey) ?? -1, node.range[0])); + } + + /** + * @param {import('estree').Identifier} identifier + * @param {string} usage + */ + function report(identifier, usage) { + context.report({node: identifier, messageId: 'opaqueNamespaceUsage', data: {name: identifier.name, usage}}); + } + + /** Whether an alias is member-accessed is only known once the whole file is traversed, so the aliases are reported on Program:exit. */ + function reportUnreadAliases() { + // Aliases with the same name are one alias for knip: an access counts once it follows the first declaration of the name. + const firstDeclarationStart = new Map(); + for (const {aliasName, key, declaratorStart} of [...pendingAliases, ...otherAliasDeclarations]) { + const readKey = key ? `${aliasName}.${key}` : aliasName; + firstDeclarationStart.set(readKey, Math.min(firstDeclarationStart.get(readKey) ?? Infinity, declaratorStart)); + } + for (const {identifier, aliasName, key} of pendingAliases) { + const readKey = key ? `${aliasName}.${key}` : aliasName; + const isRead = (lastMemberAccessStart.get(readKey) ?? -1) > firstDeclarationStart.get(readKey) || (!key && exportedSpreadNames.has(aliasName)); + if (!isRead) { + report(identifier, 'unread alias'); + } + } + } + + /** + * @param {import('estree').Node} bindingNode The import specifier or the `import Name = require()` declaration that declares the local name. + * @param {boolean} isInternal Whether the import resolves to a module of the repo. + * @param {boolean} isCheckedNamespace Whether the binding is a value namespace import of an internal module. + */ + function processImportBinding(bindingNode, isInternal, isCheckedNamespace) { + // Only references bound to this import are checked, so a same-named local or parameter is ignored. + for (const variable of context.sourceCode.getDeclaredVariables(bindingNode)) { + for (const {identifier} of variable.references) { + const spreadName = isInternal ? getExportedSpreadName(identifier) : undefined; + if (spreadName) { + exportedSpreadNames.add(spreadName); + } + if (isCheckedNamespace) { + const usage = getOpaqueUsage(identifier); + if (usage) { + report(identifier, usage); + continue; + } + } + const alias = getAssignedAlias(identifier); + if (!alias) { + continue; + } + if (isCheckedNamespace) { + pendingAliases.push({identifier, ...alias}); + } else if (isInternal && !alias.key) { + // Knip registers an alias of every import that resolves to a module of the repo (named, default, type-only, `import = require`, JSON, assets, re-exports), under the same name, + // which is only a declaration for the source order. It does not register an alias of a package or an unresolved import, nor the `{key: value}` form of a non-namespace import. + otherAliasDeclarations.push(alias); + } + } + } + } + + return { + MemberExpression(node) { + if (node.object.type === 'Identifier') { + recordMemberAccess(node.object.name, node); + } + + // Collect `holder.key.member` and `holder.key['member']`, which read the `{key: NS}` form. + const holder = node.object; + const isStaticMember = !node.computed || isStaticStringKey(node.property); + if (holder.type === 'MemberExpression' && !holder.computed && holder.object.type === 'Identifier' && isStaticMember) { + recordMemberAccess(`${holder.object.name}.${holder.property.name}`, node); + } + }, + + ImportDeclaration(node) { + const isInternal = INTERNAL_SOURCE_PATTERN.test(node.source.value); + for (const specifier of node.specifiers) { + // A type-only namespace import has no runtime exports to hide, so it is never checked, but knip still registers its aliases like any other import. + const isCheckedNamespace = isInternal && specifier.type === 'ImportNamespaceSpecifier' && node.importKind !== 'type'; + processImportBinding(specifier, isInternal, isCheckedNamespace); + } + }, + + // `import Name = require('./module')` is an import for knip, a default one. + TSImportEqualsDeclaration(node) { + const reference = node.moduleReference; + if (reference.type === 'TSExternalModuleReference' && reference.expression.type === 'Literal' && typeof reference.expression.value === 'string') { + processImportBinding(node, INTERNAL_SOURCE_PATTERN.test(reference.expression.value), false); + } + }, + + 'Program:exit': reportUnreadAliases, + }; +} + +export {name, meta, create}; diff --git a/oxlint.config.mts b/oxlint.config.mts index 11412827cebd..af0e6eceb0a8 100644 --- a/oxlint.config.mts +++ b/oxlint.config.mts @@ -325,6 +325,7 @@ export default await buildOxlintConfig({ 'rulesdir/no-layout-spacing-conditional': 'error', 'rulesdir/no-onyx-get-snapshot-key': 'error', 'rulesdir/no-onyx-loading-status': 'error', + 'rulesdir/no-opaque-namespace-usage': 'error', 'rulesdir/no-raw-typography': 'error', 'rulesdir/no-unsafe-onyx-read': 'error', 'rulesdir/prefer-type-fest': 'error', diff --git a/src/components/Icon/GroupDefaultAvatars.ts b/src/components/Icon/GroupDefaultAvatars.ts index 7b4afb7c7309..2c920e7ab6e6 100644 --- a/src/components/Icon/GroupDefaultAvatars.ts +++ b/src/components/Icon/GroupDefaultAvatars.ts @@ -17,4 +17,25 @@ import Avatar16 from '@assets/images/avatars/group/default-avatar_16.svg'; import Avatar17 from '@assets/images/avatars/group/default-avatar_17.svg'; import Avatar18 from '@assets/images/avatars/group/default-avatar_18.svg'; -export {Avatar1, Avatar2, Avatar3, Avatar4, Avatar5, Avatar6, Avatar7, Avatar8, Avatar9, Avatar10, Avatar11, Avatar12, Avatar13, Avatar14, Avatar15, Avatar16, Avatar17, Avatar18}; +const groupDefaultAvatars = { + Avatar1, + Avatar2, + Avatar3, + Avatar4, + Avatar5, + Avatar6, + Avatar7, + Avatar8, + Avatar9, + Avatar10, + Avatar11, + Avatar12, + Avatar13, + Avatar14, + Avatar15, + Avatar16, + Avatar17, + Avatar18, +}; + +export default groupDefaultAvatars; diff --git a/src/components/Icon/MCCIcons.ts b/src/components/Icon/MCCIcons.ts index 922fb274f23d..5b6f1a38a538 100644 --- a/src/components/Icon/MCCIcons.ts +++ b/src/components/Icon/MCCIcons.ts @@ -12,4 +12,6 @@ import Services from '@assets/images/MCCGroupIcons/MCC-Services.svg'; import Taxi from '@assets/images/MCCGroupIcons/MCC-Taxi.svg'; import Utilities from '@assets/images/MCCGroupIcons/MCC-Utilities.svg'; -export {Airlines, Commuter, Gas, Goods, Groceries, Hotel, Mail, Meals, Rental, Services, Taxi, Miscellaneous, Utilities}; +const mccIcons = {Airlines, Commuter, Gas, Goods, Groceries, Hotel, Mail, Meals, Rental, Services, Taxi, Miscellaneous, Utilities}; + +export default mccIcons; diff --git a/src/components/Icon/WorkspaceDefaultAvatars.ts b/src/components/Icon/WorkspaceDefaultAvatars.ts index 53d2ca088118..5b8ecec22284 100644 --- a/src/components/Icon/WorkspaceDefaultAvatars.ts +++ b/src/components/Icon/WorkspaceDefaultAvatars.ts @@ -36,7 +36,7 @@ import WorkspaceX from '@assets/images/avatars/workspace/default-avatar_x.svg'; import WorkspaceY from '@assets/images/avatars/workspace/default-avatar_y.svg'; import WorkspaceZ from '@assets/images/avatars/workspace/default-avatar_z.svg'; -export { +const workspaceDefaultAvatars = { Workspace0, Workspace1, Workspace2, @@ -75,3 +75,5 @@ export { WorkspaceZ, WorkspaceBuilding, }; + +export default workspaceDefaultAvatars; diff --git a/src/hooks/useEReceipt.tsx b/src/hooks/useEReceipt.tsx index 0327d6cdc6d5..4da6c58ff71a 100644 --- a/src/hooks/useEReceipt.tsx +++ b/src/hooks/useEReceipt.tsx @@ -1,5 +1,5 @@ import * as eReceiptBGs from '@components/Icon/EReceiptBGs'; -import * as MCCIcons from '@components/Icon/MCCIcons'; +import MCCIcons from '@components/Icon/MCCIcons'; import type {TransactionListItemType} from '@components/Search/SearchList/ListItem/types'; import {getTransactionDetails} from '@libs/ReportUtils'; @@ -31,7 +31,7 @@ export default function useEReceipt(transactionData: Transaction | TransactionLi const titleColor = colorStyles?.titleColor; const transactionDetails = getTransactionDetails(transactionData); const transactionMCCGroup = transactionDetails?.mccGroup; - const MCCIcon = transactionMCCGroup ? MCCIcons[`${transactionMCCGroup}`] : undefined; + const MCCIcon = transactionMCCGroup ? MCCIcons[transactionMCCGroup] : undefined; const tripIcon = getTripEReceiptIcon(expensifyIcons, transactionData); const backgroundImage = backgroundImages[colorCode]; diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 1fc0662c8f90..e62681b03b2c 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -1,7 +1,7 @@ import FallbackAvatar from '@assets/images/avatars/fallback-avatar.svg'; -import * as defaultGroupAvatars from '@components/Icon/GroupDefaultAvatars'; -import * as defaultWorkspaceAvatars from '@components/Icon/WorkspaceDefaultAvatars'; +import defaultGroupAvatars from '@components/Icon/GroupDefaultAvatars'; +import defaultWorkspaceAvatars from '@components/Icon/WorkspaceDefaultAvatars'; import type {LocaleContextProps, LocalizedTranslate} from '@components/LocaleContextProvider'; import type {MoneyRequestAmountInputProps} from '@components/MoneyRequestAmountInput'; import type {PersonalDetailsByLogin} from '@components/PersonalDetailsByLoginProvider'; diff --git a/tests/tooling/noManualMemoization.test.ts b/tests/tooling/noManualMemoization.test.ts index 7a13aae2f385..fc648326b038 100644 --- a/tests/tooling/noManualMemoization.test.ts +++ b/tests/tooling/noManualMemoization.test.ts @@ -7,7 +7,7 @@ import {Linter} from 'eslint'; import type {LintMessage} from '../../scripts/lint/types'; import checkReactCompilerWithOxc from '../../config/reactCompiler/checkWithOxc.mjs'; -import * as rule from '../../eslint-plugin-local-rules/no-manual-memoization'; +import {create, meta} from '../../eslint-plugin-local-rules/no-manual-memoization'; import {filterReactCompilerMessages} from '../../scripts/lint/processors/ReactCompilerFilter'; import {LINT_SEVERITY} from '../../scripts/lint/types'; @@ -16,7 +16,7 @@ function isRuleModule(value: unknown): value is Rule.RuleModule { } function lint(code: string) { - const ruleModule: unknown = rule; + const ruleModule: unknown = {create, meta}; if (!isRuleModule(ruleModule)) { throw new TypeError('Expected a local ESLint rule module'); } diff --git a/tests/unit/NoOpaqueNamespaceUsageRuleTest.ts b/tests/unit/NoOpaqueNamespaceUsageRuleTest.ts new file mode 100644 index 000000000000..776d1753deb2 --- /dev/null +++ b/tests/unit/NoOpaqueNamespaceUsageRuleTest.ts @@ -0,0 +1,557 @@ +import type {Rule} from 'eslint'; + +import {RuleTester} from 'eslint'; +import {parser as tsParser} from 'typescript-eslint'; + +type LocalRuleModule = Rule.RuleModule & { + name: string; +}; + +function isLocalRuleModule(ruleModule: unknown): ruleModule is LocalRuleModule { + if (typeof ruleModule !== 'object' || ruleModule === null) { + return false; + } + + const ruleName: unknown = Reflect.get(ruleModule, 'name'); + const create: unknown = Reflect.get(ruleModule, 'create'); + const meta: unknown = Reflect.get(ruleModule, 'meta'); + + return typeof ruleName === 'string' && typeof create === 'function' && typeof meta === 'object' && meta !== null; +} + +const ruleModule: unknown = require('../../eslint-plugin-local-rules/no-opaque-namespace-usage'); + +if (!isLocalRuleModule(ruleModule)) { + throw new TypeError('Expected no-opaque-namespace-usage to export an ESLint rule module.'); +} + +const tsRuleTester = new RuleTester({ + languageOptions: { + ecmaVersion: 2022, + sourceType: 'module', + parser: tsParser, + }, +}); + +const tsxRuleTester = new RuleTester({ + languageOptions: { + ecmaVersion: 2022, + sourceType: 'module', + parser: tsParser, + parserOptions: {ecmaFeatures: {jsx: true}}, + }, +}); + +const IMPORT = "import * as Utils from '@libs/Utils';"; + +/** + * @param usage The label of the usage the rule is expected to report. + * @returns The expected rule error for the `Utils` namespace. + */ +function usageError(usage: string): {messageId: string; data: Record} { + return {messageId: 'opaqueNamespaceUsage', data: {name: 'Utils', usage}}; +} + +describe('no-opaque-namespace-usage', () => { + tsRuleTester.run(ruleModule.name, ruleModule, { + valid: [ + // Given a plain member access, which knip tracks per export. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} export const value = Utils.member;`}, + // Given a string literal key, which knip resolves statically. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} export const value = Utils['member'];`}, + // Given a template key without substitutions, which knip resolves statically. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} export const value = Utils[\`member\`];`}, + // Given plain destructuring, which names the used exports. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const {a, b} = Utils; export {a, b};`}, + // Given computed-key destructuring, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const key = 'a'; const {[key]: value} = Utils; export {value};`}, + // Given an assignment-expression rest, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} let a; let rest; ({a, ...rest} = Utils); export {a, rest};`}, + // Given the namespace used as the key of another object, not as the object. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const map = {}; export const value = map[Utils];`}, + // Given the namespace used as the computed key of an object literal, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const holder = {[Utils]: 1}; export {holder};`}, + // Given a namespace passed as an argument, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} register(Utils);`}, + // Given a returned namespace, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} export function get() { return Utils; }`}, + // Given a spread into a declared array, which is not an alias. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const list = [...Utils]; register(list);`}, + // Given a spread into an object literal passed to a call, which is not an alias. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} register({...Utils});`}, + // Given an exported spread alias, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} export const copy = {...Utils};`}, + // Given a default value in a nested array pattern, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const [[a = Utils]] = list; export {a};`}, + // Given a default value in the head of a for-of loop, which has no initializer and which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} for (const {a = Utils} of list) { use(a); }`}, + // Given `Object.freeze`, which is not an enumeration and knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} export const frozen = Object.freeze(Utils);`}, + // Given a `keys` method of another object, which is not an enumeration of the namespace. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} Registry.keys(Utils);`}, + // Given `Object[keys]` with a computed callee, which knip does not recognize as an enumeration and tracks. It guards the `!callee.computed` check. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const keys = 'values'; Object[keys](Utils);`}, + // Given a namespace returned from a ternary, which is not assigned to a variable. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} export function get(flag) { return flag ? Utils : other; }`}, + // Given the namespace used as the test of a ternary, which is not an alias. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} export const value = Utils ? 1 : 2;`}, + // Given a parameter that shadows the namespace name. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} export function run(Utils) { return Utils[Utils.key]; }`}, + // Given a TypeScript `as` wrapper around a computed key, which knip does not see through. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} export const value = (Utils as Foo)[key];`}, + // Given a rest destructuring of a wrapped namespace, which knip does not see through. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const {a, ...rest} = Utils as Foo; export {a, rest};`}, + // Given an alias wrapped by `as`, which knip does not see through. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const Alias = Utils as Foo; export {Alias};`}, + // Given an alias whose members are read, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const Alias = Utils; Alias.member();`}, + // Given a ternary alias whose members are read, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const target = flag ? Utils : other; target.member();`}, + // Given a spread alias whose members are read, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const copy = {...Utils}; copy.member();`}, + // Given an object property alias whose members are read, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const holder = {utils: Utils}; holder.utils.member();`}, + // Given an object property alias whose members are read by a string key, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const holder = {utils: Utils}; holder.utils['member']();`}, + // Given a string object property key that holds the namespace, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const holder = {'utils': Utils}; export {holder};`}, + // Given a call argument inside an object literal alias, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const holder = {utils: wrap(Utils)}; export {holder};`}, + // Given an alias read after its declaration inside a function declared after it, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const Alias = Utils; function run() {Alias.member();} run();`}, + // Given an alias read both before and after its declaration, where the later read is the one knip counts. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} function run() {Alias.member();} const Alias = Utils; Alias.member(); run();`}, + // Given two aliases with the same name, where knip matches by name and the read follows the first declaration. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} function first() {const Alias = Utils; return 1;} function second() {const Alias = Utils; return Alias.member();} first(); second();`}, + // Given an alias of a named import that is read before a namespace alias with the same name is declared, where knip registers both under one name. + // When the rule checks how the namespace is used. + // Then nothing is reported. + { + code: `${IMPORT} import {obj} from './other'; function first() {const Alias = obj; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + }, + // Given a ternary alias and a spread alias of a named import, and a default import alias, which knip registers like a namespace alias. + // When the rule checks how the namespace is used. + // Then nothing is reported. + { + code: `${IMPORT} import Def, {obj} from './other'; function first() {const Alias = flag ? obj : Def; return Alias.member;} function second() {const Alias = {...obj}; return Alias.member;} function third() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second(); third();`, + }, + // Given an exported spread of the namespace, which knip counts as an access to every alias with the same name, whatever the scope and order. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} Utils.used(); export const copy = {...Utils}; function run() {const copy = Utils; return 1;} run();`}, + // Given an exported nested spread and an exported spread of an internal named import, which knip counts the same way. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} import {obj} from './other'; Utils.used(); export const copy = {a: {...obj}}; function run() {const copy = Utils; return 1;} run();`}, + // Given an alias that a destructuring default of a named import declares, which knip registers and reads before a namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then nothing is reported. + { + code: `${IMPORT} import {obj} from './other'; function first() {const {value: Alias = obj} = source; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + }, + // Given an alias read by a parameter of the same name after the declaration, which knip counts because it matches aliases by name. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const Alias = Utils; function read(Alias) {return Alias.member();} read({});`}, + // Given an alias read by `Alias?.member`, which is a member access for knip. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const Alias = Utils; Alias?.member();`}, + // Given an object literal that holds the namespace in a call argument, which is not an alias. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} register({utils: Utils});`}, + // Given a named import, which is not a namespace. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: "import {member} from '@libs/Utils'; export const value = member[key];"}, + // Given a type-only namespace import, which has no runtime exports to hide. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: "import type * as Utils from '@libs/Utils'; export const value = Utils[key];"}, + // Given a namespace import of a package, which knip does not report unused exports for. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: "import * as Pkg from 'some-package'; export const value = Pkg[key];"}, + // Given an alias of a type-only default import of an internal module, which knip registers as an alias, so the read counts for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then nothing is reported. + { + code: `${IMPORT} import type Def from './other'; function first() {const Alias = Def; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + }, + // Given a ternary alias of an inline type named import of an internal module, which knip registers as an alias, so the read counts for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then nothing is reported. + { + code: `${IMPORT} import {type member as Item} from './other'; function first() {const Alias = flag ? Item : 1; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + }, + // Given a spread alias of a type-only namespace import of an internal module, which knip registers as an alias, so the read counts for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then nothing is reported. + { + code: `${IMPORT} import type * as Other from './other'; function first() {const Alias = {...Other}; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + }, + // Given an alias of an `import = require` of an internal module, which knip registers as an alias, so the read counts for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then nothing is reported. + { + code: `${IMPORT} import Other = require('./other'); function first() {const Alias = Other; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + }, + // Given an alias of a JSON import, which knip registers as an alias, so the read counts for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then nothing is reported. + { + code: `${IMPORT} import data from './data.json'; function first() {const Alias = data; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + }, + // Given a ternary alias of an asset import through a path alias, which knip registers as an alias, so the read counts for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then nothing is reported. + { + code: `${IMPORT} import logo from '@assets/images/logo.png'; function first() {const Alias = flag ? logo : 1; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + }, + // Given a spread alias of a re-exported import, which knip registers as an alias, so the read counts for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then nothing is reported. + { + code: `${IMPORT} import {Item} from './barrel'; function first() {const Alias = {...Item}; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + }, + // Given an alias of a default import through a path alias, which knip registers as an alias, so the read counts for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then nothing is reported. + { + code: `${IMPORT} import Other from '@libs/Other'; function first() {const Alias = Other; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + }, + // Given an alias of another internal namespace import, which knip registers as an alias, so the read counts for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then nothing is reported. + { + code: `${IMPORT} import * as Other from '@libs/Other'; function first() {const Alias = Other; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + }, + ], + invalid: [ + // Given a computed key, which knip cannot resolve to an export. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} export const value = Utils[key];`, errors: [usageError('computed key')]}, + // Given an optional computed key, which knip cannot resolve to an export. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} export const value = Utils?.[key];`, errors: [usageError('computed key')]}, + // Given a numeric key, which knip does not treat as a static key. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} export const value = Utils[0];`, errors: [usageError('computed key')]}, + // Given a template key with a substitution, which knip cannot resolve. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} export const value = Utils[\`prefix\${key}\`];`, errors: [usageError('computed key')]}, + // Given two opaque usages of the same namespace. + // When the rule checks how the namespace is used. + // Then both usages are reported. + {code: `${IMPORT} export const value = Utils[key]; export const names = Object.keys(Utils);`, errors: [usageError('computed key'), usageError('enumeration')]}, + // Given `Object.keys`, which knip treats as reading every export. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} Object.keys(Utils);`, errors: [usageError('enumeration')]}, + // Given `Object.values`, which knip treats as reading every export. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} Object.values(Utils);`, errors: [usageError('enumeration')]}, + // Given `Object.entries`, which knip treats as reading every export. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} Object.entries(Utils);`, errors: [usageError('enumeration')]}, + // Given `Object.getOwnPropertyNames`, which knip treats as reading every export. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} Object.getOwnPropertyNames(Utils);`, errors: [usageError('enumeration')]}, + // Given `Object.keys` with the namespace after another argument, which knip also treats as reading every export. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} export const keys = Object.keys(other, Utils);`, errors: [usageError('enumeration')]}, + // Given `for...in`, which knip treats as reading every export. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} for (const key in Utils) { use(key); }`, errors: [usageError('enumeration')]}, + // Given `for...of`, which knip treats as reading every export. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} for (const value of Utils) { use(value); }`, errors: [usageError('enumeration')]}, + // Given a rest destructuring, which knip cannot track even when the rest is unused. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} const {a, ...rest} = Utils; export {a};`, errors: [usageError('rest destructuring')]}, + // Given a default value of a destructured property, which knip treats as an opaque use. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} const {a = Utils} = obj; export {a};`, errors: [usageError('destructuring default')]}, + // Given an alias that is only exported, which knip cannot follow. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} const Alias = Utils; export {Alias};`, errors: [usageError('unread alias')]}, + // Given an alias whose name is member-accessed only on another variable. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} const Alias = Utils; other.member(); export {Alias};`, errors: [usageError('unread alias')]}, + // Given a shorthand object property alias that is only exported, which knip cannot follow. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} const holder = {Utils}; export {holder};`, errors: [usageError('unread alias')]}, + // Given an object property alias read by a computed holder key with an identifier, which knip cannot follow. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} const holder = {utils: Utils}; const utils = 'utils'; holder[utils].member(); register(holder);`, errors: [usageError('unread alias')]}, + // Given an object property alias read without a member of the namespace, which knip cannot follow. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} const holder = {utils: Utils}; register(holder.utils);`, errors: [usageError('unread alias')]}, + // Given an object property alias read by a computed member key, which knip cannot follow. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} const holder = {utils: Utils}; holder.utils[key]; register(holder);`, errors: [usageError('unread alias')]}, + // Given a spread alias that is only passed to a call, which knip cannot follow. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} const copy = {...Utils}; register(copy);`, errors: [usageError('unread alias')]}, + // Given a ternary alias with the namespace in the first branch that is never read. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} const target = flag ? Utils : other; export {target};`, errors: [usageError('unread alias')]}, + // Given two aliases of the same namespace that are never read. + // When the rule checks how the namespace is used. + // Then both usages are reported. + {code: `${IMPORT} const First = Utils; const Second = Utils; export {First, Second};`, errors: [usageError('unread alias'), usageError('unread alias')]}, + // Given an exported spread nested under a quoted key, which knip does not follow, so the alias with the same name is not counted as read. + // When the rule checks how the namespace is used. + // Then the usage is reported. + { + code: `${IMPORT} import {obj} from './other'; Utils.used(); export const copy = {'nested': {...obj}}; function run() {const copy = Utils; return 1;} run();`, + errors: [usageError('unread alias')], + }, + // Given an exported spread of a package import, which knip does not count as an access to the alias with the same name. + // When the rule checks how the namespace is used. + // Then the usage is reported. + { + code: `${IMPORT} import pkg from 'some-package'; Utils.used(); export const copy = {...pkg}; function run() {const copy = Utils; return 1;} run();`, + errors: [usageError('unread alias')], + }, + // Given an earlier alias that holds a named import in an object, which knip does not register as an alias, so the read before the namespace alias is not counted. + // When the rule checks how the namespace is used. + // Then the usage is reported. + { + code: `${IMPORT} import {obj} from './other'; function first() {const Alias = {key: obj}; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + errors: [usageError('unread alias')], + }, + // Given an alias read only in a function declared before the alias, which knip does not count because it registers aliases in source order. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} function run() {Alias.member();} const Alias = Utils; Utils.other(); run();`, errors: [usageError('unread alias')]}, + // Given an alias read at the top level before its declaration with `var`, which knip does not count. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} Alias.member(); var Alias = Utils; Utils.other();`, errors: [usageError('unread alias')]}, + // Given a class method that reads the alias before the declaration, which knip does not count. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} class Foo {run() {return Alias.member();}} const Alias = Utils; Utils.other();`, errors: [usageError('unread alias')]}, + // Given a ternary alias read only before its declaration, which knip does not count. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} function run() {target.member();} const target = flag ? Utils : other; run();`, errors: [usageError('unread alias')]}, + // Given a spread alias read only before its declaration, which knip does not count. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} function run() {copy.member();} const copy = {...Utils}; run();`, errors: [usageError('unread alias')]}, + // Given an object property alias read only before its declaration, which knip does not count. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} function run() {holder.utils.member();} const holder = {utils: Utils}; run();`, errors: [usageError('unread alias')]}, + // Given an alias read only through a non-null assertion, which knip does not see as a member access of the alias. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} const Alias = Utils; Alias!.member(); Utils.other();`, errors: [usageError('unread alias')]}, + // Given an alias read only by a type query, which knip does not count. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} const Alias = Utils; export type Member = typeof Alias.member; Utils.other();`, errors: [usageError('unread alias')]}, + // Given an alias that is only destructured, which knip does not count as a member read. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} const Alias = Utils; const {member} = Alias; export {member};`, errors: [usageError('unread alias')]}, + // Given an `@src` source, which resolves to an internal module. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: "import * as Utils from '@src/libs/Utils'; export const value = Utils[key];", errors: [usageError('computed key')]}, + // Given a `tests/` source, which resolves to an internal module. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: "import * as Utils from 'tests/utils/Utils'; export const value = Utils[key];", errors: [usageError('computed key')]}, + // Given a parent-relative source, which resolves to an internal module. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: "import * as Utils from '../Utils'; export const value = Utils[key];", errors: [usageError('computed key')]}, + // Given an alias of a default import of a package, which knip does not register as an alias, so the read does not count for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then the usage is reported. + { + code: `${IMPORT} import React from 'react'; function first() {const Alias = React; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + errors: [usageError('unread alias')], + }, + // Given an alias of a named import of a package, which knip does not register as an alias, so the read does not count for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then the usage is reported. + { + code: `${IMPORT} import {createElement as Item} from 'react'; function first() {const Alias = Item; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + errors: [usageError('unread alias')], + }, + // Given an alias of a namespace import of a package, which knip does not register as an alias, so the read does not count for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then the usage is reported. + { + code: `${IMPORT} import * as Pkg from 'react'; function first() {const Alias = Pkg; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + errors: [usageError('unread alias')], + }, + // Given a ternary alias of a default import of a package, which knip does not register as an alias, so the read does not count for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then the usage is reported. + { + code: `${IMPORT} import React from 'react'; function first() {const Alias = flag ? React : 1; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + errors: [usageError('unread alias')], + }, + // Given a spread alias of a default import of a package, which knip does not register as an alias, so the read does not count for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then the usage is reported. + { + code: `${IMPORT} import React from 'react'; function first() {const Alias = {...React}; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + errors: [usageError('unread alias')], + }, + // Given an alias of a built-in module import, which knip does not register as an alias, so the read does not count for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then the usage is reported. + { + code: `${IMPORT} import fs from 'node:fs'; function first() {const Alias = fs; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + errors: [usageError('unread alias')], + }, + // Given an alias of a type-only import of a package, which knip does not register as an alias, so the read does not count for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then the usage is reported. + { + code: `${IMPORT} import type Pkg from 'react'; function first() {const Alias = Pkg; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + errors: [usageError('unread alias')], + }, + // Given an alias of an `import = require` of a package, which knip does not register as an alias, so the read does not count for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then the usage is reported. + { + code: `${IMPORT} import Pkg = require('react'); function first() {const Alias = Pkg; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + errors: [usageError('unread alias')], + }, + // Given an object property alias of a default import of an internal module, which knip does not register as an alias, so the read does not count for the namespace alias with the same name. + // When the rule checks how the namespace is used. + // Then the usage is reported. + { + code: `${IMPORT} import Other from './other'; function first() {const Alias = {key: Other}; return Alias.member;} function second() {const Alias = Utils; consume(Alias);} Utils.other(); first(); second();`, + errors: [usageError('unread alias')], + }, + ], + }); + + tsxRuleTester.run(`${ruleModule.name} (tsx)`, ruleModule, { + valid: [ + // Given a JSX attribute that receives the namespace, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} export const element = ;`}, + // Given a JSX tag that is a member of the namespace itself, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} export const element = ;`}, + // Given a nested JSX tag on the namespace itself, which knip tracks. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} export const element = ;`}, + // Given a `.tsx` alias that is also read as a value, which knip counts. + // When the rule checks how the namespace is used. + // Then nothing is reported. + {code: `${IMPORT} const Alias = Utils; export const element = ;`}, + ], + invalid: [ + // Given a computed key in a `.tsx` file. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} export const element = ;`, errors: [usageError('computed key')]}, + // Given a `.tsx` alias that is read only as a JSX tag, which knip does not count as a member read of the alias. + // When the rule checks how the namespace is used. + // Then the usage is reported. + {code: `${IMPORT} const Alias = Utils; export const element = ; Utils.other();`, errors: [usageError('unread alias')]}, + ], + }); +}); diff --git a/tests/unit/Search/SearchUIUtilsTest.ts b/tests/unit/Search/SearchUIUtilsTest.ts index 343bbc4212a8..b216bccb0acb 100644 --- a/tests/unit/Search/SearchUIUtilsTest.ts +++ b/tests/unit/Search/SearchUIUtilsTest.ts @@ -1,4 +1,4 @@ -import * as defaultWorkspaceAvatars from '@components/Icon/WorkspaceDefaultAvatars'; +import defaultWorkspaceAvatars from '@components/Icon/WorkspaceDefaultAvatars'; import type {LocalizedTranslate} from '@components/LocaleContextProvider'; import type { ReportActionListItemType, diff --git a/tests/unit/components/Table/tableAccessibilityTest.ts b/tests/unit/components/Table/tableAccessibilityTest.ts index 751a7537d833..79a10b2dcbe2 100644 --- a/tests/unit/components/Table/tableAccessibilityTest.ts +++ b/tests/unit/components/Table/tableAccessibilityTest.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/naming-convention -- ARIA attributes are kebab-case by spec. */ -import * as tableAccessibilityModule from '@components/Table/tableAccessibility'; +import type * as tableAccessibilityModule from '@components/Table/tableAccessibility'; import CONST from '@src/CONST'; @@ -17,7 +17,7 @@ jest.mock('@libs/getPlatform', () => ({ function loadModule(platform: string): TableAccessibilityModule { mockedPlatform = platform; - let module: TableAccessibilityModule = tableAccessibilityModule; + let module!: TableAccessibilityModule; jest.isolateModules(() => { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment module = require('@components/Table/tableAccessibility');