UNPKG

eslint-plugin-jsdoc

Version:
715 lines (649 loc) • 22.5 kB
import iterateJsdoc, { parseComment, } from '../iterateJsdoc.js'; import { rewireByParsedType, } from '../jsdocUtils.js'; import { generate, } from '@es-joy/escodegen'; import { commentParserToESTree, estreeToString, // getJSDocComment, parse as parseType, stringify, traverse, tryParse as tryParseType, } from '@es-joy/jsdoccomment'; import { Linter, } from 'eslint'; import { parse as espree, } from 'espree'; import { parseImportsExports, } from 'parse-imports-exports'; import semver from 'semver'; import toValidIdentifier from 'to-valid-identifier'; // Scope definitions that give a name a type meaning (or, for an import, any // meaning), as the type-only names of `@import` have const typeDefinitionTypes = new Set([ 'ClassName', 'ImportBinding', // typescript-eslint 'TSEnumName', 'TSModuleName', 'Type', ]); export default iterateJsdoc(({ context, indent, jsdoc, node: documentedNode, settings, sourceCode, utils, }) => { const { mode, } = settings; const { enableFixer = true, exemptTypedefs = true, outputType = 'namespaced-import', } = context.options[0] || {}; const allComments = sourceCode.getAllComments(); const comments = allComments .filter((comment) => { return (/^\*(?!\*)/v).test(comment.value); }) .map((commentNode) => { return commentParserToESTree( parseComment(commentNode, ''), mode === 'permissive' ? 'typescript' : mode, { jsdocTypePrattParserArgs: { // Pass it for parity, but probably not needed // with the typedefs and import statements below computedPropertyParser: espree, }, }, ); }); // Only `@typedef` names are type aliases; names of `@param`, // `@property`, `@const`, etc. are not types const typedefs = comments .flatMap((doc) => { return doc.tags.filter(({ tag, }) => { return tag === 'typedef'; }); }); const imports = comments .flatMap((doc) => { return doc.tags.filter(({ tag, }) => { return tag === 'import'; }); }).map((tag) => { // Causes problems with stringification otherwise tag.delimiter = ''; return tag; }); /** @type {Set<string>|undefined} */ let takenNames; /** * The names the file already gives a type or import meaning where the * block is: an import, a `require()` alias, a class (also a JavaScript * function using `this`, which TypeScript treats as one), a TypeScript * type, enum or namespace, a `@typedef` or an `@import`, in the scopes * around the block; a global the code uses; or a name another type in the * file refers to. An `@import` added by the fixer (which is type-only, so a * variable or function of the same name is fine) must not take one of * them, or the file no longer type-checks or a type changes what it refers * to. * @returns {Set<string>} */ const getTakenNames = () => { if (takenNames) { return takenNames; } const { globalScope, } = /** @type {import('eslint').Scope.ScopeManager & {globalScope: import('eslint').Scope.Scope}} */ ( sourceCode.scopeManager ); const scopes = new Set([ globalScope, // The module scope, or the function scope of CommonJS ...globalScope.childScopes.filter(({ block, }) => { return block === sourceCode.ast; }), ]); // A JSDoc type is resolved from the position of its block for (let scope = documentedNode ? sourceCode.getScope(documentedNode) : null; scope; scope = scope.upper) { scopes.add(scope); } const names = new Set(/** @type {string[]} */ ([ ...[ ...scopes, ].flatMap(({ variables, }) => { return variables.filter(({ defs, }) => { return defs.some(({ node: defNode, type, }) => { return typeDefinitionTypes.has(type) || ( type === 'FunctionName' && Boolean(/** @type {{thisFound?: boolean}|null} */ ( sourceCode.scopeManager?.acquire(defNode) )?.thisFound) ) || ( type === 'Variable' && defNode.init?.type === 'CallExpression' && defNode.init.callee.type === 'Identifier' && defNode.init.callee.name === 'require' ); }); }).map(({ name, }) => { return name; }); }), // A global the code uses (built in, configured or unknown), which a // type-only `@import` of the same name would hide ...globalScope.through.map(({ identifier: { name, }, }) => { return name; }), ...globalScope.variables.filter(({ defs, references, }) => { return !defs.length && references.length; }).map(({ name, }) => { return name; }), ...comments.flatMap(({ tags, }) => { return tags.flatMap(({ parsedType, }) => { /** @type {string[]} */ const typeNames = []; if (parsedType) { traverse(parsedType, (nde) => { if (nde.type === 'JsdocTypeName') { typeNames.push(nde.value); } }); } return typeNames; }); }), ...typedefs.map(({ name, }) => { return name; }), ...imports.flatMap((imprt) => { const parsedImport = parseImportsExports( estreeToString(imprt, { jtppStringificationRules: generate, }).replace(/^\s*@/v, '').trim(), ); return [ ...Object.values(parsedImport.namedImports ?? {}), ...Object.values(parsedImport.namespaceImports ?? {}), ].flat().flatMap((importInfo) => { const { default: defaultName, names: localNames, namespace, } = /** @type {{default?: string, names?: object, namespace?: string}} */ (importInfo); return [ defaultName, namespace, ...Object.keys(localNames ?? {}), ]; }); }), ].filter(Boolean))); takenNames = names; return names; }; /** * Helper to insert an import statement at the top of the file. * @param {string} importText - The import statement text (without newline) * @returns {((fixer: import('eslint').Rule.RuleFixer) => import('eslint').Rule.Fix|void)} - Fixer function for ESLint */ const createImportInserter = (importText) => { return (fixer) => { // A hashbang (`#!`) must stay on the first line const hashbang = (/^#!.*(?:\r\n|\n)/v).exec(sourceCode.text); if (hashbang) { return fixer.insertTextAfterRange( [ 0, hashbang[0].length, ], `${importText}${hashbang[0].endsWith('\r\n') ? '\r\n' : '\n'}`, ); } const programNode = sourceCode.ast; const commentNodes = sourceCode.getCommentsBefore(programNode); /* c8 ignore start -- ESLint < 10 */ if (commentNodes[0]) { return fixer.insertTextBefore( // @ts-expect-error - Comment is compatible with Node in practice commentNodes[0], `${importText}\n${indent}`, ); } // For ESLint < 10, use the simple approach of inserting before programNode if (semver.lt(Linter.version, '10.0.0')) { return fixer.insertTextBefore( programNode, importText, ); } // For ESLint 10+, handle the changed Program node range const sourceText = sourceCode.getText(); const hasCode = programNode.body && programNode.body.length > 0; const leadingMatch = hasCode ? sourceText.match(/^(\n[ \t]*)/v) : null; if (leadingMatch) { const leading = leadingMatch[1]; return fixer.replaceTextRange( [ leading.length, leading.length, ], `${importText}\n${leading.slice(1)}`, ); } const startsWithNewline = sourceText[0] === '\n'; return fixer.replaceTextRange( startsWithNewline ? [ 0, 1, ] : [ 0, 0, ], `${importText}\n`, ); /* c8 ignore end -- ESLint < 10 */ }; }; /** * @param {import('@es-joy/jsdoccomment').JsdocTagWithInline} tag */ const iterateInlineImports = (tag) => { const potentialType = tag.type; let parsedType; try { parsedType = mode === 'permissive' ? tryParseType(/** @type {string} */ (potentialType), undefined, { computedPropertyParser: espree, }) : parseType(/** @type {string} */ (potentialType), mode, { computedPropertyParser: espree, }); } catch { return; } traverse(parsedType, (nde, parentNode) => { // @ts-expect-error Adding our own property for use below nde.parentNode = parentNode; }); traverse(parsedType, (nde) => { const { element, type, } = /** @type {import('jsdoc-type-pratt-parser').ImportResult} */ (nde); if (type !== 'JsdocTypeImport') { return; } /** @type {import('jsdoc-type-pratt-parser').NonRootResult} */ let currentNode = nde; /** @type {string[]} */ const pathSegments = []; /** @type {import('jsdoc-type-pratt-parser').NamePathResult[]} */ const nodes = []; /** @type {string[]} */ const extraPathSegments = []; /** @type {(import('jsdoc-type-pratt-parser').QuoteStyle|undefined)[]} */ const quotes = []; const propertyOrBrackets = /** @type {import('jsdoc-type-pratt-parser').NamePathResult['pathType'][]} */ ([]); // @ts-expect-error Referencing our own property added above while (currentNode && currentNode.parentNode) { // @ts-expect-error Referencing our own property added above currentNode = currentNode.parentNode; /* c8 ignore next 3 -- Guard */ if (currentNode.type !== 'JsdocTypeNamePath') { break; } pathSegments.unshift( currentNode.right.type === 'JsdocTypeIndexedAccessIndex' ? stringify(currentNode.right.right, generate) : currentNode.right.value, ); nodes.unshift(currentNode); propertyOrBrackets.unshift(currentNode.pathType); quotes.unshift( currentNode.right.type === 'JsdocTypeIndexedAccessIndex' ? undefined : currentNode.right.meta.quote, ); } /** * @param {string} matchingName An identifier (escape module specifiers * with `toValidIdentifier` before passing them) * @param {string[]} extrPathSegments */ const getFixer = (matchingName, extrPathSegments) => { return () => { /** @type {import('jsdoc-type-pratt-parser').NamePathResult|undefined} */ let node = nodes.at(0); if (!node) { // Not really a NamePathResult, but will be converted later anyways node = /** @type {import('jsdoc-type-pratt-parser').NamePathResult} */ ( /** @type {unknown} */ (nde) ); } const keys = /** @type {(keyof import('jsdoc-type-pratt-parser').NamePathResult)[]} */ ( Object.keys(node) ); for (const key of keys) { delete node[key]; } if (extrPathSegments.length) { let newNode = /** @type {import('jsdoc-type-pratt-parser').NamePathResult} */ ( /** @type {unknown} */ (node) ); while (extrPathSegments.length && newNode) { newNode.type = 'JsdocTypeNamePath'; newNode.right = { meta: { quote: quotes.shift(), }, type: 'JsdocTypeProperty', value: /** @type {string} */ (extrPathSegments.shift()), }; newNode.pathType = /** @type {import('jsdoc-type-pratt-parser').NamePathResult['pathType']} */ ( propertyOrBrackets.shift() ); // @ts-expect-error Temporary newNode.left = {}; newNode = /** @type {import('jsdoc-type-pratt-parser').NamePathResult} */ ( newNode.left ); } const nameNode = /** @type {import('jsdoc-type-pratt-parser').NameResult} */ ( /** @type {unknown} */ (newNode) ); nameNode.type = 'JsdocTypeName'; nameNode.value = matchingName; } else { const newNode = /** @type {import('jsdoc-type-pratt-parser').NameResult} */ ( /** @type {unknown} */ (node) ); newNode.type = 'JsdocTypeName'; newNode.value = matchingName; } // Over all the lines of the type, which may be several rewireByParsedType(jsdoc, tag, parsedType, indent); }; }; /** @type {string[]} */ let unusedPathSegments = []; const findMatchingTypedef = () => { // Don't want typedefs to find themselves if (!exemptTypedefs) { return undefined; } const pthSegments = [ ...pathSegments, ]; return typedefs.find((typedef) => { let typedefNode = typedef.parsedType; let namepathMatch; while (typedefNode && typedefNode.type === 'JsdocTypeNamePath') { const pathSegment = pthSegments.shift(); if (!pathSegment) { namepathMatch = false; break; } if ( (typedefNode.right.type === 'JsdocTypeIndexedAccessIndex' && stringify(typedefNode.right.right, generate) !== pathSegment) || (typedefNode.right.type !== 'JsdocTypeIndexedAccessIndex' && typedefNode.right.value !== pathSegment) ) { if (namepathMatch === true) { // It stopped matching, so stop break; } extraPathSegments.push(pathSegment); namepathMatch = false; continue; } namepathMatch = true; unusedPathSegments = pthSegments; typedefNode = typedefNode.left; } return namepathMatch && // `import('eslint')` matches typedefNode && typedefNode.type === 'JsdocTypeImport' && typedefNode.element.value === element.value; }); }; // Check @typedef's first as should be longest match, allowing // for shorter abbreviations const matchingTypedef = findMatchingTypedef(); if (matchingTypedef) { utils.reportJSDoc( 'Inline `import()` found; using `@typedef`', tag, enableFixer ? getFixer(matchingTypedef.name, [ ...extraPathSegments, ...unusedPathSegments.slice(-1), ...unusedPathSegments.slice(0, -1), ]) : null, ); return; } const findMatchingImport = () => { for (const imprt of imports) { const parsedImport = parseImportsExports( estreeToString(imprt, { jtppStringificationRules: generate, }).replace(/^\s*@/v, '').trim(), ); const namedImportsModuleSpecifier = Object.keys(parsedImport.namedImports || {})[0]; const namedImports = Object.values(parsedImport.namedImports || {})[0]?.[0]; const namedImportNames = (namedImports && namedImports.names && Object.keys(namedImports.names)) ?? []; const namespaceImports = Object.values(parsedImport.namespaceImports || {})[0]?.[0]; const namespaceImportsDefault = namespaceImports && namespaceImports.default; const namespaceImportsNamespace = namespaceImports && namespaceImports.namespace; const namespaceImportsModuleSpecifier = Object.keys(parsedImport.namespaceImports || {})[0]; const lastPathSegment = pathSegments.at(-1); if ( (namespaceImportsDefault && namespaceImportsModuleSpecifier === element.value) || (element.value === namedImportsModuleSpecifier && ( (lastPathSegment && namedImportNames.includes(lastPathSegment)) || lastPathSegment === 'default' )) || (namespaceImportsNamespace && namespaceImportsModuleSpecifier === element.value) ) { return { namedImportNames, namedImports, namedImportsModuleSpecifier, namespaceImports, namespaceImportsDefault, namespaceImportsModuleSpecifier, namespaceImportsNamespace, }; } } return undefined; }; const matchingImport = findMatchingImport(); if (matchingImport) { const { namedImportNames, namedImports, namedImportsModuleSpecifier, namespaceImportsNamespace, } = matchingImport; if (!namedImportNames.length && namedImportsModuleSpecifier && namedImports.default) { utils.reportJSDoc( 'Inline `import()` found; prefer `@import`', tag, enableFixer ? getFixer(namedImports.default, []) : null, ); return; } const lastPthSegment = pathSegments.at(-1); if (lastPthSegment && namedImportNames.includes(lastPthSegment)) { utils.reportJSDoc( 'Inline `import()` found; prefer `@import`', tag, enableFixer ? getFixer(lastPthSegment, pathSegments.slice(0, -1)) : null, ); return; } if (namespaceImportsNamespace) { utils.reportJSDoc( 'Inline `import()` found; prefer `@import`', tag, enableFixer ? getFixer(namespaceImportsNamespace, [ ...pathSegments, ]) : null, ); return; } } // The fixes below add an `@import` with a new name, so they are not // offered when the file already uses that name const namespaceName = toValidIdentifier(element.value); if (!pathSegments.length) { utils.reportJSDoc( 'Inline `import()` found; prefer `@import`', tag, enableFixer && !getTakenNames().has(namespaceName) ? (fixer) => { getFixer(toValidIdentifier(element.value), [])(); return createImportInserter( `/** @import * as ${toValidIdentifier(element.value)} from '${element.value}'; */`, )(fixer); } : null, ); return; } const lstPathSegment = pathSegments.at(-1); if (lstPathSegment && lstPathSegment === 'default') { utils.reportJSDoc( 'Inline `import()` found; prefer `@import`', tag, enableFixer && !getTakenNames().has(namespaceName) ? (fixer) => { getFixer(toValidIdentifier(element.value), [])(); return createImportInserter( `/** @import ${toValidIdentifier(element.value)} from '${element.value}'; */`, )(fixer); } : null, ); return; } const importedName = outputType === 'namespaced-import' ? namespaceName : toValidIdentifier(/** @type {string} */ (pathSegments.at(-1))); utils.reportJSDoc( 'Inline `import()` found; prefer `@import`', tag, enableFixer && !getTakenNames().has(importedName) ? (fixer) => { if (outputType === 'namespaced-import') { getFixer(toValidIdentifier(element.value), [ ...pathSegments, ])(); } else { getFixer( toValidIdentifier(/** @type {string} */ (pathSegments.at(-1))), pathSegments.slice(0, -1), )(); } const importText = outputType === 'namespaced-import' ? `/** @import * as ${toValidIdentifier(element.value)} from '${element.value}'; */` : `/** @import { ${toValidIdentifier( /* c8 ignore next -- TS */ pathSegments.at(-1) ?? '', )} } from '${element.value}'; */`; return createImportInserter(importText)(fixer); } : null, ); }); }; for (const tag of jsdoc.tags) { const mightHaveTypePosition = utils.tagMightHaveTypePosition(tag.tag); const hasTypePosition = mightHaveTypePosition === true && Boolean(tag.type); // Only the `@typedef` itself is exempt; `@param`, `@property`, `@const`, // etc. are not type aliases and their `import()` types are reported if (hasTypePosition && (!exemptTypedefs || tag.tag !== 'typedef')) { iterateInlineImports(tag); } } }, { iterateAllJsdocs: true, meta: { docs: { description: 'Prefer `@import` tags to inline `import()` statements.', url: 'https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/prefer-import-tag.md#repos-sticky-header', }, fixable: 'code', schema: [ { additionalProperties: false, properties: { enableFixer: { description: 'Whether or not to enable the fixer to add `@import` tags.', type: 'boolean', }, exemptTypedefs: { description: 'Whether to allow `import()` statements within `@typedef`', type: 'boolean', }, // We might add `typedef` and `typedef-local-only`, but also raises // question of how deep the generated typedef should be outputType: { description: 'What kind of `@import` to generate when no matching `@typedef` or `@import` is found', enum: [ 'named-import', 'namespaced-import', ], type: 'string', }, }, type: 'object', }, ], type: 'suggestion', }, });