merong-docs 0.1.11 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/OVERVIEW.md +19 -19
  2. package/OVERVIEW.zh-CN.md +19 -22
  3. package/README.md +77 -77
  4. package/README.zh-CN.md +81 -81
  5. package/client/android-file-share.ts +25 -25
  6. package/client/controls.tsx +163 -163
  7. package/client/document-panel.tsx +166 -166
  8. package/client/external-file.tsx +78 -78
  9. package/client/file-reader.tsx +43 -43
  10. package/client/markdown-panel.tsx +737 -737
  11. package/client/markdown-scroll.ts +122 -122
  12. package/client/messages.ts +224 -224
  13. package/client/native-contacts.ts +145 -145
  14. package/client/page-render-queue.ts +12 -12
  15. package/client/page-selection.tsx +227 -227
  16. package/client/page-tools.tsx +72 -72
  17. package/client/pdf-geometry.ts +96 -96
  18. package/client/pdf-panel.tsx +477 -477
  19. package/client/reader-find.tsx +190 -190
  20. package/client/reader-notice.tsx +46 -46
  21. package/client/settings.tsx +143 -143
  22. package/client/syntax.tsx +55 -55
  23. package/client/viewport-geometry.ts +61 -61
  24. package/client/web.ts +462 -462
  25. package/client/worksheet-panel.tsx +631 -631
  26. package/client/zoom-controls.tsx +140 -140
  27. package/index.client.tsx +36 -36
  28. package/index.server.ts +73 -73
  29. package/node_modules/markdown-it/bin/markdown-it.mjs +0 -0
  30. package/node_modules/yaml/bin.mjs +0 -0
  31. package/npm-shrinkwrap.json +2 -2
  32. package/package.json +1 -1
  33. package/scripts/prepare-office.mjs +20 -20
  34. package/server/engine.ts +89 -89
  35. package/server/external-file.ts +42 -42
  36. package/server/generated/document-worker.ts +1 -1
  37. package/server/generated/rust-reader_bg.wasm +0 -0
  38. package/server/markdown-index.ts +305 -305
  39. package/server/markdown-links.ts +51 -51
  40. package/server/markdown-page.ts +120 -120
  41. package/server/office-fonts.cjs +824 -824
  42. package/server/office-location.ts +41 -41
  43. package/server/office-preview.ts +186 -186
  44. package/server/office-worker.cjs +49 -49
  45. package/server/office-xml.ts +79 -79
  46. package/server/pdf-engine.ts +168 -168
  47. package/server/pdf-text-geometry.ts +60 -60
  48. package/server/rust-reader.ts +40 -40
  49. package/server/structured-document.ts +69 -69
  50. package/server/text-search.ts +15 -15
  51. package/server/worker-entry.ts +42 -42
  52. package/server/worker-protocol.ts +38 -38
  53. package/server/worksheet.ts +67 -67
  54. package/server/workspace-file.ts +63 -63
  55. package/shared/contracts.ts +187 -187
  56. package/shared/file-limits.ts +5 -5
  57. package/shared/markdown-constants.ts +4 -4
  58. package/shared/markdown-math.ts +198 -198
  59. package/shared/markdown-references.ts +83 -83
  60. package/shared/markdown-source-location.ts +8 -8
  61. package/shared/reader-settings.ts +15 -15
  62. package/shared/reader-shortcuts.ts +132 -132
  63. package/vendor/office2pdf/office2pdf_bg.wasm +2 -2
