@deepseek-ai/libreoffice-kit 0.0.1 → 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 (94) hide show
  1. package/NOTICE +240 -0
  2. package/README.md +43 -47
  3. package/README.zh.md +35 -50
  4. package/assets/font-subset.json +70 -0
  5. package/assets/font-subset.wasm +0 -0
  6. package/lib/browser/assets.json +10 -0
  7. package/lib/browser/index.js +442 -0
  8. package/lib/browser/types/connection.d.ts +20 -0
  9. package/lib/browser/types/engine-rendering.d.ts +3 -0
  10. package/lib/browser/types/engine-types.d.ts +17 -0
  11. package/lib/browser/types/font-channel.d.ts +20 -0
  12. package/lib/browser/types/index.d.ts +13 -0
  13. package/lib/browser/types/office-engine.d.ts +46 -0
  14. package/lib/browser/types/office-types.d.ts +107 -0
  15. package/lib/browser/types/office.d.ts +4 -0
  16. package/lib/browser/types/protocol.d.ts +109 -0
  17. package/lib/browser/types/rendering.d.ts +4 -0
  18. package/lib/browser/types/types.d.ts +92 -0
  19. package/lib/browser/types/worker.d.ts +2 -0
  20. package/lib/browser/worker.js +3498 -0
  21. package/lib/browser-assets.js +119 -0
  22. package/lib/cli.js +1336 -0
  23. package/lib/document.js +178 -0
  24. package/lib/engine-rendering.js +120 -0
  25. package/lib/font-config.js +46 -0
  26. package/lib/font-source.js +377 -0
  27. package/lib/font-worker.js +1383 -0
  28. package/lib/index.js +408 -165
  29. package/lib/rendering.js +99 -0
  30. package/lib/sheet-geometry.js +111 -0
  31. package/lib/types/browser-assets.d.ts +15 -0
  32. package/lib/types/cli.d.ts +3 -0
  33. package/lib/types/default-fonts.d.ts +3 -0
  34. package/lib/types/document.d.ts +1 -1
  35. package/lib/types/engine-rendering.d.ts +15 -0
  36. package/lib/types/engine.d.ts +5 -5
  37. package/lib/types/font-config.d.ts +24 -0
  38. package/lib/types/font-full.d.ts +13 -0
  39. package/lib/types/font-loader.d.ts +1 -7
  40. package/lib/types/font-preferences-data.d.ts +16 -0
  41. package/lib/types/font-preferences.d.ts +29 -0
  42. package/lib/types/font-request.d.ts +12 -0
  43. package/lib/types/font-source-types.d.ts +84 -0
  44. package/lib/types/font-source.d.ts +10 -0
  45. package/lib/types/font-subsets.d.ts +35 -0
  46. package/lib/types/font-worker.d.ts +2 -0
  47. package/lib/types/fonts.d.ts +20 -37
  48. package/lib/types/harfbuzz-subset.d.ts +11 -0
  49. package/lib/types/image-operations.d.ts +58 -0
  50. package/lib/types/image-renderer.d.ts +6 -0
  51. package/lib/types/index.d.ts +25 -2
  52. package/lib/types/native.d.ts +4 -2
  53. package/lib/types/operations.d.ts +41 -0
  54. package/lib/types/options.d.ts +1 -1
  55. package/lib/types/png.d.ts +2 -0
  56. package/lib/types/profile.d.ts +8 -0
  57. package/lib/types/rendering.d.ts +41 -0
  58. package/lib/types/runtime.d.ts +14 -0
  59. package/lib/types/sheet-geometry.d.ts +38 -0
  60. package/lib/types/unicode-scripts.d.ts +18 -0
  61. package/lib/types/wasm.d.ts +76 -1
  62. package/lib/types/worker.d.ts +3 -0
  63. package/lib/worker.js +1716 -271
  64. package/licenses/font-subset/harfbuzz-COPYING +42 -0
  65. package/licenses/font-subset/harfbuzzjs-LICENSE +19 -0
  66. package/licenses/javascript/fflate-LICENSE +21 -0
  67. package/licenses/javascript/saxes-LICENSE +64 -0
  68. package/licenses/javascript/xmlchars-LICENSE +18 -0
  69. package/package.json +59 -12
  70. package/sources/browser/packages/browser/package.json +22 -0
  71. package/sources/browser/packages/browser/src/connection.ts +166 -0
  72. package/sources/browser/packages/browser/src/engine-rendering.ts +2 -0
  73. package/sources/browser/packages/browser/src/engine-types.ts +14 -0
  74. package/sources/browser/packages/browser/src/font-channel.ts +99 -0
  75. package/sources/browser/packages/browser/src/index.ts +39 -0
  76. package/sources/browser/packages/browser/src/office-engine.ts +299 -0
  77. package/sources/browser/packages/browser/src/office-types.ts +77 -0
  78. package/sources/browser/packages/browser/src/office.ts +62 -0
  79. package/sources/browser/packages/browser/src/protocol.ts +39 -0
  80. package/sources/browser/packages/browser/src/rendering.ts +3 -0
  81. package/sources/browser/packages/browser/src/types.ts +94 -0
  82. package/sources/browser/packages/browser/src/worker.ts +166 -0
  83. package/sources/browser/packages/browser/tsconfig.json +5 -0
  84. package/sources/browser/packages/browser/tsdown.config.ts +7 -0
  85. package/sources/browser/scripts/build-browser.mjs +82 -0
  86. package/sources/font-subset/engine/font-subset/README.md +23 -0
  87. package/sources/font-subset/engine/font-subset/README.zh.md +23 -0
  88. package/sources/font-subset/engine/font-subset/source.json +16 -0
  89. package/sources/font-subset/harfbuzzjs/config-override-subset.h +7 -0
  90. package/sources/font-subset/harfbuzzjs/harfbuzz-subset.symbols +34 -0
  91. package/sources/font-subset/scripts/build-font-subset.mjs +64 -0
  92. package/sources/font-subset/scripts/pack-utils.mjs +69 -0
  93. package/sources/font-subset/scripts/platform-matrix.mjs +100 -0
  94. package/sources/font-subset/scripts/verify-artifacts.mjs +260 -0
