Skip to content

Commit

Permalink
style: format with prettier v3
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 25, 2023
1 parent 1a25f45 commit 914493c
Show file tree
Hide file tree
Showing 11 changed files with 53 additions and 55 deletions.
18 changes: 9 additions & 9 deletions README.md
Expand Up @@ -101,7 +101,7 @@ import { resolveImports } from "mlly";

// import foo from 'file:///home/user/project/bar.mjs'
console.log(
await resolveImports(`import foo from './bar.mjs'`, { url: import.meta.url })
await resolveImports(`import foo from './bar.mjs'`, { url: import.meta.url }),
);
```
Expand Down Expand Up @@ -216,7 +216,7 @@ console.log(
findStaticImports(`
// Empty line
import foo, { bar /* foo */ } from 'baz'
`)
`),
);
```
Expand Down Expand Up @@ -276,7 +276,7 @@ import { findDynamicImports } from "mlly";
console.log(
findDynamicImports(`
const foo = await import('bar')
`)
`),
);
```
Expand All @@ -290,7 +290,7 @@ console.log(
export const foo = 'bar'
export { bar, baz }
export default something
`)
`),
);
```
Expand Down Expand Up @@ -331,7 +331,7 @@ console.log(
export const foo = 'bar'
export { bar, baz }
export default something
`)
`),
);
```
Expand Down Expand Up @@ -369,7 +369,7 @@ await evalModule(
import { reverse } from './utils.mjs'
console.log(reverse('!emosewa si sj'))
`,
{ url: import.meta.url }
{ url: import.meta.url },
);
```
Expand Down Expand Up @@ -453,7 +453,7 @@ console.log(
toDataURL(`
// This is an example
console.log('Hello world')
`)
`),
);
```
Expand Down Expand Up @@ -508,7 +508,7 @@ import { parseNodeModulePath } from "mlly";
// name: "lib"
// subpath: "./dist/index.mjs"
const { dir, name, subpath } = parseNodeModulePath(
"/src/a/node_modules/lib/dist/index.mjs"
"/src/a/node_modules/lib/dist/index.mjs",
);
```
Expand All @@ -521,7 +521,7 @@ import { lookupNodeModuleSubpath } from "mlly";

