@deepseek-ai/libreoffice-kit 0.0.2-rc7 → 0.0.2-rc9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2457,6 +2457,14 @@ ${XMLNS_NAMESPACE}.`);
2457
2457
  bytes: new Uint8Array(channel, 8)
2458
2458
  };
2459
2459
  }
2460
+ /** @returns Empty runtime-owned font state shared by successive documents. */
2461
+ function createEngineFontCache() {
2462
+ return {
2463
+ installed: /* @__PURE__ */ new Map(),
2464
+ aliases: /* @__PURE__ */ new Map(),
2465
+ loadedBytes: 0
2466
+ };
2467
+ }
2460
2468
  const SCRIPT_GROUPS = [
2461
2469
  ["arabic", /\p{Script_Extensions=Arabic}/u],
2462
2470
  ["cyrillic", /\p{Script_Extensions=Cyrillic}/u],
@@ -2476,10 +2484,9 @@ ${XMLNS_NAMESPACE}.`);
2476
2484
  return SCRIPT_GROUPS.find(([, pattern]) => pattern.test(character))?.[0] ?? `other-${point >>> 8}`;
2477
2485
  }
2478
2486
  /** The synchronous reader installs immutable font assets before returning their MEMFS paths and aliases. */
2479
- function createFontReader(channel, timeoutMs, maxLoadedFontBytes, declaredFamilies, request, next, install, missing, documentCodePoints = []) {
2487
+ function createFontReader(channel, timeoutMs, maxLoadedFontBytes, declaredFamilies, request, next, install, missing, documentCodePoints = [], cache = createEngineFontCache()) {
2480
2488
  const { control, bytes } = fontViews(channel);
2481
- const installed = /* @__PURE__ */ new Map();
2482
- const aliases = /* @__PURE__ */ new Map();
2489
+ const { installed, aliases } = cache;
2483
2490
  const requests = /* @__PURE__ */ new Map();
2484
2491
  const coverage = /* @__PURE__ */ new Map();
2485
2492
  const expanded = /* @__PURE__ */ new Map();
@@ -2491,7 +2498,6 @@ ${XMLNS_NAMESPACE}.`);
2491
2498
  else documentGroups.set(group, [point]);
2492
2499
  }
2493
2500
  const families = /* @__PURE__ */ new Set();
2494
- let loadedBytes = 0;
2495
2501
  function read() {
2496
2502
  const started = performance.now();
2497
2503
  while (Atomics.load(control, 0) === 0) {
@@ -2565,7 +2571,7 @@ ${XMLNS_NAMESPACE}.`);
2565
2571
  const alias = normalize(font.alias);
2566
2572
  const previousAlias = aliases.get(alias);
2567
2573
  if (previousAlias && (previousAlias.family !== font.family || font.format === void 0 && previousAlias.id !== font.id)) throw new BrowserRenderError("font-unavailable", "Font alias identifies conflicting subsets.");
2568
- if (!prior && loadedBytes + font.bytes > maxLoadedFontBytes) throw new BrowserRenderError("font-limit", "Imported fonts exceed maxLoadedFontBytes.");
2574
+ if (!prior && cache.loadedBytes + font.bytes > maxLoadedFontBytes) throw new BrowserRenderError("font-limit", "Imported fonts exceed maxLoadedFontBytes.");
2569
2575
  const buffer = prior ? void 0 : new Uint8Array(font.bytes);
2570
2576
  let received = 0;
2571
2577
  while (!font.reference && received < font.bytes) {
@@ -2585,7 +2591,7 @@ ${XMLNS_NAMESPACE}.`);
2585
2591
  bytes: buffer.length,
2586
2592
  format: font.format
2587
2593
  });
2588
- loadedBytes += buffer.length;
2594
+ cache.loadedBytes += buffer.length;
2589
2595
  }
2590
2596
  aliases.set(alias, {
2591
2597
  id: font.id,
@@ -2826,7 +2832,8 @@ ${XMLNS_NAMESPACE}.`);
2826
2832
  geometryDirty = false;
2827
2833
  stopped = false;
2828
2834
  layoutWidth = 0;
2829
- viewport = "";
2835
+ viewportKey = "";
2836
+ viewportState = null;
2830
2837
  captureView;
2831
2838
  readingView;
2832
2839
  commandResult;
@@ -3028,7 +3035,8 @@ ${XMLNS_NAMESPACE}.`);
3028
3035
  ...this.state,
3029
3036
  part
3030
3037
  };
3031
- this.viewport = "";
3038
+ this.viewportKey = "";
3039
+ this.viewportState = null;
3032
3040
  this.geometryDirty = true;
3033
3041
  changed = true;
3034
3042
  }
@@ -3150,7 +3158,8 @@ ${XMLNS_NAMESPACE}.`);
3150
3158
  const part = integer(operation.part, this.state.parts.length - 1);
