@unieai/libreoffice-kit-wasm 0.0.0-stage → 0.2.3

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 (51) hide show
  1. package/README.md +7 -2
  2. package/assets/dsoffice.cjs +26 -0
  3. package/assets/dsoffice.data +0 -0
  4. package/assets/dsoffice.data.js.metadata +1 -0
  5. package/assets/dsoffice.wasm +4 -0
  6. package/assets/manifest.json +1888 -0
  7. package/licenses/LICENSE +4666 -0
  8. package/licenses/NOTICE +63 -0
  9. package/licenses/Rabi-Harness-MIT.txt +28 -0
  10. package/package.json +22 -4
  11. package/prebuilds.json +128 -0
  12. package/sources/build-autogen.input +35 -0
  13. package/sources/core-source.json +4 -0
  14. package/sources/docs/ui-resources.md +123 -0
  15. package/sources/engine/build-identity.mjs +49 -0
  16. package/sources/engine/core-source.mjs +27 -0
  17. package/sources/engine/document-operations.hxx +51 -0
  18. package/sources/engine/ui-resource-policy.mjs +33 -0
  19. package/sources/engine/wasm-source/autogen.input +33 -0
  20. package/sources/engine/wasm-source/build.mjs +300 -0
  21. package/sources/engine/wasm-source/lok.cxx +428 -0
  22. package/sources/engine/wasm-source/patches/0001-macos-build-tools.patch +87 -0
  23. package/sources/engine/wasm-source/patches/0002-system-font-demand.patch +322 -0
  24. package/sources/engine/wasm-source/patches/0003-node-runtime.patch +99 -0
  25. package/sources/engine/wasm-source/patches/0004-system-fonts-only.patch +10 -0
  26. package/sources/engine/wasm-source/patches/0005-cross-build-rules.patch +46 -0
  27. package/sources/engine/wasm-source/patches/0006-wasm-external-platforms.patch +55 -0
  28. package/sources/engine/wasm-source/patches/0008-disable-link-updates.patch +30 -0
  29. package/sources/engine/wasm-source/patches/0009-disable-optional-curl.patch +11 -0
  30. package/sources/engine/wasm-source/patches/0010-refresh-component-registry.patch +11 -0
  31. package/sources/engine/wasm-source/patches/0011-preserve-optimization-with-prefix-maps.patch +21 -0
  32. package/sources/engine/wasm-source/patches/0012-anonymize-explicit-source-paths.patch +39 -0
  33. package/sources/engine/wasm-source/patches/0023-pdfium-for-embedded-graphics.patch +14 -0
  34. package/sources/engine/wasm-source/patches/0024-pdfium-emscripten-platform.patch +11 -0
  35. package/sources/engine/wasm-source/patches/0025-browser-editing.patch +18 -0
  36. package/sources/engine/wasm-source/patches/0028-synchronous-workbook-calculation.patch +64 -0
  37. package/sources/engine/wasm-source/patches/0029-unloaded-external-blip.patch +21 -0
  38. package/sources/engine/wasm-source/patches/0030-no-password-strength-ui.patch +117 -0
  39. package/sources/engine/wasm-source/patches/0031-size-optimization-lto.patch +26 -0
  40. package/sources/engine/wasm-source/patches/0047-defer-offscreen-canvas-output.patch +59 -0
  41. package/sources/engine/wasm-source/slim.mjs +74 -0
  42. package/sources/engine/wasm-source/source.json +16 -0
  43. package/sources/engine/wasm-source/source.mjs +12 -0
  44. package/sources/engine/wasm-source/stage.mjs +91 -0
  45. package/sources/scripts/checkout-wasm.mjs +24 -0
  46. package/sources/scripts/core-checkout.mjs +39 -0
  47. package/sources/scripts/minimize-ui-resources.py +198 -0
  48. package/sources/scripts/pack-utils.mjs +69 -0
  49. package/sources/scripts/platform-matrix.mjs +122 -0
  50. package/sources/scripts/verify-artifacts.mjs +261 -0
  51. package/sources/source-changes.patch +1081 -0
