@deepseek-ai/libreoffice-kit 0.0.2-rc6 → 0.0.2-rc8

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 CHANGED
@@ -52,7 +52,7 @@ CLI paths resolve against its working directory. Success writes one JSON object
52
52
 
53
53
  Node operations and the Host font service use bounded system-font discovery. Exact installed families and explicit aliases precede Unicode-script and regional body-text preferences, then other glyph-covering fonts. Windows preferences derive from pinned Chromium data; macOS/Linux use Fontconfig categories, with the other source supplying additional candidates. Unicode 17 Script/Script_Extensions data keeps mixed text independent of incorrectly declared document languages. Only unlisted Latin/CJK decorative faces are demoted; cursive writing traditions such as Urdu Nastaliq remain normal body fonts. No fonts are downloaded or bundled by these rules. Full original files retain shaping and encoding. Recreate the converter after changing installed fonts. `missingFonts` reports unavailable declared OOXML families; font-service `unresolvedCodePoints` separately reports scalars no installed face covers. The rule data and licenses are regenerated with `node scripts/generate-font-preferences.mjs` and retained in `NOTICE`.
54
54
 
55
- `createFontSource` from `@deepseek-ai/libreoffice-kit/fonts` provides an independent lazy Worker service. `resolve(attributes)` retains the Unicode-script subset behavior for interactive Office. `resolve({...attributes, mode:'full'})` returns opaque `full_…` identities, original family names and `format` (`ttf`, `otf`, `ttc`); `read(id)` returns complete original font bytes. Apple dfont resources are extracted as complete sfnt faces. Reads reject unknown or changed sources and do not expose host paths.
55
+ `createFontSource` from `@deepseek-ai/libreoffice-kit/fonts` provides an independent Worker service. `prepare()` builds its lifetime font snapshot before the first document request. Default discovery supplements normal system roots with a small compatibility set from an installed Microsoft Office on macOS or Windows; explicit `fontDirectories` replace all defaults. No font bytes or Host paths enter the package. `resolve(attributes)` retains the Unicode-script subset behavior for interactive Office. `resolve({...attributes, mode:'full'})` returns opaque `full_…` identities, original family names and `format` (`ttf`, `otf`, `ttc`); `read(id)` returns complete original font bytes. Apple dfont resources are extracted as complete sfnt faces. Reads reject unknown or changed sources and do not expose host paths.
56
56
 
57
57
  Full-mode selections from the same unchanged TTC share one file read and retained byte entry while keeping each selected family's name and alias. The existing cache budget counts unique full assets once; eviction may require a later read to regenerate them. Subsets and dfont resources remain specific to each physical face.
58
58
 
@@ -39,8 +39,8 @@
39
39
  "sha256": "aa5368e0dd38d90459f0ef14e1d4b27740aef2f4e46617aca6d6fafed0577a44"
40
40
  },
41
41
  "sources/font-subset/scripts/verify-artifacts.mjs": {
42
- "bytes": 16017,
43
- "sha256": "b69af5760f7ebfedece94f198dba765def2fd840a4d46bdb8c8b7729fb4884ea"
42
+ "bytes": 16020,
43
+ "sha256": "bc3103bdeedc64c80487e7daf096a03e3b8c180e0b4fdc8986e987fb823a6d82"
44
44
  },
45
45
  "sources/font-subset/engine/font-subset/README.md": {
46
46
  "bytes": 2130,
@@ -3,8 +3,8 @@
3
3
  "files": {
4
4
  "worker": {
5
5
  "path": "lib/browser/worker.js",
6
- "bytes": 116577,
7
- "sha256": "81237217e64c708763b3e8c2128ed29c1d589ddd4753008c761396d69449eb43"
6
+ "bytes": 120352,
7
+ "sha256": "f74836c2d512f9f9da3fc5d8ff29296932ed25f3e4af918a1595f22eb6a84e89"
8
8
  }
9
9
  }
10
10
  }