3151
3159
  if (part === this.state.part) break;
3152
3160
  this.invoke("part", [part]);
3153
- this.viewport = "";
3161
+ this.viewportKey = "";
3162
+ this.viewportState = null;
3154
3163
  this.state = {
3155
3164
  ...this.state,
3156
3165
  part,
@@ -3190,9 +3199,13 @@ ${XMLNS_NAMESPACE}.`);
3190
3199
  twips(height)
3191
3200
  ];
3192
3201
  const key = args.join(",");
3193
- if (key !== this.viewport) {
3202
+ if (key !== this.viewportKey) {
3194
3203
  this.invoke("viewport", args);
3195
- this.viewport = key;
3204
+ this.viewportKey = key;
3205
+ this.viewportState = {
3206
+ rectangle: { ...operation.rectangle },
3207
+ scale: operation.scale
3208
+ };
3196
3209
  }
3197
3210
  break;
3198
3211
  }
@@ -3205,7 +3218,8 @@ ${XMLNS_NAMESPACE}.`);
3205
3218
  if (request.mode === this.state.layout && width === this.layoutWidth) return { layout: { changed: false } };
3206
3219
  const result = this.configure(request);
3207
3220
  this.layoutWidth = width;
3208
- this.viewport = "";
3221
+ this.viewportKey = "";
3222
+ this.viewportState = null;
3209
3223
  this.state = {
3210
3224
  ...this.state,
3211
3225
  layout: request.mode,
@@ -3281,6 +3295,98 @@ ${XMLNS_NAMESPACE}.`);
3281
3295
  this.commandResult = void 0;
3282
3296
  }
3283
3297
  }
3298
+ /** Read the part and selection the next open of these bytes must restore. */
3299
+ capture() {
3300
+ this.requireOpen();
3301
+ if (this.readingView !== void 0) this.invoke("set_view", [this.readingView]);
3302
+ this.flush();
3303
+ const raw = this.text("dsh_lok_document_capture_reading_selection", [this.document]);
3304
+ let text = null;
3305
+ let cell = null;
3306
+ let object = null;
3307
+ if (raw !== null && raw !== "") {
3308
+ const selection = JSON.parse(raw);
3309
+ if (selection.kind === "text") text = {
3310
+ pointNode: integer(selection.pointNode),
3311
+ pointOffset: integer(selection.pointOffset),
3312
+ markNode: integer(selection.markNode),
3313
+ markOffset: integer(selection.markOffset)
3314
+ };
3315
+ else if (selection.kind === "cell" && typeof selection.range === "string") {
3316
+ parseCellRange(selection.range);
3317
+ cell = selection.range;
3318
+ } else if (selection.kind === "object" && typeof selection.paths === "string") {
3319
+ const paths = selection.paths.split(",");
3320
+ if (paths.some((path) => path === "" || path.split("/").some((value) => value === ""))) throw new BrowserRenderError("render-failed", "LibreOffice returned an invalid object selection.");
3321
+ object = paths.map((path) => path.split("/").map((value) => integer(Number(value))));
3322
+ }
3323
+ }
3324
+ const layout = this.state.layout === "continuous" ? {
3325
+ mode: "continuous",
3326
+ width: this.layoutWidth / 15
3327
+ } : { mode: "paginated" };
3328
+ return {
3329
+ version: 1,
3330
+ documentType: this.state.documentType,
3331
+ part: this.state.part,
3332
+ layout,
3333
+ viewport: this.viewportState,
3334
+ text,
3335
+ cell,
3336
+ object
3337
+ };
3338
+ }
3339
+ /**
3340
+ * Apply a reading position captured from the same bytes.
3341
+ * @param state - Part and selection captured before this document closed.
3342
+ */
3343
+ async restore(state) {
3344
+ this.requireOpen();
3345
+ if (state.version !== 1 || state.documentType !== this.state.documentType) throw new BrowserRenderError("render-failed", "The captured reading state belongs to another document.");
3346
+ if (this.state.documentType === "text") {
3347
+ if (state.layout.mode === "continuous") {
3348
+ const anchor = state.viewport === null ? void 0 : {
3349
+ x: state.viewport.rectangle.x,
3350
+ y: state.viewport.rectangle.y
3351
+ };
3352
+ await this.operation({
3353
+ type: "layout",
3354
+ request: {
3355
+ mode: "continuous",
3356
+ width: state.layout.width,
3357
+ ...anchor === void 0 ? {} : { anchor }
3358
+ }
3359
+ });
3360
+ } else if (state.layout.mode !== "paginated") throw new BrowserRenderError("render-failed", "The captured reading layout is invalid.");
3361
+ } else if (state.layout.mode !== "paginated") throw new BrowserRenderError("render-failed", "The captured reading layout belongs to a Writer document.");
3362
+ if (this.state.documentType !== "text" && state.part !== this.state.part) await this.operation({
3363
+ type: "part",
3364
+ part: state.part
3365
+ });
3366
+ if (state.text && this.state.documentType === "text") {
3367
+ const { pointNode, pointOffset, markNode, markOffset } = state.text;
3368
+ this.invoke("restore_reading_text_selection", [
3369
+ integer(pointNode),
3370
+ integer(pointOffset),
3371
+ integer(markNode),
3372
+ integer(markOffset)
3373
+ ]);
3374
+ }
3375
+ if (state.cell && this.state.documentType === "spreadsheet") await this.operation({
3376
+ type: "cell",
3377
+ address: state.cell
3378
+ });
3379
+ if (state.object && this.state.documentType === "presentation") {
3380
+ const paths = state.object.map((path) => path.map((value) => integer(value)).join("/")).join(",");
3381
+ if (!paths) throw new BrowserRenderError("render-failed", "The captured object selection is invalid.");
3382
+ this.invoke("restore_reading_object_selection", [paths]);
3383
+ }
3384
+ if (state.viewport !== null) await this.operation({
3385
+ type: "viewport",
3386
+ ...state.viewport
3387
+ });
3388
+ this.pump();
3389
+ }
3284
3390
  /** Direct tiles preserve the active view, navigation state and selection. */
3285
3391
  render(request) {
3286
3392
  this.requireOpen();
@@ -3308,8 +3414,19 @@ ${XMLNS_NAMESPACE}.`);
3308
3414
  };
