@deepseek-ai/libreoffice-kit 0.0.2-rc4 → 0.0.2-rc5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/NOTICE +238 -0
  2. package/README.md +3 -3
  3. package/README.zh.md +3 -3
  4. package/lib/browser/assets.json +2 -2
  5. package/lib/browser/index.js +65 -58
  6. package/lib/browser/types/connection.d.ts +3 -3
  7. package/lib/browser/types/index.d.ts +2 -2
  8. package/lib/browser/types/office-engine.d.ts +46 -0
  9. package/lib/browser/types/office-types.d.ts +107 -0
  10. package/lib/browser/types/office.d.ts +4 -0
  11. package/lib/browser/types/protocol.d.ts +24 -32
  12. package/lib/browser/types/types.d.ts +3 -1
  13. package/lib/browser/worker.js +276 -489
  14. package/lib/browser-assets.js +1 -1
  15. package/lib/cli.js +91 -58
  16. package/lib/font-source.js +89 -56
  17. package/lib/font-worker.js +710 -39
  18. package/lib/index.js +91 -58
  19. package/lib/types/default-fonts.d.ts +3 -0
  20. package/lib/types/engine.d.ts +1 -1
  21. package/lib/types/font-preferences-data.d.ts +16 -0
  22. package/lib/types/font-preferences.d.ts +29 -0
  23. package/lib/types/font-source-types.d.ts +2 -0
  24. package/lib/types/fonts.d.ts +11 -8
  25. package/lib/types/options.d.ts +1 -1
  26. package/lib/worker.js +707 -37
  27. package/package.json +3 -3
  28. package/sources/browser/packages/browser/package.json +2 -2
  29. package/sources/browser/packages/browser/src/connection.ts +7 -9
  30. package/sources/browser/packages/browser/src/index.ts +3 -3
  31. package/sources/browser/packages/browser/src/office-engine.ts +299 -0
  32. package/sources/browser/packages/browser/src/office-types.ts +77 -0
  33. package/sources/browser/packages/browser/src/office.ts +62 -0
  34. package/sources/browser/packages/browser/src/protocol.ts +15 -16
  35. package/sources/browser/packages/browser/src/types.ts +3 -1
  36. package/sources/browser/packages/browser/src/worker.ts +25 -30
  37. package/sources/browser/scripts/build-browser.mjs +9 -1
  38. package/lib/browser/types/editor-engine.d.ts +0 -50
  39. package/lib/browser/types/editor-types.d.ts +0 -141
  40. package/lib/browser/types/editor.d.ts +0 -9
  41. package/sources/browser/packages/browser/src/editor-engine.ts +0 -382
  42. package/sources/browser/packages/browser/src/editor-types.ts +0 -106
  43. package/sources/browser/packages/browser/src/editor.ts +0 -55
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/libreoffice-kit",
3
- "description": "WASM Office editing, direct document images, and conversion for Node and browsers",
4
- "version": "0.0.2-rc4",
3
+ "description": "WASM Office previews, document images, and conversion for Node and browsers",
4
+ "version": "0.0.2-rc5",
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-rc4"
88
+ "@deepseek-ai/libreoffice-kit-wasm": "0.0.2-rc5"
89
89
  },
