resolver.mjs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. /**
  2. * 导入说明符解析器。
  3. *
  4. * 修复原因(2026-09 review):首版 `resolveImport` 只解析 `./` `../` 开头的相对路径,
  5. * 其余全部返回 null 不建边。而本仓库主流写法是 `@zcode/<pkg>`、ui 的 `@/`、services 的 `#src/`,
  6. * 于是 module-dependency / deep-import / cycle / layer-direction / ui-implementation-import
  7. * 对跨包依赖全部失明(用 `@zcode/services/src/bots/botsService.js` 深导入实测 0 违规)。
  8. *
  9. * 这里按 Node 与 TypeScript 的真实解析顺序建边:
  10. * 1. 相对路径
  11. * 2. 最近 package.json 的 `imports`(`#src/*`)
  12. * 3. 最近 tsconfig.json 的 `compilerOptions.paths`(`@/*`)
  13. * 4. workspace 包名 + `exports`(含条件导出、通配符;`dist/` 目标回映到 `src/`)
  14. * 没有 exports 条目的子路径直接拼到包目录,保证深路径也能建边
  15. */
  16. import { promises as fs } from "node:fs";
  17. import path from "node:path";
  18. import { parse as parseYaml } from "yaml";
  19. import { parseConfigFileTextToJson } from "typescript";
  20. export const SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
  21. const DEFAULT_WORKSPACE_GLOBS = ["packages/*", "apps/*", "apps/*/packages/*"];
  22. const EXPORT_CONDITION_ORDER = ["import", "default", "node", "require", "types"];
  23. async function readJsonLoose(file) {
  24. try {
  25. const text = await fs.readFile(file, "utf8");
  26. // 正则去注释会把 @/* 与后续 src/**/*.ts 串成块注释,漏掉 UI 别名甚至整个 Desktop 包。
  27. // 复用 TypeScript 的 JSONC 解析,只移除真正的注释,保留字符串与尾逗号语义。
  28. const result = parseConfigFileTextToJson(file, text);
  29. return result.error ? null : result.config;
  30. } catch {
  31. return null;
  32. }
  33. }
  34. async function expandGlob(cwd, pattern) {
  35. const segments = pattern.split("/").filter(Boolean);
  36. let current = [cwd];
  37. for (const segment of segments) {
  38. const next = [];
  39. for (const dir of current) {
  40. if (segment === "*") {
  41. let entries = [];
  42. try {
  43. entries = await fs.readdir(dir, { withFileTypes: true });
  44. } catch {
  45. continue;
  46. }
  47. for (const entry of entries) {
  48. if (entry.isDirectory() && entry.name !== "node_modules")
  49. next.push(path.join(dir, entry.name));
  50. }
  51. } else {
  52. next.push(path.join(dir, segment));
  53. }
  54. }
  55. current = next;
  56. }
  57. return current;
  58. }
  59. async function workspaceGlobs(cwd) {
  60. try {
  61. const raw = parseYaml(await fs.readFile(path.join(cwd, "pnpm-workspace.yaml"), "utf8"));
  62. if (Array.isArray(raw?.packages) && raw.packages.length > 0) return raw.packages;
  63. } catch {
  64. // 没有 workspace 文件时退回默认目录约定
  65. }
  66. return DEFAULT_WORKSPACE_GLOBS;
  67. }
  68. export async function loadWorkspace(cwd = process.cwd()) {
  69. const dirs = new Set();
  70. for (const glob of await workspaceGlobs(cwd)) {
  71. for (const dir of await expandGlob(cwd, glob)) dirs.add(dir);
  72. }
  73. const packages = [];
  74. for (const dir of dirs) {
  75. const manifest = await readJsonLoose(path.join(dir, "package.json"));
  76. if (!manifest) continue;
  77. const tsconfig = await readJsonLoose(path.join(dir, "tsconfig.json"));
  78. const paths = tsconfig?.compilerOptions?.paths ?? null;
  79. const baseUrl = tsconfig?.compilerOptions?.baseUrl ?? ".";
  80. packages.push({
  81. name: typeof manifest.name === "string" ? manifest.name : null,
  82. dir,
  83. exports: manifest.exports ?? null,
  84. imports: manifest.imports ?? null,
  85. main: typeof manifest.main === "string" ? manifest.main : null,
  86. paths,
  87. pathsBase: path.resolve(dir, baseUrl),
  88. });
  89. }
  90. packages.sort((a, b) => b.dir.length - a.dir.length);
  91. const byName = new Map();
  92. for (const pkg of packages) if (pkg.name) byName.set(pkg.name, pkg);
  93. return { cwd, packages, byName };
  94. }
  95. function nearestPackage(file, workspace) {
  96. return workspace.packages.find((pkg) => file.startsWith(`${pkg.dir}${path.sep}`)) ?? null;
  97. }
  98. /** 在 exports/imports/paths 这类映射里匹配 key,支持单个 `*` 通配。 */
  99. function matchMap(map, key) {
  100. if (!map || typeof map !== "object") return null;
  101. if (Object.hasOwn(map, key)) return { value: map[key], wildcard: null };
  102. for (const [pattern, value] of Object.entries(map)) {
  103. const star = pattern.indexOf("*");
  104. if (star < 0) continue;
  105. const prefix = pattern.slice(0, star);
  106. const suffix = pattern.slice(star + 1);
  107. if (key.startsWith(prefix) && key.endsWith(suffix) && key.length >= pattern.length - 1) {
  108. return { value, wildcard: key.slice(prefix.length, key.length - suffix.length) };
  109. }
  110. }
  111. return null;
  112. }
  113. function targetsOf(value) {
  114. if (typeof value === "string") return [value];
  115. if (Array.isArray(value)) return value.flatMap(targetsOf);
  116. if (value && typeof value === "object") {
  117. const ordered = EXPORT_CONDITION_ORDER.filter((key) => key in value).map((key) => value[key]);
  118. const rest = Object.entries(value)
  119. .filter(([key]) => !EXPORT_CONDITION_ORDER.includes(key))
  120. .map(([, item]) => item);
  121. return [...ordered, ...rest].flatMap(targetsOf);
  122. }
  123. return [];
  124. }
  125. function substitute(target, wildcard) {
  126. return wildcard === null ? target : target.replace("*", wildcard);
  127. }
  128. function stripExtension(base) {
  129. if (base.endsWith(".d.ts")) return base.slice(0, -".d.ts".length);
  130. const extension = SOURCE_EXTENSIONS.find((item) => base.endsWith(item));
  131. return extension ? base.slice(0, -extension.length) : base;
  132. }
  133. function probe(absolute, knownFiles) {
  134. const base = stripExtension(absolute);
  135. const candidates = [];
  136. for (const extension of SOURCE_EXTENSIONS) candidates.push(`${base}${extension}`);
  137. for (const extension of SOURCE_EXTENSIONS) candidates.push(path.join(base, `index${extension}`));
  138. const found = candidates.find((candidate) => knownFiles.has(candidate));
  139. if (found) return found;
  140. // CLI 侧包的 exports 指向 dist/,源码在 src/;按同名路径回映。
  141. const distIndex = base.split(path.sep).lastIndexOf("dist");
  142. if (distIndex >= 0) {
  143. const parts = base.split(path.sep);
  144. parts[distIndex] = "src";
  145. return probe(parts.join(path.sep), knownFiles);
  146. }
  147. return null;
  148. }
  149. export function resolveSpecifier(from, specifier, knownFiles, workspace = null) {
  150. if (specifier.startsWith(".")) {
  151. return probe(path.resolve(path.dirname(from), specifier), knownFiles);
  152. }
  153. if (!workspace) return null;
  154. const pkg = nearestPackage(from, workspace);
  155. if (specifier.startsWith("#") && pkg?.imports) {
  156. const hit = matchMap(pkg.imports, specifier);
  157. if (hit) {
  158. for (const target of targetsOf(hit.value)) {
  159. const found = probe(path.resolve(pkg.dir, substitute(target, hit.wildcard)), knownFiles);
  160. if (found) return found;
  161. }
  162. }
  163. }
  164. if (pkg?.paths) {
  165. const hit = matchMap(pkg.paths, specifier);
  166. if (hit) {
  167. for (const target of targetsOf(hit.value)) {
  168. const found = probe(
  169. path.resolve(pkg.pathsBase, substitute(target, hit.wildcard)),
  170. knownFiles,
  171. );
  172. if (found) return found;
  173. }
  174. }
  175. }
  176. let owner = null;
  177. for (const [name, candidate] of workspace.byName) {
  178. if (specifier === name || specifier.startsWith(`${name}/`)) {
  179. if (!owner || name.length > owner.name.length) owner = candidate;
  180. }
  181. }
  182. if (!owner) return null;
  183. const subpath = specifier === owner.name ? "." : `./${specifier.slice(owner.name.length + 1)}`;
  184. const candidates = [];
  185. const hit = matchMap(owner.exports, subpath);
  186. if (hit)
  187. candidates.push(...targetsOf(hit.value).map((target) => substitute(target, hit.wildcard)));
  188. if (subpath === ".") {
  189. if (owner.main) candidates.push(owner.main);
  190. candidates.push("./src/index", "./index");
  191. } else {
  192. // 没有 exports 条目(或 exports 缺失)的深路径直接拼到包目录,再试 src/ 前缀:这类导入正是要拦的对象。
  193. candidates.push(subpath, `./src/${subpath.slice(2)}`);
  194. }
  195. for (const candidate of candidates) {
  196. const found = probe(path.resolve(owner.dir, candidate), knownFiles);
  197. if (found) return found;
  198. }
  199. return null;
  200. }