exportsFrom

tcmts.cli.mirror.exportsFrom · #qb3fklx3 · term · runs on the server

uses node:fs

Whether module entry exports leaf from file, under that name: it is the file, or re-exports it (export * from, export { leaf } from).

import fs from "node:fs";
import path from "node:path";

export function exportsFrom(entry: string, file: string, leaf: string, seen: Set<string>): boolean {
  if (entry === file) return true;
  if (seen.has(entry) || !fs.existsSync(entry)) return false;
  seen.add(entry);
  for (const m of fs.readFileSync(entry, "utf8").matchAll(/export\s+(?:type\s+)?(\*|\{([^}]*)\})\s+from\s+["'](\.{1,2}\/[^"']+)["']/g)) {
    const named = m[2]?.split(",").map((e) => e.trim().replace(/^type\s+/, "").split(/\s+as\s+/));
    if (m[1] !== "*" && !named?.some(([a, b]) => a === leaf && (b ?? a) === leaf)) continue;
    if (exportsFrom(path.resolve(path.dirname(entry), m[3]!), file, leaf, seen)) return true;
  }
  return false;
}

used by