File size: 1,331 Bytes
fc93158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { pathToFileURL } from "node:url";

type ModuleNamespace = Record<string, unknown>;
type GenericFunction = (...args: never[]) => unknown;

export function resolveFileModuleUrl(params: {
  modulePath: string;
  cacheBust?: boolean;
  nowMs?: number;
}): string {
  const url = pathToFileURL(params.modulePath).href;
  if (!params.cacheBust) {
    return url;
  }
  const ts = params.nowMs ?? Date.now();
  return `${url}?t=${ts}`;
}

export async function importFileModule(params: {
  modulePath: string;
  cacheBust?: boolean;
  nowMs?: number;
}): Promise<ModuleNamespace> {
  const specifier = resolveFileModuleUrl(params);
  return (await import(specifier)) as ModuleNamespace;
}

export function resolveFunctionModuleExport<T extends GenericFunction>(params: {
  mod: ModuleNamespace;
  exportName?: string;
  fallbackExportNames?: string[];
}): T | undefined {
  const explicitExport = params.exportName?.trim();
  if (explicitExport) {
    const candidate = params.mod[explicitExport];
    return typeof candidate === "function" ? (candidate as T) : undefined;
  }
  const fallbacks = params.fallbackExportNames ?? ["default"];
  for (const exportName of fallbacks) {
    const candidate = params.mod[exportName];
    if (typeof candidate === "function") {
      return candidate as T;
    }
  }
  return undefined;
}