@@ -0,0 +1,42 @@
1
+ HarfBuzz is licensed under the so-called "Old MIT" license. Details follow.
2
+ For parts of HarfBuzz that are licensed under different licenses see individual
3
+ files names COPYING in subdirectories where applicable.
4
+
5
+ Copyright © 2010-2022 Google, Inc.
6
+ Copyright © 2015-2020 Ebrahim Byagowi
7
+ Copyright © 2019,2020 Facebook, Inc.
8
+ Copyright © 2012,2015 Mozilla Foundation
9
+ Copyright © 2011 Codethink Limited
10
+ Copyright © 2008,2010 Nokia Corporation and/or its subsidiary(-ies)
11
+ Copyright © 2009 Keith Stribley
12
+ Copyright © 2011 Martin Hosken and SIL International
13
+ Copyright © 2007 Chris Wilson
14
+ Copyright © 2005,2006,2020,2021,2022,2023 Behdad Esfahbod
15
+ Copyright © 2004,2007,2008,2009,2010,2013,2021,2022,2023 Red Hat, Inc.
16
+ Copyright © 1998-2005 David Turner and Werner Lemberg
17
+ Copyright © 2016 Igalia S.L.
18
+ Copyright © 2022 Matthias Clasen
19
+ Copyright © 2018,2021 Khaled Hosny
20
+ Copyright © 2018,2019,2020 Adobe, Inc
21
+ Copyright © 2013-2015 Alexei Podtelezhnikov
22
+
23
+ For full copyright notices consult the individual files in the package.
24
+
25
+
26
+ Permission is hereby granted, without written agreement and without
27
+ license or royalty fees, to use, copy, modify, and distribute this
28
+ software and its documentation for any purpose, provided that the
29
+ above copyright notice and the following two paragraphs appear in
30
+ all copies of this software.
31
+
32
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
33
+ DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
34
+ ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
35
+ IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
36
+ DAMAGE.
37
+
38
+ THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
39
+ BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
40
+ FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
41
+ ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
42
+ PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2019-2026 The harfbuzzjs project authors
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Arjun Barrett
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,64 @@
1
+ The ISC License
2
+
3
+ Copyright (c) Contributors
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
15
+ IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
+
17
+ ====
18
+
19
+ The following license is the one that governed sax, from which saxes
20
+ was forked. Isaac Schlueter is not *directly* involved with saxes so
21
+ don't go bugging him for saxes issues.
22
+
23
+ The ISC License
24
+
25
+ Copyright (c) Isaac Z. Schlueter and Contributors
26
+
27
+ Permission to use, copy, modify, and/or distribute this software for any
28
+ purpose with or without fee is hereby granted, provided that the above
29
+ copyright notice and this permission notice appear in all copies.
30
+
31
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
32
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
33
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
34
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
35
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
36
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
37
+ IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38
+
39
+ ====
40
+
41
+ `String.fromCodePoint` by Mathias Bynens is no longer used, but it can
42
+ still be found in old commits. It was once used according to terms of
43
+ MIT License, as follows:
44
+
45
+ Copyright Mathias Bynens <https://mathiasbynens.be/>
46
+
47
+ Permission is hereby granted, free of charge, to any person obtaining
48
+ a copy of this software and associated documentation files (the
49
+ "Software"), to deal in the Software without restriction, including
50
+ without limitation the rights to use, copy, modify, merge, publish,
51
+ distribute, sublicense, and/or sell copies of the Software, and to
52
+ permit persons to whom the Software is furnished to do so, subject to
53
+ the following conditions:
54
+
55
+ The above copyright notice and this permission notice shall be
56
+ included in all copies or substantial portions of the Software.
57
+
58
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
59
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
60
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
61
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
62
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
63
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
64
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,18 @@
1
+ Copyright Louis-Dominique Dubeau and contributors to xmlchars
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ this software and associated documentation files (the "Software"), to deal in
5
+ the Software without restriction, including without limitation the rights to
6
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7
+ the Software, and to permit persons to whom the Software is furnished to do so,
8
+ subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/libreoffice-kit",
3
- "description": "Convert on-disk Office documents to PDF with prebuilt LibreOffice",
4
- "version": "0.0.1",
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
  },