3309
3415
  //#endregion
3310
3416
  //#region lib/types/worker.js
3311
- /** Classic Worker entry: serializes one LibreOffice instance and owns its pthreads. */
3417
+ /** Classic Worker entry: serializes one LibreOffice instance, its documents and its pthreads. */
3312
3418
  const scope = globalThis;
3419
+ /** Host font request that installs a fallback face before LibreOffice resolves any family. */
3420
+ const initialFont = {
3421
+ family: "sans-serif",
3422
+ style: "",
3423
+ weight: 5,
3424
+ italic: 0,
3425
+ width: 5,
3426
+ pitch: 0,
3427
+ language: "",
3428
+ codePoints: []
3429
+ };
3313
3430
  let module;
3314
3431
  let office = 0;
3315
3432
  let document = 0;
@@ -3320,6 +3437,12 @@ ${XMLNS_NAMESPACE}.`);
3320
3437
  let fontFailure;
3321
3438
  let serial = Promise.resolve();
3322
3439
  const lifetime = new AbortController();
3440
+ let runtime;
3441
+ let resolveFonts;
3442
+ /** MEMFS path of the open document; removed when its model is released. */
3443
+ let source;
3444
+ /** Font identities and files retained until this runtime is destroyed. */
3445
+ const fontCache = createEngineFontCache();
3323
3446
  function send(message, transfer = []) {
3324
3447
  scope.postMessage(message, transfer);
3325
3448
  }
@@ -3337,34 +3460,31 @@ ${XMLNS_NAMESPACE}.`);
3337
3460
  call("free", [pointer]);
3338
3461
  }
3339
3462
  }