// subpath: "./utils"
const subpath = lookupNodeModuleSubpath(
"/src/a/node_modules/lib/dist/utils.mjs"
"/src/a/node_modules/lib/dist/utils.mjs",
);
```
Expand Down
4 changes: 1 addition & 3 deletions renovate.json
@@ -1,5 +1,3 @@
{
"extends": [
"github>unjs/renovate-config"
]
"extends": ["github>unjs/renovate-config"]
}
2 changes: 1 addition & 1 deletion src/_utils.ts
Expand Up @@ -12,7 +12,7 @@ export function pcall<TFn extends (...args: any[]) => any>(
): Promise<ReturnType<TFn>> {
try {
return Promise.resolve(function_(...arguments_)).catch((error) =>
perr(error)
perr(error),
);
} catch (error) {
return perr(error);
Expand Down
24 changes: 12 additions & 12 deletions src/analyze.ts
Expand Up @@ -95,13 +95,13 @@ 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)
(match) => /[^A-Za-z]type\s/.test(match.imports),
),
];
}

export function parseStaticImport(
matched: StaticImport | TypeImport
matched: StaticImport | TypeImport,
): ParsedStaticImport {
const cleanedImports = clearImports(matched.imports);

Expand All @@ -126,7 +126,7 @@ export function parseStaticImport(
}

export function parseTypeImport(
matched: TypeImport | StaticImport
matched: TypeImport | StaticImport,
): ParsedStaticImport {
if (matched.type === "type") {
return parseStaticImport(matched);
Expand Down Expand Up @@ -169,13 +169,13 @@ export function findExports(code: string): ESMExport[] {
const namedExports: NamedExport[] = normalizeNamedExports(
matchAll(EXPORT_NAMED_RE, code, {
type: "named",
})
}),
);

const destructuredExports: NamedExport[] = matchAll(
EXPORT_NAMED_DESTRUCT,
code,
{ type: "named" }
{ type: "named" },
);
for (const namedExport of destructuredExports) {
// @ts-expect-error groups
Expand All @@ -188,7 +188,7 @@ export function findExports(code: string): ESMExport[] {
name
.replace(/^.*?\s*:\s*/, "")
.replace(/\s*=\s*.*$/, "")
.trim()
.trim(),
);
}

Expand Down Expand Up @@ -226,7 +226,7 @@ export function findExports(code: string): ESMExport[] {
exports
// Filter false positive export matches
.filter(
(exp) => !exportLocations || _isExportStatement(exportLocations, exp)
(exp) => !exportLocations || _isExportStatement(exportLocations, exp),
)
// Prevent multiple exports of same function, only keep latest iteration of signatures
.filter((exp, index, exports) => {
Expand All @@ -246,14 +246,14 @@ export function findTypeExports(code: string): ESMExport[] {
const declaredExports: DeclarationExport[] = matchAll(
EXPORT_DECAL_TYPE_RE,
code,
{ type: "declaration" }
{ type: "declaration" },
);

// Find named exports
const namedExports: NamedExport[] = normalizeNamedExports(
matchAll(EXPORT_NAMED_TYPE_RE, code, {
type: "named",
})
}),
);

// Merge and normalize exports
Expand All @@ -275,7 +275,7 @@ export function findTypeExports(code: string): ESMExport[] {
exports
// Filter false positive export matches
.filter(
(exp) => !exportLocations || _isExportStatement(exportLocations, exp)
(exp) => !exportLocations || _isExportStatement(exportLocations, exp),
)
// Prevent multiple exports of same function, only keep latest iteration of signatures
.filter((exp, index, exports) => {
Expand Down Expand Up @@ -325,15 +325,15 @@ export function findExportNames(code: string): string[] {

export async function resolveModuleExportNames(
id: string,
options?: ResolveOptions
options?: ResolveOptions,
): Promise<string[]> {
const url = await resolvePath(id, options);
const code = await loadURL(url);
const exports = findExports(code);

// Explicit named exports
const exportNames = new Set(
exports.flatMap((exp) => exp.names).filter(Boolean)
exports.flatMap((exp) => exp.names).filter(Boolean),
);

// Recursive * exports
Expand Down
14 changes: 7 additions & 7 deletions src/eval.ts
Expand Up @@ -11,7 +11,7 @@ const EVAL_ESM_IMPORT_RE =

export async function loadModule(
id: string,
options: EvaluateOptions = {}
options: EvaluateOptions = {},
): Promise<any> {
const url = await resolve(id, options);
const code = await loadURL(url);
Expand All @@ -20,22 +20,22 @@ export async function loadModule(

export async function evalModule(
code: string,
options: EvaluateOptions = {}
options: EvaluateOptions = {},
): Promise<any> {
const transformed = await transformModule(code, options);
const dataURL = toDataURL(transformed);
return import(dataURL).catch((error) => {
error.stack = error.stack.replace(
new RegExp(dataURL, "g"),
options.url || "_mlly_eval_"
options.url || "_mlly_eval_",
);
throw error;
});
}

export function transformModule(
code: string,
options?: EvaluateOptions
options?: EvaluateOptions,
): Promise<string> {
// Convert JSON to module
if (options.url && options.url.endsWith(".json")) {
Expand All @@ -52,7 +52,7 @@ export function transformModule(

export async function resolveImports(
code: string,
options?: EvaluateOptions
options?: EvaluateOptions,
): Promise<string> {
const imports = [...code.matchAll(EVAL_ESM_IMPORT_RE)].map((m) => m[0]);
if (imports.length === 0) {
Expand All @@ -69,12 +69,12 @@ export async function resolveImports(
url = toDataURL(await transformModule(code, { url }));
}
resolved.set(id, url);
})
}),
);

const re = new RegExp(
uniqueImports.map((index) => `(${index})`).join("|"),
"g"
"g",
);
return code.replace(re, (id) => resolved.get(id));
}
16 changes: 8 additions & 8 deletions src/resolve.ts
Expand Up @@ -26,7 +26,7 @@ export interface ResolveOptions {
function _tryModuleResolve(
id: string,
url: URL,
conditions: any
conditions: any,
): any | undefined {
try {
return moduleResolve(id, url, conditions);
Expand Down Expand Up @@ -77,7 +77,7 @@ function _resolve(id: string, options: ResolveOptions = {}): string {
// If url is directory
new URL(joinURL(url.pathname, "_index.js"), url),
// TODO: Remove in next major version?
new URL("node_modules", url)
new URL("node_modules", url),
);
}
}
Expand All @@ -95,7 +95,7 @@ function _resolve(id: string, options: ResolveOptions = {}): string {
resolved = _tryModuleResolve(
id + prefix + extension,
url,
conditionsSet
conditionsSet,
);
if (resolved) {
break;
Expand All @@ -113,7 +113,7 @@ function _resolve(id: string, options: ResolveOptions = {}): string {
// Throw error if not found
if (!resolved) {
const error = new Error(
`Cannot find module ${id} imported from ${urls.join(", ")}`
`Cannot find module ${id} imported from ${urls.join(", ")}`,
);
// @ts-ignore
error.code = "ERR_MODULE_NOT_FOUND";
Expand All @@ -139,7 +139,7 @@ export function resolvePathSync(id: string, options?: ResolveOptions): string {

export function resolvePath(
id: string,
options?: ResolveOptions
options?: ResolveOptions,
): Promise<string> {
return pcall(resolvePathSync, id, options);
}
Expand Down Expand Up @@ -171,7 +171,7 @@ export function parseNodeModulePath(path: string) {

/** Reverse engineer a subpath export if possible */
export async function lookupNodeModuleSubpath(
path: string
path: string,
): Promise<string | undefined> {
path = normalize(fileURLToPath(path));
const { name, subpath } = parseNodeModulePath(path);
Expand Down Expand Up @@ -216,11 +216,11 @@ function _findSubpath(subpath: string, exports: PackageJson["exports"]) {

function _flattenExports(
exports: Exclude<PackageJson["exports"], string>,
path?: string
path?: string,
) {
return Object.entries(exports).flatMap(([key, value]) =>
typeof value === "string"
? [[path ?? key, value]]
: _flattenExports(value, path ?? key)
: _flattenExports(value, path ?? key),
);
}
2 changes: 1 addition & 1 deletion src/syntax.ts
Expand Up @@ -50,7 +50,7 @@ const validNodeImportDefaults: ValidNodeImportOptions = {

export async function isValidNodeImport(
id: string,
_options: ValidNodeImportOptions = {}
_options: ValidNodeImportOptions = {},
): Promise<boolean> {
if (isNodeBuiltin(id)) {
return true;
Expand Down
12 changes: 6 additions & 6 deletions test/exports.test.ts
Expand Up @@ -220,7 +220,7 @@ describe("findExportNames", () => {
export const foo = 'bar'
export { bar, baz }
export default something
`)
`),
).toMatchInlineSnapshot(`
[
"foo",
Expand Down Expand Up @@ -258,8 +258,8 @@ describe("resolveModuleExportNames", () => {
it("star exports", async () => {
expect(
await resolveModuleExportNames(
new URL("fixture/exports.mjs", import.meta.url).toString()
)
new URL("fixture/exports.mjs", import.meta.url).toString(),
),
).toMatchInlineSnapshot(`
[
"foo",
Expand All @@ -286,8 +286,8 @@ describe("resolveModuleExportNames", () => {
it("star exports with package", async () => {
expect(
await resolveModuleExportNames(
new URL("fixture/package/exports.mjs", import.meta.url).toString()
)
new URL("fixture/package/exports.mjs", import.meta.url).toString(),
),
).toMatchInlineSnapshot(`
[
"StaticRouter",
Expand Down Expand Up @@ -316,7 +316,7 @@ describe("findTypeExports", () => {
export type { Qux }
export type Bing = Qux
export declare function getWidget(n: number): Widget
`
`,
);
expect(matches).toMatchInlineSnapshot(`
[
Expand Down
8 changes: 4 additions & 4 deletions test/fixture/eval.mjs
Expand Up @@ -9,17 +9,17 @@ await evalModule(
`,
{
url: fileURLToPath(import.meta.url),
}
},
);

await loadModule("./hello.mjs", { url: import.meta.url });

console.log(
await loadModule("../../package.json", { url: import.meta.url }).then(
(r) => r.default.name
)
(r) => r.default.name,
),
);

await loadModule("./eval-err.mjs", { url: import.meta.url }).catch((e) =>
console.error(e)
console.error(e),
);

0 comments on commit 914493c

Please sign in to comment.