@deepseek-ai/libreoffice-kit 0.1.2 → 0.1.4

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/lib/index.js CHANGED
@@ -1,10 +1,13 @@
1
1
  import { createRequire } from "node:module";
2
- import { constants, lstatSync, readdirSync } from "node:fs";
3
- import { lstat, mkdir, mkdtemp, open, readFile, rm, stat, unlink, writeFile } from "node:fs/promises";
2
+ import { closeSync, constants, createWriteStream, lstatSync, readSync, readdirSync } from "node:fs";
3
+ import { copyFile, lstat, mkdir, mkdtemp, open, readFile, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import { dirname, extname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
6
6
  import { Worker } from "node:worker_threads";
7
7
  import { spawn } from "node:child_process";
8
+ import { EventEmitter } from "node:events";
9
+ import { Readable } from "node:stream";
10
+ import { finished } from "node:stream/promises";
8
11
  import { createHash, randomUUID } from "node:crypto";
9
12
  import { createInterface } from "node:readline";
10
13
  import { zlibSync } from "fflate";
@@ -315,6 +318,164 @@ function selectedPages(pages, count, limit) {
315
318
  return result;
316
319
  }
317
320
  //#endregion
321
+ //#region lib/types/native-process.js
322
+ /** Native helper stdio; Windows anonymous pipes retain the caller's restricted-token permissions. */
323
+ function windowsPipes() {
324
+ const koffi = createRequire(import.meta.url)("koffi");
325
+ const kernel = koffi.load("kernel32.dll"), node = koffi.load(null);
326
+ const createPipe = kernel.func("int __stdcall CreatePipe(_Out_ void **read, _Out_ void **write, void *attributes, uint32 size)");
327
+ const closeHandle = kernel.func("int __stdcall CloseHandle(void *handle)");
328
+ const peek = kernel.func("int __stdcall PeekNamedPipe(void *pipe, void *buffer, uint32 size, void *read, _Out_ uint32 *available, void *remaining)");
329
+ const lastError = kernel.func("uint32 __stdcall GetLastError()");
330
+ const openFd = node.func("int uv_open_osfhandle(void *handle)");
331
+ function pipe() {
332
+ const reads = [null], writes = [null];
333
+ if (!createPipe(reads, writes, null, 0)) throw new Error(`CreatePipe failed: ${lastError()}`);
334
+ const read = openFd(reads[0]);
335
+ if (read < 0) {
336
+ closeHandle(reads[0]);
337
+ closeHandle(writes[0]);
338
+ throw new Error("Cannot open anonymous input descriptor");
339
+ }
340
+ const write = openFd(writes[0]);
341
+ if (write < 0) {
342
+ closeSync(read);
343
+ closeHandle(writes[0]);
344
+ throw new Error("Cannot open anonymous output descriptor");
345
+ }
346
+ let timer;
347
+ let ended = false;
348
+ const readable = new Readable({
349
+ read() {
350
+ if (timer === void 0 && !ended) poll();
351
+ },
352
+ destroy(error, callback) {
353
+ ended = true;
354
+ clearTimeout(timer);
355
+ try {
356
+ closeSync(read);
357
+ callback(error);
358
+ } catch (cause) {
359
+ callback(error ?? cause);
360
+ }
361
+ }
362
+ });
363
+ function poll() {
364
+ timer = void 0;
365
+ try {
366
+ const available = [0];
367
+ if (!peek(reads[0], null, 0, null, available, null)) {
368
+ const code = lastError();
369
+ if (code !== 109) throw new Error(`PeekNamedPipe failed: ${code}`);
370
+ ended = true;
371
+ readable.push(null);
372
+ return;
373
+ }
374
+ if (available[0] > 0) {
375
+ const buffer = Buffer.allocUnsafe(Math.min(available[0], 65536));
376
+ const count = readSync(read, buffer, 0, buffer.length, null);
377
+ if (!readable.push(buffer.subarray(0, count))) return;
378
+ }
379
+ timer = setTimeout(poll, 5);
380
+ } catch (error) {
381
+ readable.destroy(error);
382
+ }
383
+ }
384
+ return {
385
+ read,
386
+ write,
387
+ readable
388
+ };
389
+ }
390
+ return { pipe };
391
+ }
392
+ /**
393
+ * Spawn with inherited token and Job restrictions; pipe creation never requests a new sandbox policy.
394
+ * @param executable - Verified native helper executable.
395
+ * @param args - Helper protocol arguments.
396
+ * @param env - Filtered operation environment.
397
+ * @returns Helper streams and process lifetime, with output drained before close.
398
+ */
399
+ function spawnNative(executable, args, env) {
400
+ if (process.platform !== "win32") return spawn(executable, args, {
401
+ stdio: "pipe",
402
+ windowsHide: true,
403
+ env
404
+ });
405
+ const { pipe } = windowsPipes();
406
+ const owned = [];
407
+ let child;
408
+ try {
409
+ const input = pipe();
410
+ owned.push(input);
411
+ const output = pipe();
412
+ owned.push(output);
413
+ const error = pipe();
414
+ owned.push(error);
415
+ child = spawn(executable, args, {
416
+ stdio: [
417
+ input.read,
418
+ output.write,
419
+ error.write
420
+ ],
421
+ windowsHide: true,
422
+ env
423
+ });
424
+ } catch (error) {
425
+ for (const entry of owned) {
426
+ entry.readable.destroy();
427
+ closeSync(entry.write);
428
+ }
429
+ throw error;
430
+ }
431
+ const [input, output, error] = owned;
432
+ input.readable.destroy();
433
+ closeSync(output.write);
434
+ closeSync(error.write);
435
+ const stdin = createWriteStream("", {
436
+ fd: input.write,
437
+ autoClose: true
438
+ });
439
+ const helper = new class extends EventEmitter {
440
+ stdin = stdin;
441
+ stdout = output.readable;
442
+ stderr = error.readable;
443
+ get exitCode() {
444
+ return child.exitCode;
445
+ }
446
+ get signalCode() {
447
+ return child.signalCode;
448
+ }
449
+ kill(signal) {
450
+ return child.kill(signal);
451
+ }
452
+ }();
453
+ let failure;
454
+ const fail = (cause) => {
455
+ failure ??= cause;
456
+ child.kill("SIGKILL");
457
+ };
458
+ stdin.on("error", fail);
459
+ output.readable.on("error", fail);
460
+ error.readable.on("error", fail);
461
+ const drained = Promise.allSettled([
462
+ finished(stdin),
463
+ finished(output.readable),
464
+ finished(error.readable)
465
+ ]);
466
+ child.once("error", (cause) => {
467
+ failure ??= cause;
468
+ });
469
+ child.once("close", (code, signal) => {
470
+ stdin.destroy();
471
+ drained.then(() => {
472
+ if (failure !== void 0) helper.emit("error", failure);
473
+ helper.emit("close", code, signal);
474
+ });
475
+ });
476
+ return helper;
477
+ }
478
+ //#endregion
318
479
  //#region lib/types/profile.js
319
480
  /** Private headless profile used by both native and WASM conversions. */
320
481
  /**
@@ -559,6 +720,30 @@ function nativeEnvironment(profile, programDirectory, source = process.env, plat
559
720
  });
560
721
  }
561
722
  /**
723
+ * Keep Windows engine resources reachable through a short profile-owned path until the helper exits.
724
+ * @param engine - Verified engine installation; its resources remain in place.
725
+ * @param profile - Private operation directory that owns the temporary executable and junction.
726
+ * @param run - Operation that settles only after its helper closes.
727
+ * @returns The operation result after removing the resource junction.
728
+ */
729
+ async function withNativeEngine(engine, profile, run) {
730
+ if (process.platform !== "win32" || engine.executable.length < 260 && engine.programDirectory.length < 260) return run(engine);
731
+ const root = join(profile, "engine");
732
+ await symlink(engine.root, root, "junction");
733
+ try {
734
+ const executable = join(profile, "libreoffice-kit.exe");
735
+ await copyFile(engine.executable, executable, constants.COPYFILE_EXCL);
736
+ return await run({
737
+ ...engine,
738
+ root,
739
+ executable,
740
+ programDirectory: join(root, relative(engine.root, engine.programDirectory))
741
+ });
742
+ } finally {
743
+ await unlink(root);
744
+ }
745
+ }
746
+ /**
562
747
  * Run one native conversion and await bounded result transport.
563
748
  * @param engine - Resolved native engine installation.
564
749
  * @param options - Validated conversion limits.
@@ -578,77 +763,73 @@ async function runNative(engine, options, input, output, profile, fonts, substit
578
763
  signal.throwIfAborted();
579
764
  await prepareNativeFontProfile(profile, substitutions);
580
765
  signal.throwIfAborted();
581
- const env = nativeEnvironment(profile, engine.programDirectory);
582
- const child = spawn(engine.executable, [
583
- "--program-directory",
584
- engine.programDirectory,
585
- "--input-path",
586
- input,
587
- "--output-path",
588
- output,
589
- "--profile-directory",
590
- profile,
591
- "--max-output-bytes",
592
- String(options.maxOutputBytes),
593
- "--max-image-resolution",
594
- String(options.maxImageResolution),
595
- "--format",
596
- operation.format,
597
- "--recalculate",
598
- String(operation.recalculate),
599
- ...operation.sheet === void 0 ? [] : ["--sheet", operation.sheet],
600
- ...fonts.flatMap((path) => ["--font-file", path])
601
- ], {
602
- stdio: [
603
- "ignore",
604
- "pipe",
605
- "pipe"
606
- ],
607
- windowsHide: true,
608
- env
609
- });
610
- let stdout = "";
611
- let stderr = "";
612
- let failure;
613
- const abort = () => {
614
- failure ??= signal.reason;
615
- child.kill("SIGKILL");
616
- };
617
- signal.addEventListener("abort", abort, { once: true });
618
- child.stdout.setEncoding("utf8");
619
- child.stderr.setEncoding("utf8");
620
- child.stdout.on("data", (chunk) => {
621
- stdout += chunk;
622
- if (stdout.length > 65536) {
623
- failure ??= /* @__PURE__ */ new Error("LibreOffice helper exceeded its response limit.");
766
+ return withNativeEngine(engine, profile, async (engine) => {
767
+ signal.throwIfAborted();
768
+ const env = nativeEnvironment(profile, engine.programDirectory);
769
+ const child = spawnNative(engine.executable, [
770
+ "--program-directory",
771
+ engine.programDirectory,
772
+ "--input-path",
773
+ input,
774
+ "--output-path",
775
+ output,
776
+ "--profile-directory",
777
+ profile,
778
+ "--max-output-bytes",
779
+ String(options.maxOutputBytes),
780
+ "--max-image-resolution",
781
+ String(options.maxImageResolution),
782
+ "--format",
783
+ operation.format,
784
+ "--recalculate",
785
+ String(operation.recalculate),
786
+ ...operation.sheet === void 0 ? [] : ["--sheet", operation.sheet],
787
+ ...fonts.flatMap((path) => ["--font-file", path])
788
+ ], env);
789
+ child.stdin.end();
790
+ let stdout = "";
791
+ let stderr = "";
792
+ let failure;
793
+ const abort = () => {
794
+ failure ??= signal.reason;
624
795
  child.kill("SIGKILL");
625
- }
626
- });
627
- child.stderr.on("data", (chunk) => {
628
- stderr = (stderr + chunk).slice(-65536);
629
- });
630
- try {
631
- const code = await new Promise((resolve, reject) => {
632
- child.once("error", (error) => {
633
- failure ??= error;
634
- });
635
- child.once("close", (code, signal) => {
636
- if (signal === "SIGXFSZ") failure ??= new ConversionError("output-too-large", "LibreOffice exceeded its output file-size limit.");
637
- if (failure) reject(failure);
638
- else resolve(code);
639
- });
796
+ };
797
+ signal.addEventListener("abort", abort, { once: true });
798
+ child.stdout.setEncoding("utf8");
799
+ child.stderr.setEncoding("utf8");
800
+ child.stdout.on("data", (chunk) => {
801
+ stdout += chunk;
802
+ if (stdout.length > 65536) {
803
+ failure ??= /* @__PURE__ */ new Error("LibreOffice helper exceeded its response limit.");
804
+ child.kill("SIGKILL");
805
+ }
806
+ });
807
+ child.stderr.on("data", (chunk) => {
808
+ stderr = (stderr + chunk).slice(-65536);
640
809
  });
641
- signal.throwIfAborted();
642
- let result;
643
810
  try {
644
- result = JSON.parse(stdout);
645
- } catch (cause) {
646
- throw new Error(`LibreOffice helper returned an invalid response (exit ${code}). ${stderr}`, { cause });
811
+ const code = await new Promise((resolve, reject) => {
812
+ child.once("error", (error) => {
813
+ failure ??= error;
814
+ });
815
+ child.once("close", (code, signal) => {
816
+ if (signal === "SIGXFSZ") failure ??= new ConversionError("output-too-large", "LibreOffice exceeded its output file-size limit.");
817
+ if (failure) reject(failure);
818
+ else resolve(code);
819
+ });
820
+ });
821
+ signal.throwIfAborted();
822
+ let result;
823
+ try {
824
+ result = JSON.parse(stdout);
825
+ } catch (cause) {
826
+ throw new Error(`LibreOffice helper returned an invalid response (exit ${code}). ${stderr}`, { cause });
827
+ }
828
+ if (code !== 0 || result.ok !== true) throw new ConversionError(failureCode(result), `LibreOffice native conversion failed: ${result.error ?? stderr}`);
829
+ } finally {
830
+ signal.removeEventListener("abort", abort);
647
831
  }
648
- if (code !== 0 || result.ok !== true) throw new ConversionError(failureCode(result), `LibreOffice native conversion failed: ${result.error ?? stderr}`);
649
- } finally {
650
- signal.removeEventListener("abort", abort);
651
- }
832
+ });
652
833
  }