3340
- async function open(options, channel, reading = false) {
3463
+ /**
3464
+ * Bind one document's declared families to the runtime's font channel.
3465
+ * The first synchronous read of a request consumes the Host response that was
3466
+ * requested before the engine's filesystem was configured.
3467
+ */
3468
+ function installFonts(loaded, options, families, codePoints, consumeInitial) {
3469
+ loaded.FS.writeFile("/dsh/fonts.conf", new TextEncoder().encode(memoryFontConfig(options.fontFallbacks, families.values())));
3470
+ return createFontReader(runtime.channel, options.timeoutMs, options.maxLoadedFontBytes, families, (request, known) => {
3471
+ if (consumeInitial.pending) consumeInitial.pending = false;
3472
+ else send({
3473
+ type: "font",
3474
+ request,
3475
+ known
3476
+ });
3477
+ }, () => send({ type: "font-next" }), (path, bytes) => {
3478
+ loaded.FS.writeFile(path, bytes);
3479
+ }, (missing) => send({
3480
+ type: "missing-fonts",
3481
+ families: missing
3482
+ }), codePoints, fontCache);
3483
+ }
3484
+ /** Create this runtime's WASM module, filesystem configuration and office instance once. */
3485
+ async function createEngine(options, families, codePoints, consumeInitial, portableDocument) {
3341
3486
  const { assets } = options;
3342
3487
  const prepared = options.preparedEngine === void 0 ? void 0 : preparedBrowserModule(options.preparedEngine, assets);
3343
- let metadata;
3344
- try {
3345
- metadata = options.extension === "pdf" ? {
3346
- families: /* @__PURE__ */ new Map(),
3347
- codePoints: []
3348
- } : inspectDocument(options.data, options.extension, options);
3349
- } catch (failure) {
3350
- throw new BrowserRenderError("invalid-document", failure instanceof Error ? failure.message : String(failure));
3351
- }
3352
- const initialFont = {
3353
- family: "sans-serif",
3354
- style: "",
3355
- weight: 5,
3356
- italic: 0,
3357
- width: 5,
3358
- pitch: 0,
3359
- language: "",
3360
- codePoints: []
3361
- };
3362
- let initialFontPending = options.extension !== "pdf";
3363
- if (initialFontPending) send({
3364
- type: "font",
3365
- request: initialFont,
3366
- known: []
3367
- });
3368
3488
  const response = await fetch(assets.dataUrl, {
3369
3489
  credentials: "same-origin",
3370
3490
  signal: lifetime.signal
@@ -3372,8 +3492,7 @@ ${XMLNS_NAMESPACE}.`);
3372
3492
  if (!response.ok) throw new BrowserRenderError("unavailable", `LibreOffice data request failed: ${response.status}`);
3373
3493
  const data = await response.arrayBuffer();
3374
3494
  scope.importScripts(assets.loaderUrl);
3375
- let resolveFonts;
3376
- module = await scope.createLibreOfficeModule({
3495
+ const created = await scope.createLibreOfficeModule({
3377
3496
  noInitialRun: true,
3378
3497
  dshOnCallback(type, payload) {
3379
3498
  reader?.callback(type, payload);
@@ -3410,30 +3529,19 @@ ${XMLNS_NAMESPACE}.`);
3410
3529
  "/dsh-fonts",
3411
3530
  "/usr/share/fonts/dsh-pdfium"
3412
3531
  ]) loaded.FS.mkdirTree(path);
3413
- loaded.FS.writeFile("/dsh/fonts.conf", new TextEncoder().encode(memoryFontConfig(options.fontFallbacks, metadata.families.values())));
3532
+ resolveFonts = installFonts(loaded, options, families, codePoints, consumeInitial);
3533
+ if (portableDocument) for (const family of new Set(options.fontFallbacks.flat())) resolveFonts({
3534
+ ...initialFont,
3535
+ family,
3536
+ mode: "full"
3537
+ });
3538
+ else resolveFonts(initialFont);
3414
3539
  Object.assign(loaded.ENV, {
3415
3540
  HOME: "/dsh/profile",
3416
3541
  TMPDIR: "/tmp",
3417
3542
  FONTCONFIG_FILE: "/dsh/fonts.conf",
3418
3543
  LOK_HOST_ALLOWLIST: "^$"
3419
3544
  });
3420
- resolveFonts = createFontReader(channel, options.timeoutMs, options.maxLoadedFontBytes, metadata.families, (request, known) => {
3421
- if (initialFontPending) initialFontPending = false;
3422
- else send({
3423
- type: "font",
3424
- request,
3425
- known
3426
- });
3427
- }, () => send({ type: "font-next" }), (path, bytes) => loaded.FS.writeFile(path, bytes), (families) => send({
3428
- type: "missing-fonts",
3429
- families
3430
- }), metadata.codePoints);
3431
- if (options.extension === "pdf") for (const family of new Set(options.fontFallbacks.flat())) resolveFonts({
3432
- ...initialFont,
3433
- family,
3434
- mode: "full"
3435
- });
3436
- else resolveFonts(initialFont);
3437
3545
  }],
