@deepseek-ai/libreoffice-kit 0.0.1 → 0.0.2-rc4

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 (90) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +43 -47
  3. package/README.zh.md +35 -50
  4. package/assets/font-subset.json +70 -0
  5. package/assets/font-subset.wasm +0 -0
  6. package/lib/browser/assets.json +10 -0
  7. package/lib/browser/index.js +435 -0
  8. package/lib/browser/types/connection.d.ts +20 -0
  9. package/lib/browser/types/editor-engine.d.ts +50 -0
  10. package/lib/browser/types/editor-types.d.ts +141 -0
  11. package/lib/browser/types/editor.d.ts +9 -0
  12. package/lib/browser/types/engine-rendering.d.ts +3 -0
  13. package/lib/browser/types/engine-types.d.ts +17 -0
  14. package/lib/browser/types/font-channel.d.ts +20 -0
  15. package/lib/browser/types/index.d.ts +13 -0
  16. package/lib/browser/types/protocol.d.ts +117 -0
  17. package/lib/browser/types/rendering.d.ts +4 -0
  18. package/lib/browser/types/types.d.ts +90 -0
  19. package/lib/browser/types/worker.d.ts +2 -0
  20. package/lib/browser/worker.js +3711 -0
  21. package/lib/browser-assets.js +119 -0
  22. package/lib/cli.js +1303 -0
  23. package/lib/document.js +178 -0
  24. package/lib/engine-rendering.js +120 -0
  25. package/lib/font-config.js +46 -0
  26. package/lib/font-source.js +344 -0
  27. package/lib/font-worker.js +712 -0
  28. package/lib/index.js +319 -109
  29. package/lib/rendering.js +99 -0
  30. package/lib/sheet-geometry.js +111 -0
  31. package/lib/types/browser-assets.d.ts +15 -0
  32. package/lib/types/cli.d.ts +3 -0
  33. package/lib/types/document.d.ts +1 -1
  34. package/lib/types/engine-rendering.d.ts +15 -0
  35. package/lib/types/engine.d.ts +5 -5
  36. package/lib/types/font-config.d.ts +24 -0
  37. package/lib/types/font-full.d.ts +13 -0
  38. package/lib/types/font-loader.d.ts +1 -7
  39. package/lib/types/font-request.d.ts +12 -0
  40. package/lib/types/font-source-types.d.ts +82 -0
  41. package/lib/types/font-source.d.ts +10 -0
  42. package/lib/types/font-subsets.d.ts +35 -0
  43. package/lib/types/font-worker.d.ts +2 -0
  44. package/lib/types/fonts.d.ts +9 -29
  45. package/lib/types/harfbuzz-subset.d.ts +11 -0
  46. package/lib/types/image-operations.d.ts +58 -0
  47. package/lib/types/image-renderer.d.ts +6 -0
  48. package/lib/types/index.d.ts +25 -2
  49. package/lib/types/native.d.ts +4 -2
  50. package/lib/types/operations.d.ts +41 -0
  51. package/lib/types/png.d.ts +2 -0
  52. package/lib/types/profile.d.ts +8 -0
  53. package/lib/types/rendering.d.ts +41 -0
  54. package/lib/types/runtime.d.ts +14 -0
  55. package/lib/types/sheet-geometry.d.ts +38 -0
  56. package/lib/types/unicode-scripts.d.ts +18 -0
  57. package/lib/types/wasm.d.ts +76 -1
  58. package/lib/types/worker.d.ts +3 -0
  59. package/lib/worker.js +1012 -237
  60. package/licenses/font-subset/harfbuzz-COPYING +42 -0
  61. package/licenses/font-subset/harfbuzzjs-LICENSE +19 -0
  62. package/licenses/javascript/fflate-LICENSE +21 -0
  63. package/licenses/javascript/saxes-LICENSE +64 -0
  64. package/licenses/javascript/xmlchars-LICENSE +18 -0
  65. package/package.json +59 -12
  66. package/sources/browser/packages/browser/package.json +22 -0
  67. package/sources/browser/packages/browser/src/connection.ts +168 -0
  68. package/sources/browser/packages/browser/src/editor-engine.ts +382 -0
  69. package/sources/browser/packages/browser/src/editor-types.ts +106 -0
  70. package/sources/browser/packages/browser/src/editor.ts +55 -0
  71. package/sources/browser/packages/browser/src/engine-rendering.ts +2 -0
  72. package/sources/browser/packages/browser/src/engine-types.ts +14 -0
  73. package/sources/browser/packages/browser/src/font-channel.ts +99 -0
  74. package/sources/browser/packages/browser/src/index.ts +39 -0
  75. package/sources/browser/packages/browser/src/protocol.ts +40 -0
  76. package/sources/browser/packages/browser/src/rendering.ts +3 -0
  77. package/sources/browser/packages/browser/src/types.ts +92 -0
  78. package/sources/browser/packages/browser/src/worker.ts +171 -0
  79. package/sources/browser/packages/browser/tsconfig.json +5 -0
  80. package/sources/browser/packages/browser/tsdown.config.ts +7 -0
  81. package/sources/browser/scripts/build-browser.mjs +74 -0
  82. package/sources/font-subset/engine/font-subset/README.md +23 -0
  83. package/sources/font-subset/engine/font-subset/README.zh.md +23 -0
  84. package/sources/font-subset/engine/font-subset/source.json +16 -0
  85. package/sources/font-subset/harfbuzzjs/config-override-subset.h +7 -0
  86. package/sources/font-subset/harfbuzzjs/harfbuzz-subset.symbols +34 -0
  87. package/sources/font-subset/scripts/build-font-subset.mjs +64 -0
  88. package/sources/font-subset/scripts/pack-utils.mjs +69 -0
  89. package/sources/font-subset/scripts/platform-matrix.mjs +100 -0
  90. package/sources/font-subset/scripts/verify-artifacts.mjs +260 -0