@@ -22,25 +22,72 @@
22
22
  "types": "./lib/types/index.d.ts",
23
23
  "default": "./lib/index.js"
24
24
  },
25
- "./package.json": "./package.json"
25
+ "./package.json": "./package.json",
26
+ "./fonts": {
27
+ "types": "./lib/types/font-source.d.ts",
28
+ "default": "./lib/font-source.js"
29
+ },
30
+ "./font-config": {
31
+ "types": "./lib/types/font-config.d.ts",
32
+ "default": "./lib/font-config.js"
33
+ },
34
+ "./document-inspection": {
35
+ "types": "./lib/types/document.d.ts",
36
+ "default": "./lib/document.js"
37
+ },
38
+ "./cli": "./lib/cli.js",
39
+ "./browser-assets": {
40
+ "types": "./lib/types/browser-assets.d.ts",
41
+ "default": "./lib/browser-assets.js"
42
+ },
43
+ "./internal/rendering": {
44
+ "types": "./lib/types/rendering.d.ts",
45
+ "default": "./lib/rendering.js"
46
+ },
47
+ "./internal/engine-rendering": {
48
+ "types": "./lib/types/engine-rendering.d.ts",
49
+ "default": "./lib/engine-rendering.js"
50
+ },
51
+ "./internal/sheet-geometry": {
52
+ "types": "./lib/types/sheet-geometry.d.ts",
53
+ "default": "./lib/sheet-geometry.js"
54
+ },
55
+ "./browser": {
56
+ "types": "./lib/browser/types/index.d.ts",
57
+ "import": "./lib/browser/index.js"
58
+ }
26
59
  },
27
60
  "files": [
28
61
  "README.zh.md",
29
62
  "lib/index.js",
63
+ "lib/cli.js",
30
64
  "lib/worker.js",
31
65
  "NOTICE",
32
- "lib/types/**/*.d.ts"
66
+ "lib/types/**/*.d.ts",
67
+ "lib/font-source.js",
68
+ "lib/font-worker.js",
69
+ "lib/font-config.js",
70
+ "lib/document.js",
71
+ "assets/font-subset.wasm",
72
+ "assets/font-subset.json",
73
+ "sources/font-subset/",
74
+ "licenses/font-subset/",
75
+ "lib/browser-assets.js",
76
+ "lib/rendering.js",
77
+ "lib/engine-rendering.js",
78
+ "lib/sheet-geometry.js",
79
+ "lib/browser/",
80
+ "sources/browser/",
81
+ "licenses/javascript/"
33
82
  ],
34
83
  "dependencies": {
84
+ "@unicode/unicode-17.0.0": "2.0.7",
35
85
  "fflate": "0.8.2",
36
86
  "fontkit": "2.0.4",
37
- "saxes": "6.0.0"
87
+ "saxes": "6.0.0",
88
+ "@deepseek-ai/libreoffice-kit-wasm": "0.0.2-rc5"
38
89
  },
