@deepseek-ai/libreoffice-kit 0.2.2 → 0.2.3-rc.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.
Files changed (34) hide show
  1. package/README.md +12 -0
  2. package/README.zh.md +12 -0
  3. package/frame-forwarding/README.md +6 -2
  4. package/frame-forwarding/README.zh.md +6 -2
  5. package/frame-forwarding/include/dsh_frame_forwarding.h +10 -1
  6. package/frame-forwarding/index.d.ts +1 -1
  7. package/frame-forwarding/prebuilds/darwin-arm64/frame-forwarding.node +0 -0
  8. package/frame-forwarding/prebuilds/darwin-arm64/libdsh_frame_forwarding_sdk.a +0 -0
  9. package/frame-forwarding/prebuilds/darwin-arm64/manifest.json +13 -12
  10. package/frame-forwarding/prebuilds/darwin-x64/frame-forwarding.node +0 -0
  11. package/frame-forwarding/prebuilds/darwin-x64/libdsh_frame_forwarding_sdk.a +0 -0
  12. package/frame-forwarding/prebuilds/darwin-x64/manifest.json +13 -12
  13. package/frame-forwarding/prebuilds/win32-arm64/dsh_frame_forwarding_sdk.lib +0 -0
  14. package/frame-forwarding/prebuilds/win32-arm64/frame-forwarding.node +0 -0
  15. package/frame-forwarding/prebuilds/win32-arm64/manifest.json +13 -12
  16. package/frame-forwarding/prebuilds/win32-x64/dsh_frame_forwarding_sdk.lib +0 -0
  17. package/frame-forwarding/prebuilds/win32-x64/frame-forwarding.node +0 -0
  18. package/frame-forwarding/prebuilds/win32-x64/manifest.json +13 -12
  19. package/frame-forwarding/receipt.json +9 -8
  20. package/frame-forwarding/scripts/metadata.mjs +4 -3
  21. package/frame-forwarding/sdk.json +3 -2
  22. package/frame-forwarding/src/producer.cc +30 -7
  23. package/frame-forwarding/src/receiver.cc +7 -1
  24. package/frame-forwarding/src/transport.cc +28 -21
  25. package/frame-forwarding/src/transport.h +13 -0
  26. package/lib/cli.js +69 -20
  27. package/lib/editor.js +52 -15
  28. package/lib/index.js +69 -20
  29. package/lib/types/engine.d.ts +15 -4
  30. package/lib/types/errors.d.ts +6 -0
  31. package/lib/types/index.d.ts +7 -0
  32. package/lib/types/options.d.ts +9 -1
  33. package/lib/types/runtime.d.ts +5 -1
  34. package/package.json +6 -6
@@ -336,9 +336,14 @@ int wait_pipe(HANDLE pipe, OVERLAPPED& operation, HANDLE stop, HANDLE deadline,
336
336
  }
337
337
  return GetOverlappedResult(pipe, &operation, &count, FALSE) ? 1 : -1;
338
338
  }