653
834
  //#endregion
654
835
  //#region lib/types/png.js
@@ -785,179 +966,210 @@ async function renderImagesWithNative(request) {
785
966
  signal.throwIfAborted();
786
967
  await mkdir(profile, { mode: 448 });
787
968
  await prepareNativeFontProfile(profile, substitutions);
788
- const child = spawn(engine.executable, [
789
- "--operation",
790
- "render-images",
791
- "--program-directory",
792
- engine.programDirectory,
793
- "--input-path",
794
- inputPath,
795
- "--scratch-directory",
796
- scratch,
797
- "--profile-directory",
798
- profile,
799
- "--max-output-bytes",
800
- String(options.maxOutputBytes),
801
- "--max-image-resolution",
802
- String(options.maxImageResolution),
803
- ...fonts.flatMap((path) => ["--font-file", path])
804
- ], {
805
- stdio: [
806
- "pipe",
807
- "pipe",
808
- "pipe"
809
- ],
810
- windowsHide: true,
811
- env: nativeEnvironment(profile, engine.programDirectory)
812
- });
813
- const lines = [];
814
- const waiters = [];
815
- const output = createInterface({ input: child.stdout });
816
- output.on("line", (line) => {
817
- const waiter = waiters.shift();
818
- if (waiter) waiter(line);
819
- else lines.push(line);
820
- });
821
- let stderr = "";
822
- let stopped;
823
- child.stderr.setEncoding("utf8");
824
- child.stderr.on("data", (chunk) => {
825
- stderr = (stderr + chunk).slice(-65536);
826
- });
827
- const closed = new Promise((resolve, reject) => {
828
- child.once("error", reject);
829
- child.once("close", resolve);
830
- });
831
- const abort = () => {
832
- stopped ??= signal.reason;
833
- child.kill("SIGKILL");
834
- };
835
- signal.addEventListener("abort", abort, { once: true });
836
- const next = async () => {
969
+ return withNativeEngine(engine, profile, async (engine) => {
837
970
  signal.throwIfAborted();
838
- if (lines.length > 0) return lines.shift();
839
- return new Promise((resolve, reject) => {
840
- const done = (line) => {
841
- signal.removeEventListener("abort", cancel);
842
- resolve(line);
843
- };
844
- const cancel = () => {
845
- const index = waiters.indexOf(done);
846
- if (index >= 0) waiters.splice(index, 1);
847
- reject(signal.reason);
848
- };
849
- signal.addEventListener("abort", cancel, { once: true });
850
- waiters.push(done);
971
+ const child = spawnNative(engine.executable, [
972
+ "--operation",
973
+ "render-images",
974
+ "--program-directory",
975
+ engine.programDirectory,
976
+ "--input-path",
977
+ inputPath,
978
+ "--scratch-directory",
979
+ scratch,
980
+ "--profile-directory",
981
+ profile,
982
+ "--max-output-bytes",
983
+ String(options.maxOutputBytes),
984
+ "--max-image-resolution",
985
+ String(options.maxImageResolution),
986
+ ...fonts.flatMap((path) => ["--font-file", path])
987
+ ], nativeEnvironment(profile, engine.programDirectory));
988
+ const lines = [];
989
+ const waiters = [];
990
+ const output = createInterface({ input: child.stdout });
991
+ output.on("line", (line) => {
992
+ const waiter = waiters.shift();
993
+ if (waiter) waiter(line);
994
+ else lines.push(line);
851
995
  });
852
- };
853
- const response = async () => {
854
- const line = await next();
855
- let value;
856
- try {
857
- value = JSON.parse(line);
858
- } catch (cause) {
859
- throw new Error(`LibreOffice native renderer returned invalid JSON. ${stderr}`, { cause });
860
- }
861
- if (!value.ok) throw failure(value, stderr);
862
- return value;
863
- };
864
- try {
865
- const ready = await response();
866
- if (ready.kind !== "ready") throw new Error("LibreOffice native renderer did not initialize.");
867
- const planned = plan(ready, operation);
868
- const scale = operation.dpi / 96;
869
- const selected = [];
870
- for (const region of planned.regions) if (region.sheet === void 0) selected.push(region);
871
- else {
872
- let rectangles;
996
+ let stderr = "";
997
+ let stopped;
998
+ child.stderr.setEncoding("utf8");
999
+ child.stderr.on("data", (chunk) => {
1000
+ stderr = (stderr + chunk).slice(-65536);
1001
+ });
1002
+ const closed = new Promise((resolve, reject) => {
1003
+ let failure;
1004
+ child.once("error", (error) => {
1005
+ failure = error;
1006
+ });
1007
+ child.once("close", (code) => {
1008
+ if (failure) reject(failure);
1009
+ else resolve(code);
1010
+ });
1011
+ });
1012
+ const abort = () => {
1013
+ stopped ??= signal.reason;
1014
+ child.kill("SIGKILL");
1015
+ };
1016
+ signal.addEventListener("abort", abort, { once: true });
1017
+ const next = async () => {
1018
+ signal.throwIfAborted();
1019
+ if (lines.length > 0) return lines.shift();
1020
+ return new Promise((resolve, reject) => {
1021
+ const done = (line) => {
1022
+ signal.removeEventListener("abort", cancel);
1023
+ resolve(line);
1024
+ };
1025
+ const fail = (error) => {
1026
+ const index = waiters.indexOf(done);
1027
+ if (index >= 0) waiters.splice(index, 1);
1028
+ signal.removeEventListener("abort", cancel);
1029
+ reject(error);
1030
+ };
1031
+ const cancel = () => {
1032
+ fail(signal.reason);
1033
+ };
1034
+ signal.addEventListener("abort", cancel, { once: true });
1035
+ waiters.push(done);
1036
+ closed.then((code) => {
1037
+ fail(/* @__PURE__ */ new Error(`LibreOffice native renderer exited ${code ?? child.signalCode} before responding. ${stderr}`));
1038
+ }, fail);
1039
+ });
1040
+ };
1041
+ const response = async () => {
1042
+ const line = await next();
1043
+ let value;
873
1044
  try {
874
- rectangles = splitRasterRectangle(region.rectangle, scale, {
875
- maxPixels: operation.maxPixels,
876
- maxDimension: operation.maxDimension,
877
- maxTiles: operation.maxPages - selected.length
878
- });
1045
+ value = JSON.parse(line);
879
1046
  } catch (cause) {
880
- throw new ConversionError("output-too-large", String(cause), { cause });
1047
+ throw new Error(`LibreOffice native renderer returned invalid JSON. ${stderr}`, { cause });
881
1048
  }
882
- selected.push(...rectangles.map((rectangle) => ({
883
- ...region,
884
- rectangle
885
- })));
886
- }
887
- for (const { page, rectangle } of selected) {
888
- const { width, height } = tileDimensions({
889
- pageIndex: 0,
890
- ...rectangle,
891
- scale
892
- }, [page]);
893
- if (width > operation.maxDimension || height > operation.maxDimension || width * height > operation.maxPixels) throw new ConversionError("output-too-large", "Selected page exceeds maxPixels or maxDimension; reduce DPI or raise the image limits.");
894
- }
895
- const images = [];
896
- let total = 0;
897
- for (const region of selected) {
898
- signal.throwIfAborted();
899
- const { width, height } = tileDimensions({
900
- pageIndex: 0,
901
- ...region.rectangle,
902
- scale
903
- }, [region.page]);
904
- const x = region.page.x + Math.round(region.rectangle.x * 15);
905
- const y = region.page.y + Math.round(region.rectangle.y * 15);
906
- const twipsWidth = Math.max(1, Math.round(region.rectangle.width * 15));
907
- const twipsHeight = Math.max(1, Math.round(region.rectangle.height * 15));
908
- const index = images.length + 1;
909
- child.stdin.write(`P ${index} ${region.page.part} ${width} ${height} ${x} ${y} ${twipsWidth} ${twipsHeight}\n`);
910
- const painted = await response();
911
- if (painted.kind !== "paint" || painted.index !== index || painted.width !== width || painted.height !== height) throw new Error("LibreOffice native renderer returned inconsistent tile metadata.");
912
- if (resolve(painted.path) !== resolve(scratch, `tile-${index}.rgba`)) throw new Error("LibreOffice native renderer returned a tile outside its scratch directory.");
913
- const raw = await readFile(painted.path);
914
- if (raw.byteLength !== width * height * 4) throw new Error("LibreOffice native renderer returned incomplete pixels.");
915
- const png = encodePng(width, height, ready.documentType === "pdf" ? new Uint8ClampedArray(raw) : rgbaPixels(raw, ready.tileMode));
916
- total += png.byteLength;
917
- if (total > options.maxOutputBytes) throw new ConversionError("output-too-large", "PNG batch exceeds maxOutputBytes.");
918
- const path = join(operation.outputDir, `page-${String(index).padStart(4, "0")}.png`);
919
- await writeFile(path, png, {
920
- flag: "wx",
921
- mode: 384
922
- });
923
- images.push({
924
- index,
925
- ...region.number === void 0 ? {} : { page: region.number },
926
- ...region.sheet === void 0 ? {} : {
927
- sheet: region.sheet,
928
- range: region.range,
929
- rtl: region.rtl
930
- },
931
- path,
932
- width,
933
- height,
934
- rectangle: region.rectangle,
935
- byteLength: png.byteLength
936
- });
937
- }
938
- child.stdin.end("DONE\n");
939
- if ((await response()).kind !== "done") throw new Error("LibreOffice native renderer did not finish.");
940
- const code = await closed;
941
- if (code !== 0) throw new Error(`LibreOffice native renderer exited ${code}. ${stderr}`);
942
- return {
943
- schemaVersion: 1,
944
- backend: "native",
945
- rasterEngine: ready.documentType === "pdf" ? "pdfium" : "libreoffice",
946
- source: "saved",
947
- inputPath: operation.inputPath,
948
- sourceSha256: createHash("sha256").update(source).digest("hex"),
949
- dpi: operation.dpi,
950
- pageCount: planned.count,
951
- images,
952
- missingFonts: [...missingFonts]
1049
+ if (!value.ok) throw failure(value, stderr);
1050
+ return value;
953
1051
  };
954
- } finally {
955
- signal.removeEventListener("abort", abort);
956
- output.close();
957
- if (child.exitCode === null) child.kill("SIGKILL");
958
- await closed.catch(() => {});
959
- if (stopped !== void 0) throw stopped;
960
- }
1052
+ try {
1053
+ const ready = await response();
1054
+ if (ready.kind !== "ready") throw new Error("LibreOffice native renderer did not initialize.");
1055
+ const planned = plan(ready, operation);
1056
+ const scale = operation.dpi / 96;
1057
+ const selected = [];
1058
+ for (const region of planned.regions) if (region.sheet === void 0) selected.push(region);
1059
+ else {
1060
+ let rectangles;
1061
+ try {
1062
+ rectangles = splitRasterRectangle(region.rectangle, scale, {
1063
+ maxPixels: operation.maxPixels,
1064
+ maxDimension: operation.maxDimension,
1065
+ maxTiles: operation.maxPages - selected.length
1066
+ });
1067
+ } catch (cause) {
1068
+ throw new ConversionError("output-too-large", String(cause), { cause });
1069
+ }
1070
+ selected.push(...rectangles.map((rectangle) => ({
1071
+ ...region,
1072
+ rectangle
1073
+ })));
1074
+ }
1075
+ for (const { page, rectangle } of selected) {
1076
+ const { width, height } = tileDimensions({
1077
+ pageIndex: 0,
1078
+ ...rectangle,
1079
+ scale
1080
+ }, [page]);
1081
+ if (width > operation.maxDimension || height > operation.maxDimension || width * height > operation.maxPixels) throw new ConversionError("output-too-large", "Selected page exceeds maxPixels or maxDimension; reduce DPI or raise the image limits.");
1082
+ }
1083
+ const images = [];
1084
+ let total = 0;
1085
+ for (const region of selected) {
1086
+ signal.throwIfAborted();
1087
+ const { width, height } = tileDimensions({
1088
+ pageIndex: 0,
1089
+ ...region.rectangle,
1090
+ scale
1091
+ }, [region.page]);
1092
+ const x = region.page.x + Math.round(region.rectangle.x * 15);
1093
+ const y = region.page.y + Math.round(region.rectangle.y * 15);
1094
+ const twipsWidth = Math.max(1, Math.round(region.rectangle.width * 15));
1095
+ const twipsHeight = Math.max(1, Math.round(region.rectangle.height * 15));
1096
+ const index = images.length + 1;
1097
+ child.stdin.write(`P ${index} ${region.page.part} ${width} ${height} ${x} ${y} ${twipsWidth} ${twipsHeight}\n`);
1098
+ const painted = await response();
1099
+ if (painted.kind !== "paint" || painted.index !== index || painted.width !== width || painted.height !== height) throw new Error("LibreOffice native renderer returned inconsistent tile metadata.");
1100
+ if (resolve(painted.path) !== resolve(scratch, `tile-${index}.rgba`)) throw new Error("LibreOffice native renderer returned a tile outside its scratch directory.");
1101
+ const raw = await readFile(painted.path);
1102
+ if (raw.byteLength !== width * height * 4) throw new Error("LibreOffice native renderer returned incomplete pixels.");
1103
+ const png = encodePng(width, height, ready.documentType === "pdf" ? new Uint8ClampedArray(raw) : rgbaPixels(raw, ready.tileMode));
1104
+ total += png.byteLength;
1105
+ if (total > options.maxOutputBytes) throw new ConversionError("output-too-large", "PNG batch exceeds maxOutputBytes.");
1106
+ const path = join(operation.outputDir, `page-${String(index).padStart(4, "0")}.png`);
1107
+ await writeFile(path, png, {
1108
+ flag: "wx",
1109
+ mode: 384
1110
+ });
1111
+ images.push({
1112
+ index,
1113
+ ...region.number === void 0 ? {} : { page: region.number },
1114
+ ...region.sheet === void 0 ? {} : {
1115
+ sheet: region.sheet,
1116
+ range: region.range,
1117
+ rtl: region.rtl
1118
+ },
1119
+ path,
1120
+ width,
1121
+ height,
1122
+ rectangle: region.rectangle,
1123
+ byteLength: png.byteLength
1124
+ });
1125
+ }
1126
+ child.stdin.end("DONE\n");
1127
+ if ((await response()).kind !== "done") throw new Error("LibreOffice native renderer did not finish.");
1128
+ const code = await closed;
1129
+ if (code !== 0) throw new Error(`LibreOffice native renderer exited ${code}. ${stderr}`);
1130
+ return {
1131
+ schemaVersion: 1,
1132
+ backend: "native",
1133
+ rasterEngine: ready.documentType === "pdf" ? "pdfium" : "libreoffice",
1134
+ source: "saved",
1135
+ inputPath: operation.inputPath,
1136
+ sourceSha256: createHash("sha256").update(source).digest("hex"),
1137
+ dpi: operation.dpi,
1138
+ pageCount: planned.count,
1139
+ images,
1140
+ missingFonts: [...missingFonts]
1141
+ };
1142
+ } finally {
1143
+ signal.removeEventListener("abort", abort);
1144
+ output.close();
1145
+ if (child.exitCode === null) child.kill("SIGKILL");
1146
+ await closed.catch(() => {});
1147
+ if (stopped !== void 0) throw stopped;
1148
+ }
1149
+ });
1150
+ }
1151
+ //#endregion
1152
+ //#region lib/types/font-file-identity.js
1153
+ /** Preserve 64-bit device and inode values without JavaScript integer rounding. */
1154
+ function fontFileIdentity(status) {
1155
+ return {
1156
+ dev: status.dev.toString(),
1157
+ ino: status.ino.toString(),
1158
+ size: Number(status.size),
1159
+ mtimeMs: Number(status.mtimeNs) / 1e6,
1160
+ ctimeMs: Number(status.ctimeNs) / 1e6
1161
+ };
1162
+ }
1163
+ /** Compare a source descriptor's exact identity with its indexed font metadata. */
1164
+ function matchesFontFile(status, expected) {
1165
+ const current = fontFileIdentity(status);
1166
+ return [
1167
+ "dev",
1168
+ "ino",
1169
+ "size",
1170
+ "mtimeMs",
1171
+ "ctimeMs"
1172
+ ].every((key) => current[key] === expected[key]);
961
1173
  }
962
1174
  //#endregion
963
1175
  //#region lib/types/fonts.js
@@ -1210,16 +1422,16 @@ function resolveOptions(input = {}) {
1210
1422
  /** Resolve installed, version-matched engine packages without downloads or compilation. */
1211
1423
  const require = createRequire(import.meta.url);
1212
1424
  /** Node API release version returned by runtime discovery. */
1213
- const ENGINE_VERSION = "0.1.2";
1425
+ const ENGINE_VERSION = "0.1.4";
1214
1426
  /** Exact compatible engine versions; unchanged platforms retain their published packages. */
1215
1427
  const ENGINE_VERSIONS = Object.freeze({
1216
- "darwin-arm64": "0.1.1",
1217
- "darwin-x64": "0.1.1",
1428
+ "darwin-arm64": "0.1.4",
1429
+ "darwin-x64": "0.1.4",
1218
1430
  "linux-arm64-glibc": "0.1.1",
1219
1431
  "linux-x64-glibc": "0.1.1",
1220
- "win32-arm64": "0.1.2",
1221
- "win32-x64": "0.1.2",
1222
- wasm: "0.1.1"
1432
+ "win32-arm64": "0.1.4",
1433
+ "win32-x64": "0.1.4",
1434
+ wasm: "0.1.4"
1223
1435
  });
1224
1436
  /** npm scope and name prefix shared by the engine packages this adapter installs. */
1225
1437
  const ENGINE_PREFIX = "@deepseek-ai/libreoffice-kit";
@@ -1526,14 +1738,8 @@ var FontSnapshotState = class {
1526
1738
  async function validateFontSnapshot(snapshot) {
1527
1739
  await Promise.all(snapshot.records.map(async (record) => {
1528
1740
  try {
1529
- const current = await lstat(record.path);
1530
- if (current.isFile() && [
1531
- "dev",
1532
- "ino",
1533
- "size",
1534
- "mtimeMs",
1535
- "ctimeMs"
1536
- ].every((key) => current[key] === record[key])) return;
1741
+ const current = await lstat(record.path, { bigint: true });
1742
+ if (current.isFile() && matchesFontFile(current, record)) return;
1537
1743
  } catch {}
1538
1744
  throw new ConversionError("failed", "A system font changed during conversion; retry the operation.");
1539
1745
  }));