@@ -1,824 +1,824 @@
1
- const { execFile } = require("node:child_process");
2
- const { open, readdir, readFile, stat } = require("node:fs/promises");
3
- const { homedir } = require("node:os");
4
- const { basename, extname, join, win32 } = require("node:path");
5
- const { promisify } = require("node:util");
6
- const { fromBufferPromise } = require("yauzl");
7
-
8
- const execFileAsync = promisify(execFile);
9
-
10
- const FONT_EXTENSIONS = new Set([".ttf", ".otf", ".ttc", ".otc"]);
11
- const MAX_XML_ENTRY_BYTES = 8 * 1024 * 1024;
12
- const MAX_XML_TOTAL_BYTES = 32 * 1024 * 1024;
13
- const MAX_NAME_TABLE_BYTES = 1024 * 1024;
14
- const DEFAULT_MAX_FILE_BYTES = 48 * 1024 * 1024;
15
- const DEFAULT_MAX_TOTAL_BYTES = 64 * 1024 * 1024;
16
- const DEFAULT_MAX_FILES = 48;
17
-
18
- const FILENAME_FAMILY_ALIASES = {
19
- times: "timesnewroman",
20
- timesbd: "timesnewroman",
21
- timesi: "timesnewroman",
22
- timesbi: "timesnewroman",
23
- arial: "arial",
24
- arialbd: "arial",
25
- ariali: "arial",
26
- arialbi: "arial",
27
- cour: "couriernew",
28
- courbd: "couriernew",
29
- couri: "couriernew",
30
- courbi: "couriernew",
31
- calibri: "calibri",
32
- calibrib: "calibri",
33
- calibrii: "calibri",
34
- calibriz: "calibri",
35
- calibril: "calibri",
36
- calibrili: "calibri",
37
- cambria: "cambria",
38
- cambriab: "cambria",
39
- cambriai: "cambria",
40
- cambriaz: "cambria",
41
- georgia: "georgia",
42
- georgiab: "georgia",
43
- georgiai: "georgia",
44
- georgiaz: "georgia",
45
- verdana: "verdana",
46
- verdanab: "verdana",
47
- verdanai: "verdana",
48
- verdanaz: "verdana",
49
- tahoma: "tahoma",
50
- tahomabd: "tahoma",
51
- trebuc: "trebuchetms",
52
- trebucbd: "trebuchetms",
53
- trebucit: "trebuchetms",
54
- trebucbi: "trebuchetms",
55
- consola: "consolas",
56
- consolab: "consolas",
57
- consolai: "consolas",
58
- consolaz: "consolas",
59
- simsun: "simsun",
60
- simsunb: "simsun",
61
- simhei: "simhei",
62
- msyh: "microsoftyahei",
63
- msyhbd: "microsoftyahei",
64
- msyhl: "microsoftyahei",
65
- simkai: "kaiti",
66
- simfang: "fangsong",
67
- deng: "dengxian",
68
- dengb: "dengxian",
69
- dengl: "dengxian",
70
- pingfang: "pingfangsc",
71
- songti: "songtisc",
72
- stsong: "stsong",
73
- stheiti: "stheiti",
74
- stkaiti: "stkaiti",
75
- stfangsong: "stfangsong",
76
- };
77
-
78
- const FONT_SUBSTITUTIONS = {
79
- timesnewroman: ["timesnewroman", "liberationserif", "caladea", "dejavuserif", "notoserif", "nimbusroman"],
80
- times: ["timesnewroman", "liberationserif", "caladea", "dejavuserif", "nimbusroman"],
81
- georgia: ["georgia", "liberationserif", "caladea", "dejavuserif"],
82
- cambria: ["cambria", "caladea", "liberationserif", "dejavuserif"],
83
- arial: ["arial", "liberationsans", "carlito", "dejavusans", "notosans", "nimbussans"],
84
- helvetica: ["helvetica", "arial", "liberationsans", "carlito", "dejavusans", "nimbussans"],
85
- calibri: ["calibri", "carlito", "liberationsans", "dejavusans"],
86
- verdana: ["verdana", "dejavusans", "liberationsans", "carlito"],
87
- tahoma: ["tahoma", "dejavusans", "liberationsans"],
88
- trebuchetms: ["trebuchetms", "liberationsans", "carlito", "dejavusans"],
89
- segoeui: ["segoeui", "liberationsans", "carlito", "dejavusans"],
90
- courier: ["couriernew", "liberationmono", "dejavusansmono", "notosansmono", "nimbusmono"],
91
- couriernew: ["couriernew", "liberationmono", "dejavusansmono", "notosansmono", "nimbusmono"],
92
- consolas: ["consolas", "liberationmono", "dejavusansmono", "notosansmono"],
93
- monaco: ["monaco", "liberationmono", "dejavusansmono"],
94
- menlo: ["menlo", "liberationmono", "dejavusansmono"],
95
- 宋体: ["simsun", "宋体", "stsong", "songtisc", "notoserifcjksc", "notoserifsc", "sourcehanserifsc", "wqyzenhei"],
96
- simsun: ["simsun", "宋体", "stsong", "songtisc", "notoserifcjksc", "notoserifsc", "sourcehanserifsc"],
97
- 新宋体: ["nsimsun", "simsun", "宋体", "songtisc", "notoserifcjksc", "notoserifsc"],
98
- nsimsun: ["nsimsun", "simsun", "宋体", "songtisc", "notoserifcjksc", "notoserifsc"],
99
- 仿宋: ["fangsong", "仿宋", "stfangsong", "notoserifcjksc", "notoserifsc"],
100
- fangsong: ["fangsong", "仿宋", "stfangsong", "notoserifcjksc", "notoserifsc"],
101
- 黑体: ["simhei", "黑体", "stheiti", "heitisc", "notosanscjksc", "notosanssc", "sourcehansanssc", "wqyzenhei"],
102
- simhei: ["simhei", "黑体", "stheiti", "heitisc", "notosanscjksc", "notosanssc", "sourcehansanssc", "wqyzenhei"],
103
- 微软雅黑: ["microsoftyahei", "微软雅黑", "pingfangsc", "notosanscjksc", "notosanssc", "sourcehansanssc", "wqyzenhei"],
104
- microsoftyahei: ["microsoftyahei", "微软雅黑", "pingfangsc", "notosanscjksc", "notosanssc", "sourcehansanssc", "wqyzenhei"],
105
- 等线: ["dengxian", "等线", "pingfangsc", "notosanscjksc", "notosanssc", "sourcehansanssc"],
106
- dengxian: ["dengxian", "等线", "pingfangsc", "notosanscjksc", "notosanssc", "sourcehansanssc"],
107
- 苹方: ["pingfangsc", "苹方", "notosanscjksc", "notosanssc", "microsoftyahei"],
108
- pingfangsc: ["pingfangsc", "苹方", "notosanscjksc", "notosanssc", "microsoftyahei"],
109
- 楷体: ["kaiti", "楷体", "stkaiti", "kaitisc", "notoserifcjksc"],
110
- kaiti: ["kaiti", "楷体", "stkaiti", "kaitisc", "notoserifcjksc"],
111
- notosanssc: ["notosanssc", "notosanscjksc", "sourcehansanssc", "microsoftyahei", "pingfangsc"],
112
- notoserifsc: ["notoserifsc", "notoserifcjksc", "sourcehanserifsc", "simsun", "songtisc"],
113
- };
114
-
115
- const LATIN_BASELINE_FAMILIES = [
116
- "liberationserif",
117
- "liberationsans",
118
- "liberationmono",
119
- "carlito",
120
- "caladea",
121
- "dejavuserif",
122
- "dejavusans",
123
- "dejavusansmono",
124
- "timesnewroman",
125
- "arial",
126
- "couriernew",
127
- ];
128
-
129
- const CJK_BASELINE_FAMILIES = [
130
- "simsun",
131
- "microsoftyahei",
132
- "pingfangsc",
133
- "songtisc",
134
- "notoserifcjksc",
135
- "notosanscjksc",
136
- "notoserifsc",
137
- "notosanssc",
138
- "wqyzenhei",
139
- ];
140
-
141
- function normalizeFontKey(name) {
142
- return String(name || "")
143
- .trim()
144
- .toLowerCase()
145
- .replace(/[\s\-_'".,]+/g, "");
146
- }
147
-
148
- function decodeXmlEntities(text) {
149
- return text
150
- .replace(/&/g, "&")
151
- .replace(/&lt;/g, "<")
152
- .replace(/&gt;/g, ">")
153
- .replace(/&quot;/g, '"')
154
- .replace(/&apos;/g, "'");
155
- }
156
-
157
- function isBodyOfficeXml(fileName, extension) {
158
- const lower = fileName.toLowerCase();
159
- if (!lower.endsWith(".xml")) return false;
160
- if (extension === "docx") {
161
- return (
162
- lower === "word/document.xml" ||
163
- lower.startsWith("word/header") ||
164
- lower.startsWith("word/footer") ||
165
- lower === "word/footnotes.xml" ||
166
- lower === "word/endnotes.xml"
167
- );
168
- }
169
- if (extension === "pptx") {
170
- return lower.startsWith("ppt/slides/slide");
171
- }
172
- if (extension === "xlsx") {
173
- return lower === "xl/sharedstrings.xml" || lower.startsWith("xl/worksheets/sheet");
174
- }
175
- return false;
176
- }
177
-
178
- function isStyleOrThemeOfficeXml(fileName, extension) {
179
- const lower = fileName.toLowerCase();
180
- if (!lower.endsWith(".xml")) return false;
181
- if (extension === "docx") {
182
- return lower === "word/styles.xml" || lower.startsWith("word/theme/");
183
- }
184
- if (extension === "pptx") {
185
- return (
186
- lower === "ppt/presentation.xml" ||
187
- lower.startsWith("ppt/slidelayouts/") ||
188
- lower.startsWith("ppt/slidemasters/") ||
189
- lower.startsWith("ppt/theme/")
190
- );
191
- }
192
- if (extension === "xlsx") {
193
- return lower === "xl/styles.xml" || lower.startsWith("xl/theme/");
194
- }
195
- return false;
196
- }
197
-
198
- const CJK_CHAR_RE = /[\u3001-\u303F\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF\u{20000}-\u{2EBFF}]/u;
199
- const KANA_CHAR_RE = /[\u3040-\u309F\u30A0-\u30FF\u31F0-\u31FF\uFF65-\uFF9F]/;
200
- const HANGUL_CHAR_RE = /[\u1100-\u11FF\u3130-\u318F\uAC00-\uD7AF]/;
201
-
202
- function detectTextScripts(xml, scripts) {
203
- for (const match of xml.matchAll(/>([^<]+)</g)) {
204
- const text = match[1];
205
- if (!scripts.hasCjk && CJK_CHAR_RE.test(text)) scripts.hasCjk = true;
206
- if (!scripts.hasKana && KANA_CHAR_RE.test(text)) scripts.hasKana = true;
207
- if (!scripts.hasHangul && HANGUL_CHAR_RE.test(text)) scripts.hasHangul = true;
208
- if (scripts.hasCjk && scripts.hasKana && scripts.hasHangul) break;
209
- }
210
- }
211
-
212
- function collectReferencedStyleIds(xml, styleIds) {
213
- for (const match of xml.matchAll(/<w:(?:pStyle|rStyle|tblStyle)\b[^>]*\bw:val\s*=\s*(["'])(.*?)\1/g)) {
214
- const id = decodeXmlEntities(match[2]).trim();
215
- if (id) styleIds.add(id);
216
- }
217
- }
218
-
219
- function addFontName(out, raw) {
220
- const name = decodeXmlEntities(raw).trim();
221
- if (name && !name.startsWith("+")) out.add(name);
222
- }
223
-
224
- function extractFontsFromXmlFragment(xml, out, { includeEastAsia = true } = {}) {
225
- const attrPattern = includeEastAsia
226
- ? /\bw:(?:ascii|eastAsia|hAnsi|cs)="([^"]+)"/g
227
- : /\bw:(?:ascii|hAnsi|cs)="([^"]+)"/g;
228
- for (const tag of xml.matchAll(/<w:rFonts\b[^>]*>/g)) {
229
- for (const match of tag[0].matchAll(attrPattern)) {
230
- addFontName(out, match[1]);
231
- }
232
- }
233
- for (const match of xml.matchAll(/<a:latin\b[^>]*\btypeface="([^"]+)"/g)) {
234
- addFontName(out, match[1]);
235
- }
236
- for (const match of xml.matchAll(/<a:cs\b[^>]*\btypeface="([^"]+)"/g)) {
237
- addFontName(out, match[1]);
238
- }
239
- if (includeEastAsia) {
240
- for (const match of xml.matchAll(/<a:ea\b[^>]*\btypeface="([^"]+)"/g)) {
241
- addFontName(out, match[1]);
242
- }
243
- }
244
- for (const match of xml.matchAll(/<name\b[^>]*\bval="([^"]+)"/g)) {
245
- addFontName(out, match[1]);
246
- }
247
- }
248
-
249
- function extractFontsFromThemeXml(xml, out, scripts) {
250
- const includeEastAsia = scripts.hasCjk || scripts.hasKana || scripts.hasHangul;
251
- extractFontsFromXmlFragment(xml, out, { includeEastAsia });
252
- for (const tag of xml.matchAll(/<a:font\b[^>]*>/g)) {
253
- const scriptMatch = tag[0].match(/\bscript="([^"]+)"/);
254
- const typefaceMatch = tag[0].match(/\btypeface="([^"]+)"/);
255
- if (!scriptMatch || !typefaceMatch) continue;
256
- const script = scriptMatch[1];
257
- if ((script === "Hans" || script === "Hant") && scripts.hasCjk) {
258
- addFontName(out, typefaceMatch[1]);
259
- } else if (script === "Jpan" && scripts.hasKana) {
260
- addFontName(out, typefaceMatch[1]);
261
- } else if (script === "Hang" && scripts.hasHangul) {
262
- addFontName(out, typefaceMatch[1]);
263
- }
264
- }
265
- }
266
-
267
- function extractFontsFromStylesXml(xml, out, referencedStyleIds, includeEastAsia) {
268
- for (const match of xml.matchAll(/<w:docDefaults\b[\s\S]*?<\/w:docDefaults>/g)) {
269
- extractFontsFromXmlFragment(match[0], out, { includeEastAsia });
270
- }
271
- const styles = new Map();
272
- const pending = new Set(referencedStyleIds);
273
- for (const match of xml.matchAll(/<w:style\b([^>]*)>([\s\S]*?)<\/w:style>/g)) {
274
- const id = match[1].match(/\bw:styleId\s*=\s*(["'])(.*?)\1/)?.[2];
275
- if (!id) continue;
276
- const styleId = decodeXmlEntities(id).trim();
277
- styles.set(styleId, match[2]);
278
- if (styleId === "Normal" || /\bw:default\s*=\s*(["'])(?:1|on|true)\1/.test(match[1])) pending.add(styleId);
279
- }
280
- for (const styleId of pending) {
281
- const style = styles.get(styleId);
282
- if (!style) continue;
283
- extractFontsFromXmlFragment(style, out, { includeEastAsia });
284
- const parent = style.match(/<w:basedOn\b[^>]*\bw:val\s*=\s*(["'])(.*?)\1/)?.[2];
285
- if (parent) pending.add(decodeXmlEntities(parent).trim());
286
- }
287
- }
288
-
289
- async function extractDocumentFontInfo(content, extension) {
290
- const fonts = new Set();
291
- const scripts = { hasCjk: false, hasKana: false, hasHangul: false };
292
- if (!Buffer.isBuffer(content) && !(content instanceof Uint8Array)) return { fonts, scripts };
293
- const ext = String(extension || "").toLowerCase();
294
- if (!["docx", "pptx", "xlsx"].includes(ext)) return { fonts, scripts };
295
-
296
- const buffer = Buffer.isBuffer(content) ? content : Buffer.from(content);
297
- const archive = await fromBufferPromise(buffer, { lazyEntries: true, validateEntrySizes: true }).catch(() => null);
298
- if (!archive) return { fonts, scripts };
299
-
300
- let totalBytes = 0;
301
- const bodyXmls = [];
302
- const styleXmls = [];
303
- const referencedStyleIds = new Set();
304
- try {
305
- for await (const entry of archive.eachEntry()) {
306
- const fileName = entry.fileName;
307
- const isBody = isBodyOfficeXml(fileName, ext);
308
- const isStyleOrTheme = !isBody && isStyleOrThemeOfficeXml(fileName, ext);
309
- if (!isBody && !isStyleOrTheme) continue;
310
- if (entry.uncompressedSize > MAX_XML_ENTRY_BYTES) continue;
311
- if (totalBytes + entry.uncompressedSize > MAX_XML_TOTAL_BYTES) break;
312
- totalBytes += entry.uncompressedSize;
313
- const stream = await archive.openReadStreamPromise(entry);
314
- const chunks = [];
315
- for await (const chunk of stream) chunks.push(chunk);
316
- const xml = Buffer.concat(chunks).toString("utf8");
317
- if (isBody) {
318
- detectTextScripts(xml, scripts);
319
- if (ext === "docx") collectReferencedStyleIds(xml, referencedStyleIds);
320
- bodyXmls.push(xml);
321
- } else {
322
- styleXmls.push({ fileName: fileName.toLowerCase(), xml });
323
- }
324
- }
325
- } catch {
326
- return { fonts, scripts };
327
- } finally {
328
- archive.close();
329
- }
330
-
331
- const includeEastAsia = scripts.hasCjk || scripts.hasKana || scripts.hasHangul;
332
- for (const xml of bodyXmls) {
333
- extractFontsFromXmlFragment(xml, fonts, { includeEastAsia });
334
- }
335
- for (const { fileName, xml } of styleXmls) {
336
- if (fileName.includes("/theme/")) {
337
- extractFontsFromThemeXml(xml, fonts, scripts);
338
- } else if (fileName === "word/styles.xml") {
339
- extractFontsFromStylesXml(xml, fonts, referencedStyleIds, includeEastAsia);
340
- } else {
341
- extractFontsFromXmlFragment(xml, fonts, { includeEastAsia });
342
- }
343
- }
344
- return { fonts, scripts };
345
- }
346
-
347
- async function extractDocumentFonts(content, extension) {
348
- const { fonts } = await extractDocumentFontInfo(content, extension);
349
- return fonts;
350
- }
351
-
352
- function systemFontDirectories(platform = process.platform, env = process.env) {
353
- const home = env.HOME || env.USERPROFILE || homedir();
354
- if (platform === "linux") {
355
- return [
356
- "/usr/share/fonts",
357
- "/usr/local/share/fonts",
358
- home ? join(home, ".local", "share", "fonts") : "",
359
- home ? join(home, ".fonts") : "",
360
- ].filter(Boolean);
361
- }
362
- if (platform === "darwin") {
363
- return [
364
- "/System/Library/Fonts",
365
- "/Library/Fonts",
366
- home ? join(home, "Library", "Fonts") : "",
367
- ].filter(Boolean);
368
- }
369
- if (platform === "win32") {
370
- return [
371
- win32.join(env.WINDIR || env.SystemRoot || "C:\\Windows", "Fonts"),
372
- env.LOCALAPPDATA ? win32.join(env.LOCALAPPDATA, "Microsoft", "Windows", "Fonts") : "",
373
- ].filter(Boolean);
374
- }
375
- return [];
376
- }
377
-
378
- function systemFontPaths(platform = process.platform, env = process.env) {
379
- const paths = [];
380
- if (platform === "linux") {
381
- const linuxGroups = [
382
- [
383
- ["/usr/share/fonts/truetype/liberation", "/usr/share/fonts/truetype/liberation2", "/usr/share/fonts/liberation-serif", "/usr/share/fonts/liberation", "/usr/local/share/fonts"],
384
- ["LiberationSerif-Regular.ttf", "LiberationSerif-Bold.ttf", "LiberationSerif-Italic.ttf", "LiberationSerif-BoldItalic.ttf"],
385
- ],
386
- [
387
- ["/usr/share/fonts/truetype/liberation", "/usr/share/fonts/truetype/liberation2", "/usr/share/fonts/liberation-sans", "/usr/share/fonts/liberation", "/usr/local/share/fonts"],
388
- ["LiberationSans-Regular.ttf", "LiberationSans-Bold.ttf", "LiberationSans-Italic.ttf", "LiberationSans-BoldItalic.ttf"],
389
- ],
390
- [
391
- ["/usr/share/fonts/truetype/liberation", "/usr/share/fonts/truetype/liberation2", "/usr/share/fonts/liberation-mono", "/usr/share/fonts/liberation", "/usr/local/share/fonts"],
392
- ["LiberationMono-Regular.ttf", "LiberationMono-Bold.ttf", "LiberationMono-Italic.ttf", "LiberationMono-BoldItalic.ttf"],
393
- ],
394
- [
395
- ["/usr/share/fonts/truetype/dejavu", "/usr/share/fonts/dejavu"],
396
- [
397
- "DejaVuSerif.ttf", "DejaVuSerif-Bold.ttf", "DejaVuSerif-Italic.ttf", "DejaVuSerif-BoldItalic.ttf",
398
- "DejaVuSans.ttf", "DejaVuSans-Bold.ttf", "DejaVuSans-Oblique.ttf", "DejaVuSans-BoldOblique.ttf",
399
- "DejaVuSansMono.ttf", "DejaVuSansMono-Bold.ttf", "DejaVuSansMono-Oblique.ttf", "DejaVuSansMono-BoldOblique.ttf",
400
- ],
401
- ],
402
- [
403
- ["/usr/share/fonts/truetype/crosextra", "/usr/share/fonts/google-crosextra-carlito"],
404
- ["Carlito-Regular.ttf", "Carlito-Bold.ttf", "Carlito-Italic.ttf", "Carlito-BoldItalic.ttf"],
405
- ],
406
- [
407
- ["/usr/share/fonts/truetype/crosextra", "/usr/share/fonts/google-crosextra-caladea"],
408
- ["Caladea-Regular.ttf", "Caladea-Bold.ttf", "Caladea-Italic.ttf", "Caladea-BoldItalic.ttf"],
409
- ],
410
- ];
411
- for (const [directories, files] of linuxGroups) {
412
- for (const directory of directories) {
413
- for (const file of files) paths.push(join(directory, file));
414
- }
415
- }
416
- } else if (platform === "darwin") {
417
- const directory = "/System/Library/Fonts/Supplemental";
418
- for (const file of [
419
- "Times New Roman.ttf", "Times New Roman Bold.ttf", "Times New Roman Italic.ttf", "Times New Roman Bold Italic.ttf",
420
- "Arial.ttf", "Arial Bold.ttf", "Arial Italic.ttf", "Arial Bold Italic.ttf",
421
- "Courier New.ttf", "Courier New Bold.ttf", "Courier New Italic.ttf", "Courier New Bold Italic.ttf",
422
- "Georgia.ttf", "Georgia Bold.ttf", "Georgia Italic.ttf", "Georgia Bold Italic.ttf",
423
- "Verdana.ttf", "Verdana Bold.ttf", "Verdana Italic.ttf", "Verdana Bold Italic.ttf",
424
- "Tahoma.ttf", "Tahoma Bold.ttf",
425
- "Trebuchet MS.ttf", "Trebuchet MS Bold.ttf", "Trebuchet MS Italic.ttf", "Trebuchet MS Bold Italic.ttf",
426
- ]) {
427
- paths.push(join(directory, file));
428
- }
429
- } else if (platform === "win32") {
430
- const directory = win32.join(env.WINDIR || env.SystemRoot || "C:\\Windows", "Fonts");
431
- for (const file of [
432
- "times.ttf", "timesbd.ttf", "timesi.ttf", "timesbi.ttf",
433
- "arial.ttf", "arialbd.ttf", "ariali.ttf", "arialbi.ttf",
434
- "cour.ttf", "courbd.ttf", "couri.ttf", "courbi.ttf",
435
- "calibri.ttf", "calibrib.ttf", "calibrii.ttf", "calibriz.ttf", "calibril.ttf", "calibrili.ttf",
436
- "cambria.ttc", "cambriab.ttf", "cambriai.ttf", "cambriaz.ttf",
437
- "georgia.ttf", "georgiab.ttf", "georgiai.ttf", "georgiaz.ttf",
438
- "verdana.ttf", "verdanab.ttf", "verdanai.ttf", "verdanaz.ttf",
439
- "tahoma.ttf", "tahomabd.ttf",
440
- "trebuc.ttf", "trebucbd.ttf", "trebucit.ttf", "trebucbi.ttf",
441
- "consola.ttf", "consolab.ttf", "consolai.ttf", "consolaz.ttf",
442
- ]) {
443
- paths.push(win32.join(directory, file));
444
- }
445
- }
446
- return [...new Set(paths)];
447
- }
448
-
449
- async function discoverViaFcList() {
450
- try {
451
- const { stdout } = await execFileAsync(
452
- "fc-list",
453
- ["--format=%{family}\t%{style}\t%{file}\n"],
454
- { timeout: 2_000, maxBuffer: 8 * 1024 * 1024, encoding: "utf8" },
455
- );
456
- const byPath = new Map();
457
- for (const line of stdout.split(/\r?\n/)) {
458
- if (!line) continue;
459
- const [rawFamilies, rawStyles, filePath] = line.split("\t");
460
- if (!filePath || !FONT_EXTENSIONS.has(extname(filePath).toLowerCase())) continue;
461
- const existing = byPath.get(filePath) || { path: filePath, families: new Set(), styles: new Set() };
462
- for (const fam of (rawFamilies || "").split(",")) {
463
- const key = normalizeFontKey(fam);
464
- if (key) existing.families.add(key);
465
- }
466
- for (const sty of (rawStyles || "").split(",")) {
467
- const s = sty.trim().toLowerCase();
468
- if (s) existing.styles.add(s);
469
- }
470
- byPath.set(filePath, existing);
471
- }
472
- return [...byPath.values()].map((entry) => ({
473
- path: entry.path,
474
- families: [...entry.families],
475
- styles: [...entry.styles],
476
- }));
477
- } catch {
478
- return null;
479
- }
480
- }
481
-
482
- async function readSlice(handle, offset, length) {
483
- if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length <= 0 || length > MAX_NAME_TABLE_BYTES) {
484
- return null;
485
- }
486
- const buf = Buffer.allocUnsafe(length);
487
- let total = 0;
488
- while (total < length) {
489
- const { bytesRead } = await handle.read(buf, total, length - total, offset + total);
490
- if (bytesRead <= 0) break;
491
- total += bytesRead;
492
- }
493
- return total === length ? buf : null;
494
- }
495
-
496
- function isValidSfntHeader(buf, offset = 0) {
497
- if (!buf || buf.length < offset + 12) return false;
498
- const ver = buf.readUInt32BE(offset);
499
- const tag = buf.toString("ascii", offset, offset + 4);
500
- return ver === 0x00010000 || tag === "OTTO" || tag === "true" || tag === "typ1";
501
- }
502
-
503
- function decodeNameString(rawSlice, platformID, encodingID) {
504
- if (!rawSlice || rawSlice.length === 0) return "";
505
- if (platformID === 0 || (platformID === 3 && (encodingID === 0 || encodingID === 1 || encodingID === 10))) {
506
- const evenLen = rawSlice.length & ~1;
507
- if (evenLen === 0) return "";
508
- const copy = Buffer.from(rawSlice.subarray(0, evenLen));
509
- copy.swap16();
510
- return copy.toString("utf16le").replace(/\0/g, "").trim();
511
- }
512
- if (platformID === 1 && encodingID === 0) {
513
- return rawSlice.toString("latin1").replace(/\0/g, "").trim();
514
- }
515
- return "";
516
- }
517
-
518
- async function readFontNameTableMetadata(filePath) {
519
- let handle;
520
- try {
521
- handle = await open(filePath, "r");
522
- } catch {
523
- return null;
524
- }
525
- try {
526
- const header = await readSlice(handle, 0, 12);
527
- if (!header) return null;
528
-
529
- const tag = header.toString("ascii", 0, 4);
530
- let sfntOffsets = [];
531
- if (tag === "ttcf") {
532
- const numFonts = header.readUInt32BE(8);
533
- const count = Math.min(numFonts, 32);
534
- if (count === 0) return null;
535
- const offsetBuf = await readSlice(handle, 12, count * 4);
536
- if (!offsetBuf) return null;
537
- for (let i = 0; i < count; i++) {
538
- sfntOffsets.push(offsetBuf.readUInt32BE(i * 4));
539
- }
540
- } else if (isValidSfntHeader(header, 0)) {
541
- sfntOffsets = [0];
542
- } else {
543
- return null;
544
- }
545
-
546
- const families = new Set();
547
- const styles = new Set();
548
-
549
- for (const sfntOffset of sfntOffsets) {
550
- const sfntHeader = sfntOffset === 0 ? header : await readSlice(handle, sfntOffset, 12);
551
- if (!isValidSfntHeader(sfntHeader, 0)) continue;
552
- const numTables = Math.min(sfntHeader.readUInt16BE(4), 128);
553
- if (numTables === 0) continue;
554
- const tableRecords = await readSlice(handle, sfntOffset + 12, numTables * 16);
555
- if (!tableRecords) continue;
556
-
557
- let nameOffset = 0;
558
- let nameLength = 0;
559
- for (let i = 0; i < numTables; i++) {
560
- const recStart = i * 16;
561
- if (tableRecords.toString("ascii", recStart, recStart + 4) === "name") {
562
- nameOffset = tableRecords.readUInt32BE(recStart + 8);
563
- nameLength = tableRecords.readUInt32BE(recStart + 12);
564
- break;
565
- }
566
- }
567
- if (!nameOffset || nameLength < 6 || nameLength > MAX_NAME_TABLE_BYTES) continue;
568
-
569
- const nameBuf = await readSlice(handle, nameOffset, nameLength);
570
- if (!nameBuf) continue;
571
- const count = nameBuf.readUInt16BE(2);
572
- const stringOffset = nameBuf.readUInt16BE(4);
573
- const maxRecords = Math.min(count, Math.floor((nameBuf.length - 6) / 12));
574
-
575
- for (let i = 0; i < maxRecords; i++) {
576
- const recStart = 6 + i * 12;
577
- const platformID = nameBuf.readUInt16BE(recStart);
578
- const encodingID = nameBuf.readUInt16BE(recStart + 2);
579
- const nameID = nameBuf.readUInt16BE(recStart + 6);
580
- if (nameID !== 1 && nameID !== 2 && nameID !== 16 && nameID !== 17) continue;
581
-
582
- const strLen = nameBuf.readUInt16BE(recStart + 8);
583
- const strOff = nameBuf.readUInt16BE(recStart + 10);
584
- const start = stringOffset + strOff;
585
- const end = start + strLen;
586
- if (strLen === 0 || end > nameBuf.length) continue;
587
-
588
- const text = decodeNameString(nameBuf.subarray(start, end), platformID, encodingID);
589
- if (!text) continue;
590
- if (nameID === 1 || nameID === 16) {
591
- const key = normalizeFontKey(text);
592
- if (key) families.add(key);
593
- } else {
594
- styles.add(text.toLowerCase());
595
- }
596
- }
597
- }
598
-
599
- if (families.size === 0) return null;
600
- if (styles.size === 0) styles.add("regular");
601
- return {
602
- path: filePath,
603
- families: [...families],
604
- styles: [...styles],
605
- };
606
- } catch {
607
- return null;
608
- } finally {
609
- await handle.close().catch(() => {});
610
- }
611
- }
612
-
613
- async function inspectFontEntry(filePath) {
614
- const parsed = await readFontNameTableMetadata(filePath);
615
- if (!parsed) return inferFontEntryFromPath(filePath);
616
- const stem = basename(filePath, extname(filePath)).toLowerCase();
617
- const alias = FILENAME_FAMILY_ALIASES[stem];
618
- const families = alias && !parsed.families.includes(alias)
619
- ? [...parsed.families, alias]
620
- : parsed.families;
621
- return {
622
- path: filePath,
623
- families,
624
- styles: parsed.styles,
625
- };
626
- }
627
-
628
- async function walkFontDirectories(directories, maxDepth = 6) {
629
- const fontFiles = [];
630
- const seenDirs = new Set();
631
- const seenFiles = new Set();
632
-
633
- async function walk(dir, depth) {
634
- if (depth > maxDepth || seenDirs.has(dir)) return;
635
- seenDirs.add(dir);
636
- let entries;
637
- try {
638
- entries = await readdir(dir, { withFileTypes: true });
639
- } catch {
640
- return;
641
- }
642
- for (const entry of entries) {
643
- const fullPath = join(dir, entry.name);
644
- if (entry.isDirectory()) {
645
- await walk(fullPath, depth + 1);
646
- } else if (entry.isFile() || entry.isSymbolicLink()) {
647
- if (!FONT_EXTENSIONS.has(extname(entry.name).toLowerCase())) continue;
648
- if (seenFiles.has(fullPath)) continue;
649
- seenFiles.add(fullPath);
650
- fontFiles.push(fullPath);
651
- }
652
- }
653
- }
654
-
655
- for (const directory of directories) {
656
- await walk(directory, 0);
657
- }
658
-
659
- const results = new Array(fontFiles.length);
660
- const concurrency = 16;
661
- let nextIndex = 0;
662
- async function worker() {
663
- while (nextIndex < fontFiles.length) {
664
- const index = nextIndex++;
665
- results[index] = await inspectFontEntry(fontFiles[index]);
666
- }
667
- }
668
- await Promise.all(Array.from({ length: Math.min(concurrency, fontFiles.length) }, () => worker()));
669
- return results;
670
- }
671
-
672
- function inferFontEntryFromPath(filePath) {
673
- const stem = basename(filePath, extname(filePath));
674
- const lowerStem = stem.toLowerCase();
675
- const families = new Set();
676
-
677
- const alias = FILENAME_FAMILY_ALIASES[lowerStem];
678
- if (alias) families.add(alias);
679
-
680
- const stripped = stem.replace(/(?:[-_\s]+(?:Regular|Bold|Italic|Oblique|BoldItalic|Bold Italic|BoldOblique|Light|Thin|Medium|SemiBold|ExtraLight|Black))+$/i, "");
681
- const normStripped = normalizeFontKey(stripped);
682
- if (normStripped) families.add(normStripped);
683
-
684
- const normFull = normalizeFontKey(stem);
685
- if (normFull) families.add(normFull);
686
-
687
- const styles = new Set();
688
- if (/bold\s*italic|bold\s*oblique|bi$|z$/i.test(lowerStem)) styles.add("bold italic");
689
- else if (/bold|bd$/i.test(lowerStem)) styles.add("bold");
690
- else if (/italic|oblique|i$|it$/i.test(lowerStem)) styles.add("italic");
691
- else if (/thin|extralight|light|medium|semibold|black|heavy/i.test(lowerStem)) styles.add("other");
692
- else styles.add("regular");
693
-
694
- return {
695
- path: filePath,
696
- families: [...families],
697
- styles: [...styles],
698
- };
699
- }
700
-
701
- async function discoverSystemFonts({ platform = process.platform, env = process.env, useFcList = true } = {}) {
702
- if (platform === "linux" && useFcList) {
703
- const fcEntries = await discoverViaFcList();
704
- if (fcEntries && fcEntries.length > 0) return fcEntries;
705
- }
706
- return walkFontDirectories(systemFontDirectories(platform, env));
707
- }
708
-
709
- const CORE_STYLE_SET = new Set(["regular", "bold", "italic", "bolditalic"]);
710
-
711
- function coreStyles(styles) {
712
- const normalized = (styles?.length ? styles : ["regular"]).map((style) => style
713
- .toLowerCase().replace(/[\s_-]+/g, "").replace("oblique", "italic")
714
- .replace(/^(?:roman|book|normal)$/, "regular").replace(/^italicbold$/, "bolditalic"));
715
- return normalized.filter((style) => CORE_STYLE_SET.has(style));
716
- }
717
-
718
- const CJK_FAMILY_SET = new Set([
719
- ...CJK_BASELINE_FAMILIES,
720
- "宋体", "新宋体", "仿宋", "黑体", "微软雅黑", "等线", "苹方", "楷体",
721
- "nsimsun", "fangsong", "kaiti", "dengxian", "stsong", "stheiti", "stkaiti", "stfangsong",
722
- "heitisc", "kaitisc", "sourcehansanssc", "sourcehanserifsc",
723
- ]);
724
-
725
- function isCjkFontEntry(entry) {
726
- const families = entry.families || [];
727
- if (families.some((f) => CJK_FAMILY_SET.has(f) || /cjk/.test(f))) return true;
728
- return /noto(?:sans|serif)cjk|simsun|simhei|msyh|pingfang|songti|wqy/i.test(entry.path || "");
729
- }
730
-
731
- function selectSystemFonts(discovered, requestedFonts = [], scripts) {
732
- const hasEastAsian = scripts ? Boolean(scripts.hasCjk || scripts.hasKana || scripts.hasHangul) : true;
733
- const families = new Map();
734
- for (const entry of discovered) {
735
- if (!entry?.path || (!hasEastAsian && isCjkFontEntry(entry))) continue;
736
- const styles = coreStyles(entry.styles);
737
- for (const key of entry.families || []) {
738
- if (!families.has(key)) families.set(key, { styles: new Set(), core: new Set(), other: new Set() });
739
- const family = families.get(key);
740
- for (const style of styles) family.styles.add(style);
741
- (styles.length ? family.core : family.other).add(entry.path);
742
- }
743
- }
744
-
745
- const requested = new Set(requestedFonts.map(normalizeFontKey).filter(Boolean));
746
- const selected = new Set();
747
- const selectedEastAsian = new Set();
748
- const extra = new Set();
749
- for (const key of requested) {
750
- if (key === "notosanssc") continue;
751
- const original = families.get(key);
752
- const eastAsian = isCjkFontEntry({ families: [key] });
753
- let chosen = original;
754
- for (const substitute of FONT_SUBSTITUTIONS[key] ?? []) {
755
- if (substitute === "notosanssc") continue;
756
- const candidate = families.get(substitute);
757
- if (!candidate?.core.size) continue;
758
- if (!chosen?.core.size) {
759
- chosen = candidate;
760
- } else if (!eastAsian && candidate.styles.has("regular") &&
761
- candidate.styles.size > chosen.styles.size &&
762
- [...chosen.styles].every((style) => candidate.styles.has(style))) {
763
- chosen = candidate;
764
- }
765
- if (eastAsian || chosen.styles.size === 4) break;
766
- }
767
- if (chosen) {
768
- const target = eastAsian ? selectedEastAsian : selected;
769
- for (const path of chosen.core) target.add(path);
770
- if (chosen === original) for (const path of chosen.other) extra.add(path);
771
- }
772
- }
773
-
774
- if (selected.size === 0) {
775
- for (const family of LATIN_BASELINE_FAMILIES) {
776
- for (const path of families.get(family)?.core ?? []) selected.add(path);
777
- }
778
- }
779
- return [...new Set([...selected, ...selectedEastAsian, ...extra])];
780
- }
781
-
782
- async function readSelectedFonts(paths, {
783
- maxFileBytes = DEFAULT_MAX_FILE_BYTES,
784
- maxTotalBytes = DEFAULT_MAX_TOTAL_BYTES,
785
- maxFiles = DEFAULT_MAX_FILES,
786
- } = {}) {
787
- const buffers = [];
788
- let totalBytes = 0;
789
-
790
- for (const filePath of paths) {
791
- if (buffers.length >= maxFiles || totalBytes >= maxTotalBytes) break;
792
- try {
793
- const info = await stat(filePath);
794
- if (!info.isFile() || info.size <= 0 || info.size > maxFileBytes) continue;
795
- if (totalBytes + info.size > maxTotalBytes) continue;
796
- const buf = await readFile(filePath);
797
- totalBytes += buf.byteLength;
798
- buffers.push(buf);
799
- } catch {
800
- // Ignore unreadable or vanished font files
801
- }
802
- }
803
- return buffers;
804
- }
805
-
806
- async function loadFontsForDocument(content, extension, options = {}) {
807
- const [{ fonts: requestedFonts, scripts }, discovered] = await Promise.all([
808
- extractDocumentFontInfo(content, extension),
809
- discoverSystemFonts(options),
810
- ]);
811
- const selectedPaths = selectSystemFonts(discovered, [...requestedFonts], scripts);
812
- return readSelectedFonts(selectedPaths, options);
813
- }
814
-
815
- module.exports = {
816
- extractDocumentFontInfo,
817
- extractDocumentFonts,
818
- loadFontsForDocument,
819
- readFontNameTableMetadata,
820
- readSelectedFonts,
821
- selectSystemFonts,
822
- systemFontDirectories,
823
- systemFontPaths,
824
- };
1
+ const { execFile } = require("node:child_process");
2
+ const { open, readdir, readFile, stat } = require("node:fs/promises");
3
+ const { homedir } = require("node:os");
4
+ const { basename, extname, join, win32 } = require("node:path");
5
+ const { promisify } = require("node:util");
6
+ const { fromBufferPromise } = require("yauzl");
7
+
8
+ const execFileAsync = promisify(execFile);
9
+
10
+ const FONT_EXTENSIONS = new Set([".ttf", ".otf", ".ttc", ".otc"]);
11
+ const MAX_XML_ENTRY_BYTES = 8 * 1024 * 1024;
12
+ const MAX_XML_TOTAL_BYTES = 32 * 1024 * 1024;
13
+ const MAX_NAME_TABLE_BYTES = 1024 * 1024;
14
+ const DEFAULT_MAX_FILE_BYTES = 48 * 1024 * 1024;
15
+ const DEFAULT_MAX_TOTAL_BYTES = 64 * 1024 * 1024;
16
+ const DEFAULT_MAX_FILES = 48;
17
+
18
+ const FILENAME_FAMILY_ALIASES = {
19
+ times: "timesnewroman",
20
+ timesbd: "timesnewroman",
21
+ timesi: "timesnewroman",
22
+ timesbi: "timesnewroman",
23
+ arial: "arial",
24
+ arialbd: "arial",
25
+ ariali: "arial",
26
+ arialbi: "arial",
27
+ cour: "couriernew",
28
+ courbd: "couriernew",
29
+ couri: "couriernew",
30
+ courbi: "couriernew",
31
+ calibri: "calibri",
32
+ calibrib: "calibri",
33
+ calibrii: "calibri",
34
+ calibriz: "calibri",
35
+ calibril: "calibri",
36
+ calibrili: "calibri",
37
+ cambria: "cambria",
38
+ cambriab: "cambria",
39
+ cambriai: "cambria",
40
+ cambriaz: "cambria",
41
+ georgia: "georgia",
42
+ georgiab: "georgia",
43
+ georgiai: "georgia",
44
+ georgiaz: "georgia",
45
+ verdana: "verdana",
46
+ verdanab: "verdana",
47
+ verdanai: "verdana",
48
+ verdanaz: "verdana",
49
+ tahoma: "tahoma",
50
+ tahomabd: "tahoma",
51
+ trebuc: "trebuchetms",
52
+ trebucbd: "trebuchetms",
53
+ trebucit: "trebuchetms",
54
+ trebucbi: "trebuchetms",
55
+ consola: "consolas",
56
+ consolab: "consolas",
57
+ consolai: "consolas",
58
+ consolaz: "consolas",
59
+ simsun: "simsun",
60
+ simsunb: "simsun",
61
+ simhei: "simhei",
62
+ msyh: "microsoftyahei",
63
+ msyhbd: "microsoftyahei",
64
+ msyhl: "microsoftyahei",
65
+ simkai: "kaiti",
66
+ simfang: "fangsong",
67
+ deng: "dengxian",
68
+ dengb: "dengxian",
69
+ dengl: "dengxian",
70
+ pingfang: "pingfangsc",
71
+ songti: "songtisc",
72
+ stsong: "stsong",
73
+ stheiti: "stheiti",
74
+ stkaiti: "stkaiti",
75
+ stfangsong: "stfangsong",
76
+ };
77
+
78
+ const FONT_SUBSTITUTIONS = {
79
+ timesnewroman: ["timesnewroman", "liberationserif", "caladea", "dejavuserif", "notoserif", "nimbusroman"],
80
+ times: ["timesnewroman", "liberationserif", "caladea", "dejavuserif", "nimbusroman"],
81
+ georgia: ["georgia", "liberationserif", "caladea", "dejavuserif"],
82
+ cambria: ["cambria", "caladea", "liberationserif", "dejavuserif"],
83
+ arial: ["arial", "liberationsans", "carlito", "dejavusans", "notosans", "nimbussans"],
84
+ helvetica: ["helvetica", "arial", "liberationsans", "carlito", "dejavusans", "nimbussans"],
85
+ calibri: ["calibri", "carlito", "liberationsans", "dejavusans"],
86
+ verdana: ["verdana", "dejavusans", "liberationsans", "carlito"],
87
+ tahoma: ["tahoma", "dejavusans", "liberationsans"],
88
+ trebuchetms: ["trebuchetms", "liberationsans", "carlito", "dejavusans"],
89
+ segoeui: ["segoeui", "liberationsans", "carlito", "dejavusans"],
90
+ courier: ["couriernew", "liberationmono", "dejavusansmono", "notosansmono", "nimbusmono"],
91
+ couriernew: ["couriernew", "liberationmono", "dejavusansmono", "notosansmono", "nimbusmono"],
92
+ consolas: ["consolas", "liberationmono", "dejavusansmono", "notosansmono"],
93
+ monaco: ["monaco", "liberationmono", "dejavusansmono"],
94
+ menlo: ["menlo", "liberationmono", "dejavusansmono"],
95
+ 宋体: ["simsun", "宋体", "stsong", "songtisc", "notoserifcjksc", "notoserifsc", "sourcehanserifsc", "wqyzenhei"],
96
+ simsun: ["simsun", "宋体", "stsong", "songtisc", "notoserifcjksc", "notoserifsc", "sourcehanserifsc"],
97
+ 新宋体: ["nsimsun", "simsun", "宋体", "songtisc", "notoserifcjksc", "notoserifsc"],
98
+ nsimsun: ["nsimsun", "simsun", "宋体", "songtisc", "notoserifcjksc", "notoserifsc"],
99
+ 仿宋: ["fangsong", "仿宋", "stfangsong", "notoserifcjksc", "notoserifsc"],
100
+ fangsong: ["fangsong", "仿宋", "stfangsong", "notoserifcjksc", "notoserifsc"],
101
+ 黑体: ["simhei", "黑体", "stheiti", "heitisc", "notosanscjksc", "notosanssc", "sourcehansanssc", "wqyzenhei"],
102
+ simhei: ["simhei", "黑体", "stheiti", "heitisc", "notosanscjksc", "notosanssc", "sourcehansanssc", "wqyzenhei"],
103
+ 微软雅黑: ["microsoftyahei", "微软雅黑", "pingfangsc", "notosanscjksc", "notosanssc", "sourcehansanssc", "wqyzenhei"],
104
+ microsoftyahei: ["microsoftyahei", "微软雅黑", "pingfangsc", "notosanscjksc", "notosanssc", "sourcehansanssc", "wqyzenhei"],
105
+ 等线: ["dengxian", "等线", "pingfangsc", "notosanscjksc", "notosanssc", "sourcehansanssc"],
106
+ dengxian: ["dengxian", "等线", "pingfangsc", "notosanscjksc", "notosanssc", "sourcehansanssc"],
107
+ 苹方: ["pingfangsc", "苹方", "notosanscjksc", "notosanssc", "microsoftyahei"],
108
+ pingfangsc: ["pingfangsc", "苹方", "notosanscjksc", "notosanssc", "microsoftyahei"],
109
+ 楷体: ["kaiti", "楷体", "stkaiti", "kaitisc", "notoserifcjksc"],
110
+ kaiti: ["kaiti", "楷体", "stkaiti", "kaitisc", "notoserifcjksc"],
111
+ notosanssc: ["notosanssc", "notosanscjksc", "sourcehansanssc", "microsoftyahei", "pingfangsc"],
112
+ notoserifsc: ["notoserifsc", "notoserifcjksc", "sourcehanserifsc", "simsun", "songtisc"],
113
+ };
114
+
115
+ const LATIN_BASELINE_FAMILIES = [
116
+ "liberationserif",
117
+ "liberationsans",
118
+ "liberationmono",
119
+ "carlito",
120
+ "caladea",
121
+ "dejavuserif",
122
+ "dejavusans",
123
+ "dejavusansmono",
124
+ "timesnewroman",
125
+ "arial",
126
+ "couriernew",
127
+ ];
128
+
129
+ const CJK_BASELINE_FAMILIES = [
130
+ "simsun",
131
+ "microsoftyahei",
132
+ "pingfangsc",
133
+ "songtisc",
134
+ "notoserifcjksc",
135
+ "notosanscjksc",
136
+ "notoserifsc",
137
+ "notosanssc",
138
+ "wqyzenhei",
139
+ ];
140
+
141
+ function normalizeFontKey(name) {
142
+ return String(name || "")
143
+ .trim()
144
+ .toLowerCase()
145
+ .replace(/[\s\-_'".,]+/g, "");
146
+ }
147
+
148
+ function decodeXmlEntities(text) {
149
+ return text
150
+ .replace(/&amp;/g, "&")
151
+ .replace(/&lt;/g, "<")
152
+ .replace(/&gt;/g, ">")
153
+ .replace(/&quot;/g, '"')
154
+ .replace(/&apos;/g, "'");
155
+ }
156
+
157
+ function isBodyOfficeXml(fileName, extension) {
158
+ const lower = fileName.toLowerCase();
159
+ if (!lower.endsWith(".xml")) return false;
160
+ if (extension === "docx") {
161
+ return (
162
+ lower === "word/document.xml" ||
163
+ lower.startsWith("word/header") ||
164
+ lower.startsWith("word/footer") ||
165
+ lower === "word/footnotes.xml" ||
166
+ lower === "word/endnotes.xml"
167
+ );
168
+ }
169
+ if (extension === "pptx") {
170
+ return lower.startsWith("ppt/slides/slide");
171
+ }
172
+ if (extension === "xlsx") {
173
+ return lower === "xl/sharedstrings.xml" || lower.startsWith("xl/worksheets/sheet");
174
+ }
175
+ return false;
176
+ }
177
+
178
+ function isStyleOrThemeOfficeXml(fileName, extension) {
179
+ const lower = fileName.toLowerCase();
180
+ if (!lower.endsWith(".xml")) return false;
181
+ if (extension === "docx") {
182
+ return lower === "word/styles.xml" || lower.startsWith("word/theme/");
183
+ }
184
+ if (extension === "pptx") {
185
+ return (
186
+ lower === "ppt/presentation.xml" ||
187
+ lower.startsWith("ppt/slidelayouts/") ||
188
+ lower.startsWith("ppt/slidemasters/") ||
189
+ lower.startsWith("ppt/theme/")
190
+ );
191
+ }
192
+ if (extension === "xlsx") {
193
+ return lower === "xl/styles.xml" || lower.startsWith("xl/theme/");
194
+ }
195
+ return false;
196
+ }
197
+
198
+ const CJK_CHAR_RE = /[\u3001-\u303F\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF\u{20000}-\u{2EBFF}]/u;
199
+ const KANA_CHAR_RE = /[\u3040-\u309F\u30A0-\u30FF\u31F0-\u31FF\uFF65-\uFF9F]/;
200
+ const HANGUL_CHAR_RE = /[\u1100-\u11FF\u3130-\u318F\uAC00-\uD7AF]/;
201
+
202
+ function detectTextScripts(xml, scripts) {
203
+ for (const match of xml.matchAll(/>([^<]+)</g)) {
204
+ const text = match[1];
205
+ if (!scripts.hasCjk && CJK_CHAR_RE.test(text)) scripts.hasCjk = true;
206
+ if (!scripts.hasKana && KANA_CHAR_RE.test(text)) scripts.hasKana = true;
207
+ if (!scripts.hasHangul && HANGUL_CHAR_RE.test(text)) scripts.hasHangul = true;
208
+ if (scripts.hasCjk && scripts.hasKana && scripts.hasHangul) break;
209
+ }
210
+ }
211
+
212
+ function collectReferencedStyleIds(xml, styleIds) {
213
+ for (const match of xml.matchAll(/<w:(?:pStyle|rStyle|tblStyle)\b[^>]*\bw:val\s*=\s*(["'])(.*?)\1/g)) {
214
+ const id = decodeXmlEntities(match[2]).trim();
215
+ if (id) styleIds.add(id);
216
+ }
217
+ }
218
+
219
+ function addFontName(out, raw) {
220
+ const name = decodeXmlEntities(raw).trim();
221
+ if (name && !name.startsWith("+")) out.add(name);
222
+ }
223
+
224
+ function extractFontsFromXmlFragment(xml, out, { includeEastAsia = true } = {}) {
225
+ const attrPattern = includeEastAsia
226
+ ? /\bw:(?:ascii|eastAsia|hAnsi|cs)="([^"]+)"/g
227
+ : /\bw:(?:ascii|hAnsi|cs)="([^"]+)"/g;
228
+ for (const tag of xml.matchAll(/<w:rFonts\b[^>]*>/g)) {
229
+ for (const match of tag[0].matchAll(attrPattern)) {
230
+ addFontName(out, match[1]);
231
+ }
232
+ }
233
+ for (const match of xml.matchAll(/<a:latin\b[^>]*\btypeface="([^"]+)"/g)) {
234
+ addFontName(out, match[1]);
235
+ }
236
+ for (const match of xml.matchAll(/<a:cs\b[^>]*\btypeface="([^"]+)"/g)) {
237
+ addFontName(out, match[1]);
238
+ }
239
+ if (includeEastAsia) {
240
+ for (const match of xml.matchAll(/<a:ea\b[^>]*\btypeface="([^"]+)"/g)) {
241
+ addFontName(out, match[1]);
242
+ }
243
+ }
244
+ for (const match of xml.matchAll(/<name\b[^>]*\bval="([^"]+)"/g)) {
245
+ addFontName(out, match[1]);
246
+ }
247
+ }
248
+
249
+ function extractFontsFromThemeXml(xml, out, scripts) {
250
+ const includeEastAsia = scripts.hasCjk || scripts.hasKana || scripts.hasHangul;
251
+ extractFontsFromXmlFragment(xml, out, { includeEastAsia });
252
+ for (const tag of xml.matchAll(/<a:font\b[^>]*>/g)) {
253
+ const scriptMatch = tag[0].match(/\bscript="([^"]+)"/);
254
+ const typefaceMatch = tag[0].match(/\btypeface="([^"]+)"/);
255
+ if (!scriptMatch || !typefaceMatch) continue;
256
+ const script = scriptMatch[1];
257
+ if ((script === "Hans" || script === "Hant") && scripts.hasCjk) {
258
+ addFontName(out, typefaceMatch[1]);
259
+ } else if (script === "Jpan" && scripts.hasKana) {
260
+ addFontName(out, typefaceMatch[1]);
261
+ } else if (script === "Hang" && scripts.hasHangul) {
262
+ addFontName(out, typefaceMatch[1]);
263
+ }
264
+ }
265
+ }
266
+
267
+ function extractFontsFromStylesXml(xml, out, referencedStyleIds, includeEastAsia) {
268
+ for (const match of xml.matchAll(/<w:docDefaults\b[\s\S]*?<\/w:docDefaults>/g)) {
269
+ extractFontsFromXmlFragment(match[0], out, { includeEastAsia });
270
+ }
271
+ const styles = new Map();
272
+ const pending = new Set(referencedStyleIds);
273
+ for (const match of xml.matchAll(/<w:style\b([^>]*)>([\s\S]*?)<\/w:style>/g)) {
274
+ const id = match[1].match(/\bw:styleId\s*=\s*(["'])(.*?)\1/)?.[2];
275
+ if (!id) continue;
276
+ const styleId = decodeXmlEntities(id).trim();
277
+ styles.set(styleId, match[2]);
278
+ if (styleId === "Normal" || /\bw:default\s*=\s*(["'])(?:1|on|true)\1/.test(match[1])) pending.add(styleId);
279
+ }
280
+ for (const styleId of pending) {
281
+ const style = styles.get(styleId);
282
+ if (!style) continue;
283
+ extractFontsFromXmlFragment(style, out, { includeEastAsia });
284
+ const parent = style.match(/<w:basedOn\b[^>]*\bw:val\s*=\s*(["'])(.*?)\1/)?.[2];
285
+ if (parent) pending.add(decodeXmlEntities(parent).trim());
286
+ }
287
+ }
288
+
289
+ async function extractDocumentFontInfo(content, extension) {
290
+ const fonts = new Set();
291
+ const scripts = { hasCjk: false, hasKana: false, hasHangul: false };
292
+ if (!Buffer.isBuffer(content) && !(content instanceof Uint8Array)) return { fonts, scripts };
293
+ const ext = String(extension || "").toLowerCase();
294
+ if (!["docx", "pptx", "xlsx"].includes(ext)) return { fonts, scripts };
295
+
296
+ const buffer = Buffer.isBuffer(content) ? content : Buffer.from(content);
297
+ const archive = await fromBufferPromise(buffer, { lazyEntries: true, validateEntrySizes: true }).catch(() => null);
298
+ if (!archive) return { fonts, scripts };
299
+
300
+ let totalBytes = 0;
301
+ const bodyXmls = [];
302
+ const styleXmls = [];
303
+ const referencedStyleIds = new Set();
304
+ try {
305
+ for await (const entry of archive.eachEntry()) {
306
+ const fileName = entry.fileName;
307
+ const isBody = isBodyOfficeXml(fileName, ext);
308
+ const isStyleOrTheme = !isBody && isStyleOrThemeOfficeXml(fileName, ext);
309
+ if (!isBody && !isStyleOrTheme) continue;
310
+ if (entry.uncompressedSize > MAX_XML_ENTRY_BYTES) continue;
311
+ if (totalBytes + entry.uncompressedSize > MAX_XML_TOTAL_BYTES) break;
312
+ totalBytes += entry.uncompressedSize;
313
+ const stream = await archive.openReadStreamPromise(entry);
314
+ const chunks = [];
315
+ for await (const chunk of stream) chunks.push(chunk);
316
+ const xml = Buffer.concat(chunks).toString("utf8");
317
+ if (isBody) {
318
+ detectTextScripts(xml, scripts);
319
+ if (ext === "docx") collectReferencedStyleIds(xml, referencedStyleIds);
320
+ bodyXmls.push(xml);
321
+ } else {
322
+ styleXmls.push({ fileName: fileName.toLowerCase(), xml });
323
+ }
324
+ }
325
+ } catch {
326
+ return { fonts, scripts };
327
+ } finally {
328
+ archive.close();
329
+ }
330
+
331
+ const includeEastAsia = scripts.hasCjk || scripts.hasKana || scripts.hasHangul;
332
+ for (const xml of bodyXmls) {
333
+ extractFontsFromXmlFragment(xml, fonts, { includeEastAsia });
334
+ }
335
+ for (const { fileName, xml } of styleXmls) {
336
+ if (fileName.includes("/theme/")) {
337
+ extractFontsFromThemeXml(xml, fonts, scripts);
338
+ } else if (fileName === "word/styles.xml") {
339
+ extractFontsFromStylesXml(xml, fonts, referencedStyleIds, includeEastAsia);
340
+ } else {
341
+ extractFontsFromXmlFragment(xml, fonts, { includeEastAsia });
342
+ }
343
+ }
344
+ return { fonts, scripts };
345
+ }
346
+
347
+ async function extractDocumentFonts(content, extension) {
348
+ const { fonts } = await extractDocumentFontInfo(content, extension);
349
+ return fonts;
350
+ }
351
+
352
+ function systemFontDirectories(platform = process.platform, env = process.env) {
353
+ const home = env.HOME || env.USERPROFILE || homedir();
354
+ if (platform === "linux") {
355
+ return [
356
+ "/usr/share/fonts",
357
+ "/usr/local/share/fonts",
358
+ home ? join(home, ".local", "share", "fonts") : "",
359
+ home ? join(home, ".fonts") : "",
360
+ ].filter(Boolean);
361
+ }
362
+ if (platform === "darwin") {
363
+ return [
364
+ "/System/Library/Fonts",
365
+ "/Library/Fonts",
366
+ home ? join(home, "Library", "Fonts") : "",
367
+ ].filter(Boolean);
368
+ }
369
+ if (platform === "win32") {
370
+ return [
371
+ win32.join(env.WINDIR || env.SystemRoot || "C:\\Windows", "Fonts"),
372
+ env.LOCALAPPDATA ? win32.join(env.LOCALAPPDATA, "Microsoft", "Windows", "Fonts") : "",
373
+ ].filter(Boolean);
374
+ }
375
+ return [];
376
+ }
377
+
378
+ function systemFontPaths(platform = process.platform, env = process.env) {
379
+ const paths = [];
380
+ if (platform === "linux") {
381
+ const linuxGroups = [
382
+ [
383
+ ["/usr/share/fonts/truetype/liberation", "/usr/share/fonts/truetype/liberation2", "/usr/share/fonts/liberation-serif", "/usr/share/fonts/liberation", "/usr/local/share/fonts"],
384
+ ["LiberationSerif-Regular.ttf", "LiberationSerif-Bold.ttf", "LiberationSerif-Italic.ttf", "LiberationSerif-BoldItalic.ttf"],
385
+ ],
386
+ [
387
+ ["/usr/share/fonts/truetype/liberation", "/usr/share/fonts/truetype/liberation2", "/usr/share/fonts/liberation-sans", "/usr/share/fonts/liberation", "/usr/local/share/fonts"],
388
+ ["LiberationSans-Regular.ttf", "LiberationSans-Bold.ttf", "LiberationSans-Italic.ttf", "LiberationSans-BoldItalic.ttf"],
389
+ ],
390
+ [
391
+ ["/usr/share/fonts/truetype/liberation", "/usr/share/fonts/truetype/liberation2", "/usr/share/fonts/liberation-mono", "/usr/share/fonts/liberation", "/usr/local/share/fonts"],
392
+ ["LiberationMono-Regular.ttf", "LiberationMono-Bold.ttf", "LiberationMono-Italic.ttf", "LiberationMono-BoldItalic.ttf"],
393
+ ],
394
+ [
395
+ ["/usr/share/fonts/truetype/dejavu", "/usr/share/fonts/dejavu"],
396
+ [
397
+ "DejaVuSerif.ttf", "DejaVuSerif-Bold.ttf", "DejaVuSerif-Italic.ttf", "DejaVuSerif-BoldItalic.ttf",
398
+ "DejaVuSans.ttf", "DejaVuSans-Bold.ttf", "DejaVuSans-Oblique.ttf", "DejaVuSans-BoldOblique.ttf",
399
+ "DejaVuSansMono.ttf", "DejaVuSansMono-Bold.ttf", "DejaVuSansMono-Oblique.ttf", "DejaVuSansMono-BoldOblique.ttf",
400
+ ],
401
+ ],
402
+ [
403
+ ["/usr/share/fonts/truetype/crosextra", "/usr/share/fonts/google-crosextra-carlito"],
404
+ ["Carlito-Regular.ttf", "Carlito-Bold.ttf", "Carlito-Italic.ttf", "Carlito-BoldItalic.ttf"],
405
+ ],
406
+ [
407
+ ["/usr/share/fonts/truetype/crosextra", "/usr/share/fonts/google-crosextra-caladea"],
408
+ ["Caladea-Regular.ttf", "Caladea-Bold.ttf", "Caladea-Italic.ttf", "Caladea-BoldItalic.ttf"],
409
+ ],
410
+ ];
411
+ for (const [directories, files] of linuxGroups) {
412
+ for (const directory of directories) {
413
+ for (const file of files) paths.push(join(directory, file));
414
+ }
415
+ }
416
+ } else if (platform === "darwin") {
417
+ const directory = "/System/Library/Fonts/Supplemental";
418
+ for (const file of [
419
+ "Times New Roman.ttf", "Times New Roman Bold.ttf", "Times New Roman Italic.ttf", "Times New Roman Bold Italic.ttf",
420
+ "Arial.ttf", "Arial Bold.ttf", "Arial Italic.ttf", "Arial Bold Italic.ttf",
421
+ "Courier New.ttf", "Courier New Bold.ttf", "Courier New Italic.ttf", "Courier New Bold Italic.ttf",
422
+ "Georgia.ttf", "Georgia Bold.ttf", "Georgia Italic.ttf", "Georgia Bold Italic.ttf",
423
+ "Verdana.ttf", "Verdana Bold.ttf", "Verdana Italic.ttf", "Verdana Bold Italic.ttf",
424
+ "Tahoma.ttf", "Tahoma Bold.ttf",
425
+ "Trebuchet MS.ttf", "Trebuchet MS Bold.ttf", "Trebuchet MS Italic.ttf", "Trebuchet MS Bold Italic.ttf",
426
+ ]) {
427
+ paths.push(join(directory, file));
428
+ }
429
+ } else if (platform === "win32") {
430
+ const directory = win32.join(env.WINDIR || env.SystemRoot || "C:\\Windows", "Fonts");
431
+ for (const file of [
432
+ "times.ttf", "timesbd.ttf", "timesi.ttf", "timesbi.ttf",
433
+ "arial.ttf", "arialbd.ttf", "ariali.ttf", "arialbi.ttf",
434
+ "cour.ttf", "courbd.ttf", "couri.ttf", "courbi.ttf",
435
+ "calibri.ttf", "calibrib.ttf", "calibrii.ttf", "calibriz.ttf", "calibril.ttf", "calibrili.ttf",
436
+ "cambria.ttc", "cambriab.ttf", "cambriai.ttf", "cambriaz.ttf",
437
+ "georgia.ttf", "georgiab.ttf", "georgiai.ttf", "georgiaz.ttf",
438
+ "verdana.ttf", "verdanab.ttf", "verdanai.ttf", "verdanaz.ttf",
439
+ "tahoma.ttf", "tahomabd.ttf",
440
+ "trebuc.ttf", "trebucbd.ttf", "trebucit.ttf", "trebucbi.ttf",
441
+ "consola.ttf", "consolab.ttf", "consolai.ttf", "consolaz.ttf",
442
+ ]) {
443
+ paths.push(win32.join(directory, file));
444
+ }
445
+ }
446
+ return [...new Set(paths)];
447
+ }
448
+
449
+ async function discoverViaFcList() {
450
+ try {
451
+ const { stdout } = await execFileAsync(
452
+ "fc-list",
453
+ ["--format=%{family}\t%{style}\t%{file}\n"],
454
+ { timeout: 2_000, maxBuffer: 8 * 1024 * 1024, encoding: "utf8" },
455
+ );
456
+ const byPath = new Map();
457
+ for (const line of stdout.split(/\r?\n/)) {
458
+ if (!line) continue;
459
+ const [rawFamilies, rawStyles, filePath] = line.split("\t");
460
+ if (!filePath || !FONT_EXTENSIONS.has(extname(filePath).toLowerCase())) continue;
461
+ const existing = byPath.get(filePath) || { path: filePath, families: new Set(), styles: new Set() };
462
+ for (const fam of (rawFamilies || "").split(",")) {
463
+ const key = normalizeFontKey(fam);
464
+ if (key) existing.families.add(key);
465
+ }
466
+ for (const sty of (rawStyles || "").split(",")) {
467
+ const s = sty.trim().toLowerCase();
468
+ if (s) existing.styles.add(s);
469
+ }
470
+ byPath.set(filePath, existing);
471
+ }
472
+ return [...byPath.values()].map((entry) => ({
473
+ path: entry.path,
474
+ families: [...entry.families],
475
+ styles: [...entry.styles],
476
+ }));
477
+ } catch {
478
+ return null;
479
+ }
480
+ }
481
+
482
+ async function readSlice(handle, offset, length) {
483
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length <= 0 || length > MAX_NAME_TABLE_BYTES) {
484
+ return null;
485
+ }
486
+ const buf = Buffer.allocUnsafe(length);
487
+ let total = 0;
488
+ while (total < length) {
489
+ const { bytesRead } = await handle.read(buf, total, length - total, offset + total);
490
+ if (bytesRead <= 0) break;
491
+ total += bytesRead;
492
+ }
493
+ return total === length ? buf : null;
494
+ }
495
+
496
+ function isValidSfntHeader(buf, offset = 0) {
497
+ if (!buf || buf.length < offset + 12) return false;
498
+ const ver = buf.readUInt32BE(offset);
499
+ const tag = buf.toString("ascii", offset, offset + 4);
500
+ return ver === 0x00010000 || tag === "OTTO" || tag === "true" || tag === "typ1";
501
+ }
502
+
503
+ function decodeNameString(rawSlice, platformID, encodingID) {
504
+ if (!rawSlice || rawSlice.length === 0) return "";
505
+ if (platformID === 0 || (platformID === 3 && (encodingID === 0 || encodingID === 1 || encodingID === 10))) {
506
+ const evenLen = rawSlice.length & ~1;
507
+ if (evenLen === 0) return "";
508
+ const copy = Buffer.from(rawSlice.subarray(0, evenLen));
509
+ copy.swap16();
510
+ return copy.toString("utf16le").replace(/\0/g, "").trim();
511
+ }
512
+ if (platformID === 1 && encodingID === 0) {
513
+ return rawSlice.toString("latin1").replace(/\0/g, "").trim();
514
+ }
515
+ return "";
516
+ }
517
+
518
+ async function readFontNameTableMetadata(filePath) {
519
+ let handle;
520
+ try {
521
+ handle = await open(filePath, "r");
522
+ } catch {
523
+ return null;
524
+ }
525
+ try {
526
+ const header = await readSlice(handle, 0, 12);
527
+ if (!header) return null;
528
+
529
+ const tag = header.toString("ascii", 0, 4);
530
+ let sfntOffsets = [];
531
+ if (tag === "ttcf") {
532
+ const numFonts = header.readUInt32BE(8);
533
+ const count = Math.min(numFonts, 32);
534
+ if (count === 0) return null;
535
+ const offsetBuf = await readSlice(handle, 12, count * 4);
536
+ if (!offsetBuf) return null;
537
+ for (let i = 0; i < count; i++) {
538
+ sfntOffsets.push(offsetBuf.readUInt32BE(i * 4));
539
+ }
540
+ } else if (isValidSfntHeader(header, 0)) {
541
+ sfntOffsets = [0];
542
+ } else {
543
+ return null;
544
+ }
545
+
546
+ const families = new Set();
547
+ const styles = new Set();
548
+
549
+ for (const sfntOffset of sfntOffsets) {
550
+ const sfntHeader = sfntOffset === 0 ? header : await readSlice(handle, sfntOffset, 12);
551
+ if (!isValidSfntHeader(sfntHeader, 0)) continue;
552
+ const numTables = Math.min(sfntHeader.readUInt16BE(4), 128);
553
+ if (numTables === 0) continue;
554
+ const tableRecords = await readSlice(handle, sfntOffset + 12, numTables * 16);
555
+ if (!tableRecords) continue;
556
+
557
+ let nameOffset = 0;
558
+ let nameLength = 0;
559
+ for (let i = 0; i < numTables; i++) {
560
+ const recStart = i * 16;
561
+ if (tableRecords.toString("ascii", recStart, recStart + 4) === "name") {
562
+ nameOffset = tableRecords.readUInt32BE(recStart + 8);
563
+ nameLength = tableRecords.readUInt32BE(recStart + 12);
564
+ break;
565
+ }
566
+ }
567
+ if (!nameOffset || nameLength < 6 || nameLength > MAX_NAME_TABLE_BYTES) continue;
568
+
569
+ const nameBuf = await readSlice(handle, nameOffset, nameLength);
570
+ if (!nameBuf) continue;
571
+ const count = nameBuf.readUInt16BE(2);
572
+ const stringOffset = nameBuf.readUInt16BE(4);
573
+ const maxRecords = Math.min(count, Math.floor((nameBuf.length - 6) / 12));
574
+
575
+ for (let i = 0; i < maxRecords; i++) {
576
+ const recStart = 6 + i * 12;
577
+ const platformID = nameBuf.readUInt16BE(recStart);
578
+ const encodingID = nameBuf.readUInt16BE(recStart + 2);
579
+ const nameID = nameBuf.readUInt16BE(recStart + 6);
580
+ if (nameID !== 1 && nameID !== 2 && nameID !== 16 && nameID !== 17) continue;
581
+
582
+ const strLen = nameBuf.readUInt16BE(recStart + 8);
583
+ const strOff = nameBuf.readUInt16BE(recStart + 10);
584
+ const start = stringOffset + strOff;
585
+ const end = start + strLen;
586
+ if (strLen === 0 || end > nameBuf.length) continue;
587
+
588
+ const text = decodeNameString(nameBuf.subarray(start, end), platformID, encodingID);
589
+ if (!text) continue;
590
+ if (nameID === 1 || nameID === 16) {
591
+ const key = normalizeFontKey(text);
592
+ if (key) families.add(key);
593
+ } else {
594
+ styles.add(text.toLowerCase());
595
+ }
596
+ }
597
+ }
598
+
599
+ if (families.size === 0) return null;
600
+ if (styles.size === 0) styles.add("regular");
601
+ return {
602
+ path: filePath,
603
+ families: [...families],
604
+ styles: [...styles],
605
+ };
606
+ } catch {
607
+ return null;
608
+ } finally {
609
+ await handle.close().catch(() => {});
610
+ }
611
+ }
612
+
613
+ async function inspectFontEntry(filePath) {
614
+ const parsed = await readFontNameTableMetadata(filePath);
615
+ if (!parsed) return inferFontEntryFromPath(filePath);
616
+ const stem = basename(filePath, extname(filePath)).toLowerCase();
617
+ const alias = FILENAME_FAMILY_ALIASES[stem];
618
+ const families = alias && !parsed.families.includes(alias)
619
+ ? [...parsed.families, alias]
620
+ : parsed.families;
621
+ return {
622
+ path: filePath,
623
+ families,
624
+ styles: parsed.styles,
625
+ };
626
+ }
627
+
628
+ async function walkFontDirectories(directories, maxDepth = 6) {
629
+ const fontFiles = [];
630
+ const seenDirs = new Set();
631
+ const seenFiles = new Set();
632
+
633
+ async function walk(dir, depth) {
634
+ if (depth > maxDepth || seenDirs.has(dir)) return;
635
+ seenDirs.add(dir);
636
+ let entries;
637
+ try {
638
+ entries = await readdir(dir, { withFileTypes: true });
639
+ } catch {
640
+ return;
641
+ }
642
+ for (const entry of entries) {
643
+ const fullPath = join(dir, entry.name);
644
+ if (entry.isDirectory()) {
645
+ await walk(fullPath, depth + 1);
646
+ } else if (entry.isFile() || entry.isSymbolicLink()) {
647
+ if (!FONT_EXTENSIONS.has(extname(entry.name).toLowerCase())) continue;
648
+ if (seenFiles.has(fullPath)) continue;
649
+ seenFiles.add(fullPath);
650
+ fontFiles.push(fullPath);
651
+ }
652
+ }
653
+ }
654
+
655
+ for (const directory of directories) {
656
+ await walk(directory, 0);
657
+ }
658
+
659
+ const results = new Array(fontFiles.length);
660
+ const concurrency = 16;
661
+ let nextIndex = 0;
662
+ async function worker() {
663
+ while (nextIndex < fontFiles.length) {
664
+ const index = nextIndex++;
665
+ results[index] = await inspectFontEntry(fontFiles[index]);
666
+ }
667
+ }
668
+ await Promise.all(Array.from({ length: Math.min(concurrency, fontFiles.length) }, () => worker()));
669
+ return results;
670
+ }
671
+
672
+ function inferFontEntryFromPath(filePath) {
673
+ const stem = basename(filePath, extname(filePath));
674
+ const lowerStem = stem.toLowerCase();
675
+ const families = new Set();
676
+
677
+ const alias = FILENAME_FAMILY_ALIASES[lowerStem];
678
+ if (alias) families.add(alias);
679
+
680
+ const stripped = stem.replace(/(?:[-_\s]+(?:Regular|Bold|Italic|Oblique|BoldItalic|Bold Italic|BoldOblique|Light|Thin|Medium|SemiBold|ExtraLight|Black))+$/i, "");
681
+ const normStripped = normalizeFontKey(stripped);
682
+ if (normStripped) families.add(normStripped);
683
+
684
+ const normFull = normalizeFontKey(stem);
685
+ if (normFull) families.add(normFull);
686
+
687
+ const styles = new Set();
688
+ if (/bold\s*italic|bold\s*oblique|bi$|z$/i.test(lowerStem)) styles.add("bold italic");
689
+ else if (/bold|bd$/i.test(lowerStem)) styles.add("bold");
690
+ else if (/italic|oblique|i$|it$/i.test(lowerStem)) styles.add("italic");
691
+ else if (/thin|extralight|light|medium|semibold|black|heavy/i.test(lowerStem)) styles.add("other");
692
+ else styles.add("regular");
693
+
694
+ return {
695
+ path: filePath,
696
+ families: [...families],
697
+ styles: [...styles],
698
+ };
699
+ }
700
+
701
+ async function discoverSystemFonts({ platform = process.platform, env = process.env, useFcList = true } = {}) {
702
+ if (platform === "linux" && useFcList) {
703
+ const fcEntries = await discoverViaFcList();
704
+ if (fcEntries && fcEntries.length > 0) return fcEntries;
705
+ }
706
+ return walkFontDirectories(systemFontDirectories(platform, env));
707
+ }
708
+
709
+ const CORE_STYLE_SET = new Set(["regular", "bold", "italic", "bolditalic"]);
710
+
711
+ function coreStyles(styles) {
712
+ const normalized = (styles?.length ? styles : ["regular"]).map((style) => style
713
+ .toLowerCase().replace(/[\s_-]+/g, "").replace("oblique", "italic")
714
+ .replace(/^(?:roman|book|normal)$/, "regular").replace(/^italicbold$/, "bolditalic"));
715
+ return normalized.filter((style) => CORE_STYLE_SET.has(style));
716
+ }
717
+
718
+ const CJK_FAMILY_SET = new Set([
719
+ ...CJK_BASELINE_FAMILIES,
720
+ "宋体", "新宋体", "仿宋", "黑体", "微软雅黑", "等线", "苹方", "楷体",
721
+ "nsimsun", "fangsong", "kaiti", "dengxian", "stsong", "stheiti", "stkaiti", "stfangsong",
722
+ "heitisc", "kaitisc", "sourcehansanssc", "sourcehanserifsc",
723
+ ]);
724
+
725
+ function isCjkFontEntry(entry) {
726
+ const families = entry.families || [];
727
+ if (families.some((f) => CJK_FAMILY_SET.has(f) || /cjk/.test(f))) return true;
728
+ return /noto(?:sans|serif)cjk|simsun|simhei|msyh|pingfang|songti|wqy/i.test(entry.path || "");
729
+ }
730
+
731
+ function selectSystemFonts(discovered, requestedFonts = [], scripts) {
732
+ const hasEastAsian = scripts ? Boolean(scripts.hasCjk || scripts.hasKana || scripts.hasHangul) : true;
733
+ const families = new Map();
734
+ for (const entry of discovered) {
735
+ if (!entry?.path || (!hasEastAsian && isCjkFontEntry(entry))) continue;
736
+ const styles = coreStyles(entry.styles);
737
+ for (const key of entry.families || []) {
738
+ if (!families.has(key)) families.set(key, { styles: new Set(), core: new Set(), other: new Set() });
739
+ const family = families.get(key);
740
+ for (const style of styles) family.styles.add(style);
741
+ (styles.length ? family.core : family.other).add(entry.path);
742
+ }
743
+ }
744
+
745
+ const requested = new Set(requestedFonts.map(normalizeFontKey).filter(Boolean));
746
+ const selected = new Set();
747
+ const selectedEastAsian = new Set();
748
+ const extra = new Set();
749
+ for (const key of requested) {
750
+ if (key === "notosanssc") continue;
751
+ const original = families.get(key);
752
+ const eastAsian = isCjkFontEntry({ families: [key] });
753
+ let chosen = original;
754
+ for (const substitute of FONT_SUBSTITUTIONS[key] ?? []) {
755
+ if (substitute === "notosanssc") continue;
756
+ const candidate = families.get(substitute);
757
+ if (!candidate?.core.size) continue;
758
+ if (!chosen?.core.size) {
759
+ chosen = candidate;
760
+ } else if (!eastAsian && candidate.styles.has("regular") &&
761
+ candidate.styles.size > chosen.styles.size &&
762
+ [...chosen.styles].every((style) => candidate.styles.has(style))) {
763
+ chosen = candidate;
764
+ }
765
+ if (eastAsian || chosen.styles.size === 4) break;
766
+ }
767
+ if (chosen) {
768
+ const target = eastAsian ? selectedEastAsian : selected;
769
+ for (const path of chosen.core) target.add(path);
770
+ if (chosen === original) for (const path of chosen.other) extra.add(path);
771
+ }
772
+ }
773
+
774
+ if (selected.size === 0) {
775
+ for (const family of LATIN_BASELINE_FAMILIES) {
776
+ for (const path of families.get(family)?.core ?? []) selected.add(path);
777
+ }
778
+ }
779
+ return [...new Set([...selected, ...selectedEastAsian, ...extra])];
780
+ }
781
+
782
+ async function readSelectedFonts(paths, {
783
+ maxFileBytes = DEFAULT_MAX_FILE_BYTES,
784
+ maxTotalBytes = DEFAULT_MAX_TOTAL_BYTES,
785
+ maxFiles = DEFAULT_MAX_FILES,
786
+ } = {}) {
787
+ const buffers = [];
788
+ let totalBytes = 0;
789
+
790
+ for (const filePath of paths) {
791
+ if (buffers.length >= maxFiles || totalBytes >= maxTotalBytes) break;
792
+ try {
793
+ const info = await stat(filePath);
794
+ if (!info.isFile() || info.size <= 0 || info.size > maxFileBytes) continue;
795
+ if (totalBytes + info.size > maxTotalBytes) continue;
796
+ const buf = await readFile(filePath);
797
+ totalBytes += buf.byteLength;
798
+ buffers.push(buf);
799
+ } catch {
800
+ // Ignore unreadable or vanished font files
801
+ }
802
+ }
803
+ return buffers;
804
+ }
805
+
806
+ async function loadFontsForDocument(content, extension, options = {}) {
807
+ const [{ fonts: requestedFonts, scripts }, discovered] = await Promise.all([
808
+ extractDocumentFontInfo(content, extension),
809
+ discoverSystemFonts(options),
810
+ ]);
811
+ const selectedPaths = selectSystemFonts(discovered, [...requestedFonts], scripts);
812
+ return readSelectedFonts(selectedPaths, options);
813
+ }
814
+
815
+ module.exports = {
816
+ extractDocumentFontInfo,
817
+ extractDocumentFonts,
818
+ loadFontsForDocument,
819
+ readFontNameTableMetadata,
820
+ readSelectedFonts,
821
+ selectSystemFonts,
822
+ systemFontDirectories,
823
+ systemFontPaths,
824
+ };