({
filePath,
functionName,
defaultFunctionName = 'func',
basePath = cliState.basePath,
useCache = true,
}: LoadFunctionOptions)
| 22 | * @returns The loaded function |
| 23 | */ |
| 24 | export async function loadFunction<T extends Function>({ |
| 25 | filePath, |
| 26 | functionName, |
| 27 | defaultFunctionName = 'func', |
| 28 | basePath = cliState.basePath, |
| 29 | useCache = true, |
| 30 | }: LoadFunctionOptions): Promise<T> { |
| 31 | const resolvedPath = basePath ? path.resolve(basePath, filePath) : filePath; |
| 32 | const cacheKey = `${resolvedPath}:${ |
| 33 | functionName ? `named:${functionName}` : `default:${defaultFunctionName}` |
| 34 | }`; |
| 35 | |
| 36 | if (useCache && functionCache[cacheKey]) { |
| 37 | return functionCache[cacheKey] as T; |
| 38 | } |
| 39 | |
| 40 | if (!isJavascriptFile(resolvedPath) && !resolvedPath.endsWith('.py')) { |
| 41 | throw new Error( |
| 42 | `File must be a JavaScript (${JAVASCRIPT_EXTENSIONS.join(', ')}) or Python (.py) file`, |
| 43 | ); |
| 44 | } |
| 45 | |
| 46 | try { |
| 47 | let func: T; |
| 48 | if (isJavascriptFile(resolvedPath)) { |
| 49 | const module = await importModule(resolvedPath, functionName); |
| 50 | let moduleFunc: any; |
| 51 | |
| 52 | if (functionName) { |
| 53 | moduleFunc = module; |
| 54 | } else { |
| 55 | moduleFunc = |
| 56 | typeof module === 'function' |
| 57 | ? module |
| 58 | : module?.default?.default || |
| 59 | module?.default || |
| 60 | module?.[defaultFunctionName] || |
| 61 | module; |
| 62 | } |
| 63 | |
| 64 | if (typeof moduleFunc !== 'function') { |
| 65 | throw new Error( |
| 66 | functionName |
| 67 | ? `JavaScript file must export a "${functionName}" function` |
| 68 | : `JavaScript file must export a function (as default export or named export "${defaultFunctionName}")`, |
| 69 | ); |
| 70 | } |
| 71 | func = moduleFunc as T; |
| 72 | } else { |
| 73 | const result = (...args: any[]) => |
| 74 | runPython(resolvedPath, functionName || defaultFunctionName, args); |
| 75 | func = result as unknown as T; |
| 76 | } |
| 77 | |
| 78 | if (useCache) { |
| 79 | functionCache[cacheKey] = func; |
| 80 | } |
| 81 |
no test coverage detected
searching dependent graphs…