@@ -0,0 +1,300 @@
1
+ #!/usr/bin/env node
2
+ /** Builds pinned official LibreOffice source into immutable Node.js WASM assets. */
3
+
4
+ import { createHash } from 'node:crypto';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
7
+ import { availableParallelism } from 'node:os';
8
+ import path from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { parseArgs } from 'node:util';
11
+ import { slimWasmData } from './slim.mjs';
12
+ import { assertUiCoreRevision } from '../ui-resource-policy.mjs';
13
+ import { buildEnvironment, buildIdentity, publicBuildValue } from '../build-identity.mjs';
14
+ import { readWasmSource } from './source.mjs';
15
+
16
+ const owner = path.dirname(fileURLToPath(import.meta.url));
17
+ const repository = path.resolve(owner, '../..');
18
+ const cache = path.join(repository, '.build/wasm');
19
+ const pinned = readWasmSource();
20
+ const stages = ['prepare', 'verify', 'configure', 'compile', 'build', 'package'];
21
+ const { values } = parseArgs({
22
+ options: {
23
+ stage: { type: 'string', default: 'build' },
24
+ source: { type: 'string', default: path.join(cache, 'core') },
25
+ emsdk: { type: 'string', default: path.join(cache, 'emsdk') },
26
+ build: { type: 'string', default: path.join(cache, 'build') },
27
+ tarballs: { type: 'string', default: path.join(cache, 'tarballs') },
28
+ output: { type: 'string', default: path.join(cache, 'dist') },
29
+ jobs: { type: 'string', default: String(availableParallelism()) },
30
+ help: { type: 'boolean', default: false },
31
+ },
32
+ });
33
+
34
+ if (values.help) {
35
+ console.log(`Usage: node engine/wasm-source/build.mjs [--stage ${stages.join('|')}] [--source DIR] [--emsdk DIR] [--build DIR] [--tarballs DIR] [--output DIR] [--jobs N]`);
36
+ process.exit(0);
37
+ }
38
+ if (!stages.includes(values.stage)) throw new Error(`Unknown build stage: ${values.stage}`);
39
+ const jobs = Number(values.jobs);
40
+ if (!Number.isSafeInteger(jobs) || jobs < 1) throw new Error('--jobs must be a positive integer');
41
+
42
+ const source = path.resolve(values.source);
43
+ const emsdk = path.resolve(values.emsdk);
44
+ const build = path.resolve(values.build);
45
+ const tarballs = path.resolve(values.tarballs);
46
+ const output = path.resolve(values.output);
47
+ const receiptPath = path.join(build, 'rabi-wasm-build.json');
48
+ const shimTarget = path.join(source, 'desktop/source/lib/rabi_wasm.cxx');
49
+ const operationsTarget = path.join(source, 'desktop/source/lib/rabi_document_operations.hxx');
50
+ const identityPaths = { workspace: repository, source, build, tarballs, emsdk };
51
+ const env = buildEnvironment(process.env, 'wasm', identityPaths);
52
+ const identity = buildIdentity('wasm', identityPaths, env);
53
+ const identityFile = path.join(build, 'rabi-build-identity.json');
54
+ env.MAKE = env.GNUMAKE || env.MAKE || (process.platform === 'darwin' ? 'gmake' : 'make');
55
+ const artifacts = {
56
+ 'soffice.cjs': 'soffice.js',
57
+ 'soffice.wasm': 'soffice.wasm',
58
+ 'soffice.data': 'soffice.data',
59
+ 'soffice.data.js.metadata': 'soffice.data.js.metadata',
60
+ };
61
+
62
+ function run(command, args, options = {}) {
63
+ const result = spawnSync(command, args, { cwd: repository, env, stdio: 'inherit', ...options });
64
+ if (result.error) throw result.error;
65
+ if (result.status !== 0) {
66
+ throw new Error(`${command} exited with ${result.signal ?? result.status}${result.stderr ? `\n${result.stderr.trim()}` : ''}`);
67
+ }
68
+ return result.stdout?.trim();
69
+ }
70
+
71
+ function git(args, cwd = source) {
72
+ return run('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' });
73
+ }
74
+
75
+ function sha256(data) {
76
+ return createHash('sha256').update(data).digest('hex');
77
+ }
78
+
79
+ function hashFile(filename) {
80
+ if (!lstatSync(filename).isFile()) throw new Error(`Expected a regular build file: ${filename}`);
81
+ return sha256(readFileSync(filename));
82
+ }
83
+
84
+ function patches() {
85
+ const files = readdirSync(path.join(owner, pinned.patches)).filter((name) => name.endsWith('.patch')).sort();
86
+ if (files.length === 0) throw new Error('No LibreOffice WASM patches were found');
87
+ return files.map((name) => path.join(owner, pinned.patches, name));
88
+ }
89
+
90
+ function requireCheckout(directory, specification) {
91
+ if (!existsSync(path.join(directory, '.git'))) {
92
+ throw new Error(`Missing official checkout at ${directory}; clone ${specification.repository} and check out ${specification.commit}`);
93
+ }
94
+ const actual = git(['rev-parse', 'HEAD'], directory);
95
+ if (actual !== specification.commit) {
96
+ throw new Error(`${directory} is at ${actual}; required official commit is ${specification.commit}`);
97
+ }
98
+ }
99
+
100
+ function requireCheckouts() {
101
+ requireCheckout(source, pinned.libreoffice);
102
+ requireCheckout(emsdk, pinned.emsdk);
103
+ }
104
+
105
+ function checkPatch(patch, reverse = false) {
106
+ const args = ['apply', '--check', ...(reverse ? ['--reverse'] : []), patch];
107
+ const result = spawnSync('git', args, { cwd: source, env, stdio: 'ignore' });
108
+ if (result.error) throw result.error;
109
+ return result.status === 0;
110
+ }
111
+
112
+ function prepare() {
113
+ requireCheckouts();
114
+ for (const patch of patches()) {
115
+ if (checkPatch(patch)) run('git', ['apply', patch], { cwd: source });
116
+ else if (!checkPatch(patch, true)) {
117
+ throw new Error(`Official source differs from ${path.basename(patch)}; preserve local edits and reconcile the patch`);
118
+ }
119
+ }
120
+ copyFileSync(path.join(owner, '../document-operations.hxx'), operationsTarget);
121
+ const shim = readFileSync(path.join(owner, pinned.shim));
122
+ if (!existsSync(shimTarget) || !readFileSync(shimTarget).equals(shim)) {
123
+ writeFileSync(shimTarget, shim);
124
+ }
125
+ }
126
+
127
+ function withEmsdk(command, args, options = {}) {
128
+ return run('bash', ['-c', 'set -e\nsource "$1" >/dev/null\nshift\nexec "$@"', 'rabi-libreoffice-build', path.join(emsdk, 'emsdk_env.sh'), command, ...args], options);
129
+ }
130
+
131
+ function verifyRecipe() {
132
+ requireCheckouts();
133
+ for (const patch of patches()) {
134
+ if (!checkPatch(patch, true)) throw new Error(`${path.basename(patch)} is not applied; run the prepare stage`);
135
+ }
136
+ if (!existsSync(operationsTarget) || hashFile(operationsTarget) !== hashFile(path.join(owner, '../document-operations.hxx'))) throw new Error('Document operations header does not match the current recipe.');
137
+ if (!existsSync(shimTarget) || hashFile(shimTarget) !== hashFile(path.join(owner, pinned.shim))) {
138
+ throw new Error('The LibreOfficeKit shim differs from the recipe; run the prepare stage');
139
+ }
140
+ const version = withEmsdk('emcc', ['--version'], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' });
141
+ if (!version.split('\n')[0].includes(` ${pinned.emsdk.version} `)) {
142
+ throw new Error(`Emscripten ${pinned.emsdk.version} is required; found ${version.split('\n')[0]}`);
143
+ }
144
+ return version;
145
+ }
146
+
147
+ function configure() {
148
+ verifyRecipe();
149
+ mkdirSync(build, { recursive: true });
150
+ mkdirSync(tarballs, { recursive: true });
151
+ if (existsSync(path.join(build, 'config_host.mk')) && (!existsSync(identityFile)
152
+ || readFileSync(identityFile, 'utf8') !== `${JSON.stringify(identity, null, 2)}\n`))
153
+ throw new Error('WASM build identity differs; use a fresh build directory');
154
+ const configuration = readFileSync(path.join(owner, 'autogen.input'), 'utf8');
155
+ writeFileSync(path.join(build, 'autogen.input'), `${configuration}--with-external-tar=${tarballs}\n--with-parallelism=${jobs}\n`);
156
+ withEmsdk(path.join(source, 'autogen.sh'), [], { cwd: build });
157
+ writeFileSync(identityFile, `${JSON.stringify(identity, null, 2)}\n`);
158
+ }
159
+
160
+ function buildInputs() {
161
+ if (!existsSync(identityFile) || readFileSync(identityFile, 'utf8') !== `${JSON.stringify(identity, null, 2)}\n`)
162
+ throw new Error('WASM build identity differs; run the configure and compile stages');
163
+ return {
164
+ buildIdentity: identity,
165
+ source: readWasmSource(),
166
+ recipe: hashFile(path.join(owner, 'autogen.input')),
167
+ configuration: hashFile(path.join(build, 'autogen.input')),
168
+ hostConfiguration: hashFile(path.join(build, 'config_host.mk')),
169
+ buildConfiguration: hashFile(path.join(build, 'config_build.mk')),
170
+ sourceChanges: sha256(git(['diff', '--binary', 'HEAD', '--'])),
171
+ shim: hashFile(shimTarget),
172
+ operations: hashFile(operationsTarget),
173
+ toolchain: verifyRecipe(),
174
+ patches: Object.fromEntries(patches().map((patch) => [path.basename(patch), hashFile(patch)])),
175
+ };
176
+ }
177
+
178
+ function artifactHashes() {
179
+ const program = path.join(build, 'instdir/program');
180
+ const metadata = JSON.parse(readFileSync(path.join(program, 'soffice.data.js.metadata'), 'utf8'));
181
+ if (!Array.isArray(metadata.files) || metadata.files.some((file) => typeof file.filename !== 'string')) {
182
+ throw new Error('The LibreOffice WASM data metadata has no valid file inventory');
183
+ }
184
+ const fonts = metadata.files.filter((file) => /\.(?:ttf|otf|ttc|otc|woff2?|dfont|pfa|pfb|pfr|bdf|pcf)(?:\.gz)?$/i.test(file.filename));
185
+ if (fonts.length > 0) throw new Error(`The LibreOffice WASM bundle contains fonts: ${fonts.map((file) => file.filename).join(', ')}`);
186
+ return Object.fromEntries(Object.entries(artifacts).map(([name, filename]) => [name, hashFile(path.join(program, filename))]));
187
+ }
188
+
189
+ function compile() {
190
+ const inputs = buildInputs();
191
+ withEmsdk(env.MAKE, ['build', `PARALLELISM=${jobs}`], { cwd: build });
192
+ if (JSON.stringify(inputs) !== JSON.stringify(buildInputs())) {
193
+ throw new Error('LibreOffice build inputs changed during compilation; rerun the compile stage');
194
+ }
195
+ const files = artifactHashes();
196
+ writeFileSync(receiptPath, `${JSON.stringify({ inputs, files }, null, 2)}\n`);
197
+ }
198
+
199
+ function packageArtifacts() {
200
+ assertUiCoreRevision(pinned.libreoffice.commit);
201
+ if (!existsSync(receiptPath)) throw new Error('No successful LibreOffice build receipt exists; run the compile stage');
202
+ const receipt = JSON.parse(readFileSync(receiptPath, 'utf8'));
203
+ const compiledInputs = buildInputs();
204
+ const compiledFiles = artifactHashes();
205
+ if (JSON.stringify(receipt.inputs) !== JSON.stringify(compiledInputs) || JSON.stringify(receipt.files) !== JSON.stringify(compiledFiles)) {
206
+ throw new Error('LibreOffice sources or assets differ from the successful build receipt; rerun the compile stage');
207
+ }
208
+ const program = path.join(build, 'instdir/program');
209
+ const originalData = readFileSync(path.join(program, artifacts['soffice.data']));
210
+ const originalMetadata = readFileSync(path.join(program, artifacts['soffice.data.js.metadata']));
211
+ if (sha256(originalData) !== compiledFiles['soffice.data'] || sha256(originalMetadata) !== compiledFiles['soffice.data.js.metadata']) {
212
+ throw new Error('LibreOffice filesystem image changed during packaging');
213
+ }
214
+ const slimmed = slimWasmData(originalData, JSON.parse(originalMetadata.toString('utf8')));
215
+ const originalLoader = readFileSync(path.join(program, artifacts['soffice.cjs']));
216
+ if (sha256(originalLoader) !== compiledFiles['soffice.cjs']) throw new Error('WASM loader changed during packaging');
217
+ const repacked = {
218
+ // Emscripten embeds the data image's build path in diagnostic dependency names.
219
+ 'soffice.cjs': Buffer.from(publicBuildValue(originalLoader.toString('utf8'), identityPaths)
220
+ .replaceAll('soffice.wasm', 'dsoffice.wasm').replaceAll('soffice.data', 'dsoffice.data')),
221
+ 'soffice.data': slimmed.data,
222
+ 'soffice.data.js.metadata': Buffer.from(`${JSON.stringify(slimmed.metadata)}\n`),
223
+ };
224
+ const inputs = { ...compiledInputs, packaging: {
225
+ recipes: Object.fromEntries(['build.mjs', 'slim.mjs', '../build-identity.mjs', '../ui-resource-policy.mjs'].map(name => [name, hashFile(path.join(owner, name))])),
226
+ compiledFiles,
227
+ } };
228
+ const packagedName = name => name.replace(/^soffice\./, 'dsoffice.');
229
+ const files = Object.fromEntries(Object.entries({ ...compiledFiles,
230
+ ...Object.fromEntries(Object.entries(repacked).map(([name, bytes]) => [name, sha256(bytes)])),
231
+ }).map(([name, hash]) => [packagedName(name), hash]));
232
+ const manifest = {
233
+ schemaVersion: 2,
234
+ runtime: 'node',
235
+ entry: 'dsoffice.cjs',
236
+ wasm: 'dsoffice.wasm',
237
+ data: 'dsoffice.data',
238
+ metadata: 'dsoffice.data.js.metadata',
239
+ programPath: '/instdir/program',
240
+ version: pinned.libreoffice.version,
241
+ sourceCommit: pinned.libreoffice.commit,
242
+ buildId: sha256(JSON.stringify({ inputs, files })),
243
+ files,
244
+ inputs,
245
+ slimming: { removed: slimmed.removed, removedBytes: slimmed.removedBytes },
246
+ };
247
+ const serialized = `${JSON.stringify(manifest, null, 2)}\n`;
248
+ if (existsSync(output)) {
249
+ const prior = path.join(output, 'manifest.json');
250
+ if (!existsSync(prior) || readFileSync(prior, 'utf8') !== serialized
251
+ || Object.entries(files).some(([name, hash]) => hashFile(path.join(output, name)) !== hash)) {
252
+ throw new Error(`The artifact directory already contains a different or incomplete bundle: ${output}; choose a new --output directory`);
253
+ }
254
+ } else {
255
+ mkdirSync(path.dirname(output), { recursive: true });
256
+ const staging = mkdtempSync(path.join(path.dirname(output), `.${path.basename(output)}-`));
257
+ let published = false;
258
+ try {
259
+ for (const [name, filename] of Object.entries(artifacts)) {
260
+ const target = path.join(staging, packagedName(name));
261
+ if (repacked[name]) writeFileSync(target, repacked[name]);
262
+ else copyFileSync(path.join(program, filename), target);
263
+ if (hashFile(target) !== files[packagedName(name)]) throw new Error(`LibreOffice asset changed during packaging: ${filename}`);
264
+ }
265
+ writeFileSync(path.join(staging, 'manifest.json'), serialized);
266
+ renameSync(staging, output);
267
+ published = true;
268
+ } finally {
269
+ if (!published) rmSync(staging, { recursive: true, force: true });
270
+ }
271
+ }
272
+ console.log(`LibreOffice ${manifest.version} WASM bundle: ${output}`);
273
+ console.log(`Build ID: ${manifest.buildId}`);
274
+ }
275
+
276
+ switch (values.stage) {
277
+ case 'prepare':
278
+ prepare();
279
+ break;
280
+ case 'verify':
281
+ verifyRecipe();
282
+ console.log('Pinned source, patches, LibreOfficeKit shim and Emscripten verified.');
283
+ break;
284
+ case 'configure':
285
+ prepare();
286
+ configure();
287
+ break;
288
+ case 'compile':
289
+ compile();
290
+ break;
291
+ case 'build':
292
+ prepare();
293
+ configure();
294
+ compile();
295
+ packageArtifacts();
296
+ break;
297
+ case 'package':
298
+ packageArtifacts();
299
+ break;
300
+ }