@deepseek-ai/libreoffice-kit 0.0.1
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 +73 -0
- package/README.zh.md +73 -0
- package/lib/index.js +924 -0
- package/lib/types/document.d.ts +15 -0
- package/lib/types/engine.d.ts +67 -0
- package/lib/types/errors.d.ts +21 -0
- package/lib/types/font-loader.d.ts +42 -0
- package/lib/types/fonts.d.ts +141 -0
- package/lib/types/index.d.ts +65 -0
- package/lib/types/native-font-names.d.ts +3 -0
- package/lib/types/native.d.ts +34 -0
- package/lib/types/ooxml.d.ts +17 -0
- package/lib/types/options.d.ts +28 -0
- package/lib/types/wasm.d.ts +25 -0
- package/lib/types/worker.d.ts +14 -0
- package/lib/worker.js +800 -0
- package/package.json +46 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,924 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { constants, lstatSync, readdirSync } from "node:fs";
|
|
3
|
+
import { mkdir, mkdtemp, open, readFile, rm, stat, unlink, writeFile } from "node:fs/promises";
|
|
4
|
+
import { homedir, tmpdir } from "node:os";
|
|
5
|
+
import { dirname, extname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
|
|
6
|
+
import { Worker } from "node:worker_threads";
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import "fontkit";
|
|
9
|
+
import "fflate";
|
|
10
|
+
import "saxes";
|
|
11
|
+
//#region lib/types/errors.js
|
|
12
|
+
/** Stable render failure categories shared across the Node worker and native helper transports. */
|
|
13
|
+
const CODES = /* @__PURE__ */ new Set([
|
|
14
|
+
"input-too-large",
|
|
15
|
+
"output-too-large",
|
|
16
|
+
"invalid-document",
|
|
17
|
+
"unsupported-format",
|
|
18
|
+
"invalid-output",
|
|
19
|
+
"timeout",
|
|
20
|
+
"unavailable",
|
|
21
|
+
"failed"
|
|
22
|
+
]);
|
|
23
|
+
/** An actionable converter failure; operating-system errors and caller abort reasons remain unchanged. */
|
|
24
|
+
var ConversionError = class extends Error {
|
|
25
|
+
/** Published failure category carried across worker and helper transports. */
|
|
26
|
+
code;
|
|
27
|
+
/**
|
|
28
|
+
* @param code - Published failure category.
|
|
29
|
+
* @param message - Consumer-facing failure description.
|
|
30
|
+
* @param options - Standard error options; a cause is preserved for diagnostics.
|
|
31
|
+
*/
|
|
32
|
+
constructor(code, message, options) {
|
|
33
|
+
super(message, options);
|
|
34
|
+
this.name = "ConversionError";
|
|
35
|
+
this.code = code;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Only published categories cross worker/helper messages; unknown errors use the generic failure category.
|
|
40
|
+
* @param error - The thrown value, which may be any type and may carry an unpublished `code`.
|
|
41
|
+
* @returns The published category, or `failed` when no published category is present.
|
|
42
|
+
*/
|
|
43
|
+
function failureCode(error) {
|
|
44
|
+
const code = error?.code;
|
|
45
|
+
return typeof code === "string" && CODES.has(code) ? code : "failed";
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
//#region lib/types/native-font-names.js
|
|
49
|
+
/** Localized search names from LibreOffice Core's fixed font-name dictionary. */
|
|
50
|
+
const LOCALIZED_FONT_SEARCH_NAMES = /* @__PURE__ */ new Map([
|
|
51
|
+
["바탕", "batang"],
|
|
52
|
+
["바탕체", "batangche"],
|
|
53
|
+
["궁서", "gungshu"],
|
|
54
|
+
["궁서체", "gungshuche"],
|
|
55
|
+
["굴림", "gulim"],
|
|
56
|
+
["굴림체", "gulimche"],
|
|
57
|
+
["돋움", "dotum"],
|
|
58
|
+
["돋움체", "dotumche"],
|
|
59
|
+
["宋体", "simsun"],
|
|
60
|
+
["新宋体", "nsimsun"],
|
|
61
|
+
["黑体", "simhei"],
|
|
62
|
+
["楷体", "simkai"],
|
|
63
|
+
["中易宋体", "zycjksun"],
|
|
64
|
+
["中易黑体", "zycjkhei"],
|
|
65
|
+
["中易楷体", "zycjkkai"],
|
|
66
|
+
["方正黑体", "fzhei"],
|
|
67
|
+
["方正楷体", "fzkai"],
|
|
68
|
+
["方正宋一", "fzsong"],
|
|
69
|
+
["方正书宋", "fzshusong"],
|
|
70
|
+
["方正仿宋", "fzfangsong"],
|
|
71
|
+
["m简黑", "mhei"],
|
|
72
|
+
["m潠窪", "mhei"],
|
|
73
|
+
["m简楷噬", "mkai"],
|
|
74
|
+
["m潠翱抎", "mkai"],
|
|
75
|
+
["m简宋", "msong"],
|
|
76
|
+
["m潠冼", "msong"],
|
|
77
|
+
["m简夫宋", "cfangsong"],
|
|
78
|
+
["m潠溘冼", "cfangsong"],
|
|
79
|
+
["細明體", "mingliu"],
|
|
80
|
+
["新細明體", "pmingliu"],
|
|
81
|
+
["桥", "hei"],
|
|
82
|
+
["歡", "kai"],
|
|
83
|
+
["浩湧", "ming"],
|
|
84
|
+
["msゴシック", "msgothic"],
|
|
85
|
+
["mspゴシック", "mspgothic"],
|
|
86
|
+
["ms明朝", "msmincho"],
|
|
87
|
+
["msp明朝", "mspmincho"],
|
|
88
|
+
["微軟正黑體", "microsoftjhenghei"],
|
|
89
|
+
["微软雅黑", "microsoftyahei"],
|
|
90
|
+
["メイリオ", "meiryo"],
|
|
91
|
+
["hg明朝l", "hgminchol"],
|
|
92
|
+
["hgゴシックb", "hggothicb"],
|
|
93
|
+
["hgp明朝l", "hgpminchol"],
|
|
94
|
+
["hgpゴシックb", "hgpgothicb"],
|
|
95
|
+
["hg明朝lsun", "hgmincholsun"],
|
|
96
|
+
["hgゴシックbsun", "hggothicbsun"],
|
|
97
|
+
["hgp明朝lsun", "hgpmincholsun"],
|
|
98
|
+
["hgpゴシックbsun", "hgpgothicbsun"],
|
|
99
|
+
["hg平成明朝体", "hgheiseimin"],
|
|
100
|
+
["hg平成明朝体w3x12", "hgheiseimin"],
|
|
101
|
+
["ipa明朝", "ipamincho"],
|
|
102
|
+
["ipap明朝", "ipapmincho"],
|
|
103
|
+
["ipaゴシック", "ipagothic"],
|
|
104
|
+
["ipapゴシック", "ipapgothic"],
|
|
105
|
+
["ipauiゴシック", "ipauigothic"],
|
|
106
|
+
["takao明朝", "takaomincho"],
|
|
107
|
+
["takaop明朝", "takaopmincho"],
|
|
108
|
+
["takaoゴシック", "takaogothic"],
|
|
109
|
+
["takaopゴシック", "takaopgothic"],
|
|
110
|
+
["さざなみ明朝", "sazanamimincho"],
|
|
111
|
+
["さざなみゴシック", "sazanamigothic"],
|
|
112
|
+
["東風明朝", "kochimincho"],
|
|
113
|
+
["東風ゴシック", "kochigothic"],
|
|
114
|
+
["썬돋움", "sundotum"],
|
|
115
|
+
["썬굴림", "sungulim"],
|
|
116
|
+
["썬바탕", "sunbatang"],
|
|
117
|
+
["백묵돋움", "baekmukdotum"],
|
|
118
|
+
["백묵굴림", "baekmukgulim"],
|
|
119
|
+
["백묵바탕", "baekmukbatang"],
|
|
120
|
+
["方正黑體", "fzheiti"],
|
|
121
|
+
["方正楷體", "fzkaitib"],
|
|
122
|
+
["方正明體", "fzmingtib"],
|
|
123
|
+
["方正宋体", "fzsongti"],
|
|
124
|
+
["hy견명조", "hymyeongjoextra"],
|
|
125
|
+
["hy신명조", "hysinmyeongjomedium"],
|
|
126
|
+
["hy중고딕", "hygothicmedium"],
|
|
127
|
+
["hy그래픽m", "hygraphicmedium"],
|
|
128
|
+
["hy그래픽", "hygraphic"],
|
|
129
|
+
["새굴림", "newgulim"],
|
|
130
|
+
["썬궁서", "sungungseo"],
|
|
131
|
+
["hy궁서b", "hygungsobold"],
|
|
132
|
+
["hy궁서", "hygungso"],
|
|
133
|
+
["썬헤드라인", "sunheadline"],
|
|
134
|
+
["hy헤드라인m", "hyheadlinemedium"],
|
|
135
|
+
["hy헤드라인", "hyheadline"],
|
|
136
|
+
["휴먼옛체", "yetr"],
|
|
137
|
+
["hy견고딕", "hygothicextra"],
|
|
138
|
+
["썬목판", "sunmokpan"],
|
|
139
|
+
["썬엽서", "sunyeopseo"],
|
|
140
|
+
["썬백송", "sunbaeksong"],
|
|
141
|
+
["hy엽서l", "hypostlight"],
|
|
142
|
+
["hy엽서", "hypost"],
|
|
143
|
+
["휴먼매직체", "magicr"],
|
|
144
|
+
["썬크리스탈", "suncrystal"],
|
|
145
|
+
["썬샘물", "sunsaemmul"],
|
|
146
|
+
["hy얕은샘물m", "hyshortsamulmedium"],
|
|
147
|
+
["hy얕은샘물", "hyshortsamul"],
|
|
148
|
+
["한컴바탕", "haansoftbatang"],
|
|
149
|
+
["한컴돋움", "haansoftdotum"],
|
|
150
|
+
["한양해서", "hyhaeseo"],
|
|
151
|
+
["md솔체", "mdsol"],
|
|
152
|
+
["md개성체", "mdgaesung"],
|
|
153
|
+
["md아트체", "mdart"],
|
|
154
|
+
["md아롱체", "mdalong"],
|
|
155
|
+
["md이솝체", "mdeasop"],
|
|
156
|
+
["hgゴシックe", "hggothice"],
|
|
157
|
+
["hgpゴシックe", "hgpgothice"],
|
|
158
|
+
["hgsゴシックe", "hgsgothice"],
|
|
159
|
+
["hgゴシックm", "hggothicm"],
|
|
160
|
+
["hgpゴシックm", "hgpgothicm"],
|
|
161
|
+
["hgsゴシックm", "hgsgothicm"],
|
|
162
|
+
["hg行書体", "hggyoshotai"],
|
|
163
|
+
["hgp行書体", "hgpgyoshotai"],
|
|
164
|
+
["hgs行書体", "hgsgyoshotai"],
|
|
165
|
+
["hg教科書体", "hgkyokashotai"],
|
|
166
|
+
["hgp教科書体", "hgpkyokashotai"],
|
|
167
|
+
["hgs教科書体", "hgskyokashotai"],
|
|
168
|
+
["hg明朝b", "hgminchob"],
|
|
169
|
+
["hgp明朝b", "hgpminchob"],
|
|
170
|
+
["hgs明朝b", "hgsminchob"],
|
|
171
|
+
["hg明朝e", "hgminchoe"],
|
|
172
|
+
["hgp明朝e", "hgpminchoe"],
|
|
173
|
+
["hgs明朝e", "hgsminchoe"],
|
|
174
|
+
["hg創英角ポップ体", "hgsoeikakupoptai"],
|
|
175
|
+
["hgp創英角ポップ体", "hgpsoeikakupopta"],
|
|
176
|
+
["hgs創英角ポップ体", "hgssoeikakupopta"],
|
|
177
|
+
["hg創英プレゼンスeb", "hgsoeipresenceeb"],
|
|
178
|
+
["hgp創英プレゼンスeb", "hgpsoeipresenceeb"],
|
|
179
|
+
["hgs創英プレゼンスeb", "hgssoeipresenceeb"],
|
|
180
|
+
["hg創英角ゴシックub", "hgsoeikakugothicub"],
|
|
181
|
+
["hgp創英角ゴシックub", "hgpsoeikakugothicub"],
|
|
182
|
+
["hgs創英角ゴシックub", "hgssoeikakugothicub"],
|
|
183
|
+
["hg正楷書体-pro", "hgseikaishotaipro"],
|
|
184
|
+
["hg丸ゴシック-pro", "hgmarugothicmpro"],
|
|
185
|
+
["ヒラギノ明朝pro", "hiraginominchopro"],
|
|
186
|
+
["ヒラギノ明朝pron", "hiraginominchopron"],
|
|
187
|
+
["ヒラギノ角ゴシック", "hiraginosans"],
|
|
188
|
+
["ヒラギノ角ゴpro", "hiraginokakugothicpro"],
|
|
189
|
+
["ヒラギノ角ゴpron", "hiraginokakugothicpron"],
|
|
190
|
+
["ヒラギノ丸ゴpro", "hiraginomarugothicpro"],
|
|
191
|
+
["ヒラギノ丸ゴpron", "hiraginomarugothicpron"],
|
|
192
|
+
["游ゴシック", "yugothic"],
|
|
193
|
+
["游ゴシック体", "yugothictai"],
|
|
194
|
+
["游明朝", "yumincho"],
|
|
195
|
+
["游明朝体", "yuminchotai"],
|
|
196
|
+
["源ノ角ゴシック", "sourcehansans"],
|
|
197
|
+
["源ノ角ゴシックjp", "sourcehansansjp"],
|
|
198
|
+
["源ノ角ゴシックhw", "sourcehansanshw"],
|
|
199
|
+
["源ノ明朝", "sourcehanserif"],
|
|
200
|
+
["源ノ明朝jp", "sourcehanserifjp"],
|
|
201
|
+
["ipamj明朝", "ipamjmincho"],
|
|
202
|
+
["ipaexゴシック", "ipaexgothic"],
|
|
203
|
+
["ipaex明朝", "ipaexmimcho"]
|
|
204
|
+
]);
|
|
205
|
+
//#endregion
|
|
206
|
+
//#region lib/types/native.js
|
|
207
|
+
/** Per-render native helper process ownership and bounded result transport. */
|
|
208
|
+
const METRIC_SEARCH_NAMES = /* @__PURE__ */ new Map([
|
|
209
|
+
["timesnewroman", "liberationserif"],
|
|
210
|
+
["arial", "liberationsans"],
|
|
211
|
+
["arialnarrow", "liberationsansnarrow"],
|
|
212
|
+
["couriernew", "liberationmono"],
|
|
213
|
+
["cambria", "caladea"],
|
|
214
|
+
["calibri", "carlito"],
|
|
215
|
+
["bundessans", "calibri"],
|
|
216
|
+
["bundessansoffice", "calibri"],
|
|
217
|
+
["bundessansregular", "calibri"],
|
|
218
|
+
["bundesserif", "cambria"],
|
|
219
|
+
["bundesserifoffice", "cambria"],
|
|
220
|
+
["bundesserifregular", "cambria"]
|
|
221
|
+
]);
|
|
222
|
+
/** Environment variables the helper inherits from the embedding process. */
|
|
223
|
+
const NATIVE_ENVIRONMENT_KEYS = [
|
|
224
|
+
"PATH",
|
|
225
|
+
"SystemRoot",
|
|
226
|
+
"SYSTEMROOT",
|
|
227
|
+
"WINDIR",
|
|
228
|
+
"COMSPEC",
|
|
229
|
+
"PATHEXT",
|
|
230
|
+
"LANG",
|
|
231
|
+
"LC_ALL",
|
|
232
|
+
"TZ"
|
|
233
|
+
];
|
|
234
|
+
function fontSearchName(value) {
|
|
235
|
+
const name = value.replaceAll(/[\uff00-\uff5e]/g, (character) => String.fromCharCode(character.charCodeAt(0) - 65248)).replaceAll(/[A-Z]/g, (character) => character.toLowerCase()).replaceAll(/[^a-z0-9;()\u0080-\uffff]/g, "");
|
|
236
|
+
return LOCALIZED_FONT_SEARCH_NAMES.get(name) ?? name;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Write missing-family choices into the private profile's VCL substitution table.
|
|
240
|
+
* Installed originals and metric-compatible fonts are resolved before this table by LibreOffice.
|
|
241
|
+
* @param profile - Existing, conversion-owned profile directory.
|
|
242
|
+
* @param substitutions - Missing document families and the selected installed family.
|
|
243
|
+
* @returns Resolves after the exclusive profile file is written; empty choices create no file.
|
|
244
|
+
*/
|
|
245
|
+
async function prepareNativeFontProfile(profile, substitutions) {
|
|
246
|
+
if (substitutions.length === 0) return;
|
|
247
|
+
const families = new Map(substitutions.map(({ family, substitute }) => [fontSearchName(family), substitute]));
|
|
248
|
+
for (const [family, substitute] of [...families]) for (let alias = METRIC_SEARCH_NAMES.get(family); alias; alias = METRIC_SEARCH_NAMES.get(alias)) if (!families.has(alias)) families.set(alias, substitute);
|
|
249
|
+
const escape = (value) => value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("'", "'");
|
|
250
|
+
const xml = `<?xml version="1.0" encoding="UTF-8"?><oor:items xmlns:oor="http://openoffice.org/2001/registry"><item oor:path="/org.openoffice.VCL/FontSubstitutions/en">${[...families].map(([family, substitute]) => `<node oor:name="${escape(family)}" oor:op="replace"><prop oor:name="SubstFonts" oor:op="fuse"><value>${escape(substitute)}</value></prop></node>`).join("")}</item></oor:items>\n`;
|
|
251
|
+
const user = join(profile, "user");
|
|
252
|
+
await mkdir(user, { mode: 448 });
|
|
253
|
+
await writeFile(join(user, "registrymodifications.xcu"), xml, {
|
|
254
|
+
flag: "wx",
|
|
255
|
+
mode: 384
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Linux searches the verified program directory; ambient loader overrides and credentials are excluded.
|
|
260
|
+
* @param profile - Conversion-owned profile directory the helper treats as home.
|
|
261
|
+
* @param programDirectory - Verified engine program directory.
|
|
262
|
+
* @param source - Embedding process environment.
|
|
263
|
+
* @param platform - Host operating system.
|
|
264
|
+
* @returns the environment the helper starts with.
|
|
265
|
+
*/
|
|
266
|
+
function nativeEnvironment(profile, programDirectory, source = process.env, platform = process.platform) {
|
|
267
|
+
const env = {};
|
|
268
|
+
for (const key of NATIVE_ENVIRONMENT_KEYS) {
|
|
269
|
+
const value = source[key];
|
|
270
|
+
if (value !== void 0) env[key] = value;
|
|
271
|
+
}
|
|
272
|
+
if (platform === "linux") env.LD_LIBRARY_PATH = programDirectory;
|
|
273
|
+
return Object.assign(env, {
|
|
274
|
+
HOME: profile,
|
|
275
|
+
USERPROFILE: profile,
|
|
276
|
+
TMPDIR: profile,
|
|
277
|
+
TMP: profile,
|
|
278
|
+
TEMP: profile
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Run one native conversion and await bounded result transport.
|
|
283
|
+
* @param engine - Resolved native engine installation.
|
|
284
|
+
* @param options - Validated conversion limits.
|
|
285
|
+
* @param input - Private source path inside the conversion scratch directory.
|
|
286
|
+
* @param output - Private PDF path inside the conversion scratch directory.
|
|
287
|
+
* @param profile - Conversion-owned profile directory.
|
|
288
|
+
* @param fonts - Installed font files the helper may load.
|
|
289
|
+
* @param substitutions - Missing families and their selected installed substitutes.
|
|
290
|
+
* @param signal - Cancellation; it kills the helper and awaits its exit.
|
|
291
|
+
* @throws ConversionError for a reported conversion failure, and the abort reason for cancellation.
|
|
292
|
+
*/
|
|
293
|
+
async function runNative(engine, options, input, output, profile, fonts, substitutions, signal) {
|
|
294
|
+
signal.throwIfAborted();
|
|
295
|
+
await prepareNativeFontProfile(profile, substitutions);
|
|
296
|
+
signal.throwIfAborted();
|
|
297
|
+
const env = nativeEnvironment(profile, engine.programDirectory);
|
|
298
|
+
const child = spawn(engine.executable, [
|
|
299
|
+
"--program-directory",
|
|
300
|
+
engine.programDirectory,
|
|
301
|
+
"--input-path",
|
|
302
|
+
input,
|
|
303
|
+
"--output-path",
|
|
304
|
+
output,
|
|
305
|
+
"--profile-directory",
|
|
306
|
+
profile,
|
|
307
|
+
"--max-output-bytes",
|
|
308
|
+
String(options.maxOutputBytes),
|
|
309
|
+
"--max-image-resolution",
|
|
310
|
+
String(options.maxImageResolution),
|
|
311
|
+
...fonts.flatMap((path) => ["--font-file", path])
|
|
312
|
+
], {
|
|
313
|
+
stdio: [
|
|
314
|
+
"ignore",
|
|
315
|
+
"pipe",
|
|
316
|
+
"pipe"
|
|
317
|
+
],
|
|
318
|
+
windowsHide: true,
|
|
319
|
+
env
|
|
320
|
+
});
|
|
321
|
+
let stdout = "";
|
|
322
|
+
let stderr = "";
|
|
323
|
+
let failure;
|
|
324
|
+
const abort = () => {
|
|
325
|
+
failure ??= signal.reason;
|
|
326
|
+
child.kill("SIGKILL");
|
|
327
|
+
};
|
|
328
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
329
|
+
child.stdout.setEncoding("utf8");
|
|
330
|
+
child.stderr.setEncoding("utf8");
|
|
331
|
+
child.stdout.on("data", (chunk) => {
|
|
332
|
+
stdout += chunk;
|
|
333
|
+
if (stdout.length > 65536) {
|
|
334
|
+
failure ??= /* @__PURE__ */ new Error("LibreOffice helper exceeded its response limit.");
|
|
335
|
+
child.kill("SIGKILL");
|
|
336
|
+
}
|
|
337
|
+
});
|
|
338
|
+
child.stderr.on("data", (chunk) => {
|
|
339
|
+
stderr = (stderr + chunk).slice(-65536);
|
|
340
|
+
});
|
|
341
|
+
try {
|
|
342
|
+
const code = await new Promise((resolve, reject) => {
|
|
343
|
+
child.once("error", (error) => {
|
|
344
|
+
failure ??= error;
|
|
345
|
+
});
|
|
346
|
+
child.once("close", (code, signal) => {
|
|
347
|
+
if (signal === "SIGXFSZ") failure ??= new ConversionError("output-too-large", "LibreOffice exceeded its output file-size limit.");
|
|
348
|
+
if (failure) reject(failure);
|
|
349
|
+
else resolve(code);
|
|
350
|
+
});
|
|
351
|
+
});
|
|
352
|
+
signal.throwIfAborted();
|
|
353
|
+
let result;
|
|
354
|
+
try {
|
|
355
|
+
result = JSON.parse(stdout);
|
|
356
|
+
} catch (cause) {
|
|
357
|
+
throw new Error(`LibreOffice helper returned an invalid response (exit ${code}). ${stderr}`, { cause });
|
|
358
|
+
}
|
|
359
|
+
if (code !== 0 || result.ok !== true) throw new ConversionError(failureCode(result), `LibreOffice native conversion failed: ${result.error ?? stderr}`);
|
|
360
|
+
} finally {
|
|
361
|
+
signal.removeEventListener("abort", abort);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
//#endregion
|
|
365
|
+
//#region lib/types/fonts.js
|
|
366
|
+
/** Host font metadata snapshots and conversion-local glyph matching over original files. */
|
|
367
|
+
/**
|
|
368
|
+
* @param error - Thrown filesystem value.
|
|
369
|
+
* @returns whether it means the path is not a usable font source.
|
|
370
|
+
*/
|
|
371
|
+
function absent(error) {
|
|
372
|
+
return error instanceof Error && "code" in error && [
|
|
373
|
+
"ENOENT",
|
|
374
|
+
"EACCES",
|
|
375
|
+
"EPERM",
|
|
376
|
+
"ENOTDIR"
|
|
377
|
+
].includes(String(error.code));
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Discover system and per-user font roots using the selected platform's path separators.
|
|
381
|
+
* @param platform - Host operating system.
|
|
382
|
+
* @param home - Host user home used to locate per-user font directories.
|
|
383
|
+
* @param env - Host environment containing Windows and XDG directory overrides.
|
|
384
|
+
* @returns candidate directories; missing platform directories are ignored during indexing.
|
|
385
|
+
*/
|
|
386
|
+
function systemFontDirectories(platform = process.platform, home = homedir(), env = process.env) {
|
|
387
|
+
if (platform === "win32") return [win32.join(env.SystemRoot ?? "C:\\Windows", "Fonts"), win32.join(env.LOCALAPPDATA ?? win32.join(home, "AppData", "Local"), "Microsoft", "Windows", "Fonts")];
|
|
388
|
+
if (platform === "darwin") return [
|
|
389
|
+
"/System/Library/Fonts",
|
|
390
|
+
"/Library/Fonts",
|
|
391
|
+
posix.join(home, "Library/Fonts"),
|
|
392
|
+
...mobileAssetFontDirectories("/System/Library/AssetsV2")
|
|
393
|
+
];
|
|
394
|
+
const shared = (env.XDG_DATA_DIRS ?? "/usr/local/share:/usr/share").split(":").filter(Boolean);
|
|
395
|
+
return [.../* @__PURE__ */ new Set([
|
|
396
|
+
...shared.map((path) => posix.join(path, "fonts")),
|
|
397
|
+
posix.join(home, ".fonts"),
|
|
398
|
+
posix.join(env.XDG_DATA_HOME ?? posix.join(home, ".local/share"), "fonts")
|
|
399
|
+
])];
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Font asset directories macOS publishes under its MobileAsset root.
|
|
403
|
+
* @param assets - Absolute MobileAsset font directory root.
|
|
404
|
+
* @returns matching asset directories, sorted by name.
|
|
405
|
+
* @throws when the root exists but cannot be read for a reason other than its absence or protection.
|
|
406
|
+
*/
|
|
407
|
+
function mobileAssetFontDirectories(assets) {
|
|
408
|
+
let entries = [];
|
|
409
|
+
try {
|
|
410
|
+
entries = readdirSync(assets);
|
|
411
|
+
} catch (error) {
|
|
412
|
+
if (!absent(error)) throw error;
|
|
413
|
+
}
|
|
414
|
+
return entries.filter((name) => /^com_apple_MobileAsset_Font\d*$/.test(name)).sort().map((name) => join(assets, name));
|
|
415
|
+
}
|
|
416
|
+
//#endregion
|
|
417
|
+
//#region lib/types/options.js
|
|
418
|
+
const SANS_CJK_FAMILIES = [
|
|
419
|
+
"Microsoft YaHei",
|
|
420
|
+
"Microsoft YaHei UI",
|
|
421
|
+
"微软雅黑",
|
|
422
|
+
"PingFang SC",
|
|
423
|
+
"Noto Sans CJK SC",
|
|
424
|
+
"Noto Sans SC",
|
|
425
|
+
"Source Han Sans SC",
|
|
426
|
+
"SimHei",
|
|
427
|
+
"黑体",
|
|
428
|
+
"Heiti SC",
|
|
429
|
+
"STHeiti"
|
|
430
|
+
];
|
|
431
|
+
/** Ordered family groups used when the caller supplies none. */
|
|
432
|
+
const FONT_FALLBACKS = [
|
|
433
|
+
["Calibri", "Carlito"],
|
|
434
|
+
[
|
|
435
|
+
"Calibri Light",
|
|
436
|
+
"Carlito",
|
|
437
|
+
"Calibri"
|
|
438
|
+
],
|
|
439
|
+
["Cambria", "Caladea"],
|
|
440
|
+
[
|
|
441
|
+
"宋体",
|
|
442
|
+
"SimSun",
|
|
443
|
+
"NSimSun",
|
|
444
|
+
"Songti SC",
|
|
445
|
+
"STSong",
|
|
446
|
+
"Noto Serif CJK SC",
|
|
447
|
+
"Noto Serif SC",
|
|
448
|
+
"Source Han Serif SC"
|
|
449
|
+
],
|
|
450
|
+
[
|
|
451
|
+
"黑体",
|
|
452
|
+
"SimHei",
|
|
453
|
+
"Heiti SC",
|
|
454
|
+
"STHeiti",
|
|
455
|
+
"Noto Sans CJK SC",
|
|
456
|
+
"Noto Sans SC",
|
|
457
|
+
"Source Han Sans SC"
|
|
458
|
+
],
|
|
459
|
+
[
|
|
460
|
+
"微软雅黑",
|
|
461
|
+
"Microsoft YaHei",
|
|
462
|
+
"Microsoft YaHei UI",
|
|
463
|
+
"PingFang SC",
|
|
464
|
+
"Noto Sans CJK SC",
|
|
465
|
+
"Noto Sans SC"
|
|
466
|
+
],
|
|
467
|
+
[
|
|
468
|
+
"楷体",
|
|
469
|
+
"KaiTi",
|
|
470
|
+
"Kaiti SC",
|
|
471
|
+
"STKaiti",
|
|
472
|
+
"LXGW WenKai"
|
|
473
|
+
],
|
|
474
|
+
[
|
|
475
|
+
"仿宋",
|
|
476
|
+
"FangSong",
|
|
477
|
+
"STFangsong",
|
|
478
|
+
"Songti SC",
|
|
479
|
+
"Noto Serif CJK SC"
|
|
480
|
+
],
|
|
481
|
+
[
|
|
482
|
+
"sans-serif",
|
|
483
|
+
"Arial",
|
|
484
|
+
"Liberation Sans",
|
|
485
|
+
"Helvetica",
|
|
486
|
+
"DejaVu Sans",
|
|
487
|
+
"Calibri",
|
|
488
|
+
"Calibri Light",
|
|
489
|
+
"Carlito",
|
|
490
|
+
...SANS_CJK_FAMILIES
|
|
491
|
+
],
|
|
492
|
+
[
|
|
493
|
+
"serif",
|
|
494
|
+
"Times New Roman",
|
|
495
|
+
"Liberation Serif",
|
|
496
|
+
"Times",
|
|
497
|
+
"DejaVu Serif",
|
|
498
|
+
"Cambria",
|
|
499
|
+
"Caladea",
|
|
500
|
+
"SimSun",
|
|
501
|
+
"NSimSun",
|
|
502
|
+
"宋体",
|
|
503
|
+
"Songti SC",
|
|
504
|
+
"STSong",
|
|
505
|
+
"Noto Serif CJK SC",
|
|
506
|
+
"Noto Serif SC",
|
|
507
|
+
"Source Han Serif SC"
|
|
508
|
+
],
|
|
509
|
+
[
|
|
510
|
+
"monospace",
|
|
511
|
+
"Courier New",
|
|
512
|
+
"Liberation Mono",
|
|
513
|
+
"DejaVu Sans Mono",
|
|
514
|
+
"Menlo",
|
|
515
|
+
"Monaco",
|
|
516
|
+
"Courier",
|
|
517
|
+
"NSimSun",
|
|
518
|
+
"Noto Sans Mono CJK SC",
|
|
519
|
+
...SANS_CJK_FAMILIES
|
|
520
|
+
],
|
|
521
|
+
[
|
|
522
|
+
"Symbol",
|
|
523
|
+
"Standard Symbols PS",
|
|
524
|
+
"Symbola",
|
|
525
|
+
"Segoe UI Symbol",
|
|
526
|
+
"Apple Symbols",
|
|
527
|
+
"FreeSerif",
|
|
528
|
+
"DejaVu Sans"
|
|
529
|
+
]
|
|
530
|
+
];
|
|
531
|
+
const DEFAULT_LIMITS = {
|
|
532
|
+
timeoutMs: 12e4,
|
|
533
|
+
maxInputBytes: 67108864,
|
|
534
|
+
maxOutputBytes: 134217728,
|
|
535
|
+
maxImageResolution: 144,
|
|
536
|
+
maxArchiveEntries: 2e4,
|
|
537
|
+
maxUncompressedBytes: 536870912,
|
|
538
|
+
maxFontFiles: 2e4,
|
|
539
|
+
maxFontFileBytes: 268435456,
|
|
540
|
+
maxLoadedFontBytes: 536870912
|
|
541
|
+
};
|
|
542
|
+
const FONT_COLLECTION_NAMES = ["fontDirectories", "initialFontFamilies"];
|
|
543
|
+
function positiveSafeInteger(value, name) {
|
|
544
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) throw new RangeError(`${name} must be a positive safe integer.`);
|
|
545
|
+
if (name.endsWith("Ms") && value > 2147483647) throw new RangeError(`${name} exceeds the Node timer range.`);
|
|
546
|
+
return value;
|
|
547
|
+
}
|
|
548
|
+
function fontNames(value, name) {
|
|
549
|
+
if (!Array.isArray(value)) throw new TypeError(`${name} must contain nonempty strings.`);
|
|
550
|
+
const names = [];
|
|
551
|
+
for (const entry of value) {
|
|
552
|
+
if (typeof entry !== "string" || entry.length === 0 || entry.includes("\0")) throw new TypeError(`${name} must contain nonempty strings.`);
|
|
553
|
+
names.push(entry);
|
|
554
|
+
}
|
|
555
|
+
return names;
|
|
556
|
+
}
|
|
557
|
+
function fontGroups(value) {
|
|
558
|
+
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.");
|
|
559
|
+
return value.map((group) => [...group]);
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Resolve defaults once; reject misspelled options and malformed font settings.
|
|
563
|
+
* @param input - Caller options; absent fields keep their documented default.
|
|
564
|
+
* @returns The validated limits and font settings, with caller arrays copied.
|
|
565
|
+
* @throws TypeError for a non-object argument or an unknown option name.
|
|
566
|
+
* @throws RangeError for a limit outside the positive safe-integer timer range.
|
|
567
|
+
*/
|
|
568
|
+
function resolveOptions(input = {}) {
|
|
569
|
+
const callerOptions = input;
|
|
570
|
+
if (callerOptions === null || typeof callerOptions !== "object" || Array.isArray(callerOptions)) throw new TypeError("Converter options must be an object.");
|
|
571
|
+
const merged = {
|
|
572
|
+
...DEFAULT_LIMITS,
|
|
573
|
+
fontDirectories: systemFontDirectories(),
|
|
574
|
+
fontFallbacks: FONT_FALLBACKS,
|
|
575
|
+
initialFontFamilies: [],
|
|
576
|
+
...input
|
|
577
|
+
};
|
|
578
|
+
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}`);
|
|
579
|
+
return {
|
|
580
|
+
timeoutMs: positiveSafeInteger(merged.timeoutMs, "timeoutMs"),
|
|
581
|
+
maxInputBytes: positiveSafeInteger(merged.maxInputBytes, "maxInputBytes"),
|
|
582
|
+
maxOutputBytes: positiveSafeInteger(merged.maxOutputBytes, "maxOutputBytes"),
|
|
583
|
+
maxImageResolution: positiveSafeInteger(merged.maxImageResolution, "maxImageResolution"),
|
|
584
|
+
maxArchiveEntries: positiveSafeInteger(merged.maxArchiveEntries, "maxArchiveEntries"),
|
|
585
|
+
maxUncompressedBytes: positiveSafeInteger(merged.maxUncompressedBytes, "maxUncompressedBytes"),
|
|
586
|
+
maxFontFiles: positiveSafeInteger(merged.maxFontFiles, "maxFontFiles"),
|
|
587
|
+
maxFontFileBytes: positiveSafeInteger(merged.maxFontFileBytes, "maxFontFileBytes"),
|
|
588
|
+
maxLoadedFontBytes: positiveSafeInteger(merged.maxLoadedFontBytes, "maxLoadedFontBytes"),
|
|
589
|
+
fontDirectories: fontNames(merged.fontDirectories, "fontDirectories"),
|
|
590
|
+
initialFontFamilies: fontNames(merged.initialFontFamilies, "initialFontFamilies"),
|
|
591
|
+
fontFallbacks: fontGroups(merged.fontFallbacks)
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
//#endregion
|
|
595
|
+
//#region lib/types/engine.js
|
|
596
|
+
/** Resolve installed, version-matched engine packages without downloads or compilation. */
|
|
597
|
+
const require = createRequire(import.meta.url);
|
|
598
|
+
/**
|
|
599
|
+
* Engine-family version every installed engine package must carry. The engine
|
|
600
|
+
* family shares its release version with this Node API.
|
|
601
|
+
*/
|
|
602
|
+
const ENGINE_VERSION = "0.0.1";
|
|
603
|
+
/** npm scope and name prefix shared by the engine packages this adapter installs. */
|
|
604
|
+
const ENGINE_PREFIX = "@deepseek-ai/libreoffice-kit";
|
|
605
|
+
/**
|
|
606
|
+
* Whether an installed engine package directory is present on the resolution path.
|
|
607
|
+
* @param name - Engine package name.
|
|
608
|
+
* @returns true when at least one resolution directory holds the package.
|
|
609
|
+
*/
|
|
610
|
+
function installedPackageExists(name) {
|
|
611
|
+
return (require.resolve.paths(name) ?? []).some((directory) => lstatSync(join(directory, name), { throwIfNoEntry: false }) !== void 0);
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* Return the optional package target for the current process ABI.
|
|
615
|
+
* @param platform - Host operating system.
|
|
616
|
+
* @param arch - Host CPU architecture.
|
|
617
|
+
* @param report - Host diagnostic report used to identify glibc.
|
|
618
|
+
* @returns the declared platform target, or undefined for an unsupported host.
|
|
619
|
+
*/
|
|
620
|
+
function platformTarget(platform = process.platform, arch = process.arch, report = hostReport) {
|
|
621
|
+
if (!["arm64", "x64"].includes(arch)) return void 0;
|
|
622
|
+
if (platform === "darwin" || platform === "win32") return `${platform}-${arch}`;
|
|
623
|
+
if (platform !== "linux") return void 0;
|
|
624
|
+
return report().header?.glibcVersionRuntime ? `linux-${arch}-glibc` : void 0;
|
|
625
|
+
}
|
|
626
|
+
/** @returns the host diagnostic report as the engine resolver reads it. */
|
|
627
|
+
function hostReport() {
|
|
628
|
+
return process.report.getReport();
|
|
629
|
+
}
|
|
630
|
+
function asset(root, value) {
|
|
631
|
+
if (typeof value !== "string" || !value || isAbsolute(value)) throw new Error("Engine manifest contains an invalid asset path.");
|
|
632
|
+
const path = resolve(root, value);
|
|
633
|
+
if (relative(root, path).startsWith(`..${sep}`) || relative(root, path) === "..") throw new Error("Engine asset escapes its installed package.");
|
|
634
|
+
return path;
|
|
635
|
+
}
|
|
636
|
+
function glibcVersion(value) {
|
|
637
|
+
return typeof value === "string" && /^(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?$/.test(value) && value.split(".").every((part) => Number.isSafeInteger(Number(part))) ? value.split(".").map(Number) : void 0;
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* macOS and Windows require their native engine. Linux uses WASM when no compatible development native engine is installed.
|
|
641
|
+
* @param resolvePackage - Package manifest resolver; injectable for selection tests.
|
|
642
|
+
* @param packageExists - Installed-package probe; injectable for selection tests.
|
|
643
|
+
* @param host - Process identification and diagnostic report.
|
|
644
|
+
* @returns the installed native engine, or the installed WASM engine.
|
|
645
|
+
*/
|
|
646
|
+
async function resolveEngine(resolvePackage = (name) => require.resolve(`${name}/package.json`), packageExists = installedPackageExists, { platform = process.platform, arch = process.arch, report = hostReport } = {}) {
|
|
647
|
+
const details = platform === "linux" ? report() : {};
|
|
648
|
+
const target = platformTarget(platform, arch, () => details);
|
|
649
|
+
if (target !== void 0) {
|
|
650
|
+
const name = `${ENGINE_PREFIX}-${target}`;
|
|
651
|
+
let packageFile;
|
|
652
|
+
try {
|
|
653
|
+
packageFile = resolvePackage(name);
|
|
654
|
+
} catch (error) {
|
|
655
|
+
const failure = error;
|
|
656
|
+
if (!(failure?.code === "MODULE_NOT_FOUND" && typeof failure.message === "string" && failure.message.includes(`${name}/package.json`))) throw error;
|
|
657
|
+
if (packageExists(name)) throw new Error(`Installed LibreOfficeKit package is incomplete: ${name}`, { cause: error });
|
|
658
|
+
if (platform !== "linux") throw new Error(`Required LibreOfficeKit native package is missing: ${name}`, { cause: error });
|
|
659
|
+
}
|
|
660
|
+
if (packageFile !== void 0) {
|
|
661
|
+
const engine = await readEngine(packageFile, "native", target);
|
|
662
|
+
const minimum = glibcVersion(engine.glibcMinimum);
|
|
663
|
+
const host = glibcVersion(details.header?.glibcVersionRuntime);
|
|
664
|
+
if (!(minimum && host && minimum.some((part, index) => part > (host[index] ?? 0) && minimum.slice(0, index).every((prior, priorIndex) => prior === host[priorIndex])))) return engine;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
if (platform !== "linux") throw new Error(`Unsupported LibreOfficeKit host: ${platform}-${arch}`);
|
|
668
|
+
return readEngine(resolvePackage(`${ENGINE_PREFIX}-wasm`), "wasm", "wasm");
|
|
669
|
+
}
|
|
670
|
+
async function engineAsset(root, value, name, kind) {
|
|
671
|
+
const path = asset(root, value);
|
|
672
|
+
const status = await stat(path);
|
|
673
|
+
if (kind === "directory" ? !status.isDirectory() : !status.isFile()) throw new Error(`Installed LibreOfficeKit ${name} is not a ${kind}.`);
|
|
674
|
+
if (name === "executable" && process.platform !== "win32" && !(status.mode & 73)) throw new Error("Installed LibreOfficeKit executable is not executable.");
|
|
675
|
+
return path;
|
|
676
|
+
}
|
|
677
|
+
async function readEngine(packageFile, backend, target) {
|
|
678
|
+
const root = dirname(packageFile);
|
|
679
|
+
const [pkg, manifest] = await Promise.all([readFile(packageFile, "utf8").then((text) => JSON.parse(text)), readFile(resolve(root, "prebuilds.json"), "utf8").then((text) => JSON.parse(text))]);
|
|
680
|
+
const engine = manifest.engine;
|
|
681
|
+
if (pkg.name !== `${ENGINE_PREFIX}-${target}` || pkg.version !== "0.0.1" || manifest.version !== pkg.version || manifest.schemaVersion !== 1 || manifest.status !== "built" || engine === void 0 || engine.kind !== backend || manifest.platform !== target) throw new Error(`Installed LibreOfficeKit ${backend} package has an incompatible or incomplete manifest.`);
|
|
682
|
+
const minimum = engine.glibcMinimum;
|
|
683
|
+
if (minimum !== void 0 && (!target.endsWith("-glibc") || !glibcVersion(minimum))) throw new Error("Installed LibreOfficeKit engine has an invalid glibcMinimum.");
|
|
684
|
+
const glibcFloor = minimum === void 0 ? {} : { glibcMinimum: minimum };
|
|
685
|
+
if (backend === "native") {
|
|
686
|
+
const executable = await engineAsset(root, engine.executable, "executable", "file");
|
|
687
|
+
return {
|
|
688
|
+
backend,
|
|
689
|
+
root,
|
|
690
|
+
programDirectory: await engineAsset(root, engine.programDirectory, "programDirectory", "directory"),
|
|
691
|
+
executable,
|
|
692
|
+
...glibcFloor
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
return {
|
|
696
|
+
backend,
|
|
697
|
+
root,
|
|
698
|
+
programDirectory: String(engine.programDirectory),
|
|
699
|
+
loader: await engineAsset(root, engine.loader, "loader", "file"),
|
|
700
|
+
wasm: await engineAsset(root, engine.wasm, "wasm", "file"),
|
|
701
|
+
data: await engineAsset(root, engine.data, "data", "file"),
|
|
702
|
+
metadata: await engineAsset(root, engine.metadata, "metadata", "file"),
|
|
703
|
+
...glibcFloor
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
//#endregion
|
|
707
|
+
//#region lib/types/document.js
|
|
708
|
+
/** Input suffixes accepted by the public converter. */
|
|
709
|
+
const DOCUMENT_EXTENSIONS = [
|
|
710
|
+
"doc",
|
|
711
|
+
"docx",
|
|
712
|
+
"xls",
|
|
713
|
+
"xlsx",
|
|
714
|
+
"ppt",
|
|
715
|
+
"pptx"
|
|
716
|
+
];
|
|
717
|
+
//#endregion
|
|
718
|
+
//#region lib/types/index.js
|
|
719
|
+
/** Convert caller-authorized disk documents with installed native or Node WASM engines. */
|
|
720
|
+
/** File identity that must match across a bounded read. */
|
|
721
|
+
const CHANGED_KEYS = [
|
|
722
|
+
"size",
|
|
723
|
+
"mtimeMs",
|
|
724
|
+
"ctimeMs"
|
|
725
|
+
];
|
|
726
|
+
async function readBounded(path, limit, signal, role) {
|
|
727
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
|
|
728
|
+
try {
|
|
729
|
+
const before = await file.stat();
|
|
730
|
+
const invalid = role === "input" ? "invalid-document" : "invalid-output";
|
|
731
|
+
if (!before.isFile() || before.size < 1) throw new ConversionError(invalid, "Document must be a nonempty regular file.");
|
|
732
|
+
if (before.size > limit) throw new ConversionError(`${role}-too-large`, `Document exceeds its ${role} byte limit.`);
|
|
733
|
+
const bytes = Buffer.alloc(before.size);
|
|
734
|
+
for (let offset = 0; offset < bytes.length;) {
|
|
735
|
+
signal.throwIfAborted();
|
|
736
|
+
const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset);
|
|
737
|
+
if (!bytesRead) throw new ConversionError(invalid, "Document was truncated while reading.");
|
|
738
|
+
offset += bytesRead;
|
|
739
|
+
}
|
|
740
|
+
const after = await file.stat();
|
|
741
|
+
if (CHANGED_KEYS.some((key) => before[key] !== after[key])) throw new ConversionError(invalid, "Document changed while reading.");
|
|
742
|
+
signal.throwIfAborted();
|
|
743
|
+
return bytes;
|
|
744
|
+
} finally {
|
|
745
|
+
await file.close();
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
async function runWorker(data, signal, onFonts) {
|
|
749
|
+
signal.throwIfAborted();
|
|
750
|
+
const worker = new Worker(new URL("./worker.js", import.meta.url), {
|
|
751
|
+
workerData: data,
|
|
752
|
+
name: "libreoffice-conversion",
|
|
753
|
+
execArgv: [],
|
|
754
|
+
stdout: true,
|
|
755
|
+
stderr: true
|
|
756
|
+
});
|
|
757
|
+
worker.stdout.resume();
|
|
758
|
+
worker.stderr.resume();
|
|
759
|
+
const settled = Promise.withResolvers();
|
|
760
|
+
const abort = () => {
|
|
761
|
+
settled.reject(signal.reason);
|
|
762
|
+
};
|
|
763
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
764
|
+
worker.once("error", settled.reject);
|
|
765
|
+
worker.once("exit", (code) => {
|
|
766
|
+
settled.reject(new ConversionError("failed", `LibreOffice worker exited before returning a result (${code}).`));
|
|
767
|
+
});
|
|
768
|
+
worker.on("message", (message) => {
|
|
769
|
+
if (message.kind === "fonts") onFonts(message.faces);
|
|
770
|
+
else if (message.ok) settled.resolve(message);
|
|
771
|
+
else settled.reject(new ConversionError(failureCode(message), message.error));
|
|
772
|
+
});
|
|
773
|
+
try {
|
|
774
|
+
return await settled.promise;
|
|
775
|
+
} finally {
|
|
776
|
+
signal.removeEventListener("abort", abort);
|
|
777
|
+
await worker.terminate();
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* Resolve the installed engine and deployment limits without starting LibreOffice.
|
|
782
|
+
* @param options - Conversion, font, and output limits.
|
|
783
|
+
* @returns A serial converter; dispose it after use.
|
|
784
|
+
* @throws TypeError for invalid options, or an unavailable ConversionError for invalid installed engines.
|
|
785
|
+
* An absent native engine or a known unsupported glibc version selects WASM.
|
|
786
|
+
*/
|
|
787
|
+
async function createConverter(options) {
|
|
788
|
+
const resolvedOptions = resolveOptions(options);
|
|
789
|
+
let engine;
|
|
790
|
+
try {
|
|
791
|
+
engine = await resolveEngine();
|
|
792
|
+
} catch (cause) {
|
|
793
|
+
throw new ConversionError("unavailable", cause.message, { cause });
|
|
794
|
+
}
|
|
795
|
+
const lifetime = new AbortController();
|
|
796
|
+
const active = /* @__PURE__ */ new Set();
|
|
797
|
+
const waiting = /* @__PURE__ */ new Set();
|
|
798
|
+
let running = false;
|
|
799
|
+
let disposal;
|
|
800
|
+
let fontFaces;
|
|
801
|
+
async function acquire(signal) {
|
|
802
|
+
while (running) {
|
|
803
|
+
signal.throwIfAborted();
|
|
804
|
+
await new Promise((resolve, reject) => {
|
|
805
|
+
const cleanup = () => {
|
|
806
|
+
waiting.delete(wake);
|
|
807
|
+
signal.removeEventListener("abort", abort);
|
|
808
|
+
};
|
|
809
|
+
const wake = () => {
|
|
810
|
+
cleanup();
|
|
811
|
+
resolve();
|
|
812
|
+
};
|
|
813
|
+
const abort = () => {
|
|
814
|
+
cleanup();
|
|
815
|
+
reject(signal.reason);
|
|
816
|
+
};
|
|
817
|
+
waiting.add(wake);
|
|
818
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
819
|
+
});
|
|
820
|
+
}
|
|
821
|
+
signal.throwIfAborted();
|
|
822
|
+
running = true;
|
|
823
|
+
}
|
|
824
|
+
async function render(request, signal) {
|
|
825
|
+
if (!request || typeof request.inputPath !== "string" || typeof request.outputPath !== "string" || !isAbsolute(request.inputPath) || !isAbsolute(request.outputPath) || request.inputPath.includes("\0") || request.outputPath.includes("\0")) throw new TypeError("inputPath and outputPath must be absolute filesystem paths.");
|
|
826
|
+
if (resolve(request.inputPath) === resolve(request.outputPath)) throw new Error("Input and output paths must differ.");
|
|
827
|
+
const extension = extname(request.inputPath).slice(1).toLowerCase();
|
|
828
|
+
if (!DOCUMENT_EXTENSIONS.includes(extension)) throw new ConversionError("unsupported-format", `Input extension must be ${DOCUMENT_EXTENSIONS.join(", ")}.`);
|
|
829
|
+
await acquire(signal);
|
|
830
|
+
const deadline = new AbortController();
|
|
831
|
+
const stopped = AbortSignal.any([signal, deadline.signal]);
|
|
832
|
+
const timer = setTimeout(() => {
|
|
833
|
+
deadline.abort(new ConversionError("timeout", "LibreOffice conversion timed out."));
|
|
834
|
+
}, resolvedOptions.timeoutMs);
|
|
835
|
+
let scratch;
|
|
836
|
+
let output;
|
|
837
|
+
let succeeded = false;
|
|
838
|
+
let failure;
|
|
839
|
+
try {
|
|
840
|
+
stopped.throwIfAborted();
|
|
841
|
+
output = await open(request.outputPath, "wx", 384);
|
|
842
|
+
const bytes = await readBounded(request.inputPath, resolvedOptions.maxInputBytes, stopped, "input");
|
|
843
|
+
scratch = await mkdtemp(join(tmpdir(), "libreoffice-kit-"));
|
|
844
|
+
const inputPath = join(scratch, `document.${extension}`);
|
|
845
|
+
const input = await open(inputPath, "wx", 384);
|
|
846
|
+
try {
|
|
847
|
+
await input.writeFile(bytes);
|
|
848
|
+
} finally {
|
|
849
|
+
await input.close();
|
|
850
|
+
}
|
|
851
|
+
const result = await runWorker({
|
|
852
|
+
inputPath,
|
|
853
|
+
extension,
|
|
854
|
+
options: resolvedOptions,
|
|
855
|
+
engine,
|
|
856
|
+
scratch,
|
|
857
|
+
fontFaces
|
|
858
|
+
}, stopped, (faces) => {
|
|
859
|
+
fontFaces = faces;
|
|
860
|
+
});
|
|
861
|
+
let pdf;
|
|
862
|
+
if ("pdf" in result) pdf = result.pdf;
|
|
863
|
+
else {
|
|
864
|
+
const native = engine;
|
|
865
|
+
const profile = join(scratch, "profile");
|
|
866
|
+
await mkdir(profile, { mode: 448 });
|
|
867
|
+
const path = join(scratch, "document.pdf");
|
|
868
|
+
await runNative(native, resolvedOptions, inputPath, path, profile, result.fonts, result.substitutions, stopped);
|
|
869
|
+
pdf = await readBounded(path, resolvedOptions.maxOutputBytes, stopped, "output");
|
|
870
|
+
}
|
|
871
|
+
if (Buffer.from(pdf.subarray(0, 5)).toString() !== "%PDF-") throw new ConversionError("invalid-output", "LibreOffice did not produce a PDF.");
|
|
872
|
+
stopped.throwIfAborted();
|
|
873
|
+
await output.writeFile(pdf);
|
|
874
|
+
stopped.throwIfAborted();
|
|
875
|
+
succeeded = true;
|
|
876
|
+
return {
|
|
877
|
+
backend: engine.backend,
|
|
878
|
+
missingFonts: result.missingFonts
|
|
879
|
+
};
|
|
880
|
+
} catch (error) {
|
|
881
|
+
failure = error;
|
|
882
|
+
throw error;
|
|
883
|
+
} finally {
|
|
884
|
+
clearTimeout(timer);
|
|
885
|
+
try {
|
|
886
|
+
const errors = [];
|
|
887
|
+
try {
|
|
888
|
+
await output?.close();
|
|
889
|
+
} catch (error) {
|
|
890
|
+
errors.push(error);
|
|
891
|
+
}
|
|
892
|
+
const cleanup = await Promise.allSettled([...output && !succeeded ? [unlink(request.outputPath)] : [], ...scratch ? [rm(scratch, {
|
|
893
|
+
recursive: true,
|
|
894
|
+
force: true
|
|
895
|
+
})] : []]);
|
|
896
|
+
for (const result of cleanup) if (result.status === "rejected") errors.push(result.reason);
|
|
897
|
+
if (errors.length) throw new AggregateError(failure ? [failure, ...errors] : errors, "LibreOffice conversion cleanup failed.");
|
|
898
|
+
} finally {
|
|
899
|
+
running = false;
|
|
900
|
+
for (const wake of [...waiting]) wake();
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
return {
|
|
905
|
+
backend: engine.backend,
|
|
906
|
+
render(request, signal) {
|
|
907
|
+
const task = render(request, signal ? AbortSignal.any([signal, lifetime.signal]) : lifetime.signal);
|
|
908
|
+
active.add(task);
|
|
909
|
+
task.finally(() => {
|
|
910
|
+
active.delete(task);
|
|
911
|
+
}).catch((_error) => {});
|
|
912
|
+
return task;
|
|
913
|
+
},
|
|
914
|
+
dispose() {
|
|
915
|
+
disposal ??= (async () => {
|
|
916
|
+
lifetime.abort(/* @__PURE__ */ new Error("LibreOffice converter is disposed."));
|
|
917
|
+
await Promise.allSettled(active);
|
|
918
|
+
})();
|
|
919
|
+
return disposal;
|
|
920
|
+
}
|
|
921
|
+
};
|
|
922
|
+
}
|
|
923
|
+
//#endregion
|
|
924
|
+
export { ConversionError, ENGINE_VERSION, createConverter };
|