From c0c5822db097ec8d3835f0cde6d8b1d83435c2f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Correa=20Casablanca?= Date: Thu, 19 Sep 2024 10:18:09 +0200 Subject: [PATCH] refactor: minor improvements Signed-off-by: Andres Correa Casablanca --- .github/workflows/ci.yml | 2 +- rollup.config.ts | 2 +- src/index.ts | 4 ++-- src/options.ts | 2 +- src/program.ts | 8 ++++---- src/transform/DeclarationScope.ts | 23 +++++++++++++---------- src/transform/NamespaceFixer.ts | 6 +++--- src/transform/Transformer.ts | 12 ++++++------ src/transform/astHelpers.ts | 2 +- src/transform/errors.ts | 6 +++--- src/transform/index.ts | 4 ++-- src/transform/preprocess.ts | 10 +++++----- 12 files changed, 42 insertions(+), 39 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 93585f27..f19d71d1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,7 +6,7 @@ jobs: strategy: fail-fast: false matrix: - node: [16, 18, 20] + node: [16, 18, 20, 22] os: [ubuntu-latest, windows-latest] name: Node ${{ matrix.node }} on ${{ matrix.os }} diff --git a/rollup.config.ts b/rollup.config.ts index 195ce8a3..17b6bbfb 100644 --- a/rollup.config.ts +++ b/rollup.config.ts @@ -3,7 +3,7 @@ import type { RollupWatchOptions } from "rollup"; import dts from "./src/index.js"; const pkg = JSON.parse(fs.readFileSync("./package.json", { encoding: "utf-8" })); -const external = ["module", "path", "typescript", "rollup", "@babel/code-frame", "magic-string"]; +const external = ["node:module", "node:path", "typescript", "rollup", "@babel/code-frame", "magic-string"]; const config: Array = [ { diff --git a/src/index.ts b/src/index.ts index bfa22ffe..cd0ebf12 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,4 @@ -import * as path from "path"; +import * as path from "node:path"; import type { PluginImpl, Plugin } from "rollup"; import ts from "typescript"; import { type Options, resolveDefaultOptions, type ResolvedOptions } from "./options.js"; @@ -140,7 +140,7 @@ const plugin: PluginImpl = (options = {}) => { const treatTsAsDts = () => { const declarationId = id.replace(TS_EXTENSIONS, dts); - let module = getModule(ctx, declarationId, code); + const module = getModule(ctx, declarationId, code); if (module) { watchFiles(module); return transformPlugin.transform.call(this, module.code, declarationId); diff --git a/src/options.ts b/src/options.ts index 3cc2af77..5d93c214 100644 --- a/src/options.ts +++ b/src/options.ts @@ -1,4 +1,4 @@ -import ts from "typescript"; +import type ts from "typescript"; export interface Options { /** diff --git a/src/program.ts b/src/program.ts index 503aa008..dd064105 100644 --- a/src/program.ts +++ b/src/program.ts @@ -1,4 +1,4 @@ -import * as path from "path"; +import * as path from "node:path"; import ts from "typescript"; export const DTS_EXTENSIONS = /\.d\.(c|m)?tsx?$/; @@ -30,7 +30,7 @@ const DEFAULT_OPTIONS: ts.CompilerOptions = { const configByPath = new Map(); -const logCache = (...args: any[]) => (process.env.DTS_LOG_CACHE ? console.log("[cache]", ...args) : null); +const logCache = (...args: unknown[]) => (process.env.DTS_LOG_CACHE ? console.log("[cache]", ...args) : null); /** * Caches the config for every path between two given paths. @@ -71,7 +71,7 @@ export function getCompilerOptions( if (!configPath) { return { dtsFiles, dirName, compilerOptions }; } - let inputDirName = dirName; + const inputDirName = dirName; dirName = path.dirname(configPath); const { config, error } = ts.readConfigFile(configPath, ts.sys.readFile); if (error) { @@ -118,8 +118,8 @@ export function createProgram(fileName: string, overrideOptions: ts.CompilerOpti export function createPrograms(input: Array, overrideOptions: ts.CompilerOptions, tsconfig?: string) { const programs = []; + const dtsFiles: Set = new Set(); let inputs: Array = []; - let dtsFiles: Set = new Set(); let dirName = ""; let compilerOptions: ts.CompilerOptions = {}; diff --git a/src/transform/DeclarationScope.ts b/src/transform/DeclarationScope.ts index c05e4ea8..43da3576 100644 --- a/src/transform/DeclarationScope.ts +++ b/src/transform/DeclarationScope.ts @@ -129,7 +129,7 @@ export class DeclarationScope { throw new UnsupportedSyntaxError(node.name); } - let object = ts.isIdentifier(node.expression) + const object = ts.isIdentifier(node.expression) ? createIdentifier(node.expression) : this.convertPropertyAccess(node.expression); @@ -190,7 +190,7 @@ export class DeclarationScope { } } - convertMembers(members: ts.NodeArray) { + convertMembers(members: ts.NodeArray): void { for (const node of members) { if (ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isIndexSignatureDeclaration(node)) { if (ts.isPropertyDeclaration(node) && node.initializer && ts.isPropertyAccessExpression(node.initializer)) { @@ -229,7 +229,7 @@ export class DeclarationScope { return params.length; } - convertTypeNode(node?: ts.TypeNode): any { + convertTypeNode(node?: ts.TypeNode): void { if (!node) { return; } @@ -242,11 +242,13 @@ export class DeclarationScope { return; } if (ts.isTypeLiteralNode(node)) { - return this.convertMembers(node.members); + this.convertMembers(node.members); + return } if (ts.isArrayTypeNode(node)) { - return this.convertTypeNode(node.elementType); + this.convertTypeNode(node.elementType); + return } if (ts.isTupleTypeNode(node)) { for (const type of node.elements) { @@ -260,7 +262,8 @@ export class DeclarationScope { ts.isTypeOperatorNode(node) || ts.isTypePredicateNode(node) ) { - return this.convertTypeNode(node.type); + this.convertTypeNode(node.type); + return } if (ts.isUnionTypeNode(node) || ts.isIntersectionTypeNode(node)) { for (const type of node.types) { @@ -353,7 +356,7 @@ export class DeclarationScope { if (stmt.name && ts.isIdentifier(stmt.name)) { this.pushTypeVariable(stmt.name); } else { - throw new UnsupportedSyntaxError(stmt, `non-Identifier name not supported`); + throw new UnsupportedSyntaxError(stmt, 'non-Identifier name not supported'); } continue; } @@ -362,7 +365,7 @@ export class DeclarationScope { if (ts.isIdentifier(decl.name)) { this.pushTypeVariable(decl.name); } else { - throw new UnsupportedSyntaxError(decl, `non-Identifier name not supported`); + throw new UnsupportedSyntaxError(decl, 'non-Identifier name not supported'); } } continue; @@ -370,7 +373,7 @@ export class DeclarationScope { if (ts.isExportDeclaration(stmt)) { // noop } else { - throw new UnsupportedSyntaxError(stmt, `namespace child (hoisting) not supported yet`); + throw new UnsupportedSyntaxError(stmt, 'namespace child (hoisting) not supported yet'); } } @@ -420,7 +423,7 @@ export class DeclarationScope { } } } else { - throw new UnsupportedSyntaxError(stmt, `namespace child (walking) not supported yet`); + throw new UnsupportedSyntaxError(stmt, 'namespace child (walking) not supported yet'); } } diff --git a/src/transform/NamespaceFixer.ts b/src/transform/NamespaceFixer.ts index 31f3d30f..5cd8abe5 100644 --- a/src/transform/NamespaceFixer.ts +++ b/src/transform/NamespaceFixer.ts @@ -70,10 +70,10 @@ export class NamespaceFixer { node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier) ) { - let { text } = node.moduleSpecifier; + const { text } = node.moduleSpecifier; if (text.startsWith(".") && (text.endsWith(".d.ts") || text.endsWith(".d.cts") || text.endsWith(".d.mts"))) { - let start = node.moduleSpecifier.getStart() + 1; // +1 to account for the quote - let end = node.moduleSpecifier.getEnd() - 1; // -1 to account for the quote + const start = node.moduleSpecifier.getStart() + 1; // +1 to account for the quote + const end = node.moduleSpecifier.getEnd() - 1; // -1 to account for the quote namespaces.unshift({ name: "", exports: [], diff --git a/src/transform/Transformer.ts b/src/transform/Transformer.ts index fc96c903..db86f00e 100644 --- a/src/transform/Transformer.ts +++ b/src/transform/Transformer.ts @@ -61,7 +61,7 @@ class Transformer { // we possibly have other declarations, such as an ExportDeclaration in // between, which should also be updated to the correct start/end. - let selfIdx = this.ast.body.findIndex((node) => node == existingScope.declaration); + const selfIdx = this.ast.body.findIndex((node) => node == existingScope.declaration); for (let i = selfIdx + 1; i < this.ast.body.length; i++) { const decl = this.ast.body[i] as any; decl.start = decl.end = range.end; @@ -95,7 +95,7 @@ class Transformer { if (ts.isModuleDeclaration(node)) { return this.convertNamespaceDeclaration(node); } - if (node.kind == ts.SyntaxKind.NamespaceExportDeclaration) { + if (node.kind === ts.SyntaxKind.NamespaceExportDeclaration) { // just ignore `export as namespace FOO` statements… return this.removeStatement(node); } @@ -143,7 +143,7 @@ class Transformer { convertFunctionDeclaration(node: ts.FunctionDeclaration) { if (!node.name) { - throw new UnsupportedSyntaxError(node, `FunctionDeclaration should have a name`); + throw new UnsupportedSyntaxError(node, 'FunctionDeclaration should have a name'); } const scope = this.createDeclaration(node, node.name); @@ -153,7 +153,7 @@ class Transformer { convertClassOrInterfaceDeclaration(node: ts.ClassDeclaration | ts.InterfaceDeclaration) { if (!node.name) { - throw new UnsupportedSyntaxError(node, `ClassDeclaration / InterfaceDeclaration should have a name`); + throw new UnsupportedSyntaxError(node, 'ClassDeclaration / InterfaceDeclaration should have a name'); } const scope = this.createDeclaration(node, node.name); @@ -175,11 +175,11 @@ class Transformer { convertVariableStatement(node: ts.VariableStatement) { const { declarations } = node.declarationList; if (declarations.length !== 1) { - throw new UnsupportedSyntaxError(node, `VariableStatement with more than one declaration not yet supported`); + throw new UnsupportedSyntaxError(node, 'VariableStatement with more than one declaration not yet supported'); } for (const decl of declarations) { if (!ts.isIdentifier(decl.name)) { - throw new UnsupportedSyntaxError(node, `VariableDeclaration must have a name`); + throw new UnsupportedSyntaxError(node, 'VariableDeclaration must have a name'); } const scope = this.createDeclaration(node, decl.name); diff --git a/src/transform/astHelpers.ts b/src/transform/astHelpers.ts index 56f02816..1855dc10 100644 --- a/src/transform/astHelpers.ts +++ b/src/transform/astHelpers.ts @@ -153,7 +153,7 @@ export interface Range { } export function withStartEnd(esNode: T, nodeOrRange: ts.Node | Range): T { - let range: Range = + const range: Range = "start" in nodeOrRange ? nodeOrRange : { start: nodeOrRange.getStart(), end: nodeOrRange.getEnd() }; return Object.assign(esNode, range); } diff --git a/src/transform/errors.ts b/src/transform/errors.ts index a0e25927..14e6d2ad 100644 --- a/src/transform/errors.ts +++ b/src/transform/errors.ts @@ -1,6 +1,6 @@ -import * as codeFrame from "@babel/code-frame"; -import ts from "typescript"; -import { createRequire } from "module"; +import { createRequire } from "node:module"; +import type * as codeFrame from "@babel/code-frame"; +import type ts from "typescript"; function getCodeFrame(): typeof codeFrame.codeFrameColumns | undefined { let codeFrameColumns = undefined; diff --git a/src/transform/index.ts b/src/transform/index.ts index 60040b7f..86e8f1fd 100644 --- a/src/transform/index.ts +++ b/src/transform/index.ts @@ -1,4 +1,4 @@ -import * as path from "path"; +import * as path from "node:path"; import type { Plugin } from "rollup"; import ts from "typescript"; import { NamespaceFixer } from "./NamespaceFixer.js"; @@ -39,7 +39,7 @@ export const transform = () => { return { ...options, onLog(level, log, defaultHandler) { - if (level === "warn" && log.code == "CIRCULAR_DEPENDENCY") { + if (level === "warn" && log.code === "CIRCULAR_DEPENDENCY") { return; } if (onLog) { diff --git a/src/transform/preprocess.ts b/src/transform/preprocess.ts index 14e590b4..288f233e 100644 --- a/src/transform/preprocess.ts +++ b/src/transform/preprocess.ts @@ -108,7 +108,7 @@ export function preProcess({ sourceFile }: PreProcessInput): PreProcessOutput { fixModifiers(code, node); // collect the ranges for re-ordering - if (declarations.length == 1) { + if (declarations.length === 1) { const decl = declarations[0]!; if (ts.isIdentifier(decl.name)) { pushNamedNode(decl.name.getText(), [getStart(node), getEnd(node)]); @@ -143,7 +143,7 @@ export function preProcess({ sourceFile }: PreProcessInput): PreProcessOutput { code.appendLeft(commaPos, ";\n"); const start = node.getFullStart(); const slice = code.slice(start, node.getStart()); - let whitespace = slice.length - slice.trimStart().length; + const whitespace = slice.length - slice.trimStart().length; if (whitespace) { code.overwrite(start, start + whitespace, prefix); } else { @@ -230,7 +230,7 @@ export function preProcess({ sourceFile }: PreProcessInput): PreProcessOutput { const { line } = sourceFile.getLineAndCharacterOfPosition(ref.pos); const start = lineStarts[line]!; let end = sourceFile.getLineEndOfPosition(ref.pos); - if (code.slice(end, end + 1) == "\n") { + if (code.slice(end, end + 1) === "\n") { end += 1; } @@ -245,7 +245,7 @@ export function preProcess({ sourceFile }: PreProcessInput): PreProcessOutput { const { line } = sourceFile.getLineAndCharacterOfPosition(ref.pos); const start = lineStarts[line]!; let end = sourceFile.getLineEndOfPosition(ref.pos); - if (code.slice(end, end + 1) == "\n") { + if (code.slice(end, end + 1) === "\n") { end += 1; } @@ -371,5 +371,5 @@ function getEnd(node: ts.Node): number { } function newlineAt(node: ts.Node, idx: number): boolean { - return node.getSourceFile().getFullText()[idx] == "\n"; + return node.getSourceFile().getFullText()[idx] === "\n"; }