90
90
  "bin": {
91
91
  "libreoffice-kit": "./lib/cli.js"
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@deepseek-ai/libreoffice-kit-browser-internal",
3
- "version": "0.0.2-rc4",
3
+ "version": "0.0.2-rc5",
4
4
  "type": "module",
5
5
  "license": "MPL-2.0",
6
- "description": "Browser Worker LibreOffice rendering and persistent OOXML editing",
6
+ "description": "Browser Worker LibreOffice reading sessions and PDF rendering",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "git+https://github.com/deepseek-harness/libreoffice-kit.git",
@@ -4,7 +4,7 @@ import type { OwnerMessage, OwnerRequest, WorkerMessage, WorkerOptions } from '.
4
4
  import { fontFrames, fontViews } from './font-channel.ts'
5
5
  import { BrowserRenderError } from './types.ts'
6
6
  import type { BrowserDocumentOptions } from './types.ts'
7
- import type { BrowserEditorEvent, BrowserEditorOptions } from './editor-types.ts'
7
+ import type { OfficeDocumentEvent, OfficeDocumentOptions } from './office-types.ts'
8
8
 
9
9
  interface Pending {
10
10
  resolve(message: WorkerMessage): void
@@ -17,13 +17,12 @@ interface Pending {
17
17
  * @param signal - Document lifetime; abort closes its Worker and all pending work.
18
18
  * @returns Initial geometry, ordered Worker requests and joined disposal.
19
19
  */
20
- export async function openBrowserConnection(options: BrowserDocumentOptions | BrowserEditorOptions, signal?: AbortSignal,
21
- editing = false, onEvent?: (event: BrowserEditorEvent) => void) {
20
+ export async function openBrowserConnection(options: BrowserDocumentOptions | OfficeDocumentOptions, signal?: AbortSignal,
21
+ office = false, onEvent?: (event: OfficeDocumentEvent) => void) {
22
22
  signal?.throwIfAborted()
23
23
  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
24
  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
- if (!(editing ? ['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.')
26
- if (['doc', 'xls', 'ppt'].includes(options.extension) && !('readOnly' in options && options.readOnly === true)) throw new BrowserRenderError('invalid-document', 'Legacy Office documents require readOnly mode.')
25
+ 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
26
  const worker = new Worker(options.assets.workerUrl, { name: 'libreoffice-document' })
28
27
  const channel = new SharedArrayBuffer(FONT_HEADER_BYTES + FONT_CHUNK_BYTES)
29
28
  const { control, bytes } = fontViews(channel)
@@ -62,7 +61,7 @@ export async function openBrowserConnection(options: BrowserDocumentOptions | Br
62
61
  worker.onmessage = (event: MessageEvent<WorkerMessage>) => {
63
62
  const message = event.data
64
63
  switch (message.type) {
65
- case 'editor-event': if (!closed) { onEvent?.(message.event); if (message.event.type === 'error') void dispose() }; return
64
+ case 'office-event': if (!closed) { onEvent?.(message.event); if (message.event.type === 'error') void dispose() }; return
66
65
  case 'font':
67
66
  if (closed) return
68
67
  void Promise.resolve().then(() => options.resolveFonts(message.request, lifetime.signal)).then(result => {
@@ -137,9 +136,8 @@ export async function openBrowserConnection(options: BrowserDocumentOptions | Br
137
136
 
138
137
  try {
139
138
  const data = new Uint8Array(options.data)
140
- 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
- ...('readOnly' in options && options.readOnly !== undefined ? { readOnly: options.readOnly } : {}) }
142
- const result = await post({ type: 'open', id: ++sequence, options: engineOptions, channel, ...(editing ? { editing: true } : {}) }, [data.buffer])
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 }
140
+ const result = await post({ type: 'open', id: ++sequence, options: engineOptions, channel, ...(office ? { office: true } : {}) }, [data.buffer])
143
141
  if (result.type !== 'opened') throw new BrowserRenderError('invalid-document', 'LibreOffice returned an unexpected load response.')
144
142
  opened = result
145
143
  if (opened.type !== 'opened' || opened.pages.length === 0) throw new BrowserRenderError('invalid-document', 'LibreOffice returned no document pages.')
@@ -1,10 +1,10 @@
1
- /** Browser Office preview and persistent editing entry points. */
1
+ /** Browser Office preview and retained reading entry points. */
2
2
  import { openBrowserConnection } from './connection.ts'
3
3
  import { BrowserRenderError } from './types.ts'
4
4
  import type { BrowserDocument, BrowserDocumentOptions, BrowserTile, BrowserTileRequest } from './types.ts'
5
5
  export { BrowserRenderError } from './types.ts'
6
- export { openEditor } from './editor.ts'
7
- export type * from './editor-types.ts'
6
+ export { openOfficeDocument } from './office.ts'
7
+ export type * from './office-types.ts'
8
8
  export type { BrowserDocument, BrowserDocumentOptions, BrowserEngineAssets, BrowserFontRequest, BrowserFontResult, BrowserPage, BrowserRenderErrorCode, BrowserTile, BrowserTileRequest } from './types.ts'
9
9
 
10
10
  /**
@@ -0,0 +1,299 @@
1
+ /** Worker-owned reading, bounded VCL event slices and immutable notifications. */
2
+ import { BrowserRenderError } from './types.ts'
3
+ import type { BrowserTile } from './types.ts'
4
+ import type { EmscriptenModule } from './engine-types.ts'
5
+ import type { OfficeOperation } from './protocol.ts'
6
+ import type { OfficeDocumentEvent, OfficeDocumentFormat, OfficeDocumentState, OfficeDocumentTileRequest, OfficeDocumentRectangle, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult } from './office-types.ts'
7
+ import { parseCellRange } from '@deepseek-ai/libreoffice-kit/internal/sheet-geometry'
8
+ import { renderRegion } from './engine-rendering.ts'
9
+ import { TWIPS_PER_CSS_PIXEL, writerPages } from './rendering.ts'
10
+
11
+ function rectangle(payload: string): OfficeDocumentRectangle | null {
12
+ if (payload.startsWith('{')) {
13
+ const value: unknown = JSON.parse(payload)
14
+ if (typeof value !== 'object' || value === null || !('rectangle' in value) || typeof value.rectangle !== 'string') return null
15
+ payload = value.rectangle
16
+ }
17
+ if (!payload || payload.startsWith('EMPTY') || payload === 'INPLACE') return null
18
+ const values = payload.split(',').slice(0, 4).map(Number)
19
+ if (values.length !== 4 || values.some(value => !Number.isFinite(value))) return null
20
+ const [x, y, width, height] = values.map(value => value / TWIPS_PER_CSS_PIXEL) as [number, number, number, number]
21
+ return width >= 0 && height >= 0 ? { x, y, width, height } : null
22
+ }
23
+
24
+ function integer(value: number, max = 0x7fffffff): number {
25
+ if (!Number.isSafeInteger(value) || value < 0 || value > max) throw new BrowserRenderError('render-failed', 'Office input contains an invalid integer.')
26
+ return value
27
+ }
28
+
29
+ function twips(value: number): number {
30
+ if (!Number.isFinite(value) || Math.abs(value * TWIPS_PER_CSS_PIXEL) > 0x7fffffff) throw new BrowserRenderError('render-failed', 'Office input lies outside document coordinates.')
31
+ return Math.round(value * TWIPS_PER_CSS_PIXEL)
32
+ }
33
+
34
+ const navigationKeys = { down: 0x400, up: 0x401, left: 0x402, right: 0x403, home: 0x404, end: 0x405, pageUp: 0x406, pageDown: 0x407 } as const
35
+
36
+ /** One read-only document, driven exclusively by its Worker's messages and timer. */
37
+ export class OfficeEngine {
38
+ state: OfficeDocumentState
39
+ private timer: ReturnType<typeof setTimeout> | undefined
40
+ private readonly callbacks: { type: number; payload: string }[] = []
41
+ private geometryDirty = false
42
+ private stopped = false
43
+ private layoutWidth = 0
44
+ private viewport = ''
45
+ private commandResult: { name: string; resolve: () => void; reject: (error: unknown) => void } | undefined
46
+
47
+ constructor(private readonly module: EmscriptenModule, private readonly document: number,
48
+ format: OfficeDocumentFormat, private readonly emit: (event: OfficeDocumentEvent) => void,
49
+ private readonly failure: (error: unknown) => void) {
50
+ this.state = { documentType: format === 'docx' || format === 'doc' ? 'text' : format === 'xlsx' || format === 'xls' ? 'spreadsheet' : 'presentation',
51
+ renderGeneration: 0, layoutGeneration: 0, layout: 'paginated', part: 0, parts: [], pages: [], cursor: null,
52
+ selection: [], graphicSelection: null, cellAddress: '', cellFormula: '' }
53
+ }
54
+
55
+ private call(name: string, args: (number | string)[] = []): number {
56
+ return this.module.ccall(name, 'number', args.map(value => typeof value), args)
57
+ }
58
+ private text(name: string, args: (number | string)[]): string {
59
+ const pointer = this.call(name, args)
60
+ if (!pointer) return ''
61
+ try { return this.module.UTF8ToString(pointer) } finally { this.call('free', [pointer]) }
62
+ }
63
+ private invoke(name: string, args: (number | string)[] = []): void {
64
+ if (!this.call(`dsh_lok_document_${name}`, [this.document, ...args])) throw new BrowserRenderError('render-failed', `LibreOffice could not complete ${name}.`)
65
+ }
66
+ private requireOpen(): void {
67
+ if (this.stopped) throw new BrowserRenderError('disposed', 'Office document is closed.')
68
+ }
69
+ /** Collect callbacks without reentering LibreOffice inside its callback. */
70
+ callback(type: number, payload: string): void { if (!this.stopped) this.callbacks.push({ type, payload }) }
71
+ /** Enforce the native read-only view before accepting any input. */
72
+ async start(): Promise<void> {
73
+ this.requireOpen()
74
+ this.configure({ mode: 'paginated' })
75
+ this.invoke('listen')
76
+ this.refreshGeometry()
77
+ this.pump()
78
+ this.schedule()
79
+ await this.command('.uno:ReportWhenIdle', { idleID: { type: 'string', value: 'office-open' } })
80
+ }
81
+ private schedule(): void {
82
+ this.timer = setTimeout(() => {
83
+ if (this.stopped) return
84
+ try { this.pump(); this.schedule() } catch (error) { this.stop(); this.failure(error) }
85
+ }, 16)
86
+ }
87
+ /** Stop event processing before destroying the document. */
88
+ stop(): void {
89
+ this.stopped = true
90
+ clearTimeout(this.timer)
91
+ this.callbacks.length = 0
92
+ this.commandResult?.reject(new BrowserRenderError('disposed', 'Office document is closed.'))
93
+ this.commandResult = undefined
94
+ }
95
+ /** Return the part whose cached coordinates changed, or -1 when part identities changed. */
96
+ private refreshGeometry(): number | undefined {
97
+ const count = this.state.documentType === 'text' ? 1 : this.call('dsh_lok_document_parts', [this.document])
98
+ if (!Number.isSafeInteger(count) || count <= 0) throw new BrowserRenderError('invalid-document', 'Office document has no parts.')
99
+ const pointer = this.call('malloc', [8])
100
+ if (!pointer) throw new BrowserRenderError('render-failed', 'Office geometry allocation failed.')
101
+ try {
102
+ const part = Math.min(this.state.part, count - 1)
103
+ this.invoke('size', [part, pointer, pointer + 4])
104
+ const width = this.module.HEAPU32[pointer / 4]! / TWIPS_PER_CSS_PIXEL
105
+ const height = this.module.HEAPU32[pointer / 4 + 1]! / TWIPS_PER_CSS_PIXEL
106
+ if (!(width > 0 && height > 0)) throw new BrowserRenderError('invalid-document', 'Office returned empty document dimensions.')
107
+ // Measure the selected part only, preserving navigation and selection.
108
+ const parts = Array.from({ length: count }, (_, index) => ({
109
+ name: this.state.documentType === 'text' ? '' : this.text('dsh_lok_document_part_name', [this.document, index]),
110
+ width: index === part ? width : this.state.parts[index]?.width ?? width,
111
+ height: index === part ? height : this.state.parts[index]?.height ?? height,
112
+ }))
113
+ const pages = this.state.documentType !== 'text' ? [] : this.state.layout === 'continuous'
114
+ ? [{ x: 0, y: 0, width, height }]
115
+ : writerPages(this.text('dsh_lok_document_page_rectangles', [this.document])).map(page => ({ x: page.x / TWIPS_PER_CSS_PIXEL,
116
+ y: page.y / TWIPS_PER_CSS_PIXEL, width: page.width, height: page.height }))
117
+ const previous = this.state
118
+ const identitiesChanged = previous.parts.length > 0 && (previous.parts.length !== parts.length
119
+ || parts.some((value, index) => value.name !== previous.parts[index]!.name))
120
+ const measured = previous.parts[part]
121
+ const geometryChanged = measured !== undefined && (measured.width !== width || measured.height !== height
122
+ || JSON.stringify(previous.pages) !== JSON.stringify(pages))
123
+ this.state = { ...previous, part, parts, pages }
124
+ this.geometryDirty = false
125
+ return identitiesChanged ? -1 : geometryChanged ? part : undefined
126
+ } finally { this.call('free', [pointer]) }
127
+ }
128
+ private pump(): void {
129
+ const deadline = performance.now() + 8
130
+ for (let pass = 0; pass < 8; pass++) {
131
+ const result = this.call('dsh_lok_pump')
132
+ if (result < 0) throw new BrowserRenderError('render-failed', 'LibreOffice event processing failed.')
133
+ if (!result || performance.now() >= deadline) break
134
+ }
135
+ this.flush()
136
+ }
137
+ private flush(): void {
138
+ if (this.callbacks.length === 0) return
139
+ let changed = false
140
+ const invalidations: { part: number; rectangle: OfficeDocumentRectangle | null }[] = []
141
+ for (const { type, payload } of this.callbacks.splice(0)) {
142
+ switch (type) {
143
+ case 0: {
144
+ const fields = payload.split(',')
145
+ const index = fields[0]?.trim() === 'EMPTY' ? fields[1] : fields[4]
146
+ const part = index !== undefined && /^\s*-?\d+\s*$/.test(index) ? Number(index) : this.state.part
147
+ invalidations.push({ part, rectangle: rectangle(payload) })
148
+ break
149
+ }
150
+ case 1: case 17: this.state = { ...this.state, cursor: rectangle(payload) }; changed = true; break
151
+ case 2: this.state = { ...this.state, selection: payload.split(';').map(rectangle).filter((value): value is OfficeDocumentRectangle => value !== null) }; changed = true; break
152
+ case 6: this.state = { ...this.state, graphicSelection: rectangle(payload) }; changed = true; break
153
+ case 13: this.geometryDirty = true; break
154
+ case 14: {
155
+ const part = Number(payload)
156
+ if (Number.isSafeInteger(part) && part >= 0 && part < this.state.parts.length) {
157
+ this.state = { ...this.state, part }; this.viewport = ''; this.geometryDirty = true; changed = true
158
+ }
159
+ break
160
+ }
161
+ case 16: {
162
+ const result: unknown = JSON.parse(payload)
163
+ if (typeof result === 'object' && result !== null && 'commandName' in result && result.commandName === this.commandResult?.name) this.commandResult?.resolve()
164
+ break
165
+ }
166
+ case 19: this.state = { ...this.state, cellFormula: payload }; changed = true; break
167
+ case 34: this.state = { ...this.state, cellAddress: payload }; changed = true; break
168
+ }
169
+ }
170
+ const geometry = this.geometryDirty ? this.refreshGeometry() : undefined
171
+ if (geometry !== undefined) {
172
+ this.state = { ...this.state, layoutGeneration: this.state.layoutGeneration + 1 }
173
+ // A size notification need not be accompanied by LOK tile invalidation.
174
+ // Keep other sheets' pixels, but never reuse coordinates from an old layout.
175
+ if (!invalidations.some(value => value.rectangle === null && (value.part === -1 || value.part === geometry))) {
176
+ for (let index = invalidations.length - 1; index >= 0; index--) {
177
+ if (geometry === -1 || invalidations[index]!.part === geometry) invalidations.splice(index, 1)
178
+ }
179
+ invalidations.push({ part: geometry, rectangle: null })
180
+ }
181
+ }
182
+ if (invalidations.length > 0) {
183
+ this.state = { ...this.state, renderGeneration: this.state.renderGeneration + 1 }
184
+ changed = true
185
+ }
186
+ if (changed) this.emit({ type: 'state', state: this.state })
187
+ for (const invalidation of invalidations) this.emit({ type: 'invalidate', ...invalidation, generation: this.state.renderGeneration })
188
+ }
189
+ /** The Worker permits only these typed reading operations, including at runtime. */
190
+ async operation(operation: OfficeOperation): Promise<{ text?: string; layout?: OfficeDocumentLayoutResult }> {
191
+ this.requireOpen()
192
+ if (!operation || typeof operation !== 'object') throw new BrowserRenderError('render-failed', 'Invalid Office reading operation.')
193
+ switch (operation.type) {
194
+ case 'pointer': {
195
+ const event = operation.event
196
+ if (!event || !['down', 'up', 'move'].includes(event.action) || ![0, 1].includes(event.buttons)
197
+ || ![0, 0x1000, 0x2000, 0x3000].includes(event.modifiers)) throw new BrowserRenderError('render-failed', 'Invalid Office selection pointer.')
198
+ this.invoke('mouse', [event.action === 'down' ? 0 : event.action === 'up' ? 1 : 2,
199
+ twips(event.x), twips(event.y), integer(event.clicks, 3), event.buttons, event.modifiers])
200
+ break
201
+ }
202
+ case 'navigate': {
203
+ const event = operation.event
204
+ if (!event || !Object.hasOwn(navigationKeys, event.key)
205
+ || (event.extend !== undefined && typeof event.extend !== 'boolean') || (event.word !== undefined && typeof event.word !== 'boolean')) {
206
+ throw new BrowserRenderError('render-failed', 'Invalid Office navigation key.')
207
+ }
208
+ const key = navigationKeys[event.key] | (event.extend ? 0x1000 : 0) | (event.word ? 0x2000 : 0)
209
+ this.invoke('key', [0, 0, key]); this.invoke('key', [1, 0, key])
210
+ break
211
+ }
212
+ case 'select-all': await this.command('.uno:SelectAll', {}); break
213
+ case 'cell': {
214
+ if (this.state.documentType !== 'spreadsheet' || typeof operation.address !== 'string') throw new BrowserRenderError('render-failed', 'Cell navigation requires a spreadsheet address.')
215
+ try { parseCellRange(operation.address) } catch { throw new BrowserRenderError('render-failed', 'Cell navigation requires a bounded A1 cell or range.') }
216
+ await this.command('.uno:GoToCell', { ToPoint: { type: 'string', value: operation.address } })
217
+ break
218
+ }
219
+ case 'copy': this.pump(); return { text: this.text('dsh_lok_document_selection', [this.document]) }
220
+ case 'part': {
221
+ const part = integer(operation.part, this.state.parts.length - 1)
222
+ if (part === this.state.part) break
223
+ this.invoke('part', [part])
224
+ this.viewport = ''
225
+ this.state = { ...this.state, part, cursor: null, selection: [], graphicSelection: null, cellAddress: '', cellFormula: '' }
226
+ const geometry = this.refreshGeometry()
227
+ if (geometry !== undefined) this.state = { ...this.state, layoutGeneration: this.state.layoutGeneration + 1,
228
+ renderGeneration: this.state.renderGeneration + 1 }
229
+ this.emit({ type: 'state', state: this.state })
230
+ if (geometry !== undefined) this.emit({ type: 'invalidate', part: geometry, rectangle: null, generation: this.state.renderGeneration })
231
+ break
232
+ }
233
+ case 'viewport': {
234
+ const { x, y, width, height } = operation.rectangle
235
+ if (!(operation.scale > 0 && operation.scale <= 16 && width > 0 && height > 0)) throw new BrowserRenderError('render-failed', 'Office viewport is invalid.')
236
+ const args = [Math.max(1, Math.round(256 * operation.scale)), 256 * TWIPS_PER_CSS_PIXEL, twips(x), twips(y), twips(width), twips(height)]
237
+ const key = args.join(',')
238
+ if (key !== this.viewport) { this.invoke('viewport', args); this.viewport = key }
239
+ break
240
+ }
241
+ case 'layout': {
242
+ const request = operation.request
243
+ if (!request || !['paginated', 'continuous'].includes(request.mode) || (request.mode === 'continuous' && this.state.documentType !== 'text')) {
244
+ throw new BrowserRenderError('render-failed', 'Continuous layout is only available for Writer documents.')
245
+ }
246
+ const width = request.mode === 'continuous' ? twips(request.width) : 0
247
+ if (request.mode === 'continuous' && width <= 0) throw new BrowserRenderError('render-failed', 'Continuous layout requires a positive width.')
248
+ if (request.anchor && (twips(request.anchor.x) < 0 || twips(request.anchor.y) < 0)) throw new BrowserRenderError('render-failed', 'Reading anchors must lie within positive document coordinates.')
249
+ if (request.mode === this.state.layout && width === this.layoutWidth) return { layout: { changed: false } }
250
+ const result = this.configure(request)
251
+ this.layoutWidth = width
252
+ this.viewport = ''
253
+ this.state = { ...this.state, layout: request.mode, layoutGeneration: this.state.layoutGeneration + 1,
254
+ renderGeneration: this.state.renderGeneration + 1 }
255
+ // Establish the requested layout before its acknowledgement pumps any
256
+ // matching size callback; that callback must not invalidate it twice.
257
+ this.refreshGeometry()
258
+ await this.command('.uno:ReportWhenIdle', { idleID: { type: 'string', value: 'office-layout' } })
259
+ this.refreshGeometry()
260
+ this.emit({ type: 'state', state: this.state })
261
+ this.emit({ type: 'invalidate', part: -1, rectangle: null, generation: this.state.renderGeneration })
262
+ return { layout: result }
263
+ }
264
+ default: throw new BrowserRenderError('render-failed', 'Unsupported Office reading operation.')
265
+ }
266
+ this.pump()
267
+ return {}
268
+ }
269
+ private configure(request: OfficeDocumentLayoutRequest): OfficeDocumentLayoutResult {
270
+ const raw = this.text('dsh_lok_document_configure_view', [this.document, 1, request.mode === 'continuous' ? 1 : 0,
271
+ request.mode === 'continuous' ? twips(request.width) : 0, request.anchor ? twips(request.anchor.x) : -1, request.anchor ? twips(request.anchor.y) : -1])
272
+ if (!raw) throw new BrowserRenderError('render-failed', 'LibreOffice could not configure its read-only view.')
273
+ const result = JSON.parse(raw) as { changed: boolean; width: number; height: number; anchor?: OfficeDocumentRectangle }
274
+ if (typeof result.changed !== 'boolean' || !(result.width > 0 && result.height > 0)) throw new BrowserRenderError('render-failed', 'LibreOffice returned an invalid reading layout.')
275
+ if (result.anchor === undefined) return { changed: result.changed }
276
+ const { x, y, width, height } = result.anchor
277
+ if (![x, y, width, height].every(value => Number.isFinite(value) && value >= 0)) throw new BrowserRenderError('render-failed', 'LibreOffice returned an invalid reading anchor.')
278
+ return { changed: result.changed, anchor: { x: x / TWIPS_PER_CSS_PIXEL, y: y / TWIPS_PER_CSS_PIXEL,
279
+ width: width / TWIPS_PER_CSS_PIXEL, height: height / TWIPS_PER_CSS_PIXEL } }
280
+ }
281
+ /** Internal whitelist commands only; no arbitrary command crosses the public API. */
282
+ private async command(name: '.uno:ReportWhenIdle' | '.uno:SelectAll' | '.uno:GoToCell', args: unknown): Promise<void> {
283
+ const result = Promise.withResolvers<void>()
284
+ this.commandResult = { name, resolve: () => result.resolve(), reject: result.reject }
285
+ try { this.invoke('command', [name, JSON.stringify(args)]); this.pump(); await result.promise }
286
+ finally { this.commandResult = undefined }
287
+ }
288
+ /** Direct tiles preserve the active view, navigation state and selection. */
289
+ render(request: OfficeDocumentTileRequest): BrowserTile {
290
+ this.requireOpen()
291
+ this.flush()
292
+ const part = this.state.parts[integer(request.part, this.state.parts.length - 1)]!
293
+ if (request.part !== this.state.part) throw new BrowserRenderError('stale-part', 'The Office tile belongs to an inactive worksheet or slide.')
294
+ try {
295
+ return renderRegion(this.module, this.document, { ...request, pageIndex: 0 }, [{ ...part, x: 0, y: 0,
296
+ part: this.state.documentType === 'text' ? -1 : request.part }], () => new BrowserRenderError('render-failed', 'Office tile rendering failed.'))
297
+ } finally { this.flush() }
298
+ }
299
+ }
@@ -0,0 +1,77 @@
1
+ /** Retained Office reading sessions; this API never exposes document mutation. */
2
+ import type { BrowserDocumentOptions, BrowserPage, BrowserRenderErrorCode, BrowserTile } from './types.ts'
3
+
4
+ /** Office containers supported by the reading engine. */
5
+ export type OfficeDocumentFormat = 'doc' | 'docx' | 'xls' | 'xlsx' | 'ppt' | 'pptx'
6
+ /** Source bytes, engine resources and Host fonts; all sessions are read-only. */
7
+ export type OfficeDocumentOptions = Omit<BrowserDocumentOptions, 'extension'> & { readonly extension: OfficeDocumentFormat }
8
+ /** Document coordinates in CSS pixels at 96 DPI, independent of zoom. */
9
+ export interface OfficeDocumentRectangle extends BrowserPage { readonly x: number; readonly y: number }
10
+ /** One Writer document, Calc worksheet or Impress slide. */
11
+ export interface OfficeDocumentPart extends BrowserPage { readonly name: string }
12
+ /** Writer layout; other document types always remain paginated. */
13
+ export type OfficeDocumentLayout = 'paginated' | 'continuous'
14
+ /** A point in the previous layout, normally the upper visible line of body text. */
15
+ export interface OfficeDocumentAnchor { readonly x: number; readonly y: number }
16
+ /** Continuous width is the available content width in document CSS pixels. */
17
+ export type OfficeDocumentLayoutRequest =
18
+ | { readonly mode: 'paginated'; readonly anchor?: OfficeDocumentAnchor }
19
+ | { readonly mode: 'continuous'; readonly width: number; readonly anchor?: OfficeDocumentAnchor }
20
+ /** An optional body-text rectangle in the new layout for restoring reading position. */
21
+ export interface OfficeDocumentLayoutResult { readonly changed: boolean; readonly anchor?: OfficeDocumentRectangle }
22
+ /** Geometry and selection; cursor is a navigation/cell rectangle, never an editing caret. */
23
+ export interface OfficeDocumentState {
24
+ readonly documentType: 'text' | 'spreadsheet' | 'presentation'
25
+ readonly renderGeneration: number
26
+ readonly layoutGeneration: number
27
+ readonly layout: OfficeDocumentLayout
28
+ readonly part: number
29
+ readonly parts: readonly OfficeDocumentPart[]
30
+ /** Writer page rectangles in paginated mode; one continuous rectangle otherwise. */
31
+ readonly pages: readonly OfficeDocumentRectangle[]
32
+ readonly cursor: OfficeDocumentRectangle | null
33
+ readonly selection: readonly OfficeDocumentRectangle[]
34
+ readonly graphicSelection: OfficeDocumentRectangle | null
35
+ readonly cellAddress: string
36
+ readonly cellFormula: string
37
+ }
38
+ /** Primary-button selection; modifiers use LOK Shift (0x1000) / Control (0x2000). */
39
+ export interface OfficeDocumentPointer {
40
+ readonly action: 'down' | 'up' | 'move'
41
+ readonly x: number
42
+ readonly y: number
43
+ readonly buttons: number
44
+ readonly modifiers: number
45
+ readonly clicks: number
46
+ }
47
+ /** Only navigation keys are accepted; no arbitrary character or key injection. */
48
+ export interface OfficeDocumentNavigation {
49
+ readonly key: 'left' | 'right' | 'up' | 'down' | 'home' | 'end' | 'pageUp' | 'pageDown'
50
+ readonly extend?: boolean
51
+ readonly word?: boolean
52
+ }
53
+ /** One region of the current part. Pixel density does not change document layout. */
54
+ export interface OfficeDocumentTileRequest extends OfficeDocumentRectangle { readonly part: number; readonly scale: number }
55
+ /** A null rectangle invalidates an entire part; negative part means every part. */
56
+ export type OfficeDocumentEvent =
57
+ | { readonly type: 'state'; readonly state: OfficeDocumentState }
58
+ | { readonly type: 'invalidate'; readonly part: number; readonly rectangle: OfficeDocumentRectangle | null; readonly generation: number }
59
+ | { readonly type: 'error'; readonly code: BrowserRenderErrorCode; readonly message: string }
60
+ /** Retain this session while hidden; dispose only when the document is closed. */
61
+ export interface OfficeDocument {
62
+ readonly state: OfficeDocumentState
63
+ subscribe(listener: (event: OfficeDocumentEvent) => void): () => void
64
+ pointer(event: OfficeDocumentPointer): Promise<void>
65
+ navigate(event: OfficeDocumentNavigation): Promise<void>
66
+ selectAll(): Promise<void>
67
+ copy(): Promise<string>
68
+ /** Select a bounded A1 cell or range on the current worksheet. */
69
+ goToCell(address: string): Promise<void>
70
+ setPart(part: number): Promise<void>
71
+ setViewport(rectangle: OfficeDocumentRectangle, scale: number): Promise<void>
72
+ /** Coalesces pending widths; superseded callers observe the newest applied layout. */
73
+ setLayout(request: OfficeDocumentLayoutRequest): Promise<OfficeDocumentLayoutResult>
74
+ /** Only the current part can be painted; queued requests for a former part reject with stale-part without changing selection. */
75
+ renderTile(request: OfficeDocumentTileRequest, signal?: AbortSignal): Promise<BrowserTile>
76
+ dispose(): Promise<void>
77
+ }
@@ -0,0 +1,62 @@
1
+ /** Browser owner for a retained read-only Office model. */
2
+ import { openBrowserConnection } from './connection.ts'
3
+ import { BrowserRenderError } from './types.ts'
4
+ import type { OfficeDocument, OfficeDocumentEvent, OfficeDocumentOptions, OfficeDocumentState, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult } from './office-types.ts'
5
+ import type { OfficeOperation } from './protocol.ts'
6
+
7
+ /** Open one read-only Office model; source bytes remain owned by the caller. */
8
+ export async function openOfficeDocument(options: OfficeDocumentOptions, signal?: AbortSignal): Promise<OfficeDocument> {
9
+ const listeners = new Set<(event: OfficeDocumentEvent) => void>()
10
+ let state: OfficeDocumentState | undefined
11
+ const connection = await openBrowserConnection(options, signal, true, (event) => {
12
+ if (event.type === 'state') state = event.state
13
+ for (const listener of listeners) {
14
+ try { listener(event) } catch (error) { console.error('Office document observer failed', error) }
15
+ }
16
+ })
17
+ state = connection.opened.office
18
+ if (!state) { await connection.dispose(); throw new BrowserRenderError('invalid-document', 'LibreOffice returned no reading state.') }
19
+ async function operate(operation: OfficeOperation) {
20
+ const response = await connection.request({ type: 'office-operation', operation })
21
+ if (response.type !== 'office-result') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected reading response.')
22
+ return response
23
+ }
24
+ let layoutRunning = false
25
+ let pendingLayout: { request: OfficeDocumentLayoutRequest; waiters: ReturnType<typeof Promise.withResolvers<OfficeDocumentLayoutResult>>[] } | undefined
26
+ async function applyLayouts(): Promise<void> {
27
+ layoutRunning = true
28
+ while (pendingLayout) {
29
+ const next = pendingLayout
30
+ pendingLayout = undefined
31
+ try {
32
+ const response = await operate({ type: 'layout', request: next.request })
33
+ if (!response.layout) throw new BrowserRenderError('render-failed', 'LibreOffice returned no layout result.')
34
+ for (const waiter of next.waiters) waiter.resolve(response.layout)
35
+ } catch (error) { for (const waiter of next.waiters) waiter.reject(error) }
36
+ }
37
+ layoutRunning = false
38
+ }
39
+ return {
40
+ get state() { return state! },
41
+ subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener) } },
42
+ async pointer(event) { await operate({ type: 'pointer', event }) },
43
+ async navigate(event) { await operate({ type: 'navigate', event }) },
44
+ async selectAll() { await operate({ type: 'select-all' }) },
45
+ async copy() { return (await operate({ type: 'copy' })).text ?? '' },
46
+ async goToCell(address) { await operate({ type: 'cell', address }) },
47
+ async setPart(part) { await operate({ type: 'part', part }) },
48
+ async setViewport(rectangle, scale) { await operate({ type: 'viewport', rectangle, scale }) },
49
+ setLayout(request) {
50
+ const waiter = Promise.withResolvers<OfficeDocumentLayoutResult>()
51
+ pendingLayout = { request, waiters: [...(pendingLayout?.waiters ?? []), waiter] }
52
+ if (!layoutRunning) void applyLayouts()
53
+ return waiter.promise
54
+ },
55
+ async renderTile(request, tileSignal) {
56
+ const response = await connection.request({ type: 'office-tile', request }, tileSignal)
57
+ if (response.type !== 'tile') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected tile response.')
58
+ return response.tile
59
+ },
60
+ dispose() { listeners.clear(); return connection.dispose() },
61
+ }
62
+ }
@@ -1,34 +1,33 @@
1
1
  /** Private messages exchanged by the document owner and its single engine Worker. */
2
2
  import type { BrowserDocumentOptions, BrowserFontRequest, BrowserPage, BrowserRenderErrorCode, BrowserTile, BrowserTileRequest } from './types.ts'
3
- import type { BrowserCommandArguments, BrowserEditorCapture, BrowserEditorCaptureRequest, BrowserEditorEvent, BrowserEditorInput, BrowserEditorOptions, BrowserEditorSnapshot, BrowserEditorState, BrowserEditorTileRequest, BrowserRectangle } from './editor-types.ts'
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
6
6
  export const FONT_HEADER_BYTES = 8
7
7
  export const enum FontState { Waiting, Header, Bytes, Done, Error, Cancelled }
8
- export type WorkerOptions = Omit<BrowserDocumentOptions | BrowserEditorOptions, 'resolveFonts' | 'onMissingFonts'> & { readonly readOnly?: boolean }
9
- export type EditorOperation =
10
- | { readonly type: 'input'; readonly event: BrowserEditorInput }
11
- | { readonly type: 'command'; readonly command: string; readonly arguments?: BrowserCommandArguments }
12
- | { readonly type: 'paste'; readonly text: string }
8
+ export type WorkerOptions = Omit<BrowserDocumentOptions | OfficeDocumentOptions, 'resolveFonts' | 'onMissingFonts'>
9
+ export type OfficeOperation =
10
+ | { readonly type: 'pointer'; readonly event: OfficeDocumentPointer }
11
+ | { readonly type: 'navigate'; readonly event: OfficeDocumentNavigation }
12
+ | { readonly type: 'select-all' }
13
+ | { readonly type: 'cell'; readonly address: string }
13
14
  | { readonly type: 'copy' }
14
15
  | { readonly type: 'part'; readonly part: number }
15
- | { readonly type: 'viewport'; readonly rectangle: BrowserRectangle; readonly scale: number }
16
- | { readonly type: 'save' }
16
+ | { readonly type: 'viewport'; readonly rectangle: OfficeDocumentRectangle; readonly scale: number }
17
+ | { readonly type: 'layout'; readonly request: OfficeDocumentLayoutRequest }
17
18
  export type OwnerMessage =
18
- | { readonly type: 'open'; readonly id: number; readonly options: WorkerOptions; readonly channel: SharedArrayBuffer; readonly editing?: boolean }
19
+ | { readonly type: 'open'; readonly id: number; readonly options: WorkerOptions; readonly channel: SharedArrayBuffer; readonly office?: boolean }
19
20
  | { readonly type: 'tile'; readonly id: number; readonly request: BrowserTileRequest }
20
- | { readonly type: 'editor-tile'; readonly id: number; readonly request: BrowserEditorTileRequest }
21
- | { readonly type: 'capture'; readonly id: number; readonly request: BrowserEditorCaptureRequest }
22
- | { readonly type: 'edit'; readonly id: number; readonly operation: EditorOperation }
21
+ | { readonly type: 'office-tile'; readonly id: number; readonly request: OfficeDocumentTileRequest }
22
+ | { readonly type: 'office-operation'; readonly id: number; readonly operation: OfficeOperation }
23
23
  | { readonly type: 'dispose'; readonly id: number }
24
24
  type WithoutId<T> = T extends unknown ? Omit<T, 'id'> : never
25
25
  export type OwnerRequest = WithoutId<OwnerMessage>
26
26
  export type WorkerMessage =
27
- | { readonly type: 'opened'; readonly id: number; readonly pages: readonly BrowserPage[]; readonly editor?: BrowserEditorState }
27
+ | { readonly type: 'opened'; readonly id: number; readonly pages: readonly BrowserPage[]; readonly office?: OfficeDocumentState }
28
28
  | { readonly type: 'tile'; readonly id: number; readonly tile: BrowserTile }
29
- | { readonly type: 'captured'; readonly id: number; readonly capture: BrowserEditorCapture }
30
- | { readonly type: 'edited'; readonly id: number; readonly text?: string; readonly snapshot?: BrowserEditorSnapshot }
31
- | { readonly type: 'editor-event'; readonly event: BrowserEditorEvent }
29
+ | { readonly type: 'office-result'; readonly id: number; readonly text?: string; readonly layout?: OfficeDocumentLayoutResult }
30
+ | { readonly type: 'office-event'; readonly event: OfficeDocumentEvent }
32
31
  | { readonly type: 'disposed'; readonly id: number }
33
32
  | { readonly type: 'error'; readonly id: number; readonly code: BrowserRenderErrorCode; readonly message: string; readonly fatal: boolean }
34
33
  | { readonly type: 'font'; readonly request: BrowserFontRequest }
@@ -27,6 +27,8 @@ export interface BrowserFontRequest {
27
27
  export interface BrowserFontResult {
28
28
  readonly fonts: readonly { readonly id: string; readonly data: Uint8Array; readonly family: string; readonly alias: string; readonly format?: 'ttf' | 'otf' | 'ttc' }[]
29
29
  readonly missingFamily?: string
30
+ /** Missing scalars reported by the Host, independently of a substituted family. */
31
+ readonly unresolvedCodePoints?: readonly number[]
30
32
  }
31
33
 
32
34
  /** All sizes are CSS pixels at 96 pixels per inch. */
@@ -81,7 +83,7 @@ export interface BrowserDocument {
81
83
  }
82
84
 
83
85
  /** Stable failures callers may map to their own localized product copy. */
84
- export type BrowserRenderErrorCode = 'unavailable' | 'invalid-document' | 'timeout' | 'font-limit' | 'font-unavailable' | 'disposed' | 'render-failed' | 'snapshot-changed'
86
+ export type BrowserRenderErrorCode = 'unavailable' | 'invalid-document' | 'timeout' | 'font-limit' | 'font-unavailable' | 'disposed' | 'render-failed' | 'stale-part'
85
87
 
86
88
  /** A rendering failure with a stable machine-readable category. */
87
89
  export class BrowserRenderError extends Error {