@deepseek-ai/libreoffice-kit 0.0.2-rc6 → 0.0.2-rc9
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 +2 -2
- package/README.zh.md +1 -1
- package/assets/font-subset.json +2 -2
- package/lib/browser/assets.json +2 -2
- package/lib/browser/index.js +333 -162
- package/lib/browser/types/connection.d.ts +28 -6
- package/lib/browser/types/font-channel.d.ts +16 -1
- package/lib/browser/types/index.d.ts +3 -2
- package/lib/browser/types/office-engine.d.ts +10 -2
- package/lib/browser/types/office-types.d.ts +60 -1
- package/lib/browser/types/office.d.ts +18 -3
- package/lib/browser/types/preparation.d.ts +13 -0
- package/lib/browser/types/protocol.d.ts +33 -10
- package/lib/browser/types/types.d.ts +31 -8
- package/lib/browser/worker.js +360 -106
- package/lib/browser-assets.js +1 -1
- package/lib/cli.js +2 -2
- package/lib/font-source.js +19 -1
- package/lib/font-worker.js +126 -29
- package/lib/index.js +2 -2
- package/lib/types/engine.d.ts +1 -1
- package/lib/types/font-source-types.d.ts +11 -0
- package/lib/types/font-subsets.d.ts +5 -1
- package/lib/types/fonts.d.ts +1 -0
- package/lib/types/office-fonts.d.ts +6 -0
- package/lib/worker.js +6 -5
- package/package.json +2 -2
- package/sources/browser/packages/browser/package.json +1 -1
- package/sources/browser/packages/browser/src/connection.ts +105 -34
- package/sources/browser/packages/browser/src/font-channel.ts +69 -9
- package/sources/browser/packages/browser/src/index.ts +3 -2
- package/sources/browser/packages/browser/src/office-engine.ts +80 -6
- package/sources/browser/packages/browser/src/office-types.ts +52 -1
- package/sources/browser/packages/browser/src/office.ts +118 -52
- package/sources/browser/packages/browser/src/preparation.ts +41 -0
- package/sources/browser/packages/browser/src/protocol.ts +19 -5
- package/sources/browser/packages/browser/src/types.ts +26 -2
- package/sources/browser/packages/browser/src/worker.ts +138 -53
- package/sources/browser/scripts/build-browser.mjs +6 -2
- package/sources/font-subset/scripts/verify-artifacts.mjs +1 -1
|
@@ -1,62 +1,128 @@
|
|
|
1
|
-
/** Browser owner for
|
|
2
|
-
import {
|
|
1
|
+
/** Browser owner for one shared engine Worker and its read-only Office documents. */
|
|
2
|
+
import { openBrowserWorker } from './connection.ts'
|
|
3
3
|
import { BrowserRenderError } from './types.ts'
|
|
4
|
-
import type {
|
|
4
|
+
import type { BrowserRuntimeOptions } from './types.ts'
|
|
5
|
+
import type { OfficeDocument, OfficeDocumentEvent, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult,
|
|
6
|
+
OfficeDocumentOpenOptions, OfficeDocumentState, OfficeReadingState, OfficeRuntime } from './office-types.ts'
|
|
5
7
|
import type { OfficeOperation } from './protocol.ts'
|
|
6
8
|
|
|
7
|
-
/**
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Start one read-only Office engine that opens documents one at a time.
|
|
11
|
+
* @param options - Engine resources and limits shared by every document.
|
|
12
|
+
* @param signal - Runtime lifetime; abort closes the Worker and its pthreads.
|
|
13
|
+
* @returns Sequential document loading and joined disposal.
|
|
14
|
+
*/
|
|
15
|
+
export async function openOfficeRuntime(options: BrowserRuntimeOptions, signal?: AbortSignal): Promise<OfficeRuntime> {
|
|
16
|
+
let current: { closed: boolean; readonly listeners: Set<(event: OfficeDocumentEvent) => void>;
|
|
17
|
+
update(state: OfficeDocumentState): void } | undefined
|
|
18
|
+
let disposed = false
|
|
19
|
+
const worker = await openBrowserWorker(options, signal, (event) => {
|
|
20
|
+
if (event.type === 'state') current?.update(event.state)
|
|
21
|
+
for (const listener of current?.listeners ?? []) {
|
|
14
22
|
try { listener(event) } catch (error) { console.error('Office document observer failed', error) }
|
|
15
23
|
}
|
|
16
24
|
})
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
25
|
+
const open = async (openOptions: OfficeDocumentOpenOptions, documentSignal?: AbortSignal): Promise<OfficeDocument> => {
|
|
26
|
+
if (disposed) throw new BrowserRenderError('disposed', 'The Office runtime is closed.')
|
|
27
|
+
if (current && !current.closed) current.closed = true
|
|
28
|
+
current?.listeners.clear()
|
|
29
|
+
current = undefined
|
|
30
|
+
await worker.closeDocument()
|
|
31
|
+
const opened = await worker.openDocument({ data: openOptions.data, extension: openOptions.extension,
|
|
32
|
+
resolveFonts: openOptions.resolveFonts,
|
|
33
|
+
...(openOptions.onMissingFonts === undefined ? {} : { onMissingFonts: openOptions.onMissingFonts }),
|
|
34
|
+
...(openOptions.restore === undefined ? {} : { restore: openOptions.restore }) }, documentSignal)
|
|
35
|
+
if (!opened.office) throw new BrowserRenderError('invalid-document', 'LibreOffice returned no reading state.')
|
|
36
|
+
let reading = opened.office
|
|
37
|
+
const record = { closed: false, listeners: new Set<(event: OfficeDocumentEvent) => void>(),
|
|
38
|
+
update(state: OfficeDocumentState): void { reading = state } }
|
|
39
|
+
current = record
|
|
40
|
+
async function operate(operation: OfficeOperation) {
|
|
41
|
+
if (record.closed) throw new BrowserRenderError('disposed', 'Office document is closed.')
|
|
42
|
+
const response = await worker.request({ type: 'office-operation', operation })
|
|
43
|
+
if (response.type !== 'office-result') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected reading response.')
|
|
44
|
+
return response
|
|
45
|
+
}
|
|
46
|
+
let layoutRunning = false
|
|
47
|
+
let pendingLayout: { request: OfficeDocumentLayoutRequest; waiters: ReturnType<typeof Promise.withResolvers<OfficeDocumentLayoutResult>>[] } | undefined
|
|
48
|
+
async function applyLayouts(): Promise<void> {
|
|
49
|
+
layoutRunning = true
|
|
50
|
+
while (pendingLayout) {
|
|
51
|
+
const next = pendingLayout
|
|
52
|
+
pendingLayout = undefined
|
|
53
|
+
try {
|
|
54
|
+
const response = await operate({ type: 'layout', request: next.request })
|
|
55
|
+
if (!response.layout) throw new BrowserRenderError('render-failed', 'LibreOffice returned no layout result.')
|
|
56
|
+
for (const waiter of next.waiters) waiter.resolve(response.layout)
|
|
57
|
+
} catch (error) { for (const waiter of next.waiters) waiter.reject(error) }
|
|
58
|
+
}
|
|
59
|
+
layoutRunning = false
|
|
60
|
+
}
|
|
61
|
+
const close = async (): Promise<void> => {
|
|
62
|
+
if (record.closed) return
|
|
63
|
+
record.closed = true
|
|
64
|
+
record.listeners.clear()
|
|
65
|
+
current = undefined
|
|
66
|
+
await worker.closeDocument()
|
|
67
|
+
}
|
|
68
|
+
let disposal: Promise<void> | undefined
|
|
69
|
+
return {
|
|
70
|
+
get state() { return reading },
|
|
71
|
+
subscribe(listener) { if (record.closed) return () => {}; record.listeners.add(listener); return () => { record.listeners.delete(listener) } },
|
|
72
|
+
async pointer(event) { await operate({ type: 'pointer', event }) },
|
|
73
|
+
async navigate(event) { await operate({ type: 'navigate', event }) },
|
|
74
|
+
async selectAll() { await operate({ type: 'select-all' }) },
|
|
75
|
+
async copy() { return (await operate({ type: 'copy' })).text ?? '' },
|
|
76
|
+
async goToCell(address) { await operate({ type: 'cell', address }) },
|
|
77
|
+
async setPart(part) { await operate({ type: 'part', part }) },
|
|
78
|
+
async setViewport(rectangle, scale) { await operate({ type: 'viewport', rectangle, scale }) },
|
|
79
|
+
setLayout(request) {
|
|
80
|
+
const waiter = Promise.withResolvers<OfficeDocumentLayoutResult>()
|
|
81
|
+
pendingLayout = { request, waiters: [...(pendingLayout?.waiters ?? []), waiter] }
|
|
82
|
+
if (!layoutRunning) void applyLayouts()
|
|
83
|
+
return waiter.promise
|
|
84
|
+
},
|
|
85
|
+
async renderTile(request, tileSignal) {
|
|
86
|
+
if (record.closed) throw new BrowserRenderError('disposed', 'Office document is closed.')
|
|
87
|
+
const response = await worker.request({ type: 'office-tile', request }, tileSignal)
|
|
88
|
+
if (response.type !== 'tile') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected tile response.')
|
|
89
|
+
return response.tile
|
|
90
|
+
},
|
|
91
|
+
async captureReadingState(): Promise<OfficeReadingState> {
|
|
92
|
+
if (record.closed) throw new BrowserRenderError('disposed', 'Office document is closed.')
|
|
93
|
+
const response = await worker.request({ type: 'reading-state' })
|
|
94
|
+
if (response.type !== 'reading-state') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected reading state.')
|
|
95
|
+
return response.state
|
|
96
|
+
},
|
|
97
|
+
close,
|
|
98
|
+
dispose() { return disposal ??= close().then(disposeRuntime) },
|
|
36
99
|
}
|
|
37
|
-
layoutRunning = false
|
|
38
100
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
101
|
+
const disposeRuntime = async (): Promise<void> => {
|
|
102
|
+
if (disposed) return
|
|
103
|
+
disposed = true
|
|
104
|
+
current?.listeners.clear()
|
|
105
|
+
if (current && !current.closed) current.closed = true
|
|
106
|
+
await worker.dispose()
|
|
107
|
+
}
|
|
108
|
+
return { open, dispose: disposeRuntime }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Open one read-only Office document in its own engine; the runtime ends with the document.
|
|
113
|
+
* @param options - Source bytes, engine resources and Host fonts.
|
|
114
|
+
* @param signal - Document lifetime; abort closes its Worker and pthreads.
|
|
115
|
+
* @returns Immutable reading state and disposal.
|
|
116
|
+
*/
|
|
117
|
+
export async function openOfficeDocument(options: BrowserRuntimeOptions & { readonly data: Uint8Array }
|
|
118
|
+
& Pick<OfficeDocumentOpenOptions, 'extension' | 'resolveFonts' | 'onMissingFonts'>, signal?: AbortSignal): Promise<OfficeDocument> {
|
|
119
|
+
const { data, extension, resolveFonts, onMissingFonts, ...runtime } = options
|
|
120
|
+
const office = await openOfficeRuntime(runtime, signal)
|
|
121
|
+
try {
|
|
122
|
+
return await office.open({ data, extension, resolveFonts,
|
|
123
|
+
...(onMissingFonts === undefined ? {} : { onMissingFonts }) }, signal)
|
|
124
|
+
} catch (error) {
|
|
125
|
+
await office.dispose()
|
|
126
|
+
throw error
|
|
61
127
|
}
|
|
62
128
|
}
|
|
@@ -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,11 +1,19 @@
|
|
|
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'
|
|
3
|
-
import type { OfficeDocumentEvent, OfficeDocumentNavigation, OfficeDocumentOptions, OfficeDocumentState, OfficeDocumentPointer, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult, OfficeDocumentTileRequest, OfficeDocumentRectangle } from './office-types.ts'
|
|
2
|
+
import type { BrowserDocumentOptions, BrowserFontIdentity, BrowserFontRequest, BrowserPage, BrowserRenderErrorCode, BrowserRuntimeOptions, BrowserTile, BrowserTileRequest } from './types.ts'
|
|
3
|
+
import type { OfficeDocumentEvent, OfficeDocumentNavigation, OfficeDocumentOptions, OfficeDocumentState, OfficeDocumentPointer, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult, OfficeDocumentTileRequest, OfficeDocumentRectangle, OfficeReadingState } from './office-types.ts'
|
|
4
4
|
|
|
5
5
|
export const FONT_CHUNK_BYTES = 1024 * 1024
|
|
6
6
|
export const FONT_HEADER_BYTES = 8
|
|
7
7
|
export const enum FontState { Waiting, Header, Bytes, Done, Error, Cancelled }
|
|
8
|
-
|
|
8
|
+
/** Engine resources a Worker holds for the lifetime of every document it opens. */
|
|
9
|
+
export type WorkerOptions = Omit<BrowserRuntimeOptions, 'resolveFonts' | 'onMissingFonts'>
|
|
10
|
+
/** Source bytes and reading position of one document opened inside a started Worker. */
|
|
11
|
+
export interface WorkerDocumentOptions {
|
|
12
|
+
readonly data: Uint8Array
|
|
13
|
+
readonly extension: BrowserDocumentOptions['extension'] | OfficeDocumentOptions['extension']
|
|
14
|
+
/** Reading position captured from an earlier open of the same bytes. */
|
|
15
|
+
readonly restore?: OfficeReadingState
|
|
16
|
+
}
|
|
9
17
|
export type OfficeOperation =
|
|
10
18
|
| { readonly type: 'pointer'; readonly event: OfficeDocumentPointer }
|
|
11
19
|
| { readonly type: 'navigate'; readonly event: OfficeDocumentNavigation }
|
|
@@ -16,7 +24,10 @@ export type OfficeOperation =
|
|
|
16
24
|
| { readonly type: 'viewport'; readonly rectangle: OfficeDocumentRectangle; readonly scale: number }
|
|
17
25
|
| { readonly type: 'layout'; readonly request: OfficeDocumentLayoutRequest }
|
|
18
26
|
export type OwnerMessage =
|
|
19
|
-
| { readonly type: '
|
|
27
|
+
| { readonly type: 'start'; readonly id: number; readonly options: WorkerOptions; readonly channel: SharedArrayBuffer }
|
|
28
|
+
| { readonly type: 'open'; readonly id: number; readonly options: WorkerDocumentOptions }
|
|
29
|
+
| { readonly type: 'close-document'; readonly id: number }
|
|
30
|
+
| { readonly type: 'reading-state'; readonly id: number }
|
|
20
31
|
| { readonly type: 'tile'; readonly id: number; readonly request: BrowserTileRequest }
|
|
21
32
|
| { readonly type: 'office-tile'; readonly id: number; readonly request: OfficeDocumentTileRequest }
|
|
22
33
|
| { readonly type: 'office-operation'; readonly id: number; readonly operation: OfficeOperation }
|
|
@@ -24,7 +35,10 @@ export type OwnerMessage =
|
|
|
24
35
|
type WithoutId<T> = T extends unknown ? Omit<T, 'id'> : never
|
|
25
36
|
export type OwnerRequest = WithoutId<OwnerMessage>
|
|
26
37
|
export type WorkerMessage =
|
|
38
|
+
| { readonly type: 'started'; readonly id: number }
|
|
27
39
|
| { readonly type: 'opened'; readonly id: number; readonly pages: readonly BrowserPage[]; readonly office?: OfficeDocumentState }
|
|
40
|
+
| { readonly type: 'closed-document'; readonly id: number }
|
|
41
|
+
| { readonly type: 'reading-state'; readonly id: number; readonly state: OfficeReadingState }
|
|
28
42
|
| { readonly type: 'tile'; readonly id: number; readonly tile: BrowserTile }
|
|
29
43
|
| { readonly type: 'office-result'; readonly id: number; readonly text?: string; readonly layout?: OfficeDocumentLayoutResult }
|
|
30
44
|
| { readonly type: 'office-event'; readonly event: OfficeDocumentEvent }
|
|
@@ -34,7 +48,7 @@ export type WorkerMessage =
|
|
|
34
48
|
| { readonly type: 'font-next' }
|
|
35
49
|
| { readonly type: 'missing-fonts'; readonly families: readonly string[] }
|
|
36
50
|
/** Immutable bytes already installed in this document's MEMFS. */
|
|
37
|
-
export
|
|
51
|
+
export type FontIdentity = BrowserFontIdentity
|
|
38
52
|
export interface FontHeader {
|
|
39
53
|
readonly fonts: readonly (FontIdentity & { readonly family: string; readonly alias: string; readonly reference?: true })[]
|
|
40
54
|
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
|
|
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,11 +88,14 @@ 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
|
}
|
|
74
95
|
|
|
96
|
+
/** Engine resources and limits one Worker holds for every document it opens. */
|
|
97
|
+
export type BrowserRuntimeOptions = Omit<BrowserDocumentOptions, 'data' | 'extension' | 'resolveFonts' | 'onMissingFonts'>
|
|
98
|
+
|
|
75
99
|
/** One Worker-owned, read-only Office document. */
|
|
76
100
|
export interface BrowserDocument {
|
|
77
101
|
/** Visible pages; Writer omits zero-area automatic section parity placeholders. */
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
/** Classic Worker entry: serializes one LibreOffice instance and
|
|
1
|
+
/** Classic Worker entry: serializes one LibreOffice instance, its documents and its pthreads. */
|
|
2
2
|
import { inspectDocument } from '@deepseek-ai/libreoffice-kit/document-inspection'
|
|
3
3
|
import { memoryFontConfig } from '@deepseek-ai/libreoffice-kit/font-config'
|
|
4
|
-
import { createFontReader } from './font-channel.ts'
|
|
4
|
+
import { createEngineFontCache, createFontReader, type EngineFontFace } from './font-channel.ts'
|
|
5
|
+
import { instantiatePreparedModule, preparedBrowserModule } from './preparation.ts'
|
|
5
6
|
import { BrowserRenderError } from './types.ts'
|
|
6
|
-
import type { BrowserRenderErrorCode, BrowserTileRequest } from './types.ts'
|
|
7
|
-
import type { OwnerMessage, WorkerMessage, WorkerOptions } from './protocol.ts'
|
|
7
|
+
import type { BrowserFontRequest, BrowserRenderErrorCode, BrowserTileRequest } from './types.ts'
|
|
8
|
+
import type { OwnerMessage, WorkerDocumentOptions, WorkerMessage, WorkerOptions } from './protocol.ts'
|
|
8
9
|
import type { EnginePage } from './rendering.ts'
|
|
9
10
|
|
|
10
11
|
import type { EmscriptenModule } from './engine-types.ts'
|
|
@@ -16,6 +17,8 @@ interface EngineGlobal extends DedicatedWorkerGlobalScope {
|
|
|
16
17
|
createLibreOfficeModule(overrides: Record<string, unknown>): Promise<EmscriptenModule>
|
|
17
18
|
}
|
|
18
19
|
const scope = globalThis as unknown as EngineGlobal
|
|
20
|
+
/** Host font request that installs a fallback face before LibreOffice resolves any family. */
|
|
21
|
+
const initialFont: BrowserFontRequest = { family: 'sans-serif', style: '', weight: 5, italic: 0, width: 5, pitch: 0, language: '', codePoints: [] }
|
|
19
22
|
let module: EmscriptenModule | undefined
|
|
20
23
|
let office = 0
|
|
21
24
|
let document = 0
|
|
@@ -26,6 +29,12 @@ let fatal = false
|
|
|
26
29
|
let fontFailure: unknown
|
|
27
30
|
let serial = Promise.resolve()
|
|
28
31
|
const lifetime = new AbortController()
|
|
32
|
+
let runtime: { options: WorkerOptions; channel: SharedArrayBuffer } | undefined
|
|
33
|
+
let resolveFonts: ((request: BrowserFontRequest) => EngineFontFace[]) | undefined
|
|
34
|
+
/** MEMFS path of the open document; removed when its model is released. */
|
|
35
|
+
let source: string | undefined
|
|
36
|
+
/** Font identities and files retained until this runtime is destroyed. */
|
|
37
|
+
const fontCache = createEngineFontCache()
|
|
29
38
|
|
|
30
39
|
function send(message: WorkerMessage, transfer: Transferable[] = []): void { scope.postMessage(message, transfer) }
|
|
31
40
|
function call(name: string, args: number[]): number { return module!.ccall(name, 'number', args.map(() => 'number'), args) }
|
|
@@ -37,21 +46,33 @@ function error(code: BrowserRenderErrorCode): BrowserRenderError {
|
|
|
37
46
|
try { return new BrowserRenderError(code, module.UTF8ToString(pointer)) } finally { call('free', [pointer]) }
|
|
38
47
|
}
|
|
39
48
|
|
|
40
|
-
|
|
49
|
+
/**
|
|
50
|
+
* Bind one document's declared families to the runtime's font channel.
|
|
51
|
+
* The first synchronous read of a request consumes the Host response that was
|
|
52
|
+
* requested before the engine's filesystem was configured.
|
|
53
|
+
*/
|
|
54
|
+
function installFonts(loaded: EmscriptenModule, options: WorkerOptions, families: ReadonlyMap<string, string>,
|
|
55
|
+
codePoints: readonly number[], consumeInitial: { pending: boolean }): (request: BrowserFontRequest) => EngineFontFace[] {
|
|
56
|
+
loaded.FS.writeFile('/dsh/fonts.conf', new TextEncoder().encode(memoryFontConfig(options.fontFallbacks, families.values())))
|
|
57
|
+
return createFontReader(runtime!.channel, options.timeoutMs, options.maxLoadedFontBytes, families,
|
|
58
|
+
(request, known) => {
|
|
59
|
+
if (consumeInitial.pending) consumeInitial.pending = false
|
|
60
|
+
else send({ type: 'font', request, known })
|
|
61
|
+
}, () => send({ type: 'font-next' }),
|
|
62
|
+
(path, bytes) => { loaded.FS.writeFile(path, bytes) },
|
|
63
|
+
missing => send({ type: 'missing-fonts', families: missing }), codePoints, fontCache)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Create this runtime's WASM module, filesystem configuration and office instance once. */
|
|
67
|
+
async function createEngine(options: WorkerOptions, families: ReadonlyMap<string, string>,
|
|
68
|
+
codePoints: readonly number[], consumeInitial: { pending: boolean }, portableDocument: boolean): Promise<void> {
|
|
41
69
|
const { assets } = options
|
|
42
|
-
|
|
43
|
-
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
|
-
const initialFont = { family: 'sans-serif', style: '', weight: 5, italic: 0, width: 5, pitch: 0, language: '', codePoints: [] }
|
|
45
|
-
let initialFontPending = options.extension !== 'pdf'
|
|
46
|
-
// Host font discovery runs while the engine downloads and compiles. The first
|
|
47
|
-
// synchronous font read consumes this response through the same bounded channel.
|
|
48
|
-
if (initialFontPending) send({ type: 'font', request: initialFont, known: [] })
|
|
70
|
+
const prepared = options.preparedEngine === undefined ? undefined : preparedBrowserModule(options.preparedEngine, assets)
|
|
49
71
|
const response = await fetch(assets.dataUrl, { credentials: 'same-origin', signal: lifetime.signal })
|
|
50
72
|
if (!response.ok) throw new BrowserRenderError('unavailable', `LibreOffice data request failed: ${response.status}`)
|
|
51
73
|
const data = await response.arrayBuffer()
|
|
52
74
|
scope.importScripts(assets.loaderUrl)
|
|
53
|
-
|
|
54
|
-
module = await scope.createLibreOfficeModule({
|
|
75
|
+
const created = await scope.createLibreOfficeModule({
|
|
55
76
|
noInitialRun: true,
|
|
56
77
|
dshOnCallback(type: number, payload: string) { reader?.callback(type, payload) },
|
|
57
78
|
mainScriptUrlOrBlob: assets.loaderUrl,
|
|
@@ -66,57 +87,103 @@ async function open(options: WorkerOptions, channel: SharedArrayBuffer, reading
|
|
|
66
87
|
}
|
|
67
88
|
},
|
|
68
89
|
getPreloadedPackage: () => data,
|
|
69
|
-
|
|
90
|
+
...(prepared === undefined ? {} : { instantiateWasm(imports: WebAssembly.Imports,
|
|
91
|
+
receive: (instance: WebAssembly.Instance, compiled: WebAssembly.Module) => void) {
|
|
92
|
+
return instantiatePreparedModule(prepared, imports, receive)
|
|
93
|
+
} }),
|
|
94
|
+
dshResolveSystemFontFaces(request: BrowserFontRequest) {
|
|
70
95
|
if (!resolveFonts) throw new BrowserRenderError('font-unavailable', 'LibreOffice requested fonts before MEMFS initialization.')
|
|
71
96
|
try { return resolveFonts(request) } catch (failure) { fontFailure = failure; throw failure }
|
|
72
97
|
},
|
|
73
98
|
preRun: [(loaded: EmscriptenModule) => {
|
|
74
99
|
for (const path of ['/dsh/profile', '/dsh/font-cache', '/dsh-fonts', '/usr/share/fonts/dsh-pdfium']) loaded.FS.mkdirTree(path)
|
|
75
|
-
loaded
|
|
100
|
+
resolveFonts = installFonts(loaded, options, families, codePoints, consumeInitial)
|
|
101
|
+
if (portableDocument) for (const family of new Set(options.fontFallbacks.flat())) resolveFonts({ ...initialFont, family, mode: 'full' })
|
|
102
|
+
else resolveFonts(initialFont)
|
|
76
103
|
Object.assign(loaded.ENV, { HOME: '/dsh/profile', TMPDIR: '/tmp', FONTCONFIG_FILE: '/dsh/fonts.conf', LOK_HOST_ALLOWLIST: '^$' })
|
|
77
|
-
resolveFonts = createFontReader(channel, options.timeoutMs, options.maxLoadedFontBytes, metadata.families,
|
|
78
|
-
(request, known) => {
|
|
79
|
-
if (initialFontPending) initialFontPending = false
|
|
80
|
-
else send({ type: 'font', request, known })
|
|
81
|
-
}, () => send({ type: 'font-next' }),
|
|
82
|
-
(path, bytes) => loaded.FS.writeFile(path, bytes), families => send({ type: 'missing-fonts', families }))
|
|
83
|
-
if (options.extension === 'pdf') {
|
|
84
|
-
for (const family of new Set(options.fontFallbacks.flat())) resolveFonts({ ...initialFont, family, mode: 'full' })
|
|
85
|
-
} else resolveFonts(initialFont)
|
|
86
104
|
}],
|
|
87
105
|
onAbort() { fatal = true },
|
|
88
106
|
print() {}, printErr() {},
|
|
89
107
|
})
|
|
90
|
-
|
|
91
|
-
|
|
108
|
+
module = created
|
|
109
|
+
office = created.ccall('dsh_lok_initialize', 'number', ['string', 'string'], [assets.programDirectory, 'file:///dsh/profile'])
|
|
110
|
+
if (!office) throw error('unavailable')
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Load one document into the already initialized engine. */
|
|
114
|
+
async function openDocument(options: WorkerDocumentOptions): Promise<void> {
|
|
115
|
+
if (!runtime) throw new BrowserRenderError('disposed', 'LibreOffice Worker has not been started.')
|
|
116
|
+
const engine = runtime.options
|
|
117
|
+
const reading = options.extension !== 'pdf'
|
|
118
|
+
let metadata: ReturnType<typeof inspectDocument>
|
|
119
|
+
try {
|
|
120
|
+
metadata = reading
|
|
121
|
+
? inspectDocument(options.data, options.extension, engine)
|
|
122
|
+
: { families: new Map(), codePoints: [] }
|
|
123
|
+
} catch (failure) { throw new BrowserRenderError('invalid-document', failure instanceof Error ? failure.message : String(failure)) }
|
|
124
|
+
// Host font discovery runs while the engine downloads and compiles. The first
|
|
125
|
+
// synchronous font read consumes this response through the same bounded channel.
|
|
126
|
+
if (reading) send({ type: 'font', request: initialFont, known: [] })
|
|
127
|
+
const consumeInitial = { pending: reading }
|
|
128
|
+
if (!module) await createEngine(engine, metadata.families, metadata.codePoints, consumeInitial, !reading)
|
|
129
|
+
else {
|
|
130
|
+
resolveFonts = installFonts(module, engine, metadata.families, metadata.codePoints, consumeInitial)
|
|
131
|
+
if (reading) resolveFonts(initialFont)
|
|
132
|
+
}
|
|
133
|
+
const loaded = module as EmscriptenModule
|
|
134
|
+
if (!reading) {
|
|
135
|
+
const pointer = loaded.ccall('malloc', 'number', ['number'], [options.data.byteLength])
|
|
92
136
|
if (!pointer) throw error('invalid-document')
|
|
93
137
|
try {
|
|
94
|
-
new Uint8Array(
|
|
95
|
-
pdf =
|
|
138
|
+
new Uint8Array(loaded.HEAPU32.buffer, pointer, options.data.byteLength).set(options.data)
|
|
139
|
+
pdf = loaded.ccall('dsh_pdf_open', 'number', ['number', 'number', 'string'], [pointer, options.data.byteLength, ''])
|
|
96
140
|
} finally { call('free', [pointer]) }
|
|
97
141
|
if (!pdf) throw error('invalid-document')
|
|
98
|
-
pages = pdfPages(
|
|
142
|
+
pages = pdfPages(loaded, pdf, () => error('invalid-document'))
|
|
99
143
|
return
|
|
100
144
|
}
|
|
101
145
|
const input = `/dsh/document.${options.extension}`
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
146
|
+
loaded.FS.writeFile(input, options.data)
|
|
147
|
+
source = input
|
|
148
|
+
document = loaded.ccall('dsh_lok_document_load', 'number', ['number', 'string', 'string'],
|
|
149
|
+
[office, `file://${input}`, 'ReadOnly=true,EnableMacrosExecution=false'])
|
|
106
150
|
if (!document || !call('dsh_lok_document_initialize_rendering', [document])) throw error('invalid-document')
|
|
107
151
|
const type = call('dsh_lok_document_type', [document])
|
|
108
152
|
if (type !== (options.extension === 'docx' || options.extension === 'doc' ? 0 : options.extension === 'xlsx' || options.extension === 'xls' ? 1 : 2)) throw new BrowserRenderError('invalid-document', 'The document type does not match its extension.')
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
153
|
+
const engineReader = reader = new OfficeEngine(loaded, document, options.extension as OfficeDocumentFormat,
|
|
154
|
+
event => send({ type: 'office-event', event }), failure => {
|
|
155
|
+
fatal ||= failure instanceof WebAssembly.RuntimeError
|
|
156
|
+
send({ type: 'office-event', event: { type: 'error', code: 'render-failed', message: failure instanceof Error ? failure.message : String(failure) } })
|
|
157
|
+
})
|
|
158
|
+
await engineReader.start()
|
|
159
|
+
if (options.restore) await engineReader.restore(options.restore)
|
|
160
|
+
pages = engineReader.state.parts.map((part, index) => ({ ...part, x: 0, y: 0, part: type === 0 ? -1 : index }))
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Release the open document's model, MEMFS bytes and installed fonts; keep the engine. */
|
|
164
|
+
function closeDocument(): void {
|
|
165
|
+
reader?.stop()
|
|
166
|
+
reader = undefined
|
|
167
|
+
try {
|
|
168
|
+
if (module && !fatal) {
|
|
169
|
+
if (pdf) { const value = pdf; pdf = 0; if (!call('dsh_pdf_destroy', [value])) throw error('render-failed') }
|
|
170
|
+
if (document) { const value = document; document = 0; if (!call('dsh_lok_document_destroy', [value])) throw error('render-failed') }
|
|
171
|
+
if (source !== undefined) unlink(source)
|
|
172
|
+
}
|
|
173
|
+
} finally {
|
|
174
|
+
resolveFonts = undefined
|
|
175
|
+
pages = []
|
|
176
|
+
source = undefined
|
|
177
|
+
document = 0
|
|
178
|
+
pdf = 0
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Remove one MEMFS path; a missing file means the engine already released it. */
|
|
183
|
+
function unlink(path: string): void {
|
|
184
|
+
try { module?.FS.unlink(path) } catch (failure: unknown) {
|
|
185
|
+
if (!(failure instanceof Error) || !/no such file|does not exist/i.test(failure.message)) throw failure
|
|
118
186
|
}
|
|
119
|
-
throw new BrowserRenderError('invalid-document', 'Office documents require a retained session.')
|
|
120
187
|
}
|
|
121
188
|
|
|
122
189
|
function render(request: BrowserTileRequest): { width: number; height: number; rgba: Uint8ClampedArray } {
|
|
@@ -125,22 +192,21 @@ function render(request: BrowserTileRequest): { width: number; height: number; r
|
|
|
125
192
|
return renderRegion(module, pdf, request, pages, () => error('render-failed'), true)
|
|
126
193
|
}
|
|
127
194
|
|
|
195
|
+
/** Destroy the office instance and every pthread after the documents are closed. */
|
|
128
196
|
function dispose(): void {
|
|
129
|
-
|
|
130
|
-
reader = undefined
|
|
197
|
+
closeDocument()
|
|
131
198
|
try {
|
|
132
|
-
if (module && !fatal) {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
if (
|
|
199
|
+
if (module && !fatal && office) {
|
|
200
|
+
const value = office
|
|
201
|
+
office = 0
|
|
202
|
+
if (!call('dsh_lok_destroy', [value])) throw error('render-failed')
|
|
136
203
|
}
|
|
137
204
|
} finally {
|
|
138
205
|
module?.PThread.terminateAllThreads()
|
|
139
206
|
module = undefined
|
|
140
|
-
document = 0
|
|
141
|
-
pdf = 0
|
|
142
207
|
office = 0
|
|
143
208
|
pages = []
|
|
209
|
+
runtime = undefined
|
|
144
210
|
}
|
|
145
211
|
}
|
|
146
212
|
|
|
@@ -150,7 +216,26 @@ scope.onmessage = (event: MessageEvent<OwnerMessage>) => {
|
|
|
150
216
|
serial = serial.then(async () => {
|
|
151
217
|
try {
|
|
152
218
|
switch (message.type) {
|
|
153
|
-
case '
|
|
219
|
+
case 'start': {
|
|
220
|
+
runtime = { options: message.options, channel: message.channel }
|
|
221
|
+
send({ type: 'started', id: message.id })
|
|
222
|
+
break
|
|
223
|
+
}
|
|
224
|
+
case 'open': {
|
|
225
|
+
// One document at a time: a caller that replaces its document without
|
|
226
|
+
// closing first still leaves the engine with a single loaded model.
|
|
227
|
+
if (document || pdf) closeDocument()
|
|
228
|
+
await openDocument(message.options)
|
|
229
|
+
send({ type: 'opened', id: message.id, pages: pages.map(({ width, height }) => ({ width, height })),
|
|
230
|
+
...(reader ? { office: reader.state } : {}) })
|
|
231
|
+
break
|
|
232
|
+
}
|
|
233
|
+
case 'close-document': closeDocument(); send({ type: 'closed-document', id: message.id }); break
|
|
234
|
+
case 'reading-state': {
|
|
235
|
+
if (!reader) throw new BrowserRenderError('disposed', 'Office document is closed.')
|
|
236
|
+
send({ type: 'reading-state', id: message.id, state: reader.capture() })
|
|
237
|
+
break
|
|
238
|
+
}
|
|
154
239
|
case 'tile': { const tile = render(message.request); send({ type: 'tile', id: message.id, tile }, [tile.rgba.buffer]); break }
|
|
155
240
|
case 'office-tile': {
|
|
156
241
|
if (!reader) throw new BrowserRenderError('disposed', 'Office reader is closed.')
|