@deepseek-ai/libreoffice-kit 0.0.2-rc7 → 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 +1 -1
- package/README.zh.md +1 -1
- package/lib/browser/assets.json +2 -2
- package/lib/browser/index.js +297 -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 +2 -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/protocol.d.ts +32 -5
- package/lib/browser/types/types.d.ts +2 -0
- package/lib/browser/worker.js +286 -105
- package/lib/browser-assets.js +1 -1
- package/lib/cli.js +2 -2
- package/lib/index.js +2 -2
- package/lib/types/engine.d.ts +1 -1
- package/package.json +2 -2
- package/sources/browser/packages/browser/package.json +1 -1
- package/sources/browser/packages/browser/src/connection.ts +103 -37
- package/sources/browser/packages/browser/src/font-channel.ts +15 -6
- package/sources/browser/packages/browser/src/index.ts +2 -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/protocol.ts +18 -4
- package/sources/browser/packages/browser/src/types.ts +3 -0
- package/sources/browser/packages/browser/src/worker.ts +132 -53
- package/sources/browser/scripts/build-browser.mjs +6 -2
|
@@ -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
|
}
|
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
/** Private messages exchanged by the document owner and its single engine Worker. */
|
|
2
|
-
import type { BrowserDocumentOptions, BrowserFontIdentity, 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 }
|
|
@@ -93,6 +93,9 @@ export interface BrowserDocumentOptions {
|
|
|
93
93
|
readonly onMissingFonts?: (families: readonly string[]) => void
|
|
94
94
|
}
|
|
95
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
|
+
|
|
96
99
|
/** One Worker-owned, read-only Office document. */
|
|
97
100
|
export interface BrowserDocument {
|
|
98
101
|
/** Visible pages; Writer omits zero-area automatic section parity placeholders. */
|
|
@@ -1,11 +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
5
|
import { instantiatePreparedModule, preparedBrowserModule } from './preparation.ts'
|
|
6
6
|
import { BrowserRenderError } from './types.ts'
|
|
7
|
-
import type { BrowserRenderErrorCode, BrowserTileRequest } from './types.ts'
|
|
8
|
-
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'
|
|
9
9
|
import type { EnginePage } from './rendering.ts'
|
|
10
10
|
|
|
11
11
|
import type { EmscriptenModule } from './engine-types.ts'
|
|
@@ -17,6 +17,8 @@ interface EngineGlobal extends DedicatedWorkerGlobalScope {
|
|
|
17
17
|
createLibreOfficeModule(overrides: Record<string, unknown>): Promise<EmscriptenModule>
|
|
18
18
|
}
|
|
19
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: [] }
|
|
20
22
|
let module: EmscriptenModule | undefined
|
|
21
23
|
let office = 0
|
|
22
24
|
let document = 0
|
|
@@ -27,6 +29,12 @@ let fatal = false
|
|
|
27
29
|
let fontFailure: unknown
|
|
28
30
|
let serial = Promise.resolve()
|
|
29
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()
|
|
30
38
|
|
|
31
39
|
function send(message: WorkerMessage, transfer: Transferable[] = []): void { scope.postMessage(message, transfer) }
|
|
32
40
|
function call(name: string, args: number[]): number { return module!.ccall(name, 'number', args.map(() => 'number'), args) }
|
|
@@ -38,22 +46,33 @@ function error(code: BrowserRenderErrorCode): BrowserRenderError {
|
|
|
38
46
|
try { return new BrowserRenderError(code, module.UTF8ToString(pointer)) } finally { call('free', [pointer]) }
|
|
39
47
|
}
|
|
40
48
|
|
|
41
|
-
|
|
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> {
|
|
42
69
|
const { assets } = options
|
|
43
70
|
const prepared = options.preparedEngine === undefined ? undefined : preparedBrowserModule(options.preparedEngine, assets)
|
|
44
|
-
let metadata: ReturnType<typeof inspectDocument>
|
|
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)) }
|
|
46
|
-
const initialFont = { family: 'sans-serif', style: '', weight: 5, italic: 0, width: 5, pitch: 0, language: '', codePoints: [] }
|
|
47
|
-
let initialFontPending = options.extension !== 'pdf'
|
|
48
|
-
// Host font discovery runs while the engine downloads and compiles. The first
|
|
49
|
-
// synchronous font read consumes this response through the same bounded channel.
|
|
50
|
-
if (initialFontPending) send({ type: 'font', request: initialFont, known: [] })
|
|
51
71
|
const response = await fetch(assets.dataUrl, { credentials: 'same-origin', signal: lifetime.signal })
|
|
52
72
|
if (!response.ok) throw new BrowserRenderError('unavailable', `LibreOffice data request failed: ${response.status}`)
|
|
53
73
|
const data = await response.arrayBuffer()
|
|
54
74
|
scope.importScripts(assets.loaderUrl)
|
|
55
|
-
|
|
56
|
-
module = await scope.createLibreOfficeModule({
|
|
75
|
+
const created = await scope.createLibreOfficeModule({
|
|
57
76
|
noInitialRun: true,
|
|
58
77
|
dshOnCallback(type: number, payload: string) { reader?.callback(type, payload) },
|
|
59
78
|
mainScriptUrlOrBlob: assets.loaderUrl,
|
|
@@ -72,57 +91,99 @@ async function open(options: WorkerOptions, channel: SharedArrayBuffer, reading
|
|
|
72
91
|
receive: (instance: WebAssembly.Instance, compiled: WebAssembly.Module) => void) {
|
|
73
92
|
return instantiatePreparedModule(prepared, imports, receive)
|
|
74
93
|
} }),
|
|
75
|
-
dshResolveSystemFontFaces(request:
|
|
94
|
+
dshResolveSystemFontFaces(request: BrowserFontRequest) {
|
|
76
95
|
if (!resolveFonts) throw new BrowserRenderError('font-unavailable', 'LibreOffice requested fonts before MEMFS initialization.')
|
|
77
96
|
try { return resolveFonts(request) } catch (failure) { fontFailure = failure; throw failure }
|
|
78
97
|
},
|
|
79
98
|
preRun: [(loaded: EmscriptenModule) => {
|
|
80
99
|
for (const path of ['/dsh/profile', '/dsh/font-cache', '/dsh-fonts', '/usr/share/fonts/dsh-pdfium']) loaded.FS.mkdirTree(path)
|
|
81
|
-
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)
|
|
82
103
|
Object.assign(loaded.ENV, { HOME: '/dsh/profile', TMPDIR: '/tmp', FONTCONFIG_FILE: '/dsh/fonts.conf', LOK_HOST_ALLOWLIST: '^$' })
|
|
83
|
-
resolveFonts = createFontReader(channel, options.timeoutMs, options.maxLoadedFontBytes, metadata.families,
|
|
84
|
-
(request, known) => {
|
|
85
|
-
if (initialFontPending) initialFontPending = false
|
|
86
|
-
else send({ type: 'font', request, known })
|
|
87
|
-
}, () => send({ type: 'font-next' }),
|
|
88
|
-
(path, bytes) => loaded.FS.writeFile(path, bytes), families => send({ type: 'missing-fonts', families }), metadata.codePoints)
|
|
89
|
-
if (options.extension === 'pdf') {
|
|
90
|
-
for (const family of new Set(options.fontFallbacks.flat())) resolveFonts({ ...initialFont, family, mode: 'full' })
|
|
91
|
-
} else resolveFonts(initialFont)
|
|
92
104
|
}],
|
|
93
105
|
onAbort() { fatal = true },
|
|
94
106
|
print() {}, printErr() {},
|
|
95
107
|
})
|
|
96
|
-
|
|
97
|
-
|
|
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])
|
|
98
136
|
if (!pointer) throw error('invalid-document')
|
|
99
137
|
try {
|
|
100
|
-
new Uint8Array(
|
|
101
|
-
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, ''])
|
|
102
140
|
} finally { call('free', [pointer]) }
|
|
103
141
|
if (!pdf) throw error('invalid-document')
|
|
104
|
-
pages = pdfPages(
|
|
142
|
+
pages = pdfPages(loaded, pdf, () => error('invalid-document'))
|
|
105
143
|
return
|
|
106
144
|
}
|
|
107
145
|
const input = `/dsh/document.${options.extension}`
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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'])
|
|
112
150
|
if (!document || !call('dsh_lok_document_initialize_rendering', [document])) throw error('invalid-document')
|
|
113
151
|
const type = call('dsh_lok_document_type', [document])
|
|
114
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.')
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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
|
|
124
186
|
}
|
|
125
|
-
throw new BrowserRenderError('invalid-document', 'Office documents require a retained session.')
|
|
126
187
|
}
|
|
127
188
|
|
|
128
189
|
function render(request: BrowserTileRequest): { width: number; height: number; rgba: Uint8ClampedArray } {
|
|
@@ -131,22 +192,21 @@ function render(request: BrowserTileRequest): { width: number; height: number; r
|
|
|
131
192
|
return renderRegion(module, pdf, request, pages, () => error('render-failed'), true)
|
|
132
193
|
}
|
|
133
194
|
|
|
195
|
+
/** Destroy the office instance and every pthread after the documents are closed. */
|
|
134
196
|
function dispose(): void {
|
|
135
|
-
|
|
136
|
-
reader = undefined
|
|
197
|
+
closeDocument()
|
|
137
198
|
try {
|
|
138
|
-
if (module && !fatal) {
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
if (
|
|
199
|
+
if (module && !fatal && office) {
|
|
200
|
+
const value = office
|
|
201
|
+
office = 0
|
|
202
|
+
if (!call('dsh_lok_destroy', [value])) throw error('render-failed')
|
|
142
203
|
}
|
|
143
204
|
} finally {
|
|
144
205
|
module?.PThread.terminateAllThreads()
|
|
145
206
|
module = undefined
|
|
146
|
-
document = 0
|
|
147
|
-
pdf = 0
|
|
148
207
|
office = 0
|
|
149
208
|
pages = []
|
|
209
|
+
runtime = undefined
|
|
150
210
|
}
|
|
151
211
|
}
|
|
152
212
|
|
|
@@ -156,7 +216,26 @@ scope.onmessage = (event: MessageEvent<OwnerMessage>) => {
|
|
|
156
216
|
serial = serial.then(async () => {
|
|
157
217
|
try {
|
|
158
218
|
switch (message.type) {
|
|
159
|
-
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
|
+
}
|
|
160
239
|
case 'tile': { const tile = render(message.request); send({ type: 'tile', id: message.id, tile }, [tile.rgba.buffer]); break }
|
|
161
240
|
case 'office-tile': {
|
|
162
241
|
if (!reader) throw new BrowserRenderError('disposed', 'Office reader is closed.')
|
|
@@ -56,7 +56,8 @@ 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('
|
|
59
|
+
assert(declarationText.includes('openOfficeDocument') && declarationText.includes('openOfficeRuntime')
|
|
60
|
+
&& declarationText.includes('OfficeReadingState') && declarationText.includes('prepareOfficeBrowser') && !declarationText.includes('openEditor')
|
|
60
61
|
&& !readdirSync(declarations).some(name => name.startsWith('editor')), 'Browser package retains a removed editing SDK');
|
|
61
62
|
const receipt = readJson(regularFile(target, 'lib/browser/assets.json'));
|
|
62
63
|
const worker = receipt.files?.worker;
|
|
@@ -66,7 +67,10 @@ export function verifyBrowserPackage(target = directory, engineDirectory = join(
|
|
|
66
67
|
const engine = readJson(join(engineDirectory, 'prebuilds.json')).engine;
|
|
67
68
|
const module = new WebAssembly.Module(readFileSync(join(engineDirectory, engine.wasm)));
|
|
68
69
|
const exports = new Set(WebAssembly.Module.exports(module).map(entry => entry.name));
|
|
69
|
-
for (const name of ['dsh_lok_document_paint', 'dsh_lok_document_configure_view', 'dsh_lok_document_composition',
|
|
70
|
+
for (const name of ['dsh_lok_document_paint', 'dsh_lok_document_configure_view', 'dsh_lok_document_composition',
|
|
71
|
+
'dsh_lok_document_create_view', 'dsh_lok_document_part_info', 'dsh_lok_document_capture_reading_selection',
|
|
72
|
+
'dsh_lok_document_restore_reading_text_selection', 'dsh_lok_document_restore_reading_object_selection',
|
|
73
|
+
'dsh_pdf_open', 'dsh_pdf_paint'])
|
|
70
74
|
assert(exports.has(name) || exports.has(`_${name}`), `WASM has no browser export: ${name}`);
|
|
71
75
|
return receipt;
|
|
72
76
|
}
|