@@ -0,0 +1,178 @@
1
+ import { strFromU8, unzipSync } from "fflate";
2
+ import { SaxesParser } from "saxes";
3
+ //#region lib/types/errors.js
4
+ /** An actionable converter failure; operating-system errors and caller abort reasons remain unchanged. */
5
+ var ConversionError = class extends Error {
6
+ /** Published failure category carried across worker and helper transports. */
7
+ code;
8
+ /**
9
+ * @param code - Published failure category.
10
+ * @param message - Consumer-facing failure description.
11
+ * @param options - Standard error options; a cause is preserved for diagnostics.
12
+ */
13
+ constructor(code, message, options) {
14
+ super(message, options);
15
+ this.name = "ConversionError";
16
+ this.code = code;
17
+ }
18
+ };
19
+ //#endregion
20
+ //#region lib/types/font-config.js
21
+ /** Browser-safe family ordering and Fontconfig XML shared by both WASM adapters. */
22
+ /**
23
+ * Case- and separator-insensitive family key used to compare names across sources.
24
+ * @param value - Family, style, or postscript name as recorded by a document or font.
25
+ * @returns The normalized key.
26
+ */
27
+ function normalize(value) {
28
+ return value.normalize("NFKC").toLowerCase().replaceAll(/[\s_-]/g, "");
29
+ }
30
+ //#endregion
31
+ //#region lib/types/ooxml.js
32
+ /** Bounded OOXML inspection and declared font diagnostics, using maintained ZIP/XML parsers. */
33
+ const MAIN_PARTS = {
34
+ odt: ["content.xml", "application/vnd.oasis.opendocument.text"],
35
+ ods: ["content.xml", "application/vnd.oasis.opendocument.spreadsheet"],
36
+ odp: ["content.xml", "application/vnd.oasis.opendocument.presentation"],
37
+ docx: ["word/document.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"],
38
+ xlsx: ["xl/workbook.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"],
39
+ pptx: ["ppt/presentation.xml", "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"]
40
+ };
41
+ /**
42
+ * @param character - One code point as yielded by iteration over a string.
43
+ * @returns the Unicode scalar the character encodes; iteration never yields an empty string.
44
+ */
45
+ function codePointOf(character) {
46
+ return character.codePointAt(0);
47
+ }
48
+ /**
49
+ * Validate ZIP size and membership before decoding selected document XML.
50
+ * @param bytes - Complete source document bytes.
51
+ * @param extension - Input extension, which selects the main document part.
52
+ * @param limits - Archive entry and declared uncompressed byte limits.
53
+ * @returns declared font families and the scalar values readable document XML declares.
54
+ * @throws ConversionError when the extension is unsupported or the archive violates its limits.
55
+ */
56
+ function inspectDocument$1(bytes, extension, limits) {
57
+ const main = MAIN_PARTS[extension];
58
+ if (!main) throw new ConversionError("unsupported-format", "Input extension must be docx, xlsx, or pptx.");
59
+ const odf = [
60
+ "odt",
61
+ "ods",
62
+ "odp"
63
+ ].includes(extension);
64
+ const names = /* @__PURE__ */ new Set();
65
+ let total = 0;
66
+ let files;
67
+ try {
68
+ files = unzipSync(bytes, { filter(entry) {
69
+ total += entry.originalSize;
70
+ if (names.has(entry.name) || names.size >= limits.maxArchiveEntries || !Number.isSafeInteger(total) || total > limits.maxUncompressedBytes) throw new Error("OOXML archive exceeds its limits or repeats an entry.");
71
+ names.add(entry.name);
72
+ if (odf) return [
73
+ "mimetype",
74
+ "content.xml",
75
+ "styles.xml",
76
+ "META-INF/manifest.xml"
77
+ ].includes(entry.name);
78
+ return entry.name === "[Content_Types].xml" || /^(word|xl|ppt)\/.*\.xml$/.test(entry.name) && !entry.name.endsWith("/fontTable.xml") && !entry.name.includes("/theme/");
79
+ } });
80
+ } catch (cause) {
81
+ throw new ConversionError("invalid-document", "Input is not a supported, bounded OOXML archive.", { cause });
82
+ }
83
+ const contentTypes = files["[Content_Types].xml"];
84
+ if (odf ? !names.has("content.xml") || !names.has("META-INF/manifest.xml") || strFromU8(files.mimetype ?? /* @__PURE__ */ new Uint8Array()) !== main[1] : !names.has("_rels/.rels") || !names.has(main[0]) || contentTypes === void 0 || !strFromU8(contentTypes).includes(main[1])) throw new ConversionError("invalid-document", `Input does not contain a ${extension} document.`);
85
+ const families = /* @__PURE__ */ new Map();
86
+ const codePoints = /* @__PURE__ */ new Set();
87
+ for (const [name, data] of Object.entries(files)) {
88
+ if (name === "[Content_Types].xml" || name === "mimetype" || name === "META-INF/manifest.xml") continue;
89
+ const partFamilies = [];
90
+ const partPoints = /* @__PURE__ */ new Set();
91
+ const parser = new SaxesParser({ xmlns: true });
92
+ parser.on("opentag", (tag) => {
93
+ const word = /wordprocessingml\/(?:2006\/)?main$/.test(tag.uri) && tag.local === "rFonts";
94
+ const drawing = /drawingml\/(?:2006\/)?main$/.test(tag.uri);
95
+ const sheet = /spreadsheetml\/(?:2006\/)?main$/.test(tag.uri) && tag.local === "name";
96
+ for (const attribute of Object.values(tag.attributes)) {
97
+ if (odf && attribute.local === "font-family") partFamilies.push(attribute.value.replace(/^['"]|['"]$/g, ""));
98
+ if (word && [
99
+ "ascii",
100
+ "hAnsi",
101
+ "eastAsia",
102
+ "cs"
103
+ ].includes(attribute.local) || drawing && attribute.local === "typeface" || sheet && attribute.local === "val") partFamilies.push(attribute.value);
104
+ }
105
+ });
106
+ parser.on("text", (text) => {
107
+ for (const char of text) if (!/\s/u.test(char)) partPoints.add(codePointOf(char));
108
+ });
109
+ const encoding = data[0] === 255 && data[1] === 254 ? "utf-16le" : data[0] === 254 && data[1] === 255 ? "utf-16be" : "utf-8";
110
+ try {
111
+ parser.write(new TextDecoder(encoding).decode(data)).close();
112
+ } catch {
113
+ continue;
114
+ }
115
+ for (const declared of partFamilies) for (const family of declared.split(";").map((value) => value.trim()).filter((value) => value && !/^\+(?:mj|mn)-(?:lt|ea|cs)$/.test(value))) families.set(normalize(family), family);
116
+ for (const point of partPoints) codePoints.add(point);
117
+ }
118
+ return {
119
+ families,
120
+ codePoints: [...codePoints]
121
+ };
122
+ }
123
+ //#endregion
124
+ //#region lib/types/document.js
125
+ /** Select bounded OOXML inspection or a legacy Office compound-file import. */
126
+ /** Input suffixes accepted by the public converter. */
127
+ const DOCUMENT_EXTENSIONS = [
128
+ "doc",
129
+ "docx",
130
+ "odt",
131
+ "xls",
132
+ "xlsx",
133
+ "ods",
134
+ "ppt",
135
+ "pptx",
136
+ "odp"
137
+ ];
138
+ const COMPOUND_SIGNATURE = [
139
+ 208,
140
+ 207,
141
+ 17,
142
+ 224,
143
+ 161,
144
+ 177,
145
+ 26,
146
+ 225
147
+ ];
148
+ /**
149
+ * Inspect the input container before invoking LibreOffice's document importer.
150
+ * Compound-file streams and legacy font tables are interpreted by LibreOffice;
151
+ * they do not supply the API's OOXML font diagnostics.
152
+ * @param bytes - Source bytes already bounded by maxInputBytes.
153
+ * @param extension - Lowercase source suffix.
154
+ * @param limits - Limits applied to ZIP-based document contents.
155
+ * @returns OOXML font metadata, or empty diagnostics for a binary document.
156
+ */
157
+ function inspectDocument(bytes, extension, limits) {
158
+ if (!DOCUMENT_EXTENSIONS.includes(extension)) throw new ConversionError("unsupported-format", `Input extension must be ${DOCUMENT_EXTENSIONS.join(", ")}.`);
159
+ if ([
160
+ "docx",
161
+ "xlsx",
162
+ "pptx",
163
+ "odt",
164
+ "ods",
165
+ "odp"
166
+ ].includes(extension)) return inspectDocument$1(bytes, extension, limits);
167
+ if (bytes.length < 512 || !COMPOUND_SIGNATURE.every((value, index) => bytes[index] === value)) throw new ConversionError("invalid-document", "Legacy Office input must contain an OLE compound document.");
168
+ const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
169
+ const version = header.getUint16(26, true);
170
+ const sectorShift = header.getUint16(30, true);
171
+ if (header.getUint16(28, true) !== 65534 || header.getUint16(32, true) !== 6 || !(version === 3 && sectorShift === 9 || version === 4 && sectorShift === 12) || bytes.length < 2 ** sectorShift * 2 || bytes.length % 2 ** sectorShift !== 0) throw new ConversionError("invalid-document", "Legacy Office input has an invalid or truncated compound-file header.");
172
+ return {
173
+ families: /* @__PURE__ */ new Map(),
174
+ codePoints: []
175
+ };
176
+ }
177
+ //#endregion
178
+ export { DOCUMENT_EXTENSIONS, inspectDocument };
@@ -0,0 +1,120 @@
1
+ /** Validate coordinates before allocation or wasm32 integer conversion. */
2
+ function tileDimensions(request, pages) {
3
+ const page = pages[request.pageIndex];
4
+ if (!Number.isSafeInteger(request.pageIndex) || !page || ![
5
+ request.x,
6
+ request.y,
7
+ request.width,
8
+ request.height,
9
+ request.scale
10
+ ].every(Number.isFinite) || request.x < 0 || request.y < 0 || request.width <= 0 || request.height <= 0 || request.scale <= 0 || request.x + request.width > page.width + .001 || request.y + request.height > page.height + .001) throw new Error("Tile rectangle lies outside its page.");
11
+ const width = Math.ceil(request.width * request.scale - 1e-9);
12
+ const height = Math.ceil(request.height * request.scale - 1e-9);
13
+ if (width <= 0 || height <= 0 || !Number.isSafeInteger(width * height) || width * height > 16777216) throw new Error("Tile exceeds the 16 megapixel allocation limit.");
14
+ const twips = [
15
+ page.x + Math.round(request.x * 15),
16
+ page.y + Math.round(request.y * 15),
17
+ Math.round(request.width * 15),
18
+ Math.round(request.height * 15)
19
+ ];
20
+ if (twips.some((value) => !Number.isSafeInteger(value) || value < 0 || value > 2147483647) || twips[0] + twips[2] > 2147483647 || twips[1] + twips[3] > 2147483647) throw new Error("Tile coordinates exceed the wasm32 range.");
21
+ return {
22
+ page,
23
+ width,
24
+ height
25
+ };
26
+ }
27
+ /** Cairo/LO channels are premultiplied; PNG and ImageData require straight RGBA. */
28
+ function rgbaPixels(source, tileMode) {
29
+ if (tileMode !== 0 && tileMode !== 1 || source.length % 4 !== 0) throw new Error("LibreOffice returned an unsupported tile pixel format.");
30
+ const result = new Uint8ClampedArray(source.length);
31
+ for (let index = 0; index < source.length; index += 4) {
32
+ const alpha = source[index + 3];
33
+ const multiplier = alpha === 0 ? 0 : 255 / alpha;
34
+ result[index] = source[index + (tileMode === 1 ? 2 : 0)] * multiplier;
35
+ result[index + 1] = source[index + 1] * multiplier;
36
+ result[index + 2] = source[index + (tileMode === 1 ? 0 : 2)] * multiplier;
37
+ result[index + 3] = alpha;
38
+ }
39
+ return result;
40
+ }
41
+ //#endregion
42
+ //#region lib/types/engine-rendering.js
43
+ /** Shared bounded raster allocations for browser and Node engine owners. */
44
+ function numericCall(module, name, args) {
45
+ return module.ccall(name, "number", args.map(() => "number"), args);
46
+ }
47
+ /** Copy/free one engine-owned UTF-8 return value. */
48
+ function engineString(module, name, types, args, failure) {
49
+ const pointer = module.ccall(name, "number", types, args);
50
+ if (!pointer) throw failure();
51
+ try {
52
+ return module.UTF8ToString(pointer);
53
+ } finally {
54
+ numericCall(module, "free", [pointer]);
55
+ }
56
+ }
57
+ /** Paint into a temporary allocation; copy pixels before free or another engine call. */
58
+ function renderRegion(module, document, request, pages, failure, pdf = false) {
59
+ const call = (name, args) => numericCall(module, name, args);
60
+ const { page, width, height } = tileDimensions(request, pages);
61
+ const size = width * height * 4;
62
+ const pointer = call("malloc", [size]);
63
+ if (!pointer) throw failure();
64
+ try {
65
+ new Uint8Array(module.HEAPU32.buffer, pointer, size).fill(0);
66
+ const position = [
67
+ page.x + Math.round(request.x * 15),
68
+ page.y + Math.round(request.y * 15),
69
+ Math.max(1, Math.round(request.width * 15)),
70
+ Math.max(1, Math.round(request.height * 15))
71
+ ];
72
+ if (!call(pdf ? "dsh_pdf_paint" : "dsh_lok_document_paint", [
73
+ document,
74
+ pointer,
75
+ page.part,
76
+ width,
77
+ height,
78
+ ...position
79
+ ])) throw failure();
80
+ const source = new Uint8Array(module.HEAPU32.buffer, pointer, size);
81
+ return {
82
+ width,
83
+ height,
84
+ rgba: pdf ? new Uint8ClampedArray(source) : rgbaPixels(source, call("dsh_lok_document_tile_mode", [document]))
85
+ };
86
+ } finally {
87
+ call("free", [pointer]);
88
+ }
89
+ }
90
+ /** PDF page dimensions use the same twips ABI, with an immutable PDF page index as part. */
91
+ function pdfPages(module, pdf, failure) {
92
+ const count = numericCall(module, "dsh_pdf_page_count", [pdf]);
93
+ if (!Number.isSafeInteger(count) || count < 1 || count > 1e5) throw failure();
94
+ const pointer = numericCall(module, "malloc", [8]);
95
+ if (!pointer) throw failure();
96
+ try {
97
+ return Array.from({ length: count }, (_, part) => {
98
+ if (!numericCall(module, "dsh_pdf_page_size", [
99
+ pdf,
100
+ part,
101
+ pointer,
102
+ pointer + 4
103
+ ])) throw failure();
104
+ const width = module.HEAPU32[pointer / 4];
105
+ const height = module.HEAPU32[pointer / 4 + 1];
106
+ if (width < 1 || height < 1 || width > 2147483647 || height > 2147483647) throw failure();
107
+ return {
108
+ part,
109
+ x: 0,
110
+ y: 0,
111
+ width: width / 15,
112
+ height: height / 15
113
+ };
114
+ });
115
+ } finally {
116
+ numericCall(module, "free", [pointer]);
117
+ }
118
+ }
119
+ //#endregion
120
+ export { engineString, numericCall, pdfPages, renderRegion };
@@ -0,0 +1,46 @@
1
+ //#region lib/types/font-config.js
2
+ /** Browser-safe family ordering and Fontconfig XML shared by both WASM adapters. */
3
+ /**
4
+ * Case- and separator-insensitive family key used to compare names across sources.
5
+ * @param value - Family, style, or postscript name as recorded by a document or font.
6
+ * @returns The normalized key.
7
+ */
8
+ function normalize(value) {
9
+ return value.normalize("NFKC").toLowerCase().replaceAll(/[\s_-]/g, "");
10
+ }
11
+ /**
12
+ * Order named substitutions and their generic text family without excluding unlisted fonts.
13
+ * @param requested - Original family names, in document order.
14
+ * @param groups - Ordered family groups shared with Fontconfig aliases.
15
+ * @param pitch - VCL pitch; one requests a monospaced fallback.
16
+ * @param symbols - Whether symbol alternatives precede the generic fallback.
17
+ * @returns distinct family names, with original requests first.
18
+ */
19
+ function fontFamilyPriority(requested, groups, pitch = 0, symbols = false) {
20
+ const original = requested.map(normalize);
21
+ const matched = groups.filter((group) => group.some((family) => original.includes(normalize(family))));
22
+ const generic = original.includes("monospace") || pitch === 1 ? "monospace" : original.includes("serif") ? "serif" : matched.flat().map(normalize).find((family) => family === "serif" || family === "sansserif" || family === "monospace") ?? "sansserif";
23
+ const families = [...requested, ...matched.flat()];
24
+ for (const kind of symbols ? ["symbol", generic] : [generic]) for (const group of groups) if (group.some((family) => normalize(family) === kind)) families.push(...group);
25
+ const priority = /* @__PURE__ */ new Map();
26
+ for (const family of families) {
27
+ const name = normalize(family);
28
+ if (!priority.has(name)) priority.set(name, family);
29
+ }
30
+ return [...priority.values()];
31
+ }
32
+ /**
33
+ * Fontconfig XML restricts WASM discovery to imported originals in MEMFS.
34
+ * @param families - Ordered family groups; the first name of each group is its canonical spelling.
35
+ * @param requested - Additional family names the document declared.
36
+ * @returns the fontconfig document written into the module's memory filesystem.
37
+ */
38
+ function memoryFontConfig(families, requested = []) {
39
+ const escape = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
40
+ return `<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "fonts.dtd"><fontconfig><dir>/dsh-fonts</dir><cachedir>/dsh/font-cache</cachedir>${[...new Map([...families.flatMap((group) => group.slice(0, 1)), ...requested].map((name) => [normalize(name), name])).values()].map((name) => {
41
+ const alternatives = fontFamilyPriority([name], families).filter((family) => normalize(family) !== normalize(name));
42
+ return `<alias><family>${escape(name)}</family><accept>${alternatives.map((family) => `<family>${escape(family)}</family>`).join("")}</accept></alias>`;
43
+ }).join("")}</fontconfig>`;
44
+ }
45
+ //#endregion
46
+ export { fontFamilyPriority, memoryFontConfig, normalize };
@@ -0,0 +1,344 @@
1
+ import { Worker } from "node:worker_threads";
2
+ import { readdirSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join, posix, win32 } from "node:path";
5
+ import "fontkit";
6
+ //#region lib/types/fonts.js
7
+ /**
8
+ * @param error - Thrown filesystem value.
9
+ * @returns whether it means the path is not a usable font source.
10
+ */
11
+ function absent(error) {
12
+ return error instanceof Error && "code" in error && [
13
+ "ENOENT",
14
+ "EACCES",
15
+ "EPERM",
16
+ "ENOTDIR"
17
+ ].includes(String(error.code));
18
+ }
19
+ /**
20
+ * Discover system and per-user font roots using the selected platform's path separators.
21
+ * @param platform - Host operating system.
22
+ * @param home - Host user home used to locate per-user font directories.
23
+ * @param env - Host environment containing Windows and XDG directory overrides.
24
+ * @returns candidate directories; missing platform directories are ignored during indexing.
25
+ */
26
+ function systemFontDirectories(platform = process.platform, home = homedir(), env = process.env) {
27
+ if (platform === "win32") return [win32.join(env.SystemRoot ?? "C:\\Windows", "Fonts"), win32.join(env.LOCALAPPDATA ?? win32.join(home, "AppData", "Local"), "Microsoft", "Windows", "Fonts")];
28
+ if (platform === "darwin") return [
29
+ "/System/Library/Fonts",
30
+ "/Library/Fonts",
31
+ posix.join(home, "Library/Fonts"),
32
+ ...mobileAssetFontDirectories("/System/Library/AssetsV2")
33
+ ];
34
+ const shared = (env.XDG_DATA_DIRS ?? "/usr/local/share:/usr/share").split(":").filter(Boolean);
35
+ return [.../* @__PURE__ */ new Set([
36
+ ...shared.map((path) => posix.join(path, "fonts")),
37
+ posix.join(home, ".fonts"),
38
+ posix.join(env.XDG_DATA_HOME ?? posix.join(home, ".local/share"), "fonts")
39
+ ])];
40
+ }
41
+ /**
42
+ * Font asset directories macOS publishes under its MobileAsset root.
43
+ * @param assets - Absolute MobileAsset font directory root.
44
+ * @returns matching asset directories, sorted by name.
45
+ * @throws when the root exists but cannot be read for a reason other than its absence or protection.
46
+ */
47
+ function mobileAssetFontDirectories(assets) {
48
+ let entries = [];
49
+ try {
50
+ entries = readdirSync(assets);
51
+ } catch (error) {
52
+ if (!absent(error)) throw error;
53
+ }
54
+ return entries.filter((name) => /^com_apple_MobileAsset_Font\d*$/.test(name)).sort().map((name) => join(assets, name));
55
+ }
56
+ //#endregion
57
+ //#region lib/types/options.js
58
+ const SANS_CJK_FAMILIES = [
59
+ "Microsoft YaHei",
60
+ "Microsoft YaHei UI",
61
+ "微软雅黑",
62
+ "PingFang SC",
63
+ "Noto Sans CJK SC",
64
+ "Noto Sans SC",
65
+ "Source Han Sans SC",
66
+ "SimHei",
67
+ "黑体",
68
+ "Heiti SC",
69
+ "STHeiti"
70
+ ];
71
+ /** Ordered family groups used when the caller supplies none. */
72
+ const FONT_FALLBACKS = [
73
+ ["Calibri", "Carlito"],
74
+ [
75
+ "Calibri Light",
76
+ "Carlito",
77
+ "Calibri"
78
+ ],
79
+ ["Cambria", "Caladea"],
80
+ [
81
+ "宋体",
82
+ "SimSun",
83
+ "NSimSun",
84
+ "Songti SC",
85
+ "STSong",
86
+ "Noto Serif CJK SC",
87
+ "Noto Serif SC",
88
+ "Source Han Serif SC"
89
+ ],
90
+ [
91
+ "黑体",
92
+ "SimHei",
93
+ "Heiti SC",
94
+ "STHeiti",
95
+ "Noto Sans CJK SC",
96
+ "Noto Sans SC",
97
+ "Source Han Sans SC"
98
+ ],
99
+ [
100
+ "微软雅黑",
101
+ "Microsoft YaHei",
102
+ "Microsoft YaHei UI",
103
+ "PingFang SC",
104
+ "Noto Sans CJK SC",
105
+ "Noto Sans SC"
106
+ ],
107
+ [
108
+ "楷体",
109
+ "KaiTi",
110
+ "Kaiti SC",
111
+ "STKaiti",
112
+ "LXGW WenKai"
113
+ ],
114
+ [
115
+ "仿宋",
116
+ "FangSong",
117
+ "STFangsong",
118
+ "Songti SC",
119
+ "Noto Serif CJK SC"
120
+ ],
121
+ [
122
+ "sans-serif",
123
+ "Arial",
124
+ "Liberation Sans",
125
+ "Helvetica",
126
+ "DejaVu Sans",
127
+ "Calibri",
128
+ "Calibri Light",
129
+ "Carlito",
130
+ ...SANS_CJK_FAMILIES
131
+ ],
132
+ [
133
+ "serif",
134
+ "Times New Roman",
135
+ "Liberation Serif",
136
+ "Times",
137
+ "DejaVu Serif",
138
+ "Cambria",
139
+ "Caladea",
140
+ "SimSun",
141
+ "NSimSun",
142
+ "宋体",
143
+ "Songti SC",
144
+ "STSong",
145
+ "Noto Serif CJK SC",
146
+ "Noto Serif SC",
147
+ "Source Han Serif SC"
148
+ ],
149
+ [
150
+ "monospace",
151
+ "Courier New",
152
+ "Liberation Mono",
153
+ "DejaVu Sans Mono",
154
+ "Menlo",
155
+ "Monaco",
156
+ "Courier",
157
+ "NSimSun",
158
+ "Noto Sans Mono CJK SC",
159
+ ...SANS_CJK_FAMILIES
160
+ ],
161
+ [
162
+ "Symbol",
163
+ "Standard Symbols PS",
164
+ "Symbola",
165
+ "Segoe UI Symbol",
166
+ "Apple Symbols",
167
+ "FreeSerif",
168
+ "DejaVu Sans"
169
+ ]
170
+ ];
171
+ const DEFAULT_LIMITS = {
172
+ timeoutMs: 12e4,
173
+ maxInputBytes: 67108864,
174
+ maxOutputBytes: 134217728,
175
+ maxImageResolution: 144,
176
+ maxArchiveEntries: 2e4,
177
+ maxUncompressedBytes: 536870912,
178
+ maxFontFiles: 2e4,
179
+ maxFontFileBytes: 268435456,
180
+ maxLoadedFontBytes: 536870912
181
+ };
182
+ const FONT_COLLECTION_NAMES = ["fontDirectories", "initialFontFamilies"];
183
+ function positiveSafeInteger(value, name) {
184
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) throw new RangeError(`${name} must be a positive safe integer.`);
185
+ if (name.endsWith("Ms") && value > 2147483647) throw new RangeError(`${name} exceeds the Node timer range.`);
186
+ return value;
187
+ }
188
+ function fontNames(value, name) {
189
+ if (!Array.isArray(value)) throw new TypeError(`${name} must contain nonempty strings.`);
190
+ const names = [];
191
+ for (const entry of value) {
192
+ if (typeof entry !== "string" || entry.length === 0 || entry.includes("\0")) throw new TypeError(`${name} must contain nonempty strings.`);
193
+ names.push(entry);
194
+ }
195
+ return names;
196
+ }
197
+ function fontGroups(value) {
198
+ if (!Array.isArray(value) || value.some((group) => !Array.isArray(group) || group.length < 2 || group.some((entry) => typeof entry !== "string" || !entry.trim()))) throw new TypeError("fontFallbacks must contain groups of at least two nonblank font names.");
199
+ return value.map((group) => [...group]);
200
+ }
201
+ /**
202
+ * Resolve defaults once; reject misspelled options and malformed font settings.
203
+ * @param input - Caller options; absent fields keep their documented default.
204
+ * @returns The validated limits and font settings, with caller arrays copied.
205
+ * @throws TypeError for a non-object argument or an unknown option name.
206
+ * @throws RangeError for a limit outside the positive safe-integer timer range.
207
+ */
208
+ function resolveOptions(input = {}) {
209
+ const callerOptions = input;
210
+ if (callerOptions === null || typeof callerOptions !== "object" || Array.isArray(callerOptions)) throw new TypeError("Converter options must be an object.");
211
+ const merged = {
212
+ ...DEFAULT_LIMITS,
213
+ fontDirectories: systemFontDirectories(),
214
+ fontFallbacks: FONT_FALLBACKS,
215
+ initialFontFamilies: [],
216
+ ...input
217
+ };
218
+ for (const key of Object.keys(input)) if (!(key in DEFAULT_LIMITS) && !FONT_COLLECTION_NAMES.includes(key) && key !== "fontFallbacks") throw new TypeError(`Unknown converter option: ${key}`);
219
+ return {
220
+ timeoutMs: positiveSafeInteger(merged.timeoutMs, "timeoutMs"),
221
+ maxInputBytes: positiveSafeInteger(merged.maxInputBytes, "maxInputBytes"),
222
+ maxOutputBytes: positiveSafeInteger(merged.maxOutputBytes, "maxOutputBytes"),
223
+ maxImageResolution: positiveSafeInteger(merged.maxImageResolution, "maxImageResolution"),
224
+ maxArchiveEntries: positiveSafeInteger(merged.maxArchiveEntries, "maxArchiveEntries"),
225
+ maxUncompressedBytes: positiveSafeInteger(merged.maxUncompressedBytes, "maxUncompressedBytes"),
226
+ maxFontFiles: positiveSafeInteger(merged.maxFontFiles, "maxFontFiles"),
227
+ maxFontFileBytes: positiveSafeInteger(merged.maxFontFileBytes, "maxFontFileBytes"),
228
+ maxLoadedFontBytes: positiveSafeInteger(merged.maxLoadedFontBytes, "maxLoadedFontBytes"),
229
+ fontDirectories: fontNames(merged.fontDirectories, "fontDirectories"),
230
+ initialFontFamilies: fontNames(merged.initialFontFamilies, "initialFontFamilies"),
231
+ fontFallbacks: fontGroups(merged.fontFallbacks)
232
+ };
233
+ }
234
+ //#endregion
235
+ //#region lib/types/font-source.js
236
+ /** Lazy Node font service, independent of native or WASM engine installation. */
237
+ /**
238
+ * Create a font catalog without loading a LibreOffice engine or reading fonts yet.
239
+ * @param options - Font directories, fallback groups, and discovery limits.
240
+ * @returns a source whose first operation starts its private Worker. Cancellation
241
+ * discards a result after dispatched work settles; dispose terminates all work.
242
+ */
243
+ function createFontSource(options = {}) {
244
+ const { fontDirectories, fontFallbacks, maxCachedSubsetBytes = 134217728, ...limits } = options;
245
+ if (!Number.isSafeInteger(maxCachedSubsetBytes) || maxCachedSubsetBytes < 1) throw new TypeError("maxCachedSubsetBytes must be a positive integer.");
246
+ const resolved = resolveOptions({
247
+ ...limits,
248
+ ...fontDirectories === void 0 ? {} : { fontDirectories: [...fontDirectories] },
249
+ ...fontFallbacks === void 0 ? {} : { fontFallbacks: fontFallbacks.map((group) => [...group]) }
250
+ });
251
+ let worker;
252
+ let nextId = 0;
253
+ let failure;
254
+ let closing;
255
+ const pending = /* @__PURE__ */ new Map();
256
+ const fail = (error) => {
257
+ failure ??= error;
258
+ for (const waiter of pending.values()) waiter.reject(error);
259
+ pending.clear();
260
+ };
261
+ function start() {
262
+ if (failure !== void 0) throw failure;
263
+ if (worker !== void 0) return worker;
264
+ worker = new Worker(new URL("./font-worker.js", import.meta.url), {
265
+ execArgv: [],
266
+ workerData: {
267
+ directories: resolved.fontDirectories,
268
+ fallbackFamilies: resolved.fontFallbacks,
269
+ maxFiles: resolved.maxFontFiles,
270
+ maxFileBytes: resolved.maxFontFileBytes,
271
+ maxCachedSubsetBytes
272
+ }
273
+ });
274
+ worker.on("message", (value) => {
275
+ if (typeof value !== "object" || value === null || !("id" in value) || typeof value.id !== "number" || !("kind" in value) || ![
276
+ "resolved",
277
+ "bytes",
278
+ "failed"
279
+ ].includes(String(value.kind))) {
280
+ fail(/* @__PURE__ */ new Error("The font Worker returned an invalid reply."));
281
+ worker?.terminate();
282
+ return;
283
+ }
284
+ const reply = value;
285
+ const waiter = pending.get(reply.id);
286
+ if (waiter === void 0) return;
287
+ pending.delete(reply.id);
288
+ if (reply.kind === "failed") waiter.reject(new Error(reply.message));
289
+ else waiter.resolve(reply);
290
+ });
291
+ worker.on("error", fail);
292
+ worker.on("exit", (code) => {
293
+ if (closing === void 0) fail(/* @__PURE__ */ new Error(`The font Worker exited with code ${code}.`));
294
+ });
295
+ return worker;
296
+ }
297
+ async function call(command, signal) {
298
+ signal?.throwIfAborted();
299
+ const owner = start();
300
+ const reply = await new Promise((resolve, reject) => {
301
+ pending.set(command.id, {
302
+ resolve,
303
+ reject
304
+ });
305
+ try {
306
+ owner.postMessage(command);
307
+ } catch (error) {
308
+ pending.delete(command.id);
309
+ reject(error);
310
+ }
311
+ });
312
+ signal?.throwIfAborted();
313
+ return reply;
314
+ }
315
+ return {
316
+ fontFallbacks: resolved.fontFallbacks,
317
+ async resolve(request, signal) {
318
+ const reply = await call({
319
+ id: ++nextId,
320
+ kind: "resolve",
321
+ request
322
+ }, signal);
323
+ if (reply.kind !== "resolved") throw new Error("The font Worker returned the wrong operation.");
324
+ return reply.value;
325
+ },
326
+ async read(asset, signal) {
327
+ const reply = await call({
328
+ id: ++nextId,
329
+ kind: "read",
330
+ asset
331
+ }, signal);
332
+ if (reply.kind !== "bytes" || !(reply.value instanceof Uint8Array)) throw new Error("The font Worker returned invalid bytes.");
333
+ return reply.value;
334
+ },
335
+ dispose() {
336
+ if (closing !== void 0) return closing;
337
+ fail(/* @__PURE__ */ new Error("The font source is disposed."));
338
+ closing = worker === void 0 ? Promise.resolve() : worker.terminate().then(() => {});
339
+ return closing;
340
+ }
341
+ };
342
+ }
343
+ //#endregion
344
+ export { createFontSource };