build.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. import { build } from "esbuild";
  2. import { cp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
  3. import { createRequire } from "node:module";
  4. import { dirname, join, resolve } from "node:path";
  5. import { fileURLToPath } from "node:url";
  6. import { keepKindLines } from "./kind-filter.mjs";
  7. import { writeNotices } from "./licenses.mjs";
  8. import { readPluginName } from "./plugin-name.mjs";
  9. // Builds the plugin package in the current directory into its dist/. The package declares its
  10. // panel title and formats under "office" in package.json.
  11. // 插件名取自 .zcode-plugin/plugin.json:内置插件包目录名(如 pdf-plugin)与插件名不同。
  12. const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
  13. const target = process.cwd();
  14. const pkg = JSON.parse(await readFile(join(target, "package.json"), "utf8"));
  15. const ALL_KINDS = ["docx", "xlsx", "pptx", "pdf"];
  16. const profile = {
  17. name: await readPluginName(target),
  18. version: pkg.version,
  19. title: pkg.office?.title,
  20. kinds: pkg.office?.kinds,
  21. };
  22. if (
  23. typeof profile.title?.en !== "string" ||
  24. typeof profile.title?.["zh-CN"] !== "string" ||
  25. !Array.isArray(profile.kinds) ||
  26. !profile.kinds.length ||
  27. profile.kinds.some((kind) => !ALL_KINDS.includes(kind))
  28. )
  29. throw new Error(`${target}/package.json: "office" needs title.en, title.zh-CN and kinds`);
  30. const has = (kind) => profile.kinds.includes(kind);
  31. const dist = join(target, "dist");
  32. const ui = join(dist, "ui");
  33. const require = createRequire(import.meta.url);
  34. const pdfjsRoot = dirname(require.resolve("pdfjs-dist/package.json"));
  35. const xlsxRoot = dirname(dirname(require.resolve("@extend-ai/react-xlsx")));
  36. const cjkFontRoot = dirname(require.resolve("@fontsource/noto-sans-sc/package.json"));
  37. await rm(dist, { recursive: true, force: true });
  38. await mkdir(ui, { recursive: true });
  39. await cp(join(root, "LICENSE"), join(dist, "LICENSE"));
  40. if (has("pdf")) {
  41. // pdf.js data files read by the panel (as resources) and by the server (from disk).
  42. for (const folder of ["cmaps", "standard_fonts", "wasm"]) {
  43. await cp(join(pdfjsRoot, folder), join(ui, "pdfjs", folder), {
  44. recursive: true,
  45. filter: (path) => !path.endsWith(".js"),
  46. });
  47. }
  48. await cp(join(pdfjsRoot, "build/pdf.worker.min.mjs"), join(ui, "pdf-worker.js"));
  49. // 系统没有 CJK 字体时的兜底字体(ui/cjkFontRuntime.ts):Noto Sans SC 400 的编号分片,
  50. // 每片带自己的 unicode-range,作为同一字体族的多个 FontFace 注册。
  51. const faces = [];
  52. await mkdir(join(ui, "fonts"), { recursive: true });
  53. const css = await readFile(join(cjkFontRoot, "400.css"), "utf8");
  54. for (const [, file, unicodeRange] of css.matchAll(
  55. /url\(\.\/files\/(noto-sans-sc-\d+-400-normal\.woff2)\)[^;]*;\s*unicode-range:\s*([^;]+);/g,
  56. )) {
  57. await cp(join(cjkFontRoot, "files", file), join(ui, "fonts", file));
  58. faces.push({ file: `fonts/${file}`, unicodeRange });
  59. }
  60. if (faces.length < 50)
  61. throw new Error(`Noto Sans SC: only ${faces.length} slices; check 400.css`);
  62. await writeFile(join(ui, "cjk-fallback.json"), JSON.stringify({ faces }));
  63. }
  64. /**
  65. * Makes the bundles this plugin's: src/profile.ts becomes the plugin's profile, and the format
  66. * registries keep only the lines tagged with the plugin's formats (`// kind:<format>`).
  67. */
  68. const officeProfile = {
  69. name: "office-profile",
  70. setup(builder) {
  71. builder.onLoad({ filter: /[\\/]src[\\/]profile\.ts$/ }, () => ({
  72. contents: `export const PROFILE = ${JSON.stringify(profile)};`,
  73. loader: "ts",
  74. }));
  75. builder.onLoad(
  76. { filter: /[\\/](src[\\/]adapters[\\/]parsers|ui[\\/]viewers[\\/]registry)\.ts$/ },
  77. async (args) => ({
  78. contents: keepKindLines(await readFile(args.path, "utf8"), profile.kinds),
  79. loader: "ts",
  80. }),
  81. );
  82. },
  83. };
  84. const define = { "process.env.NODE_ENV": '"production"' };
  85. // react-xlsx parses workbooks in a module worker it finds via import.meta.url, which an IIFE bundle
  86. // loses. Ship the worker as an asset and point the library at a blob URL the page creates.
  87. const xlsxWorker = has("xlsx")
  88. ? await build({
  89. metafile: true,
  90. entryPoints: [join(xlsxRoot, "dist/xlsx-worker.js")],
  91. bundle: true,
  92. format: "esm",
  93. platform: "browser",
  94. target: "es2022",
  95. minify: true,
  96. legalComments: "none",
  97. define,
  98. write: false,
  99. })
  100. : null;
  101. if (xlsxWorker) {
  102. await cp(join(xlsxRoot, "dist/duke_sheets_wasm_bg.wasm"), join(ui, "sheets.wasm"));
  103. await writeFile(join(ui, "xlsx-worker.js"), xlsxWorker.outputFiles[0].contents);
  104. }
  105. const xlsxWorkerUrl = {
  106. name: "xlsx-worker-url",
  107. setup(builder) {
  108. builder.onLoad(
  109. { filter: /@extend-ai[\\/]react-xlsx[\\/]dist[\\/]index\.js$/ },
  110. async (args) => {
  111. const source = await readFile(args.path, "utf8");
  112. const needle = 'new URL("./xlsx-worker.js", import.meta.url)';
  113. if (!source.includes(needle))
  114. throw new Error("react-xlsx worker URL not found; update the build patch");
  115. return {
  116. contents: source.replace(needle, "globalThis.__officeXlsxWorkerUrl"),
  117. loader: "js",
  118. };
  119. },
  120. );
  121. },
  122. };
  123. // pdf.js 画布对未嵌入字体只用同名系统字体或通用族;让它经 ui/cjkFontRuntime.ts 取字体链
  124. // (中日韩字体回退,规格见 docs/plugins/2026-10-15-office-viewer-builtin-panels-spec.md §5)。
  125. const pdfjsCanvasFonts = {
  126. name: "pdfjs-canvas-fonts",
  127. setup(builder) {
  128. builder.onLoad({ filter: /pdfjs-dist[\\/]build[\\/]pdf\.mjs$/ }, async (args) => {
  129. const source = await readFile(args.path, "utf8");
  130. const chain = 'fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`';
  131. const needle = `const typeface = ${chain};`;
  132. if (!source.includes(needle))
  133. throw new Error("pdf.js canvas font chain not found; update the build patch");
  134. // 正斜杠:Windows 绝对路径写进 import 语句时不依赖反斜杠转义。
  135. const hook = JSON.stringify(join(root, "ui/cjkFontRuntime.ts").replaceAll("\\", "/"));
  136. return {
  137. contents: `import { pdfTypeface as __officePdfTypeface } from ${hook};\n${source.replace(
  138. needle,
  139. () => `const typeface = __officePdfTypeface(fontObj, ${chain});`,
  140. )}`,
  141. loader: "js",
  142. };
  143. });
  144. },
  145. };
  146. const app = await build({
  147. plugins: [officeProfile, xlsxWorkerUrl, pdfjsCanvasFonts],
  148. metafile: true,
  149. entryPoints: [join(root, "ui/main.tsx")],
  150. bundle: true,
  151. format: "iife",
  152. platform: "browser",
  153. target: "es2022",
  154. minify: true,
  155. legalComments: "none",
  156. define,
  157. write: false,
  158. outdir: ui,
  159. logOverride: { "direct-eval": "silent" },
  160. });
  161. const js = Buffer.from(app.outputFiles.find((file) => file.path.endsWith(".js")).contents);
  162. // Split the bundle into resources below the host's per-read limit, on UTF-8 boundaries.
  163. const scripts = [];
  164. for (let offset = 0; offset < js.length; ) {
  165. let end = Math.min(offset + 4 * 1024 * 1024, js.length);
  166. while (end < js.length && (js[end] & 0xc0) === 0x80) end--;
  167. const name = `bundle-${scripts.length}.txt`;
  168. scripts.push(name);
  169. await writeFile(join(ui, name), js.subarray(offset, end));
  170. offset = end;
  171. }
  172. await writeFile(join(ui, "assets.json"), JSON.stringify({ scripts, scriptBytes: js.length }));
  173. await writeFile(join(ui, "panel.css"), await readFile(join(root, "ui/panel.css"), "utf8"));
  174. const bootstrap = await build({
  175. plugins: [officeProfile],
  176. metafile: true,
  177. entryPoints: [join(root, "ui/bootstrap.ts")],
  178. bundle: true,
  179. format: "iife",
  180. platform: "browser",
  181. target: "es2022",
  182. minify: true,
  183. define,
  184. write: false,
  185. });
  186. const escapeHtml = (text) =>
  187. text.replace(
  188. /[&<>"]/g,
  189. (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[char],
  190. );
  191. const html = (await readFile(join(root, "ui/panel.html"), "utf8"))
  192. .replaceAll("__TITLE__", () => escapeHtml(profile.title.en))
  193. .replace("/*__BOOTSTRAP__*/", () =>
  194. bootstrap.outputFiles[0].text.replaceAll("</script", "<\\/script"),
  195. );
  196. await writeFile(join(ui, "panel.html"), html);
  197. // ExcelJS's streaming reader/writer and CSV support are unused (workbooks load through JSZip);
  198. // stub their dependencies so they are not bundled.
  199. const unusedExcelJsDeps = {
  200. name: "unused-exceljs-deps",
  201. setup(builder) {
  202. builder.onResolve({ filter: /^(archiver|unzipper|tmp|fast-csv)$/ }, (args) => ({
  203. path: args.path,
  204. namespace: "unused",
  205. }));
  206. builder.onLoad({ filter: /.*/, namespace: "unused" }, (args) => ({
  207. // Module-level calls (tmp.setGracefulCleanup) must still work; any real use throws.
  208. contents: `const fail = () => { throw new Error(${JSON.stringify(`${args.path} is not bundled`)}); };
  209. module.exports = new Proxy({}, { get: (_, key) => (key === "setGracefulCleanup" ? () => {} : fail) });`,
  210. loader: "js",
  211. }));
  212. },
  213. };
  214. const server = await build({
  215. plugins: [officeProfile, unusedExcelJsDeps],
  216. metafile: true,
  217. entryPoints: [join(root, "src/adapters/main.ts")],
  218. outfile: join(dist, "server.mjs"),
  219. bundle: true,
  220. platform: "node",
  221. format: "esm",
  222. target: "node24",
  223. legalComments: "none",
  224. banner: {
  225. js: 'import { createRequire as __createRequire } from "node:module"; const require=__createRequire(import.meta.url);',
  226. },
  227. logOverride: { "direct-eval": "silent" },
  228. });
  229. // Licences of everything bundled, plus the pdf.js / react-xlsx data files copied verbatim.
  230. const notices = join(dist, "THIRD_PARTY_NOTICES.txt");
  231. await writeNotices(
  232. [app.metafile, bootstrap.metafile, server.metafile, xlsxWorker?.metafile].filter(Boolean),
  233. notices,
  234. );
  235. const extra = [
  236. // ui/icons.tsx copies path data from Lucide.
  237. `lucide icons (path data in ui/icons.tsx) — ISC\nISC License\n\nCopyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather (MIT). All other copyright (c) for Lucide are held by Lucide Contributors 2022.\n\nPermission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.`,
  238. ];
  239. if (has("pdf"))
  240. extra.push(
  241. `@fontsource/noto-sans-sc (ui/fonts, ui/cjk-fallback.json) — OFL-1.1\n${await readFile(join(cjkFontRoot, "LICENSE"), "utf8")}`,
  242. );
  243. for (const folder of has("pdf") ? ["standard_fonts", "wasm"] : [])
  244. for (const file of (await readdir(join(pdfjsRoot, folder))).filter((name) =>
  245. name.startsWith("LICENSE"),
  246. ))
  247. extra.push(
  248. `pdfjs-dist ${folder}/${file}\n${await readFile(join(pdfjsRoot, folder, file), "utf8")}`,
  249. );
  250. await writeFile(
  251. notices,
  252. `${await readFile(notices, "utf8")}\n\n----------------------------------------\n\n${extra.join("\n\n----------------------------------------\n\n")}\n`,
  253. );
  254. const kib = (bytes) => `${(bytes / 1024 / 1024).toFixed(2)} MiB`;
  255. process.stdout.write(
  256. `${profile.title.en} UI (${profile.kinds.join(", ")}): ${kib(js.length)} in ${scripts.length} resources, loader ${Math.round(Buffer.byteLength(html) / 1024)} KiB\n`,
  257. );