3438
3546
  onAbort() {
3439
3547
  fatal = true;
@@ -3441,12 +3549,42 @@ ${XMLNS_NAMESPACE}.`);
3441
3549
  print() {},
3442
3550
  printErr() {}
3443
3551
  });
3444
- if (options.extension === "pdf") {
3445
- const pointer = call("malloc", [options.data.byteLength]);
3552
+ module = created;
3553
+ office = created.ccall("dsh_lok_initialize", "number", ["string", "string"], [assets.programDirectory, "file:///dsh/profile"]);
3554
+ if (!office) throw error("unavailable");
3555
+ }
3556
+ /** Load one document into the already initialized engine. */
3557
+ async function openDocument(options) {
3558
+ if (!runtime) throw new BrowserRenderError("disposed", "LibreOffice Worker has not been started.");
3559
+ const engine = runtime.options;
3560
+ const reading = options.extension !== "pdf";
3561
+ let metadata;
3562
+ try {
3563
+ metadata = reading ? inspectDocument(options.data, options.extension, engine) : {
3564
+ families: /* @__PURE__ */ new Map(),
3565
+ codePoints: []
3566
+ };
3567
+ } catch (failure) {
3568
+ throw new BrowserRenderError("invalid-document", failure instanceof Error ? failure.message : String(failure));
3569
+ }
3570
+ if (reading) send({
3571
+ type: "font",
3572
+ request: initialFont,
3573
+ known: []
3574
+ });
3575
+ const consumeInitial = { pending: reading };
3576
+ if (!module) await createEngine(engine, metadata.families, metadata.codePoints, consumeInitial, !reading);
3577
+ else {
3578
+ resolveFonts = installFonts(module, engine, metadata.families, metadata.codePoints, consumeInitial);
3579
+ if (reading) resolveFonts(initialFont);
3580
+ }
3581
+ const loaded = module;
3582
+ if (!reading) {
3583
+ const pointer = loaded.ccall("malloc", "number", ["number"], [options.data.byteLength]);
3446
3584
  if (!pointer) throw error("invalid-document");
3447
3585
  try {
3448
- new Uint8Array(module.HEAPU32.buffer, pointer, options.data.byteLength).set(options.data);
3449
- pdf = module.ccall("dsh_pdf_open", "number", [
3586
+ new Uint8Array(loaded.HEAPU32.buffer, pointer, options.data.byteLength).set(options.data);
3587
+ pdf = loaded.ccall("dsh_pdf_open", "number", [
3450
3588
  "number",
3451
3589
  "number",
3452
3590
  "string"
@@ -3459,14 +3597,13 @@ ${XMLNS_NAMESPACE}.`);
3459
3597
  call("free", [pointer]);
3460
3598
  }
3461
3599
  if (!pdf) throw error("invalid-document");
3462
- pages = pdfPages(module, pdf, () => error("invalid-document"));
3600
+ pages = pdfPages(loaded, pdf, () => error("invalid-document"));
3463
3601
  return;
3464
3602
  }
3465
3603
  const input = `/dsh/document.${options.extension}`;
