@deepseek-ai/libreoffice-kit 0.0.3 → 0.0.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/README.md +21 -4
- package/README.zh.md +21 -4
- package/lib/cli.js +149 -20
- package/lib/font-snapshot-worker.js +454 -0
- package/lib/index.js +153 -22
- package/lib/types/engine.d.ts +1 -1
- package/lib/types/font-metadata-cache.d.ts +11 -0
- package/lib/types/font-snapshot-state.d.ts +15 -0
- package/lib/types/font-snapshot-validation.d.ts +4 -0
- package/lib/types/font-snapshot-worker.d.ts +9 -0
- package/lib/types/font-snapshot.d.ts +11 -0
- package/lib/types/fonts.d.ts +9 -3
- package/lib/types/index.d.ts +4 -0
- package/lib/types/options.d.ts +2 -0
- package/lib/types/worker.d.ts +3 -3
- package/lib/worker.js +7 -248
- package/package.json +7 -6
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ Binary `.doc`, `.xls`, and `.ppt` inputs must be OLE compound documents, such as
|
|
|
11
11
|
Install with Node.js 22.19.0 or newer:
|
|
12
12
|
|
|
13
13
|
```sh
|
|
14
|
-
npm install @deepseek-ai/libreoffice-kit@0.0.
|
|
14
|
+
npm install @deepseek-ai/libreoffice-kit@0.0.4
|
|
15
15
|
```
|
|
16
16
|
|
|
17
17
|
npm installs the matching native engine on macOS/Windows ARM64 or x64, and the shared WASM engine on Linux. macOS and Windows require their native package; a missing or invalid package rejects `createConverter` with `unavailable`, without switching to WASM. Linux uses WASM unless a compatible development native package was installed explicitly. Conversion failures never switch engines.
|
|
@@ -35,7 +35,7 @@ Native and WASM engines are platform-filtered optional dependencies. Application
|
|
|
35
35
|
|
|
36
36
|
Each converter serializes renders. A render creates a separate native process or Node worker and private profile, so fonts, document state, and failures do not leak into later renders. The deadline begins after acquiring its conversion slot. An `AbortSignal` cancels queued or active work; cancellation and `dispose()` await process or worker exit and scratch cleanup. Disposed converters reject further work.
|
|
37
37
|
|
|
38
|
-
Converters created through the compatibility `createConverter(options)` API transparently share bounded font metadata and match results with other process-local converters using the same engine and font configuration. Disposing a converter still joins only its own work;
|
|
38
|
+
Converters created through the compatibility `createConverter(options)` API transparently share bounded font metadata and match results with other process-local converters using the same engine and font configuration. Disposing a converter still joins only its own work; metadata remains available to later compatible converters, with at most 16 retained configurations. `maxFontMetadataCacheBytes` bounds retained per-file metadata; `maxFontResolutionEntries` bounds matching entries and defaults to 4096.
|
|
39
39
|
|
|
40
40
|
For a long-lived service that wants one explicit lifecycle owner for concurrent conversion slots, create one `createConverterFactory(options)` and obtain converters through `factory.create()`. Those converters use a factory-private cache while retaining separate Workers, native helpers, profiles, and output ownership. Dispose the factory to stop and join every converter it created.
|
|
41
41
|
|
|
@@ -53,7 +53,24 @@ The caller authorizes input access and owns private input/output directories; pa
|
|
|
53
53
|
|
|
54
54
|
The Node API and engine packages share the kit release version. `ENGINE_VERSION` pins both WASM and native optional dependencies to the exact engine version. npm installs prepared engines; installation and conversion never compile LibreOffice or download additional engine payloads. Each engine includes its matching source recipes, patches, build information, and third-party license notices under `sources/` and `licenses/`.
|
|
55
55
|
|
|
56
|
-
Defaults and all options are documented in the shipped TypeScript declarations in `lib/types/index.d.ts`. Font directories use conventional system/user paths for the selected OS. Indexing skips missing or protected sources and propagates other filesystem errors. `fontkit` indexes original font files and selects installed faces and glyph coverage; it does not rewrite fonts.
|
|
56
|
+
Defaults and all options are documented in the shipped TypeScript declarations in `lib/types/index.d.ts`. Font directories use conventional system/user paths for the selected OS. Indexing skips missing or protected sources and propagates other filesystem errors. `fontkit` indexes original font files and selects installed faces and glyph coverage; it does not rewrite fonts. Each operation discovers font candidates again and revalidates cached file identities. It uses one ordered metadata snapshot; matching entries are invalidated when that snapshot changes. A detected font change during conversion rejects the operation and removes its output. Original font bytes and decoded glyph coverage remain conversion-local. `missingFonts` contains absent families declared in readable document XML, excluding unrelated engine defaults. Missing glyphs without a named missing family are not a complete document accessibility report.
|
|
57
|
+
|
|
58
|
+
### Font metadata cache
|
|
59
|
+
|
|
60
|
+
Both `createConverter()` and `createConverterFactory()` accept:
|
|
61
|
+
|
|
62
|
+
| Option | Default | Behavior |
|
|
63
|
+
| --- | --- | --- |
|
|
64
|
+
| `fontMetadataCacheDirectory` | User system cache directory | Absolute directory path, or `false` to disable disk caching. |
|
|
65
|
+
| `maxFontMetadataCacheBytes` | 32 MiB | Positive safe integer limiting each cache file read/write and retained per-file metadata per shared configuration. |
|
|
66
|
+
|
|
67
|
+
The default directory is `~/Library/Caches/libreoffice-kit` on macOS, `%LOCALAPPDATA%/libreoffice-kit/Cache` on Windows (falling back to the user's `AppData/Local`), and `$XDG_CACHE_HOME/libreoffice-kit` on Linux (falling back to `~/.cache`). The single `font-metadata.json` file contains canonical file paths, device/inode, size, modification/change times, and all face metadata, including empty parse results. It contains no font bytes, glyph coverage, parsed font objects, document text, or document matching entries. Keep this user-local file private.
|
|
68
|
+
|
|
69
|
+
A first run without reusable metadata performs the full original font inspection. Later processes skip inspection only for discovered files with matching identities. Each operation re-enumerates sources, including supplemental Office sources, so additions, deletions, replacements, and directory changes do not require a restart. Candidate order, file budgets, Office filtering, fallback matching, glyph queries, and original font import remain unchanged. A corrupted, incompatible, oversized, or inaccessible cache falls back to source inspection; unreadable source files never reuse stale records. Format, extractor, and pinned fontkit versions must match.
|
|
70
|
+
|
|
71
|
+
New cache directories and files use private permissions (`0700`/`0600` where supported). Writes close an exclusive temporary file in the same directory before atomic replacement. Unchanged snapshots are not rewritten; snapshots exceeding the byte limit are not retained or written. Independent processes may publish competing complete snapshots, affecting hit rate only. The owning operation cleans up its temporary file after its metadata Worker exits.
|
|
72
|
+
|
|
73
|
+
Simultaneous operations within one shared configuration share a short-lived metadata Worker. Each waiter keeps its own cancellation and deadline; cancelling one does not cancel the others. The last departing waiter terminates and joins the Worker. Completed scans retain bounded metadata, without a live scan Worker or original font buffers. Setting `fontMetadataCacheDirectory: false` keeps these in-process sharing and source-version checks. Factory caches have their own lifetime and are cleared by `factory.dispose()`.
|
|
57
74
|
|
|
58
75
|
When `fontDirectories` is omitted on macOS or Windows, default discovery also checks Microsoft Office's bundled/private font directory and the user's Office font cache. Only curated Office-compatible families absent from normal system roots are added, including SimSun and Microsoft YaHei. Explicit `fontDirectories` disables this supplemental discovery.
|
|
59
76
|
|
|
@@ -78,4 +95,4 @@ This package is licensed under [MPL-2.0](LICENSE). The engine packages include `
|
|
|
78
95
|
- Font import and output limits do not bound all native memory or temporary disk use. Native platform engines may resolve fonts differently from WASM.
|
|
79
96
|
- Installations from npm use platform-specific optional packages. Applications that bundle engines must retain the complete selected package, including its resources and notices.
|
|
80
97
|
- Windows requires the Microsoft Visual C++ v14 Redistributable matching the Node.js architecture (x64 or ARM64); it is not bundled. Use ARM64 Node.js for the Windows ARM64 engine.
|
|
81
|
-
- Version `0.0.
|
|
98
|
+
- Version `0.0.4` ships macOS and Windows native engines for ARM64 and x64 and a shared Node WASM engine for Linux. Other native platforms are development recipes.
|
package/README.zh.md
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
使用 Node.js 22.19.0 或更新版本安装:
|
|
12
12
|
|
|
13
13
|
```sh
|
|
14
|
-
npm install @deepseek-ai/libreoffice-kit@0.0.
|
|
14
|
+
npm install @deepseek-ai/libreoffice-kit@0.0.4
|
|
15
15
|
```
|
|
16
16
|
|
|
17
17
|
npm 在 macOS/Windows ARM64 或 x64 上安装匹配的原生引擎,在 Linux 上安装共享 WASM 引擎。macOS 和 Windows 必须具有对应原生包;包缺失或无效时,`createConverter` 以 `unavailable` 拒绝,不会切换到 WASM。Linux 使用 WASM,除非显式安装了兼容的原生开发包。转换失败不会切换引擎。
|
|
@@ -35,7 +35,7 @@ try {
|
|
|
35
35
|
|
|
36
36
|
每个转换器串行执行渲染。一次渲染会创建独立的原生进程或 Node worker 以及私有配置目录,因此字体、文档状态和失败不会泄漏到后续渲染。截止时间在获得转换槽位之后开始计算。`AbortSignal` 可以取消排队中或进行中的工作;取消和 `dispose()` 都会等待进程或 worker 退出并完成临时文件清理。已释放的转换器会拒绝后续工作。
|
|
37
37
|
|
|
38
|
-
通过兼容 API `createConverter(options)` 创建的转换器,会自动与进程内使用相同引擎及字体配置的其他转换器共享有界字体元数据和匹配结果。释放 converter
|
|
38
|
+
通过兼容 API `createConverter(options)` 创建的转换器,会自动与进程内使用相同引擎及字体配置的其他转换器共享有界字体元数据和匹配结果。释放 converter 仍只等待它自己的工作;元数据会留给后续兼容 converter,最多保留 16 种配置。`maxFontMetadataCacheBytes` 限制保留的逐文件元数据,`maxFontResolutionEntries` 限制匹配条目,默认值为 4096。
|
|
39
39
|
|
|
40
40
|
长驻服务如果需要为多个并发转换槽提供一个显式生命周期所有者,可创建 `createConverterFactory(options)`,再通过 `factory.create()` 建立转换器。这些转换器使用 factory 私有缓存,同时仍分别拥有 Worker、原生 helper、配置目录和输出。释放 factory 会停止并等待它创建的全部转换器。
|
|
41
41
|
|
|
@@ -53,7 +53,24 @@ try {
|
|
|
53
53
|
|
|
54
54
|
Node API 与引擎包使用相同的 kit 发布版本。`ENGINE_VERSION` 将 WASM 和原生可选依赖固定到精确的引擎版本。npm 安装预编译引擎;安装和转换阶段均不会编译 LibreOffice 或额外下载引擎资源。每个引擎包的 `sources/` 和 `licenses/` 保留匹配的源码配方、补丁、构建信息和第三方许可声明。
|
|
55
55
|
|
|
56
|
-
默认值和所有选项记录在随包发布的 `lib/types/index.d.ts` 类型声明中。字体目录使用所选操作系统的常规系统/用户路径。索引会跳过缺失或受保护的来源,并传播其他文件系统错误。`fontkit`
|
|
56
|
+
默认值和所有选项记录在随包发布的 `lib/types/index.d.ts` 类型声明中。字体目录使用所选操作系统的常规系统/用户路径。索引会跳过缺失或受保护的来源,并传播其他文件系统错误。`fontkit` 索引原始字体文件并选择已安装的字面和字形覆盖;它不重写字体。每次操作都会重新发现字体候选并验证缓存中的文件身份。一次操作使用一份有序元数据快照;快照变化后字体匹配条目失效。检测到转换期间字体变化时,操作会失败并删除其输出。原始字体字节和解码后的字形覆盖都只在本次转换内有效。精确的 family 匹配优先于 `fontFallbacks`。`missingFonts` 包含可读文档 XML 中声明但缺失的 family,不包含无关的引擎默认值。未命名缺失 family 的缺字并不构成完整的文档可访问性报告。
|
|
57
|
+
|
|
58
|
+
### 字体元数据缓存
|
|
59
|
+
|
|
60
|
+
`createConverter()` 和 `createConverterFactory()` 均接受:
|
|
61
|
+
|
|
62
|
+
| 选项 | 默认值 | 行为 |
|
|
63
|
+
| --- | --- | --- |
|
|
64
|
+
| `fontMetadataCacheDirectory` | 用户系统缓存目录 | 目录的绝对路径,或用 `false` 关闭磁盘缓存。 |
|
|
65
|
+
| `maxFontMetadataCacheBytes` | 32 MiB | 正安全整数,限制单个缓存文件的读取、写入及每份共享配置保留的逐文件元数据。 |
|
|
66
|
+
|
|
67
|
+
macOS 默认使用 `~/Library/Caches/libreoffice-kit`,Windows 使用 `%LOCALAPPDATA%/libreoffice-kit/Cache`(缺省时回退到用户的 `AppData/Local`),Linux 使用 `$XDG_CACHE_HOME/libreoffice-kit`(缺省时回退到 `~/.cache`)。单个 `font-metadata.json` 文件保存规范文件路径、设备/inode、大小、修改/变更时间及全部 face 元数据,包括解析结果为空的记录。它不保存字体字节、字形覆盖、解析对象、文档文本或文档匹配条目。请将此用户级文件保持私有。
|
|
68
|
+
|
|
69
|
+
没有可复用元数据的首次运行仍执行原来的完整字体 inspect。后续进程只跳过已发现且文件身份完全匹配的字体。每次操作重新枚举来源,包括 Office 补充字体,因此新增、删除、替换和目录变化无需重启。候选顺序、文件预算、Office 过滤、fallback 匹配、字形查询和原字体导入保持原有行为。缓存损坏、版本不兼容、超限或不可访问时回退到字体源计算;不可读的源字体不会复用旧记录。缓存格式、提取逻辑和固定的 fontkit 版本均须匹配。
|
|
70
|
+
|
|
71
|
+
新建缓存目录和文件使用私有权限(平台支持时为 `0700`/`0600`)。写入先在同目录独占创建临时文件,关闭后原子替换。未变化的快照不重写;超过字节上限的快照不保留、不写入。独立进程可以竞争发布完整快照,只影响命中率。元数据 Worker 退出后,所属操作清理自己创建的临时文件。
|
|
72
|
+
|
|
73
|
+
同一共享配置内同时开始的操作共享短生命周期元数据 Worker。每个等待者保留自己的取消和截止时间;取消一个不会取消其他等待者。最后一个等待者退出时终止并等待 Worker。扫描完成后只保留有界元数据,不保留扫描 Worker 或原始字体 Buffer。`fontMetadataCacheDirectory: false` 仍保留进程内共享与源字体版本检查。factory 缓存有独立生命周期,由 `factory.dispose()` 清理。
|
|
57
74
|
|
|
58
75
|
macOS 或 Windows 上省略 `fontDirectories` 时,默认发现还会检查 Microsoft Office 的捆绑/私有字体目录和用户 Office 字体缓存。只补充常规系统目录中不存在的精选 Office 兼容字体族,包括宋体和微软雅黑。显式 `fontDirectories` 会关闭这项补充发现。
|
|
59
76
|
|
|
@@ -78,4 +95,4 @@ Node WASM 的图像降采样使用 LibreOffice 的 CPU 图像过滤器。文本
|
|
|
78
95
|
- 字体导入和输出限制不能约束全部原生内存或临时磁盘使用。原生平台引擎的字体解析可能与 WASM 不同。
|
|
79
96
|
- npm 安装使用按平台选择的可选包。自行打包引擎的应用需要保留所选包的完整内容,包括资源和许可声明。
|
|
80
97
|
- Windows 需要系统安装与 Node.js 架构一致的 Microsoft Visual C++ v14 Redistributable(x64 或 ARM64);包中不捆绑该运行库。Windows ARM64 引擎需要使用 ARM64 Node.js。
|
|
81
|
-
- `0.0.
|
|
98
|
+
- `0.0.4` 提供 macOS 和 Windows 的 ARM64、x64 原生引擎,以及供 Linux 使用的共享 Node WASM 引擎;其他原生平台仅保留开发构建配方。
|
package/lib/cli.js
CHANGED
|
@@ -3,11 +3,11 @@ 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
5
|
import { constants, lstatSync, readdirSync } from "node:fs";
|
|
6
|
-
import { mkdir, mkdtemp, open, readFile, rm, stat, unlink, writeFile } from "node:fs/promises";
|
|
6
|
+
import { lstat, mkdir, mkdtemp, open, readFile, rm, stat, unlink, writeFile } from "node:fs/promises";
|
|
7
7
|
import { homedir, tmpdir } from "node:os";
|
|
8
8
|
import { Worker } from "node:worker_threads";
|
|
9
9
|
import { spawn } from "node:child_process";
|
|
10
|
-
import { createHash } from "node:crypto";
|
|
10
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
11
11
|
import { createInterface } from "node:readline";
|
|
12
12
|
import { zlibSync } from "fflate";
|
|
13
13
|
import "fontkit";
|
|
@@ -1014,6 +1014,14 @@ function mobileAssetFontDirectories(assets) {
|
|
|
1014
1014
|
return entries.filter((name) => /^com_apple_MobileAsset_Font\d*$/.test(name)).sort().map((name) => join(assets, name));
|
|
1015
1015
|
}
|
|
1016
1016
|
//#endregion
|
|
1017
|
+
//#region lib/types/font-metadata-cache.js
|
|
1018
|
+
/** Resolve the platform's user-local cache, independently of font discovery. */
|
|
1019
|
+
function defaultFontMetadataCacheDirectory(platform = process.platform, home = homedir(), env = process.env) {
|
|
1020
|
+
if (platform === "darwin") return posix.join(home, "Library/Caches/libreoffice-kit");
|
|
1021
|
+
if (platform === "win32") return win32.join(env.LOCALAPPDATA ?? win32.join(home, "AppData/Local"), "libreoffice-kit/Cache");
|
|
1022
|
+
return posix.join(env.XDG_CACHE_HOME && posix.isAbsolute(env.XDG_CACHE_HOME) ? env.XDG_CACHE_HOME : posix.join(home, ".cache"), "libreoffice-kit");
|
|
1023
|
+
}
|
|
1024
|
+
//#endregion
|
|
1017
1025
|
//#region lib/types/options.js
|
|
1018
1026
|
const SANS_CJK_FAMILIES = [
|
|
1019
1027
|
"Microsoft YaHei",
|
|
@@ -1138,7 +1146,8 @@ const DEFAULT_LIMITS = {
|
|
|
1138
1146
|
maxFontFiles: 2e4,
|
|
1139
1147
|
maxFontFileBytes: 268435456,
|
|
1140
1148
|
maxLoadedFontBytes: 536870912,
|
|
1141
|
-
maxFontResolutionEntries: 4096
|
|
1149
|
+
maxFontResolutionEntries: 4096,
|
|
1150
|
+
maxFontMetadataCacheBytes: 33554432
|
|
1142
1151
|
};
|
|
1143
1152
|
const FONT_COLLECTION_NAMES = ["fontDirectories", "initialFontFamilies"];
|
|
1144
1153
|
function positiveSafeInteger(value, name) {
|
|
@@ -1176,8 +1185,12 @@ function resolveOptions(input = {}) {
|
|
|
1176
1185
|
initialFontFamilies: [],
|
|
1177
1186
|
...input
|
|
1178
1187
|
};
|
|
1179
|
-
for (const key of Object.keys(input)) if (!(key in DEFAULT_LIMITS) && !FONT_COLLECTION_NAMES.includes(key) && key !== "fontFallbacks") throw new TypeError(`Unknown converter option: ${key}`);
|
|
1188
|
+
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}`);
|
|
1189
|
+
const cacheDirectory = input.fontMetadataCacheDirectory === void 0 ? defaultFontMetadataCacheDirectory() : input.fontMetadataCacheDirectory;
|
|
1190
|
+
if (cacheDirectory !== false && (typeof cacheDirectory !== "string" || !isAbsolute(cacheDirectory) || cacheDirectory.includes("\0"))) throw new TypeError("fontMetadataCacheDirectory must be an absolute path or false.");
|
|
1180
1191
|
return {
|
|
1192
|
+
fontMetadataCacheDirectory: cacheDirectory,
|
|
1193
|
+
maxFontMetadataCacheBytes: positiveSafeInteger(merged.maxFontMetadataCacheBytes, "maxFontMetadataCacheBytes"),
|
|
1181
1194
|
timeoutMs: positiveSafeInteger(merged.timeoutMs, "timeoutMs"),
|
|
1182
1195
|
maxInputBytes: positiveSafeInteger(merged.maxInputBytes, "maxInputBytes"),
|
|
1183
1196
|
maxOutputBytes: positiveSafeInteger(merged.maxOutputBytes, "maxOutputBytes"),
|
|
@@ -1202,7 +1215,7 @@ const require = createRequire(import.meta.url);
|
|
|
1202
1215
|
* Engine-family version every installed engine package must carry. The engine
|
|
1203
1216
|
* family shares its release version with this Node API.
|
|
1204
1217
|
*/
|
|
1205
|
-
const ENGINE_VERSION = "0.0.
|
|
1218
|
+
const ENGINE_VERSION = "0.0.4";
|
|
1206
1219
|
/** npm scope and name prefix shared by the engine packages this adapter installs. */
|
|
1207
1220
|
const ENGINE_PREFIX = "@deepseek-ai/libreoffice-kit";
|
|
1208
1221
|
/**
|
|
@@ -1281,7 +1294,7 @@ async function readEngine(packageFile, backend, target) {
|
|
|
1281
1294
|
const root = dirname(packageFile);
|
|
1282
1295
|
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))]);
|
|
1283
1296
|
const engine = manifest.engine;
|
|
1284
|
-
if (pkg.name !== `${ENGINE_PREFIX}-${target}` || pkg.version !== "0.0.
|
|
1297
|
+
if (pkg.name !== `${ENGINE_PREFIX}-${target}` || pkg.version !== "0.0.4" || 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.`);
|
|
1285
1298
|
const minimum = engine.glibcMinimum;
|
|
1286
1299
|
if (minimum !== void 0 && (!target.endsWith("-glibc") || !glibcVersion(minimum))) throw new Error("Installed LibreOfficeKit engine has an invalid glibcMinimum.");
|
|
1287
1300
|
const glibcFloor = minimum === void 0 ? {} : { glibcMinimum: minimum };
|
|
@@ -1416,6 +1429,111 @@ async function discoverRuntime() {
|
|
|
1416
1429
|
}
|
|
1417
1430
|
}
|
|
1418
1431
|
//#endregion
|
|
1432
|
+
//#region lib/types/font-snapshot-state.js
|
|
1433
|
+
/** Shared in-flight metadata work with independent cancellation and joined Worker cleanup. */
|
|
1434
|
+
/** Run one scan outside the event loop and join it before returning or cleaning its temporary file. */
|
|
1435
|
+
async function runFontSnapshot(options, previous, signal) {
|
|
1436
|
+
signal.throwIfAborted();
|
|
1437
|
+
const temporaryPath = options.fontMetadataCacheDirectory === false ? void 0 : join(options.fontMetadataCacheDirectory, `.font-metadata-${randomUUID()}.tmp`);
|
|
1438
|
+
const data = {
|
|
1439
|
+
options,
|
|
1440
|
+
previous,
|
|
1441
|
+
...temporaryPath === void 0 ? {} : { temporaryPath }
|
|
1442
|
+
};
|
|
1443
|
+
const worker = new Worker(new URL("./font-snapshot-worker.js", import.meta.url), {
|
|
1444
|
+
workerData: data,
|
|
1445
|
+
execArgv: [],
|
|
1446
|
+
name: "libreoffice-font-metadata",
|
|
1447
|
+
stdout: true,
|
|
1448
|
+
stderr: true
|
|
1449
|
+
});
|
|
1450
|
+
worker.stdout.resume();
|
|
1451
|
+
worker.stderr.resume();
|
|
1452
|
+
const result = Promise.withResolvers();
|
|
1453
|
+
const abort = () => result.reject(signal.reason);
|
|
1454
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
1455
|
+
worker.once("error", result.reject);
|
|
1456
|
+
worker.once("exit", (code) => result.reject(new ConversionError("failed", `Font metadata worker exited before returning a snapshot (${code}).`)));
|
|
1457
|
+
worker.once("message", (message) => {
|
|
1458
|
+
if (message.ok) result.resolve(message.snapshot);
|
|
1459
|
+
else result.reject(new ConversionError(failureCode(message), message.error));
|
|
1460
|
+
});
|
|
1461
|
+
try {
|
|
1462
|
+
return await result.promise;
|
|
1463
|
+
} finally {
|
|
1464
|
+
signal.removeEventListener("abort", abort);
|
|
1465
|
+
await worker.terminate();
|
|
1466
|
+
if (temporaryPath !== void 0) try {
|
|
1467
|
+
await rm(temporaryPath, { force: true });
|
|
1468
|
+
} catch {}
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
/** Each acquisition refreshes inventory; overlapping acquisitions share only the active scan. */
|
|
1472
|
+
var FontSnapshotState = class {
|
|
1473
|
+
previous = [];
|
|
1474
|
+
scan;
|
|
1475
|
+
/** Revalidate files for an operation without coupling its cancellation to other waiters. */
|
|
1476
|
+
async acquire(options, signal) {
|
|
1477
|
+
signal.throwIfAborted();
|
|
1478
|
+
while (this.scan?.controller.signal.aborted) {
|
|
1479
|
+
await this.scan.promise.catch(() => {});
|
|
1480
|
+
signal.throwIfAborted();
|
|
1481
|
+
}
|
|
1482
|
+
if (this.scan === void 0) {
|
|
1483
|
+
const controller = new AbortController();
|
|
1484
|
+
const promise = runFontSnapshot(options, this.previous, controller.signal).then((snapshot) => {
|
|
1485
|
+
this.previous = Buffer.byteLength(JSON.stringify(snapshot.records)) <= options.maxFontMetadataCacheBytes ? snapshot.records : [];
|
|
1486
|
+
return snapshot;
|
|
1487
|
+
}).finally(() => {
|
|
1488
|
+
this.scan = void 0;
|
|
1489
|
+
});
|
|
1490
|
+
this.scan = {
|
|
1491
|
+
controller,
|
|
1492
|
+
promise,
|
|
1493
|
+
waiters: 0
|
|
1494
|
+
};
|
|
1495
|
+
}
|
|
1496
|
+
const scan = this.scan;
|
|
1497
|
+
scan.waiters++;
|
|
1498
|
+
const cancelled = Promise.withResolvers();
|
|
1499
|
+
const abort = () => cancelled.reject(signal.reason);
|
|
1500
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
1501
|
+
try {
|
|
1502
|
+
return await Promise.race([scan.promise, cancelled.promise]);
|
|
1503
|
+
} finally {
|
|
1504
|
+
signal.removeEventListener("abort", abort);
|
|
1505
|
+
scan.waiters--;
|
|
1506
|
+
if (scan.waiters === 0 && this.scan === scan) {
|
|
1507
|
+
scan.controller.abort(/* @__PURE__ */ new Error("All font scan waiters stopped."));
|
|
1508
|
+
await scan.promise.catch(() => {});
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
/** Release completed metadata after the owning factory has joined its operations. */
|
|
1513
|
+
clear() {
|
|
1514
|
+
this.previous = [];
|
|
1515
|
+
}
|
|
1516
|
+
};
|
|
1517
|
+
//#endregion
|
|
1518
|
+
//#region lib/types/font-snapshot-validation.js
|
|
1519
|
+
/** Verify the operation's source versions before publishing its output. */
|
|
1520
|
+
/** Reject changed, removed, or replaced sources without exposing local font paths. */
|
|
1521
|
+
async function validateFontSnapshot(snapshot) {
|
|
1522
|
+
await Promise.all(snapshot.records.map(async (record) => {
|
|
1523
|
+
try {
|
|
1524
|
+
const current = await lstat(record.path);
|
|
1525
|
+
if (current.isFile() && [
|
|
1526
|
+
"dev",
|
|
1527
|
+
"ino",
|
|
1528
|
+
"size",
|
|
1529
|
+
"mtimeMs",
|
|
1530
|
+
"ctimeMs"
|
|
1531
|
+
].every((key) => current[key] === record[key])) return;
|
|
1532
|
+
} catch {}
|
|
1533
|
+
throw new ConversionError("failed", "A system font changed during conversion; retry the operation.");
|
|
1534
|
+
}));
|
|
1535
|
+
}
|
|
1536
|
+
//#endregion
|
|
1419
1537
|
//#region lib/types/index.js
|
|
1420
1538
|
/** Convert caller-authorized disk documents with installed native or Node WASM engines. */
|
|
1421
1539
|
/** File identity that must match across a bounded read. */
|
|
@@ -1446,7 +1564,7 @@ async function readBounded(path, limit, signal, role) {
|
|
|
1446
1564
|
await file.close();
|
|
1447
1565
|
}
|
|
1448
1566
|
}
|
|
1449
|
-
async function runWorker(data, signal,
|
|
1567
|
+
async function runWorker(data, signal, onFontCache) {
|
|
1450
1568
|
signal.throwIfAborted();
|
|
1451
1569
|
const worker = new Worker(new URL("./worker.js", import.meta.url), {
|
|
1452
1570
|
workerData: data,
|
|
@@ -1467,8 +1585,7 @@ async function runWorker(data, signal, onFonts, onFontCache) {
|
|
|
1467
1585
|
settled.reject(new ConversionError("failed", `LibreOffice worker exited before returning a result (${code}).`));
|
|
1468
1586
|
});
|
|
1469
1587
|
worker.on("message", (message) => {
|
|
1470
|
-
if (message.kind === "
|
|
1471
|
-
else if (message.kind === "font-cache") onFontCache(message.entries);
|
|
1588
|
+
if (message.kind === "font-cache") onFontCache(message.entries);
|
|
1472
1589
|
else if (message.ok) settled.resolve(message);
|
|
1473
1590
|
else settled.reject(new ConversionError(failureCode(message), message.error));
|
|
1474
1591
|
});
|
|
@@ -1491,7 +1608,9 @@ function sharedStateKey(options, engine) {
|
|
|
1491
1608
|
maxFontFiles: options.maxFontFiles,
|
|
1492
1609
|
maxFontFileBytes: options.maxFontFileBytes,
|
|
1493
1610
|
maxLoadedFontBytes: options.maxLoadedFontBytes,
|
|
1494
|
-
maxFontResolutionEntries: options.maxFontResolutionEntries
|
|
1611
|
+
maxFontResolutionEntries: options.maxFontResolutionEntries,
|
|
1612
|
+
fontMetadataCacheDirectory: options.fontMetadataCacheDirectory,
|
|
1613
|
+
maxFontMetadataCacheBytes: options.maxFontMetadataCacheBytes
|
|
1495
1614
|
});
|
|
1496
1615
|
}
|
|
1497
1616
|
function defaultSharedState(options, engine) {
|
|
@@ -1503,7 +1622,8 @@ function defaultSharedState(options, engine) {
|
|
|
1503
1622
|
return existing;
|
|
1504
1623
|
}
|
|
1505
1624
|
const state = {
|
|
1506
|
-
|
|
1625
|
+
snapshots: new FontSnapshotState(),
|
|
1626
|
+
generation: void 0,
|
|
1507
1627
|
fontCache: /* @__PURE__ */ new Map()
|
|
1508
1628
|
};
|
|
1509
1629
|
defaultSharedStates.set(key, state);
|
|
@@ -1529,7 +1649,8 @@ function createConverterWith(resolvedOptions, engine, shared, onDispose) {
|
|
|
1529
1649
|
const waiting = /* @__PURE__ */ new Set();
|
|
1530
1650
|
let running = false;
|
|
1531
1651
|
let disposal;
|
|
1532
|
-
const mergeCache = (entries) => {
|
|
1652
|
+
const mergeCache = (generation, entries) => {
|
|
1653
|
+
if (shared.generation !== generation) return;
|
|
1533
1654
|
for (const entry of entries) {
|
|
1534
1655
|
const prior = shared.fontCache.get(entry.key);
|
|
1535
1656
|
const faces = new Map((prior?.faces ?? []).map((face) => [`${face.path}\0${face.faceIndex}`, face]));
|
|
@@ -1546,6 +1667,14 @@ function createConverterWith(resolvedOptions, engine, shared, onDispose) {
|
|
|
1546
1667
|
}
|
|
1547
1668
|
while (shared.fontCache.size > resolvedOptions.maxFontResolutionEntries) shared.fontCache.delete(shared.fontCache.keys().next().value);
|
|
1548
1669
|
};
|
|
1670
|
+
async function snapshot(signal) {
|
|
1671
|
+
const current = await shared.snapshots.acquire(resolvedOptions, signal);
|
|
1672
|
+
if (shared.generation !== current.generation) {
|
|
1673
|
+
shared.generation = current.generation;
|
|
1674
|
+
shared.fontCache.clear();
|
|
1675
|
+
}
|
|
1676
|
+
return current;
|
|
1677
|
+
}
|
|
1549
1678
|
async function acquire(signal) {
|
|
1550
1679
|
while (running) {
|
|
1551
1680
|
signal.throwIfAborted();
|
|
@@ -1593,6 +1722,7 @@ function createConverterWith(resolvedOptions, engine, shared, onDispose) {
|
|
|
1593
1722
|
} finally {
|
|
1594
1723
|
await input.close();
|
|
1595
1724
|
}
|
|
1725
|
+
const fonts = await snapshot(stopped);
|
|
1596
1726
|
const result = await runWorker({
|
|
1597
1727
|
inputPath,
|
|
1598
1728
|
extension,
|
|
@@ -1600,11 +1730,9 @@ function createConverterWith(resolvedOptions, engine, shared, onDispose) {
|
|
|
1600
1730
|
options: resolvedOptions,
|
|
1601
1731
|
engine,
|
|
1602
1732
|
scratch,
|
|
1603
|
-
fontFaces:
|
|
1733
|
+
fontFaces: fonts.faces,
|
|
1604
1734
|
fontCache: [...shared.fontCache.values()]
|
|
1605
|
-
}, stopped, (
|
|
1606
|
-
shared.fontFaces ??= faces;
|
|
1607
|
-
}, mergeCache);
|
|
1735
|
+
}, stopped, (entries) => mergeCache(fonts.generation, entries));
|
|
1608
1736
|
if ("images" in result) throw new ConversionError("failed", "Conversion worker returned an image batch for an export request.");
|
|
1609
1737
|
let bytes;
|
|
1610
1738
|
if ("output" in result) bytes = result.output;
|
|
@@ -1617,6 +1745,7 @@ function createConverterWith(resolvedOptions, engine, shared, onDispose) {
|
|
|
1617
1745
|
bytes = await readBounded(path, resolvedOptions.maxOutputBytes, stopped, "output");
|
|
1618
1746
|
}
|
|
1619
1747
|
validateOutput(bytes, format);
|
|
1748
|
+
await validateFontSnapshot(fonts);
|
|
1620
1749
|
stopped.throwIfAborted();
|
|
1621
1750
|
await output.writeFile(bytes);
|
|
1622
1751
|
stopped.throwIfAborted();
|
|
@@ -1668,6 +1797,7 @@ function createConverterWith(resolvedOptions, engine, shared, onDispose) {
|
|
|
1668
1797
|
flag: "wx",
|
|
1669
1798
|
mode: 384
|
|
1670
1799
|
});
|
|
1800
|
+
const fonts = await snapshot(stopped);
|
|
1671
1801
|
const result = await runWorker({
|
|
1672
1802
|
inputPath,
|
|
1673
1803
|
extension: request.extension,
|
|
@@ -1675,11 +1805,9 @@ function createConverterWith(resolvedOptions, engine, shared, onDispose) {
|
|
|
1675
1805
|
options: resolvedOptions,
|
|
1676
1806
|
engine,
|
|
1677
1807
|
scratch,
|
|
1678
|
-
fontFaces:
|
|
1808
|
+
fontFaces: fonts.faces,
|
|
1679
1809
|
fontCache: [...shared.fontCache.values()]
|
|
1680
|
-
}, stopped, (
|
|
1681
|
-
shared.fontFaces ??= faces;
|
|
1682
|
-
}, mergeCache);
|
|
1810
|
+
}, stopped, (entries) => mergeCache(fonts.generation, entries));
|
|
1683
1811
|
let images;
|
|
1684
1812
|
if ("images" in result) images = result.images;
|
|
1685
1813
|
else if ("fonts" in result) {
|
|
@@ -1698,6 +1826,7 @@ function createConverterWith(resolvedOptions, engine, shared, onDispose) {
|
|
|
1698
1826
|
signal: stopped
|
|
1699
1827
|
});
|
|
1700
1828
|
} else throw new ConversionError("failed", "Image worker did not return its manifest.");
|
|
1829
|
+
await validateFontSnapshot(fonts);
|
|
1701
1830
|
stopped.throwIfAborted();
|
|
1702
1831
|
await writeFile(join(request.outputDir, "manifest.json"), `${JSON.stringify(images, null, 2)}\n`, {
|
|
1703
1832
|
flag: "wx",
|