Skip to content

Commit

Permalink
chore: format
Browse files Browse the repository at this point in the history
  • Loading branch information
benyap committed Sep 30, 2023
1 parent 10cf47a commit 0a6bba6
Show file tree
Hide file tree
Showing 8 changed files with 98 additions and 89 deletions.
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export type ResolveTsPathOptions = Omit<
* in your transpiled JavaScript code.
*/
export async function resolveTsPaths(
options: ResolveTsPathOptions = {}
options: ResolveTsPathOptions = {},
): Promise<void> {
const {
project = "tsconfig.json",
Expand All @@ -30,7 +30,7 @@ export async function resolveTsPaths(
const programPaths = resolvePaths({ project, src, out }, tsConfig);
const aliases = computeAliases(
programPaths.basePath,
tsConfig?.options?.paths ?? {}
tsConfig?.options?.paths ?? {},
);
const files = getFilesToProcess(programPaths.outPath, ext);
const changes = generateChanges(files, aliases, programPaths);
Expand Down
10 changes: 5 additions & 5 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ function main() {

const aliases = computeAliases(
programPaths.basePath,
tsConfig?.options?.paths ?? {}
tsConfig?.options?.paths ?? {},
);
logger.fancyParams("aliases", aliases);

Expand All @@ -42,30 +42,30 @@ function main() {
const changes = generateChanges(files, aliases, programPaths);
logger.fancyParams(
"fileChanges",
changes.map(({ file, changes }) => ({ file, changes }))
changes.map(({ file, changes }) => ({ file, changes })),
);

if (options.noEmit) {
logger.info(
bold("resolve-tspaths:"),
"discovered",
changes.length,
"file(s) for change (none actually changed since --noEmit was given)"
"file(s) for change (none actually changed since --noEmit was given)",
);
} else {
applyChanges(changes);
logger.info(
bold("resolve-tspaths:"),
"changed",
changes.length,
"file(s)"
"file(s)",
);
}
} catch (error: any) {
if (error instanceof StepError) {
logger.fancyError(
`Error during step '${bold(error.step)}'`,
error.message
error.message,
);
} else throw error;
}
Expand Down
4 changes: 2 additions & 2 deletions src/steps/computeAliases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ import { InvalidAliasError } from "~/utils/errors";
*/
export function computeAliases(
basePath: string,
paths: { [key: string]: string[] }
paths: { [key: string]: string[] },
): Alias[] {
const regex = /\*$/;

const aliases: Alias[] = Object.keys(paths).map((alias) => ({
alias,
prefix: alias.replace(regex, ""),
aliasPaths: paths[alias].map((path: string) =>
resolve(basePath, path.replace(regex, ""))
resolve(basePath, path.replace(regex, "")),
),
}));

Expand Down
2 changes: 1 addition & 1 deletion src/steps/createProgram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function createProgram() {
.option(
"--ext <extensions...>",
"space-delimited list of file extensions to process",
DEFAULT_EXTENSIONS as any
DEFAULT_EXTENSIONS as any,
)
.option("--verbose", "output logs", false)
.option("--noEmit", "changes will not be emitted", false);
Expand Down
34 changes: 17 additions & 17 deletions src/steps/generateChanges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const IMPORT_EXPORT_REGEX =
/((?:require\(|require\.resolve\(|import\()|(?:import|export)\s+(?:[\s\S]*?from\s+)?)['"]([^'"]*)['"]\)?/g;

export const ESM_IMPORT_EXPORT_REGEX =
/(?:(?:import\()|(?:import|export)\s+(?:[\s\S]*?from\s+)?)['"]([^'"]*)['"]\)?/g
/(?:(?:import\()|(?:import|export)\s+(?:[\s\S]*?from\s+)?)['"]([^'"]*)['"]\)?/g;

export const COMMONJS_IMPORT_EXPORT_REGEX =
/(?:(?:require\(|require\.resolve\()\s+)['"]([^'"]*)['"]\)/g;
Expand All @@ -36,15 +36,15 @@ const MODULE_EXTS = [
export function generateChanges(
files: string[],
aliases: Alias[],
programPaths: Pick<ProgramPaths, "srcPath" | "outPath">
programPaths: Pick<ProgramPaths, "srcPath" | "outPath">,
): Change[] {
const changeList: Change[] = [];

for (const file of files) {
const { changed, text, changes } = replaceAliasPathsInFile(
file,
aliases,
programPaths
programPaths,
);

if (!changed) continue;
Expand All @@ -65,7 +65,7 @@ export function generateChanges(
export function replaceAliasPathsInFile(
filePath: string,
aliases: Alias[],
programPaths: Pick<ProgramPaths, "srcPath" | "outPath">
programPaths: Pick<ProgramPaths, "srcPath" | "outPath">,
): { changed: boolean; text: string; changes: TextChange[] } {
if (!existsSync(filePath))
throw new FileNotFoundError(replaceAliasPathsInFile.name, filePath);
Expand All @@ -87,7 +87,7 @@ export function replaceAliasPathsInFile(
filePath,
aliases,
programPaths,
esmImport
esmImport,
);

if (!result.replacement) return original;
Expand All @@ -103,7 +103,7 @@ export function replaceAliasPathsInFile(
result.replacement +
original.substring(index + importSpecifier.length)
);
}
},
);

return { changed: originalText !== newText, text: newText, changes };
Expand All @@ -123,7 +123,7 @@ export function aliasToRelativePath(
outputFile: string,
aliases: Alias[],
{ srcPath, outPath }: Pick<ProgramPaths, "srcPath" | "outPath">,
esModule?: boolean
esModule?: boolean,
): { file: string; original: string; replacement?: string } {
const sourceFile = resolve(srcPath, relative(outPath, outputFile));
const sourceFileDirectory = dirname(sourceFile);
Expand All @@ -133,15 +133,15 @@ export function aliasToRelativePath(
importSpecifier.startsWith("./") || importSpecifier.startsWith("../");

const matchingAliases = aliases.filter(({ prefix }) =>
importSpecifier.startsWith(prefix)
importSpecifier.startsWith(prefix),
);

const absoluteImportPaths = importPathIsRelative
? [resolve(sourceFileDirectory, importSpecifier)]
: matchingAliases.flatMap(({ prefix, aliasPaths }) =>
aliasPaths.map((aliasPath) =>
resolve(aliasPath, importSpecifier.replace(prefix, ""))
)
resolve(aliasPath, importSpecifier.replace(prefix, "")),
),
);

const absoluteImport = absoluteImportPaths.reduce<null | ReturnType<
Expand All @@ -163,13 +163,13 @@ export function aliasToRelativePath(
absoluteImport.type === "file"
? join(
relative(sourceFileDirectory, dirname(absoluteImportPath)),
basename(absoluteImportPath)
basename(absoluteImportPath),
)
: relative(sourceFileDirectory, absoluteImportPath);

const prefixedRelativePath = relativeImportPath.replace(
/^(?!\.+\/)/,
(m) => "./" + m
(m) => "./" + m,
);

const relativePathJsExtension = prefixedRelativePath.replace(
Expand All @@ -179,11 +179,11 @@ export function aliasToRelativePath(
.replace(/\.ts$/, ".js")
.replace(/\.tsx$/, ".jsx")
.replace(/\.mts$/, ".mjs")
.replace(/\.cts$/, ".cjs")
.replace(/\.cts$/, ".cjs"),
);

const jsxFileExists = isFile(
resolve(outputFileDirectory, relativePathJsExtension)
resolve(outputFileDirectory, relativePathJsExtension),
);
const relativePathJsxExtension = jsxFileExists
? relativePathJsExtension
Expand All @@ -205,10 +205,10 @@ export function aliasToRelativePath(
*/
function resolveImportPath(importPath: string) {
const importPathTs = importPath.replace(/\.[^/.]*js[^/.]*$/, (match) =>
match.replace("js", "ts")
match.replace("js", "ts"),
);
const importPathWithExtensions = MODULE_EXTS.map(
(ext) => `${importPath}${ext}`
(ext) => `${importPath}${ext}`,
);

const possiblePaths = [importPath, importPathTs, ...importPathWithExtensions];
Expand All @@ -228,7 +228,7 @@ function resolveImportPath(importPath: string) {
: [];

const existingIndexPath = possiblePathsAsDirectory.find((path) =>
isFile(path)
isFile(path),
);

if (existingIndexPath) {
Expand Down
4 changes: 2 additions & 2 deletions src/steps/resolvePaths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ import type { ProgramOptions, ProgramPaths, TSConfig } from "~/types";
*/
export function resolvePaths(
options: Pick<ProgramOptions, "out" | "project" | "src">,
tsConfig: TSConfig
tsConfig: TSConfig,
): ProgramPaths {
const { baseUrl = "", outDir, paths } = tsConfig.options ?? {};

const out = options.out ?? outDir;
if (!out) {
throw new StepError(
resolvePaths.name,
`Output directory must be specified using either the --out option or in tsconfig`
`Output directory must be specified using either the --out option or in tsconfig`,
);
}

Expand Down
17 changes: 13 additions & 4 deletions src/utils/errors.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
export class StepError extends Error {
constructor(public readonly step: string, message: string) {
constructor(
public readonly step: string,
message: string,
) {
super(message);
}
}
Expand All @@ -8,7 +11,7 @@ export class FileError extends StepError {
constructor(
public readonly step: string,
public readonly path: string,
message: string
message: string,
) {
super(step, `Error processing ${path}: ${message}`);
}
Expand All @@ -21,13 +24,19 @@ export class FileNotFoundError extends FileError {
}

export class TSConfigPropertyError extends StepError {
constructor(public readonly step: string, public readonly property: string) {
constructor(
public readonly step: string,
public readonly property: string,
) {
super(step, `${property} is not set in tsconfig`);
}
}

export class InvalidAliasError extends StepError {
constructor(public readonly step: string, public readonly alias: string) {
constructor(
public readonly step: string,
public readonly alias: string,
) {
super(step, `The alias ${alias} is not permitted`);
}
}
Loading

0 comments on commit 0a6bba6

Please sign in to comment.