3466
- module.FS.writeFile(input, options.data);
3467
- office = module.ccall("dsh_lok_initialize", "number", ["string", "string"], [assets.programDirectory, "file:///dsh/profile"]);
3468
- if (!office) throw error("invalid-document");
3469
- document = module.ccall("dsh_lok_document_load", "number", [
3604
+ loaded.FS.writeFile(input, options.data);
3605
+ source = input;
3606
+ document = loaded.ccall("dsh_lok_document_load", "number", [
3470
3607
  "number",
3471
3608
  "string",
3472
3609
  "string"
@@ -3478,38 +3615,31 @@ ${XMLNS_NAMESPACE}.`);
3478
3615
  if (!document || !call("dsh_lok_document_initialize_rendering", [document])) throw error("invalid-document");
3479
3616
  const type = call("dsh_lok_document_type", [document]);
3480
3617
  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.");
3481
- if (reading) {
3482
- reader = new OfficeEngine(module, document, options.extension, (event) => send({
3618
+ const engineReader = reader = new OfficeEngine(loaded, document, options.extension, (event) => send({
3619
+ type: "office-event",
3620
+ event
3621
+ }), (failure) => {
3622
+ fatal ||= failure instanceof WebAssembly.RuntimeError;
3623
+ send({
3483
3624
  type: "office-event",
3484
- event
3485
- }), (failure) => {
3486
- fatal ||= failure instanceof WebAssembly.RuntimeError;
3487
- send({
3488
- type: "office-event",
3489
- event: {
3490
- type: "error",
3491
- code: "render-failed",
3492
- message: failure instanceof Error ? failure.message : String(failure)
3493
- }
3494
- });
3625
+ event: {
3626
+ type: "error",
3627
+ code: "render-failed",
3628
+ message: failure instanceof Error ? failure.message : String(failure)
3629
+ }
3495
3630
  });
3496
- await reader.start();
3497
- pages = reader.state.parts.map((part, index) => ({
3498
- ...part,
3499
- x: 0,
3500
- y: 0,
3501
- part: type === 0 ? -1 : index
3502
- }));
3503
- return;
3504
- }
3505
- throw new BrowserRenderError("invalid-document", "Office documents require a retained session.");
3506
- }
3507
- function render(request) {
3508
- if (fatal) throw new BrowserRenderError("render-failed", "LibreOffice Worker has aborted.");
3509
- if (!pdf || !module) throw new BrowserRenderError("disposed", "The document is closed.");
3510
- return renderRegion(module, pdf, request, pages, () => error("render-failed"), true);
3631
+ });
3632
+ await engineReader.start();
3633
+ if (options.restore) await engineReader.restore(options.restore);
3634
+ pages = engineReader.state.parts.map((part, index) => ({
3635
+ ...part,
3636
+ x: 0,
3637
+ y: 0,
3638
+ part: type === 0 ? -1 : index
3639
+ }));
3511
3640
  }
3512
- function dispose() {
3641
+ /** Release the open document's model, MEMFS bytes and installed fonts; keep the engine. */
3642
+ function closeDocument() {
3513
3643
  reader?.stop();
3514
3644
  reader = void 0;
3515
3645
  try {
@@ -3524,19 +3654,44 @@ ${XMLNS_NAMESPACE}.`);
3524
3654
  document = 0;
3525
3655
  if (!call("dsh_lok_document_destroy", [value])) throw error("render-failed");
3526
3656
  }
3527
- if (office) {
3528
- const value = office;
3529
- office = 0;
3530
- if (!call("dsh_lok_destroy", [value])) throw error("render-failed");
3531
- }
3657
+ if (source !== void 0) unlink(source);
3532
3658
  }
3533
3659
  } finally {
3534
- module?.PThread.terminateAllThreads();
3535
- module = void 0;
3660
+ resolveFonts = void 0;
3661
+ pages = [];
3662
+ source = void 0;
3536
3663
  document = 0;
3537
3664
  pdf = 0;
3665
+ }
3666
+ }
3667
+ /** Remove one MEMFS path; a missing file means the engine already released it. */
3668
+ function unlink(path) {
3669
+ try {
3670
+ module?.FS.unlink(path);
3671
+ } catch (failure) {
3672
+ if (!(failure instanceof Error) || !/no such file|does not exist/i.test(failure.message)) throw failure;
3673
+ }
3674
+ }
3675
+ function render(request) {
3676
+ if (fatal) throw new BrowserRenderError("render-failed", "LibreOffice Worker has aborted.");
3677
+ if (!pdf || !module) throw new BrowserRenderError("disposed", "The document is closed.");
3678
+ return renderRegion(module, pdf, request, pages, () => error("render-failed"), true);
3679
+ }
3680
+ /** Destroy the office instance and every pthread after the documents are closed. */
3681
+ function dispose() {
3682
+ closeDocument();
3683
+ try {
3684
+ if (module && !fatal && office) {
3685
+ const value = office;
3686
+ office = 0;
3687
+ if (!call("dsh_lok_destroy", [value])) throw error("render-failed");
3688
+ }
3689
+ } finally {
3690
+ module?.PThread.terminateAllThreads();
3691
+ module = void 0;
3538
3692
  office = 0;
3539
3693
  pages = [];
3694
+ runtime = void 0;
3540
3695
  }
3541
3696
  }