@@ -26,13 +26,15 @@ function* fontFrames(result, known = []) {
26
26
  const identities = new Map(known.map((font) => [font.id, font]));
27
27
  const header = {
28
28
  fonts: result.fonts.map((font) => {
29
+ const size = font.data === void 0 ? font.bytes : font.data.byteLength;
29
30
  const identity = {
30
31
  id: font.id,
31
- bytes: font.data.byteLength,
32
+ bytes: size,
32
33
  ...font.format ? { format: font.format } : {}
33
34
  };
34
35
  const prior = identities.get(font.id);
35
36
  if (prior && (prior.bytes !== identity.bytes || prior.format !== identity.format)) throw new BrowserRenderError("font-unavailable", "Font identity has conflicting bytes or formats.");
37
+ if (!prior && font.data === void 0) throw new BrowserRenderError("font-unavailable", "Font reference has not been installed.");
36
38
  identities.set(font.id, identity);
37
39
  return {
38
40
  ...identity,
@@ -51,6 +53,8 @@ function* fontFrames(result, known = []) {
51
53
  };
52
54
  for (const [index, font] of result.fonts.entries()) {
53
55
  if (header.fonts[index].reference) continue;
56
+ /* v8 ignore next -- header validation rejects an unknown data-less font before iteration. */
57
+ if (font.data === void 0) throw new BrowserRenderError("font-unavailable", "Font reference has not been installed.");
54
58
  for (let offset = 0; offset < font.data.byteLength; offset += FONT_CHUNK_BYTES) yield {
55
59
  state: 2,
56
60
  bytes: font.data.subarray(offset, offset + FONT_CHUNK_BYTES)
@@ -62,6 +66,36 @@ function* fontFrames(result, known = []) {
62
66
  };
63
67
  }
64
68
  //#endregion
69
+ //#region lib/types/preparation.js
70
+ /** Browser-side WASM compilation without creating an Office Worker or memory. */
71
+ /**
72
+ * Compile the version-matched LibreOffice WASM module for later document Workers.
73
+ * @param assets - Browser resources whose WASM URL identifies the compiled module.
74
+ * @param signal - Cancels the resource request; compilation may finish before cancellation is observed.
75
+ * @returns an opaque, structured-cloneable engine handle that allocates no WASM memory.
76
+ */
77
+ async function prepareOfficeBrowser(assets, signal) {
78
+ signal?.throwIfAborted();
79
+ if (typeof WebAssembly.compileStreaming !== "function") throw new BrowserRenderError("unavailable", "Streaming WebAssembly compilation is unavailable.");
80
+ const response = await fetch(assets.wasmUrl, {
81
+ credentials: "same-origin",
82
+ ...signal === void 0 ? {} : { signal }
83
+ });
84
+ if (!response.ok) throw new BrowserRenderError("unavailable", `LibreOffice WASM request failed: ${response.status}`);
85
+ const module = await WebAssembly.compileStreaming(Promise.resolve(response));
86
+ signal?.throwIfAborted();
87
+ return Object.freeze({
88
+ wasmUrl: assets.wasmUrl,
89
+ module
90
+ });
91
+ }
92
+ /** Return the compiled module after validating the Worker-bound asset identity. */
93
+ function preparedBrowserModule(prepared, assets) {
94
+ const record = prepared;
95
+ if (record.wasmUrl !== assets.wasmUrl || !(record.module instanceof WebAssembly.Module)) throw new TypeError("The prepared browser engine does not match the requested WASM asset.");
96
+ return record.module;
97
+ }
98
+ //#endregion
65
99
  //#region lib/types/connection.js
66
100
  /** Browser document ownership, cancellation and asynchronous Host font delivery. */
67
101
  /**
@@ -87,6 +121,7 @@ async function openBrowserConnection(options, signal, office = false, onEvent) {
87
121
  "ppt",
88
122
  "pptx"
89
123
  ] : ["pdf"]).includes(options.extension) || options.data.byteLength === 0) throw new BrowserRenderError("invalid-document", "The document is empty or has an unsupported extension.");
124
+ if (options.preparedEngine !== void 0) preparedBrowserModule(options.preparedEngine, options.assets);
90
125
  const worker = new Worker(options.assets.workerUrl, { name: "libreoffice-document" });
91
126
  const channel = new SharedArrayBuffer(1048584);
92
127
  const { control, bytes } = fontViews(channel);
@@ -137,7 +172,7 @@ async function openBrowserConnection(options, signal, office = false, onEvent) {
137
172
  return;
138
173
  case "font":
139
174
  if (closed) return;
140
- Promise.resolve().then(() => options.resolveFonts(message.request, lifetime.signal)).then((result) => {
175
+ Promise.resolve().then(() => options.resolveFonts(message.request, message.known, lifetime.signal)).then((result) => {
141
176
  if (closed) return;
142
177
  frames = fontFrames(result, message.known);
143
178
  pumpFonts();
@@ -252,6 +287,7 @@ async function openBrowserConnection(options, signal, office = false, onEvent) {
252
287
  data,
253
288
  extension: options.extension,
254
289
  assets: options.assets,
290
+ ...options.preparedEngine === void 0 ? {} : { preparedEngine: options.preparedEngine },
255
291
  timeoutMs: options.timeoutMs,
256
292
  maxLoadedFontBytes: options.maxLoadedFontBytes,
257
293
  fontFallbacks: options.fontFallbacks,
@@ -452,4 +488,4 @@ async function openDocument(options, signal) {
452
488
  };
453
489
  }
454
490
  //#endregion
455
- export { BrowserRenderError, openDocument, openOfficeDocument };
491
+ export { BrowserRenderError, openDocument, openOfficeDocument, prepareOfficeBrowser };
@@ -17,5 +17,5 @@ export interface EngineFontFace {
17
17
  readonly family: string;
18
18
  }
19
19
  /** The synchronous reader installs immutable font assets before returning their MEMFS paths and aliases. */
20
- export declare function createFontReader(channel: SharedArrayBuffer, timeoutMs: number, maxLoadedFontBytes: number, declaredFamilies: ReadonlyMap<string, string>, request: (request: BrowserFontRequest, known: readonly FontIdentity[]) => void, next: () => void, install: (path: string, bytes: Uint8Array) => void, missing: (families: readonly string[]) => void): (request: BrowserFontRequest) => EngineFontFace[];
20
+ export declare function createFontReader(channel: SharedArrayBuffer, timeoutMs: number, maxLoadedFontBytes: number, declaredFamilies: ReadonlyMap<string, string>, request: (request: BrowserFontRequest, known: readonly FontIdentity[]) => void, next: () => void, install: (path: string, bytes: Uint8Array) => void, missing: (families: readonly string[]) => void, documentCodePoints?: readonly number[]): (request: BrowserFontRequest) => EngineFontFace[];
21
21
  //# sourceMappingURL=font-channel.d.ts.map
@@ -1,8 +1,9 @@
1
1
  import type { BrowserDocument, BrowserDocumentOptions } from './types.ts';
2
2
  export { BrowserRenderError } from './types.ts';
3
3
  export { openOfficeDocument } from './office.ts';
4
+ export { prepareOfficeBrowser } from './preparation.ts';
4
5
  export type * from './office-types.ts';
5
- export type { BrowserDocument, BrowserDocumentOptions, BrowserEngineAssets, BrowserFontRequest, BrowserFontResult, BrowserPage, BrowserRenderErrorCode, BrowserTile, BrowserTileRequest } from './types.ts';
6
+ export type { BrowserDocument, BrowserDocumentOptions, BrowserEngineAssets, BrowserFontIdentity, BrowserFontRequest, BrowserFontResult, BrowserPage, BrowserRenderErrorCode, BrowserResolvedFont, BrowserTile, BrowserTileRequest, PreparedBrowserEngine } from './types.ts';
6
7
  /**
7
8
  * Open a read-only document; each call owns an independent Worker.
8
9
  * @param options - Source bytes, version-matched resources and Host fonts.
@@ -0,0 +1,13 @@
1
+ import type { BrowserEngineAssets, PreparedBrowserEngine } from './types.ts';
2
+ /**
3
+ * Compile the version-matched LibreOffice WASM module for later document Workers.
4
+ * @param assets - Browser resources whose WASM URL identifies the compiled module.
5
+ * @param signal - Cancels the resource request; compilation may finish before cancellation is observed.
6
+ * @returns an opaque, structured-cloneable engine handle that allocates no WASM memory.
7
+ */
8
+ export declare function prepareOfficeBrowser(assets: BrowserEngineAssets, signal?: AbortSignal): Promise<PreparedBrowserEngine>;
9
+ /** Return the compiled module after validating the Worker-bound asset identity. */
10
+ export declare function preparedBrowserModule(prepared: PreparedBrowserEngine, assets: BrowserEngineAssets): WebAssembly.Module;
11
+ /** Instantiate precompiled code through Emscripten's synchronous override. */
12
+ export declare function instantiatePreparedModule(module: WebAssembly.Module, imports: WebAssembly.Imports, receive: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void): WebAssembly.Exports;
13
+ //# sourceMappingURL=preparation.d.ts.map
@@ -1,5 +1,5 @@
1
1
  /** Private messages exchanged by the document owner and its single engine Worker. */
2
- import type { BrowserDocumentOptions, BrowserFontRequest, BrowserPage, BrowserRenderErrorCode, BrowserTile, BrowserTileRequest } from './types.ts';
2
+ import type { BrowserDocumentOptions, BrowserFontIdentity, BrowserFontRequest, BrowserPage, BrowserRenderErrorCode, BrowserTile, BrowserTileRequest } from './types.ts';
3
3
  import type { OfficeDocumentEvent, OfficeDocumentNavigation, OfficeDocumentOptions, OfficeDocumentState, OfficeDocumentPointer, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult, OfficeDocumentTileRequest, OfficeDocumentRectangle } from './office-types.ts';
4
4
  export declare const FONT_CHUNK_BYTES: number;
5
5
  export declare const FONT_HEADER_BYTES = 8;
@@ -97,11 +97,7 @@ export type WorkerMessage = {
97
97
  readonly families: readonly string[];
98
98
  };
99
99
  /** Immutable bytes already installed in this document's MEMFS. */
100
- export interface FontIdentity {
101
- readonly id: string;
102
- readonly bytes: number;
103
- readonly format?: 'ttf' | 'otf' | 'ttc';
104
- }
100
+ export type FontIdentity = BrowserFontIdentity;
105
101
  export interface FontHeader {
106
102
  readonly fonts: readonly (FontIdentity & {
107
103
  readonly family: string;
@@ -8,6 +8,11 @@ export interface BrowserEngineAssets {
8
8
  readonly metadataUrl: string;
9
9
  readonly programDirectory: string;
10
10
  }
11
+ declare const preparedBrowserEngine: unique symbol;
12
+ /** Compiled engine code bound to one WASM resource identity. */
13
+ export interface PreparedBrowserEngine {
14
+ readonly [preparedBrowserEngine]: true;
15
+ }
11
16
  /** VCL attributes passed unchanged to the Host's font matcher. */
12
17
  export interface BrowserFontRequest {
13
18
  readonly mode?: 'full';
@@ -20,15 +25,28 @@ export interface BrowserFontRequest {
20
25
  readonly language: string;
21
26
  readonly codePoints: readonly number[];
22
27
  }
28
+ /** Immutable font content already installed in one document Worker. */
29
+ export interface BrowserFontIdentity {
30
+ readonly id: string;
31
+ readonly bytes: number;
32
+ readonly format?: 'ttf' | 'otf' | 'ttc';
33
+ }
34
+ /** One new font body or a metadata-only reference to content already installed in the Worker. */
35
+ export type BrowserResolvedFont = {
36
+ readonly id: string;
37
+ readonly family: string;
38
+ readonly alias: string;
39
+ readonly format?: 'ttf' | 'otf' | 'ttc';
40
+ } & ({
41
+ readonly data: Uint8Array;
42
+ readonly bytes?: never;
43
+ } | {
44
+ readonly data?: never;
45
+ readonly bytes: number;
46
+ });
23
47
  /** Immutable per-face font subsets; equal ids and aliases must identify equal bytes. */
24
48
  export interface BrowserFontResult {
25
- readonly fonts: readonly {
26
- readonly id: string;
27
- readonly data: Uint8Array;
28
- readonly family: string;
29
- readonly alias: string;
30
- readonly format?: 'ttf' | 'otf' | 'ttc';
31
- }[];
49
+ readonly fonts: readonly BrowserResolvedFont[];
32
50
  readonly missingFamily?: string;
33
51
  /** Missing scalars reported by the Host, independently of a substituted family. */
34
52
  readonly unresolvedCodePoints?: readonly number[];
@@ -58,6 +76,8 @@ export interface BrowserDocumentOptions {
58
76
  readonly data: Uint8Array;
59
77
  readonly extension: 'pdf';
60
78
  readonly assets: BrowserEngineAssets;
79
+ /** Optional compiled WASM code created by prepareOfficeBrowser for these assets. */
80
+ readonly preparedEngine?: PreparedBrowserEngine;
61
81
  /** Maximum time for each load, render, font request, or teardown operation. */
62
82
  readonly timeoutMs: number;
63
83
  /** Maximum ZIP entries inspected before LibreOffice loads OOXML. */
@@ -69,7 +89,7 @@ export interface BrowserDocumentOptions {
69
89
  /** The same ordered substitution groups used by the Host font matcher. */
70
90
  readonly fontFallbacks: readonly (readonly string[])[];
71
91
  /** Match fonts without blocking the browser's main thread. */
72
- readonly resolveFonts: (request: BrowserFontRequest, signal: AbortSignal) => Promise<BrowserFontResult>;
92
+ readonly resolveFonts: (request: BrowserFontRequest, known: readonly BrowserFontIdentity[], signal: AbortSignal) => Promise<BrowserFontResult>;
73
93
  /** Called with unavailable declared OOXML families; binary DOC/PPT have no font diagnostics. */
74
94
  readonly onMissingFonts?: (families: readonly string[]) => void;
75
95
  }
@@ -89,4 +109,5 @@ export declare class BrowserRenderError extends Error {
89
109
  readonly code: BrowserRenderErrorCode;
90
110
  constructor(code: BrowserRenderErrorCode, message: string);
91
111
  }
112
+ export {};
92
113
  //# sourceMappingURL=types.d.ts.map
@@ -2457,12 +2457,39 @@ ${XMLNS_NAMESPACE}.`);
2457
2457
  bytes: new Uint8Array(channel, 8)
2458
2458
  };
2459
2459
  }
2460
+ const SCRIPT_GROUPS = [
2461
+ ["arabic", /\p{Script_Extensions=Arabic}/u],
2462
+ ["cyrillic", /\p{Script_Extensions=Cyrillic}/u],
2463
+ ["devanagari", /\p{Script_Extensions=Devanagari}/u],
2464
+ ["greek", /\p{Script_Extensions=Greek}/u],
2465
+ ["han", /\p{Script_Extensions=Han}/u],
2466
+ ["hangul", /\p{Script_Extensions=Hangul}/u],
2467
+ ["hebrew", /\p{Script_Extensions=Hebrew}/u],
2468
+ ["hiragana", /\p{Script_Extensions=Hiragana}/u],
2469
+ ["katakana", /\p{Script_Extensions=Katakana}/u],
2470
+ ["latin", /\p{Script_Extensions=Latin}/u],
2471
+ ["thai", /\p{Script_Extensions=Thai}/u],
2472
+ ["common", /[\p{Script=Common}\p{Script=Inherited}]/u]
2473
+ ];
2474
+ function scriptGroup(point) {
2475
+ const character = String.fromCodePoint(point);
2476
+ return SCRIPT_GROUPS.find(([, pattern]) => pattern.test(character))?.[0] ?? `other-${point >>> 8}`;
2477
+ }
2460
2478
  /** The synchronous reader installs immutable font assets before returning their MEMFS paths and aliases. */
2461
- function createFontReader(channel, timeoutMs, maxLoadedFontBytes, declaredFamilies, request, next, install, missing) {
2479
+ function createFontReader(channel, timeoutMs, maxLoadedFontBytes, declaredFamilies, request, next, install, missing, documentCodePoints = []) {
2462
2480
  const { control, bytes } = fontViews(channel);
2463
2481
  const installed = /* @__PURE__ */ new Map();
2464
2482
  const aliases = /* @__PURE__ */ new Map();
2465
2483
  const requests = /* @__PURE__ */ new Map();
2484
+ const coverage = /* @__PURE__ */ new Map();
2485
+ const expanded = /* @__PURE__ */ new Map();
2486
+ const documentGroups = /* @__PURE__ */ new Map();
2487
+ for (const point of [...new Set(documentCodePoints)].sort((left, right) => left - right)) {
2488
+ const group = scriptGroup(point);
2489
+ const points = documentGroups.get(group);
2490
+ if (points) points.push(point);
2491
+ else documentGroups.set(group, [point]);
2492
+ }
2466
2493
  const families = /* @__PURE__ */ new Set();
2467
2494
  let loadedBytes = 0;
2468
2495
  function read() {
@@ -2486,14 +2513,30 @@ ${XMLNS_NAMESPACE}.`);
2486
2513
  }
2487
2514
  return (attributes) => {
2488
2515
  const canonical = aliases.get(normalize(attributes.family))?.family;
2516
+ const codePoints = [...new Set(attributes.codePoints)].sort((left, right) => left - right);
2489
2517
  const original = {
2490
2518
  ...attributes,
2519
+ codePoints,
2491
2520
  ...canonical === void 0 ? {} : { family: canonical }
2492
2521
  };
2493
2522
  const key = JSON.stringify(original);
2494
2523
  const cached = requests.get(key);
2495
2524
  if (cached) return cached;
2496
- request(original, [...installed].map(([id, font]) => ({
2525
+ const { codePoints: _points, ...base } = original;
2526
+ const coverageKey = JSON.stringify(base);
2527
+ const covered = coverage.get(coverageKey);
2528
+ if (codePoints.length > 0 && covered && (covered.complete || codePoints.every((point) => covered.points.has(point)))) {
2529
+ requests.set(key, covered.faces);
2530
+ return covered.faces;
2531
+ }
2532
+ const groups = new Set(codePoints.map(scriptGroup));
2533
+ const expandedGroups = expanded.get(coverageKey);
2534
+ const newGroups = original.mode === "full" ? [] : [...groups].filter((group) => !expandedGroups?.has(group));
2535
+ const requestedPoints = newGroups.length === 0 ? codePoints : [.../* @__PURE__ */ new Set([...codePoints, ...newGroups.flatMap((group) => documentGroups.get(group) ?? [])])].sort((left, right) => left - right);
2536
+ request({
2537
+ ...original,
2538
+ codePoints: requestedPoints
2539
+ }, [...installed].map(([id, font]) => ({
2497
2540
  id,
2498
2541
  bytes: font.bytes,
2499
2542
  ...font.format ? { format: font.format } : {}
@@ -2557,10 +2600,36 @@ ${XMLNS_NAMESPACE}.`);
2557
2600
  missing([...families]);
2558
2601
  }
2559
2602
  requests.set(key, faces);
2603
+ if (newGroups.length > 0) expanded.set(coverageKey, /* @__PURE__ */ new Set([...expandedGroups ?? [], ...newGroups]));
2604
+ if (requestedPoints.length > 0) {
2605
+ const group = {
2606
+ points: new Set(covered?.points),
2607
+ faces: [...covered?.faces ?? []],
2608
+ complete: covered?.complete ?? false
2609
+ };
2610
+ for (const point of requestedPoints) group.points.add(point);
2611
+ for (const face of faces) if (!group.faces.some((existing) => existing.path === face.path && existing.family === face.family)) group.faces.push(face);
2612
+ group.complete ||= header.fonts.every((font) => font.format !== void 0);
2613
+ coverage.set(coverageKey, group);
2614
+ }
2560
2615
  return faces;
2561
2616
  };
2562
2617
  }
2563
2618
  //#endregion
2619
+ //#region lib/types/preparation.js
2620
+ /** Return the compiled module after validating the Worker-bound asset identity. */
2621
+ function preparedBrowserModule(prepared, assets) {
2622
+ const record = prepared;
2623
+ if (record.wasmUrl !== assets.wasmUrl || !(record.module instanceof WebAssembly.Module)) throw new TypeError("The prepared browser engine does not match the requested WASM asset.");
2624
+ return record.module;
2625
+ }
2626
+ /** Instantiate precompiled code through Emscripten's synchronous override. */
2627
+ function instantiatePreparedModule(module, imports, receive) {
2628
+ const instance = new WebAssembly.Instance(module, imports);
2629
+ receive(instance, module);
2630
+ return instance.exports;
2631
+ }
2632
+ //#endregion
2564
2633
  //#region ../entry/lib/sheet-geometry.js
2565
2634
  const MAX_COLUMN = 16383;
2566
2635
  const MAX_ROW = 1048575;
@@ -3270,6 +3339,7 @@ ${XMLNS_NAMESPACE}.`);
3270
3339
  }
3271
3340
  async function open(options, channel, reading = false) {
3272
3341
  const { assets } = options;
3342
+ const prepared = options.preparedEngine === void 0 ? void 0 : preparedBrowserModule(options.preparedEngine, assets);
3273
3343
  let metadata;
3274
3344
  try {
3275
3345
  metadata = options.extension === "pdf" ? {
@@ -3321,6 +3391,9 @@ ${XMLNS_NAMESPACE}.`);
3321
3391
  }
3322
3392
  },
3323
3393
  getPreloadedPackage: () => data,
3394
+ ...prepared === void 0 ? {} : { instantiateWasm(imports, receive) {
3395
+ return instantiatePreparedModule(prepared, imports, receive);
3396
+ } },
3324
3397
  dshResolveSystemFontFaces(request) {
3325
3398
  if (!resolveFonts) throw new BrowserRenderError("font-unavailable", "LibreOffice requested fonts before MEMFS initialization.");
3326
3399
  try {
@@ -3354,7 +3427,7 @@ ${XMLNS_NAMESPACE}.`);
3354
3427
  }, () => send({ type: "font-next" }), (path, bytes) => loaded.FS.writeFile(path, bytes), (families) => send({
3355
3428
  type: "missing-fonts",
3356
3429
  families
3357
- }));
3430
+ }), metadata.codePoints);
3358
3431
  if (options.extension === "pdf") for (const family of new Set(options.fontFallbacks.flat())) resolveFonts({
3359
3432
  ...initialFont,
3360
3433
  family,
@@ -47,7 +47,7 @@ async function readEngine(packageFile) {
47
47
  const root = dirname(packageFile);
48
48
  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))]);
49
49
  const engine = manifest.engine;
50
- if (pkg.name !== `${ENGINE_PREFIX}-wasm` || pkg.version !== "0.0.2-rc6" || 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.");
50
+ if (pkg.name !== `${ENGINE_PREFIX}-wasm` || pkg.version !== "0.0.2-rc8" || 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.");
51
51
  if (engine.glibcMinimum !== void 0) throw new Error("Installed LibreOfficeKit engine has an invalid glibcMinimum.");
52
52
  return {
53
53
  backend: "wasm",
package/lib/cli.js CHANGED
@@ -733,7 +733,7 @@ const require = createRequire(import.meta.url);
733
733
  * Engine-family version every installed engine package must carry. The engine
734
734
  * family shares its release version with this Node API.
735
735
  */
736
- const ENGINE_VERSION = "0.0.2-rc6";
736
+ const ENGINE_VERSION = "0.0.2-rc8";
737
737
  /** npm scope and name prefix shared by the engine packages this adapter installs. */
738
738
  const ENGINE_PREFIX = "@deepseek-ai/libreoffice-kit";
739
739
  /**
@@ -774,7 +774,7 @@ async function readEngine(packageFile) {
774
774
  const root = dirname(packageFile);
775
775
  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))]);
776
776
  const engine = manifest.engine;
777
- if (pkg.name !== `${ENGINE_PREFIX}-wasm` || pkg.version !== "0.0.2-rc6" || 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.");
777
+ if (pkg.name !== `${ENGINE_PREFIX}-wasm` || pkg.version !== "0.0.2-rc8" || 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.");
778
778
  if (engine.glibcMinimum !== void 0) throw new Error("Installed LibreOfficeKit engine has an invalid glibcMinimum.");
779
779
  return {
780
780
  backend: "wasm",
@@ -285,6 +285,7 @@ function createFontSource(options = {}) {
285
285
  let nextId = 0;
286
286
  let failure;
287
287
  let closing;
288
+ let preparing;
288
289
  const pending = /* @__PURE__ */ new Map();
289
290
  const fail = (error) => {
290
291
  failure ??= error;
@@ -301,11 +302,13 @@ function createFontSource(options = {}) {
301
302
  fallbackFamilies: resolved.fontFallbacks,
302
303
  maxFiles: resolved.maxFontFiles,
303
304
  maxFileBytes: resolved.maxFontFileBytes,
304
- maxCachedSubsetBytes
305
+ maxCachedSubsetBytes,
306
+ includeOfficeFonts: fontDirectories === void 0
305
307
  }
306
308
  });
307
309
  worker.on("message", (value) => {
308
310
  if (typeof value !== "object" || value === null || !("id" in value) || typeof value.id !== "number" || !("kind" in value) || ![
311
+ "prepared",
309
312
  "resolved",
310
313
  "bytes",
311
314
  "failed"
@@ -347,6 +350,21 @@ function createFontSource(options = {}) {
347
350
  }
348
351
  return {
349
352
  fontFallbacks: resolved.fontFallbacks,
353
+ async prepare(signal) {
354
+ signal?.throwIfAborted();
355
+ if (failure !== void 0) throw failure;
356
+ if (preparing === void 0) preparing = call({
357
+ id: ++nextId,
358
+ kind: "prepare"
359
+ }).then((reply) => {
360
+ if (reply.kind !== "prepared") throw new Error("The font Worker returned the wrong operation.");
361
+ }).catch((error) => {
362
+ preparing = void 0;
363
+ throw error;
364
+ });
365
+ await preparing;
366
+ signal?.throwIfAborted();
367
+ },
350
368
  async resolve(request, signal) {
351
369
  const reply = await call({
352
370
  id: ++nextId,
@@ -1,8 +1,9 @@
1
1
  import { parentPort, workerData } from "node:worker_threads";
2
2
  import { createHash } from "node:crypto";
3
3
  import { closeSync, constants, fstatSync, openSync, readSync, readdirSync, realpathSync, statSync } from "node:fs";
4
- import { extname, join } from "node:path";
4
+ import { extname, join, posix, win32 } from "node:path";
5
5
  import { create } from "fontkit";
6
+ import { homedir } from "node:os";
6
7
  import { readFile } from "node:fs/promises";
7
8
  import * as publishedProperties from "@unicode/unicode-17.0.0";
8
9
  import variationSelectors from "@unicode/unicode-17.0.0/Binary_Property/Variation_Selector/code-points.mjs";
@@ -704,7 +705,7 @@ function fontPreferences(request, groups, script, scripts, platform = process.pl
704
705
  //#endregion
705
706
  //#region lib/types/fonts.js
706
707
  /** Host font metadata snapshots and conversion-local glyph matching over original files. */
707
- const FONT_EXTENSIONS = /* @__PURE__ */ new Set([
708
+ const FONT_EXTENSIONS$1 = /* @__PURE__ */ new Set([
708
709
  ".ttf",
709
710
  ".otf",
710
711
  ".ttc",
@@ -778,7 +779,7 @@ function fontPaths(directories, maxFiles) {
778
779
  throw error;
779
780
  }
780
781
  pending.push(...names.sort().reverse().map((name) => join(canonical, name)));
781
- } else if (status.isFile() && FONT_EXTENSIONS.has(extname(canonical).toLowerCase())) {
782
+ } else if (status.isFile() && FONT_EXTENSIONS$1.has(extname(canonical).toLowerCase())) {
782
783
  if (paths.length >= maxFiles) throw new Error("The system font catalog exceeds maxFontFiles.");
783
784
  paths.push(canonical);
784
785
  }
@@ -913,7 +914,7 @@ function indexSystemFonts(options, previous = []) {
913
914
  if (group) group.push(face);
914
915
  else reusable.set(face.path, [face]);
915
916
  }
916
- return fontPaths(options.directories, options.maxFiles).flatMap((path) => {
917
+ return fontPaths([...options.directories, ...options.files ?? []], options.maxFiles).flatMap((path) => {
917
918
  const prior = reusable.get(path);
918
919
  if (prior !== void 0) {
919
920
  let current;
@@ -1023,6 +1024,89 @@ function readFont(face) {
1023
1024
  }
1024
1025
  }
1025
1026
  //#endregion
1027
+ //#region lib/types/office-fonts.js
1028
+ /** Curated fonts discovered from a user's Microsoft Office installation. */
1029
+ const FONT_EXTENSIONS = /* @__PURE__ */ new Set([
1030
+ ".ttf",
1031
+ ".otf",
1032
+ ".ttc",
1033
+ ".otc",
1034
+ ".dfont"
1035
+ ]);
1036
+ const OFFICE_FONT_FILE = /^(?:aptos(?:[- ].*)?|arial(?:bd|bi|i)?|calibri(?:b|i|z|l|li)?|cambria(?:b|i|z)?|cour(?:bd|bi|i)?|deng(?:b|l)?|fangsong|kaiti|msjh(?:bd)?|msyh(?:bd|l)?|segoeui(?:b|i|z|l|li|sb|sbi|sl|sli)?|simhei|simsunb?|symbol|times(?:bd|bi|i)?|wingdings(?: [23])?|wingdng[23])\.(?:ttf|otf|ttc|otc)$/iu;
1037
+ const FAMILIES = new Set([
1038
+ "aptos",
1039
+ "aptos display",
1040
+ "aptos narrow",
1041
+ "arial",
1042
+ "calibri",
1043
+ "calibri light",
1044
+ "cambria",
1045
+ "cambria math",
1046
+ "courier new",
1047
+ "dengxian",
1048
+ "fangsong",
1049
+ "kaiti",
1050
+ "microsoft jhenghei",
1051
+ "microsoft jhenghei ui",
1052
+ "microsoft yahei",
1053
+ "microsoft yahei ui",
1054
+ "nsimsun",
1055
+ "segoe ui",
1056
+ "simhei",
1057
+ "simsun",
1058
+ "symbol",
1059
+ "times new roman",
1060
+ "wingdings",
1061
+ "wingdings 2",
1062
+ "wingdings 3"
1063
+ ].map(normalize));
1064
+ /** @returns whether parsed font names belong to the curated Office compatibility set. */
1065
+ function officeFontFace(face) {
1066
+ return face.aliases.some((alias) => FAMILIES.has(alias));
1067
+ }
1068
+ function directory(path) {
1069
+ try {
1070
+ return statSync(path).isDirectory();
1071
+ } catch (error) {
1072
+ if (absent(error)) return false;
1073
+ throw error;
1074
+ }
1075
+ }
1076
+ function files(root, recursive, namesOnly = true) {
1077
+ const pending = [root], result = [];
1078
+ for (let current = pending.pop(); current !== void 0; current = pending.pop()) {
1079
+ let entries;
1080
+ try {
1081
+ entries = readdirSync(current, { withFileTypes: true });
1082
+ } catch (error) {
1083
+ if (absent(error)) continue;
1084
+ throw error;
1085
+ }
1086
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name, "en"))) if (entry.isDirectory()) {
1087
+ if (recursive && entry.name !== "PreviewFont") pending.push(join(current, entry.name));
1088
+ } else if (entry.isFile() && FONT_EXTENSIONS.has(extname(entry.name).toLowerCase()) && (!namesOnly || OFFICE_FONT_FILE.test(entry.name))) result.push(join(current, entry.name));
1089
+ }
1090
+ return result;
1091
+ }
1092
+ /** Find compatibility font files without exposing their paths outside the font Worker. */
1093
+ function officeFontFiles(platform = process.platform, home = homedir(), env = process.env, applicationRoots = ["/Applications", posix.join(home, "Applications")]) {
1094
+ const bundled = platform === "darwin" ? [
1095
+ "Microsoft Word",
1096
+ "Microsoft Excel",
1097
+ "Microsoft PowerPoint"
1098
+ ].flatMap((app) => applicationRoots.map((root) => posix.join(root, `${app}.app/Contents/Resources/DFonts`))).find(directory) : platform === "win32" ? [env.ProgramFiles, env["ProgramFiles(x86)"]].filter((root) => Boolean(root)).map((root) => win32.join(root, "Microsoft Office", "root", "vfs", "Fonts", "private")).find(directory) : void 0;
1099
+ const cloud = platform === "darwin" ? posix.join(home, "Library/Group Containers/UBF8T346G9.Office/FontCache") : platform === "win32" ? win32.join(env.LOCALAPPDATA ?? win32.join(home, "AppData", "Local"), "Microsoft", "FontCache") : void 0;
1100
+ const ordered = [...bundled === void 0 ? [] : files(bundled, false).sort(), ...cloud === void 0 ? [] : files(cloud, true, false).sort((a, b) => b.localeCompare(a, "en", { numeric: true }))];
1101
+ const unique = /* @__PURE__ */ new Map();
1102
+ for (const file of ordered) {
1103
+ const portable = file.replaceAll("\\", "/");
1104
+ const name = portable.slice(portable.lastIndexOf("/") + 1).toLowerCase();
1105
+ if (!unique.has(name)) unique.set(name, file);
1106
+ }
1107
+ return [...unique.values()];
1108
+ }
1109
+ //#endregion
1026
1110
  //#region lib/types/font-full.js
1027
1111
  /** Whole fonts for engines such as PDFium that perform their own glyph mapping. */
1028
1112
  function fontFileFormat(bytes) {
@@ -1175,7 +1259,7 @@ async function fontScriptCodePoints(points, script) {
1175
1259
  }
1176
1260
  //#endregion
1177
1261
  //#region lib/types/font-subsets.js
1178
- /** Refreshable installed-font matching with deterministic, memory-bounded sfnt subsets. */
1262
+ /** Lifetime-scoped installed-font matching with deterministic, memory-bounded sfnt subsets. */
1179
1263
  const ALGORITHM = `${FONT_SUBSET_VERSION}/${FONT_PARTITION_VERSION}`;
1180
1264
  const STAT_KEYS = [
1181
1265
  "dev",
@@ -1211,6 +1295,29 @@ var FontSubsetSource = class {
1211
1295
  constructor(options) {
1212
1296
  this.options = options;
1213
1297
  }
1298
+ /** Build the immutable lifetime catalog, adding only Office families absent from normal system roots. */
1299
+ prepare() {
1300
+ if (this.catalog === void 0) {
1301
+ const primary = indexSystemFonts(this.options);
1302
+ const primaryFiles = new Set(primary.map((face) => face.path));
1303
+ const remaining = Math.max(0, this.options.maxFiles - primaryFiles.size);
1304
+ const supplementalFiles = this.options.includeOfficeFonts ? officeFontFiles() : [];
1305
+ const supplemental = remaining === 0 ? [] : indexSystemFonts({
1306
+ directories: [],
1307
+ files: supplementalFiles.slice(0, remaining),
1308
+ maxFiles: remaining,
1309
+ maxFileBytes: this.options.maxFileBytes
1310
+ });
1311
+ const aliases = new Set(primary.flatMap((face) => face.aliases));
1312
+ this.snapshot = [...primary, ...supplemental.filter((face) => officeFontFace(face) && !face.aliases.some((alias) => aliases.has(alias)))];
1313
+ this.catalog = new SystemFontCatalog({
1314
+ faces: this.snapshot,
1315
+ fallbackFamilies: this.options.fallbackFamilies,
1316
+ deduplicateBy: "face"
1317
+ });
1318
+ }
1319
+ return this.catalog;
1320
+ }
1214
1321
  retain(key, bytes) {
1215
1322
  const existing = this.cached.get(key);
1216
1323
  if (existing !== void 0) {
@@ -1285,33 +1392,13 @@ var FontSubsetSource = class {
1285
1392
  return asset;
1286
1393
  }
1287
1394
  /**
1288
- * Refresh installed files and select whole Unicode-script subsets for matching physical faces.
1395
+ * Select whole Unicode-script subsets from the source lifetime's installed-font snapshot.
1289
1396
  * @param request - Requested family/style attributes and Unicode scalars.
1290
1397
  * @returns reusable subset identities; unavailable characters remain unresolved.
1291
1398
  */
1292
1399
  async resolve(request) {
1293
1400
  if (request.mode !== void 0 && request.mode !== "subset" && request.mode !== "full") throw new TypeError("Unknown font asset mode.");
1294
- const snapshot = indexSystemFonts(this.options, this.snapshot);
1295
- if (this.catalog === void 0 || snapshot.length !== this.snapshot.length || snapshot.some((face, index) => face !== this.snapshot[index])) {
1296
- const current = new Set(snapshot.map((face) => fileIdentity(face)));
1297
- for (const [partition, selection] of this.partitions) {
1298
- if (current.has(fileIdentity(selection.face))) continue;
1299
- this.partitions.delete(partition);
1300
- if (this.selected.get(selection.asset.id) === selection) this.selected.delete(selection.asset.id);
1301
- const bytes = this.cached.get(selection.key);
1302
- if (bytes !== void 0) {
1303
- this.cached.delete(selection.key);
1304
- this.cachedBytes -= bytes.byteLength;
1305
- }
1306
- }
1307
- this.snapshot = snapshot;
1308
- this.catalog = new SystemFontCatalog({
1309
- faces: snapshot,
1310
- fallbackFamilies: this.options.fallbackFamilies,
1311
- deduplicateBy: "face"
1312
- });
1313
- }
1314
- const matched = this.catalog.match(request, new AbortController().signal);
1401
+ const matched = this.prepare().match(request, new AbortController().signal);
1315
1402
  const fonts = [];
1316
1403
  for (const face of matched.fonts) {
1317
1404
  if (request.mode === "full") {
@@ -1353,10 +1440,20 @@ const port = parentPort;
1353
1440
  const source = new FontSubsetSource(workerData);
1354
1441
  let queue = Promise.resolve();
1355
1442
  port.on("message", (command) => {
1356
- if (!Number.isSafeInteger(command?.id) || command.kind !== "resolve" && command.kind !== "read") throw new Error("The font Worker received an invalid operation.");
1443
+ if (!Number.isSafeInteger(command?.id) || ![
1444
+ "prepare",
1445
+ "resolve",
1446
+ "read"
1447
+ ].includes(command.kind)) throw new Error("The font Worker received an invalid operation.");
1357
1448
  queue = queue.then(async () => {
1358
1449
  try {
1359
- if (command.kind === "resolve") {
1450
+ if (command.kind === "prepare") {
1451
+ source.prepare();
1452
+ port.postMessage({
1453
+ id: command.id,
1454
+ kind: "prepared"
1455
+ });
1456
+ } else if (command.kind === "resolve") {
1360
1457
  const value = await source.resolve(command.request);
1361
1458
  port.postMessage({
1362
1459
  id: command.id,
package/lib/index.js CHANGED
@@ -731,7 +731,7 @@ const require = createRequire(import.meta.url);
731
731
  * Engine-family version every installed engine package must carry. The engine
732
732
  * family shares its release version with this Node API.
733
733
  */
734
- const ENGINE_VERSION = "0.0.2-rc6";
734
+ const ENGINE_VERSION = "0.0.2-rc8";
735
735
  /** npm scope and name prefix shared by the engine packages this adapter installs. */
736
736
  const ENGINE_PREFIX = "@deepseek-ai/libreoffice-kit";
737
737
  /**
@@ -772,7 +772,7 @@ async function readEngine(packageFile) {
772
772
  const root = dirname(packageFile);
773
773
  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))]);
774
774
  const engine = manifest.engine;
775
- if (pkg.name !== `${ENGINE_PREFIX}-wasm` || pkg.version !== "0.0.2-rc6" || 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.");
775
+ if (pkg.name !== `${ENGINE_PREFIX}-wasm` || pkg.version !== "0.0.2-rc8" || 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.");
776
776
  if (engine.glibcMinimum !== void 0) throw new Error("Installed LibreOfficeKit engine has an invalid glibcMinimum.");
777
777
  return {
778
778
  backend: "wasm",
@@ -2,7 +2,7 @@
2
2
  * Engine-family version every installed engine package must carry. The engine
3
3
  * family shares its release version with this Node API.
4
4
  */
5
- export declare const ENGINE_VERSION = "0.0.2-rc6";
5
+ export declare const ENGINE_VERSION = "0.0.2-rc8";
6
6
  /** Host diagnostic fields used to identify the runtime glibc version. */
7
7
  export interface EngineHostReport {
8
8
  readonly header?: {
@@ -40,6 +40,11 @@ export interface FontSourceOptions {
40
40
  export interface FontSource {
41
41
  /** Resolved ordered font family preferences shared with browser Fontconfig. */
42
42
  readonly fontFallbacks: readonly (readonly string[])[];
43
+ /**
44
+ * Start the lifetime font snapshot without matching a document request.
45
+ * @param signal - Checked before dispatch and after the shared preparation settles.
46
+ */
47
+ prepare(signal?: AbortSignal): Promise<void>;
43
48
  /**
44
49
  * Select deterministic Unicode-script subsets using LibreOffice's requested attributes.
45
50
  * @param request - Family, style, language, and required Unicode scalars.
@@ -59,6 +64,9 @@ export interface FontSource {
59
64
  }
60
65
  /** Parent-to-worker operations; neither message contains a caller-selected file path. */
61
66
  export type FontCommand = {
67
+ readonly id: number;
68
+ readonly kind: 'prepare';
69
+ } | {
62
70
  readonly id: number;
63
71
  readonly kind: 'resolve';
64
72
  readonly request: FontResolveRequest;
@@ -69,6 +77,9 @@ export type FontCommand = {
69
77
  };
70
78
  /** Worker replies retain their operation discriminator across structured cloning. */
71
79
  export type FontReply = {
80
+ readonly id: number;
81
+ readonly kind: 'prepared';
82
+ } | {
72
83
  readonly id: number;
73
84
  readonly kind: 'resolved';
74
85
  readonly value: FontResolution;
@@ -1,9 +1,11 @@
1
+ import { SystemFontCatalog } from './fonts.ts';
1
2
  import type { FontIndexOptions } from './fonts.ts';
2
3
  import type { FontAssetId, FontResolution, FontResolveRequest } from './font-source-types.ts';
3
4
  /** Source limits and resolved family preferences passed to the private font Worker. */
4
5
  export interface FontSubsetOptions extends FontIndexOptions {
5
6
  readonly fallbackFamilies: readonly (readonly string[])[];
6
7
  readonly maxCachedSubsetBytes: number;
8
+ readonly includeOfficeFonts?: boolean;
7
9
  }
8
10
  /** One Worker-owned font index and LRU whose byte budget excludes transient subsetting input/output. */
9
11
  export declare class FontSubsetSource {
@@ -16,11 +18,13 @@ export declare class FontSubsetSource {
16
18
  private cachedBytes;
17
19
  /** @param options - Resolved discovery, fallback, and retained subset limits. */
18
20
  constructor(options: FontSubsetOptions);
21
+ /** Build the immutable lifetime catalog, adding only Office families absent from normal system roots. */
22
+ prepare(): SystemFontCatalog;
19
23
  private retain;
20
24
  private generate;
21
25
  private describe;
22
26
  /**
23
- * Refresh installed files and select whole Unicode-script subsets for matching physical faces.
27
+ * Select whole Unicode-script subsets from the source lifetime's installed-font snapshot.
24
28
  * @param request - Requested family/style attributes and Unicode scalars.
25
29
  * @returns reusable subset identities; unavailable characters remain unresolved.
26
30
  */
@@ -45,6 +45,7 @@ export interface SystemFontCatalogOptions {
45
45
  /** Host font roots and physical file limits. */
46
46
  export interface FontIndexOptions {
47
47
  readonly directories: readonly string[];
48
+ readonly files?: readonly string[];
48
49
  readonly maxFiles: number;
49
50
  readonly maxFileBytes: number;
50
51
  }
@@ -0,0 +1,6 @@
1
+ import type { FontFace } from './fonts.ts';
2
+ /** @returns whether parsed font names belong to the curated Office compatibility set. */
3
+ export declare function officeFontFace(face: Pick<FontFace, 'aliases'>): boolean;
4
+ /** Find compatibility font files without exposing their paths outside the font Worker. */
5
+ export declare function officeFontFiles(platform?: NodeJS.Platform, home?: string, env?: NodeJS.ProcessEnv, applicationRoots?: readonly string[]): string[];
6
+ //# sourceMappingURL=office-fonts.d.ts.map
package/lib/worker.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { parentPort, workerData } from "node:worker_threads";
3
3
  import { closeSync, constants, fstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
4
- import { basename, dirname, extname, join } from "node:path";
4
+ import { basename, extname, join } from "node:path";
5
5
  import { strFromU8, unzipSync, zlibSync } from "fflate";
6
6
  import { SaxesParser } from "saxes";
7
7
  import { create } from "fontkit";
@@ -1110,7 +1110,7 @@ function indexSystemFonts(options, previous = []) {
1110
1110
  if (group) group.push(face);
1111
1111
  else reusable.set(face.path, [face]);
1112
1112
  }
1113
- return fontPaths(options.directories, options.maxFiles).flatMap((path) => {
1113
+ return fontPaths([...options.directories, ...options.files ?? []], options.maxFiles).flatMap((path) => {
1114
1114
  const prior = reusable.get(path);
1115
1115
  if (prior !== void 0) {
1116
1116
  let current;
@@ -1430,13 +1430,14 @@ async function withWasmSession(request, use) {
1430
1430
  mainScriptUrlOrBlob: engine.loader,
1431
1431
  locateFile(name) {
1432
1432
  const file = basename(name);
1433
- if (![
1433
+ if (file === "soffice.wasm") return engine.wasm;
1434
+ for (const asset of [
1434
1435
  engine.loader,
1435
1436
  engine.data,
1436
1437
  engine.wasm,
1437
1438
  engine.metadata
1438
- ].some((path) => basename(path) === file)) throw new Error(`LibreOffice requested an unlisted asset: ${file}`);
1439
- return join(dirname(engine.loader), file);
1439
+ ]) if (basename(asset) === file) return asset;
1440
+ throw new Error(`LibreOffice requested an unlisted asset: ${file}`);
1440
1441
  },
1441
1442
  getPreloadedPackage: () => data,
1442
1443
  dshResolveSystemFonts(request) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/libreoffice-kit",
3
3
  "description": "WASM Office previews, document images, and conversion for Node and browsers",
4
- "version": "0.0.2-rc6",
4
+ "version": "0.0.2-rc8",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -85,7 +85,7 @@
85
85
  "fflate": "0.8.2",
86
86
  "fontkit": "2.0.4",
87
87
  "saxes": "6.0.0",
88
- "@deepseek-ai/libreoffice-kit-wasm": "0.0.2-rc6"
88
+ "@deepseek-ai/libreoffice-kit-wasm": "0.0.2-rc8"
89
89
  },
90
90
  "bin": {
91
91
  "libreoffice-kit": "./lib/cli.js"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepseek-ai/libreoffice-kit-browser-internal",
3
- "version": "0.0.2-rc6",
3
+ "version": "0.0.2-rc8",
4
4
  "type": "module",
5
5
  "license": "MPL-2.0",
6
6
  "description": "Browser Worker LibreOffice reading sessions and PDF rendering",
@@ -3,6 +3,7 @@ import { FONT_CHUNK_BYTES, FONT_HEADER_BYTES, FontState } from './protocol.ts'
3
3
  import type { OwnerMessage, OwnerRequest, WorkerMessage, WorkerOptions } from './protocol.ts'
4
4
  import { fontFrames, fontViews } from './font-channel.ts'
5
5
  import { BrowserRenderError } from './types.ts'
6
+ import { preparedBrowserModule } from './preparation.ts'
6
7
  import type { BrowserDocumentOptions } from './types.ts'
7
8
  import type { OfficeDocumentEvent, OfficeDocumentOptions } from './office-types.ts'
8
9
 
@@ -23,6 +24,7 @@ export async function openBrowserConnection(options: BrowserDocumentOptions | Of
23
24
  if (!globalThis.crossOriginIsolated || typeof SharedArrayBuffer === 'undefined' || typeof Worker === 'undefined') throw new BrowserRenderError('unavailable', 'LibreOffice requires an isolated secure browser context with Worker and SharedArrayBuffer support.')
24
25
  if (![options.timeoutMs, options.maxLoadedFontBytes, options.maxArchiveEntries, options.maxUncompressedBytes].every(value => Number.isSafeInteger(value) && value > 0) || options.timeoutMs > 0x7fffffff) throw new TypeError('Document limits must be positive integers and timeoutMs must fit a browser timer.')
25
26
  if (!(office ? ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'] : ['pdf']).includes(options.extension) || options.data.byteLength === 0) throw new BrowserRenderError('invalid-document', 'The document is empty or has an unsupported extension.')
27
+ if (options.preparedEngine !== undefined) preparedBrowserModule(options.preparedEngine, options.assets)
26
28
  const worker = new Worker(options.assets.workerUrl, { name: 'libreoffice-document' })
27
29
  const channel = new SharedArrayBuffer(FONT_HEADER_BYTES + FONT_CHUNK_BYTES)
28
30
  const { control, bytes } = fontViews(channel)
@@ -64,7 +66,7 @@ export async function openBrowserConnection(options: BrowserDocumentOptions | Of
64
66
  case 'office-event': if (!closed) { onEvent?.(message.event); if (message.event.type === 'error') void dispose() }; return
65
67
  case 'font':
66
68
  if (closed) return
67
- void Promise.resolve().then(() => options.resolveFonts(message.request, lifetime.signal)).then(result => {
69
+ void Promise.resolve().then(() => options.resolveFonts(message.request, message.known, lifetime.signal)).then(result => {
68
70
  if (closed) return
69
71
  frames = fontFrames(result, message.known)
70
72
  pumpFonts()
@@ -136,7 +138,10 @@ export async function openBrowserConnection(options: BrowserDocumentOptions | Of
136
138
 
137
139
  try {
138
140
  const data = new Uint8Array(options.data)
139
- const engineOptions: WorkerOptions = { data, extension: options.extension, assets: options.assets, timeoutMs: options.timeoutMs, maxLoadedFontBytes: options.maxLoadedFontBytes, fontFallbacks: options.fontFallbacks, maxArchiveEntries: options.maxArchiveEntries, maxUncompressedBytes: options.maxUncompressedBytes }
141
+ const engineOptions: WorkerOptions = { data, extension: options.extension, assets: options.assets,
142
+ ...(options.preparedEngine === undefined ? {} : { preparedEngine: options.preparedEngine }),
143
+ timeoutMs: options.timeoutMs, maxLoadedFontBytes: options.maxLoadedFontBytes, fontFallbacks: options.fontFallbacks,
144
+ maxArchiveEntries: options.maxArchiveEntries, maxUncompressedBytes: options.maxUncompressedBytes }
140
145
  const result = await post({ type: 'open', id: ++sequence, options: engineOptions, channel, ...(office ? { office: true } : {}) }, [data.buffer])
141
146
  if (result.type !== 'opened') throw new BrowserRenderError('invalid-document', 'LibreOffice returned an unexpected load response.')
142
147
  opened = result
@@ -14,9 +14,11 @@ export function fontViews(channel: SharedArrayBuffer): { control: Int32Array; by
14
14
  export function* fontFrames(result: BrowserFontResult, known: readonly FontIdentity[] = []): Generator<{ state: FontState; bytes: Uint8Array }> {
15
15
  const identities = new Map(known.map(font => [font.id, font]))
16
16
  const header: FontHeader = { fonts: result.fonts.map(font => {
17
- const identity: FontIdentity = { id: font.id, bytes: font.data.byteLength, ...(font.format ? { format: font.format } : {}) }
17
+ const size = font.data === undefined ? font.bytes : font.data.byteLength
18
+ const identity: FontIdentity = { id: font.id, bytes: size, ...(font.format ? { format: font.format } : {}) }
18
19
  const prior = identities.get(font.id)
19
20
  if (prior && (prior.bytes !== identity.bytes || prior.format !== identity.format)) throw new BrowserRenderError('font-unavailable', 'Font identity has conflicting bytes or formats.')
21
+ if (!prior && font.data === undefined) throw new BrowserRenderError('font-unavailable', 'Font reference has not been installed.')
20
22
  identities.set(font.id, identity)
21
23
  return { ...identity, family: font.family, alias: font.alias, ...(prior ? { reference: true as const } : {}) }
22
24
  }), ...(result.missingFamily === undefined ? {} : { missingFamily: result.missingFamily }) }
@@ -25,6 +27,8 @@ export function* fontFrames(result: BrowserFontResult, known: readonly FontIdent
25
27
  yield { state: FontState.Header, bytes: encoded }
26
28
  for (const [index, font] of result.fonts.entries()) {
27
29
  if (header.fonts[index]!.reference) continue
30
+ /* v8 ignore next -- header validation rejects an unknown data-less font before iteration. */
31
+ if (font.data === undefined) throw new BrowserRenderError('font-unavailable', 'Font reference has not been installed.')
28
32
  for (let offset = 0; offset < font.data.byteLength; offset += FONT_CHUNK_BYTES) {
29
33
  yield { state: FontState.Bytes, bytes: font.data.subarray(offset, offset + FONT_CHUNK_BYTES) }
30
34
  }
@@ -35,14 +39,38 @@ export function* fontFrames(result: BrowserFontResult, known: readonly FontIdent
35
39
  /** One MEMFS font face registered under a document-local family alias. */
36
40
  export interface EngineFontFace { readonly path: string; readonly family: string }
37
41
 
42
+ const SCRIPT_GROUPS = [
43
+ ['arabic', /\p{Script_Extensions=Arabic}/u], ['cyrillic', /\p{Script_Extensions=Cyrillic}/u],
44
+ ['devanagari', /\p{Script_Extensions=Devanagari}/u], ['greek', /\p{Script_Extensions=Greek}/u],
45
+ ['han', /\p{Script_Extensions=Han}/u], ['hangul', /\p{Script_Extensions=Hangul}/u],
46
+ ['hebrew', /\p{Script_Extensions=Hebrew}/u], ['hiragana', /\p{Script_Extensions=Hiragana}/u],
47
+ ['katakana', /\p{Script_Extensions=Katakana}/u], ['latin', /\p{Script_Extensions=Latin}/u],
48
+ ['thai', /\p{Script_Extensions=Thai}/u], ['common', /[\p{Script=Common}\p{Script=Inherited}]/u],
49
+ ] as const
50
+
51
+ function scriptGroup(point: number): string {
52
+ const character = String.fromCodePoint(point)
53
+ return SCRIPT_GROUPS.find(([, pattern]) => pattern.test(character))?.[0] ?? `other-${point >>> 8}`
54
+ }
55
+
38
56
  /** The synchronous reader installs immutable font assets before returning their MEMFS paths and aliases. */
39
57
  export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number, maxLoadedFontBytes: number,
40
58
  declaredFamilies: ReadonlyMap<string, string>, request: (request: BrowserFontRequest, known: readonly FontIdentity[]) => void, next: () => void,
41
- install: (path: string, bytes: Uint8Array) => void, missing: (families: readonly string[]) => void): (request: BrowserFontRequest) => EngineFontFace[] {
59
+ install: (path: string, bytes: Uint8Array) => void, missing: (families: readonly string[]) => void,
60
+ documentCodePoints: readonly number[] = []): (request: BrowserFontRequest) => EngineFontFace[] {
42
61
  const { control, bytes } = fontViews(channel)
43
62
  const installed = new Map<string, { face: EngineFontFace; bytes: number; format: FontIdentity['format'] }>()
44
63
  const aliases = new Map<string, { id: string; family: string }>()
45
64
  const requests = new Map<string, EngineFontFace[]>()
65
+ const coverage = new Map<string, { readonly points: Set<number>; readonly faces: EngineFontFace[]; complete: boolean }>()
66
+ const expanded = new Map<string, Set<string>>()
67
+ const documentGroups = new Map<string, number[]>()
68
+ for (const point of [...new Set(documentCodePoints)].sort((left, right) => left - right)) {
69
+ const group = scriptGroup(point)
70
+ const points = documentGroups.get(group)
71
+ if (points) points.push(point)
72
+ else documentGroups.set(group, [point])
73
+ }
46
74
  const families = new Set<string>()
47
75
  let loadedBytes = 0
48
76
  function read(): { state: FontState; data: Uint8Array } {
@@ -63,11 +91,24 @@ export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number,
63
91
  }
64
92
  return (attributes) => {
65
93
  const canonical = aliases.get(normalize(attributes.family))?.family
66
- const original = { ...attributes, ...(canonical === undefined ? {} : { family: canonical }) }
94
+ const codePoints = [...new Set(attributes.codePoints)].sort((left, right) => left - right)
95
+ const original = { ...attributes, codePoints, ...(canonical === undefined ? {} : { family: canonical }) }
67
96
  const key = JSON.stringify(original)
68
97
  const cached = requests.get(key)
69
98
  if (cached) return cached
70
- request(original, [...installed].map(([id, font]) => ({ id, bytes: font.bytes, ...(font.format ? { format: font.format } : {}) })))
99
+ const { codePoints: _points, ...base } = original
100
+ const coverageKey = JSON.stringify(base)
101
+ const covered = coverage.get(coverageKey)
102
+ if (codePoints.length > 0 && covered && (covered.complete || codePoints.every(point => covered.points.has(point)))) {
103
+ requests.set(key, covered.faces)
104
+ return covered.faces
105
+ }
106
+ const groups = new Set(codePoints.map(scriptGroup))
107
+ const expandedGroups = expanded.get(coverageKey)
108
+ const newGroups = original.mode === 'full' ? [] : [...groups].filter(group => !expandedGroups?.has(group))
109
+ const requestedPoints = newGroups.length === 0 ? codePoints : [...new Set([...codePoints,
110
+ ...newGroups.flatMap(group => documentGroups.get(group) ?? [])])].sort((left, right) => left - right)
111
+ request({ ...original, codePoints: requestedPoints }, [...installed].map(([id, font]) => ({ id, bytes: font.bytes, ...(font.format ? { format: font.format } : {}) })))
71
112
  const first = read()
72
113
  if (first.state !== FontState.Header) throw new BrowserRenderError('font-unavailable', 'Expected font transfer metadata.')
73
114
  let header: FontHeader
@@ -104,6 +145,16 @@ export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number,
104
145
  const absentFamily = header.missingFamily === undefined ? undefined : declaredFamilies.get(normalize(header.missingFamily))
105
146
  if (absentFamily !== undefined && !families.has(absentFamily)) { families.add(absentFamily); missing([...families]) }
106
147
  requests.set(key, faces)
148
+ if (newGroups.length > 0) expanded.set(coverageKey, new Set([...(expandedGroups ?? []), ...newGroups]))
149
+ if (requestedPoints.length > 0) {
150
+ const group = { points: new Set(covered?.points), faces: [...(covered?.faces ?? [])], complete: covered?.complete ?? false }
151
+ for (const point of requestedPoints) group.points.add(point)
152
+ for (const face of faces) {
153
+ if (!group.faces.some(existing => existing.path === face.path && existing.family === face.family)) group.faces.push(face)
154
+ }
155
+ group.complete ||= header.fonts.every(font => font.format !== undefined)
156
+ coverage.set(coverageKey, group)
157
+ }
107
158
  return faces
108
159
  }
109
160
  }
@@ -4,8 +4,9 @@ import { BrowserRenderError } from './types.ts'
4
4
  import type { BrowserDocument, BrowserDocumentOptions, BrowserTile, BrowserTileRequest } from './types.ts'
5
5
  export { BrowserRenderError } from './types.ts'
6
6
  export { openOfficeDocument } from './office.ts'
7
+ export { prepareOfficeBrowser } from './preparation.ts'
7
8
  export type * from './office-types.ts'
8
- export type { BrowserDocument, BrowserDocumentOptions, BrowserEngineAssets, BrowserFontRequest, BrowserFontResult, BrowserPage, BrowserRenderErrorCode, BrowserTile, BrowserTileRequest } from './types.ts'
9
+ export type { BrowserDocument, BrowserDocumentOptions, BrowserEngineAssets, BrowserFontIdentity, BrowserFontRequest, BrowserFontResult, BrowserPage, BrowserRenderErrorCode, BrowserResolvedFont, BrowserTile, BrowserTileRequest, PreparedBrowserEngine } from './types.ts'
9
10
 
10
11
  /**
11
12
  * Open a read-only document; each call owns an independent Worker.
@@ -0,0 +1,41 @@
1
+ /** Browser-side WASM compilation without creating an Office Worker or memory. */
2
+ import { BrowserRenderError } from './types.ts'
3
+ import type { BrowserEngineAssets, PreparedBrowserEngine } from './types.ts'
4
+
5
+ interface PreparedBrowserEngineRecord {
6
+ readonly wasmUrl: string
7
+ readonly module: WebAssembly.Module
8
+ }
9
+
10
+ /**
11
+ * Compile the version-matched LibreOffice WASM module for later document Workers.
12
+ * @param assets - Browser resources whose WASM URL identifies the compiled module.
13
+ * @param signal - Cancels the resource request; compilation may finish before cancellation is observed.
14
+ * @returns an opaque, structured-cloneable engine handle that allocates no WASM memory.
15
+ */
16
+ export async function prepareOfficeBrowser(assets: BrowserEngineAssets, signal?: AbortSignal): Promise<PreparedBrowserEngine> {
17
+ signal?.throwIfAborted()
18
+ if (typeof WebAssembly.compileStreaming !== 'function') throw new BrowserRenderError('unavailable', 'Streaming WebAssembly compilation is unavailable.')
19
+ const response = await fetch(assets.wasmUrl, { credentials: 'same-origin', ...(signal === undefined ? {} : { signal }) })
20
+ if (!response.ok) throw new BrowserRenderError('unavailable', `LibreOffice WASM request failed: ${response.status}`)
21
+ const module = await WebAssembly.compileStreaming(Promise.resolve(response))
22
+ signal?.throwIfAborted()
23
+ return Object.freeze({ wasmUrl: assets.wasmUrl, module }) as unknown as PreparedBrowserEngine
24
+ }
25
+
26
+ /** Return the compiled module after validating the Worker-bound asset identity. */
27
+ export function preparedBrowserModule(prepared: PreparedBrowserEngine, assets: BrowserEngineAssets): WebAssembly.Module {
28
+ const record = prepared as unknown as PreparedBrowserEngineRecord
29
+ if (record.wasmUrl !== assets.wasmUrl || !(record.module instanceof WebAssembly.Module)) {
30
+ throw new TypeError('The prepared browser engine does not match the requested WASM asset.')
31
+ }
32
+ return record.module
33
+ }
34
+
35
+ /** Instantiate precompiled code through Emscripten's synchronous override. */
36
+ export function instantiatePreparedModule(module: WebAssembly.Module, imports: WebAssembly.Imports,
37
+ receive: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void): WebAssembly.Exports {
38
+ const instance = new WebAssembly.Instance(module, imports)
39
+ receive(instance, module)
40
+ return instance.exports
41
+ }
@@ -1,5 +1,5 @@
1
1
  /** Private messages exchanged by the document owner and its single engine Worker. */
2
- import type { BrowserDocumentOptions, BrowserFontRequest, BrowserPage, BrowserRenderErrorCode, BrowserTile, BrowserTileRequest } from './types.ts'
2
+ import type { BrowserDocumentOptions, BrowserFontIdentity, BrowserFontRequest, BrowserPage, BrowserRenderErrorCode, BrowserTile, BrowserTileRequest } from './types.ts'
3
3
  import type { OfficeDocumentEvent, OfficeDocumentNavigation, OfficeDocumentOptions, OfficeDocumentState, OfficeDocumentPointer, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult, OfficeDocumentTileRequest, OfficeDocumentRectangle } from './office-types.ts'
4
4
 
5
5
  export const FONT_CHUNK_BYTES = 1024 * 1024
@@ -34,7 +34,7 @@ export type WorkerMessage =
34
34
  | { readonly type: 'font-next' }
35
35
  | { readonly type: 'missing-fonts'; readonly families: readonly string[] }
36
36
  /** Immutable bytes already installed in this document's MEMFS. */
37
- export interface FontIdentity { readonly id: string; readonly bytes: number; readonly format?: 'ttf' | 'otf' | 'ttc' }
37
+ export type FontIdentity = BrowserFontIdentity
38
38
  export interface FontHeader {
39
39
  readonly fonts: readonly (FontIdentity & { readonly family: string; readonly alias: string; readonly reference?: true })[]
40
40
  readonly missingFamily?: string
@@ -10,6 +10,10 @@ export interface BrowserEngineAssets {
10
10
  readonly programDirectory: string
11
11
  }
12
12
 
13
+ declare const preparedBrowserEngine: unique symbol
14
+ /** Compiled engine code bound to one WASM resource identity. */
15
+ export interface PreparedBrowserEngine { readonly [preparedBrowserEngine]: true }
16
+
13
17
  /** VCL attributes passed unchanged to the Host's font matcher. */
14
18
  export interface BrowserFontRequest {
15
19
  readonly mode?: 'full'
@@ -23,9 +27,24 @@ export interface BrowserFontRequest {
23
27
  readonly codePoints: readonly number[]
24
28
  }
25
29
 
30
+ /** Immutable font content already installed in one document Worker. */
31
+ export interface BrowserFontIdentity {
32
+ readonly id: string
33
+ readonly bytes: number
34
+ readonly format?: 'ttf' | 'otf' | 'ttc'
35
+ }
36
+
37
+ /** One new font body or a metadata-only reference to content already installed in the Worker. */
38
+ export type BrowserResolvedFont = {
39
+ readonly id: string
40
+ readonly family: string
41
+ readonly alias: string
42
+ readonly format?: 'ttf' | 'otf' | 'ttc'
43
+ } & ({ readonly data: Uint8Array; readonly bytes?: never } | { readonly data?: never; readonly bytes: number })
44
+
26
45
  /** Immutable per-face font subsets; equal ids and aliases must identify equal bytes. */
27
46
  export interface BrowserFontResult {
28
- readonly fonts: readonly { readonly id: string; readonly data: Uint8Array; readonly family: string; readonly alias: string; readonly format?: 'ttf' | 'otf' | 'ttc' }[]
47
+ readonly fonts: readonly BrowserResolvedFont[]
29
48
  readonly missingFamily?: string
30
49
  /** Missing scalars reported by the Host, independently of a substituted family. */
31
50
  readonly unresolvedCodePoints?: readonly number[]
@@ -56,6 +75,8 @@ export interface BrowserDocumentOptions {
56
75
  readonly data: Uint8Array
57
76
  readonly extension: 'pdf'
58
77
  readonly assets: BrowserEngineAssets
78
+ /** Optional compiled WASM code created by prepareOfficeBrowser for these assets. */
79
+ readonly preparedEngine?: PreparedBrowserEngine
59
80
  /** Maximum time for each load, render, font request, or teardown operation. */
60
81
  readonly timeoutMs: number
61
82
  /** Maximum ZIP entries inspected before LibreOffice loads OOXML. */
@@ -67,7 +88,7 @@ export interface BrowserDocumentOptions {
67
88
  /** The same ordered substitution groups used by the Host font matcher. */
68
89
  readonly fontFallbacks: readonly (readonly string[])[]
69
90
  /** Match fonts without blocking the browser's main thread. */
70
- readonly resolveFonts: (request: BrowserFontRequest, signal: AbortSignal) => Promise<BrowserFontResult>
91
+ readonly resolveFonts: (request: BrowserFontRequest, known: readonly BrowserFontIdentity[], signal: AbortSignal) => Promise<BrowserFontResult>
71
92
  /** Called with unavailable declared OOXML families; binary DOC/PPT have no font diagnostics. */
72
93
  readonly onMissingFonts?: (families: readonly string[]) => void
73
94
  }
@@ -2,6 +2,7 @@
2
2
  import { inspectDocument } from '@deepseek-ai/libreoffice-kit/document-inspection'
3
3
  import { memoryFontConfig } from '@deepseek-ai/libreoffice-kit/font-config'
4
4
  import { createFontReader } from './font-channel.ts'
5
+ import { instantiatePreparedModule, preparedBrowserModule } from './preparation.ts'
5
6
  import { BrowserRenderError } from './types.ts'
6
7
  import type { BrowserRenderErrorCode, BrowserTileRequest } from './types.ts'
7
8
  import type { OwnerMessage, WorkerMessage, WorkerOptions } from './protocol.ts'
@@ -39,6 +40,7 @@ function error(code: BrowserRenderErrorCode): BrowserRenderError {
39
40
 
40
41
  async function open(options: WorkerOptions, channel: SharedArrayBuffer, reading = false): Promise<void> {
41
42
  const { assets } = options
43
+ const prepared = options.preparedEngine === undefined ? undefined : preparedBrowserModule(options.preparedEngine, assets)
42
44
  let metadata: ReturnType<typeof inspectDocument>
43
45
  try { metadata = options.extension === 'pdf' ? { families: new Map(), codePoints: [] } : inspectDocument(options.data, options.extension, options) } catch (failure) { throw new BrowserRenderError('invalid-document', failure instanceof Error ? failure.message : String(failure)) }
44
46
  const initialFont = { family: 'sans-serif', style: '', weight: 5, italic: 0, width: 5, pitch: 0, language: '', codePoints: [] }
@@ -66,6 +68,10 @@ async function open(options: WorkerOptions, channel: SharedArrayBuffer, reading
66
68
  }
67
69
  },
68
70
  getPreloadedPackage: () => data,
71
+ ...(prepared === undefined ? {} : { instantiateWasm(imports: WebAssembly.Imports,
72
+ receive: (instance: WebAssembly.Instance, compiled: WebAssembly.Module) => void) {
73
+ return instantiatePreparedModule(prepared, imports, receive)
74
+ } }),
69
75
  dshResolveSystemFontFaces(request: Parameters<NonNullable<typeof resolveFonts>>[0]) {
70
76
  if (!resolveFonts) throw new BrowserRenderError('font-unavailable', 'LibreOffice requested fonts before MEMFS initialization.')
71
77
  try { return resolveFonts(request) } catch (failure) { fontFailure = failure; throw failure }
@@ -79,7 +85,7 @@ async function open(options: WorkerOptions, channel: SharedArrayBuffer, reading
79
85
  if (initialFontPending) initialFontPending = false
80
86
  else send({ type: 'font', request, known })
81
87
  }, () => send({ type: 'font-next' }),
82
- (path, bytes) => loaded.FS.writeFile(path, bytes), families => send({ type: 'missing-fonts', families }))
88
+ (path, bytes) => loaded.FS.writeFile(path, bytes), families => send({ type: 'missing-fonts', families }), metadata.codePoints)
83
89
  if (options.extension === 'pdf') {
84
90
  for (const family of new Set(options.fontFallbacks.flat())) resolveFonts({ ...initialFont, family, mode: 'full' })
85
91
  } else resolveFonts(initialFont)
@@ -56,7 +56,7 @@ export function verifyBrowserPackage(target = directory, engineDirectory = join(
56
56
  for (const helper of helpers) regularFile(target, `lib/${helper}.js`);
57
57
  const declarations = join(target, 'lib/browser/types');
58
58
  const declarationText = readdirSync(declarations).filter(name => name.endsWith('.d.ts')).map(name => readFileSync(join(declarations, name), 'utf8')).join('\n');
59
- assert(declarationText.includes('openOfficeDocument') && !declarationText.includes('openEditor')
59
+ assert(declarationText.includes('openOfficeDocument') && declarationText.includes('prepareOfficeBrowser') && !declarationText.includes('openEditor')
60
60
  && !readdirSync(declarations).some(name => name.startsWith('editor')), 'Browser package retains a removed editing SDK');
61
61
  const receipt = readJson(regularFile(target, 'lib/browser/assets.json'));
62
62
  const worker = receipt.files?.worker;
@@ -89,7 +89,7 @@ export function verifyEngineMetadata(manifest, prebuild) {
89
89
  const exact = (actual, expected) => JSON.stringify(actual) === JSON.stringify(expected);
90
90
  if (prebuild.platform === 'wasm') {
91
91
  assert(manifest.os === undefined && manifest.cpu === undefined && manifest.libc === undefined, 'WASM package must install across operating systems, CPUs and libc variants');
92
- assert(engine?.kind === 'wasm' && engine.loader === 'assets/soffice.cjs' && engine.wasm === 'assets/soffice.wasm'
92
+ assert(engine?.kind === 'wasm' && engine.loader === 'assets/soffice.cjs' && engine.wasm === 'assets/dsh-office.wasm'
93
93
  && engine.data === 'assets/soffice.data' && engine.metadata === 'assets/soffice.data.js.metadata'
94
94
  && engine.programDirectory === '/instdir/program', 'Unsupported WASM engine paths');
95
95
  } else {