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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +43 -47
  3. package/README.zh.md +35 -50
  4. package/assets/font-subset.json +70 -0
  5. package/assets/font-subset.wasm +0 -0
  6. package/lib/browser/assets.json +10 -0
  7. package/lib/browser/index.js +435 -0
  8. package/lib/browser/types/connection.d.ts +20 -0
  9. package/lib/browser/types/editor-engine.d.ts +50 -0
  10. package/lib/browser/types/editor-types.d.ts +141 -0
  11. package/lib/browser/types/editor.d.ts +9 -0
  12. package/lib/browser/types/engine-rendering.d.ts +3 -0
  13. package/lib/browser/types/engine-types.d.ts +17 -0
  14. package/lib/browser/types/font-channel.d.ts +20 -0
  15. package/lib/browser/types/index.d.ts +13 -0
  16. package/lib/browser/types/protocol.d.ts +117 -0
  17. package/lib/browser/types/rendering.d.ts +4 -0
  18. package/lib/browser/types/types.d.ts +90 -0
  19. package/lib/browser/types/worker.d.ts +2 -0
  20. package/lib/browser/worker.js +3711 -0
  21. package/lib/browser-assets.js +119 -0
  22. package/lib/cli.js +1303 -0
  23. package/lib/document.js +178 -0
  24. package/lib/engine-rendering.js +120 -0
  25. package/lib/font-config.js +46 -0
  26. package/lib/font-source.js +344 -0
  27. package/lib/font-worker.js +712 -0
  28. package/lib/index.js +319 -109
  29. package/lib/rendering.js +99 -0
  30. package/lib/sheet-geometry.js +111 -0
  31. package/lib/types/browser-assets.d.ts +15 -0
  32. package/lib/types/cli.d.ts +3 -0
  33. package/lib/types/document.d.ts +1 -1
  34. package/lib/types/engine-rendering.d.ts +15 -0
  35. package/lib/types/engine.d.ts +5 -5
  36. package/lib/types/font-config.d.ts +24 -0
  37. package/lib/types/font-full.d.ts +13 -0
  38. package/lib/types/font-loader.d.ts +1 -7
  39. package/lib/types/font-request.d.ts +12 -0
  40. package/lib/types/font-source-types.d.ts +82 -0
  41. package/lib/types/font-source.d.ts +10 -0
  42. package/lib/types/font-subsets.d.ts +35 -0
  43. package/lib/types/font-worker.d.ts +2 -0
  44. package/lib/types/fonts.d.ts +9 -29
  45. package/lib/types/harfbuzz-subset.d.ts +11 -0
  46. package/lib/types/image-operations.d.ts +58 -0
  47. package/lib/types/image-renderer.d.ts +6 -0
  48. package/lib/types/index.d.ts +25 -2
  49. package/lib/types/native.d.ts +4 -2
  50. package/lib/types/operations.d.ts +41 -0
  51. package/lib/types/png.d.ts +2 -0
  52. package/lib/types/profile.d.ts +8 -0
  53. package/lib/types/rendering.d.ts +41 -0
  54. package/lib/types/runtime.d.ts +14 -0
  55. package/lib/types/sheet-geometry.d.ts +38 -0
  56. package/lib/types/unicode-scripts.d.ts +18 -0
  57. package/lib/types/wasm.d.ts +76 -1
  58. package/lib/types/worker.d.ts +3 -0
  59. package/lib/worker.js +1012 -237
  60. package/licenses/font-subset/harfbuzz-COPYING +42 -0
  61. package/licenses/font-subset/harfbuzzjs-LICENSE +19 -0
  62. package/licenses/javascript/fflate-LICENSE +21 -0
  63. package/licenses/javascript/saxes-LICENSE +64 -0
  64. package/licenses/javascript/xmlchars-LICENSE +18 -0
  65. package/package.json +59 -12
  66. package/sources/browser/packages/browser/package.json +22 -0
  67. package/sources/browser/packages/browser/src/connection.ts +168 -0
  68. package/sources/browser/packages/browser/src/editor-engine.ts +382 -0
  69. package/sources/browser/packages/browser/src/editor-types.ts +106 -0
  70. package/sources/browser/packages/browser/src/editor.ts +55 -0
  71. package/sources/browser/packages/browser/src/engine-rendering.ts +2 -0
  72. package/sources/browser/packages/browser/src/engine-types.ts +14 -0
  73. package/sources/browser/packages/browser/src/font-channel.ts +99 -0
  74. package/sources/browser/packages/browser/src/index.ts +39 -0
  75. package/sources/browser/packages/browser/src/protocol.ts +40 -0
  76. package/sources/browser/packages/browser/src/rendering.ts +3 -0
  77. package/sources/browser/packages/browser/src/types.ts +92 -0
  78. package/sources/browser/packages/browser/src/worker.ts +171 -0
  79. package/sources/browser/packages/browser/tsconfig.json +5 -0
  80. package/sources/browser/packages/browser/tsdown.config.ts +7 -0
  81. package/sources/browser/scripts/build-browser.mjs +74 -0
  82. package/sources/font-subset/engine/font-subset/README.md +23 -0
  83. package/sources/font-subset/engine/font-subset/README.zh.md +23 -0
  84. package/sources/font-subset/engine/font-subset/source.json +16 -0
  85. package/sources/font-subset/harfbuzzjs/config-override-subset.h +7 -0
  86. package/sources/font-subset/harfbuzzjs/harfbuzz-subset.symbols +34 -0
  87. package/sources/font-subset/scripts/build-font-subset.mjs +64 -0
  88. package/sources/font-subset/scripts/pack-utils.mjs +69 -0
  89. package/sources/font-subset/scripts/platform-matrix.mjs +100 -0
  90. package/sources/font-subset/scripts/verify-artifacts.mjs +260 -0
