@deepseek-ai/libreoffice-kit 0.0.1-2
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.
- package/LICENSE +373 -0
- package/NOTICE +26 -0
- package/README.md +81 -0
- package/README.zh.md +81 -0
- package/lib/cli.js +1929 -0
- package/lib/index.js +1791 -0
- package/lib/types/cli.d.ts +3 -0
- package/lib/types/document.d.ts +15 -0
- package/lib/types/engine-rendering.d.ts +15 -0
- package/lib/types/engine.d.ts +67 -0
- package/lib/types/errors.d.ts +21 -0
- package/lib/types/font-full.d.ts +13 -0
- package/lib/types/font-loader.d.ts +38 -0
- package/lib/types/fonts.d.ts +142 -0
- package/lib/types/image-operations.d.ts +58 -0
- package/lib/types/image-renderer.d.ts +6 -0
- package/lib/types/index.d.ts +94 -0
- package/lib/types/native-font-names.d.ts +3 -0
- package/lib/types/native-image-renderer.d.ts +19 -0
- package/lib/types/native.d.ts +36 -0
- package/lib/types/office-fonts.d.ts +6 -0
- package/lib/types/ooxml.d.ts +17 -0
- package/lib/types/operations.d.ts +41 -0
- package/lib/types/options.d.ts +30 -0
- package/lib/types/png.d.ts +2 -0
- package/lib/types/profile.d.ts +8 -0
- package/lib/types/rendering.d.ts +41 -0
- package/lib/types/runtime.d.ts +14 -0
- package/lib/types/sheet-geometry.d.ts +38 -0
- package/lib/types/wasm.d.ts +103 -0
- package/lib/types/worker.d.ts +19 -0
- package/lib/worker.js +1724 -0
- package/package.json +51 -0
package/lib/worker.js
ADDED
|
@@ -0,0 +1,1724 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
3
|
+
import { closeSync, constants, fstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { basename, extname, join, posix, win32 } from "node:path";
|
|
5
|
+
import { strFromU8, unzipSync, zlibSync } from "fflate";
|
|
6
|
+
import { SaxesParser } from "saxes";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { create } from "fontkit";
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
//#region lib/types/errors.js
|
|
11
|
+
/** Stable render failure categories shared across the Node worker and native helper transports. */
|
|
12
|
+
const CODES = /* @__PURE__ */ new Set([
|
|
13
|
+
"input-too-large",
|
|
14
|
+
"output-too-large",
|
|
15
|
+
"invalid-document",
|
|
16
|
+
"unsupported-format",
|
|
17
|
+
"invalid-output",
|
|
18
|
+
"timeout",
|
|
19
|
+
"unavailable",
|
|
20
|
+
"failed"
|
|
21
|
+
]);
|
|
22
|
+
/** An actionable converter failure; operating-system errors and caller abort reasons remain unchanged. */
|
|
23
|
+
var ConversionError = class extends Error {
|
|
24
|
+
/** Published failure category carried across worker and helper transports. */
|
|
25
|
+
code;
|
|
26
|
+
/**
|
|
27
|
+
* @param code - Published failure category.
|
|
28
|
+
* @param message - Consumer-facing failure description.
|
|
29
|
+
* @param options - Standard error options; a cause is preserved for diagnostics.
|
|
30
|
+
*/
|
|
31
|
+
constructor(code, message, options) {
|
|
32
|
+
super(message, options);
|
|
33
|
+
this.name = "ConversionError";
|
|
34
|
+
this.code = code;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Only published categories cross worker/helper messages; unknown errors use the generic failure category.
|
|
39
|
+
* @param error - The thrown value, which may be any type and may carry an unpublished `code`.
|
|
40
|
+
* @returns The published category, or `failed` when no published category is present.
|
|
41
|
+
*/
|
|
42
|
+
function failureCode(error) {
|
|
43
|
+
const code = error?.code;
|
|
44
|
+
return typeof code === "string" && CODES.has(code) ? code : "failed";
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region lib/types/fonts.js
|
|
48
|
+
/** Host font metadata snapshots and conversion-local glyph matching over original files. */
|
|
49
|
+
const FONT_EXTENSIONS$1 = /* @__PURE__ */ new Set([
|
|
50
|
+
".ttf",
|
|
51
|
+
".otf",
|
|
52
|
+
".ttc",
|
|
53
|
+
".otc",
|
|
54
|
+
".dfont"
|
|
55
|
+
]);
|
|
56
|
+
const VCL_WEIGHTS = [
|
|
57
|
+
400,
|
|
58
|
+
100,
|
|
59
|
+
200,
|
|
60
|
+
300,
|
|
61
|
+
350,
|
|
62
|
+
400,
|
|
63
|
+
500,
|
|
64
|
+
600,
|
|
65
|
+
700,
|
|
66
|
+
800,
|
|
67
|
+
900
|
|
68
|
+
];
|
|
69
|
+
const GENERIC_FAMILIES = /* @__PURE__ */ new Set([
|
|
70
|
+
"serif",
|
|
71
|
+
"sansserif",
|
|
72
|
+
"monospace",
|
|
73
|
+
"cursive",
|
|
74
|
+
"fantasy",
|
|
75
|
+
"systemui",
|
|
76
|
+
"symbol"
|
|
77
|
+
]);
|
|
78
|
+
/** File identity read from the descriptor, before and after, to detect concurrent replacement. */
|
|
79
|
+
const STAT_KEYS = [
|
|
80
|
+
"dev",
|
|
81
|
+
"ino",
|
|
82
|
+
"size",
|
|
83
|
+
"mtimeMs",
|
|
84
|
+
"ctimeMs"
|
|
85
|
+
];
|
|
86
|
+
/**
|
|
87
|
+
* @param error - Thrown filesystem value.
|
|
88
|
+
* @returns whether it means the path is not a usable font source.
|
|
89
|
+
*/
|
|
90
|
+
function absent(error) {
|
|
91
|
+
return error instanceof Error && "code" in error && [
|
|
92
|
+
"ENOENT",
|
|
93
|
+
"EACCES",
|
|
94
|
+
"EPERM",
|
|
95
|
+
"ENOTDIR"
|
|
96
|
+
].includes(String(error.code));
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Case- and separator-insensitive family key used to compare names across sources.
|
|
100
|
+
* @param value - Family, style, or postscript name as recorded by a document or font.
|
|
101
|
+
* @returns The normalized key.
|
|
102
|
+
*/
|
|
103
|
+
function normalize(value) {
|
|
104
|
+
return value.normalize("NFKC").toLowerCase().replaceAll(/[\s_-]/g, "");
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Order named substitutions and their generic text family without excluding unlisted fonts.
|
|
108
|
+
* @param requested - Original family names, in document order.
|
|
109
|
+
* @param groups - Ordered family groups shared with Fontconfig aliases.
|
|
110
|
+
* @param pitch - VCL pitch; one requests a monospaced fallback.
|
|
111
|
+
* @param symbols - Whether symbol alternatives precede the generic fallback.
|
|
112
|
+
* @returns distinct family names, with original requests first.
|
|
113
|
+
*/
|
|
114
|
+
function fontFamilyPriority(requested, groups, pitch = 0, symbols = false) {
|
|
115
|
+
const original = requested.map(normalize);
|
|
116
|
+
const matched = groups.filter((group) => group.some((family) => original.includes(normalize(family))));
|
|
117
|
+
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";
|
|
118
|
+
const families = [...requested, ...matched.flat()];
|
|
119
|
+
for (const kind of symbols ? ["symbol", generic] : [generic]) for (const group of groups) if (group.some((family) => normalize(family) === kind)) families.push(...group);
|
|
120
|
+
const priority = /* @__PURE__ */ new Map();
|
|
121
|
+
for (const family of families) {
|
|
122
|
+
const name = normalize(family);
|
|
123
|
+
if (!priority.has(name)) priority.set(name, family);
|
|
124
|
+
}
|
|
125
|
+
return [...priority.values()];
|
|
126
|
+
}
|
|
127
|
+
function fontPaths(directories, maxFiles) {
|
|
128
|
+
const pending = [...directories].reverse();
|
|
129
|
+
const visited = /* @__PURE__ */ new Set();
|
|
130
|
+
const paths = [];
|
|
131
|
+
for (let path = pending.pop(); path !== void 0; path = pending.pop()) {
|
|
132
|
+
let canonical;
|
|
133
|
+
let status;
|
|
134
|
+
try {
|
|
135
|
+
canonical = realpathSync(path);
|
|
136
|
+
status = statSync(canonical);
|
|
137
|
+
} catch (error) {
|
|
138
|
+
if (absent(error)) continue;
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
if (visited.has(canonical)) continue;
|
|
142
|
+
visited.add(canonical);
|
|
143
|
+
if (status.isDirectory()) {
|
|
144
|
+
let names;
|
|
145
|
+
try {
|
|
146
|
+
names = readdirSync(canonical);
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (absent(error)) continue;
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
pending.push(...names.sort().reverse().map((name) => join(canonical, name)));
|
|
152
|
+
} else if (status.isFile() && FONT_EXTENSIONS$1.has(extname(canonical).toLowerCase())) {
|
|
153
|
+
if (paths.length >= maxFiles) throw new Error("The system font catalog exceeds maxFontFiles.");
|
|
154
|
+
paths.push(canonical);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return paths;
|
|
158
|
+
}
|
|
159
|
+
function ranges(font) {
|
|
160
|
+
const points = font.characterSet.filter((point) => font.hasGlyphForCodePoint(point)).sort((left, right) => left - right);
|
|
161
|
+
const result = [];
|
|
162
|
+
for (const point of points) {
|
|
163
|
+
const last = result.at(-1);
|
|
164
|
+
if (last !== void 0 && point <= last[1] + 1) last[1] = Math.max(last[1], point);
|
|
165
|
+
else result.push([point, point]);
|
|
166
|
+
}
|
|
167
|
+
return result;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Decode glyph coverage for one parsed face.
|
|
171
|
+
* @param font - The parsed physical face.
|
|
172
|
+
* @returns the inclusive ranges the face renders, or none when its glyph tables reject decoding.
|
|
173
|
+
*/
|
|
174
|
+
function faceCoverage(font) {
|
|
175
|
+
try {
|
|
176
|
+
return ranges(font);
|
|
177
|
+
} catch {
|
|
178
|
+
return [];
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* @param parsed - Parsed font file: one face, or a collection of faces.
|
|
183
|
+
* @param face - Indexed metadata naming the face inside that file.
|
|
184
|
+
* @returns the physical face the index names.
|
|
185
|
+
* @throws when the file no longer provides the indexed face.
|
|
186
|
+
*/
|
|
187
|
+
function indexedFace(parsed, face) {
|
|
188
|
+
const font = "fonts" in parsed ? parsed.fonts[face.faceIndex] : parsed;
|
|
189
|
+
if (font === void 0 || font.postscriptName !== face.postscriptName) throw new Error("The indexed font face is no longer available; recreate the converter.");
|
|
190
|
+
return font;
|
|
191
|
+
}
|
|
192
|
+
function covers(face, points) {
|
|
193
|
+
if (points.length === 0) return [];
|
|
194
|
+
if (face.coverage === void 0) face.coverage = faceCoverage(indexedFace(create(readFont(face)), face));
|
|
195
|
+
const coverage = face.coverage;
|
|
196
|
+
return points.filter((point) => coverage.some(([first, last]) => point >= first && point <= last));
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* VCL weight, width, and fixed-pitch values for one parsed face.
|
|
200
|
+
* @param font - The parsed physical face, whose `OS/2` and `post` tables may be absent.
|
|
201
|
+
* @returns the recorded classes, or the regular defaults for an absent table.
|
|
202
|
+
*/
|
|
203
|
+
function faceMetrics(font) {
|
|
204
|
+
const os2 = font["OS/2"];
|
|
205
|
+
return {
|
|
206
|
+
weight: os2 === void 0 ? 400 : os2.usWeightClass,
|
|
207
|
+
width: os2 === void 0 ? 5 : os2.usWidthClass,
|
|
208
|
+
fixed: Boolean(font.post?.isFixedPitch)
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
function inspect(path, maxBytes) {
|
|
212
|
+
let status;
|
|
213
|
+
let bytes;
|
|
214
|
+
try {
|
|
215
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
|
|
216
|
+
try {
|
|
217
|
+
status = fstatSync(fd);
|
|
218
|
+
if (!status.isFile() || status.size > maxBytes) return [];
|
|
219
|
+
bytes = Buffer.alloc(status.size);
|
|
220
|
+
let offset = 0;
|
|
221
|
+
while (offset < bytes.length) {
|
|
222
|
+
const count = readSync(fd, bytes, offset, bytes.length - offset, offset);
|
|
223
|
+
if (count === 0) throw new Error("A system font was truncated while indexing; reload the font service.");
|
|
224
|
+
offset += count;
|
|
225
|
+
}
|
|
226
|
+
const after = fstatSync(fd);
|
|
227
|
+
if (after.size !== status.size || after.mtimeMs !== status.mtimeMs || after.ctimeMs !== status.ctimeMs) throw new Error("A system font changed while indexing; reload the font service.");
|
|
228
|
+
} finally {
|
|
229
|
+
closeSync(fd);
|
|
230
|
+
}
|
|
231
|
+
} catch (error) {
|
|
232
|
+
if (absent(error)) return [];
|
|
233
|
+
throw error;
|
|
234
|
+
}
|
|
235
|
+
let faces;
|
|
236
|
+
try {
|
|
237
|
+
const parsed = create(bytes);
|
|
238
|
+
faces = ("fonts" in parsed ? parsed.fonts : [parsed]).map((font, faceIndex) => {
|
|
239
|
+
const names = [
|
|
240
|
+
"fontFamily",
|
|
241
|
+
"preferredFamily",
|
|
242
|
+
"fullName",
|
|
243
|
+
"postscriptName"
|
|
244
|
+
].flatMap((key) => Object.values(font.name?.records[key] ?? {})).filter((name) => typeof name === "string");
|
|
245
|
+
const aliases = [...new Set([
|
|
246
|
+
...names,
|
|
247
|
+
font.familyName,
|
|
248
|
+
font.fullName,
|
|
249
|
+
font.postscriptName
|
|
250
|
+
].filter((name) => Boolean(name)).map(normalize))];
|
|
251
|
+
return {
|
|
252
|
+
path,
|
|
253
|
+
size: status.size,
|
|
254
|
+
mtimeMs: status.mtimeMs,
|
|
255
|
+
ctimeMs: status.ctimeMs,
|
|
256
|
+
dev: status.dev,
|
|
257
|
+
ino: status.ino,
|
|
258
|
+
faceIndex,
|
|
259
|
+
family: font.familyName,
|
|
260
|
+
style: font.subfamilyName,
|
|
261
|
+
aliases,
|
|
262
|
+
...faceMetrics(font),
|
|
263
|
+
italic: font.italicAngle !== 0,
|
|
264
|
+
postscriptName: font.postscriptName
|
|
265
|
+
};
|
|
266
|
+
});
|
|
267
|
+
} catch {
|
|
268
|
+
return [];
|
|
269
|
+
}
|
|
270
|
+
return faces;
|
|
271
|
+
}
|
|
272
|
+
function regionalPriority(face, language) {
|
|
273
|
+
const locale = language.toLowerCase();
|
|
274
|
+
const preferred = locale.startsWith("ja") ? ["jp"] : locale.startsWith("ko") ? ["kr"] : locale.startsWith("zh") ? /hant|tw|hk|mo/.test(locale) ? ["tc", "hk"] : ["sc"] : [];
|
|
275
|
+
if (preferred.length === 0) return 0;
|
|
276
|
+
const region = `${face.family} ${face.postscriptName} ${basename(face.path)}`.toLowerCase().match(/(?:cjk|[\s_-])(sc|tc|jp|kr|hk)(?=[\s_.-]|$)/)?.[1];
|
|
277
|
+
return region === void 0 ? 1 : preferred.includes(region) ? 0 : 2;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Snapshot eligible local font metadata without retaining font bytes or decoding glyph coverage.
|
|
281
|
+
* @param options - Host font roots and physical file limits.
|
|
282
|
+
* @returns metadata reused for the converter lifetime; recreate it after changing installed fonts.
|
|
283
|
+
*/
|
|
284
|
+
function indexSystemFonts(options) {
|
|
285
|
+
return fontPaths(options.directories, options.maxFiles).flatMap((path) => inspect(path, options.maxFileBytes));
|
|
286
|
+
}
|
|
287
|
+
/** Conversion-local glyph coverage over the converter's first metadata snapshot. */
|
|
288
|
+
var SystemFontCatalog = class {
|
|
289
|
+
options;
|
|
290
|
+
faces;
|
|
291
|
+
/**
|
|
292
|
+
* @param options - Host metadata snapshot and fallback families.
|
|
293
|
+
*/
|
|
294
|
+
constructor(options) {
|
|
295
|
+
this.options = options;
|
|
296
|
+
this.faces = options.faces.map((face) => ({ ...face }));
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Find installed faces covering the requested family or missing characters.
|
|
300
|
+
* Exact families precede configured alternatives, symbol families for missing symbols,
|
|
301
|
+
* generic families, then other glyph-covering faces.
|
|
302
|
+
* @param request - VCL family/style attributes and Unicode scalars missing from its current font.
|
|
303
|
+
* @param signal - cancellation checked between synchronous font reads.
|
|
304
|
+
* @returns selected physical files, deduplicated across collection faces; absent glyphs remain unresolved.
|
|
305
|
+
* @throws if an indexed font changes or cannot be read during glyph matching.
|
|
306
|
+
*/
|
|
307
|
+
match(request, signal) {
|
|
308
|
+
signal.throwIfAborted();
|
|
309
|
+
const requested = request.family.split(";").map((family) => family.trim()).filter(Boolean);
|
|
310
|
+
const primary = requested[0];
|
|
311
|
+
let missingFamily;
|
|
312
|
+
if (primary !== void 0 && !GENERIC_FAMILIES.has(normalize(primary)) && !this.faces.some((face) => face.aliases.includes(normalize(primary)))) missingFamily = primary;
|
|
313
|
+
const priority = fontFamilyPriority(requested, this.options.fallbackFamilies, request.pitch, request.codePoints.some((point) => /\p{Symbol}/u.test(String.fromCodePoint(point)))).map(normalize);
|
|
314
|
+
const missing = new Set(request.codePoints);
|
|
315
|
+
const ranked = this.faces.map((face) => {
|
|
316
|
+
const rank = priority.findIndex((family) => face.aliases.includes(family));
|
|
317
|
+
const region = regionalPriority(face, request.language);
|
|
318
|
+
const style = (request.style && normalize(request.style) === normalize(face.style) ? -1 : 0) + (request.italic === 3 || request.italic !== 0 === face.italic ? 0 : 100) + (request.pitch === 0 || request.pitch === 1 === face.fixed ? 0 : 50) + Math.abs((VCL_WEIGHTS[request.weight] ?? 400) - face.weight) / 100 + (request.width === 0 ? 0 : Math.abs(request.width - face.width));
|
|
319
|
+
return {
|
|
320
|
+
face,
|
|
321
|
+
rank: rank < 0 ? priority.length : rank,
|
|
322
|
+
region,
|
|
323
|
+
style
|
|
324
|
+
};
|
|
325
|
+
}).sort((left, right) => left.rank - right.rank || left.region - right.region || left.style - right.style || left.face.path.localeCompare(right.face.path, "en") || left.face.faceIndex - right.face.faceIndex);
|
|
326
|
+
const selected = [];
|
|
327
|
+
const files = /* @__PURE__ */ new Set();
|
|
328
|
+
for (const { face } of ranked) {
|
|
329
|
+
signal.throwIfAborted();
|
|
330
|
+
const covered = covers(face, [...missing]);
|
|
331
|
+
if (missing.size > 0 && covered.length === 0) continue;
|
|
332
|
+
if (!files.has(face.path)) {
|
|
333
|
+
selected.push(face);
|
|
334
|
+
files.add(face.path);
|
|
335
|
+
}
|
|
336
|
+
for (const point of covered) missing.delete(point);
|
|
337
|
+
if (missing.size === 0) break;
|
|
338
|
+
}
|
|
339
|
+
return {
|
|
340
|
+
fonts: selected,
|
|
341
|
+
...missingFamily === void 0 ? {} : { missingFamily },
|
|
342
|
+
...missing.size === 0 ? {} : { unresolvedCodePoints: [...missing] }
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
};
|
|
346
|
+
/**
|
|
347
|
+
* Read the unchanged indexed regular file; reject concurrent replacement or truncation.
|
|
348
|
+
* @param face - Indexed face metadata whose identity and timestamps must still match the file.
|
|
349
|
+
* @returns the complete original font bytes.
|
|
350
|
+
* @throws when the file changed, was replaced, or was truncated since indexing.
|
|
351
|
+
*/
|
|
352
|
+
function readFont(face) {
|
|
353
|
+
const fd = openSync(face.path, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
|
|
354
|
+
try {
|
|
355
|
+
const before = fstatSync(fd);
|
|
356
|
+
if (!before.isFile() || STAT_KEYS.some((key) => before[key] !== face[key])) throw new Error("An indexed font changed; recreate the converter.");
|
|
357
|
+
const bytes = Buffer.alloc(face.size);
|
|
358
|
+
for (let offset = 0; offset < bytes.length;) {
|
|
359
|
+
const count = readSync(fd, bytes, offset, bytes.length - offset, offset);
|
|
360
|
+
if (!count) throw new Error("An indexed font was truncated.");
|
|
361
|
+
offset += count;
|
|
362
|
+
}
|
|
363
|
+
const after = fstatSync(fd);
|
|
364
|
+
if (STAT_KEYS.some((key) => after[key] !== face[key])) throw new Error("An indexed font changed while reading.");
|
|
365
|
+
return bytes;
|
|
366
|
+
} finally {
|
|
367
|
+
closeSync(fd);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
//#endregion
|
|
371
|
+
//#region lib/types/ooxml.js
|
|
372
|
+
/** Bounded OOXML inspection and declared font diagnostics, using maintained ZIP/XML parsers. */
|
|
373
|
+
const MAIN_PARTS = {
|
|
374
|
+
odt: ["content.xml", "application/vnd.oasis.opendocument.text"],
|
|
375
|
+
ods: ["content.xml", "application/vnd.oasis.opendocument.spreadsheet"],
|
|
376
|
+
odp: ["content.xml", "application/vnd.oasis.opendocument.presentation"],
|
|
377
|
+
docx: ["word/document.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"],
|
|
378
|
+
xlsx: ["xl/workbook.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"],
|
|
379
|
+
pptx: ["ppt/presentation.xml", "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"]
|
|
380
|
+
};
|
|
381
|
+
/**
|
|
382
|
+
* @param character - One code point as yielded by iteration over a string.
|
|
383
|
+
* @returns the Unicode scalar the character encodes; iteration never yields an empty string.
|
|
384
|
+
*/
|
|
385
|
+
function codePointOf(character) {
|
|
386
|
+
return character.codePointAt(0);
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Validate ZIP size and membership before decoding selected document XML.
|
|
390
|
+
* @param bytes - Complete source document bytes.
|
|
391
|
+
* @param extension - Input extension, which selects the main document part.
|
|
392
|
+
* @param limits - Archive entry and declared uncompressed byte limits.
|
|
393
|
+
* @returns declared font families and the scalar values readable document XML declares.
|
|
394
|
+
* @throws ConversionError when the extension is unsupported or the archive violates its limits.
|
|
395
|
+
*/
|
|
396
|
+
function inspectDocument$1(bytes, extension, limits) {
|
|
397
|
+
const main = MAIN_PARTS[extension];
|
|
398
|
+
if (!main) throw new ConversionError("unsupported-format", "Input extension must be docx, xlsx, or pptx.");
|
|
399
|
+
const odf = [
|
|
400
|
+
"odt",
|
|
401
|
+
"ods",
|
|
402
|
+
"odp"
|
|
403
|
+
].includes(extension);
|
|
404
|
+
const names = /* @__PURE__ */ new Set();
|
|
405
|
+
let total = 0;
|
|
406
|
+
let files;
|
|
407
|
+
try {
|
|
408
|
+
files = unzipSync(bytes, { filter(entry) {
|
|
409
|
+
total += entry.originalSize;
|
|
410
|
+
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.");
|
|
411
|
+
names.add(entry.name);
|
|
412
|
+
if (odf) return [
|
|
413
|
+
"mimetype",
|
|
414
|
+
"content.xml",
|
|
415
|
+
"styles.xml",
|
|
416
|
+
"META-INF/manifest.xml"
|
|
417
|
+
].includes(entry.name);
|
|
418
|
+
return entry.name === "[Content_Types].xml" || /^(word|xl|ppt)\/.*\.xml$/.test(entry.name) && !entry.name.endsWith("/fontTable.xml") && !entry.name.includes("/theme/");
|
|
419
|
+
} });
|
|
420
|
+
} catch (cause) {
|
|
421
|
+
throw new ConversionError("invalid-document", "Input is not a supported, bounded OOXML archive.", { cause });
|
|
422
|
+
}
|
|
423
|
+
const contentTypes = files["[Content_Types].xml"];
|
|
424
|
+
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.`);
|
|
425
|
+
const families = /* @__PURE__ */ new Map();
|
|
426
|
+
const codePoints = /* @__PURE__ */ new Set();
|
|
427
|
+
for (const [name, data] of Object.entries(files)) {
|
|
428
|
+
if (name === "[Content_Types].xml" || name === "mimetype" || name === "META-INF/manifest.xml") continue;
|
|
429
|
+
const partFamilies = [];
|
|
430
|
+
const partPoints = /* @__PURE__ */ new Set();
|
|
431
|
+
const parser = new SaxesParser({ xmlns: true });
|
|
432
|
+
parser.on("opentag", (tag) => {
|
|
433
|
+
const word = /wordprocessingml\/(?:2006\/)?main$/.test(tag.uri) && tag.local === "rFonts";
|
|
434
|
+
const drawing = /drawingml\/(?:2006\/)?main$/.test(tag.uri);
|
|
435
|
+
const sheet = /spreadsheetml\/(?:2006\/)?main$/.test(tag.uri) && tag.local === "name";
|
|
436
|
+
for (const attribute of Object.values(tag.attributes)) {
|
|
437
|
+
if (odf && attribute.local === "font-family") partFamilies.push(attribute.value.replace(/^['"]|['"]$/g, ""));
|
|
438
|
+
if (word && [
|
|
439
|
+
"ascii",
|
|
440
|
+
"hAnsi",
|
|
441
|
+
"eastAsia",
|
|
442
|
+
"cs"
|
|
443
|
+
].includes(attribute.local) || drawing && attribute.local === "typeface" || sheet && attribute.local === "val") partFamilies.push(attribute.value);
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
parser.on("text", (text) => {
|
|
447
|
+
for (const char of text) if (!/\s/u.test(char)) partPoints.add(codePointOf(char));
|
|
448
|
+
});
|
|
449
|
+
const encoding = data[0] === 255 && data[1] === 254 ? "utf-16le" : data[0] === 254 && data[1] === 255 ? "utf-16be" : "utf-8";
|
|
450
|
+
try {
|
|
451
|
+
parser.write(new TextDecoder(encoding).decode(data)).close();
|
|
452
|
+
} catch {
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
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);
|
|
456
|
+
for (const point of partPoints) codePoints.add(point);
|
|
457
|
+
}
|
|
458
|
+
return {
|
|
459
|
+
families,
|
|
460
|
+
codePoints: [...codePoints]
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
//#endregion
|
|
464
|
+
//#region lib/types/document.js
|
|
465
|
+
/** Select bounded OOXML inspection or a legacy Office compound-file import. */
|
|
466
|
+
/** Input suffixes accepted by the public converter. */
|
|
467
|
+
const DOCUMENT_EXTENSIONS = [
|
|
468
|
+
"doc",
|
|
469
|
+
"docx",
|
|
470
|
+
"odt",
|
|
471
|
+
"xls",
|
|
472
|
+
"xlsx",
|
|
473
|
+
"ods",
|
|
474
|
+
"ppt",
|
|
475
|
+
"pptx",
|
|
476
|
+
"odp"
|
|
477
|
+
];
|
|
478
|
+
const COMPOUND_SIGNATURE = [
|
|
479
|
+
208,
|
|
480
|
+
207,
|
|
481
|
+
17,
|
|
482
|
+
224,
|
|
483
|
+
161,
|
|
484
|
+
177,
|
|
485
|
+
26,
|
|
486
|
+
225
|
|
487
|
+
];
|
|
488
|
+
/**
|
|
489
|
+
* Inspect the input container before invoking LibreOffice's document importer.
|
|
490
|
+
* Compound-file streams and legacy font tables are interpreted by LibreOffice;
|
|
491
|
+
* they do not supply the API's OOXML font diagnostics.
|
|
492
|
+
* @param bytes - Source bytes already bounded by maxInputBytes.
|
|
493
|
+
* @param extension - Lowercase source suffix.
|
|
494
|
+
* @param limits - Limits applied to ZIP-based document contents.
|
|
495
|
+
* @returns OOXML font metadata, or empty diagnostics for a binary document.
|
|
496
|
+
*/
|
|
497
|
+
function inspectDocument(bytes, extension, limits) {
|
|
498
|
+
if (!DOCUMENT_EXTENSIONS.includes(extension)) throw new ConversionError("unsupported-format", `Input extension must be ${DOCUMENT_EXTENSIONS.join(", ")}.`);
|
|
499
|
+
if ([
|
|
500
|
+
"docx",
|
|
501
|
+
"xlsx",
|
|
502
|
+
"pptx",
|
|
503
|
+
"odt",
|
|
504
|
+
"ods",
|
|
505
|
+
"odp"
|
|
506
|
+
].includes(extension)) return inspectDocument$1(bytes, extension, limits);
|
|
507
|
+
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.");
|
|
508
|
+
const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
509
|
+
const version = header.getUint16(26, true);
|
|
510
|
+
const sectorShift = header.getUint16(30, true);
|
|
511
|
+
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.");
|
|
512
|
+
return {
|
|
513
|
+
families: /* @__PURE__ */ new Map(),
|
|
514
|
+
codePoints: []
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
//#endregion
|
|
518
|
+
//#region lib/types/font-loader.js
|
|
519
|
+
/** Conversion-local font imports backed by a factory-lifetime match cache. */
|
|
520
|
+
const faceKey = (face) => `${face.path}\0${face.faceIndex}`;
|
|
521
|
+
const requestKey = ({ codePoints: _codePoints, ...request }) => JSON.stringify(request);
|
|
522
|
+
/** Build one operation's loader over a factory-owned immutable font snapshot. */
|
|
523
|
+
function createFontLoader(options, document, install, faces, cache = []) {
|
|
524
|
+
const catalog = new SystemFontCatalog({
|
|
525
|
+
faces,
|
|
526
|
+
fallbackFamilies: options.fontFallbacks
|
|
527
|
+
});
|
|
528
|
+
const byFace = new Map(faces.map((face) => [faceKey(face), face]));
|
|
529
|
+
const matches = /* @__PURE__ */ new Map();
|
|
530
|
+
for (const entry of cache.slice(-options.maxFontResolutionEntries)) matches.set(entry.key, {
|
|
531
|
+
...entry,
|
|
532
|
+
codePoints: [...entry.codePoints],
|
|
533
|
+
faces: entry.faces.map((face) => ({ ...face }))
|
|
534
|
+
});
|
|
535
|
+
const loaded = /* @__PURE__ */ new Map();
|
|
536
|
+
const resolved = /* @__PURE__ */ new Map();
|
|
537
|
+
const missing = /* @__PURE__ */ new Map();
|
|
538
|
+
const substitutions = /* @__PURE__ */ new Map();
|
|
539
|
+
const signal = new AbortController().signal;
|
|
540
|
+
let bytes = 0;
|
|
541
|
+
function retain(entry) {
|
|
542
|
+
matches.delete(entry.key);
|
|
543
|
+
matches.set(entry.key, entry);
|
|
544
|
+
while (matches.size > options.maxFontResolutionEntries) matches.delete(matches.keys().next().value);
|
|
545
|
+
}
|
|
546
|
+
function cachedMatch(request) {
|
|
547
|
+
const key = requestKey(request);
|
|
548
|
+
const points = [...new Set(request.codePoints)].sort((left, right) => left - right);
|
|
549
|
+
const prior = matches.get(key);
|
|
550
|
+
if (prior && (points.length === 0 && prior.emptyRequest || points.every((point) => prior.codePoints.includes(point)))) {
|
|
551
|
+
retain(prior);
|
|
552
|
+
return {
|
|
553
|
+
fonts: prior.faces.map((reference) => byFace.get(faceKey(reference))).filter((face) => face !== void 0),
|
|
554
|
+
...prior.missingFamily === void 0 ? {} : { missingFamily: prior.missingFamily }
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
const unknown = prior === void 0 ? points : points.filter((point) => !prior.codePoints.includes(point));
|
|
558
|
+
const current = catalog.match({
|
|
559
|
+
...request,
|
|
560
|
+
codePoints: points.length === 0 ? [] : unknown
|
|
561
|
+
}, signal);
|
|
562
|
+
const references = new Map((prior?.faces ?? []).map((face) => [faceKey(face), face]));
|
|
563
|
+
for (const face of current.fonts) references.set(faceKey(face), {
|
|
564
|
+
path: face.path,
|
|
565
|
+
faceIndex: face.faceIndex
|
|
566
|
+
});
|
|
567
|
+
const missingFamily = prior?.missingFamily ?? current.missingFamily;
|
|
568
|
+
const entry = {
|
|
569
|
+
key,
|
|
570
|
+
codePoints: [.../* @__PURE__ */ new Set([...prior?.codePoints ?? [], ...points])].sort((left, right) => left - right),
|
|
571
|
+
emptyRequest: prior?.emptyRequest === true || points.length === 0,
|
|
572
|
+
faces: [...references.values()],
|
|
573
|
+
...missingFamily === void 0 ? {} : { missingFamily }
|
|
574
|
+
};
|
|
575
|
+
retain(entry);
|
|
576
|
+
return {
|
|
577
|
+
fonts: entry.faces.map((reference) => byFace.get(faceKey(reference))).filter((face) => face !== void 0),
|
|
578
|
+
...entry.missingFamily === void 0 ? {} : { missingFamily: entry.missingFamily }
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
return {
|
|
582
|
+
get missingFonts() {
|
|
583
|
+
return [...missing.values()];
|
|
584
|
+
},
|
|
585
|
+
get substitutions() {
|
|
586
|
+
return [...substitutions.values()];
|
|
587
|
+
},
|
|
588
|
+
get files() {
|
|
589
|
+
return [...loaded.values()];
|
|
590
|
+
},
|
|
591
|
+
get cacheEntries() {
|
|
592
|
+
return [...matches.values()];
|
|
593
|
+
},
|
|
594
|
+
resolve(request) {
|
|
595
|
+
const key = JSON.stringify(request);
|
|
596
|
+
const cached = resolved.get(key);
|
|
597
|
+
if (cached) return cached;
|
|
598
|
+
const match = cachedMatch(request);
|
|
599
|
+
if (match.missingFamily && document.families.has(normalize(match.missingFamily))) {
|
|
600
|
+
const family = normalize(match.missingFamily);
|
|
601
|
+
missing.set(family, match.missingFamily);
|
|
602
|
+
if (match.fonts[0]) substitutions.set(family, {
|
|
603
|
+
family: match.missingFamily,
|
|
604
|
+
substitute: match.fonts[0].family
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
const paths = match.fonts.map((face) => {
|
|
608
|
+
const installed = loaded.get(face.path);
|
|
609
|
+
if (installed !== void 0) return installed;
|
|
610
|
+
if (bytes + face.size > options.maxLoadedFontBytes) throw new Error("Imported fonts exceed maxLoadedFontBytes.");
|
|
611
|
+
const path = install(`${loaded.size}${extname(face.path)}`, readFont(face));
|
|
612
|
+
bytes += face.size;
|
|
613
|
+
loaded.set(face.path, path);
|
|
614
|
+
return path;
|
|
615
|
+
});
|
|
616
|
+
resolved.set(key, paths);
|
|
617
|
+
return paths;
|
|
618
|
+
}
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
/** Supply native imports and seed WASM's first usable default font. */
|
|
622
|
+
function preloadFonts(loader, options, document, native = false) {
|
|
623
|
+
const families = [
|
|
624
|
+
...options.initialFontFamilies,
|
|
625
|
+
...native ? [...document.families.values()] : [],
|
|
626
|
+
"sans-serif"
|
|
627
|
+
];
|
|
628
|
+
for (const family of families) loader.resolve({
|
|
629
|
+
family,
|
|
630
|
+
style: "",
|
|
631
|
+
weight: 5,
|
|
632
|
+
italic: 0,
|
|
633
|
+
width: 5,
|
|
634
|
+
pitch: 0,
|
|
635
|
+
language: "",
|
|
636
|
+
codePoints: native ? document.codePoints : []
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
/** Fontconfig XML restricts WASM discovery to imported originals in MEMFS. */
|
|
640
|
+
function memoryFontConfig(families, requested = []) {
|
|
641
|
+
const escape = (value) => value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("'", "'");
|
|
642
|
+
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) => {
|
|
643
|
+
const alternatives = fontFamilyPriority([name], families).filter((family) => normalize(family) !== normalize(name));
|
|
644
|
+
return `<alias><family>${escape(name)}</family><accept>${alternatives.map((family) => `<family>${escape(family)}</family>`).join("")}</accept></alias>`;
|
|
645
|
+
}).join("")}</fontconfig>`;
|
|
646
|
+
}
|
|
647
|
+
//#endregion
|
|
648
|
+
//#region lib/types/office-fonts.js
|
|
649
|
+
/** Curated fonts discovered from a user's Microsoft Office installation. */
|
|
650
|
+
const FONT_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
651
|
+
".ttf",
|
|
652
|
+
".otf",
|
|
653
|
+
".ttc",
|
|
654
|
+
".otc",
|
|
655
|
+
".dfont"
|
|
656
|
+
]);
|
|
657
|
+
const OFFICE_FONT_FILE = /^(?:aptos(?:[- ].*)?|arial(?:bd|bi|i)?|calibri(?:b|i|z|l|li)?|cambria(?:b|i|z)?|cour(?:bd|bi|i)?|deng(?:b|l)?|fangsong|kaiti|msjh(?:bd)?|msyh(?:bd|l)?|segoeui(?:b|i|z|l|li|sb|sbi|sl|sli)?|simhei|simsunb?|symbol|times(?:bd|bi|i)?|wingdings(?: [23])?|wingdng[23])\.(?:ttf|otf|ttc|otc)$/iu;
|
|
658
|
+
const FAMILIES = new Set([
|
|
659
|
+
"aptos",
|
|
660
|
+
"aptos display",
|
|
661
|
+
"aptos narrow",
|
|
662
|
+
"arial",
|
|
663
|
+
"calibri",
|
|
664
|
+
"calibri light",
|
|
665
|
+
"cambria",
|
|
666
|
+
"cambria math",
|
|
667
|
+
"courier new",
|
|
668
|
+
"dengxian",
|
|
669
|
+
"fangsong",
|
|
670
|
+
"kaiti",
|
|
671
|
+
"microsoft jhenghei",
|
|
672
|
+
"microsoft jhenghei ui",
|
|
673
|
+
"microsoft yahei",
|
|
674
|
+
"microsoft yahei ui",
|
|
675
|
+
"nsimsun",
|
|
676
|
+
"segoe ui",
|
|
677
|
+
"simhei",
|
|
678
|
+
"simsun",
|
|
679
|
+
"symbol",
|
|
680
|
+
"times new roman",
|
|
681
|
+
"wingdings",
|
|
682
|
+
"wingdings 2",
|
|
683
|
+
"wingdings 3"
|
|
684
|
+
].map(normalize));
|
|
685
|
+
/** @returns whether parsed font names belong to the curated Office compatibility set. */
|
|
686
|
+
function officeFontFace(face) {
|
|
687
|
+
return face.aliases.some((alias) => FAMILIES.has(alias));
|
|
688
|
+
}
|
|
689
|
+
function directory(path) {
|
|
690
|
+
try {
|
|
691
|
+
return statSync(path).isDirectory();
|
|
692
|
+
} catch (error) {
|
|
693
|
+
if (absent(error)) return false;
|
|
694
|
+
throw error;
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
function files(root, recursive, namesOnly = true) {
|
|
698
|
+
const pending = [root], result = [];
|
|
699
|
+
for (let current = pending.pop(); current !== void 0; current = pending.pop()) {
|
|
700
|
+
let entries;
|
|
701
|
+
try {
|
|
702
|
+
entries = readdirSync(current, { withFileTypes: true });
|
|
703
|
+
} catch (error) {
|
|
704
|
+
/* v8 ignore next -- Optional Office cache disappearance is also covered by system-font absence handling. */
|
|
705
|
+
if (absent(error)) continue;
|
|
706
|
+
throw error;
|
|
707
|
+
}
|
|
708
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name, "en"))) if (entry.isDirectory()) {
|
|
709
|
+
if (recursive && entry.name !== "PreviewFont") pending.push(join(current, entry.name));
|
|
710
|
+
} else if (entry.isFile() && FONT_EXTENSIONS.has(extname(entry.name).toLowerCase()) && (!namesOnly || OFFICE_FONT_FILE.test(entry.name))) result.push(join(current, entry.name));
|
|
711
|
+
}
|
|
712
|
+
return result;
|
|
713
|
+
}
|
|
714
|
+
/** Find compatibility font files without exposing their paths outside the font Worker. */
|
|
715
|
+
function officeFontFiles(platform = process.platform, home = homedir(), env = process.env, applicationRoots = ["/Applications", posix.join(home, "Applications")]) {
|
|
716
|
+
const bundled = platform === "darwin" ? [
|
|
717
|
+
"Microsoft Word",
|
|
718
|
+
"Microsoft Excel",
|
|
719
|
+
"Microsoft PowerPoint"
|
|
720
|
+
].flatMap((app) => applicationRoots.map((root) => posix.join(root, `${app}.app/Contents/Resources/DFonts`))).find(directory) : platform === "win32" ? [env.ProgramFiles, env["ProgramFiles(x86)"]].filter((root) => Boolean(root)).map((root) => win32.join(root, "Microsoft Office", "root", "vfs", "Fonts", "private")).find(directory) : void 0;
|
|
721
|
+
const cloud = platform === "darwin" ? posix.join(home, "Library/Group Containers/UBF8T346G9.Office/FontCache") : platform === "win32" ? win32.join(env.LOCALAPPDATA ?? win32.join(home, "AppData", "Local"), "Microsoft", "FontCache") : void 0;
|
|
722
|
+
const ordered = [...bundled === void 0 ? [] : files(bundled, false).sort(), ...cloud === void 0 ? [] : files(cloud, true, false).sort((a, b) => b.localeCompare(a, "en", { numeric: true }))];
|
|
723
|
+
const unique = /* @__PURE__ */ new Map();
|
|
724
|
+
for (const file of ordered) {
|
|
725
|
+
const portable = file.replaceAll("\\", "/");
|
|
726
|
+
const name = portable.slice(portable.lastIndexOf("/") + 1).toLowerCase();
|
|
727
|
+
if (!unique.has(name)) unique.set(name, file);
|
|
728
|
+
}
|
|
729
|
+
return [...unique.values()];
|
|
730
|
+
}
|
|
731
|
+
//#endregion
|
|
732
|
+
//#region lib/types/font-full.js
|
|
733
|
+
/** Whole fonts for engines such as PDFium that perform their own glyph mapping. */
|
|
734
|
+
function fontFileFormat(bytes) {
|
|
735
|
+
const magic = new TextDecoder().decode(bytes.subarray(0, 4));
|
|
736
|
+
if (magic === "ttcf") return "ttc";
|
|
737
|
+
if (magic === "OTTO") return "otf";
|
|
738
|
+
if (magic === "true" || bytes[0] === 0 && bytes[1] === 1 && bytes[2] === 0 && bytes[3] === 0) return "ttf";
|
|
739
|
+
throw new Error("The full font asset is not an sfnt font or collection.");
|
|
740
|
+
}
|
|
741
|
+
/** Keep full names, encoding tables and glyphs. Apple dfont containers expose one complete sfnt resource. */
|
|
742
|
+
function fullFontFile(face) {
|
|
743
|
+
const original = readFont(face);
|
|
744
|
+
const sourceHash = createHash("sha256").update(original).digest("hex");
|
|
745
|
+
let bytes = original;
|
|
746
|
+
/* v8 ignore next -- Apple dfont resource extraction is exercised by matching-host font qualification. */
|
|
747
|
+
if (extname(face.path).toLowerCase() === ".dfont") bytes = indexedFace(create(original), face).stream.buffer;
|
|
748
|
+
return {
|
|
749
|
+
bytes,
|
|
750
|
+
sourceHash,
|
|
751
|
+
format: fontFileFormat(bytes)
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
/** Mount a fixed bounded set before PDFium performs its first installed-font enumeration. */
|
|
755
|
+
function preloadPdfFonts(options, faces, install) {
|
|
756
|
+
const catalog = new SystemFontCatalog({
|
|
757
|
+
faces,
|
|
758
|
+
fallbackFamilies: options.fontFallbacks
|
|
759
|
+
});
|
|
760
|
+
const files = /* @__PURE__ */ new Set();
|
|
761
|
+
const assets = /* @__PURE__ */ new Set();
|
|
762
|
+
let total = 0;
|
|
763
|
+
const families = [.../* @__PURE__ */ new Set([
|
|
764
|
+
...options.initialFontFamilies,
|
|
765
|
+
...options.fontFallbacks.flat(),
|
|
766
|
+
"sans-serif",
|
|
767
|
+
"serif",
|
|
768
|
+
"monospace"
|
|
769
|
+
])];
|
|
770
|
+
for (const family of families) {
|
|
771
|
+
const result = catalog.match({
|
|
772
|
+
family,
|
|
773
|
+
style: "",
|
|
774
|
+
weight: 5,
|
|
775
|
+
italic: 0,
|
|
776
|
+
width: 5,
|
|
777
|
+
pitch: 0,
|
|
778
|
+
language: "",
|
|
779
|
+
codePoints: []
|
|
780
|
+
}, new AbortController().signal);
|
|
781
|
+
for (const face of result.fonts) {
|
|
782
|
+
/* v8 ignore next -- Apple dfont face identity is covered by matching-host font qualification. */
|
|
783
|
+
const physical = `${face.path}#${extname(face.path).toLowerCase() === ".dfont" ? face.faceIndex : ""}`;
|
|
784
|
+
if (files.has(physical)) continue;
|
|
785
|
+
files.add(physical);
|
|
786
|
+
const { bytes, format } = fullFontFile(face);
|
|
787
|
+
const id = createHash("sha256").update(bytes).digest("hex");
|
|
788
|
+
if (assets.has(id)) continue;
|
|
789
|
+
if (total + bytes.length > options.maxLoadedFontBytes) throw new Error("PDF full-font preload exceeds maxLoadedFontBytes.");
|
|
790
|
+
install(`${id}.${format}`, bytes);
|
|
791
|
+
total += bytes.length;
|
|
792
|
+
assets.add(id);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
//#endregion
|
|
797
|
+
//#region lib/types/profile.js
|
|
798
|
+
/** Private headless profile used by both native and WASM conversions. */
|
|
799
|
+
/**
|
|
800
|
+
* CSV selection is checked by the engine wrapper before saving; suppress the interactive warning.
|
|
801
|
+
* @param fontNodes - Escaped VCL font-substitution nodes, or an empty string for WASM.
|
|
802
|
+
* @returns The per-operation registry XML; macro execution is independently disabled at load.
|
|
803
|
+
*/
|
|
804
|
+
function profileXml(fontNodes = "") {
|
|
805
|
+
return `<?xml version="1.0" encoding="UTF-8"?><oor:items xmlns:oor="http://openoffice.org/2001/registry"><item oor:path="/org.openoffice.Office.Calc/Input"><prop oor:name="WarnActiveSheet" oor:op="fuse"><value>false</value></prop></item><item oor:path="/org.openoffice.VCL/FontSubstitutions/en">${fontNodes}</item></oor:items>\n`;
|
|
806
|
+
}
|
|
807
|
+
//#endregion
|
|
808
|
+
//#region lib/types/operations.js
|
|
809
|
+
/**
|
|
810
|
+
* Reject an engine output with an incorrect container signature.
|
|
811
|
+
* @param bytes - Complete bounded output.
|
|
812
|
+
* @param format - Requested output suffix.
|
|
813
|
+
*/
|
|
814
|
+
function validateOutput(bytes, format) {
|
|
815
|
+
if (format === "pdf" && new TextDecoder().decode(bytes.subarray(0, 5)) !== "%PDF-") throw new ConversionError("invalid-output", "LibreOffice did not produce a PDF.");
|
|
816
|
+
if ([
|
|
817
|
+
"docx",
|
|
818
|
+
"xlsx",
|
|
819
|
+
"pptx",
|
|
820
|
+
"odt",
|
|
821
|
+
"ods",
|
|
822
|
+
"odp"
|
|
823
|
+
].includes(format) && (bytes[0] !== 80 || bytes[1] !== 75 || bytes[2] !== 3 || bytes[3] !== 4)) throw new ConversionError("invalid-output", `LibreOffice did not produce a ${format} archive.`);
|
|
824
|
+
}
|
|
825
|
+
//#endregion
|
|
826
|
+
//#region lib/types/wasm.js
|
|
827
|
+
/** Node-only LibreOffice module execution; the owner terminates this worker on cancellation. */
|
|
828
|
+
const require = createRequire(import.meta.url);
|
|
829
|
+
function engineError(module, office) {
|
|
830
|
+
const pointer = module.ccall("dsh_lok_error", "number", ["number"], [office]);
|
|
831
|
+
if (!pointer) return /* @__PURE__ */ new Error("LibreOffice WASM could not convert the document.");
|
|
832
|
+
try {
|
|
833
|
+
return new Error(module.UTF8ToString(pointer));
|
|
834
|
+
} finally {
|
|
835
|
+
module.ccall("free", null, ["number"], [pointer]);
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* @param loader - Loader the module's pre-run hook installs.
|
|
840
|
+
* @returns the initialized font loader.
|
|
841
|
+
* @throws when the module resolved without running its pre-run hook.
|
|
842
|
+
*/
|
|
843
|
+
function requiredFontLoader(loader) {
|
|
844
|
+
if (loader === void 0) throw new Error("LibreOffice initialized without its font loader.");
|
|
845
|
+
return loader;
|
|
846
|
+
}
|
|
847
|
+
/** A single module loader and owned session lifecycle for export and direct raster operations. */
|
|
848
|
+
async function withWasmSession(request, use) {
|
|
849
|
+
const { engine, bytes, extension, options, document: metadata, faces } = request;
|
|
850
|
+
const pdf = extension === "pdf";
|
|
851
|
+
let idleReady = false;
|
|
852
|
+
const factory = require(engine.loader);
|
|
853
|
+
const raw = readFileSync(engine.data);
|
|
854
|
+
const data = raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength);
|
|
855
|
+
let module;
|
|
856
|
+
let office = 0;
|
|
857
|
+
let document = 0;
|
|
858
|
+
let fontLoader;
|
|
859
|
+
let fatal = false;
|
|
860
|
+
let failure;
|
|
861
|
+
try {
|
|
862
|
+
module = await factory({
|
|
863
|
+
dshOnCallback(type, payload) {
|
|
864
|
+
if (type !== 16) return;
|
|
865
|
+
try {
|
|
866
|
+
const result = JSON.parse(payload);
|
|
867
|
+
if (result.commandName === ".uno:ReportWhenIdle" && result.idleID === "node-raster") idleReady = true;
|
|
868
|
+
} catch {}
|
|
869
|
+
},
|
|
870
|
+
noInitialRun: true,
|
|
871
|
+
mainScriptUrlOrBlob: engine.loader,
|
|
872
|
+
locateFile(name) {
|
|
873
|
+
const file = basename(name);
|
|
874
|
+
if (file === "soffice.wasm") return engine.wasm;
|
|
875
|
+
for (const asset of [
|
|
876
|
+
engine.loader,
|
|
877
|
+
engine.data,
|
|
878
|
+
engine.wasm,
|
|
879
|
+
engine.metadata
|
|
880
|
+
]) if (basename(asset) === file) return asset;
|
|
881
|
+
throw new Error(`LibreOffice requested an unlisted asset: ${file}`);
|
|
882
|
+
},
|
|
883
|
+
getPreloadedPackage: () => data,
|
|
884
|
+
dshResolveSystemFonts(request) {
|
|
885
|
+
if (!fontLoader) throw new Error("LibreOffice requested fonts before initializing MEMFS.");
|
|
886
|
+
return fontLoader.resolve(request);
|
|
887
|
+
},
|
|
888
|
+
preRun: [(loadedModule) => {
|
|
889
|
+
for (const path of [
|
|
890
|
+
"/dsh/profile/user",
|
|
891
|
+
"/dsh/font-cache",
|
|
892
|
+
"/dsh-fonts"
|
|
893
|
+
]) loadedModule.FS.mkdirTree(path);
|
|
894
|
+
loadedModule.FS.writeFile("/dsh/profile/user/registrymodifications.xcu", new TextEncoder().encode(profileXml()));
|
|
895
|
+
loadedModule.FS.writeFile("/dsh/fonts.conf", new TextEncoder().encode(memoryFontConfig(options.fontFallbacks, metadata.families.values())));
|
|
896
|
+
Object.assign(loadedModule.ENV, {
|
|
897
|
+
HOME: "/dsh/profile",
|
|
898
|
+
TMPDIR: "/tmp",
|
|
899
|
+
FONTCONFIG_FILE: "/dsh/fonts.conf",
|
|
900
|
+
LOK_HOST_ALLOWLIST: "^$"
|
|
901
|
+
});
|
|
902
|
+
fontLoader = createFontLoader(options, metadata, (name, bytes) => {
|
|
903
|
+
const path = `/dsh-fonts/${name}`;
|
|
904
|
+
loadedModule.FS.writeFile(path, bytes);
|
|
905
|
+
return path;
|
|
906
|
+
}, faces, request.fontCache);
|
|
907
|
+
if (pdf) {
|
|
908
|
+
loadedModule.FS.mkdirTree("/usr/share/fonts/dsh-pdfium");
|
|
909
|
+
preloadPdfFonts(options, faces, (name, bytes) => loadedModule.FS.writeFile(`/usr/share/fonts/dsh-pdfium/${name}`, bytes));
|
|
910
|
+
} else preloadFonts(fontLoader, options, metadata);
|
|
911
|
+
}],
|
|
912
|
+
onAbort() {
|
|
913
|
+
fatal = true;
|
|
914
|
+
},
|
|
915
|
+
print() {},
|
|
916
|
+
printErr() {}
|
|
917
|
+
});
|
|
918
|
+
const instance = module;
|
|
919
|
+
const input = `/dsh/document.${extension}`;
|
|
920
|
+
if (!pdf) instance.FS.writeFile(input, bytes);
|
|
921
|
+
if (pdf) {
|
|
922
|
+
const pointer = instance.ccall("malloc", "number", ["number"], [bytes.length]);
|
|
923
|
+
if (!pointer) throw engineError(instance, 0);
|
|
924
|
+
try {
|
|
925
|
+
new Uint8Array(instance.HEAPU32.buffer).set(bytes, pointer);
|
|
926
|
+
document = instance.ccall("dsh_pdf_open", "number", [
|
|
927
|
+
"number",
|
|
928
|
+
"number",
|
|
929
|
+
"string"
|
|
930
|
+
], [
|
|
931
|
+
pointer,
|
|
932
|
+
bytes.length,
|
|
933
|
+
""
|
|
934
|
+
]);
|
|
935
|
+
} finally {
|
|
936
|
+
instance.ccall("free", null, ["number"], [pointer]);
|
|
937
|
+
}
|
|
938
|
+
if (!document) throw engineError(instance, 0);
|
|
939
|
+
} else {
|
|
940
|
+
office = instance.ccall("dsh_lok_initialize", "number", ["string", "string"], [engine.programDirectory, "file:///dsh/profile"]);
|
|
941
|
+
if (!office) throw engineError(instance, 0);
|
|
942
|
+
document = instance.ccall("dsh_lok_document_load", "number", [
|
|
943
|
+
"number",
|
|
944
|
+
"string",
|
|
945
|
+
"string"
|
|
946
|
+
], [
|
|
947
|
+
office,
|
|
948
|
+
`file://${input}`,
|
|
949
|
+
"Batch=true,EnableMacrosExecution=false"
|
|
950
|
+
]);
|
|
951
|
+
if (!document) throw engineError(instance, office);
|
|
952
|
+
}
|
|
953
|
+
const result = await use({
|
|
954
|
+
module: instance,
|
|
955
|
+
office,
|
|
956
|
+
document,
|
|
957
|
+
pdf,
|
|
958
|
+
get missingFonts() {
|
|
959
|
+
return requiredFontLoader(fontLoader).missingFonts;
|
|
960
|
+
},
|
|
961
|
+
async idle() {
|
|
962
|
+
if (pdf) return;
|
|
963
|
+
idleReady = false;
|
|
964
|
+
if (!instance.ccall("dsh_lok_document_command", "number", [
|
|
965
|
+
"number",
|
|
966
|
+
"string",
|
|
967
|
+
"string"
|
|
968
|
+
], [
|
|
969
|
+
document,
|
|
970
|
+
".uno:ReportWhenIdle",
|
|
971
|
+
"{\"idleID\":{\"type\":\"string\",\"value\":\"node-raster\"}}"
|
|
972
|
+
])) throw engineError(instance, office);
|
|
973
|
+
const deadline = performance.now() + options.timeoutMs;
|
|
974
|
+
while (!idleReady) {
|
|
975
|
+
for (let i = 0; i < 8 && !idleReady; i++) {
|
|
976
|
+
const pending = instance.ccall("dsh_lok_pump", "number", [], []);
|
|
977
|
+
if (pending < 0) throw engineError(instance, office);
|
|
978
|
+
if (!pending) break;
|
|
979
|
+
}
|
|
980
|
+
if (performance.now() > deadline) throw new ConversionError("timeout", "LibreOffice did not reach its raster idle barrier.");
|
|
981
|
+
if (!idleReady) await new Promise((resolve) => setTimeout(resolve, 0));
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
});
|
|
985
|
+
request.onFontCache?.(requiredFontLoader(fontLoader).cacheEntries);
|
|
986
|
+
return result;
|
|
987
|
+
} catch (error) {
|
|
988
|
+
fatal ||= error instanceof WebAssembly.RuntimeError;
|
|
989
|
+
failure = error;
|
|
990
|
+
throw error;
|
|
991
|
+
} finally {
|
|
992
|
+
const errors = [];
|
|
993
|
+
if (module && !fatal) {
|
|
994
|
+
if (document) try {
|
|
995
|
+
if (!module.ccall(pdf ? "dsh_pdf_destroy" : "dsh_lok_document_destroy", "number", ["number"], [document])) throw engineError(module, office);
|
|
996
|
+
} catch (error) {
|
|
997
|
+
errors.push(error);
|
|
998
|
+
fatal ||= error instanceof WebAssembly.RuntimeError;
|
|
999
|
+
}
|
|
1000
|
+
if (office && !fatal) try {
|
|
1001
|
+
if (!module.ccall("dsh_lok_destroy", "number", ["number"], [office])) throw engineError(module, 0);
|
|
1002
|
+
} catch (error) {
|
|
1003
|
+
errors.push(error);
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
if (module) try {
|
|
1007
|
+
module.PThread.terminateAllThreads();
|
|
1008
|
+
} catch (error) {
|
|
1009
|
+
errors.push(error);
|
|
1010
|
+
}
|
|
1011
|
+
if (errors.length) throw new AggregateError(failure ? [failure, ...errors] : errors, "LibreOffice WASM cleanup failed.");
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
/** Convert bounded source bytes; return owned bytes only after engine teardown. */
|
|
1015
|
+
async function convertWithWasm(request) {
|
|
1016
|
+
return withWasmSession(request, (session) => {
|
|
1017
|
+
const { module, office, document } = session;
|
|
1018
|
+
const { options } = request;
|
|
1019
|
+
const operation = request.operation ?? {
|
|
1020
|
+
format: "pdf",
|
|
1021
|
+
recalculate: false
|
|
1022
|
+
};
|
|
1023
|
+
const output = `/dsh/output.${operation.format}`;
|
|
1024
|
+
const filterOptions = operation.format === "pdf" ? JSON.stringify({
|
|
1025
|
+
ExportBookmarks: {
|
|
1026
|
+
type: "boolean",
|
|
1027
|
+
value: "true"
|
|
1028
|
+
},
|
|
1029
|
+
ReduceImageResolution: {
|
|
1030
|
+
type: "boolean",
|
|
1031
|
+
value: "true"
|
|
1032
|
+
},
|
|
1033
|
+
MaxImageResolution: {
|
|
1034
|
+
type: "long",
|
|
1035
|
+
value: String(options.maxImageResolution)
|
|
1036
|
+
}
|
|
1037
|
+
}) : operation.format === "txt" ? "UTF8,LF" : "";
|
|
1038
|
+
if (!module.ccall("dsh_lok_document_export", "number", [
|
|
1039
|
+
"number",
|
|
1040
|
+
"number",
|
|
1041
|
+
"string",
|
|
1042
|
+
"string",
|
|
1043
|
+
"string",
|
|
1044
|
+
"number",
|
|
1045
|
+
"string"
|
|
1046
|
+
], [
|
|
1047
|
+
office,
|
|
1048
|
+
document,
|
|
1049
|
+
`file://${output}`,
|
|
1050
|
+
operation.format,
|
|
1051
|
+
filterOptions,
|
|
1052
|
+
Number(operation.recalculate),
|
|
1053
|
+
operation.sheet ?? ""
|
|
1054
|
+
])) throw engineError(module, office);
|
|
1055
|
+
if (!module.FS.analyzePath(output).exists) throw new ConversionError("invalid-output", "LibreOffice did not create its output.");
|
|
1056
|
+
const status = module.FS.stat(output);
|
|
1057
|
+
if (!module.FS.isFile(status.mode)) throw new ConversionError("invalid-output", "Generated output is not a regular file.");
|
|
1058
|
+
if (status.size > options.maxOutputBytes) throw new ConversionError("output-too-large", "Generated output exceeds its output byte limit.");
|
|
1059
|
+
const result = module.FS.readFile(output);
|
|
1060
|
+
validateOutput(result, operation.format);
|
|
1061
|
+
return {
|
|
1062
|
+
output: result,
|
|
1063
|
+
missingFonts: session.missingFonts
|
|
1064
|
+
};
|
|
1065
|
+
});
|
|
1066
|
+
}
|
|
1067
|
+
/** Split a region on its output-pixel grid, bounding the plan before allocating it. */
|
|
1068
|
+
function splitRasterRectangle(rectangle, scale, limits) {
|
|
1069
|
+
const { x, y, width, height } = rectangle;
|
|
1070
|
+
const { maxPixels, maxDimension, maxTiles } = limits;
|
|
1071
|
+
if (![
|
|
1072
|
+
x,
|
|
1073
|
+
y,
|
|
1074
|
+
width,
|
|
1075
|
+
height,
|
|
1076
|
+
scale
|
|
1077
|
+
].every(Number.isFinite) || x < 0 || y < 0 || width <= 0 || height <= 0 || scale <= 0 || !Number.isSafeInteger(maxPixels) || maxPixels < 1 || maxPixels > 16777216 || !Number.isSafeInteger(maxDimension) || maxDimension < 1 || maxDimension > 16777216 || !Number.isSafeInteger(maxTiles) || maxTiles < 0) throw new TypeError("Invalid raster splitting limits or rectangle.");
|
|
1078
|
+
const pixelWidth = Math.ceil(width * scale - 1e-9), pixelHeight = Math.ceil(height * scale - 1e-9);
|
|
1079
|
+
if (![pixelWidth, pixelHeight].every((value) => Number.isSafeInteger(value) && value > 0)) throw new RangeError("Raster dimensions exceed the coordinate range.");
|
|
1080
|
+
let tileWidth = Math.min(pixelWidth, maxDimension), tileHeight = Math.min(pixelHeight, maxDimension);
|
|
1081
|
+
if (tileWidth * tileHeight > maxPixels) {
|
|
1082
|
+
const side = Math.floor(Math.sqrt(maxPixels));
|
|
1083
|
+
if (tileWidth <= side) tileHeight = Math.floor(maxPixels / tileWidth);
|
|
1084
|
+
else if (tileHeight <= side) tileWidth = Math.floor(maxPixels / tileHeight);
|
|
1085
|
+
else {
|
|
1086
|
+
tileWidth = side;
|
|
1087
|
+
tileHeight = Math.min(tileHeight, Math.floor(maxPixels / tileWidth));
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
const columns = Math.ceil(pixelWidth / tileWidth), rows = Math.ceil(pixelHeight / tileHeight);
|
|
1091
|
+
if (columns * rows > maxTiles) throw new RangeError("Raster batch exceeds maxPages after worksheet splitting.");
|
|
1092
|
+
const result = [];
|
|
1093
|
+
for (let row = 0; row < rows; row++) for (let column = 0; column < columns; column++) {
|
|
1094
|
+
const left = column * tileWidth / scale, top = row * tileHeight / scale;
|
|
1095
|
+
result.push({
|
|
1096
|
+
x: x + left,
|
|
1097
|
+
y: y + top,
|
|
1098
|
+
width: Math.min(tileWidth / scale, width - left),
|
|
1099
|
+
height: Math.min(tileHeight / scale, height - top)
|
|
1100
|
+
});
|
|
1101
|
+
}
|
|
1102
|
+
return result;
|
|
1103
|
+
}
|
|
1104
|
+
/** Writer's zero-area parity placeholders have no visible page. Offsets stay in twips. */
|
|
1105
|
+
function writerPages(rectangles) {
|
|
1106
|
+
const pages = rectangles.split(";").filter((value) => value.trim()).flatMap((rectangle) => {
|
|
1107
|
+
const fields = rectangle.split(",").map((value) => Number(value.trim()));
|
|
1108
|
+
const [x, y, width, height] = fields;
|
|
1109
|
+
if (fields.length !== 4 || x === void 0 || y === void 0 || width === void 0 || height === void 0 || fields.some((value) => !Number.isSafeInteger(value) || value < 0 || value > 2147483647) || width === 0 !== (height === 0) || x + width > 2147483647 || y + height > 2147483647) throw new Error("LibreOffice returned invalid page rectangles.");
|
|
1110
|
+
return width === 0 ? [] : [{
|
|
1111
|
+
x,
|
|
1112
|
+
y,
|
|
1113
|
+
width: width / 15,
|
|
1114
|
+
height: height / 15,
|
|
1115
|
+
part: -1
|
|
1116
|
+
}];
|
|
1117
|
+
});
|
|
1118
|
+
if (pages.length === 0) throw new Error("LibreOffice returned no document pages.");
|
|
1119
|
+
return pages;
|
|
1120
|
+
}
|
|
1121
|
+
/** Validate coordinates before allocation or wasm32 integer conversion. */
|
|
1122
|
+
function tileDimensions(request, pages) {
|
|
1123
|
+
const page = pages[request.pageIndex];
|
|
1124
|
+
if (!Number.isSafeInteger(request.pageIndex) || !page || ![
|
|
1125
|
+
request.x,
|
|
1126
|
+
request.y,
|
|
1127
|
+
request.width,
|
|
1128
|
+
request.height,
|
|
1129
|
+
request.scale
|
|
1130
|
+
].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.");
|
|
1131
|
+
const width = Math.ceil(request.width * request.scale - 1e-9);
|
|
1132
|
+
const height = Math.ceil(request.height * request.scale - 1e-9);
|
|
1133
|
+
if (width <= 0 || height <= 0 || !Number.isSafeInteger(width * height) || width * height > 16777216) throw new Error("Tile exceeds the 16 megapixel allocation limit.");
|
|
1134
|
+
const twips = [
|
|
1135
|
+
page.x + Math.round(request.x * 15),
|
|
1136
|
+
page.y + Math.round(request.y * 15),
|
|
1137
|
+
Math.round(request.width * 15),
|
|
1138
|
+
Math.round(request.height * 15)
|
|
1139
|
+
];
|
|
1140
|
+
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.");
|
|
1141
|
+
return {
|
|
1142
|
+
page,
|
|
1143
|
+
width,
|
|
1144
|
+
height
|
|
1145
|
+
};
|
|
1146
|
+
}
|
|
1147
|
+
/** Cairo/LO channels are premultiplied; PNG and ImageData require straight RGBA. */
|
|
1148
|
+
function rgbaPixels(source, tileMode) {
|
|
1149
|
+
if (tileMode !== 0 && tileMode !== 1 || source.length % 4 !== 0) throw new Error("LibreOffice returned an unsupported tile pixel format.");
|
|
1150
|
+
const result = new Uint8ClampedArray(source.length);
|
|
1151
|
+
for (let index = 0; index < source.length; index += 4) {
|
|
1152
|
+
const alpha = source[index + 3];
|
|
1153
|
+
const multiplier = alpha === 0 ? 0 : 255 / alpha;
|
|
1154
|
+
result[index] = source[index + (tileMode === 1 ? 2 : 0)] * multiplier;
|
|
1155
|
+
result[index + 1] = source[index + 1] * multiplier;
|
|
1156
|
+
result[index + 2] = source[index + (tileMode === 1 ? 0 : 2)] * multiplier;
|
|
1157
|
+
result[index + 3] = alpha;
|
|
1158
|
+
}
|
|
1159
|
+
return result;
|
|
1160
|
+
}
|
|
1161
|
+
//#endregion
|
|
1162
|
+
//#region lib/types/engine-rendering.js
|
|
1163
|
+
/** Shared bounded raster allocations for browser and Node engine owners. */
|
|
1164
|
+
function numericCall(module, name, args) {
|
|
1165
|
+
return module.ccall(name, "number", args.map(() => "number"), args);
|
|
1166
|
+
}
|
|
1167
|
+
/** Copy/free one engine-owned UTF-8 return value. */
|
|
1168
|
+
function engineString(module, name, types, args, failure) {
|
|
1169
|
+
const pointer = module.ccall(name, "number", types, args);
|
|
1170
|
+
if (!pointer) throw failure();
|
|
1171
|
+
try {
|
|
1172
|
+
return module.UTF8ToString(pointer);
|
|
1173
|
+
} finally {
|
|
1174
|
+
numericCall(module, "free", [pointer]);
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
/** Paint into a temporary allocation; copy pixels before free or another engine call. */
|
|
1178
|
+
function renderRegion(module, document, request, pages, failure, pdf = false) {
|
|
1179
|
+
const call = (name, args) => numericCall(module, name, args);
|
|
1180
|
+
const { page, width, height } = tileDimensions(request, pages);
|
|
1181
|
+
const size = width * height * 4;
|
|
1182
|
+
const pointer = call("malloc", [size]);
|
|
1183
|
+
if (!pointer) throw failure();
|
|
1184
|
+
try {
|
|
1185
|
+
new Uint8Array(module.HEAPU32.buffer, pointer, size).fill(0);
|
|
1186
|
+
const position = [
|
|
1187
|
+
page.x + Math.round(request.x * 15),
|
|
1188
|
+
page.y + Math.round(request.y * 15),
|
|
1189
|
+
Math.max(1, Math.round(request.width * 15)),
|
|
1190
|
+
Math.max(1, Math.round(request.height * 15))
|
|
1191
|
+
];
|
|
1192
|
+
if (!call(pdf ? "dsh_pdf_paint" : "dsh_lok_document_paint", [
|
|
1193
|
+
document,
|
|
1194
|
+
pointer,
|
|
1195
|
+
page.part,
|
|
1196
|
+
width,
|
|
1197
|
+
height,
|
|
1198
|
+
...position
|
|
1199
|
+
])) throw failure();
|
|
1200
|
+
const source = new Uint8Array(module.HEAPU32.buffer, pointer, size);
|
|
1201
|
+
return {
|
|
1202
|
+
width,
|
|
1203
|
+
height,
|
|
1204
|
+
rgba: pdf ? new Uint8ClampedArray(source) : rgbaPixels(source, call("dsh_lok_document_tile_mode", [document]))
|
|
1205
|
+
};
|
|
1206
|
+
} finally {
|
|
1207
|
+
call("free", [pointer]);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
/** PDF page dimensions use the same twips ABI, with an immutable PDF page index as part. */
|
|
1211
|
+
function pdfPages(module, pdf, failure) {
|
|
1212
|
+
const count = numericCall(module, "dsh_pdf_page_count", [pdf]);
|
|
1213
|
+
if (!Number.isSafeInteger(count) || count < 1 || count > 1e5) throw failure();
|
|
1214
|
+
const pointer = numericCall(module, "malloc", [8]);
|
|
1215
|
+
if (!pointer) throw failure();
|
|
1216
|
+
try {
|
|
1217
|
+
return Array.from({ length: count }, (_, part) => {
|
|
1218
|
+
if (!numericCall(module, "dsh_pdf_page_size", [
|
|
1219
|
+
pdf,
|
|
1220
|
+
part,
|
|
1221
|
+
pointer,
|
|
1222
|
+
pointer + 4
|
|
1223
|
+
])) throw failure();
|
|
1224
|
+
const width = module.HEAPU32[pointer / 4];
|
|
1225
|
+
const height = module.HEAPU32[pointer / 4 + 1];
|
|
1226
|
+
if (width < 1 || height < 1 || width > 2147483647 || height > 2147483647) throw failure();
|
|
1227
|
+
return {
|
|
1228
|
+
part,
|
|
1229
|
+
x: 0,
|
|
1230
|
+
y: 0,
|
|
1231
|
+
width: width / 15,
|
|
1232
|
+
height: height / 15
|
|
1233
|
+
};
|
|
1234
|
+
});
|
|
1235
|
+
} finally {
|
|
1236
|
+
numericCall(module, "free", [pointer]);
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
//#endregion
|
|
1240
|
+
//#region lib/types/sheet-geometry.js
|
|
1241
|
+
const MAX_COLUMN = 16383;
|
|
1242
|
+
const MAX_ROW = 1048575;
|
|
1243
|
+
function column(index) {
|
|
1244
|
+
let name = "";
|
|
1245
|
+
for (let value = index + 1; value > 0; value = Math.floor((value - 1) / 26)) name = String.fromCharCode(65 + (value - 1) % 26) + name;
|
|
1246
|
+
return name;
|
|
1247
|
+
}
|
|
1248
|
+
function rangeName(range) {
|
|
1249
|
+
return `${column(range.firstColumn)}${range.firstRow + 1}:${column(range.lastColumn)}${range.lastRow + 1}`;
|
|
1250
|
+
}
|
|
1251
|
+
function parseCellRange(value) {
|
|
1252
|
+
const match = /^\$?([A-Z]{1,3})\$?([1-9]\d{0,6})(?::\$?([A-Z]{1,3})\$?([1-9]\d{0,6}))?$/i.exec(value);
|
|
1253
|
+
if (!match) throw new TypeError("range must be an A1 cell or rectangle without a sheet prefix.");
|
|
1254
|
+
const col = (name) => [...name.toUpperCase()].reduce((sum, c) => sum * 26 + c.charCodeAt(0) - 64, 0) - 1;
|
|
1255
|
+
const firstColumn = col(match[1]);
|
|
1256
|
+
const firstRow = Number(match[2]) - 1;
|
|
1257
|
+
const lastColumn = col(match[3] ?? match[1]);
|
|
1258
|
+
const lastRow = Number(match[4] ?? match[2]) - 1;
|
|
1259
|
+
if (lastColumn < firstColumn || lastRow < firstRow || lastColumn > MAX_COLUMN || lastRow > MAX_ROW) throw new TypeError("range exceeds Calc worksheet bounds or has reversed endpoints.");
|
|
1260
|
+
return {
|
|
1261
|
+
firstColumn,
|
|
1262
|
+
firstRow,
|
|
1263
|
+
lastColumn,
|
|
1264
|
+
lastRow
|
|
1265
|
+
};
|
|
1266
|
+
}
|
|
1267
|
+
function sheetPartInfo(value) {
|
|
1268
|
+
const info = JSON.parse(value);
|
|
1269
|
+
if (!info || typeof info.name !== "string" || ![0, 1].includes(info.visible) || ![0, 1].includes(info.rtllayout) || !Number.isInteger(info.lastcolumn) || !Number.isInteger(info.lastrow) || info.lastcolumn < 0 || info.lastrow < 0 || info.lastcolumn > MAX_COLUMN || info.lastrow > MAX_ROW) throw new Error("LibreOffice returned invalid worksheet data-area metadata.");
|
|
1270
|
+
return info;
|
|
1271
|
+
}
|
|
1272
|
+
/** Formatting-only cells and standalone drawings do not enlarge LibreOffice's data area. */
|
|
1273
|
+
function dataArea(info) {
|
|
1274
|
+
return {
|
|
1275
|
+
firstColumn: 0,
|
|
1276
|
+
firstRow: 0,
|
|
1277
|
+
lastColumn: info.lastcolumn,
|
|
1278
|
+
lastRow: info.lastrow
|
|
1279
|
+
};
|
|
1280
|
+
}
|
|
1281
|
+
function spans(encoded, flags, maximum) {
|
|
1282
|
+
if (typeof encoded !== "string" || encoded.length > 33554432) throw new Error("Invalid worksheet geometry span encoding.");
|
|
1283
|
+
const tokens = encoded.trim().split(/\s+/);
|
|
1284
|
+
let previous = -1;
|
|
1285
|
+
let flag = 0;
|
|
1286
|
+
const result = tokens.map((token, i) => {
|
|
1287
|
+
const fields = token.split(":");
|
|
1288
|
+
let value;
|
|
1289
|
+
let end;
|
|
1290
|
+
if (flags && i > 0) {
|
|
1291
|
+
value = flag = 1 - flag;
|
|
1292
|
+
end = Number(fields[0]);
|
|
1293
|
+
if (fields.length !== 1) throw new Error("Invalid worksheet flag span.");
|
|
1294
|
+
} else {
|
|
1295
|
+
value = Number(fields[0]);
|
|
1296
|
+
end = Number(fields[1]);
|
|
1297
|
+
flag = value;
|
|
1298
|
+
if (fields.length !== 2) throw new Error("Invalid worksheet size span.");
|
|
1299
|
+
}
|
|
1300
|
+
if (!Number.isSafeInteger(value) || value < 0 || (flags ? value > 1 : value > 65535) || !Number.isSafeInteger(end) || end <= previous || end > maximum) throw new Error("Invalid worksheet geometry span.");
|
|
1301
|
+
previous = end;
|
|
1302
|
+
return {
|
|
1303
|
+
end,
|
|
1304
|
+
value
|
|
1305
|
+
};
|
|
1306
|
+
});
|
|
1307
|
+
if (previous !== maximum) throw new Error("Worksheet geometry does not cover the complete dimension.");
|
|
1308
|
+
return result;
|
|
1309
|
+
}
|
|
1310
|
+
function dimension(data, first, last, maximum, scale) {
|
|
1311
|
+
const sizes = spans(data?.sizes, false, maximum);
|
|
1312
|
+
const hidden = spans(data?.hidden, true, maximum);
|
|
1313
|
+
const filtered = spans(data?.filtered, true, maximum);
|
|
1314
|
+
let position = 0, start = 0, index = 0, si = 0, hi = 0, fi = 0;
|
|
1315
|
+
while (index <= last) {
|
|
1316
|
+
const size = sizes[si], hide = hidden[hi], filter = filtered[fi];
|
|
1317
|
+
const end = Math.min(size.end, hide.end, filter.end, last, index < first ? first - 1 : last);
|
|
1318
|
+
const pixels = hide.value || filter.value || size.value === 0 ? 0 : Math.max(1, Math.floor(size.value * scale / 15));
|
|
1319
|
+
if (index === first) start = position;
|
|
1320
|
+
position += (end - index + 1) * pixels;
|
|
1321
|
+
index = end + 1;
|
|
1322
|
+
if (index > size.end) si++;
|
|
1323
|
+
if (index > hide.end) hi++;
|
|
1324
|
+
if (index > filter.end) fi++;
|
|
1325
|
+
}
|
|
1326
|
+
return [start / scale, (position - start) / scale];
|
|
1327
|
+
}
|
|
1328
|
+
/** Logical columns advance from A; LOK itself mirrors RTL sheet painting. No manual x inversion. */
|
|
1329
|
+
function sheetRangeRectangle(geometry, range, scale) {
|
|
1330
|
+
if (!Number.isFinite(scale) || scale <= 0 || scale > 16) throw new TypeError("Invalid worksheet raster scale.");
|
|
1331
|
+
const [x, width] = dimension(geometry.columns, range.firstColumn, range.lastColumn, MAX_COLUMN, scale);
|
|
1332
|
+
const [y, height] = dimension(geometry.rows, range.firstRow, range.lastRow, MAX_ROW, scale);
|
|
1333
|
+
if (width <= 0 || height <= 0) throw new Error("The selected worksheet range is entirely hidden or filtered.");
|
|
1334
|
+
if ([
|
|
1335
|
+
x,
|
|
1336
|
+
y,
|
|
1337
|
+
width,
|
|
1338
|
+
height,
|
|
1339
|
+
x + width,
|
|
1340
|
+
y + height
|
|
1341
|
+
].some((value) => !Number.isFinite(value) || value * 15 > 2147483647)) throw new Error("The selected worksheet range exceeds the supported coordinate range.");
|
|
1342
|
+
return {
|
|
1343
|
+
x,
|
|
1344
|
+
y,
|
|
1345
|
+
width,
|
|
1346
|
+
height
|
|
1347
|
+
};
|
|
1348
|
+
}
|
|
1349
|
+
//#endregion
|
|
1350
|
+
//#region lib/types/image-operations.js
|
|
1351
|
+
function selectedPages(pages, count, limit) {
|
|
1352
|
+
if (!Number.isSafeInteger(count) || count < 1) throw new ConversionError("invalid-document", "The document contains no renderable pages.");
|
|
1353
|
+
const result = pages === void 0 || pages === "all" ? Array.from({ length: Math.min(count, limit + 1) }, (_, i) => i + 1) : [...pages];
|
|
1354
|
+
if (result.length > limit) throw new ConversionError("output-too-large", "Selected page count exceeds maxPages; select pages or raise the limit.");
|
|
1355
|
+
if (result.some((page) => page > count)) throw new TypeError(`Selected page lies outside the ${count}-page document.`);
|
|
1356
|
+
return result;
|
|
1357
|
+
}
|
|
1358
|
+
//#endregion
|
|
1359
|
+
//#region lib/types/png.js
|
|
1360
|
+
/** Portable PNG encoding over straight RGBA; browser and Node need no native image dependency. */
|
|
1361
|
+
const crcTable = Uint32Array.from({ length: 256 }, (_, value) => {
|
|
1362
|
+
for (let bit = 0; bit < 8; bit++) value = value & 1 ? 3988292384 ^ value >>> 1 : value >>> 1;
|
|
1363
|
+
return value >>> 0;
|
|
1364
|
+
});
|
|
1365
|
+
function chunk(type, bytes) {
|
|
1366
|
+
const output = new Uint8Array(bytes.length + 12);
|
|
1367
|
+
const view = new DataView(output.buffer);
|
|
1368
|
+
view.setUint32(0, bytes.length);
|
|
1369
|
+
output.set(new TextEncoder().encode(type), 4);
|
|
1370
|
+
output.set(bytes, 8);
|
|
1371
|
+
let crc = 4294967295;
|
|
1372
|
+
for (let i = 4; i < output.length - 4; i++) crc = crcTable[(crc ^ output[i]) & 255] ^ crc >>> 8;
|
|
1373
|
+
view.setUint32(output.length - 4, (crc ^ 4294967295) >>> 0);
|
|
1374
|
+
return output;
|
|
1375
|
+
}
|
|
1376
|
+
function encodePng(width, height, rgba) {
|
|
1377
|
+
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 || width * height > 16777216 || rgba.byteLength !== width * height * 4) throw new TypeError("Invalid PNG raster dimensions.");
|
|
1378
|
+
const header = /* @__PURE__ */ new Uint8Array(13);
|
|
1379
|
+
const view = new DataView(header.buffer);
|
|
1380
|
+
view.setUint32(0, width);
|
|
1381
|
+
view.setUint32(4, height);
|
|
1382
|
+
header[8] = 8;
|
|
1383
|
+
header[9] = 6;
|
|
1384
|
+
const scanlines = new Uint8Array(height * (width * 4 + 1));
|
|
1385
|
+
for (let y = 0; y < height; y++) {
|
|
1386
|
+
const source = y * width * 4;
|
|
1387
|
+
const target = y * (width * 4 + 1);
|
|
1388
|
+
scanlines[target] = 1;
|
|
1389
|
+
for (let x = 0; x < width * 4; x++) scanlines[target + 1 + x] = rgba[source + x] - (x < 4 ? 0 : rgba[source + x - 4]);
|
|
1390
|
+
}
|
|
1391
|
+
const chunks = [
|
|
1392
|
+
new Uint8Array([
|
|
1393
|
+
137,
|
|
1394
|
+
80,
|
|
1395
|
+
78,
|
|
1396
|
+
71,
|
|
1397
|
+
13,
|
|
1398
|
+
10,
|
|
1399
|
+
26,
|
|
1400
|
+
10
|
|
1401
|
+
]),
|
|
1402
|
+
chunk("IHDR", header),
|
|
1403
|
+
chunk("IDAT", zlibSync(scanlines, { level: 6 })),
|
|
1404
|
+
chunk("IEND", /* @__PURE__ */ new Uint8Array())
|
|
1405
|
+
];
|
|
1406
|
+
const result = new Uint8Array(chunks.reduce((sum, value) => sum + value.length, 0));
|
|
1407
|
+
let offset = 0;
|
|
1408
|
+
for (const value of chunks) {
|
|
1409
|
+
result.set(value, offset);
|
|
1410
|
+
offset += value.length;
|
|
1411
|
+
}
|
|
1412
|
+
return result;
|
|
1413
|
+
}
|
|
1414
|
+
//#endregion
|
|
1415
|
+
//#region lib/types/image-renderer.js
|
|
1416
|
+
/** One saved-file model and one bounded direct PNG batch; no Office-to-PDF intermediate. */
|
|
1417
|
+
async function regions(session, request) {
|
|
1418
|
+
const { module, document, office, pdf } = session;
|
|
1419
|
+
const call = (name, args) => numericCall(module, name, args);
|
|
1420
|
+
const failure = () => engineError(module, office);
|
|
1421
|
+
const text = (name, args) => engineString(module, name, args.map(() => "number"), args, failure);
|
|
1422
|
+
const values = (command) => engineString(module, "dsh_lok_document_command_values", ["number", "string"], [document, command], failure);
|
|
1423
|
+
const select = (pages) => ({
|
|
1424
|
+
count: pages.length,
|
|
1425
|
+
regions: selectedPages(request.pages, pages.length, request.maxPages).map((number) => {
|
|
1426
|
+
const page = pages[number - 1];
|
|
1427
|
+
return {
|
|
1428
|
+
page,
|
|
1429
|
+
number,
|
|
1430
|
+
rectangle: {
|
|
1431
|
+
x: 0,
|
|
1432
|
+
y: 0,
|
|
1433
|
+
width: page.width,
|
|
1434
|
+
height: page.height
|
|
1435
|
+
}
|
|
1436
|
+
};
|
|
1437
|
+
})
|
|
1438
|
+
});
|
|
1439
|
+
if (pdf) return select(pdfPages(module, document, failure));
|
|
1440
|
+
if (!call("dsh_lok_document_initialize_rendering", [document]) || !call("dsh_lok_document_listen", [document])) throw failure();
|
|
1441
|
+
await session.idle();
|
|
1442
|
+
const type = call("dsh_lok_document_type", [document]);
|
|
1443
|
+
if (type !== ([
|
|
1444
|
+
"xls",
|
|
1445
|
+
"xlsx",
|
|
1446
|
+
"ods"
|
|
1447
|
+
].includes(request.extension) ? 1 : [
|
|
1448
|
+
"ppt",
|
|
1449
|
+
"pptx",
|
|
1450
|
+
"odp"
|
|
1451
|
+
].includes(request.extension) ? 2 : 0)) throw new ConversionError("invalid-document", "LibreOffice imported the input as an unexpected document type.");
|
|
1452
|
+
if (type === 0) return select(writerPages(text("dsh_lok_document_page_rectangles", [document])));
|
|
1453
|
+
const parts = call("dsh_lok_document_parts", [document]);
|
|
1454
|
+
if (!Number.isSafeInteger(parts) || parts < 1 || parts > 1e5) throw new ConversionError("invalid-document", "Invalid document part count.");
|
|
1455
|
+
if (type === 2) {
|
|
1456
|
+
const sizes = JSON.parse(values(".uno:AllPageSize"));
|
|
1457
|
+
if (!Array.isArray(sizes.parts) || sizes.parts.length !== parts) throw new ConversionError("invalid-document", "Impress returned inconsistent slide dimensions.");
|
|
1458
|
+
return select(sizes.parts.map(({ width, height }, part) => {
|
|
1459
|
+
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 || width > 2147483647 || height > 2147483647) throw new ConversionError("invalid-document", "Impress returned invalid slide dimensions.");
|
|
1460
|
+
return {
|
|
1461
|
+
part,
|
|
1462
|
+
x: 0,
|
|
1463
|
+
y: 0,
|
|
1464
|
+
width: width / 15,
|
|
1465
|
+
height: height / 15
|
|
1466
|
+
};
|
|
1467
|
+
}));
|
|
1468
|
+
}
|
|
1469
|
+
const sheets = Array.from({ length: parts }, (_, part) => ({
|
|
1470
|
+
part,
|
|
1471
|
+
info: sheetPartInfo(text("dsh_lok_document_part_info", [document, part]))
|
|
1472
|
+
}));
|
|
1473
|
+
const count = sheets.filter(({ info }) => info.visible).length;
|
|
1474
|
+
const selected = request.sheet === void 0 ? sheets.filter(({ info }) => info.visible) : sheets.filter(({ info }) => info.name === request.sheet);
|
|
1475
|
+
if (!selected.length) throw new ConversionError("invalid-document", "The exact worksheet name does not exist or the workbook has no visible sheets.");
|
|
1476
|
+
if (selected.length > request.maxPages) throw new ConversionError("output-too-large", "Selected worksheet count exceeds maxPages; select a sheet or raise the limit.");
|
|
1477
|
+
const result = [];
|
|
1478
|
+
const scale = request.dpi / 96;
|
|
1479
|
+
for (const { part, info } of selected) {
|
|
1480
|
+
if (!call("dsh_lok_document_part", [document, part])) throw failure();
|
|
1481
|
+
await session.idle();
|
|
1482
|
+
const range = request.range === void 0 ? dataArea(info) : parseCellRange(request.range);
|
|
1483
|
+
const rectangle = sheetRangeRectangle(JSON.parse(values(".uno:SheetGeometryData")), range, scale);
|
|
1484
|
+
const page = {
|
|
1485
|
+
x: 0,
|
|
1486
|
+
y: 0,
|
|
1487
|
+
width: rectangle.x + rectangle.width,
|
|
1488
|
+
height: rectangle.y + rectangle.height,
|
|
1489
|
+
part
|
|
1490
|
+
};
|
|
1491
|
+
result.push({
|
|
1492
|
+
page,
|
|
1493
|
+
rectangle,
|
|
1494
|
+
sheet: info.name,
|
|
1495
|
+
range: rangeName(range),
|
|
1496
|
+
rtl: Boolean(info.rtllayout)
|
|
1497
|
+
});
|
|
1498
|
+
}
|
|
1499
|
+
return {
|
|
1500
|
+
count,
|
|
1501
|
+
regions: result
|
|
1502
|
+
};
|
|
1503
|
+
}
|
|
1504
|
+
async function renderImagesWithWasm(request) {
|
|
1505
|
+
return withWasmSession(request, async (session) => {
|
|
1506
|
+
const { operation, options } = request;
|
|
1507
|
+
const { count, regions: sourceRegions } = await regions(session, operation);
|
|
1508
|
+
const scale = operation.dpi / 96;
|
|
1509
|
+
const selected = [];
|
|
1510
|
+
for (const region of sourceRegions) {
|
|
1511
|
+
if (region.sheet === void 0) {
|
|
1512
|
+
selected.push(region);
|
|
1513
|
+
continue;
|
|
1514
|
+
}
|
|
1515
|
+
let rectangles;
|
|
1516
|
+
try {
|
|
1517
|
+
rectangles = splitRasterRectangle(region.rectangle, scale, {
|
|
1518
|
+
maxPixels: operation.maxPixels,
|
|
1519
|
+
maxDimension: operation.maxDimension,
|
|
1520
|
+
maxTiles: operation.maxPages - selected.length
|
|
1521
|
+
});
|
|
1522
|
+
} catch (cause) {
|
|
1523
|
+
throw new ConversionError("output-too-large", String(cause), { cause });
|
|
1524
|
+
}
|
|
1525
|
+
selected.push(...rectangles.map((rectangle) => ({
|
|
1526
|
+
...region,
|
|
1527
|
+
rectangle
|
|
1528
|
+
})));
|
|
1529
|
+
}
|
|
1530
|
+
for (const { page, rectangle } of selected) {
|
|
1531
|
+
const pixelWidth = Math.ceil(rectangle.width * scale - 1e-9), pixelHeight = Math.ceil(rectangle.height * scale - 1e-9);
|
|
1532
|
+
if (pixelWidth > operation.maxDimension || pixelHeight > operation.maxDimension || pixelWidth * pixelHeight > operation.maxPixels) throw new ConversionError("output-too-large", "Selected page exceeds maxPixels or maxDimension; reduce DPI or raise the image limits.");
|
|
1533
|
+
tileDimensions({
|
|
1534
|
+
pageIndex: 0,
|
|
1535
|
+
...rectangle,
|
|
1536
|
+
scale
|
|
1537
|
+
}, [page]);
|
|
1538
|
+
}
|
|
1539
|
+
const images = [];
|
|
1540
|
+
let total = 0;
|
|
1541
|
+
for (const region of selected) {
|
|
1542
|
+
if (region.sheet !== void 0) {
|
|
1543
|
+
const call = (name, args) => numericCall(session.module, name, args);
|
|
1544
|
+
if (!call("dsh_lok_document_part", [session.document, region.page.part])) throw engineError(session.module, session.office);
|
|
1545
|
+
const { x, y, width, height } = region.rectangle;
|
|
1546
|
+
const command = `.uno:ViewRowColumnHeaders?x=${Math.round(x * 15)}&y=${Math.round(y * 15)}&width=${Math.round(width * 15)}&height=${Math.round(height * 15)}`;
|
|
1547
|
+
if (!call("dsh_lok_document_viewport", [
|
|
1548
|
+
session.document,
|
|
1549
|
+
Math.round(scale * 1440),
|
|
1550
|
+
21600,
|
|
1551
|
+
Math.round(x * 15),
|
|
1552
|
+
Math.round(y * 15),
|
|
1553
|
+
Math.round(width * 15),
|
|
1554
|
+
Math.round(height * 15)
|
|
1555
|
+
])) throw engineError(session.module, session.office);
|
|
1556
|
+
engineString(session.module, "dsh_lok_document_command_values", ["number", "string"], [session.document, command], () => engineError(session.module, session.office));
|
|
1557
|
+
await session.idle();
|
|
1558
|
+
}
|
|
1559
|
+
const tile = renderRegion(session.module, session.document, {
|
|
1560
|
+
pageIndex: 0,
|
|
1561
|
+
...region.rectangle,
|
|
1562
|
+
scale
|
|
1563
|
+
}, [region.page], () => engineError(session.module, session.office), session.pdf);
|
|
1564
|
+
const png = encodePng(tile.width, tile.height, tile.rgba);
|
|
1565
|
+
total += png.length;
|
|
1566
|
+
if (total > options.maxOutputBytes) throw new ConversionError("output-too-large", "PNG batch exceeds maxOutputBytes.");
|
|
1567
|
+
const index = images.length + 1;
|
|
1568
|
+
const path = join(operation.outputDir, `page-${String(index).padStart(4, "0")}.png`);
|
|
1569
|
+
writeFileSync(path, png, {
|
|
1570
|
+
flag: "wx",
|
|
1571
|
+
mode: 384
|
|
1572
|
+
});
|
|
1573
|
+
images.push({
|
|
1574
|
+
index,
|
|
1575
|
+
...region.number === void 0 ? {} : { page: region.number },
|
|
1576
|
+
...region.sheet === void 0 ? {} : {
|
|
1577
|
+
sheet: region.sheet,
|
|
1578
|
+
range: region.range,
|
|
1579
|
+
rtl: region.rtl
|
|
1580
|
+
},
|
|
1581
|
+
path,
|
|
1582
|
+
width: tile.width,
|
|
1583
|
+
height: tile.height,
|
|
1584
|
+
rectangle: region.rectangle,
|
|
1585
|
+
byteLength: png.length
|
|
1586
|
+
});
|
|
1587
|
+
}
|
|
1588
|
+
return {
|
|
1589
|
+
schemaVersion: 1,
|
|
1590
|
+
backend: "wasm",
|
|
1591
|
+
rasterEngine: session.pdf ? "pdfium" : "libreoffice",
|
|
1592
|
+
source: "saved",
|
|
1593
|
+
inputPath: operation.inputPath,
|
|
1594
|
+
sourceSha256: createHash("sha256").update(request.bytes).digest("hex"),
|
|
1595
|
+
dpi: operation.dpi,
|
|
1596
|
+
pageCount: count,
|
|
1597
|
+
images,
|
|
1598
|
+
missingFonts: session.missingFonts
|
|
1599
|
+
};
|
|
1600
|
+
});
|
|
1601
|
+
}
|
|
1602
|
+
//#endregion
|
|
1603
|
+
//#region lib/types/worker.js
|
|
1604
|
+
/** Cancellable CPU work and WASM conversion run outside the Node event loop. */
|
|
1605
|
+
/**
|
|
1606
|
+
* @param port - The parent port, present inside a Worker thread.
|
|
1607
|
+
* @returns the connected parent port.
|
|
1608
|
+
* @throws when this entry is loaded outside a Worker.
|
|
1609
|
+
*/
|
|
1610
|
+
function requireParentPort(port) {
|
|
1611
|
+
if (port === null) throw new Error("The LibreOffice conversion worker requires a parent port.");
|
|
1612
|
+
return port;
|
|
1613
|
+
}
|
|
1614
|
+
const port = requireParentPort(parentPort);
|
|
1615
|
+
function indexFonts(options) {
|
|
1616
|
+
const primary = indexSystemFonts({
|
|
1617
|
+
directories: options.fontDirectories,
|
|
1618
|
+
maxFiles: options.maxFontFiles,
|
|
1619
|
+
maxFileBytes: options.maxFontFileBytes
|
|
1620
|
+
});
|
|
1621
|
+
if (!options.includeOfficeFonts) return primary;
|
|
1622
|
+
const primaryFiles = new Set(primary.map((face) => face.path));
|
|
1623
|
+
const remaining = Math.max(0, options.maxFontFiles - primaryFiles.size);
|
|
1624
|
+
if (remaining === 0) return primary;
|
|
1625
|
+
const supplemental = indexSystemFonts({
|
|
1626
|
+
directories: officeFontFiles().slice(0, remaining),
|
|
1627
|
+
maxFiles: remaining,
|
|
1628
|
+
maxFileBytes: options.maxFontFileBytes
|
|
1629
|
+
});
|
|
1630
|
+
const aliases = new Set(primary.flatMap((face) => face.aliases));
|
|
1631
|
+
return [...primary, ...supplemental.filter((face) => officeFontFace(face) && !face.aliases.some((alias) => aliases.has(alias)))];
|
|
1632
|
+
}
|
|
1633
|
+
try {
|
|
1634
|
+
const { inputPath, extension, operation, options, engine, scratch, fontFaces, fontCache } = workerData;
|
|
1635
|
+
const bytes = readFileSync(inputPath);
|
|
1636
|
+
const images = "kind" in operation && operation.kind === "images";
|
|
1637
|
+
if (images && extension === "pdf" && new TextDecoder().decode(bytes.subarray(0, 5)) !== "%PDF-") throw new ConversionError("invalid-document", "Input does not contain a PDF header.");
|
|
1638
|
+
const document = images && extension === "pdf" ? {
|
|
1639
|
+
families: /* @__PURE__ */ new Map(),
|
|
1640
|
+
codePoints: []
|
|
1641
|
+
} : inspectDocument(bytes, extension, options);
|
|
1642
|
+
const faces = fontFaces ?? indexFonts(options);
|
|
1643
|
+
if (!fontFaces) port.postMessage({
|
|
1644
|
+
kind: "fonts",
|
|
1645
|
+
faces
|
|
1646
|
+
});
|
|
1647
|
+
if (engine.backend === "wasm") {
|
|
1648
|
+
if (faces.length === 0 && extension !== "pdf") throw new ConversionError("unavailable", "No usable fonts were found. Install fonts or configure fontDirectories before converting documents.");
|
|
1649
|
+
if (images) {
|
|
1650
|
+
let cacheEntries = [];
|
|
1651
|
+
const result = await renderImagesWithWasm({
|
|
1652
|
+
engine,
|
|
1653
|
+
bytes,
|
|
1654
|
+
extension,
|
|
1655
|
+
operation,
|
|
1656
|
+
options,
|
|
1657
|
+
document,
|
|
1658
|
+
faces,
|
|
1659
|
+
...fontCache === void 0 ? {} : { fontCache },
|
|
1660
|
+
onFontCache: (entries) => {
|
|
1661
|
+
cacheEntries = entries;
|
|
1662
|
+
}
|
|
1663
|
+
});
|
|
1664
|
+
port.postMessage({
|
|
1665
|
+
kind: "font-cache",
|
|
1666
|
+
entries: cacheEntries
|
|
1667
|
+
});
|
|
1668
|
+
port.postMessage({
|
|
1669
|
+
ok: true,
|
|
1670
|
+
images: result
|
|
1671
|
+
});
|
|
1672
|
+
} else {
|
|
1673
|
+
const result = await convertWithWasm({
|
|
1674
|
+
engine,
|
|
1675
|
+
bytes,
|
|
1676
|
+
extension,
|
|
1677
|
+
operation,
|
|
1678
|
+
options,
|
|
1679
|
+
document,
|
|
1680
|
+
faces,
|
|
1681
|
+
...fontCache === void 0 ? {} : { fontCache },
|
|
1682
|
+
onFontCache: (entries) => port.postMessage({
|
|
1683
|
+
kind: "font-cache",
|
|
1684
|
+
entries
|
|
1685
|
+
})
|
|
1686
|
+
});
|
|
1687
|
+
port.postMessage({
|
|
1688
|
+
ok: true,
|
|
1689
|
+
...result
|
|
1690
|
+
}, [result.output.buffer]);
|
|
1691
|
+
}
|
|
1692
|
+
} else {
|
|
1693
|
+
const directory = join(scratch, "fonts");
|
|
1694
|
+
mkdirSync(directory, { mode: 448 });
|
|
1695
|
+
const fonts = createFontLoader(options, document, (name, data) => {
|
|
1696
|
+
const path = join(directory, name);
|
|
1697
|
+
writeFileSync(path, data, {
|
|
1698
|
+
flag: "wx",
|
|
1699
|
+
mode: 384
|
|
1700
|
+
});
|
|
1701
|
+
return path;
|
|
1702
|
+
}, faces, fontCache);
|
|
1703
|
+
preloadFonts(fonts, options, document, true);
|
|
1704
|
+
port.postMessage({
|
|
1705
|
+
kind: "font-cache",
|
|
1706
|
+
entries: fonts.cacheEntries
|
|
1707
|
+
});
|
|
1708
|
+
port.postMessage({
|
|
1709
|
+
ok: true,
|
|
1710
|
+
fonts: fonts.files,
|
|
1711
|
+
substitutions: fonts.substitutions,
|
|
1712
|
+
missingFonts: fonts.missingFonts
|
|
1713
|
+
});
|
|
1714
|
+
}
|
|
1715
|
+
} catch (error) {
|
|
1716
|
+
port.postMessage({
|
|
1717
|
+
ok: false,
|
|
1718
|
+
code: failureCode(error),
|
|
1719
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1720
|
+
stack: error instanceof Error ? error.stack : void 0
|
|
1721
|
+
});
|
|
1722
|
+
}
|
|
1723
|
+
//#endregion
|
|
1724
|
+
export {};
|