3542
3697
  scope.onmessage = (event) => {
@@ -3548,8 +3703,19 @@ ${XMLNS_NAMESPACE}.`);
3548
3703
  serial = serial.then(async () => {
3549
3704
  try {
3550
3705
  switch (message.type) {
3706
+ case "start":
3707
+ runtime = {
3708
+ options: message.options,
3709
+ channel: message.channel
3710
+ };
3711
+ send({
3712
+ type: "started",
3713
+ id: message.id
3714
+ });
3715
+ break;
3551
3716
  case "open":
3552
- await open(message.options, message.channel, message.office);
3717
+ if (document || pdf) closeDocument();
3718
+ await openDocument(message.options);
3553
3719
  send({
3554
3720
  type: "opened",
3555
3721
  id: message.id,
@@ -3560,6 +3726,21 @@ ${XMLNS_NAMESPACE}.`);
3560
3726
  ...reader ? { office: reader.state } : {}
3561
3727
  });
3562
3728
  break;
3729
+ case "close-document":
3730
+ closeDocument();
3731
+ send({
3732
+ type: "closed-document",
3733
+ id: message.id
3734
+ });
3735
+ break;
3736
+ case "reading-state":
3737
+ if (!reader) throw new BrowserRenderError("disposed", "Office document is closed.");
3738
+ send({
3739
+ type: "reading-state",
3740
+ id: message.id,
3741
+ state: reader.capture()
3742
+ });
3743
+ break;
3563
3744
  case "tile": {
3564
3745
  const tile = render(message.request);
3565
3746
  send({
@@ -47,7 +47,7 @@ async function readEngine(packageFile) {
47
47
  const root = dirname(packageFile);
48
48
  const [pkg, manifest] = await Promise.all([readFile(packageFile, "utf8").then((text) => JSON.parse(text)), readFile(resolve(root, "prebuilds.json"), "utf8").then((text) => JSON.parse(text))]);
49
49
  const engine = manifest.engine;
50
- if (pkg.name !== `${ENGINE_PREFIX}-wasm` || pkg.version !== "0.0.2-rc7" || manifest.version !== pkg.version || manifest.schemaVersion !== 1 || manifest.status !== "built" || engine === void 0 || engine.kind !== "wasm" || manifest.platform !== "wasm") throw new Error("Installed LibreOfficeKit wasm package has an incompatible or incomplete manifest.");
50
+ if (pkg.name !== `${ENGINE_PREFIX}-wasm` || pkg.version !== "0.0.2-rc9" || manifest.version !== pkg.version || manifest.schemaVersion !== 1 || manifest.status !== "built" || engine === void 0 || engine.kind !== "wasm" || manifest.platform !== "wasm") throw new Error("Installed LibreOfficeKit wasm package has an incompatible or incomplete manifest.");
51
51
  if (engine.glibcMinimum !== void 0) throw new Error("Installed LibreOfficeKit engine has an invalid glibcMinimum.");
52
52
  return {
53
53
  backend: "wasm",
package/lib/cli.js CHANGED
@@ -733,7 +733,7 @@ const require = createRequire(import.meta.url);
733
733
  * Engine-family version every installed engine package must carry. The engine
734
734
  * family shares its release version with this Node API.
735
735
  */
736
- const ENGINE_VERSION = "0.0.2-rc7";
736
+ const ENGINE_VERSION = "0.0.2-rc9";
737
737
  /** npm scope and name prefix shared by the engine packages this adapter installs. */
738
738
  const ENGINE_PREFIX = "@deepseek-ai/libreoffice-kit";
739
739
  /**
@@ -774,7 +774,7 @@ async function readEngine(packageFile) {
774
774
  const root = dirname(packageFile);
775
775
  const [pkg, manifest] = await Promise.all([readFile(packageFile, "utf8").then((text) => JSON.parse(text)), readFile(resolve(root, "prebuilds.json"), "utf8").then((text) => JSON.parse(text))]);
776
776
  const engine = manifest.engine;
777
- if (pkg.name !== `${ENGINE_PREFIX}-wasm` || pkg.version !== "0.0.2-rc7" || manifest.version !== pkg.version || manifest.schemaVersion !== 1 || manifest.status !== "built" || engine === void 0 || engine.kind !== "wasm" || manifest.platform !== "wasm") throw new Error("Installed LibreOfficeKit wasm package has an incompatible or incomplete manifest.");
777
+ if (pkg.name !== `${ENGINE_PREFIX}-wasm` || pkg.version !== "0.0.2-rc9" || manifest.version !== pkg.version || manifest.schemaVersion !== 1 || manifest.status !== "built" || engine === void 0 || engine.kind !== "wasm" || manifest.platform !== "wasm") throw new Error("Installed LibreOfficeKit wasm package has an incompatible or incomplete manifest.");
778
778
  if (engine.glibcMinimum !== void 0) throw new Error("Installed LibreOfficeKit engine has an invalid glibcMinimum.");
779
779
  return {
780
780
  backend: "wasm",
package/lib/index.js CHANGED
@@ -731,7 +731,7 @@ const require = createRequire(import.meta.url);
731
731
  * Engine-family version every installed engine package must carry. The engine
732
732
  * family shares its release version with this Node API.
733
733
  */
734
- const ENGINE_VERSION = "0.0.2-rc7";
734
+ const ENGINE_VERSION = "0.0.2-rc9";
735
735
  /** npm scope and name prefix shared by the engine packages this adapter installs. */
736
736
  const ENGINE_PREFIX = "@deepseek-ai/libreoffice-kit";
737
737
  /**
@@ -772,7 +772,7 @@ async function readEngine(packageFile) {
772
772
  const root = dirname(packageFile);
773
773
  const [pkg, manifest] = await Promise.all([readFile(packageFile, "utf8").then((text) => JSON.parse(text)), readFile(resolve(root, "prebuilds.json"), "utf8").then((text) => JSON.parse(text))]);
774
774
  const engine = manifest.engine;
775
- if (pkg.name !== `${ENGINE_PREFIX}-wasm` || pkg.version !== "0.0.2-rc7" || manifest.version !== pkg.version || manifest.schemaVersion !== 1 || manifest.status !== "built" || engine === void 0 || engine.kind !== "wasm" || manifest.platform !== "wasm") throw new Error("Installed LibreOfficeKit wasm package has an incompatible or incomplete manifest.");
775
+ if (pkg.name !== `${ENGINE_PREFIX}-wasm` || pkg.version !== "0.0.2-rc9" || manifest.version !== pkg.version || manifest.schemaVersion !== 1 || manifest.status !== "built" || engine === void 0 || engine.kind !== "wasm" || manifest.platform !== "wasm") throw new Error("Installed LibreOfficeKit wasm package has an incompatible or incomplete manifest.");
776
776
  if (engine.glibcMinimum !== void 0) throw new Error("Installed LibreOfficeKit engine has an invalid glibcMinimum.");
777
777
  return {
778
778
  backend: "wasm",
@@ -2,7 +2,7 @@
2
2
  * Engine-family version every installed engine package must carry. The engine
3
3
  * family shares its release version with this Node API.
4
4
  */
5
- export declare const ENGINE_VERSION = "0.0.2-rc7";
5
+ export declare const ENGINE_VERSION = "0.0.2-rc9";
6
6
  /** Host diagnostic fields used to identify the runtime glibc version. */
7
7
  export interface EngineHostReport {
8
8
  readonly header?: {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/libreoffice-kit",
3
3
  "description": "WASM Office previews, document images, and conversion for Node and browsers",
4
- "version": "0.0.2-rc7",
4
+ "version": "0.0.2-rc9",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -85,7 +85,7 @@
85
85
  "fflate": "0.8.2",
86
86
  "fontkit": "2.0.4",
87
87
  "saxes": "6.0.0",
88
- "@deepseek-ai/libreoffice-kit-wasm": "0.0.2-rc7"
88
+ "@deepseek-ai/libreoffice-kit-wasm": "0.0.2-rc9"
89
89
  },
90
90
  "bin": {
91
91
  "libreoffice-kit": "./lib/cli.js"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepseek-ai/libreoffice-kit-browser-internal",
3
- "version": "0.0.2-rc7",
3
+ "version": "0.0.2-rc9",
4
4
  "type": "module",
5
5
  "license": "MPL-2.0",
6
6
  "description": "Browser Worker LibreOffice reading sessions and PDF rendering",