@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,166 @@
1
+ /** Classic Worker entry: serializes one LibreOffice instance and owns its pthreads. */
2
+ import { inspectDocument } from '@deepseek-ai/libreoffice-kit/document-inspection'
3
+ import { memoryFontConfig } from '@deepseek-ai/libreoffice-kit/font-config'
4
+ import { createFontReader } from './font-channel.ts'
5
+ import { BrowserRenderError } from './types.ts'
6
+ import type { BrowserRenderErrorCode, BrowserTileRequest } from './types.ts'
7
+ import type { OwnerMessage, WorkerMessage, WorkerOptions } from './protocol.ts'
8
+ import type { EnginePage } from './rendering.ts'
9
+
10
+ import type { EmscriptenModule } from './engine-types.ts'
11
+ import type { OfficeDocumentFormat } from './office-types.ts'
12
+ import { OfficeEngine } from './office-engine.ts'
13
+ import { pdfPages, renderRegion } from './engine-rendering.ts'
14
+
15
+ interface EngineGlobal extends DedicatedWorkerGlobalScope {
16
+ createLibreOfficeModule(overrides: Record<string, unknown>): Promise<EmscriptenModule>
17
+ }
18
+ const scope = globalThis as unknown as EngineGlobal
19
+ let module: EmscriptenModule | undefined
20
+ let office = 0
21
+ let document = 0
22
+ let pdf = 0
23
+ let pages: EnginePage[] = []
24
+ let reader: OfficeEngine | undefined
25
+ let fatal = false
26
+ let fontFailure: unknown
27
+ let serial = Promise.resolve()
28
+ const lifetime = new AbortController()
29
+
30
+ function send(message: WorkerMessage, transfer: Transferable[] = []): void { scope.postMessage(message, transfer) }
31
+ function call(name: string, args: number[]): number { return module!.ccall(name, 'number', args.map(() => 'number'), args) }
32
+ function error(code: BrowserRenderErrorCode): BrowserRenderError {
33
+ if (fontFailure instanceof BrowserRenderError) return fontFailure
34
+ if (!module) return new BrowserRenderError(code, 'LibreOffice could not initialize.')
35
+ const pointer = call('dsh_lok_error', [office])
36
+ if (!pointer) return new BrowserRenderError(code, 'LibreOffice could not render the document.')
37
+ try { return new BrowserRenderError(code, module.UTF8ToString(pointer)) } finally { call('free', [pointer]) }
38
+ }
39
+
40
+ async function open(options: WorkerOptions, channel: SharedArrayBuffer, reading = false): Promise<void> {
41
+ const { assets } = options
42
+ let metadata: ReturnType<typeof inspectDocument>
43
+ try { metadata = options.extension === 'pdf' ? { families: new Map(), codePoints: [] } : inspectDocument(options.data, options.extension, options) } catch (failure) { throw new BrowserRenderError('invalid-document', failure instanceof Error ? failure.message : String(failure)) }
44
+ const response = await fetch(assets.dataUrl, { credentials: 'same-origin', signal: lifetime.signal })
45
+ if (!response.ok) throw new BrowserRenderError('unavailable', `LibreOffice data request failed: ${response.status}`)
46
+ const data = await response.arrayBuffer()
47
+ scope.importScripts(assets.loaderUrl)
48
+ let resolveFonts: ReturnType<typeof createFontReader> | undefined
49
+ module = await scope.createLibreOfficeModule({
50
+ noInitialRun: true,
51
+ dshOnCallback(type: number, payload: string) { reader?.callback(type, payload) },
52
+ mainScriptUrlOrBlob: assets.loaderUrl,
53
+ locateFile(name: string) {
54
+ const basename = name.slice(name.lastIndexOf('/') + 1)
55
+ switch (basename) {
56
+ case 'soffice.js': case 'soffice.cjs': return assets.loaderUrl
57
+ case 'soffice.wasm': return assets.wasmUrl
58
+ case 'soffice.data': return assets.dataUrl
59
+ case 'soffice.data.js.metadata': return assets.metadataUrl
60
+ default: throw new BrowserRenderError('unavailable', `LibreOffice requested an undeclared resource: ${basename}`)
61
+ }
62
+ },
63
+ getPreloadedPackage: () => data,
64
+ dshResolveSystemFontFaces(request: Parameters<NonNullable<typeof resolveFonts>>[0]) {
65
+ if (!resolveFonts) throw new BrowserRenderError('font-unavailable', 'LibreOffice requested fonts before MEMFS initialization.')
66
+ try { return resolveFonts(request) } catch (failure) { fontFailure = failure; throw failure }
67
+ },
68
+ preRun: [(loaded: EmscriptenModule) => {
69
+ for (const path of ['/dsh/profile', '/dsh/font-cache', '/dsh-fonts', '/usr/share/fonts/dsh-pdfium']) loaded.FS.mkdirTree(path)
70
+ loaded.FS.writeFile('/dsh/fonts.conf', new TextEncoder().encode(memoryFontConfig(options.fontFallbacks, metadata.families.values())))
71
+ Object.assign(loaded.ENV, { HOME: '/dsh/profile', TMPDIR: '/tmp', FONTCONFIG_FILE: '/dsh/fonts.conf', LOK_HOST_ALLOWLIST: '^$' })
72
+ resolveFonts = createFontReader(channel, options.timeoutMs, options.maxLoadedFontBytes, metadata.families,
73
+ request => send({ type: 'font', request }), () => send({ type: 'font-next' }),
74
+ (path, bytes) => loaded.FS.writeFile(path, bytes), families => send({ type: 'missing-fonts', families }))
75
+ const initialFamilies = options.extension === 'pdf' ? new Set(options.fontFallbacks.flat()) : new Set(['sans-serif'])
76
+ for (const family of initialFamilies) resolveFonts({ family, style: '', weight: 5, italic: 0, width: 5, pitch: 0, language: '', codePoints: [], ...(options.extension === 'pdf' ? { mode: 'full' as const } : {}) })
77
+ }],
78
+ onAbort() { fatal = true },
79
+ print() {}, printErr() {},
80
+ })
81
+ if (options.extension === 'pdf') {
82
+ const pointer = call('malloc', [options.data.byteLength])
83
+ if (!pointer) throw error('invalid-document')
84
+ try {
85
+ new Uint8Array(module.HEAPU32.buffer, pointer, options.data.byteLength).set(options.data)
86
+ pdf = module.ccall('dsh_pdf_open', 'number', ['number', 'number', 'string'], [pointer, options.data.byteLength, ''])
87
+ } finally { call('free', [pointer]) }
88
+ if (!pdf) throw error('invalid-document')
89
+ pages = pdfPages(module, pdf, () => error('invalid-document'))
90
+ return
91
+ }
92
+ const input = `/dsh/document.${options.extension}`
93
+ module.FS.writeFile(input, options.data)
94
+ office = module.ccall('dsh_lok_initialize', 'number', ['string', 'string'], [assets.programDirectory, 'file:///dsh/profile'])
95
+ if (!office) throw error('invalid-document')
96
+ document = module.ccall('dsh_lok_document_load', 'number', ['number', 'string', 'string'], [office, `file://${input}`, 'ReadOnly=true,EnableMacrosExecution=false'])
97
+ if (!document || !call('dsh_lok_document_initialize_rendering', [document])) throw error('invalid-document')
98
+ const type = call('dsh_lok_document_type', [document])
99
+ 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.')
100
+ if (reading) {
101
+ reader = new OfficeEngine(module, document, options.extension as OfficeDocumentFormat,
102
+ event => send({ type: 'office-event', event }), failure => {
103
+ fatal ||= failure instanceof WebAssembly.RuntimeError
104
+ send({ type: 'office-event', event: { type: 'error', code: 'render-failed', message: failure instanceof Error ? failure.message : String(failure) } })
105
+ })
106
+ await reader.start()
107
+ pages = reader.state.parts.map((part, index) => ({ ...part, x: 0, y: 0, part: type === 0 ? -1 : index }))
108
+ return
109
+ }
110
+ throw new BrowserRenderError('invalid-document', 'Office documents require a retained session.')
111
+ }
112
+
113
+ function render(request: BrowserTileRequest): { width: number; height: number; rgba: Uint8ClampedArray } {
114
+ if (fatal) throw new BrowserRenderError('render-failed', 'LibreOffice Worker has aborted.')
115
+ if (!pdf || !module) throw new BrowserRenderError('disposed', 'The document is closed.')
116
+ return renderRegion(module, pdf, request, pages, () => error('render-failed'), true)
117
+ }
118
+
119
+ function dispose(): void {
120
+ reader?.stop()
121
+ reader = undefined
122
+ try {
123
+ if (module && !fatal) {
124
+ if (pdf) { const value = pdf; pdf = 0; if (!call('dsh_pdf_destroy', [value])) throw error('render-failed') }
125
+ if (document) { const value = document; document = 0; if (!call('dsh_lok_document_destroy', [value])) throw error('render-failed') }
126
+ if (office) { const value = office; office = 0; if (!call('dsh_lok_destroy', [value])) throw error('render-failed') }
127
+ }
128
+ } finally {
129
+ module?.PThread.terminateAllThreads()
130
+ module = undefined
131
+ document = 0
132
+ pdf = 0
133
+ office = 0
134
+ pages = []
135
+ }
136
+ }
137
+
138
+ scope.onmessage = (event: MessageEvent<OwnerMessage>) => {
139
+ const message = event.data
140
+ if (message.type === 'dispose') { lifetime.abort(); reader?.stop() }
141
+ serial = serial.then(async () => {
142
+ try {
143
+ switch (message.type) {
144
+ case 'open': await open(message.options, message.channel, message.office); send({ type: 'opened', id: message.id, pages: pages.map(({ width, height }) => ({ width, height })), ...(reader ? { office: reader.state } : {}) }); break
145
+ case 'tile': { const tile = render(message.request); send({ type: 'tile', id: message.id, tile }, [tile.rgba.buffer]); break }
146
+ case 'office-tile': {
147
+ if (!reader) throw new BrowserRenderError('disposed', 'Office reader is closed.')
148
+ const tile = reader.render(message.request)
149
+ send({ type: 'tile', id: message.id, tile }, [tile.rgba.buffer])
150
+ break
151
+ }
152
+ case 'office-operation': {
153
+ if (!reader) throw new BrowserRenderError('disposed', 'Office reader is closed.')
154
+ const result = await reader.operation(message.operation)
155
+ send({ type: 'office-result', id: message.id, ...result })
156
+ break
157
+ }
158
+ case 'dispose': dispose(); send({ type: 'disposed', id: message.id }); scope.close(); break
159
+ default: throw new BrowserRenderError('render-failed', 'Unsupported Office Worker request.')
160
+ }
161
+ } catch (failure) {
162
+ fatal ||= failure instanceof WebAssembly.RuntimeError
163
+ send({ type: 'error', id: message.id, code: failure instanceof BrowserRenderError ? failure.code : 'render-failed', message: failure instanceof Error ? failure.message : String(failure), fatal })
164
+ }
165
+ })
166
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": { "rootDir": "src", "outDir": "lib/types", "types": [], "lib": ["ES2024", "DOM", "WebWorker"] },
4
+ "include": ["src"]
5
+ }
@@ -0,0 +1,7 @@
1
+ import { defineConfig } from 'tsdown'
2
+
3
+ /** The classic worker bundles its protocol and renderer before loading Emscripten. */
4
+ export default defineConfig([
5
+ { entry: ['lib/types/index.js'], outDir: 'lib', format: ['esm'], platform: 'browser', target: 'es2024', fixedExtension: false, dts: false, clean: false },
6
+ { entry: ['lib/types/worker.js'], outDir: 'lib', format: ['iife'], noExternal: ['@deepseek-ai/libreoffice-kit/font-config', '@deepseek-ai/libreoffice-kit/internal/rendering', '@deepseek-ai/libreoffice-kit/internal/engine-rendering', '@deepseek-ai/libreoffice-kit/internal/sheet-geometry', '@deepseek-ai/libreoffice-kit/document-inspection', 'fflate', 'saxes', 'xmlchars'], outputOptions: { entryFileNames: '[name].js' }, platform: 'browser', target: 'es2024', fixedExtension: false, dts: false, clean: false },
7
+ ])
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env node
2
+ /** Build browser entries into the existing main package; the engine stays in the WASM dependency. */
3
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
4
+ import { dirname, join } from 'node:path';
5
+ import { createRequire } from 'node:module';
6
+ import { buildKitSources } from './build-kit.mjs';
7
+ import { root, isMain, readJson } from './platform-matrix.mjs';
8
+ import { pnpm } from './pack-utils.mjs';
9
+ import { assert, regularFile, sha256, verifyEnginePackage } from './verify-artifacts.mjs';
10
+
11
+ const source = join(root, 'packages/browser');
12
+ const directory = join(root, 'packages/entry');
13
+ const helpers = ['rendering', 'engine-rendering', 'sheet-geometry'];
14
+
15
+ /** Compile browser-only JavaScript without copying any engine bytes into the main package. */
16
+ export function buildBrowserSources(buildEntry = true) {
17
+ if (buildEntry) buildKitSources();
18
+ // TypeScript does not remove declarations for deleted source files.
19
+ rmSync(join(source, 'lib/types'), { recursive: true, force: true });
20
+ rmSync(join(source, 'lib/tsconfig.tsbuildinfo'), { force: true });
21
+ pnpm(['exec', 'tsc', '-b', 'packages/browser'], { cwd: root });
22
+ pnpm(['exec', 'tsdown'], { cwd: source });
23
+ const target = join(directory, 'lib/browser');
24
+ rmSync(target, { recursive: true, force: true });
25
+ mkdirSync(join(target, 'types'), { recursive: true });
26
+ for (const name of ['index.js', 'worker.js']) cpSync(regularFile(source, `lib/${name}`), join(target, name));
27
+ for (const name of readdirSync(join(source, 'lib/types')).filter(name => name.endsWith('.d.ts')))
28
+ cpSync(join(source, 'lib/types', name), join(target, 'types', name));
29
+ rmSync(join(directory, 'sources/browser'), { recursive: true, force: true });
30
+ for (const path of ['packages/browser/src', 'packages/browser/package.json', 'packages/browser/tsconfig.json', 'packages/browser/tsdown.config.ts', 'scripts/build-browser.mjs']) {
31
+ const dest = join(directory, 'sources/browser', path);
32
+ mkdirSync(dirname(dest), { recursive: true }); cpSync(join(root, path), dest, { recursive: true });
33
+ }
34
+ const entryRequire = createRequire(join(directory, 'package.json'));
35
+ const saxesRequire = createRequire(entryRequire.resolve('saxes'));
36
+ mkdirSync(join(directory, 'licenses/javascript'), { recursive: true });
37
+ for (const [name, resolver] of [['fflate', entryRequire], ['saxes', entryRequire], ['xmlchars', saxesRequire]]) {
38
+ let folder = dirname(resolver.resolve(name));
39
+ while (!existsSync(join(folder, 'package.json')) || readJson(join(folder, 'package.json')).name !== name) {
40
+ const parent = dirname(folder); assert(parent !== folder, `Missing bundled dependency: ${name}`); folder = parent;
41
+ }
42
+ const license = name === 'saxes' ? join(source, 'third-party/saxes-6.0.0-LICENSE') : join(folder, 'LICENSE');
43
+ cpSync(license, join(directory, 'licenses/javascript', `${name}-LICENSE`));
44
+ }
45
+ const path = 'lib/browser/worker.js';
46
+ writeFileSync(join(target, 'assets.json'), `${JSON.stringify({ schemaVersion: 1, files: { worker: { path, bytes: statSync(join(directory, path)).size, sha256: sha256(join(directory, path)) } } }, null, 2)}\n`);
47
+ return directory;
48
+ }
49
+
50
+ /** Require main-package browser entries and the direct-drawing ABI in the separately staged engine. */
51
+ export function verifyBrowserPackage(target = directory, engineDirectory = join(root, 'packages/wasm')) {
52
+ const manifest = readJson(regularFile(target, 'package.json'));
53
+ assert(manifest.name === '@deepseek-ai/libreoffice-kit' && manifest.version === readJson(join(root, 'package.json')).version,
54
+ 'Browser entry must be in the matching main package');
55
+ for (const file of ['lib/browser/index.js', 'lib/browser/worker.js', 'lib/browser/types/index.d.ts', 'lib/browser-assets.js']) regularFile(target, file);
56
+ for (const helper of helpers) regularFile(target, `lib/${helper}.js`);
57
+ const declarations = join(target, 'lib/browser/types');
58
+ const declarationText = readdirSync(declarations).filter(name => name.endsWith('.d.ts')).map(name => readFileSync(join(declarations, name), 'utf8')).join('\n');
59
+ assert(declarationText.includes('openOfficeDocument') && !declarationText.includes('openEditor')
60
+ && !readdirSync(declarations).some(name => name.startsWith('editor')), 'Browser package retains a removed editing SDK');
61
+ const receipt = readJson(regularFile(target, 'lib/browser/assets.json'));
62
+ const worker = receipt.files?.worker;
63
+ assert(receipt.schemaVersion === 1 && worker?.path === 'lib/browser/worker.js'
64
+ && worker.bytes === statSync(join(target, worker.path)).size && worker.sha256 === sha256(join(target, worker.path)), 'Browser Worker receipt differs');
65
+ verifyEnginePackage(engineDirectory);
66
+ const engine = readJson(join(engineDirectory, 'prebuilds.json')).engine;
67
+ const module = new WebAssembly.Module(readFileSync(join(engineDirectory, engine.wasm)));
68
+ 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', 'dsh_lok_document_create_view', 'dsh_lok_document_part_info', 'dsh_pdf_open', 'dsh_pdf_paint'])
70
+ assert(exports.has(name) || exports.has(`_${name}`), `WASM has no browser export: ${name}`);
71
+ return receipt;
72
+ }
73
+
74
+ /** Compatibility build command; payload remains exclusively in the existing WASM package. */
75
+ export function stageBrowserAssets(engineDirectory = join(root, 'packages/wasm')) {
76
+ buildBrowserSources(); verifyBrowserPackage(directory, engineDirectory); return directory;
77
+ }
78
+ if (isMain(import.meta.url)) {
79
+ if (process.argv.includes('--verify')) verifyBrowserPackage();
80
+ else if (process.argv.includes('--stage')) stageBrowserAssets();
81
+ else buildBrowserSources();
82
+ }
@@ -0,0 +1,23 @@
1
+ # Host font subset runtime
2
+
3
+ [中文](README.zh.md)
4
+
5
+ The Node font source uses HarfBuzz to extract individual sfnt faces and preserve shaping while selecting reusable Unicode-script partitions. [source.json](source.json) pins harfbuzzjs, its HarfBuzz submodule, and Emscripten. The upstream subset module has a fixed 65 MiB heap; this recipe enables heap growth up to the WebAssembly build ceiling of 2 GiB. Input limits and the retained-subset cache budget do not bound all transient subsetting allocations.
6
+
7
+ Prepare an isolated checkout and SDK, then build:
8
+
9
+ ```sh
10
+ git clone --depth 1 --branch v1.6.1 --recurse-submodules --shallow-submodules https://github.com/harfbuzz/harfbuzzjs.git .build/font-subset/harfbuzzjs
11
+ git clone https://github.com/emscripten-core/emsdk.git .build/font-subset/emsdk
12
+ git -C .build/font-subset/emsdk checkout --detach 5eb0bde7585670252e8ba05e9d361627bffd08b5
13
+ python3 .build/font-subset/emsdk/emsdk.py install 4.0.10
14
+ python3 .build/font-subset/emsdk/emsdk.py activate 4.0.10
15
+ node scripts/build-font-subset.mjs
16
+ node scripts/build-font-subset.mjs --verify
17
+ ```
18
+
19
+ The build checks exact commits, clean tracked source files, and the compiler version. It changes only compiler/linker arguments: upstream source remains unmodified. `--source`, `--emsdk`, and `--target` accept existing checkout and staging directories; use a separate SDK cache when another build is active.
20
+
21
+ The generated `packages/entry/assets/font-subset.json` records the exact source pins, recipe hash, and checksums for the WASM module, source recipe, configuration, exports list, and license notices. Node API packing verifies this receipt. The runtime verifies its WASM bytes against the packaged receipt before initialization. Installation and font requests never build or fetch the module.
22
+
23
+ Build this runtime before running font subset tests. Portable fixtures compare Arabic, Indic, supplementary-script, and variable-font shaping and outlines, exercise TTC/dfont extraction, and force allocation beyond the upstream heap size. The tests also cover cache eviction, font-index refresh, worker teardown, and invalid module receipts.
@@ -0,0 +1,23 @@
1
+ # Host 字体子集运行时
2
+
3
+ [English](README.md)
4
+
5
+ Node 字体源使用 HarfBuzz 提取单独的 sfnt 字面,并在选择可复用 Unicode 文字系统分区时保留字形塑形。[source.json](source.json) 固定 harfbuzzjs、其 HarfBuzz 子模块和 Emscripten。上游子集模块使用固定的 65 MiB 堆;本配方允许堆增长,WebAssembly 构建上限为 2 GiB。输入限制和保留子集缓存预算不能约束所有临时子集分配。
6
+
7
+ 准备独立源码目录和 SDK,然后构建:
8
+
9
+ ```sh
10
+ git clone --depth 1 --branch v1.6.1 --recurse-submodules --shallow-submodules https://github.com/harfbuzz/harfbuzzjs.git .build/font-subset/harfbuzzjs
11
+ git clone https://github.com/emscripten-core/emsdk.git .build/font-subset/emsdk
12
+ git -C .build/font-subset/emsdk checkout --detach 5eb0bde7585670252e8ba05e9d361627bffd08b5
13
+ python3 .build/font-subset/emsdk/emsdk.py install 4.0.10
14
+ python3 .build/font-subset/emsdk/emsdk.py activate 4.0.10
15
+ node scripts/build-font-subset.mjs
16
+ node scripts/build-font-subset.mjs --verify
17
+ ```
18
+
19
+ 构建检查精确提交、已跟踪源码无修改及编译器版本。它仅调整编译和链接参数,不修改上游源码。`--source`、`--emsdk` 和 `--target` 接受已有源码、SDK 和暂存目录;另一个构建运行时,应使用独立的 SDK 缓存。
20
+
21
+ 生成的 `packages/entry/assets/font-subset.json` 记录精确源码固定信息、配方哈希,以及 WASM 模块、源码配方、配置、导出列表和许可声明的校验和。Node API 打包时验证该回执。运行时初始化前会核对 WASM 字节与随包回执。安装和字体请求不会构建或下载模块。
22
+
23
+ 运行字体子集测试前需构建该运行时。可移植测试字体比较阿拉伯文、印度文字、补充平面文字及可变字体的塑形和轮廓,覆盖 TTC/dfont 提取,并强制分配超过上游堆大小的输入。测试还覆盖缓存淘汰、字体索引刷新、Worker 释放和无效模块回执。
@@ -0,0 +1,16 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "algorithm": "harfbuzzjs-1.6.1-hb-36cb489-growth-v1",
4
+ "harfbuzzjs": {
5
+ "repository": "https://github.com/harfbuzz/harfbuzzjs.git",
6
+ "commit": "8aa047b90387790b255b118cf45ad11691a38910"
7
+ },
8
+ "harfbuzz": {
9
+ "repository": "https://github.com/harfbuzz/harfbuzz.git",
10
+ "commit": "36cb489cb02ce4b92099669ba9f9bea348eff93f"
11
+ },
12
+ "emsdk": {
13
+ "commit": "5eb0bde7585670252e8ba05e9d361627bffd08b5",
14
+ "version": "4.0.10"
15
+ }
16
+ }
@@ -0,0 +1,7 @@
1
+ #undef HB_NO_CFF
2
+ #undef HB_NO_OT_FONT_CFF
3
+ #undef HB_NO_SUBSET_CFF
4
+ #undef HB_NO_SUBSET_LAYOUT
5
+ #undef HB_NO_VAR
6
+ #undef HB_NO_STYLE
7
+ #undef HB_NO_VERTICAL
@@ -0,0 +1,34 @@
1
+ _hb_blob_create
2
+ _hb_blob_destroy
3
+ _hb_blob_get_data
4
+ _hb_blob_get_length
5
+ _hb_face_create
6
+ _hb_face_destroy
7
+ _hb_face_get_empty
8
+ _hb_face_reference_blob
9
+ _hb_set_add
10
+ _hb_set_clear
11
+ _hb_set_create
12
+ _hb_set_del
13
+ _hb_set_destroy
14
+ _hb_set_invert
15
+ _hb_set_union
16
+ _hb_subset_input_create_or_fail
17
+ _hb_subset_input_destroy
18
+ _hb_subset_input_get_flags
19
+ _hb_subset_input_get_user_data
20
+ _hb_subset_input_glyph_set
21
+ _hb_subset_input_pin_all_axes_to_default
22
+ _hb_subset_input_pin_axis_location
23
+ _hb_subset_input_pin_axis_to_default
24
+ _hb_subset_input_reference
25
+ _hb_subset_input_set
26
+ _hb_subset_input_set_axis_range
27
+ _hb_subset_input_set_flags
28
+ _hb_subset_input_set_user_data
29
+ _hb_subset_input_unicode_set
30
+ _hb_subset_input_keep_everything
31
+ _hb_subset_or_fail
32
+ _hb_subset_preprocess
33
+ _malloc
34
+ _free
@@ -0,0 +1,64 @@
1
+ #!/usr/bin/env node
2
+ /** Build a pinned HarfBuzz subset module with a growing heap and stage its redistribution receipt. */
3
+ import { cpSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
4
+ import { join, resolve } from 'node:path';
5
+ import { parseArgs } from 'node:util';
6
+ import { isMain, readJson, root } from './platform-matrix.mjs';
7
+ import { run } from './pack-utils.mjs';
8
+ import { assert, regularFile, sha256 } from './verify-artifacts.mjs';
9
+
10
+ const specPath = 'engine/font-subset/source.json';
11
+ const spec = readJson(join(root, specPath));
12
+ const wasmPath = 'assets/font-subset.wasm';
13
+ const receiptPath = 'assets/font-subset.json';
14
+ const recipePath = 'scripts/build-font-subset.mjs';
15
+ const recipeFiles = [specPath, recipePath, 'scripts/platform-matrix.mjs', 'scripts/pack-utils.mjs', 'scripts/verify-artifacts.mjs', 'engine/font-subset/README.md', 'engine/font-subset/README.zh.md'];
16
+ const required = [wasmPath, ...recipeFiles.map(path => `sources/font-subset/${path}`),
17
+ 'sources/font-subset/harfbuzzjs/config-override-subset.h', 'sources/font-subset/harfbuzzjs/harfbuzz-subset.symbols',
18
+ 'licenses/font-subset/harfbuzzjs-LICENSE', 'licenses/font-subset/harfbuzz-COPYING'];
19
+
20
+ /** Verify a staged subset module, recipe, exact source pins, and redistribution notices. */
21
+ export function verifyFontSubset(target = join(root, 'packages/entry')) {
22
+ const receipt = readJson(regularFile(target, receiptPath));
23
+ assert(receipt.schemaVersion === 1 && JSON.stringify(receipt.source) === JSON.stringify(spec), 'Font subset source receipt differs');
24
+ assert(receipt.recipe === sha256(join(root, recipePath)), 'Font subset build recipe changed; rebuild the module');
25
+ assert(JSON.stringify(Object.keys(receipt.files).sort()) === JSON.stringify(required.slice().sort()), 'Font subset receipt has an incomplete payload');
26
+ for (const path of required) {
27
+ const file = regularFile(target, path);
28
+ assert(receipt.files[path].bytes === statSync(file).size && receipt.files[path].sha256 === sha256(file), `Font subset payload checksum differs: ${path}`);
29
+ }
30
+ const module = new WebAssembly.Module(readFileSync(join(target, wasmPath)));
31
+ const names = new Set(WebAssembly.Module.exports(module).map(entry => entry.name));
32
+ for (const name of ['memory', '_initialize', 'malloc', 'hb_subset_or_fail', 'hb_subset_input_set']) assert(names.has(name), `Missing font subset export: ${name}`);
33
+ return receipt;
34
+ }
35
+
36
+ /** Compile explicit checked-out commits; this command never fetches or modifies upstream sources. */
37
+ export function buildFontSubset({ source = join(root, '.build/font-subset/harfbuzzjs'), emsdk = join(root, '.build/font-subset/emsdk'), target = join(root, 'packages/entry') } = {}) {
38
+ for (const [path, expected] of [[source, spec.harfbuzzjs.commit], [join(source, 'harfbuzz'), spec.harfbuzz.commit], [emsdk, spec.emsdk.commit]]) {
39
+ assert(run('git', ['rev-parse', 'HEAD'], { cwd: path }).trim() === expected, `Font subset checkout has the wrong commit: ${path}`);
40
+ assert(run('git', ['status', '--porcelain', '--untracked-files=no'], { cwd: path }).trim() === '', `Font subset checkout has tracked changes: ${path}`);
41
+ }
42
+ const invoke = (args) => run('bash', ['-c', 'set -e\nsource "$1" >/dev/null\nshift\nexec em++ "$@"', 'font-subset-build', join(emsdk, 'emsdk_env.sh'), ...args], { cwd: source });
43
+ assert(invoke(['--version']).split('\n')[0].includes(` ${spec.emsdk.version} `), 'Font subset Emscripten version differs');
44
+ mkdirSync(join(target, 'assets'), { recursive: true });
45
+ invoke(['-std=c++11', '-fno-exceptions', '-fno-rtti', '-fno-threadsafe-statics', '-fvisibility-inlines-hidden', '-Oz', '-I.',
46
+ '-DHB_TINY', '-DHB_USE_INTERNAL_QSORT', '-DHB_EXPERIMENTAL_API', '-DHB_CONFIG_OVERRIDE_H="config-override-subset.h"',
47
+ '--no-entry', '-sEXPORTED_FUNCTIONS=@harfbuzz-subset.symbols', '-sINITIAL_MEMORY=68157440',
48
+ '-sALLOW_MEMORY_GROWTH=1', '-sMAXIMUM_MEMORY=2147483648', '-sABORTING_MALLOC=0',
49
+ '-o', join(target, wasmPath), 'harfbuzz/src/harfbuzz-subset.cc']);
50
+ const copies = [...recipeFiles.map(path => [join(root, path), `sources/font-subset/${path}`]),
51
+ [join(source, 'config-override-subset.h'), 'sources/font-subset/harfbuzzjs/config-override-subset.h'],
52
+ [join(source, 'harfbuzz-subset.symbols'), 'sources/font-subset/harfbuzzjs/harfbuzz-subset.symbols'],
53
+ [join(source, 'LICENSE'), 'licenses/font-subset/harfbuzzjs-LICENSE'], [join(source, 'harfbuzz/COPYING'), 'licenses/font-subset/harfbuzz-COPYING']];
54
+ for (const [from, path] of copies) { mkdirSync(join(target, path, '..'), { recursive: true }); cpSync(from, join(target, path)); }
55
+ const files = Object.fromEntries(required.map(path => [path, { bytes: statSync(join(target, path)).size, sha256: sha256(join(target, path)) }]));
56
+ writeFileSync(join(target, receiptPath), `${JSON.stringify({ schemaVersion: 1, source: spec, recipe: sha256(join(root, recipePath)), files }, null, 2)}\n`);
57
+ return verifyFontSubset(target);
58
+ }
59
+
60
+ if (isMain(import.meta.url)) {
61
+ const { values } = parseArgs({ options: { verify: { type: 'boolean' }, source: { type: 'string' }, emsdk: { type: 'string' }, target: { type: 'string' } } });
62
+ const options = Object.fromEntries(['source', 'emsdk', 'target'].filter(key => values[key]).map(key => [key, resolve(values[key])]));
63
+ console.log(JSON.stringify(values.verify ? verifyFontSubset(options.target) : buildFontSubset(options)));
64
+ }
@@ -0,0 +1,69 @@
1
+ /** Local-only npm helpers shared by packaging and offline-install rehearsals. */
2
+ import { existsSync, mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
3
+ import { delimiter, dirname, join, resolve } from 'node:path';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { root } from './platform-matrix.mjs';
6
+
7
+ export function scratch(prefix = 'packaging-') {
8
+ const parent = join(root, '.cache');
9
+ mkdirSync(parent, { recursive: true });
10
+ return mkdtempSync(join(parent, prefix));
11
+ }
12
+
13
+ export function run(command, args, options = {}) {
14
+ const result = spawnSync(command, args, { encoding: 'utf8', timeout: 180_000, maxBuffer: 16 * 1024 * 1024, ...options });
15
+ if (result.error) throw result.error;
16
+ if (result.status !== 0) throw new Error(`${command} exited ${result.status} (${result.signal ?? 'no signal'}):\n${result.stderr}\n${result.stdout}`);
17
+ return result.stdout;
18
+ }
19
+
20
+ /** Invoke npm's JS CLI directly, including on Windows; no command shell is used. */
21
+ export function npmCli() {
22
+ const directories = [dirname(process.execPath), dirname(realpathSync(process.execPath)), ...(process.env.PATH ?? '').split(delimiter)];
23
+ const candidates = [process.env.npm_execpath];
24
+ for (const directory of directories) {
25
+ candidates.push(join(directory, 'node_modules/npm/bin/npm-cli.js'), resolve(directory, '../lib/node_modules/npm/bin/npm-cli.js'));
26
+ const link = join(directory, 'npm');
27
+ if (existsSync(link)) candidates.push(realpathSync(link));
28
+ }
29
+ const found = candidates.find((file) => file && /(?:^|[\\/])npm-cli\.js$/.test(file) && existsSync(file));
30
+ if (!found) throw new Error('npm-cli.js was not found next to Node or on PATH');
31
+ return found;
32
+ }
33
+
34
+ export function npmEnvironment(work) {
35
+ const config = join(work, 'empty.npmrc');
36
+ const globalConfig = join(work, 'empty-global.npmrc');
37
+ writeFileSync(config, '');
38
+ writeFileSync(globalConfig, '');
39
+ return {
40
+ ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !/KEY|TOKEN|SECRET|PASSWORD|^NODE_OPTIONS$|^NODE_PATH$|^NPM_CONFIG_/i.test(key))),
41
+ npm_config_cache: join(work, 'npm-cache'),
42
+ npm_config_userconfig: config,
43
+ npm_config_globalconfig: globalConfig,
44
+ npm_config_audit: 'false',
45
+ npm_config_fund: 'false',
46
+ npm_config_update_notifier: 'false',
47
+ npm_config_registry: 'http://127.0.0.1:9',
48
+ npm_config_offline: 'true',
49
+ };
50
+ }
51
+
52
+ export function npm(args, cwd, work) {
53
+ return run(process.execPath, [npmCli(), ...args], { cwd, env: npmEnvironment(work) });
54
+ }
55
+
56
+ /** Resolve pnpm without invoking a Windows command shim through a shell. */
57
+ export function pnpmInvocation(args, environment = process.env, platform = process.platform) {
58
+ const entry = environment.npm_execpath;
59
+ if (entry && /(?:^|[\\/])pnpm\.[cm]?js$/i.test(entry)) return { command: process.execPath, args: [entry, ...args] };
60
+ if (entry && /(?:^|[\\/])pnpm(?:\.exe)?$/i.test(entry)) return { command: entry, args };
61
+ if (platform === 'win32') throw new Error('Invoke adapter builds and local packs through pnpm run on Windows.');
62
+ return { command: 'pnpm', args };
63
+ }
64
+
65
+ /** Run the pnpm lifecycle executable, retaining each argument without shell parsing. */
66
+ export function pnpm(args, options = {}) {
67
+ const invocation = pnpmInvocation(args);
68
+ return run(invocation.command, invocation.args, options);
69
+ }
@@ -0,0 +1,100 @@
1
+ /** Package metadata shared by release tooling; runtime selection belongs to the adapter package. */
2
+ import { readFileSync, readdirSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ export const root = fileURLToPath(new URL('../', import.meta.url));
7
+ export const enginePrefix = '@deepseek-ai/libreoffice-kit';
8
+ /** Internal repository hosting qualified engine archives for application builds. */
9
+ export const releaseRepository = 'deepseek-harness/libreoffice-kit';
10
+ /** Repository maintaining the source and Actions builds referenced by release evidence. */
11
+ export const sourceRepository = releaseRepository;
12
+ export const wasmName = `${enginePrefix}-wasm`;
13
+ export const kitPackageName = '@deepseek-ai/libreoffice-kit';
14
+ export const nodeRange = '>=22.19.0';
15
+ export const targets = Object.freeze({
16
+ 'darwin-arm64': { os: 'darwin', cpu: 'arm64', runner: 'macos-15' },
17
+ 'darwin-x64': { os: 'darwin', cpu: 'x64', runner: 'macos-15-intel' },
18
+ 'linux-arm64-glibc': { os: 'linux', cpu: 'arm64', libc: 'glibc', runner: 'ubuntu-24.04-arm' },
19
+ 'linux-x64-glibc': { os: 'linux', cpu: 'x64', libc: 'glibc', runner: 'ubuntu-24.04' },
20
+ 'win32-arm64': { os: 'win32', cpu: 'arm64', runner: 'windows-11-arm' },
21
+ 'win32-x64': { os: 'win32', cpu: 'x64', runner: 'windows-2022' },
22
+ });
23
+
24
+ export function readJson(file) {
25
+ return JSON.parse(readFileSync(file, 'utf8'));
26
+ }
27
+
28
+ /** The adapter package directory in this checkout; it declares this family's released engine targets. */
29
+ export function kitDirectory(repo = root) {
30
+ return join(repo, 'packages/entry');
31
+ }
32
+
33
+ /** The adapter package manifest that declares this family's released engine targets. */
34
+ export function kitManifest(repo = root) {
35
+ return readJson(join(kitDirectory(repo), 'package.json'));
36
+ }
37
+
38
+ /** Release tags identify this standalone kit family. */
39
+ export function releaseTag(version) {
40
+ return `libreoffice-kit-v${version}`;
41
+ }
42
+
43
+ /**
44
+ * Versioned download URL for one engine archive attached to the family release.
45
+ * @param version - Engine family version.
46
+ * @param file - Release asset file name.
47
+ * @returns the asset URL, requiring authenticated build-time preparation for internal releases.
48
+ */
49
+ export function releaseAssetUrl(version, file) {
50
+ return `https://github.com/${releaseRepository}/releases/download/${releaseTag(version)}/${encodeURIComponent(file)}`;
51
+ }
52
+
53
+ /** Return the complete declared matrix, including targets without built assets. */
54
+ export function packageMatrix(repo = root) {
55
+ return readdirSync(join(repo, 'packages'), { withFileTypes: true })
56
+ .filter((entry) => entry.isDirectory() && !['entry', 'browser'].includes(entry.name))
57
+ .sort((a, b) => a.name.localeCompare(b.name))
58
+ .map((entry) => {
59
+ const dir = join(repo, 'packages', entry.name);
60
+ return { dir, manifest: readJson(join(dir, 'package.json')), prebuild: readJson(join(dir, 'prebuilds.json')) };
61
+ });
62
+ }
63
+
64
+ /** An unrecognized Linux libc is deliberately not treated as glibc. */
65
+ export function hostTarget(platform = process.platform, arch = process.arch, report = process.report?.getReport()) {
66
+ if (platform !== 'linux') return Object.hasOwn(targets, `${platform}-${arch}`) ? `${platform}-${arch}` : undefined;
67
+ if (!report?.header?.glibcVersionRuntime) return undefined;
68
+ const candidate = `${platform}-${arch}-glibc`;
69
+ return Object.hasOwn(targets, candidate) ? candidate : undefined;
70
+ }
71
+
72
+ /** The adapter declares released native packages; targets also contains unfinished build recipes. */
73
+ export function kitNativeTargets(manifest) {
74
+ return Object.keys(manifest.optionalDependencies ?? {}).filter(name => name !== wasmName).map((name) => {
75
+ const platform = name.slice(enginePrefix.length + 1);
76
+ if (!name.startsWith(`${enginePrefix}-`) || !Object.hasOwn(targets, platform)) throw new Error(`Unknown native optional dependency: ${name}`);
77
+ return platform;
78
+ });
79
+ }
80
+
81
+ /** Explicit development scopes may select a build recipe; defaults use the adapter's release declaration. */
82
+ export function releaseTargets(args, nativeTargets = kitNativeTargets(kitManifest())) {
83
+ const wasmOnly = args.includes('--wasm-only');
84
+ const index = args.indexOf('--platform');
85
+ if (wasmOnly && index !== -1) throw new Error('--wasm-only and --platform are mutually exclusive');
86
+ if (index !== -1) {
87
+ const platform = args[index + 1];
88
+ if (!Object.hasOwn(targets, platform)) throw new Error(`Unknown native platform: ${platform}`);
89
+ return [platform, 'wasm'];
90
+ }
91
+ return wasmOnly ? ['wasm'] : [...nativeTargets, 'wasm'];
92
+ }
93
+
94
+ export function tarballName(manifest) {
95
+ return `${manifest.name.replace(/^@/, '').replace('/', '-')}-${manifest.version}.tgz`;
96
+ }
97
+
98
+ export function isMain(url) {
99
+ return process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(url);
100
+ }