package/lib/index.js CHANGED
@@ -6,8 +6,7 @@ import { dirname, extname, isAbsolute, join, posix, relative, resolve, sep, win3
6
6
  import { Worker } from "node:worker_threads";
7
7
  import { spawn } from "node:child_process";
8
8
  import "fontkit";
9
- import "fflate";
10
- import "saxes";
9
+ import { fileURLToPath } from "node:url";
11
10
  //#region lib/types/errors.js
12
11
  /** Stable render failure categories shared across the Node worker and native helper transports. */
13
12
  const CODES = /* @__PURE__ */ new Set([
@@ -45,6 +44,102 @@ function failureCode(error) {
45
44
  return typeof code === "string" && CODES.has(code) ? code : "failed";
46
45
  }
47
46
  //#endregion
47
+ //#region lib/types/sheet-geometry.js
48
+ const MAX_COLUMN = 16383;
49
+ const MAX_ROW = 1048575;
50
+ function column(index) {
51
+ let name = "";
52
+ for (let value = index + 1; value > 0; value = Math.floor((value - 1) / 26)) name = String.fromCharCode(65 + (value - 1) % 26) + name;
53
+ return name;
54
+ }
55
+ function rangeName(range) {
56
+ return `${column(range.firstColumn)}${range.firstRow + 1}:${column(range.lastColumn)}${range.lastRow + 1}`;
57
+ }
58
+ function parseCellRange(value) {
59
+ const match = /^\$?([A-Z]{1,3})\$?([1-9]\d{0,6})(?::\$?([A-Z]{1,3})\$?([1-9]\d{0,6}))?$/i.exec(value);
60
+ if (!match) throw new TypeError("range must be an A1 cell or rectangle without a sheet prefix.");
61
+ const col = (name) => [...name.toUpperCase()].reduce((sum, c) => sum * 26 + c.charCodeAt(0) - 64, 0) - 1;
62
+ const firstColumn = col(match[1]);
63
+ const firstRow = Number(match[2]) - 1;
64
+ const lastColumn = col(match[3] ?? match[1]);
65
+ const lastRow = Number(match[4] ?? match[2]) - 1;
66
+ if (lastColumn < firstColumn || lastRow < firstRow || lastColumn > MAX_COLUMN || lastRow > MAX_ROW) throw new TypeError("range exceeds Calc worksheet bounds or has reversed endpoints.");
67
+ return {
68
+ firstColumn,
69
+ firstRow,
70
+ lastColumn,
71
+ lastRow
72
+ };
73
+ }
74
+ //#endregion
75
+ //#region lib/types/image-operations.js
76
+ /** Public direct-raster request and immutable saved-file manifest. */
77
+ const IMAGE_FORMATS = [
78
+ "doc",
79
+ "docx",
80
+ "odt",
81
+ "xls",
82
+ "xlsx",
83
+ "ods",
84
+ "ppt",
85
+ "pptx",
86
+ "odp",
87
+ "pdf"
88
+ ];
89
+ function resolveImageRender(request) {
90
+ if (!request || typeof request.inputPath !== "string" || typeof request.outputDir !== "string" || !isAbsolute(request.inputPath) || !isAbsolute(request.outputDir) || request.inputPath.includes("\0") || request.outputDir.includes("\0")) throw new TypeError("inputPath and outputDir must be absolute filesystem paths.");
91
+ const inputPath = resolve(request.inputPath), outputDir = resolve(request.outputDir);
92
+ const within = relative(outputDir, inputPath);
93
+ if (!within || !within.startsWith("..") && !isAbsolute(within)) throw new TypeError("Input cannot be inside the newly owned output directory.");
94
+ const extension = extname(inputPath).slice(1).toLowerCase();
95
+ if (!IMAGE_FORMATS.includes(extension)) throw new ConversionError("unsupported-format", `Unsupported image input: ${extension}.`);
96
+ const calc = [
97
+ "xls",
98
+ "xlsx",
99
+ "ods"
100
+ ].includes(extension);
101
+ if (calc && request.pages !== void 0) throw new TypeError("Worksheets use sheet and A1 range, not printed page numbers.");
102
+ if (!calc && (request.sheet !== void 0 || request.range !== void 0)) throw new TypeError("sheet and range apply only to worksheets.");
103
+ if (request.sheet !== void 0 && (typeof request.sheet !== "string" || !request.sheet.trim() || request.sheet.includes("\0"))) throw new TypeError("sheet must be a nonempty exact worksheet name.");
104
+ if (request.range !== void 0 && request.sheet === void 0) throw new TypeError("range requires an exact sheet name.");
105
+ const range = request.range === void 0 ? void 0 : rangeName(parseCellRange(request.range));
106
+ const pages = request.pages ?? "all";
107
+ if (pages !== "all" && (!Array.isArray(pages) || pages.length === 0 || pages.some((page) => !Number.isSafeInteger(page) || page < 1) || new Set(pages).size !== pages.length)) throw new TypeError("pages must be all or distinct positive one-based page numbers.");
108
+ const dpi = request.dpi ?? 144;
109
+ const maxPages = request.maxPages ?? 100;
110
+ const maxPixels = request.maxPixels ?? 16777216;
111
+ const maxDimension = request.maxDimension ?? 8192;
112
+ if (!Number.isFinite(dpi) || dpi < 24 || dpi > 600) throw new TypeError("dpi must be between 24 and 600.");
113
+ if (!Number.isSafeInteger(maxPages) || maxPages < 1 || maxPages > 1e4) throw new TypeError("maxPages must be an integer between 1 and 10000.");
114
+ if (!Number.isSafeInteger(maxPixels) || maxPixels < 1 || maxPixels > 16777216) throw new TypeError("maxPixels must be between 1 and 16777216.");
115
+ if (!Number.isSafeInteger(maxDimension) || maxDimension < 1 || maxDimension > 16777216) throw new TypeError("maxDimension must be between 1 and 16777216.");
116
+ if (pages !== "all" && pages.length > maxPages) throw new ConversionError("output-too-large", "Selected page count exceeds maxPages.");
117
+ return {
118
+ kind: "images",
119
+ inputPath,
120
+ outputDir,
121
+ extension,
122
+ dpi,
123
+ maxPages,
124
+ maxPixels,
125
+ maxDimension,
126
+ ...calc ? {} : { pages: pages === "all" ? "all" : [...pages] },
127
+ ...request.sheet === void 0 ? {} : { sheet: request.sheet },
128
+ ...range === void 0 ? {} : { range }
129
+ };
130
+ }
131
+ //#endregion
132
+ //#region lib/types/profile.js
133
+ /** Private headless profile used by both native and WASM conversions. */
134
+ /**
135
+ * CSV selection is checked by the engine wrapper before saving; suppress the interactive warning.
136
+ * @param fontNodes - Escaped VCL font-substitution nodes, or an empty string for WASM.
137
+ * @returns The per-operation registry XML; macro execution is independently disabled at load.
138
+ */
139
+ function profileXml(fontNodes = "") {
140
+ 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`;
141
+ }
142
+ //#endregion
48
143
  //#region lib/types/native-font-names.js
49
144
  /** Localized search names from LibreOffice Core's fixed font-name dictionary. */
50
145
  const LOCALIZED_FONT_SEARCH_NAMES = /* @__PURE__ */ new Map([
@@ -240,14 +335,13 @@ function fontSearchName(value) {
240
335
  * Installed originals and metric-compatible fonts are resolved before this table by LibreOffice.
241
336
  * @param profile - Existing, conversion-owned profile directory.
242
337
  * @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.
338
+ * @returns Resolves after the exclusive profile file is written; empty choices still disable the interactive CSV warning.
244
339
  */
245
340
  async function prepareNativeFontProfile(profile, substitutions) {
246
- if (substitutions.length === 0) return;
247
341
  const families = new Map(substitutions.map(({ family, substitute }) => [fontSearchName(family), substitute]));
248
342
  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
343
  const escape = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
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`;
344
+ const xml = profileXml([...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(""));
251
345
  const user = join(profile, "user");
252
346
  await mkdir(user, { mode: 448 });
253
347
  await writeFile(join(user, "registrymodifications.xcu"), xml, {
@@ -288,9 +382,10 @@ function nativeEnvironment(profile, programDirectory, source = process.env, plat
288
382
  * @param fonts - Installed font files the helper may load.
289
383
  * @param substitutions - Missing families and their selected installed substitutes.
290
384
  * @param signal - Cancellation; it kills the helper and awaits its exit.
385
+ * @param operation - Validated output format, recalculation, and worksheet selection.
291
386
  * @throws ConversionError for a reported conversion failure, and the abort reason for cancellation.
292
387
  */
293
- async function runNative(engine, options, input, output, profile, fonts, substitutions, signal) {
388
+ async function runNative(engine, options, input, output, profile, fonts, substitutions, signal, operation) {
294
389
  signal.throwIfAborted();
295
390
  await prepareNativeFontProfile(profile, substitutions);
296
391
  signal.throwIfAborted();
@@ -308,6 +403,11 @@ async function runNative(engine, options, input, output, profile, fonts, substit
308
403
  String(options.maxOutputBytes),
309
404
  "--max-image-resolution",
310
405
  String(options.maxImageResolution),
406
+ "--format",
407
+ operation.format,
408
+ "--recalculate",
409
+ String(operation.recalculate),
410
+ ...operation.sheet === void 0 ? [] : ["--sheet", operation.sheet],
311
411
  ...fonts.flatMap((path) => ["--font-file", path])
312
412
  ], {
313
413
  stdio: [
@@ -363,7 +463,6 @@ async function runNative(engine, options, input, output, profile, fonts, substit
363
463
  }
364
464
  //#endregion
365
465
  //#region lib/types/fonts.js
366
- /** Host font metadata snapshots and conversion-local glyph matching over original files. */
367
466
  /**
368
467
  * @param error - Thrown filesystem value.
369
468
  * @returns whether it means the path is not a usable font source.
@@ -599,7 +698,7 @@ const require = createRequire(import.meta.url);
599
698
  * Engine-family version every installed engine package must carry. The engine
600
699
  * family shares its release version with this Node API.
601
700
  */
602
- const ENGINE_VERSION = "0.0.1";
701
+ const ENGINE_VERSION = "0.0.2-rc4";
603
702
  /** npm scope and name prefix shared by the engine packages this adapter installs. */
604
703
  const ENGINE_PREFIX = "@deepseek-ai/libreoffice-kit";
605
704
  /**
@@ -610,110 +709,157 @@ const ENGINE_PREFIX = "@deepseek-ai/libreoffice-kit";
610
709
  function installedPackageExists(name) {
611
710
  return (require.resolve.paths(name) ?? []).some((directory) => lstatSync(join(directory, name), { throwIfNoEntry: false }) !== void 0);
612
711
  }
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
712
  function asset(root, value) {
631
713
  if (typeof value !== "string" || !value || isAbsolute(value)) throw new Error("Engine manifest contains an invalid asset path.");
632
714
  const path = resolve(root, value);
633
715
  if (relative(root, path).startsWith(`..${sep}`) || relative(root, path) === "..") throw new Error("Engine asset escapes its installed package.");
634
716
  return path;
635
717
  }
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
718
  /**
640
- * macOS and Windows require their native engine. Linux uses WASM when no compatible development native engine is installed.
719
+ * Resolve the shared WASM engine on every supported operating system.
641
720
  * @param resolvePackage - Package manifest resolver; injectable for selection tests.
642
- * @param packageExists - Installed-package probe; injectable for selection tests.
721
+ * @param _packageExists - Retained positional compatibility with earlier resolvers.
643
722
  * @param host - Process identification and diagnostic report.
644
- * @returns the installed native engine, or the installed WASM engine.
723
+ * @returns the installed WASM engine; native packages never change selection.
645
724
  */
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");
725
+ async function resolveEngine(resolvePackage = (name) => require.resolve(`${name}/package.json`), _packageExists = installedPackageExists, { platform = process.platform, arch = process.arch } = {}) {
726
+ if (![
727
+ "darwin",
728
+ "win32",
729
+ "linux"
730
+ ].includes(platform)) throw new Error(`Unsupported LibreOfficeKit host: ${platform}-${arch}`);
731
+ return readEngine(resolvePackage(`${ENGINE_PREFIX}-wasm`));
669
732
  }
670
- async function engineAsset(root, value, name, kind) {
733
+ async function engineAsset(root, value, name) {
671
734
  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.");
735
+ if (!(await stat(path)).isFile()) throw new Error(`Installed LibreOfficeKit ${name} is not a file.`);
675
736
  return path;
676
737
  }
677
- async function readEngine(packageFile, backend, target) {
738
+ async function readEngine(packageFile) {
678
739
  const root = dirname(packageFile);
679
740
  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
741
  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
- }
742
+ if (pkg.name !== `${ENGINE_PREFIX}-wasm` || pkg.version !== "0.0.2-rc4" || manifest.version !== pkg.version || manifest.schemaVersion !== 1 || manifest.status !== "built" || engine === void 0 || engine.kind !== "wasm" || manifest.platform !== "wasm") throw new Error("Installed LibreOfficeKit wasm package has an incompatible or incomplete manifest.");
743
+ if (engine.glibcMinimum !== void 0) throw new Error("Installed LibreOfficeKit engine has an invalid glibcMinimum.");
695
744
  return {
696
- backend,
745
+ backend: "wasm",
697
746
  root,
698
747
  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
748
+ loader: await engineAsset(root, engine.loader, "loader"),
749
+ wasm: await engineAsset(root, engine.wasm, "wasm"),
750
+ data: await engineAsset(root, engine.data, "data"),
751
+ metadata: await engineAsset(root, engine.metadata, "metadata")
704
752
  };
705
753
  }
706
754
  //#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"
755
+ //#region lib/types/operations.js
756
+ /** Validated document operations shared by the public API, workers, and CLI. */
757
+ /** Conversions supported by the bundled Writer, Calc, and Impress components. */
758
+ const CONVERSION_FORMATS = [
759
+ {
760
+ inputs: [
761
+ "doc",
762
+ "docx",
763
+ "odt"
764
+ ],
765
+ outputs: [
766
+ "pdf",
767
+ "docx",
768
+ "odt",
769
+ "txt"
770
+ ]
771
+ },
772
+ {
773
+ inputs: [
774
+ "xls",
775
+ "xlsx",
776
+ "ods"
777
+ ],
778
+ outputs: [
779
+ "pdf",
780
+ "xlsx",
781
+ "ods",
782
+ "csv"
783
+ ]
784
+ },
785
+ {
786
+ inputs: [
787
+ "ppt",
788
+ "pptx",
789
+ "odp"
790
+ ],
791
+ outputs: [
792
+ "pdf",
793
+ "pptx",
794
+ "odp"
795
+ ]
796
+ }
716
797
  ];
798
+ /**
799
+ * Validate paths and the format matrix before file access or queue admission.
800
+ * @param request - Public conversion parameters.
801
+ * @param operation - PDF compatibility entry, general conversion, or workbook recalculation.
802
+ * @returns The explicit engine operation.
803
+ */
804
+ function resolveConversion(request, operation) {
805
+ 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.");
806
+ if (resolve(request.inputPath) === resolve(request.outputPath)) throw new TypeError("Input and output paths must differ.");
807
+ const extension = extname(request.inputPath).slice(1).toLowerCase();
808
+ const format = operation === "render" ? "pdf" : extname(request.outputPath).slice(1).toLowerCase();
809
+ const family = CONVERSION_FORMATS.find((group) => group.inputs.includes(extension));
810
+ if (!family || !family.outputs.includes(format)) throw new ConversionError("unsupported-format", `Unsupported conversion: ${extension || "(no input extension)"} → ${format || "(no output extension)"}.`);
811
+ if (operation === "recalculate" && (![
812
+ "xls",
813
+ "xlsx",
814
+ "ods"
815
+ ].includes(extension) || !["xlsx", "ods"].includes(format))) throw new ConversionError("unsupported-format", "Recalculation requires XLS, XLSX, or ODS input and XLSX or ODS output.");
816
+ if (request.sheet !== void 0 && (format !== "csv" || typeof request.sheet !== "string" || !request.sheet.trim() || request.sheet.includes("\0"))) throw new TypeError("sheet must be a nonempty exact worksheet name and is supported only for CSV output.");
817
+ return {
818
+ inputPath: request.inputPath,
819
+ outputPath: request.outputPath,
820
+ extension,
821
+ format,
822
+ recalculate: operation === "recalculate",
823
+ ...request.sheet === void 0 ? {} : { sheet: request.sheet }
824
+ };
825
+ }
826
+ /**
827
+ * Reject an engine output with an incorrect container signature.
828
+ * @param bytes - Complete bounded output.
829
+ * @param format - Requested output suffix.
830
+ */
831
+ function validateOutput(bytes, format) {
832
+ if (format === "pdf" && new TextDecoder().decode(bytes.subarray(0, 5)) !== "%PDF-") throw new ConversionError("invalid-output", "LibreOffice did not produce a PDF.");
833
+ if ([
834
+ "docx",
835
+ "xlsx",
836
+ "pptx",
837
+ "odt",
838
+ "ods",
839
+ "odp"
840
+ ].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.`);
841
+ }
842
+ //#endregion
843
+ //#region lib/types/runtime.js
844
+ /** Offline discovery of the installed engine and public entry points. */
845
+ /**
846
+ * Inspect installed engine metadata without starting, downloading, or building an engine.
847
+ * @returns Public entry paths, engine version, and selected backend.
848
+ * @throws ConversionError when the installed engine is unavailable or invalid.
849
+ */
850
+ async function discoverRuntime() {
851
+ try {
852
+ const engine = await resolveEngine();
853
+ return {
854
+ version: ENGINE_VERSION,
855
+ backend: engine.backend,
856
+ cliPath: fileURLToPath(new URL("./cli.js", import.meta.url)),
857
+ nodeApiPath: fileURLToPath(new URL("./index.js", import.meta.url))
858
+ };
859
+ } catch (cause) {
860
+ throw new ConversionError("unavailable", cause.message, { cause });
861
+ }
862
+ }
717
863
  //#endregion
718
864
  //#region lib/types/index.js
719
865
  /** Convert caller-authorized disk documents with installed native or Node WASM engines. */
@@ -728,7 +874,7 @@ async function readBounded(path, limit, signal, role) {
728
874
  try {
729
875
  const before = await file.stat();
730
876
  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.");
877
+ if (!before.isFile() || role === "input" && before.size < 1) throw new ConversionError(invalid, "Document must be a nonempty regular file.");
732
878
  if (before.size > limit) throw new ConversionError(`${role}-too-large`, `Document exceeds its ${role} byte limit.`);
733
879
  const bytes = Buffer.alloc(before.size);
734
880
  for (let offset = 0; offset < bytes.length;) {
@@ -821,11 +967,8 @@ async function createConverter(options) {
821
967
  signal.throwIfAborted();
822
968
  running = true;
823
969
  }
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(", ")}.`);
970
+ async function execute(request, signal) {
971
+ const { extension, format } = request;
829
972
  await acquire(signal);
830
973
  const deadline = new AbortController();
831
974
  const stopped = AbortSignal.any([signal, deadline.signal]);
@@ -839,18 +982,19 @@ async function createConverter(options) {
839
982
  try {
840
983
  stopped.throwIfAborted();
841
984
  output = await open(request.outputPath, "wx", 384);
842
- const bytes = await readBounded(request.inputPath, resolvedOptions.maxInputBytes, stopped, "input");
985
+ const sourceBytes = await readBounded(request.inputPath, resolvedOptions.maxInputBytes, stopped, "input");
843
986
  scratch = await mkdtemp(join(tmpdir(), "libreoffice-kit-"));
844
987
  const inputPath = join(scratch, `document.${extension}`);
845
988
  const input = await open(inputPath, "wx", 384);
846
989
  try {
847
- await input.writeFile(bytes);
990
+ await input.writeFile(sourceBytes);
848
991
  } finally {
849
992
  await input.close();
850
993
  }
851
994
  const result = await runWorker({
852
995
  inputPath,
853
996
  extension,
997
+ operation: request,
854
998
  options: resolvedOptions,
855
999
  engine,
856
1000
  scratch,
@@ -858,19 +1002,20 @@ async function createConverter(options) {
858
1002
  }, stopped, (faces) => {
859
1003
  fontFaces = faces;
860
1004
  });
861
- let pdf;
862
- if ("pdf" in result) pdf = result.pdf;
1005
+ if ("images" in result) throw new ConversionError("failed", "Conversion worker returned an image batch for an export request.");
1006
+ let bytes;
1007
+ if ("output" in result) bytes = result.output;
863
1008
  else {
864
1009
  const native = engine;
865
1010
  const profile = join(scratch, "profile");
866
1011
  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");
1012
+ const path = join(scratch, `output.${format}`);
1013
+ await runNative(native, resolvedOptions, inputPath, path, profile, result.fonts, result.substitutions, stopped, request);
1014
+ bytes = await readBounded(path, resolvedOptions.maxOutputBytes, stopped, "output");
870
1015
  }
871
- if (Buffer.from(pdf.subarray(0, 5)).toString() !== "%PDF-") throw new ConversionError("invalid-output", "LibreOffice did not produce a PDF.");
1016
+ validateOutput(bytes, format);
872
1017
  stopped.throwIfAborted();
873
- await output.writeFile(pdf);
1018
+ await output.writeFile(bytes);
874
1019
  stopped.throwIfAborted();
875
1020
  succeeded = true;
876
1021
  return {
@@ -901,16 +1046,81 @@ async function createConverter(options) {
901
1046
  }
902
1047
  }
903
1048
  }
1049
+ async function executeImages(request, signal) {
1050
+ await acquire(signal);
1051
+ const deadline = new AbortController();
1052
+ const stopped = AbortSignal.any([signal, deadline.signal]);
1053
+ const timer = setTimeout(() => deadline.abort(new ConversionError("timeout", "LibreOffice image rendering timed out.")), resolvedOptions.timeoutMs);
1054
+ let scratch;
1055
+ let owned = false;
1056
+ let succeeded = false;
1057
+ try {
1058
+ stopped.throwIfAborted();
1059
+ await mkdir(request.outputDir, { mode: 448 });
1060
+ owned = true;
1061
+ const source = await readBounded(request.inputPath, resolvedOptions.maxInputBytes, stopped, "input");
1062
+ scratch = await mkdtemp(join(tmpdir(), "libreoffice-kit-images-"));
1063
+ const inputPath = join(scratch, `document.${request.extension}`);
1064
+ await writeFile(inputPath, source, {
1065
+ flag: "wx",
1066
+ mode: 384
1067
+ });
1068
+ const result = await runWorker({
1069
+ inputPath,
1070
+ extension: request.extension,
1071
+ operation: request,
1072
+ options: resolvedOptions,
1073
+ engine,
1074
+ scratch,
1075
+ fontFaces
1076
+ }, stopped, (faces) => {
1077
+ fontFaces = faces;
1078
+ });
1079
+ if (!("images" in result)) throw new ConversionError("failed", "Image worker did not return its manifest.");
1080
+ stopped.throwIfAborted();
1081
+ await writeFile(join(request.outputDir, "manifest.json"), `${JSON.stringify(result.images, null, 2)}\n`, {
1082
+ flag: "wx",
1083
+ mode: 384
1084
+ });
1085
+ stopped.throwIfAborted();
1086
+ succeeded = true;
1087
+ return result.images;
1088
+ } finally {
1089
+ clearTimeout(timer);
1090
+ try {
1091
+ const failures = (await Promise.allSettled([...scratch ? [rm(scratch, {
1092
+ recursive: true,
1093
+ force: true
1094
+ })] : [], ...owned && !succeeded ? [rm(request.outputDir, {
1095
+ recursive: true,
1096
+ force: true
1097
+ })] : []])).filter((result) => result.status === "rejected");
1098
+ if (failures.length) throw new AggregateError(failures.map((result) => result.reason), "Image batch cleanup failed.");
1099
+ } finally {
1100
+ running = false;
1101
+ for (const wake of [...waiting]) wake();
1102
+ }
1103
+ }
1104
+ }
1105
+ async function submit(request, operation, signal) {
1106
+ const task = execute(resolveConversion(request, operation), signal ? AbortSignal.any([signal, lifetime.signal]) : lifetime.signal);
1107
+ active.add(task);
1108
+ task.finally(() => {
1109
+ active.delete(task);
1110
+ }).catch((_error) => {});
1111
+ return task;
1112
+ }
904
1113
  return {
905
1114
  backend: engine.backend,
906
- render(request, signal) {
907
- const task = render(request, signal ? AbortSignal.any([signal, lifetime.signal]) : lifetime.signal);
1115
+ render: (request, signal) => submit(request, "render", signal),
1116
+ async renderImages(request, signal) {
1117
+ const task = executeImages(resolveImageRender(request), signal ? AbortSignal.any([signal, lifetime.signal]) : lifetime.signal);
908
1118
  active.add(task);
909
- task.finally(() => {
910
- active.delete(task);
911
- }).catch((_error) => {});
1119
+ task.finally(() => active.delete(task)).catch(() => {});
912
1120
  return task;
913
1121
  },
1122
+ convert: (request, signal) => submit(request, "convert", signal),
1123
+ recalculate: (request, signal) => submit(request, "recalculate", signal),
914
1124
  dispose() {
915
1125
  disposal ??= (async () => {
916
1126
  lifetime.abort(/* @__PURE__ */ new Error("LibreOffice converter is disposed."));
@@ -921,4 +1131,4 @@ async function createConverter(options) {
921
1131
  };
922
1132
  }
923
1133
  //#endregion
924
- export { ConversionError, ENGINE_VERSION, createConverter };
1134
+ export { CONVERSION_FORMATS, ConversionError, ENGINE_VERSION, IMAGE_FORMATS, createConverter, discoverRuntime };