providedPaths

tcmts.core.program.providedPaths · #zf75dq2b · term · runs on the server

uses node:fs

Provided packages as paths: each import of one in the root files (and a .tsx file's JSX runtime) mapped to the file it resolves to as the package's cache alias (react/jsx-runtime → npm__react__19/jsx-runtime, resolved from the cache, where its DefinitelyTyped types are found as usual).

import { packageNameOf } from "#codebase/tcmts/core/program";
import type { CompilerOptions, PackageResolver } from "#codebase/tcmts/core/program";
import { parse } from "#codebase/tcmts/core/ts";
import fs from "node:fs";
import path from "node:path";
import type { StringLiteral as ts_StringLiteral } from "typescript/ast";
import { ModuleKind as ts_ModuleKind } from "typescript/sync";
import type { ModuleResolver as ts_ModuleResolver } from "typescript/sync";

export function providedPaths(
  rootFiles: string[],
  options: CompilerOptions,
  overlay: ReadonlyMap<string, string> | undefined,
  packages: PackageResolver | undefined,
  resolver: () => ts_ModuleResolver,
): Record<string, string[]> | undefined {
  if (!packages) return undefined;
  const paths: Record<string, string[]> = {};
  for (const file of rootFiles) {
    let text = overlay?.get(file);
    if (text === undefined) {
      try {
        text = fs.readFileSync(file, "utf8");
      } catch {
        continue;
      }
    }
    const specs = parse(file, text).imports.map((n) => (n as ts_StringLiteral).text);
    if (/\.[cm]?tsx$/.test(file)) specs.push(`${(options.jsxImportSource as string | undefined) ?? "react"}/jsx-runtime`);
    for (const spec of specs) {
      const name = packageNameOf(spec);
      const target = name && !paths[spec] ? packages(name, file) : undefined;
      if (!name || !target) continue;
      const resolved = resolver().resolveModuleName(target.specifier + spec.slice(name.length), path.dirname(target.from), ts_ModuleKind.ESNext);
      if (resolved.resolvedModule) paths[spec] = [resolved.resolvedModule.resolvedFileName];
    }
  }
  return Object.keys(paths).length ? paths : undefined;
}

uses

used by