339
- /** One connected pipe instance: the producer's client handle, or one instance the listener accepted. */
339
+ /**
340
+ * One connected pipe instance: the producer's client handle, or one instance the listener accepted. A producer sends
341
+ * its own handle values, and the receiving instance duplicates each one from the producer's process.
342
+ */
340
343
  class PipeChannel final : public Channel {
341
344
  HANDLE pipe_ = INVALID_HANDLE_VALUE, stop_ = nullptr, deadline_ = nullptr;
345
+ /** The producer process a receiving instance duplicates handles from; null on the producer side. */
346
+ HANDLE producer_ = nullptr;
342
347
  std::atomic<uint32_t> peer_{0};
343
348
  std::mutex writes_;
344
349
  void open_events() {
@@ -350,7 +355,8 @@ class PipeChannel final : public Channel {
350
355
  if (pipe_ != INVALID_HANDLE_VALUE) CloseHandle(pipe_);
351
356
  if (stop_) CloseHandle(stop_);
352
357
  if (deadline_) CloseHandle(deadline_);
353
- pipe_ = INVALID_HANDLE_VALUE; stop_ = nullptr; deadline_ = nullptr;
358
+ if (producer_) CloseHandle(producer_);
359
+ pipe_ = INVALID_HANDLE_VALUE; stop_ = nullptr; deadline_ = nullptr; producer_ = nullptr;
354
360
  }
355
361
  public:
356
362
  /** Producer side: connect to the receiver's pipe and check its process identity. */
@@ -371,8 +377,8 @@ class PipeChannel final : public Channel {
371
377
  peer_ = pid;
372
378
  } catch (...) { close_handles(); throw; }
373
379
  }
374
- /** Receiver side: adopt an instance whose client connected. */
375
- PipeChannel(HANDLE pipe, uint32_t pid) : pipe_(pipe) {
380
+ /** Receiver side: adopt an instance whose client connected, with that client's process for handle duplication. */
381
+ PipeChannel(HANDLE pipe, uint32_t pid, HANDLE producer) : pipe_(pipe), producer_(producer) {
376
382
  try { open_events(); } catch (...) { close_handles(); throw; }
377
383
  peer_ = pid;
378
384
  }
@@ -380,27 +386,15 @@ class PipeChannel final : public Channel {
380
386
  uint32_t peer_pid() const override { return peer_; }
381
387
  void interrupt() override { if (stop_) SetEvent(stop_); if (pipe_ != INVALID_HANDLE_VALUE) CancelIoEx(pipe_, nullptr); }
382
388
  protected:
389
+ /** The sender keeps a sent handle open until the receiver releases its frame, so the receiver can duplicate it. */
383
390
  bool send_packet(const Packet& source, uintptr_t resource) override {
384
391
  std::lock_guard<std::mutex> lock(writes_);
385
392
  if (WaitForSingleObject(stop_, 0) == WAIT_OBJECT_0) return false;
386
- Packet packet = source;
387
- HANDLE remote_handle = nullptr, target = nullptr;
388
- if (resource) {
389
- target = OpenProcess(PROCESS_DUP_HANDLE, FALSE, peer_);
390
- if (!target || !DuplicateHandle(GetCurrentProcess(), reinterpret_cast<HANDLE>(resource), target, &remote_handle, 0, FALSE, DUPLICATE_SAME_ACCESS)) {
391
- if (target) CloseHandle(target); return false;
392
- }
393
- packet.resource = reinterpret_cast<uintptr_t>(remote_handle);
394
- }
393
+ Packet packet = source; packet.resource = static_cast<uint64_t>(resource);
395
394
  OVERLAPPED operation{}; operation.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr); DWORD count = 0;
396
395
  bool ok = WriteFile(pipe_, &packet, sizeof(packet), &count, &operation) != FALSE;
397
396
  if (!ok && GetLastError() == ERROR_IO_PENDING) ok = wait_pipe(pipe_, operation, stop_, deadline_, INFINITE, count) == 1;
398
397
  CloseHandle(operation.hEvent);
399
- if (!ok && remote_handle) {
400
- HANDLE reclaimed = nullptr;
401
- if (DuplicateHandle(target, remote_handle, GetCurrentProcess(), &reclaimed, 0, FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) CloseHandle(reclaimed);
402
- }
403
- if (target) CloseHandle(target);
404
398
  return ok && count == sizeof(packet);
405
399
  }
406
400
  int receive_packet(Received& out, uint32_t timeout) override {
@@ -411,7 +405,18 @@ class PipeChannel final : public Channel {
411
405
  CloseHandle(operation.hEvent);
412
406
  if (result == 0) return WaitForSingleObject(stop_, 0) == WAIT_OBJECT_0 ? -1 : 0;
413
407
  if (result < 0 || count != sizeof(Packet)) return -1;
414
- out.pid = peer_; out.resource = static_cast<uintptr_t>(out.packet.resource);
408
+ out.pid = peer_; out.resource = 0;
409
+ // Only a receiving instance takes handles, and only from the producer's own handle table.
410
+ if (producer_ && out.packet.resource) {
411
+ HANDLE local = nullptr;
412
+ if (!DuplicateHandle(producer_, reinterpret_cast<HANDLE>(static_cast<uintptr_t>(out.packet.resource)), GetCurrentProcess(), &local, 0, FALSE,
413
+ DUPLICATE_SAME_ACCESS)) {
414
+ // An exited producer took its handles with it; a live one named a handle it does not own.
415
+ if (WaitForSingleObject(producer_, 0) != WAIT_OBJECT_0) invalid_resource_ = true;
416
+ interrupt(); return -1;
417
+ }
418
+ out.resource = reinterpret_cast<uintptr_t>(local);
419
+ }
415
420
  return 1;
416
421
  }
417
422
  };
@@ -493,9 +498,11 @@ class PipeListener final : public Listener {
493
498
  HANDLE pipe = instance_; instance_ = INVALID_HANDLE_VALUE;
494
499
  ULONG pid = 0;
495
500
  if (!GetNamedPipeClientProcessId(pipe, &pid)) { CloseHandle(pipe); return 0; }
496
- auto channel = std::make_unique<PipeChannel>(pipe, static_cast<uint32_t>(pid));
501
+ HANDLE producer = OpenProcess(PROCESS_DUP_HANDLE | SYNCHRONIZE, FALSE, pid);
502
+ if (!producer) { CloseHandle(pipe); return 0; }
503
+ auto channel = std::make_unique<PipeChannel>(pipe, static_cast<uint32_t>(pid), producer);
497
504
  Received hello;
498
- if (channel->receive(hello, handshake_ms_) != 1) { release_resource(hello.resource); return 0; }
505
+ if (channel->receive(hello, handshake_ms_) != 1 || hello.resource) { release_resource(hello.resource); return 0; }
499
506
  candidate.hello = hello; candidate.channel = std::move(channel);
500
507
  return 1;
501
508
  }
@@ -18,6 +18,15 @@ constexpr uint32_t hello_keyed_mutex = 1;
18
18
  * refuse producers without it, so a producer that relied on PID binding never connects.
19
19
  */
20
20
  constexpr uint32_t hello_transferable = 2;
21
+ /**
22
+ * Every handle a producer names belongs to the producer: on Windows frame.resource is a handle value in the producer's
23
+ * process, which the receiver duplicates from that process. Receivers refuse producers without it, and ready.stride
24
+ * echoes the hello capabilities the receiver accepted, so producers refuse receivers that would read the value as a
25
+ * handle of their own.
26
+ */
27
+ constexpr uint32_t hello_producer_local_handles = 4;
28
+ /** The hello capabilities a receiver of these sources accepts and echoes in ready.stride. */
29
+ constexpr uint32_t hello_capabilities = hello_keyed_mutex | hello_transferable | hello_producer_local_handles;
21
30
  /**
22
31
  * frame.max_frames carries per-frame flags; zero is an ordered frame. A replaceable frame may be dropped before
23
32
  * presentation once a newer replaceable frame of the same view is ready; receivers that ignore the flag present it.
@@ -26,6 +35,7 @@ constexpr uint32_t frame_replaceable = 1;
26
35
  /** goodbye.text of a candidate the receiver refuses before it receives a connection identifier. */
27
36
  constexpr const char* reject_busy = "channel-busy";
28
37
  constexpr const char* reject_capability = "transferable-tx-required";
38
+ constexpr const char* reject_local_handles = "producer-local-handles-required";
29
39
  constexpr const char* reject_credential = "invalid-credential";
30
40
  constexpr const char* reject_closed = "channel-closed";
31
41
  /** Prefix of a refusal that names the producer's and the receiver's protocol versions. */
@@ -52,11 +62,14 @@ class Channel {
52
62
  uint64_t connection() const { return connection_; }
53
63
  /** The last receive closed because a packet named another connection. */
54
64
  bool foreign_packet() const { return foreign_; }
65
+ /** The last receive closed because a packet named a handle its live sender does not own. */
66
+ bool invalid_resource() const { return invalid_resource_; }
55
67
  virtual void interrupt() = 0;
56
68
  virtual uint32_t peer_pid() const = 0;
57
69
  protected:
58
70
  virtual int receive_packet(Received&, uint32_t timeout_ms) = 0;
59
71
  virtual bool send_packet(const Packet&, uintptr_t resource) = 0;
72
+ bool invalid_resource_ = false;
60
73
  private:
61
74
  uint64_t connection_ = 0;
62
75
  char connection_text_[65] = {};
package/lib/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { createRequire } from "node:module";
3
3
  import { parseArgs } from "node:util";
4
4
  import { dirname, extname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
5
- import { closeSync, constants, createWriteStream, lstatSync, readSync, readdirSync } from "node:fs";
5
+ import { closeSync, constants, createWriteStream, lstatSync, readSync, readdirSync, statSync } from "node:fs";
6
6
  import { copyFile, lstat, mkdir, mkdtemp, open, readFile, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
7
7
  import { homedir, tmpdir } from "node:os";
8
8
  import { Worker } from "node:worker_threads";
@@ -51,6 +51,14 @@ function failureCode(error) {
51
51
  const code = error?.code;
52
52
  return typeof code === "string" && CODES.has(code) ? code : "failed";
53
53
  }
54
+ /**
55
+ * Describe any thrown value, including caller callbacks that throw non-Error values.
56
+ * @param error - The thrown value.
57
+ * @returns The Error message, or the value's string form.
58
+ */
59
+ function failureMessage(error) {
60
+ return error instanceof Error ? error.message : String(error);
61
+ }
54
62
  //#endregion
55
63
  //#region lib/types/sheet-geometry.js
56
64
  const MAX_COLUMN = 16383;
@@ -1494,10 +1502,20 @@ function fontGroups(value) {
1494
1502
  return value.map((group) => [...group]);
1495
1503
  }
1496
1504
  /**
1505
+ * Validate an optional caller-supplied engine package resolver.
1506
+ * @param value - The `resolveEnginePackage` option value.
1507
+ * @returns the resolver, or undefined when absent.
1508
+ * @throws TypeError when the value is defined and not a function.
1509
+ */
1510
+ function enginePackageResolver(value) {
1511
+ if (value !== void 0 && typeof value !== "function") throw new TypeError("resolveEnginePackage must be a function.");
1512
+ return value;
1513
+ }
1514
+ /**
1497
1515
  * Resolve defaults once; reject misspelled options and malformed font settings.
1498
1516
  * @param input - Caller options; absent fields keep their documented default.
1499
1517
  * @returns The validated limits and font settings, with caller arrays copied.
1500
- * @throws TypeError for a non-object argument or an unknown option name.
1518
+ * @throws TypeError for a non-object argument, an unknown option name, or a non-function `resolveEnginePackage`.
1501
1519
  * @throws RangeError for a limit outside the positive safe-integer timer range.
1502
1520
  */
1503
1521
  function resolveOptions(input = {}) {
@@ -1510,7 +1528,8 @@ function resolveOptions(input = {}) {
1510
1528
  initialFontFamilies: [],
1511
1529
  ...input
1512
1530
  };
1513
- for (const key of Object.keys(input)) if (!(key in DEFAULT_LIMITS) && !FONT_COLLECTION_NAMES.includes(key) && key !== "fontFallbacks" && key !== "fontMetadataCacheDirectory") throw new TypeError(`Unknown converter option: ${key}`);
1531
+ for (const key of Object.keys(input)) if (!(key in DEFAULT_LIMITS) && !FONT_COLLECTION_NAMES.includes(key) && key !== "fontFallbacks" && key !== "fontMetadataCacheDirectory" && key !== "resolveEnginePackage") throw new TypeError(`Unknown converter option: ${key}`);
1532
+ enginePackageResolver(input.resolveEnginePackage);
1514
1533
  const cacheDirectory = input.fontMetadataCacheDirectory === void 0 ? defaultFontMetadataCacheDirectory() : input.fontMetadataCacheDirectory;
1515
1534
  if (cacheDirectory !== false && (typeof cacheDirectory !== "string" || !isAbsolute(cacheDirectory) || cacheDirectory.includes("\0"))) throw new TypeError("fontMetadataCacheDirectory must be an absolute path or false.");
1516
1535
  return {
@@ -1537,16 +1556,16 @@ function resolveOptions(input = {}) {
1537
1556
  /** Resolve installed, version-matched engine packages without downloads or compilation. */
1538
1557
  const require = createRequire(import.meta.url);
1539
1558
  /** Node API release version returned by runtime discovery. */
1540
- const ENGINE_VERSION = "0.2.2";
1559
+ const ENGINE_VERSION = "0.2.3-rc.4";
1541
1560
  /** Exact compatible engine versions; unchanged platforms retain their published packages. */
1542
1561
  const ENGINE_VERSIONS = Object.freeze({
1543
- "darwin-arm64": "0.2.2",
1544
- "darwin-x64": "0.2.2",
1562
+ "darwin-arm64": "0.2.3-rc.4",
1563
+ "darwin-x64": "0.2.3-rc.4",
1545
1564
  "linux-arm64-glibc": "0.1.1",
1546
1565
  "linux-x64-glibc": "0.1.1",
1547
- "win32-arm64": "0.2.2",
1548
- "win32-x64": "0.2.2",
1549
- wasm: "0.2.2"
1566
+ "win32-arm64": "0.2.3-rc.4",
1567
+ "win32-x64": "0.2.3-rc.4",
1568
+ wasm: "0.2.3-rc.4"
1550
1569
  });
1551
1570
  /** npm scope and name prefix shared by the engine packages this adapter installs. */
1552
1571
  const ENGINE_PREFIX = "@deepseek-ai/libreoffice-kit";
@@ -1584,24 +1603,49 @@ function asset(root, value) {
1584
1603
  function glibcVersion(value) {
1585
1604
  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;
1586
1605
  }
1606
+ /** Resolve engine packages from this module's installation with Node module resolution. */
1607
+ function installedEnginePackage(name) {
1608
+ return require.resolve(`${name}/package.json`);
1609
+ }
1610
+ /**
1611
+ * Check one resolved engine `package.json` path before reading it.
1612
+ * @param packageFile - Value the resolver returned.
1613
+ * @param name - Engine package name.
1614
+ * @returns the path unchanged.
1615
+ * @throws Error when the value is not an absolute path to an existing file.
1616
+ */
1617
+ function resolvedManifest(packageFile, name) {
1618
+ if (typeof packageFile !== "string") throw new Error(`Engine package resolver must synchronously return a string path for ${name}; it returned ${packageFile === null ? "null" : typeof packageFile}`);
1619
+ if (!isAbsolute(packageFile)) throw new Error(`Engine package resolver returned a non-absolute path for ${name}: ${String(packageFile)}`);
1620
+ let file;
1621
+ try {
1622
+ file = statSync(packageFile).isFile();
1623
+ } catch (error) {
1624
+ throw new Error(`Engine package resolver returned a missing path for ${name}: ${packageFile}`, { cause: error });
1625
+ }
1626
+ if (!file) throw new Error(`Engine package resolver returned a path that is not a file for ${name}: ${packageFile}`);
1627
+ return packageFile;
1628
+ }
1587
1629
  /**
1588
1630
  * Prefer the installed compatible native engine; hosts without one use the shared WASM package.
1589
- * @param resolvePackage - Package manifest resolver; injectable for selection tests.
1590
- * @param packageExists - Installed-package probe; injectable for selection tests.
1631
+ * @param resolvePackage - Engine package manifest resolver; defaults to Node resolution from this module.
1632
+ * @param packageExists - Whether a native package that resolved as `MODULE_NOT_FOUND` is nevertheless installed (and
1633
+ * therefore incomplete). Only the default resolver probes this module's installation; a caller resolver is the sole
1634
+ * authority on whether its packages exist.
1591
1635
  * @param host - Process identification and diagnostic report.
1592
1636
  * @returns the installed native engine, or the installed WASM engine.
1593
1637
  */
1594
- async function resolveEngine(resolvePackage = (name) => require.resolve(`${name}/package.json`), packageExists = installedPackageExists, { platform = process.platform, arch = process.arch, report = hostReport } = {}) {
1638
+ async function resolveEngine(resolvePackage = installedEnginePackage, packageExists = resolvePackage === installedEnginePackage ? installedPackageExists : () => false, { platform = process.platform, arch = process.arch, report = hostReport } = {}) {
1595
1639
  const details = platform === "linux" ? report() : {};
1596
1640
  const target = platformTarget(platform, arch, () => details);
1597
1641
  if (target !== void 0) {
1598
1642
  const name = `${ENGINE_PREFIX}-${target}`;
1599
1643
  let packageFile;
1600
1644
  try {
1601
- packageFile = resolvePackage(name);
1645
+ packageFile = resolvedManifest(resolvePackage(name), name);
1602
1646
  } catch (error) {
1603
1647
  const failure = error;
1604
- if (!(failure?.code === "MODULE_NOT_FOUND" && typeof failure.message === "string" && failure.message.includes(`${name}/package.json`))) throw error;
1648
+ if (!(failure?.code === "MODULE_NOT_FOUND" && (resolvePackage !== installedEnginePackage || typeof failure.message === "string" && failure.message.includes(`${name}/package.json`)))) throw error;
1605
1649
  if (packageExists(name)) throw new Error(`Installed LibreOfficeKit package is incomplete: ${name}`, { cause: error });
1606
1650
  }
1607
1651
  if (packageFile !== void 0) {
@@ -1611,7 +1655,8 @@ async function resolveEngine(resolvePackage = (name) => require.resolve(`${name}
1611
1655
  if (!(minimum && host && minimum.some((part, index) => part > (host[index] ?? 0) && minimum.slice(0, index).every((prior, priorIndex) => prior === host[priorIndex])))) return engine;
1612
1656
  }
1613
1657
  }
1614
- return readEngine(resolvePackage(`${ENGINE_PREFIX}-wasm`), "wasm", "wasm");
1658
+ const wasm = `${ENGINE_PREFIX}-wasm`;
1659
+ return readEngine(resolvedManifest(resolvePackage(wasm), wasm), "wasm", "wasm");
1615
1660
  }
1616
1661
  async function engineAsset(root, value, name, kind) {
1617
1662
  const path = asset(root, value);
@@ -1812,12 +1857,16 @@ function pdfPageCount(bytes) {
1812
1857
  /** Offline discovery of the installed engine and public entry points. */
1813
1858
  /**
1814
1859
  * Inspect installed engine metadata without starting, downloading, or building an engine.
1860
+ * @param options - The options of a later createConverter call, validated the same way; only `resolveEnginePackage`
1861
+ * affects discovery, so both select the same engine.
1815
1862
  * @returns Public entry paths, Node API version, and selected backend.
1863
+ * @throws TypeError or RangeError for options createConverter would reject.
1816
1864
  * @throws ConversionError when the installed engine is unavailable or invalid.
1817
1865
  */
1818
- async function discoverRuntime() {
1866
+ async function discoverRuntime(options) {
1867
+ resolveOptions(options);
1819
1868
  try {
1820
- const engine = await resolveEngine();
1869
+ const engine = await resolveEngine(options?.resolveEnginePackage);
1821
1870
  return {
1822
1871
  version: ENGINE_VERSION,
1823
1872
  backend: engine.backend,
@@ -1826,7 +1875,7 @@ async function discoverRuntime() {
1826
1875
  nodeApiPath: fileURLToPath(new URL("./index.js", import.meta.url))
1827
1876
  };
1828
1877
  } catch (cause) {
1829
- throw new ConversionError("unavailable", cause.message, { cause });
1878
+ throw new ConversionError("unavailable", failureMessage(cause), { cause });
1830
1879
  }
1831
1880
  }
1832
1881
  //#endregion
@@ -2029,9 +2078,9 @@ async function resolveConverter(options) {
2029
2078
  const resolvedOptions = resolveOptions(options);
2030
2079
  let engine;
2031
2080
  try {
2032
- engine = await resolveEngine();
2081
+ engine = await resolveEngine(options?.resolveEnginePackage);
2033
2082
  } catch (cause) {
2034
- throw new ConversionError("unavailable", cause.message, { cause });
2083
+ throw new ConversionError("unavailable", failureMessage(cause), { cause });
2035
2084
  }
2036
2085
  return {
2037
2086
  options: resolvedOptions,
package/lib/editor.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { copyFile, mkdir, mkdtemp, readFile, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
3
- import { closeSync, constants, createWriteStream, fstatSync, lstatSync, openSync, readSync, readdirSync, writeFileSync } from "node:fs";
3
+ import { closeSync, constants, createWriteStream, fstatSync, lstatSync, openSync, readSync, readdirSync, statSync, writeFileSync } from "node:fs";
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import { basename, dirname, extname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
6
6
  import { pathToFileURL } from "node:url";
@@ -431,10 +431,20 @@ function fontGroups(value) {
431
431
  return value.map((group) => [...group]);
432
432
  }
433
433
  /**
434
+ * Validate an optional caller-supplied engine package resolver.
435
+ * @param value - The `resolveEnginePackage` option value.
436
+ * @returns the resolver, or undefined when absent.
437
+ * @throws TypeError when the value is defined and not a function.
438
+ */
439
+ function enginePackageResolver(value) {
440
+ if (value !== void 0 && typeof value !== "function") throw new TypeError("resolveEnginePackage must be a function.");
441
+ return value;
442
+ }
443
+ /**
434
444
  * Resolve defaults once; reject misspelled options and malformed font settings.
435
445
  * @param input - Caller options; absent fields keep their documented default.
436
446
  * @returns The validated limits and font settings, with caller arrays copied.
437
- * @throws TypeError for a non-object argument or an unknown option name.
447
+ * @throws TypeError for a non-object argument, an unknown option name, or a non-function `resolveEnginePackage`.
438
448
  * @throws RangeError for a limit outside the positive safe-integer timer range.
439
449
  */
440
450
  function resolveOptions(input = {}) {
@@ -447,7 +457,8 @@ function resolveOptions(input = {}) {
447
457
  initialFontFamilies: [],
448
458
  ...input
449
459
  };
450
- for (const key of Object.keys(input)) if (!(key in DEFAULT_LIMITS) && !FONT_COLLECTION_NAMES.includes(key) && key !== "fontFallbacks" && key !== "fontMetadataCacheDirectory") throw new TypeError(`Unknown converter option: ${key}`);
460
+ for (const key of Object.keys(input)) if (!(key in DEFAULT_LIMITS) && !FONT_COLLECTION_NAMES.includes(key) && key !== "fontFallbacks" && key !== "fontMetadataCacheDirectory" && key !== "resolveEnginePackage") throw new TypeError(`Unknown converter option: ${key}`);
461
+ enginePackageResolver(input.resolveEnginePackage);
451
462
  const cacheDirectory = input.fontMetadataCacheDirectory === void 0 ? defaultFontMetadataCacheDirectory() : input.fontMetadataCacheDirectory;
452
463
  if (cacheDirectory !== false && (typeof cacheDirectory !== "string" || !isAbsolute(cacheDirectory) || cacheDirectory.includes("\0"))) throw new TypeError("fontMetadataCacheDirectory must be an absolute path or false.");
453
464
  return {
@@ -475,13 +486,13 @@ function resolveOptions(input = {}) {
475
486
  const require = createRequire(import.meta.url);
476
487
  /** Exact compatible engine versions; unchanged platforms retain their published packages. */
477
488
  const ENGINE_VERSIONS = Object.freeze({
478
- "darwin-arm64": "0.2.2",
479
- "darwin-x64": "0.2.2",
489
+ "darwin-arm64": "0.2.3-rc.4",
490
+ "darwin-x64": "0.2.3-rc.4",
480
491
  "linux-arm64-glibc": "0.1.1",
481
492
  "linux-x64-glibc": "0.1.1",
482
- "win32-arm64": "0.2.2",
483
- "win32-x64": "0.2.2",
484
- wasm: "0.2.2"
493
+ "win32-arm64": "0.2.3-rc.4",
494
+ "win32-x64": "0.2.3-rc.4",
495
+ wasm: "0.2.3-rc.4"
485
496
  });
486
497
  /** npm scope and name prefix shared by the engine packages this adapter installs. */
487
498
  const ENGINE_PREFIX = "@deepseek-ai/libreoffice-kit";
@@ -519,24 +530,49 @@ function asset(root, value) {
519
530
  function glibcVersion(value) {
520
531
  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;
521
532
  }
533
+ /** Resolve engine packages from this module's installation with Node module resolution. */
534
+ function installedEnginePackage(name) {
535
+ return require.resolve(`${name}/package.json`);
536
+ }
537
+ /**
538
+ * Check one resolved engine `package.json` path before reading it.
539
+ * @param packageFile - Value the resolver returned.
540
+ * @param name - Engine package name.
541
+ * @returns the path unchanged.
542
+ * @throws Error when the value is not an absolute path to an existing file.
543
+ */
544
+ function resolvedManifest(packageFile, name) {
545
+ if (typeof packageFile !== "string") throw new Error(`Engine package resolver must synchronously return a string path for ${name}; it returned ${packageFile === null ? "null" : typeof packageFile}`);
546
+ if (!isAbsolute(packageFile)) throw new Error(`Engine package resolver returned a non-absolute path for ${name}: ${String(packageFile)}`);
547
+ let file;
548
+ try {
549
+ file = statSync(packageFile).isFile();
550
+ } catch (error) {
551
+ throw new Error(`Engine package resolver returned a missing path for ${name}: ${packageFile}`, { cause: error });
552
+ }
553
+ if (!file) throw new Error(`Engine package resolver returned a path that is not a file for ${name}: ${packageFile}`);
554
+ return packageFile;
555
+ }
522
556
  /**
523
557
  * Prefer the installed compatible native engine; hosts without one use the shared WASM package.
524
- * @param resolvePackage - Package manifest resolver; injectable for selection tests.
525
- * @param packageExists - Installed-package probe; injectable for selection tests.
558
+ * @param resolvePackage - Engine package manifest resolver; defaults to Node resolution from this module.
559
+ * @param packageExists - Whether a native package that resolved as `MODULE_NOT_FOUND` is nevertheless installed (and
560
+ * therefore incomplete). Only the default resolver probes this module's installation; a caller resolver is the sole
561
+ * authority on whether its packages exist.
526
562
  * @param host - Process identification and diagnostic report.
527
563
  * @returns the installed native engine, or the installed WASM engine.
528
564
  */
529
- async function resolveEngine(resolvePackage = (name) => require.resolve(`${name}/package.json`), packageExists = installedPackageExists, { platform = process.platform, arch = process.arch, report = hostReport } = {}) {
565
+ async function resolveEngine(resolvePackage = installedEnginePackage, packageExists = resolvePackage === installedEnginePackage ? installedPackageExists : () => false, { platform = process.platform, arch = process.arch, report = hostReport } = {}) {
530
566
  const details = platform === "linux" ? report() : {};
531
567
  const target = platformTarget(platform, arch, () => details);
532
568
  if (target !== void 0) {
533
569
  const name = `${ENGINE_PREFIX}-${target}`;
534
570
  let packageFile;
535
571
  try {
536
- packageFile = resolvePackage(name);
572
+ packageFile = resolvedManifest(resolvePackage(name), name);
537
573
  } catch (error) {
538
574
  const failure = error;
539
- if (!(failure?.code === "MODULE_NOT_FOUND" && typeof failure.message === "string" && failure.message.includes(`${name}/package.json`))) throw error;
575
+ if (!(failure?.code === "MODULE_NOT_FOUND" && (resolvePackage !== installedEnginePackage || typeof failure.message === "string" && failure.message.includes(`${name}/package.json`)))) throw error;
540
576
  if (packageExists(name)) throw new Error(`Installed LibreOfficeKit package is incomplete: ${name}`, { cause: error });
541
577
  }
542
578
  if (packageFile !== void 0) {
@@ -546,7 +582,8 @@ async function resolveEngine(resolvePackage = (name) => require.resolve(`${name}
546
582
  if (!(minimum && host && minimum.some((part, index) => part > (host[index] ?? 0) && minimum.slice(0, index).every((prior, priorIndex) => prior === host[priorIndex])))) return engine;
547
583
  }
548
584
  }
549
- return readEngine(resolvePackage(`${ENGINE_PREFIX}-wasm`), "wasm", "wasm");
585
+ const wasm = `${ENGINE_PREFIX}-wasm`;
586
+ return readEngine(resolvedManifest(resolvePackage(wasm), wasm), "wasm", "wasm");
550
587
  }
551
588
  async function engineAsset(root, value, name, kind) {
552
589
  const path = asset(root, value);
@@ -1787,7 +1824,7 @@ async function openDocument(request) {
1787
1824
  const lifetime = new AbortController();
1788
1825
  const signal = request.signal ? AbortSignal.any([request.signal, lifetime.signal]) : lifetime.signal;
1789
1826
  signal.throwIfAborted();
1790
- const engine = await resolveEngine();
1827
+ const engine = await resolveEngine(request.options?.resolveEnginePackage);
1791
1828
  if (engine.backend !== "native" || engine.legacyInputPath) throw new Error("Native editing requires a preview-capable native engine package.");
1792
1829
  const scratch = await mkdtemp(join(tmpdir(), "libreoffice-editor-"));
1793
1830
  let transport;
package/lib/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from "node:module";
2
- import { closeSync, constants, createWriteStream, lstatSync, readSync, readdirSync } from "node:fs";
2
+ import { closeSync, constants, createWriteStream, lstatSync, readSync, readdirSync, statSync } from "node:fs";
3
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";
@@ -49,6 +49,14 @@ function failureCode(error) {
49
49
  const code = error?.code;
50
50
  return typeof code === "string" && CODES.has(code) ? code : "failed";
51
51
  }
52
+ /**
53
+ * Describe any thrown value, including caller callbacks that throw non-Error values.
54
+ * @param error - The thrown value.
55
+ * @returns The Error message, or the value's string form.
56
+ */
57
+ function failureMessage(error) {
58
+ return error instanceof Error ? error.message : String(error);
59
+ }
52
60
  //#endregion
53
61
  //#region lib/types/sheet-geometry.js
54
62
  const MAX_COLUMN = 16383;
@@ -1492,10 +1500,20 @@ function fontGroups(value) {
1492
1500
  return value.map((group) => [...group]);
1493
1501
  }
1494
1502
  /**
1503
+ * Validate an optional caller-supplied engine package resolver.
1504
+ * @param value - The `resolveEnginePackage` option value.
1505
+ * @returns the resolver, or undefined when absent.
1506
+ * @throws TypeError when the value is defined and not a function.
1507
+ */
1508
+ function enginePackageResolver(value) {
1509
+ if (value !== void 0 && typeof value !== "function") throw new TypeError("resolveEnginePackage must be a function.");
1510
+ return value;
1511
+ }
1512
+ /**
1495
1513
  * Resolve defaults once; reject misspelled options and malformed font settings.
1496
1514
  * @param input - Caller options; absent fields keep their documented default.
1497
1515
  * @returns The validated limits and font settings, with caller arrays copied.
1498
- * @throws TypeError for a non-object argument or an unknown option name.
1516
+ * @throws TypeError for a non-object argument, an unknown option name, or a non-function `resolveEnginePackage`.
1499
1517
  * @throws RangeError for a limit outside the positive safe-integer timer range.
1500
1518
  */
1501
1519
  function resolveOptions(input = {}) {
@@ -1508,7 +1526,8 @@ function resolveOptions(input = {}) {
1508
1526
  initialFontFamilies: [],
1509
1527
  ...input
1510
1528
  };
1511
- for (const key of Object.keys(input)) if (!(key in DEFAULT_LIMITS) && !FONT_COLLECTION_NAMES.includes(key) && key !== "fontFallbacks" && key !== "fontMetadataCacheDirectory") throw new TypeError(`Unknown converter option: ${key}`);
1529
+ for (const key of Object.keys(input)) if (!(key in DEFAULT_LIMITS) && !FONT_COLLECTION_NAMES.includes(key) && key !== "fontFallbacks" && key !== "fontMetadataCacheDirectory" && key !== "resolveEnginePackage") throw new TypeError(`Unknown converter option: ${key}`);
1530
+ enginePackageResolver(input.resolveEnginePackage);
1512
1531
  const cacheDirectory = input.fontMetadataCacheDirectory === void 0 ? defaultFontMetadataCacheDirectory() : input.fontMetadataCacheDirectory;
1513
1532
  if (cacheDirectory !== false && (typeof cacheDirectory !== "string" || !isAbsolute(cacheDirectory) || cacheDirectory.includes("\0"))) throw new TypeError("fontMetadataCacheDirectory must be an absolute path or false.");
1514
1533
  return {
@@ -1535,16 +1554,16 @@ function resolveOptions(input = {}) {
1535
1554
  /** Resolve installed, version-matched engine packages without downloads or compilation. */
1536
1555
  const require = createRequire(import.meta.url);
1537
1556
  /** Node API release version returned by runtime discovery. */
1538
- const ENGINE_VERSION = "0.2.2";
1557
+ const ENGINE_VERSION = "0.2.3-rc.4";
1539
1558
  /** Exact compatible engine versions; unchanged platforms retain their published packages. */
1540
1559
  const ENGINE_VERSIONS = Object.freeze({
1541
- "darwin-arm64": "0.2.2",
1542
- "darwin-x64": "0.2.2",
1560
+ "darwin-arm64": "0.2.3-rc.4",
1561
+ "darwin-x64": "0.2.3-rc.4",
1543
1562
  "linux-arm64-glibc": "0.1.1",
1544
1563
  "linux-x64-glibc": "0.1.1",
1545
- "win32-arm64": "0.2.2",
1546
- "win32-x64": "0.2.2",
1547
- wasm: "0.2.2"
1564
+ "win32-arm64": "0.2.3-rc.4",
1565
+ "win32-x64": "0.2.3-rc.4",
1566
+ wasm: "0.2.3-rc.4"
1548
1567
  });
1549
1568
  /** npm scope and name prefix shared by the engine packages this adapter installs. */
1550
1569
  const ENGINE_PREFIX = "@deepseek-ai/libreoffice-kit";
@@ -1582,24 +1601,49 @@ function asset(root, value) {
1582
1601
  function glibcVersion(value) {
1583
1602
  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;
1584
1603
  }
1604
+ /** Resolve engine packages from this module's installation with Node module resolution. */
1605
+ function installedEnginePackage(name) {
1606
+ return require.resolve(`${name}/package.json`);
1607
+ }
1608
+ /**
1609
+ * Check one resolved engine `package.json` path before reading it.
1610
+ * @param packageFile - Value the resolver returned.
1611
+ * @param name - Engine package name.
1612
+ * @returns the path unchanged.
1613
+ * @throws Error when the value is not an absolute path to an existing file.
1614
+ */
1615
+ function resolvedManifest(packageFile, name) {
1616
+ if (typeof packageFile !== "string") throw new Error(`Engine package resolver must synchronously return a string path for ${name}; it returned ${packageFile === null ? "null" : typeof packageFile}`);
1617
+ if (!isAbsolute(packageFile)) throw new Error(`Engine package resolver returned a non-absolute path for ${name}: ${String(packageFile)}`);
1618
+ let file;
1619
+ try {
1620
+ file = statSync(packageFile).isFile();
1621
+ } catch (error) {
1622
+ throw new Error(`Engine package resolver returned a missing path for ${name}: ${packageFile}`, { cause: error });
1623
+ }
1624
+ if (!file) throw new Error(`Engine package resolver returned a path that is not a file for ${name}: ${packageFile}`);
1625
+ return packageFile;
1626
+ }
1585
1627
  /**
1586
1628
  * Prefer the installed compatible native engine; hosts without one use the shared WASM package.
1587
- * @param resolvePackage - Package manifest resolver; injectable for selection tests.
1588
- * @param packageExists - Installed-package probe; injectable for selection tests.
1629
+ * @param resolvePackage - Engine package manifest resolver; defaults to Node resolution from this module.
1630
+ * @param packageExists - Whether a native package that resolved as `MODULE_NOT_FOUND` is nevertheless installed (and
1631
+ * therefore incomplete). Only the default resolver probes this module's installation; a caller resolver is the sole
1632
+ * authority on whether its packages exist.
1589
1633
  * @param host - Process identification and diagnostic report.
1590
1634
  * @returns the installed native engine, or the installed WASM engine.
1591
1635
  */
1592
- async function resolveEngine(resolvePackage = (name) => require.resolve(`${name}/package.json`), packageExists = installedPackageExists, { platform = process.platform, arch = process.arch, report = hostReport } = {}) {
1636
+ async function resolveEngine(resolvePackage = installedEnginePackage, packageExists = resolvePackage === installedEnginePackage ? installedPackageExists : () => false, { platform = process.platform, arch = process.arch, report = hostReport } = {}) {
1593
1637
  const details = platform === "linux" ? report() : {};
1594
1638
  const target = platformTarget(platform, arch, () => details);
1595
1639
  if (target !== void 0) {
1596
1640
  const name = `${ENGINE_PREFIX}-${target}`;
1597
1641
  let packageFile;
1598
1642
  try {
1599
- packageFile = resolvePackage(name);
1643
+ packageFile = resolvedManifest(resolvePackage(name), name);
1600
1644
  } catch (error) {
1601
1645
  const failure = error;
1602
- if (!(failure?.code === "MODULE_NOT_FOUND" && typeof failure.message === "string" && failure.message.includes(`${name}/package.json`))) throw error;
1646
+ if (!(failure?.code === "MODULE_NOT_FOUND" && (resolvePackage !== installedEnginePackage || typeof failure.message === "string" && failure.message.includes(`${name}/package.json`)))) throw error;
1603
1647
  if (packageExists(name)) throw new Error(`Installed LibreOfficeKit package is incomplete: ${name}`, { cause: error });
1604
1648
  }
1605
1649
  if (packageFile !== void 0) {
@@ -1609,7 +1653,8 @@ async function resolveEngine(resolvePackage = (name) => require.resolve(`${name}
1609
1653
  if (!(minimum && host && minimum.some((part, index) => part > (host[index] ?? 0) && minimum.slice(0, index).every((prior, priorIndex) => prior === host[priorIndex])))) return engine;
1610
1654
  }
1611
1655
  }
1612
- return readEngine(resolvePackage(`${ENGINE_PREFIX}-wasm`), "wasm", "wasm");
1656
+ const wasm = `${ENGINE_PREFIX}-wasm`;
1657
+ return readEngine(resolvedManifest(resolvePackage(wasm), wasm), "wasm", "wasm");
1613
1658
  }
1614
1659
  async function engineAsset(root, value, name, kind) {
1615
1660
  const path = asset(root, value);
@@ -1810,12 +1855,16 @@ function pdfPageCount(bytes) {
1810
1855
  /** Offline discovery of the installed engine and public entry points. */
1811
1856
  /**
1812
1857
  * Inspect installed engine metadata without starting, downloading, or building an engine.
1858
+ * @param options - The options of a later createConverter call, validated the same way; only `resolveEnginePackage`
1859
+ * affects discovery, so both select the same engine.
1813
1860
  * @returns Public entry paths, Node API version, and selected backend.
1861
+ * @throws TypeError or RangeError for options createConverter would reject.
1814
1862
  * @throws ConversionError when the installed engine is unavailable or invalid.
1815
1863
  */
1816
- async function discoverRuntime() {
1864
+ async function discoverRuntime(options) {
1865
+ resolveOptions(options);
1817
1866
  try {
1818
- const engine = await resolveEngine();
1867
+ const engine = await resolveEngine(options?.resolveEnginePackage);
1819
1868
  return {
1820
1869
  version: ENGINE_VERSION,
1821
1870
  backend: engine.backend,
@@ -1824,7 +1873,7 @@ async function discoverRuntime() {
1824
1873
  nodeApiPath: fileURLToPath(new URL("./index.js", import.meta.url))
1825
1874
  };
1826
1875
  } catch (cause) {
1827
- throw new ConversionError("unavailable", cause.message, { cause });
1876
+ throw new ConversionError("unavailable", failureMessage(cause), { cause });
1828
1877
  }
1829
1878
  }
1830
1879
  //#endregion
@@ -2027,9 +2076,9 @@ async function resolveConverter(options) {
2027
2076
  const resolvedOptions = resolveOptions(options);
2028
2077
  let engine;
2029
2078
  try {
2030
- engine = await resolveEngine();
2079
+ engine = await resolveEngine(options?.resolveEnginePackage);
2031
2080
  } catch (cause) {
2032
- throw new ConversionError("unavailable", cause.message, { cause });
2081
+ throw new ConversionError("unavailable", failureMessage(cause), { cause });
2033
2082
  }
2034
2083
  return {
2035
2084
  options: resolvedOptions,