Skip to content

Commit

Permalink
refactor: minor improvements (#316)
Browse files Browse the repository at this point in the history
Signed-off-by: Andres Correa Casablanca <[email protected]>
  • Loading branch information
castarco authored Sep 19, 2024
1 parent 9d11bba commit fa093f2
Show file tree
Hide file tree
Showing 12 changed files with 42 additions and 39 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
Expand Down
2 changes: 1 addition & 1 deletion rollup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<RollupWatchOptions> = [
{
Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -140,7 +140,7 @@ const plugin: PluginImpl<Options> = (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);
Expand Down
2 changes: 1 addition & 1 deletion src/options.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import ts from "typescript";
import type ts from "typescript";

export interface Options {
/**
Expand Down
8 changes: 4 additions & 4 deletions src/program.ts
Original file line number Diff line number Diff line change
@@ -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?$/;
Expand Down Expand Up @@ -30,7 +30,7 @@ const DEFAULT_OPTIONS: ts.CompilerOptions = {

const configByPath = new Map<string, ts.ParsedCommandLine>();

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.
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -118,8 +118,8 @@ export function createProgram(fileName: string, overrideOptions: ts.CompilerOpti

export function createPrograms(input: Array<string>, overrideOptions: ts.CompilerOptions, tsconfig?: string) {
const programs = [];
const dtsFiles: Set<string> = new Set();
let inputs: Array<string> = [];
let dtsFiles: Set<string> = new Set();
let dirName = "";
let compilerOptions: ts.CompilerOptions = {};

Expand Down
23 changes: 13 additions & 10 deletions src/transform/DeclarationScope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -190,7 +190,7 @@ export class DeclarationScope {
}
}

convertMembers(members: ts.NodeArray<ts.TypeElement | ts.ClassElement>) {
convertMembers(members: ts.NodeArray<ts.TypeElement | ts.ClassElement>): 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)) {
Expand Down Expand Up @@ -229,7 +229,7 @@ export class DeclarationScope {
return params.length;
}

convertTypeNode(node?: ts.TypeNode): any {
convertTypeNode(node?: ts.TypeNode): void {
if (!node) {
return;
}
Expand All @@ -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) {
Expand All @@ -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) {
Expand Down Expand Up @@ -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;
}
Expand All @@ -362,15 +365,15 @@ 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;
}
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');
}
}

Expand Down Expand Up @@ -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');
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/transform/NamespaceFixer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: [],
Expand Down
12 changes: 6 additions & 6 deletions src/transform/Transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand All @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/transform/astHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ export interface Range {
}

export function withStartEnd<T extends ESTree.Node>(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);
}
Expand Down
6 changes: 3 additions & 3 deletions src/transform/errors.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
4 changes: 2 additions & 2 deletions src/transform/index.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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) {
Expand Down
10 changes: 5 additions & 5 deletions src/transform/preprocess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)]);
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
}

Expand All @@ -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;
}

Expand Down Expand Up @@ -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";
}

0 comments on commit fa093f2

Please sign in to comment.