Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: findTypeImports for finding type imports #163

Merged
merged 8 commits into from Jun 19, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
64 changes: 62 additions & 2 deletions src/analyze.ts
Expand Up @@ -4,7 +4,7 @@ import { resolvePath, ResolveOptions } from "./resolve";
import { loadURL } from "./utils";

export interface ESMImport {
type: "static" | "dynamic";
type: "static" | "dynamic" | "type";
code: string;
start: number;
end: number;
Expand All @@ -27,6 +27,12 @@ export interface DynamicImport extends ESMImport {
expression: string;
}

export interface TypeImport extends ESMImport {
type: "type";
imports: string;
specifier: string;
}

export interface ESMExport {
_type?: "declaration" | "named" | "default" | "star";
type: "declaration" | "named" | "default" | "star";
Expand Down Expand Up @@ -59,6 +65,8 @@ export const ESM_STATIC_IMPORT_RE =
/(?<=\s|^|;)import\s*([\s"']*(?<imports>[\w\t\n\r $*,/{}]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gm;
export const DYNAMIC_IMPORT_RE =
/import\s*\((?<expression>(?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*)\)/gm;
const IMPORT_NAMED_TYPE_RE =
/(?<=\s|^|;)import\s*type\s+([\s"']*(?<imports>[\w\t\n\r $*,/{}]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gm;

export const EXPORT_DECAL_RE =
/\bexport\s+(?<declaration>(async function|function|let|const enum|const|enum|var|class))\s+(?<name>[\w$]+)/g;
Expand All @@ -83,7 +91,18 @@ export function findDynamicImports(code: string): DynamicImport[] {
return matchAll(DYNAMIC_IMPORT_RE, code, { type: "dynamic" });
}

export function parseStaticImport(matched: StaticImport): ParsedStaticImport {
export function findTypeImports(code: string): TypeImport[] {
return [
...matchAll(IMPORT_NAMED_TYPE_RE, code, { type: "type" }),
...matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" }).filter(
(match) => /[^A-Za-z]type\s/.test(match.imports)
),
];
}

export function parseStaticImport(
matched: StaticImport | TypeImport
): ParsedStaticImport {
const cleanedImports = (matched.imports || "")
.replace(/(\/\/[^\n]*\n|\/\*.*\*\/)/g, "")
.replace(/\s+/g, " ");
Expand Down Expand Up @@ -114,6 +133,47 @@ export function parseStaticImport(matched: StaticImport): ParsedStaticImport {
} as ParsedStaticImport;
}

export function parseTypeImport(
matched: TypeImport | StaticImport
): ParsedStaticImport {
if (matched.type === "type") {
return parseStaticImport(matched);
}
const cleanedImports = (matched.imports || "")
.replace(/(\/\/[^\n]*\n|\/\*.*\*\/)/g, "")
.replace(/\s+/g, " ");

const namedImports = {};
for (const namedImport of cleanedImports
.match(/{([^}]*)}/)?.[1]
?.split(",") || []) {
const [, source = namedImport.trim(), importName = source] = (() => {
return /\s+as\s+/.test(namedImport)
? namedImport.match(/^\s*type\s+(\S*) as (\S*)\s*$/) || []
: namedImport.match(/^\s*type\s+(\S*)\s*$/) || [];
})();

if (source && TYPE_RE.test(namedImport)) {
namedImports[source] = importName;
}
}

const topLevelImports = cleanedImports.replace(/{([^}]*)}/, "");
const namespacedImport = topLevelImports.match(/\* as \s*(\S*)/)?.[1];
const defaultImport =
topLevelImports
.split(",")
.find((index) => !/[*{}]/.test(index))
?.trim() || undefined;

return {
...matched,
defaultImport,
namespacedImport,
namedImports,
} as ParsedStaticImport;
}

export function findExports(code: string): ESMExport[] {
// Find declarations like export const foo = 'bar'
const declaredExports: DeclarationExport[] = matchAll(EXPORT_DECAL_RE, code, {
Expand Down
81 changes: 81 additions & 0 deletions test/imports.test.ts
Expand Up @@ -3,6 +3,8 @@ import {
findDynamicImports,
findStaticImports,
parseStaticImport,
findTypeImports,
parseTypeImport,
} from "../src";

// -- Static import --
Expand Down Expand Up @@ -139,6 +141,57 @@ const dynamicTests = {
},
};

const TypeTests = {
'import { type Foo, Bar } from "module-name";': {
specifier: "module-name",
namedImports: {
Foo: "Foo",
},
type: "static",
},
'import { member,/* hello */ type Foo as Baz, Bar } from "module-name";': {
specifier: "module-name",
namedImports: {
Foo: "Baz",
},
type: "static",
},
'import type { Foo, Bar } from "module-name";': {
specifier: "module-name",
namedImports: {
Foo: "Foo",
Bar: "Bar",
},
type: "type",
},
'import type Foo from "module-name";': {
specifier: "module-name",
defaultImport: "Foo",
type: "type",
},
'import type { Foo as Baz, Bar } from "module-name";': {
specifier: "module-name",
namedImports: {
Foo: "Baz",
Bar: "Bar",
},
type: "type",
},
'import { type member } from " module-name";': {
specifier: "module-name",
namedImports: { member: "member" },
type: "static",
},
'import { type member, type Foo as Bar } from " module-name";': {
specifier: "module-name",
namedImports: {
member: "member",
Foo: "Bar",
},
type: "static",
},
};

describe("findStaticImports", () => {
for (const [input, _results] of Object.entries(staticTests)) {
it(input.replace(/\n/g, "\\n"), () => {
Expand Down Expand Up @@ -177,3 +230,31 @@ describe("findDynamicImports", () => {
});
}
});

describe("findTypeImports", () => {
for (const [input, _results] of Object.entries(TypeTests)) {
it(input.replace(/\n/g, "\\n"), () => {
const matches = findTypeImports(input);
const results = Array.isArray(_results) ? _results : [_results];
expect(matches.length).toEqual(results.length);
for (const [index, test] of results.entries()) {
const match = matches[index];
expect(match.specifier).to.equal(test.specifier);

const parsed = parseTypeImport(match);
if (test.type) {
expect(parsed.type).to.equals(test.type);
}
if (test.defaultImport) {
expect(parsed.defaultImport).to.equals(test.defaultImport);
}
if (test.namedImports) {
expect(parsed.namedImports).to.eql(test.namedImports);
}
if (test.namespacedImport) {
expect(parsed.namespacedImport).to.eql(test.namespacedImport);
}
}
});
}
});