39
- "optionalDependencies": {
40
- "@deepseek-ai/libreoffice-kit-darwin-x64": "0.0.1",
41
- "@deepseek-ai/libreoffice-kit-win32-arm64": "0.0.1",
42
- "@deepseek-ai/libreoffice-kit-win32-x64": "0.0.1",
43
- "@deepseek-ai/libreoffice-kit-wasm": "0.0.1",
44
- "@deepseek-ai/libreoffice-kit-darwin-arm64": "0.0.1"
90
+ "bin": {
91
+ "libreoffice-kit": "./lib/cli.js"
45
92
  }
46
- }
93
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "@deepseek-ai/libreoffice-kit-browser-internal",
3
+ "version": "0.0.2-rc5",
4
+ "type": "module",
5
+ "license": "MPL-2.0",
6
+ "description": "Browser Worker LibreOffice reading sessions and PDF rendering",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/deepseek-harness/libreoffice-kit.git",
10
+ "directory": "packages/browser"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./lib/types/index.d.ts",
15
+ "import": "./lib/index.js"
16
+ }
17
+ },
18
+ "devDependencies": {
19
+ "@deepseek-ai/libreoffice-kit": "workspace:*"
20
+ },
21
+ "private": true
22
+ }
@@ -0,0 +1,166 @@
1
+ /** Browser document ownership, cancellation and asynchronous Host font delivery. */
2
+ import { FONT_CHUNK_BYTES, FONT_HEADER_BYTES, FontState } from './protocol.ts'
3
+ import type { OwnerMessage, OwnerRequest, WorkerMessage, WorkerOptions } from './protocol.ts'
4
+ import { fontFrames, fontViews } from './font-channel.ts'
5
+ import { BrowserRenderError } from './types.ts'
6
+ import type { BrowserDocumentOptions } from './types.ts'
7
+ import type { OfficeDocumentEvent, OfficeDocumentOptions } from './office-types.ts'
8
+
9
+ interface Pending {
10
+ resolve(message: WorkerMessage): void
11
+ reject(error: unknown): void
12
+ }
13
+
14
+ /**
15
+ * Load original Office bytes in a dedicated Worker with no intermediate PDF.
16
+ * @param options - Resources, limits, source bytes and asynchronous Host font provider.
17
+ * @param signal - Document lifetime; abort closes its Worker and all pending work.
18
+ * @returns Initial geometry, ordered Worker requests and joined disposal.
19
+ */
20
+ export async function openBrowserConnection(options: BrowserDocumentOptions | OfficeDocumentOptions, signal?: AbortSignal,
21
+ office = false, onEvent?: (event: OfficeDocumentEvent) => void) {
22
+ signal?.throwIfAborted()
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
+ 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 (!(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.')
26
+ const worker = new Worker(options.assets.workerUrl, { name: 'libreoffice-document' })
27
+ const channel = new SharedArrayBuffer(FONT_HEADER_BYTES + FONT_CHUNK_BYTES)
28
+ const { control, bytes } = fontViews(channel)
29
+ const lifetime = new AbortController()
30
+ const pending = new Map<number, Pending>()
31
+ let sequence = 0
32
+ let closed = false
33
+ let disposal: Promise<void> | undefined
34
+ let frames: ReturnType<typeof fontFrames> | undefined
35
+ let opened: Extract<WorkerMessage, { type: 'opened' }> | undefined
36
+
37
+ function failPending(error: unknown): void {
38
+ for (const entry of pending.values()) entry.reject(error)
39
+ pending.clear()
40
+ }
41
+ function sendFontError(error: unknown): void {
42
+ if (closed) return
43
+ frames = undefined
44
+ const encoded = new TextEncoder().encode(error instanceof Error ? error.message : String(error)).subarray(0, FONT_CHUNK_BYTES)
45
+ bytes.set(encoded)
46
+ Atomics.store(control, 1, encoded.length)
47
+ Atomics.store(control, 0, FontState.Error)
48
+ Atomics.notify(control, 0)
49
+ }
50
+ function pumpFonts(): void {
51
+ if (closed || !frames) return
52
+ try {
53
+ const frame = frames.next()
54
+ if (frame.done) { frames = undefined; return }
55
+ bytes.set(frame.value.bytes)
56
+ Atomics.store(control, 1, frame.value.bytes.length)
57
+ Atomics.store(control, 0, frame.value.state)
58
+ Atomics.notify(control, 0)
59
+ } catch (error) { sendFontError(error) }
60
+ }
61
+ worker.onmessage = (event: MessageEvent<WorkerMessage>) => {
62
+ const message = event.data
63
+ switch (message.type) {
64
+ case 'office-event': if (!closed) { onEvent?.(message.event); if (message.event.type === 'error') void dispose() }; return
65
+ case 'font':
66
+ if (closed) return
67
+ void Promise.resolve().then(() => options.resolveFonts(message.request, lifetime.signal)).then(result => {
68
+ if (closed) return
69
+ frames = fontFrames(result)
70
+ pumpFonts()
71
+ }, sendFontError)
72
+ return
73
+ case 'font-next': pumpFonts(); return
74
+ case 'missing-fonts': if (!closed) options.onMissingFonts?.(message.families); return
75
+ default: {
76
+ const entry = pending.get(message.id)
77
+ if (!entry) return
78
+ pending.delete(message.id)
79
+ if (message.type === 'error') {
80
+ entry.reject(new BrowserRenderError(message.code, message.message))
81
+ if (message.fatal || message.code === 'font-limit' || message.code === 'font-unavailable' || message.code === 'timeout') {
82
+ onEvent?.({ type: 'error', code: message.code, message: message.message })
83
+ void dispose()
84
+ }
85
+ } else entry.resolve(message)
86
+ }
87
+ }
88
+ }
89
+ worker.onerror = (event) => {
90
+ const error = new BrowserRenderError('render-failed', event.message || 'LibreOffice Worker failed.')
91
+ onEvent?.({ type: 'error', code: error.code, message: error.message })
92
+ failPending(error)
93
+ void dispose()
94
+ }
95
+ worker.onmessageerror = () => {
96
+ const error = new BrowserRenderError('render-failed', 'LibreOffice Worker returned an unreadable response.')
97
+ onEvent?.({ type: 'error', code: error.code, message: error.message })
98
+ failPending(error)
99
+ void dispose()
100
+ }
101
+
102
+ function post(message: OwnerMessage, transfer: Transferable[] = []): Promise<WorkerMessage> {
103
+ return new Promise((resolve, reject) => {
104
+ const timer = setTimeout(() => {
105
+ pending.delete(message.id)
106
+ const error = new BrowserRenderError('timeout', 'LibreOffice operation timed out.')
107
+ reject(error)
108
+ if (!closed) onEvent?.({ type: 'error', code: error.code, message: error.message })
109
+ void dispose()
110
+ }, options.timeoutMs)
111
+ pending.set(message.id, {
112
+ resolve(value) { clearTimeout(timer); resolve(value) },
113
+ reject(error) { clearTimeout(timer); reject(error) },
114
+ })
115
+ try { worker.postMessage(message, transfer) } catch (error) { pending.get(message.id)?.reject(error); pending.delete(message.id) }
116
+ })
117
+ }
118
+ function dispose(): Promise<void> {
119
+ if (disposal) return disposal
120
+ closed = true
121
+ signal?.removeEventListener('abort', aborted)
122
+ lifetime.abort()
123
+ frames = undefined
124
+ Atomics.store(control, 0, FontState.Cancelled)
125
+ Atomics.notify(control, 0)
126
+ failPending(new BrowserRenderError('disposed', 'The document is closed.'))
127
+ disposal = new Promise<void>((resolve) => {
128
+ // This handshake only releases owned workers; document processing has its own caller deadline.
129
+ const deadline = setTimeout(resolve, 1_000)
130
+ void post({ type: 'dispose', id: ++sequence }).then(() => resolve(), () => resolve()).finally(() => clearTimeout(deadline))
131
+ }).finally(() => { worker.terminate(); failPending(new BrowserRenderError('disposed', 'The document is closed.')); worker.onmessage = null; worker.onerror = null; worker.onmessageerror = null })
132
+ return disposal
133
+ }
134
+ function aborted(): void { void dispose() }
135
+ signal?.addEventListener('abort', aborted, { once: true })
136
+
137
+ try {
138
+ const data = new Uint8Array(options.data)
139
+ const engineOptions: WorkerOptions = { data, extension: options.extension, assets: options.assets, timeoutMs: options.timeoutMs, maxLoadedFontBytes: options.maxLoadedFontBytes, fontFallbacks: options.fontFallbacks, maxArchiveEntries: options.maxArchiveEntries, maxUncompressedBytes: options.maxUncompressedBytes }
140
+ const result = await post({ type: 'open', id: ++sequence, options: engineOptions, channel, ...(office ? { office: true } : {}) }, [data.buffer])
141
+ if (result.type !== 'opened') throw new BrowserRenderError('invalid-document', 'LibreOffice returned an unexpected load response.')
142
+ opened = result
143
+ if (opened.type !== 'opened' || opened.pages.length === 0) throw new BrowserRenderError('invalid-document', 'LibreOffice returned no document pages.')
144
+ signal?.throwIfAborted()
145
+ } catch (error) {
146
+ await dispose()
147
+ signal?.throwIfAborted()
148
+ throw error
149
+ }
150
+
151
+ return {
152
+ opened,
153
+ request(message: OwnerRequest, operation?: AbortSignal): Promise<WorkerMessage> {
154
+ if (closed) return Promise.reject(new BrowserRenderError('disposed', 'The document is closed.'))
155
+ if (operation?.aborted) return Promise.reject(operation.reason)
156
+ const task = post({ ...message, id: ++sequence })
157
+ if (!operation) return task
158
+ return new Promise((resolve, reject) => {
159
+ const abort = (): void => { reject(operation.reason) }
160
+ operation.addEventListener('abort', abort, { once: true })
161
+ void task.then(resolve, reject).finally(() => operation.removeEventListener('abort', abort))
162
+ })
163
+ },
164
+ dispose,
165
+ }
166
+ }
@@ -0,0 +1,2 @@
1
+ /** Raster allocation shared by Node and browser WASM consumers. */
2
+ export { renderRegion, pdfPages } from '@deepseek-ai/libreoffice-kit/internal/engine-rendering'
@@ -0,0 +1,14 @@
1
+ /** Emscripten operations used by the single owning engine Worker. */
2
+ export interface EmscriptenModule {
3
+ readonly FS: {
4
+ mkdirTree(path: string): void
5
+ writeFile(path: string, data: Uint8Array): void
6
+ readFile(path: string): Uint8Array<ArrayBuffer>
7
+ unlink(path: string): void
8
+ }
9
+ readonly ENV: Record<string, string>
10
+ readonly HEAPU32: Uint32Array
11
+ readonly PThread: { terminateAllThreads(): void }
12
+ ccall(name: string, returnType: string | null, argTypes: string[], args: unknown[]): number
13
+ UTF8ToString(pointer: number): string
14
+ }
@@ -0,0 +1,99 @@
1
+ /** Bounded frames bridge asynchronous Host font reads and synchronous VCL callbacks. */
2
+ import { normalize } from '@deepseek-ai/libreoffice-kit/font-config'
3
+ import { FONT_CHUNK_BYTES, FONT_HEADER_BYTES, FontState } from './protocol.ts'
4
+ import type { FontHeader } from './protocol.ts'
5
+ import { BrowserRenderError } from './types.ts'
6
+ import type { BrowserFontRequest, BrowserFontResult } from './types.ts'
7
+
8
+ /** Views shared by the owner and engine; only the engine uses Atomics.wait. */
9
+ export function fontViews(channel: SharedArrayBuffer): { control: Int32Array; bytes: Uint8Array } {
10
+ return { control: new Int32Array(channel, 0, 2), bytes: new Uint8Array(channel, FONT_HEADER_BYTES) }
11
+ }
12
+
13
+ /** Frames are produced lazily so the transfer channel never duplicates a whole font set. */
14
+ export function* fontFrames(result: BrowserFontResult): Generator<{ state: FontState; bytes: Uint8Array }> {
15
+ const header: FontHeader = { fonts: result.fonts.map(font => ({ id: font.id, bytes: font.data.byteLength, family: font.family, alias: font.alias, ...(font.format ? { format: font.format } : {}) })), ...(result.missingFamily === undefined ? {} : { missingFamily: result.missingFamily }) }
16
+ const encoded = new TextEncoder().encode(JSON.stringify(header))
17
+ if (encoded.length > FONT_CHUNK_BYTES) throw new BrowserRenderError('font-limit', 'Font response metadata exceeds the transfer limit.')
18
+ yield { state: FontState.Header, bytes: encoded }
19
+ for (const font of result.fonts) {
20
+ for (let offset = 0; offset < font.data.byteLength; offset += FONT_CHUNK_BYTES) {
21
+ yield { state: FontState.Bytes, bytes: font.data.subarray(offset, offset + FONT_CHUNK_BYTES) }
22
+ }
23
+ }
24
+ yield { state: FontState.Done, bytes: new Uint8Array() }
25
+ }
26
+
27
+ /** One MEMFS font face registered under a document-local family alias. */
28
+ export interface EngineFontFace { readonly path: string; readonly family: string }
29
+
30
+ /** The synchronous reader installs immutable subsets before returning their MEMFS paths and aliases. */
31
+ export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number, maxLoadedFontBytes: number,
32
+ declaredFamilies: ReadonlyMap<string, string>, request: (request: BrowserFontRequest) => void, next: () => void,
33
+ install: (path: string, bytes: Uint8Array) => void, missing: (families: readonly string[]) => void): (request: BrowserFontRequest) => EngineFontFace[] {
34
+ const { control, bytes } = fontViews(channel)
35
+ const installed = new Map<string, { face: EngineFontFace; format: FontHeader['fonts'][number]['format'] }>()
36
+ const aliases = new Map<string, { id: string; family: string }>()
37
+ const requests = new Map<string, EngineFontFace[]>()
38
+ const families = new Set<string>()
39
+ let loadedBytes = 0
40
+ function read(): { state: FontState; data: Uint8Array } {
41
+ const started = performance.now()
42
+ while (Atomics.load(control, 0) === FontState.Waiting) {
43
+ const remaining = timeoutMs - (performance.now() - started)
44
+ if (remaining <= 0 || Atomics.wait(control, 0, FontState.Waiting, remaining) === 'timed-out') throw new BrowserRenderError('timeout', 'Font loading timed out.')
45
+ }
46
+ const state = Atomics.load(control, 0) as FontState
47
+ if (state === FontState.Cancelled) throw new DOMException('Document closed.', 'AbortError')
48
+ const length = Atomics.load(control, 1)
49
+ if (length < 0 || length > bytes.length) throw new BrowserRenderError('font-unavailable', 'Invalid font transfer length.')
50
+ const data = bytes.slice(0, length)
51
+ if (Atomics.compareExchange(control, 0, state, FontState.Waiting) === FontState.Cancelled) throw new DOMException('Document closed.', 'AbortError')
52
+ next()
53
+ if (state === FontState.Error) throw new BrowserRenderError('font-unavailable', new TextDecoder().decode(data))
54
+ return { state, data }
55
+ }
56
+ return (attributes) => {
57
+ const canonical = aliases.get(normalize(attributes.family))?.family
58
+ const original = { ...attributes, ...(canonical === undefined ? {} : { family: canonical }) }
59
+ const key = JSON.stringify(original)
60
+ const cached = requests.get(key)
61
+ if (cached) return cached
62
+ request(original)
63
+ const first = read()
64
+ if (first.state !== FontState.Header) throw new BrowserRenderError('font-unavailable', 'Expected font transfer metadata.')
65
+ let header: FontHeader
66
+ try { header = JSON.parse(new TextDecoder().decode(first.data)) as FontHeader } catch (cause) { throw new BrowserRenderError('font-unavailable', 'Invalid font transfer metadata.') }
67
+ if (header === null || typeof header !== 'object' || !Array.isArray(header.fonts) || header.fonts.length === 0) throw new BrowserRenderError('font-unavailable', 'Host has no usable fonts.')
68
+ const faces: EngineFontFace[] = []
69
+ for (const font of header.fonts) {
70
+ if (typeof font.id !== 'string' || typeof font.family !== 'string' || font.family.length === 0 || typeof font.alias !== 'string' || font.alias.length === 0 || /[\x00\t\r\n]/.test(font.alias) || !Number.isSafeInteger(font.bytes) || font.bytes <= 0) throw new BrowserRenderError('font-unavailable', 'Invalid font file descriptor.')
71
+ if (font.format !== undefined && !['ttf', 'otf', 'ttc'].includes(font.format)) throw new BrowserRenderError('font-unavailable', 'Invalid full font format.')
72
+ const prior = installed.get(font.id)
73
+ if (prior && (prior.format !== font.format || (font.format === undefined && prior.face.family !== font.alias))) throw new BrowserRenderError('font-unavailable', 'Font identity has conflicting aliases or formats.')
74
+ const alias = normalize(font.alias)
75
+ const previousAlias = aliases.get(alias)
76
+ if (previousAlias && (previousAlias.family !== font.family || (font.format === undefined && previousAlias.id !== font.id))) throw new BrowserRenderError('font-unavailable', 'Font alias identifies conflicting subsets.')
77
+ if (!prior && loadedBytes + font.bytes > maxLoadedFontBytes) throw new BrowserRenderError('font-limit', 'Imported fonts exceed maxLoadedFontBytes.')
78
+ const buffer = prior ? undefined : new Uint8Array(font.bytes)
79
+ let received = 0
80
+ while (received < font.bytes) {
81
+ const frame = read()
82
+ if (frame.state !== FontState.Bytes || frame.data.length === 0 || received + frame.data.length > font.bytes) throw new BrowserRenderError('font-unavailable', 'Incomplete font file transfer.')
83
+ buffer?.set(frame.data, received)
84
+ received += frame.data.length
85
+ }
86
+ // A full TTC asset can expose multiple families from the same installed bytes.
87
+ // Its requested family must not inherit the first family's alias.
88
+ const face = { path: prior?.face.path ?? (font.format === undefined ? `/dsh-fonts/${installed.size}.font` : `/usr/share/fonts/dsh-pdfium/${installed.size}.${font.format}`), family: font.alias }
89
+ if (buffer) { install(face.path, buffer); installed.set(font.id, { face, format: font.format }); loadedBytes += buffer.length }
90
+ aliases.set(alias, { id: font.id, family: font.family })
91
+ faces.push(face)
92
+ }
93
+ if (read().state !== FontState.Done) throw new BrowserRenderError('font-unavailable', 'Unexpected font transfer trailer.')
94
+ const absentFamily = header.missingFamily === undefined ? undefined : declaredFamilies.get(normalize(header.missingFamily))
95
+ if (absentFamily !== undefined && !families.has(absentFamily)) { families.add(absentFamily); missing([...families]) }
96
+ requests.set(key, faces)
97
+ return faces
98
+ }
99
+ }
@@ -0,0 +1,39 @@
1
+ /** Browser Office preview and retained reading entry points. */
2
+ import { openBrowserConnection } from './connection.ts'
3
+ import { BrowserRenderError } from './types.ts'
4
+ import type { BrowserDocument, BrowserDocumentOptions, BrowserTile, BrowserTileRequest } from './types.ts'
5
+ export { BrowserRenderError } from './types.ts'
6
+ export { openOfficeDocument } from './office.ts'
7
+ export type * from './office-types.ts'
8
+ export type { BrowserDocument, BrowserDocumentOptions, BrowserEngineAssets, BrowserFontRequest, BrowserFontResult, BrowserPage, BrowserRenderErrorCode, BrowserTile, BrowserTileRequest } from './types.ts'
9
+
10
+ /**
11
+ * Open a read-only document; each call owns an independent Worker.
12
+ * @param options - Source bytes, version-matched resources and Host fonts.
13
+ * @param signal - Document lifetime; abort awaits engine teardown.
14
+ * @returns Immutable geometry, serialized tile rendering and disposal.
15
+ */
16
+ export async function openDocument(options: BrowserDocumentOptions, signal?: AbortSignal): Promise<BrowserDocument> {
17
+ const connection = await openBrowserConnection(options, signal)
18
+ let queue: Promise<unknown> = Promise.resolve()
19
+ return {
20
+ pages: Object.freeze(connection.opened.pages.map(page => Object.freeze(page))),
21
+ renderTile(request: BrowserTileRequest, tileSignal?: AbortSignal): Promise<BrowserTile> {
22
+ if (tileSignal?.aborted) return Promise.reject(tileSignal.reason)
23
+ const task = queue.catch(() => undefined).then(async () => {
24
+ tileSignal?.throwIfAborted()
25
+ const response = await connection.request({ type: 'tile', request }, tileSignal)
26
+ if (response.type !== 'tile') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected tile response.')
27
+ return response.tile
28
+ })
29
+ queue = task
30
+ if (!tileSignal) return task
31
+ return new Promise((resolve, reject) => {
32
+ const abort = (): void => { reject(tileSignal.reason) }
33
+ tileSignal.addEventListener('abort', abort, { once: true })
34
+ void task.then(resolve, reject).finally(() => tileSignal.removeEventListener('abort', abort))
35
+ })
36
+ },
37
+ dispose: connection.dispose,
38
+ }
39
+ }