package-exports.mjs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { readFileSync } from "node:fs";
  2. import path from "node:path";
  3. // Single derivation of "package export specifier -> source file" for the workspace.
  4. // The published packages point at built `dist` output, but every in-repository
  5. // consumer (type checking, Vitest resolution) must resolve the TypeScript source
  6. // instead. Keeping one implementation prevents the type-check path map and the test
  7. // resolver from disagreeing about the same package.
  8. function sourceOf(target) {
  9. return target
  10. .replace(/^\.\/dist\//u, "./src/")
  11. .replace(/\.d\.ts$/u, ".ts")
  12. .replace(/\.js$/u, ".ts");
  13. }
  14. export function packageExportEntries(root, packageRoots) {
  15. const entries = [];
  16. for (const directory of packageRoots) {
  17. const manifest = JSON.parse(
  18. readFileSync(path.join(root, directory, "package.json"), "utf8"),
  19. );
  20. for (const [subpath, value] of Object.entries(
  21. manifest.exports ?? { ".": manifest.types },
  22. )) {
  23. const target =
  24. typeof value === "string"
  25. ? value
  26. : (value?.types ?? value?.import ?? value?.default);
  27. if (!target || !subpath.startsWith(".")) continue;
  28. const specifier = manifest.name + (subpath === "." ? "" : subpath.slice(1));
  29. const source = sourceOf(target);
  30. entries.push({
  31. specifier,
  32. directory,
  33. // Repository-relative POSIX path to the source entry point.
  34. file: `${directory}/${source.replace(/^\.\//u, "")}`,
  35. });
  36. }
  37. }
  38. return entries;
  39. }