forked from promptfoo/promptfoo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathesm.ts
27 lines (23 loc) · 892 Bytes
/
esm.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { pathToFileURL } from 'node:url';
import * as path from 'path';
// esm-specific crap that needs to get mocked out in tests
//import path from 'path';
//import { fileURLToPath } from 'url';
export function getDirectory(): string {
/*
// @ts-ignore: Jest chokes on this
const __filename = fileURLToPath(import.meta.url);
return path.dirname(__filename);
*/
return __dirname;
}
export async function importModule(modulePath: string, functionName?: string) {
// This is some hacky shit. It prevents typescript from transpiling `import` to `require`, which breaks mjs imports.
const resolvedPath = pathToFileURL(path.resolve(modulePath));
const importedModule = await eval(`import('${resolvedPath}')`);
const mod = importedModule?.default?.default || importedModule?.default || importedModule;
if (functionName) {
return mod[functionName];
}
return mod;
}