sharp-package-assets.mjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. // Sharp native module staging for the shared node_repl runtime.
  2. //
  3. // Why this exists: the bundled node_repl server
  4. // (apps/zcode-cli/packages/browser-use-plugin/dist/mcp/server.js) externalizes `sharp` because it loads a native `.node`
  5. // binary that esbuild cannot inline. In dev the workspace's hoisted
  6. // `node_modules/sharp` resolves fine. In the installed ZCode.app the server
  7. // runs from `<Resources>/glm/packages/browser-use-plugin/dist/mcp/server.js` and
  8. // Node walks up looking for `node_modules/sharp`. Nothing in that walk reaches
  9. // the Electron app.asar tree, so without staging sharp into the glm/ tree the
  10. // server fails at top-level ESM resolution and product CUA never comes up.
  11. //
  12. // What we do: copy `sharp` + the per-triplet prebuild packages into each official
  13. // plugin's `node_modules/` (including `zcode-cua-plugin`, which is CUA's native
  14. // dependency root and is independent from Browser Use).
  15. // macOS/Linux split the native `.node` and libvips into `@img/sharp-*` +
  16. // `@img/sharp-libvips-*`; Windows keeps both the `.node` and libvips DLLs in
  17. // `@img/sharp-win32-*`. Keeping dependencies beside the plugin avoids
  18. // electron-builder's root node_modules filter and matches Node's resolution.
  19. //
  20. // Mirrors node-pty-package-assets.mjs in spirit (per-triplet prebuild staging
  21. // into the packaged app) but writes into the bundled-agents tree instead of
  22. // before afterPack because extraResources already ships the whole glm/
  23. // directory; afterPack then verifies the final app tree.
  24. import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
  25. import { createRequire } from "node:module";
  26. import { dirname, resolve } from "node:path";
  27. const requireFromDesktop = createRequire(import.meta.url);
  28. /**
  29. * Map a normalized target platform key (`darwin-arm64`, `linux-x64`, etc.) to
  30. * the platform suffix sharp uses for its native prebuild packages.
  31. *
  32. * sharp's runtimePlatformArch() (sharp/lib/libvips.js) yields
  33. * `${process.platform}${runtimeLibc()}-${process.arch}`, where `runtimeLibc`
  34. * is the empty string everywhere except non-glibc Linux. For the desktop build
  35. * we always target glibc Linux (matching target-platform.mjs's npmLibc), so
  36. * plain `linux` is the right suffix.
  37. */
  38. export function resolveSharpPlatformSuffix(targetPlatform) {
  39. if (targetPlatform.os === "linux") {
  40. return `linux-${targetPlatform.arch}`;
  41. }
  42. return `${targetPlatform.os}-${targetPlatform.arch}`;
  43. }
  44. /**
  45. * Return the runtime packages that Sharp actually publishes for the target.
  46. *
  47. * Bugfix: Sharp 0.34.x does not publish `@img/sharp-libvips-win32-*`.
  48. * Windows ships libvips DLLs inside `@img/sharp-win32-*`, while macOS/Linux
  49. * keep libvips in a sibling package.
  50. */
  51. export function resolveSharpRuntimePackageNames(targetPlatform) {
  52. const suffix = resolveSharpPlatformSuffix(targetPlatform);
  53. const packageNames = ["sharp", "detect-libc", "semver", "@img/colour", `@img/sharp-${suffix}`];
  54. if (targetPlatform.os !== "win32") {
  55. packageNames.push(`@img/sharp-libvips-${suffix}`);
  56. }
  57. return packageNames;
  58. }
  59. /**
  60. * Resolve a dependency package's root directory from the desktop package,
  61. * walking the hoisted workspace layout. Throws if the package is missing so
  62. * CI fails loudly instead of producing an app without sharp.
  63. *
  64. * Note: `@img/sharp-*` packages restrict their `exports` map to just
  65. * `./sharp.node` and `./package`, so `require.resolve('<pkg>/package.json')`
  66. * throws ERR_PACKAGE_PATH_NOT_EXPORTED. We use the exported `./package`
  67. * subpath instead — Node resolves it to the package's package.json — and
  68. * fall back to the bare package entry for plain packages like `sharp`.
  69. */
  70. function resolvePackageRoot(packageName, fromDir) {
  71. // Prefer `/package` (resolves to package.json for both strict-exports and
  72. // legacy packages), fall back to the bare main entry.
  73. const candidateSpecifiers = [`${packageName}/package`, packageName];
  74. const tried = [];
  75. for (const specifier of candidateSpecifiers) {
  76. try {
  77. const resolved = requireFromDesktop.resolve(specifier, { paths: [fromDir] });
  78. // Walk up to the directory containing the package's package.json.
  79. let currentDir = dirname(resolved);
  80. while (currentDir !== dirname(currentDir)) {
  81. if (existsSync(resolve(currentDir, "package.json"))) {
  82. return currentDir;
  83. }
  84. currentDir = dirname(currentDir);
  85. }
  86. return dirname(resolved);
  87. } catch (error) {
  88. tried.push(`${specifier}: ${error.code ?? error.message}`);
  89. }
  90. }
  91. throw new Error(
  92. `[sharp-package-assets] cannot resolve ${packageName} from ${fromDir}; tried:\n${tried.map((t) => ` - ${t}`).join("\n")}`,
  93. );
  94. }
  95. /**
  96. * Copy a node_modules-style package directory while pruning the same
  97. * non-runtime files electron-builder would (maps / READMEs / tests). Source
  98. * tree comes from the dev workspace; target is inside the bundled agent tree
  99. * which is later copied verbatim into Resources/glm/.
  100. */
  101. function copyRuntimePackage(sourceRoot, targetRoot) {
  102. if (!existsSync(sourceRoot)) {
  103. throw new Error(`[sharp-package-assets] source package missing: ${sourceRoot}`);
  104. }
  105. // Clean rebuilds of the desktop bundle should not accumulate stale sharp
  106. // versions from previous runs.
  107. rmSync(targetRoot, { recursive: true, force: true });
  108. mkdirSync(targetRoot, { recursive: true });
  109. const SKIP_DIRS = new Set(["test", "tests", "__tests__", "node_modules"]);
  110. const SKIP_SUFFIXES = [".map", ".md", ".markdown", ".ts"];
  111. // Keep package.json (runtime `exports`), LICENSE, the JS, and the .node/.dylib/.so binaries.
  112. function visit(from, to) {
  113. const entries = readdirSync(from, { withFileTypes: true });
  114. for (const entry of entries) {
  115. if (entry.isDirectory()) {
  116. if (SKIP_DIRS.has(entry.name)) continue;
  117. // sharp's @img/sharp-libvips-* packages ship a `versions.json` and
  118. // a `lib/glib-2.0/include/glibconfig.h` build header that the runtime
  119. // never reads; keep `lib/` (it carries the dylib/.so) but skip nested
  120. // build-only includes via the SKIP rules above.
  121. visit(resolve(from, entry.name), resolve(to, entry.name));
  122. continue;
  123. }
  124. if (!entry.isFile()) continue;
  125. // Keep the .node binary, the dylib/.so, package.json, LICENSE, .js.
  126. if (SKIP_SUFFIXES.some((suffix) => entry.name.endsWith(suffix))) {
  127. // package.json must survive even though we never want .json noise —
  128. // it's required by Node's package resolution and by sharp's exports map.
  129. if (entry.name === "package.json") {
  130. // fall through and copy
  131. } else {
  132. continue;
  133. }
  134. }
  135. cpSync(resolve(from, entry.name), resolve(to, entry.name));
  136. }
  137. }
  138. visit(sourceRoot, targetRoot);
  139. if (!existsSync(targetRoot)) {
  140. throw new Error(`[sharp-package-assets] staging copy produced no output at ${targetRoot}`);
  141. }
  142. }
  143. /**
  144. * Stage Sharp's JS dependencies and target-specific native packages into
  145. * `<glmDir>/node_modules/...` so the shared node_repl server.js can
  146. * resolve the bare specifier `import sharp from "sharp"` from either official
  147. * plugin root. CUA passes its own root explicitly and does not depend on
  148. * Browser Use's staged files.
  149. *
  150. * Must be idempotent and safe to run for every desktop target platform.
  151. */
  152. /**
  153. * sharp 只服务于 Computer Use 截图(由 @zcode/zcode-cua 声明依赖)。
  154. * 构建使用不声明 sharp 的 Computer Use 占位包时,不暂存也不校验 sharp,安装包不携带 sharp/libvips。
  155. * 这里只读当前安装的 @zcode/zcode-cua 清单,不依赖包导出(其 exports 不含 package.json)。
  156. */
  157. export function isSharpRequiredByComputerUse({ desktopPackageRoot }) {
  158. for (let dir = resolve(desktopPackageRoot); ; dir = dirname(dir)) {
  159. const manifestPath = resolve(dir, "node_modules", "@zcode", "zcode-cua", "package.json");
  160. if (existsSync(manifestPath)) {
  161. const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
  162. return ["dependencies", "optionalDependencies", "peerDependencies"].some(
  163. (field) => typeof manifest[field]?.sharp === "string",
  164. );
  165. }
  166. if (dirname(dir) === dir) return false;
  167. }
  168. }
  169. export function stageSharpIntoBundledAgents({ desktopPackageRoot, glmDir, targetPlatform }) {
  170. if (!desktopPackageRoot) {
  171. throw new Error("[sharp-package-assets] desktopPackageRoot is required");
  172. }
  173. if (!glmDir) {
  174. throw new Error("[sharp-package-assets] glmDir is required");
  175. }
  176. if (!targetPlatform?.os || !targetPlatform?.arch) {
  177. throw new Error(
  178. `[sharp-package-assets] targetPlatform.{os,arch} required (got ${JSON.stringify(targetPlatform)})`,
  179. );
  180. }
  181. const runtimePackageNames = resolveSharpRuntimePackageNames(targetPlatform);
  182. const stagedNodeModulesDir = resolve(glmDir, "node_modules");
  183. mkdirSync(stagedNodeModulesDir, { recursive: true });
  184. const staged = [];
  185. for (const packageName of runtimePackageNames) {
  186. const sourceRoot = resolvePackageRoot(packageName, desktopPackageRoot);
  187. const targetRoot = resolve(stagedNodeModulesDir, packageName);
  188. copyRuntimePackage(sourceRoot, targetRoot);
  189. staged.push({ name: packageName, sourceRoot, targetRoot });
  190. console.log(`[sharp-package-assets] staged ${packageName} -> ${targetRoot}`);
  191. }
  192. return staged;
  193. }
  194. /**
  195. * Resolve the absolute path of the staged sharp directory inside the packaged
  196. * app, for afterPack assertion. This is where Node's resolution walk lands
  197. * when the plugin's server.js does `import sharp from "sharp"` in the
  198. * installed ZCode.app.
  199. */
  200. export function resolvePackagedSharpDir({
  201. resourcesDir,
  202. pluginRelativePath = "packages/browser-use-plugin",
  203. }) {
  204. return resolve(resourcesDir, "glm", pluginRelativePath, "node_modules", "sharp");
  205. }
  206. /**
  207. * Resolve the absolute path of the staged per-platform native binary
  208. * (e.g. `@img/sharp-darwin-arm64`) so tests/afterPack can assert its presence.
  209. */
  210. export function resolvePackagedSharpNativeDir({
  211. resourcesDir,
  212. targetPlatform,
  213. pluginRelativePath = "packages/browser-use-plugin",
  214. }) {
  215. const suffix = resolveSharpPlatformSuffix(targetPlatform);
  216. return resolve(
  217. resourcesDir,
  218. "glm",
  219. pluginRelativePath,
  220. "node_modules",
  221. "@img",
  222. `sharp-${suffix}`,
  223. );
  224. }
  225. /**
  226. * Verify the staged sharp tree looks loadable: package.json present, the
  227. * native `.node` file present, and libvips present at the platform-specific
  228. * location used by Sharp.
  229. *
  230. * Returns a list of human-readable problems; empty array means OK.
  231. */
  232. export function verifyStagedSharp({
  233. resourcesDir,
  234. targetPlatform,
  235. pluginRelativePath = "packages/browser-use-plugin",
  236. }) {
  237. const problems = [];
  238. const suffix = resolveSharpPlatformSuffix(targetPlatform);
  239. const sharpDir = resolvePackagedSharpDir({ resourcesDir, pluginRelativePath });
  240. if (!existsSync(sharpDir)) {
  241. problems.push(`missing sharp dir: ${sharpDir}`);
  242. return problems; // nothing else to check
  243. }
  244. if (!existsSync(resolve(sharpDir, "package.json"))) {
  245. problems.push(`missing sharp package.json: ${sharpDir}/package.json`);
  246. }
  247. if (!existsSync(resolve(sharpDir, "lib"))) {
  248. problems.push(`missing sharp lib/ dir: ${sharpDir}/lib`);
  249. }
  250. const nativeDir = resolvePackagedSharpNativeDir({
  251. resourcesDir,
  252. targetPlatform,
  253. pluginRelativePath,
  254. });
  255. let nativeLibDir = null;
  256. if (!existsSync(nativeDir)) {
  257. problems.push(`missing @img/sharp-${suffix} dir: ${nativeDir}`);
  258. } else {
  259. nativeLibDir = resolve(nativeDir, "lib");
  260. if (!existsSync(nativeLibDir)) {
  261. problems.push(`missing @img/sharp-${suffix}/lib dir: ${nativeLibDir}`);
  262. } else {
  263. const nodeFile = readdirSync(nativeLibDir).find((name) => name.endsWith(".node"));
  264. if (!nodeFile) {
  265. problems.push(`missing .node binary under @img/sharp-${suffix}/lib`);
  266. }
  267. }
  268. }
  269. if (targetPlatform.os === "win32") {
  270. // Bugfix: Windows 没有独立的 @img/sharp-libvips-win32-* 包,libvips DLL
  271. // 与 sharp.node 一起位于 @img/sharp-win32-*/lib。沿用 macOS/Linux 的
  272. // 目录模型会在资源准备阶段要求一个上游从未发布的包。
  273. if (
  274. nativeLibDir &&
  275. existsSync(nativeLibDir) &&
  276. !readdirSync(nativeLibDir).some((name) => /\.dll$/iu.test(name))
  277. ) {
  278. problems.push(`missing libvips DLL under @img/sharp-${suffix}/lib`);
  279. }
  280. return problems;
  281. }
  282. const libvipsDir = resolve(
  283. resourcesDir,
  284. "glm",
  285. pluginRelativePath,
  286. "node_modules",
  287. "@img",
  288. `sharp-libvips-${suffix}`,
  289. );
  290. if (!existsSync(libvipsDir)) {
  291. problems.push(`missing @img/sharp-libvips-${suffix} dir: ${libvipsDir}`);
  292. } else {
  293. const libvipsLibDir = resolve(libvipsDir, "lib");
  294. if (!existsSync(libvipsLibDir)) {
  295. problems.push(`missing @img/sharp-libvips-${suffix}/lib dir: ${libvipsLibDir}`);
  296. } else {
  297. // Bugfix: Linux 上游产物使用 libvips-cpp.so.8.17.3 这类版本化名称,
  298. // 只匹配以 `.so` 结尾会把已经正确打包的动态库误判为缺失。
  299. const libraryPattern = targetPlatform.os === "linux" ? /\.so(?:\.\d+)*$/u : /\.dylib$/u;
  300. const hasBinary = readdirSync(libvipsLibDir).some((name) => libraryPattern.test(name));
  301. if (!hasBinary) {
  302. problems.push(`missing libvips binary under @img/sharp-libvips-${suffix}/lib`);
  303. }
  304. }
  305. }
  306. return problems;
  307. }
  308. // Allow `node sharp-package-assets.mjs --glm-dir=... --os=... --arch=...` for
  309. // manual smoke testing outside the prepare:agent-bundle pipeline.
  310. const entryHref =
  311. typeof process !== "undefined" && process.argv[1]
  312. ? new URL(process.argv[1], import.meta.url).href
  313. : null;
  314. if (entryHref === import.meta.url) {
  315. const args = Object.fromEntries(
  316. process.argv.slice(2).map((arg) => {
  317. const match = arg.match(/^--([\w-]+)=(.*)$/u);
  318. return match ? [match[1], match[2]] : [arg, "true"];
  319. }),
  320. );
  321. const targetPlatform = {
  322. os: args.os ?? process.platform,
  323. arch: args.arch ?? process.arch,
  324. key: `${args.os ?? process.platform}-${args.arch ?? process.arch}`,
  325. };
  326. const desktopPackageRoot = import.meta.dirname
  327. ? resolve(import.meta.dirname, "..")
  328. : process.cwd();
  329. const glmDir =
  330. args["glm-dir"] ?? resolve(desktopPackageRoot, "bundled-agents", targetPlatform.key, "glm");
  331. stageSharpIntoBundledAgents({ desktopPackageRoot, glmDir, targetPlatform });
  332. // verifyStagedSharp expects resourcesDir to be the parent of `glm/`, i.e.
  333. // `<Resources>/` in the packaged app or `dirname(glmDir)` for ad-hoc tests.
  334. const problems = verifyStagedSharp({
  335. resourcesDir: resolve(glmDir, ".."),
  336. targetPlatform,
  337. // CLI smoke can target any staging root. The desktop product passes the
  338. // plugin-local relative path by default; this direct smoke stages sharp at
  339. // <glmDir>/node_modules, so verify that exact tree.
  340. pluginRelativePath: "",
  341. });
  342. if (problems.length > 0) {
  343. console.error("[sharp-package-assets] verification failed:");
  344. for (const problem of problems) console.error(` - ${problem}`);
  345. process.exit(1);
  346. }
  347. console.log(`[sharp-package-assets] OK at ${glmDir}/node_modules`);
  348. // Touch statSync to keep the import list honest for unused-symbol linters.
  349. void statSync;
  350. }