@silurus/ooxml 0.75.5 → 0.76.1

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 (52) hide show
  1. package/README.md +66 -28
  2. package/dist/bounded-raw-part-cache-C6ro6Ezf.js +254 -0
  3. package/dist/{find-cursor-Dc5iM6s7.js → canvas-viewer-mechanics-CwVSOYke.js} +192 -64
  4. package/dist/{document-pull-client-BcNYhoAG.js → document-pull-client-AAnwzlig.js} +3625 -3601
  5. package/dist/docx-CCksIXd5.js +1301 -0
  6. package/dist/docx.mjs +4 -6
  7. package/dist/docx_parser_bg.wasm +0 -0
  8. package/dist/index.mjs +3 -3
  9. package/dist/{line-distribute-B8sqT8kC.js → line-distribute-C1r2zvji.js} +141 -141
  10. package/dist/{line-metrics-D9gqQWHl.js → line-metrics-BdCACYlq.js} +4026 -1170
  11. package/dist/math.mjs +1 -1
  12. package/dist/node.mjs +779 -465
  13. package/dist/pptx-CKAk5e-J.js +1735 -0
  14. package/dist/pptx.mjs +5 -7
  15. package/dist/pptx_parser_bg.wasm +0 -0
  16. package/dist/{render-CalC7GX4.js → render-CLcpSi0m.js} +11 -18
  17. package/dist/render-worker-host-B8HAb_sK.js +27 -0
  18. package/dist/render-worker-host-Bkf1jUcW.js +27 -0
  19. package/dist/render-worker-host-CKOmXdyr.js +27 -0
  20. package/dist/resource-measurement-E_S_iau4.js +119 -0
  21. package/dist/session-B4Y54cbT.js +730 -0
  22. package/dist/{renderer-B9R6F_QY.js → slide-pull-client-WCuYCjio.js} +973 -820
  23. package/dist/types/docx.d.ts +1181 -3994
  24. package/dist/types/index.d.ts +2733 -8171
  25. package/dist/types/math.d.ts +8 -33
  26. package/dist/types/node.d.ts +1852 -4433
  27. package/dist/types/pptx.d.ts +1030 -3678
  28. package/dist/types/xlsx.d.ts +1291 -3262
  29. package/dist/worksheet-pull-client-YzjJMOns.js +455 -0
  30. package/dist/xlsx-BBmmZNQn.js +6362 -0
  31. package/dist/xlsx.mjs +5 -7
  32. package/dist/xlsx_parser_bg.wasm +0 -0
  33. package/package.json +14 -7
  34. package/dist/bounded-raw-part-cache-BTfZD_Sz.js +0 -1248
  35. package/dist/docx-DjF8FgoP.js +0 -1274
  36. package/dist/duotone-bitmap-by-path-CWsSJkJu.js +0 -28
  37. package/dist/hyperlink-D85FexTa.js +0 -27
  38. package/dist/pptx-C17xP8AV.js +0 -1705
  39. package/dist/pptx-Dl8tOSmP.js +0 -822
  40. package/dist/preload-BEouWnlI.js +0 -132
  41. package/dist/render-worker-host-BG3a7brz.js +0 -27
  42. package/dist/render-worker-host-CsB-dPJv.js +0 -27
  43. package/dist/render-worker-host-Cyv5Hkbh.js +0 -27
  44. package/dist/resource-measurement-6aReN3K0.js +0 -93
  45. package/dist/slide-pull-client-D_T0AIoX.js +0 -175
  46. package/dist/svg-image-by-path-C1M3N2pT.js +0 -1623
  47. package/dist/worksheet-pull-worker-DCei8u-4.js +0 -347
  48. package/dist/xlsx-BaH9irS0.js +0 -5515
  49. /package/dist/{highlight-rect-cCvVU-MW.js → highlight-rect-CAkCWJ37.js} +0 -0
  50. /package/dist/{mathjax-Dqo857oC.js → mathjax-CMjda8Ip.js} +0 -0
  51. /package/dist/{transfer-3QEJrsJa.js → transfer-DCu4c2BL.js} +0 -0
  52. /package/dist/{visible-index-CKvgpUrf.js → visible-index-CgyJLAS_.js} +0 -0
@@ -0,0 +1,1301 @@
1
+ import { t as e } from "./chunk-DmhlhrBa.js";
2
+ import { B as t, Et as n, It as r, Lt as i, R as a, a as o, an as s, hn as c, ht as l, it as u, kt as d, mn as f, q as p, z as m } from "./line-metrics-BdCACYlq.js";
3
+ import { _ as h, a as g, b as _, c as v, d as y, f as b, g as x, h as ee, i as S, l as te, m as C, n as ne, o as w, p as T, r as re, s as ie, t as ae, u as oe, v as E, x as se, y as ce } from "./canvas-viewer-mechanics-CwVSOYke.js";
4
+ import { a as le, c as ue, i as de, o as fe, r as pe, s as me, t as he } from "./bounded-raw-part-cache-C6ro6Ezf.js";
5
+ import { _ as D, a as ge, c as O, d as k, f as A, g as j, h as M, l as N, m as P, n as F, o as I, p as L, s as _e, t as R, v as ve, y as z } from "./document-pull-client-AAnwzlig.js";
6
+ import { n as ye, r as B, t as V } from "./highlight-rect-CAkCWJ37.js";
7
+ //#region packages/core/src/fonts/embedded.ts
8
+ function be(e, t) {
9
+ let n = xe(t), r = e.slice(), i = Math.min(32, r.length);
10
+ for (let e = 0; e < i; e++) r[e] ^= n[e % 16];
11
+ return r;
12
+ }
13
+ function xe(e) {
14
+ let t = e.replace(/[{}\-\s]/g, "");
15
+ if (t.length !== 32 || /[^0-9a-fA-F]/.test(t)) throw Error(`invalid fontKey GUID: ${e}`);
16
+ let n = new Uint8Array(16);
17
+ for (let e = 0; e < 16; e++) n[e] = parseInt(t.slice(e * 2, e * 2 + 2), 16);
18
+ return n.reverse();
19
+ }
20
+ function Se(e, t, n, r) {
21
+ let i = 2166136261;
22
+ for (let e = 0; e < r.length; e++) i ^= r[e], i = Math.imul(i, 16777619);
23
+ return `${e}|${t}|${n}|${r.length}|${(i >>> 0).toString(16)}`;
24
+ }
25
+ async function Ce(e, t = 30 * 1024 * 1024) {
26
+ let n = pe();
27
+ if (!n || typeof FontFace > "u") return [];
28
+ let r = [], i = [], a = [];
29
+ for (let o of e) try {
30
+ if (o.bytes.length === 0 || o.bytes.length > t) {
31
+ a.push(o.family);
32
+ continue;
33
+ }
34
+ let e = o.odttf ? be(o.bytes, o.fontKey ?? "") : o.bytes, { face: s, isNew: c } = ue(`embedded:${Se(o.family, o.weight, o.style, e)}`, n, () => {
35
+ let t = e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength), r = new FontFace(o.family, t, {
36
+ weight: o.weight,
37
+ style: o.style
38
+ });
39
+ return n.add(r), r;
40
+ });
41
+ r.push(s), c && i.push(s);
42
+ } catch {
43
+ a.push(o.family);
44
+ }
45
+ return i.length > 0 && await fe(Promise.allSettled(i.map((e) => e.load())).then((e) => (e.forEach((e, t) => {
46
+ e.status === "rejected" && a.push(i[t].family);
47
+ }), n.ready))), a.length > 0 && console.warn(`[ooxml] failed to register embedded font(s): ${[...new Set(a)].join(", ")}; falling back to substitute fonts (text may shift or differ).`), r;
48
+ }
49
+ function we(e) {
50
+ me(e);
51
+ }
52
+ //#endregion
53
+ //#region packages/docx/src/worker.ts?worker&inline
54
+ var H = "var e=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,n.unregister(this),e}free(){let e=this.__destroy_into_raw();g.__wbg_docxarchive_free(e,0)}acknowledge_document_chunk(e,t,n){let r=g.docxarchive_acknowledge_document_chunk(this.__wbg_ptr,e,t,n);if(r[1])throw d(r[0])}assert_healthy(){let e=g.docxarchive_assert_healthy(this.__wbg_ptr);if(e[1])throw d(e[0])}cancel_document_cursor(){g.docxarchive_cancel_document_cursor(this.__wbg_ptr)}close_document_session(){g.docxarchive_close_document_session(this.__wbg_ptr)}document_chunk_done(){let e=g.docxarchive_document_chunk_done(this.__wbg_ptr);if(e[2])throw d(e[1]);return e[0]!==0}document_cursor_resource_usage(){let e=g.docxarchive_document_cursor_resource_usage(this.__wbg_ptr);if(e[3])throw d(e[2]);var t=r(e[0],e[1]).slice();return g.__wbindgen_free(e[0],e[1]*1,1),t}extract_image(e){let t=u(e,g.__wbindgen_malloc,g.__wbindgen_realloc),n=h,i=g.docxarchive_extract_image(this.__wbg_ptr,t,n);if(i[3])throw d(i[2]);var a=r(i[0],i[1]).slice();return g.__wbindgen_free(i[0],i[1]*1,1),a}constructor(e,t,r,i){let a=ee(e,g.__wbindgen_malloc),o=h,s=g.docxarchive_new(a,o,!l(t),l(t)?BigInt(0):t,!l(r),l(r)?BigInt(0):r,!l(i),l(i)?BigInt(0):i);if(s[2])throw d(s[1]);return this.__wbg_ptr=s[0]>>>0,n.register(this,this.__wbg_ptr,this),this}open_document_cursor(e,t){let n=g.docxarchive_open_document_cursor(this.__wbg_ptr,e,t);if(n[1])throw d(n[0])}parse(){let e=g.docxarchive_parse(this.__wbg_ptr);if(e[3])throw d(e[2]);var t=r(e[0],e[1]).slice();return g.__wbindgen_free(e[0],e[1]*1,1),t}pull_document_chunk(e,t,n,i){let a=g.docxarchive_pull_document_chunk(this.__wbg_ptr,e,t,n,i);if(a[3])throw d(a[2]);var o=r(a[0],a[1]).slice();return g.__wbindgen_free(a[0],a[1]*1,1),o}resource_usage(){let e=g.docxarchive_resource_usage(this.__wbg_ptr);if(e[3])throw d(e[2]);var t=r(e[0],e[1]).slice();return g.__wbindgen_free(e[0],e[1]*1,1),t}to_markdown(){let e,t;try{let i=g.docxarchive_to_markdown(this.__wbg_ptr);var n=i[0],r=i[1];if(i[3])throw n=0,r=0,d(i[2]);return e=n,t=r,o(n,r)}finally{g.__wbindgen_free(e,t,1)}}};Symbol.dispose&&(e.prototype[Symbol.dispose]=e.prototype.free);function t(){return{__proto__:null,\"./docx_parser_bg.js\":{__proto__:null,__wbg___wbindgen_throw_6b64449b9b9ed33c:function(e,t){throw Error(o(e,t))},__wbg_error_a6fa202b58aa1cd3:function(e,t){let n,r;try{n=e,r=t,console.error(o(e,t))}finally{g.__wbindgen_free(n,r,1)}},__wbg_new_227d7c05414eb861:function(){return Error()},__wbg_stack_3b0d974bbf31e44f:function(e,t){let n=t.stack,r=u(n,g.__wbindgen_malloc,g.__wbindgen_realloc),i=h;a().setInt32(e+4,i,!0),a().setInt32(e+0,r,!0)},__wbindgen_cast_0000000000000001:function(e,t){return o(e,t)},__wbindgen_init_externref_table:function(){let e=g.__wbindgen_externrefs,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)}}}}const n=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>g.__wbg_docxarchive_free(e>>>0,1));function r(e,t){return e>>>=0,c().subarray(e/1,e/1+t)}let i=null;function a(){return(i===null||i.buffer.detached===!0||i.buffer.detached===void 0&&i.buffer!==g.memory.buffer)&&(i=new DataView(g.memory.buffer)),i}function o(e,t){return e>>>=0,te(e,t)}let s=null;function c(){return(s===null||s.byteLength===0)&&(s=new Uint8Array(g.memory.buffer)),s}function l(e){return e==null}function ee(e,t){let n=t(e.length*1,1)>>>0;return c().set(e,n/1),h=e.length,n}function u(e,t,n){if(n===void 0){let n=m.encode(e),r=t(n.length,1)>>>0;return c().subarray(r,r+n.length).set(n),h=n.length,r}let r=e.length,i=t(r,1)>>>0,a=c(),o=0;for(;o<r;o++){let t=e.charCodeAt(o);if(t>127)break;a[i+o]=t}if(o!==r){o!==0&&(e=e.slice(o)),i=n(i,r,r=o+e.length*3,1)>>>0;let t=c().subarray(i+o,i+r),a=m.encodeInto(e,t);o+=a.written,i=n(i,r,o,1)>>>0}return h=o,i}function d(e){let t=g.__wbindgen_externrefs.get(e);return g.__externref_table_dealloc(e),t}let f=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0});f.decode();let p=0;function te(e,t){return p+=t,p>=2146435072&&(f=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}),f.decode(),p=t),f.decode(c().subarray(e,e+t))}const m=new TextEncoder;`encodeInto`in m||(m.encodeInto=function(e,t){let n=m.encode(e);return t.set(n),{read:e.length,written:n.length}});let h=0,g;function _(e,t){return g=e.exports,i=null,s=null,g.__wbindgen_start(),g}async function v(e,t){if(typeof Response==`function`&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming==`function`)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if(e.ok&&n(e.type)&&e.headers.get(`Content-Type`)!==`application/wasm`)console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\",t);else throw t}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{let n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}function n(e){switch(e){case`basic`:case`cors`:case`default`:return!0}return!1}}async function y(e){if(g!==void 0)return g;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn(`using deprecated parameters for the initialization function; pass a single object instead`));let n=t();(typeof e==`string`||typeof Request==`function`&&e instanceof Request||typeof URL==`function`&&e instanceof URL)&&(e=fetch(e));let{instance:r,module:i}=await v(await e,n);return _(r,i)}async function b(e){return g=void 0,i=null,s=null,y(e)}var x=class e extends Error{code;constructor(t,n){super(n),this.name=`OoxmlError`,this.code=t,Object.setPrototypeOf(this,e.prototype)}},S=class e extends Error{code=`ooxml-resource-limit`;details;constructor(t,n){super(t),this.name=`OoxmlResourceLimitError`;let r=n.violation,i=Object.freeze({format:r.format,operation:r.operation,resource:r.resource,metric:r.metric,...r.part===void 0?{}:{part:r.part},limit:r.limit,observed:r.observed,configurable:r.configurable,usage:Object.freeze({archiveEntryCount:r.usage.archiveEntryCount,declaredInflatedBytes:r.usage.declaredInflatedBytes,...r.usage.largestInflatedEntryBytes===void 0?{}:{largestInflatedEntryBytes:r.usage.largestInflatedEntryBytes},distinctInflatedBytes:r.usage.distinctInflatedBytes,operationInflatedBytes:r.usage.operationInflatedBytes})});this.details=Object.freeze({stage:n.stage,violation:i}),Object.setPrototypeOf(this,e.prototype)}},ne=class e extends RangeError{code=`ooxml-decoded-image-limit`;constructor(t,n,r){super(`OOXML decoded image limit exceeded: ${t} ${r} > ${n}`),this.metric=t,this.limit=n,this.observed=r,this.name=`OoxmlDecodedImageLimitError`,Object.setPrototypeOf(this,e.prototype)}};function re(e){if(!e.startsWith(`data:`))return null;let t=e.indexOf(`,`);if(t===-1)return null;let n=atob(e.slice(t+1)),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r.buffer}var ie=class{state=`uninitialized`;generationValue=0;readiness;poisonListeners=new Set;constructor(e,t,n){this.initialize=e,this.reinitialize=t,this.normalizeFailure=n}get generation(){return this.generationValue}get poisoned(){return this.state===`poisoned`}onPoison(e){return this.poisonListeners.add(e),()=>this.poisonListeners.delete(e)}async ensureReady(){if(this.state!==`ready`){if(!this.readiness){let e=this.state===`uninitialized`?this.initialize:this.reinitialize;this.readiness=Promise.resolve().then(e).then(()=>{this.generationValue+=1,this.state=`ready`,this.readiness=void 0},e=>{throw this.readiness=void 0,e})}await this.readiness}}run(e){try{return e()}catch(e){let t=this.normalizeFailure(e);throw t?(this.poison(t),t):e}}tryRunReady(e){if(this.state!==`ready`)return{current:!1};let t=this.generationValue,n=this.run(e);return this.state!==`ready`||t!==this.generationValue?{current:!1}:{current:!0,generation:t,value:n}}poison(e){this.state=`poisoned`,this.readiness=void 0;for(let t of this.poisonListeners)t(e)}assertCurrent(e){if(this.state!==`ready`||e!==this.generationValue)throw Error(`WASM archive session belongs to a discarded runtime generation`)}},C=class e extends Error{code=`parser-crashed`;constructor(t){super(t),this.name=`WasmTrapError`,Object.setPrototypeOf(this,e.prototype)}};function ae(e){let t=globalThis.WebAssembly?.RuntimeError;return t&&e instanceof t||e instanceof RangeError?!0:e instanceof Error?e.name===`RuntimeError`||e.name===`CompileError`||e.name===`LinkError`||e.name===`InternalError`||e.name===`OOMError`:!1}function w(e){try{if((typeof e!=`object`||!e)&&typeof e!=`function`)return;let t=Reflect.get(e,`__destroy_into_raw`);typeof t==`function`&&Reflect.apply(t,e,[])}catch{}}function T(e,t){return e({module_or_path:t})}var oe=class{runtime;wasmInput=null;currentArchive=null;constructor(e,t={}){this.init=e,this.options=t,this.runtime=new ie(()=>this.invokeConfigured(this.init),()=>this.invokeConfigured(this.options.reinit??this.init),E),this.runtime.onPoison(()=>this.dropPoisonedArchive())}setWasmInput(e){this.wasmInput=e,this.runtime.ensureReady().catch(()=>void 0)}setWasmUrl(e){this.setWasmInput(e)}get archive(){return this.currentArchive}setArchive(e){this.freeArchive(),this.currentArchive=e}disposeArchive(){this.freeArchive()}get poisoned(){return this.runtime.poisoned}async ensureReady(){await this.runtime.ensureReady()}run(e){return this.runtime.run(e)}poison(){this.runtime.poison(new C(`WASM parser was recycled`))}invokeConfigured(e){return this.wasmInput===null?Promise.reject(Error(`WasmParserHost: setWasmInput was never called`)):T(e,this.wasmInput)}freeArchive(){this.currentArchive!==null&&this.options.freeArchive&&this.options.freeArchive(this.currentArchive),this.currentArchive=null}dropPoisonedArchive(){let e=this.currentArchive;this.currentArchive=null,w(e)}};function E(e){return ae(e)?new C(`WASM parser trapped and was recycled: ${e instanceof Error?e.message:String(e)}`):null}function D(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function se(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return D(t.requiredBytes)&&D(t.offeredBytes)&&t.requiredBytes>t.offeredBytes}var O=class e extends RangeError{code=`ooxml-insufficient-credit`;requiredBytes;offeredBytes;constructor(t){super(`Pull unit requires ${t.requiredBytes} bytes but credit is ${t.offeredBytes}`),this.name=`PullSessionInsufficientCreditError`,this.requiredBytes=t.requiredBytes,this.offeredBytes=t.offeredBytes,Object.setPrototypeOf(this,e.prototype)}};function k(e){if(e instanceof O)return e;let t=e instanceof Error?e.message:String(e);if(!t.startsWith(`OOXML_INSUFFICIENT_CREDIT:`))return;let n;try{n=JSON.parse(t.slice(26))}catch{return}if(!n||typeof n!=`object`||Array.isArray(n))return;let r=n;if(!(r.code!==`ooxml-insufficient-credit`||!se(r)))return new O(r)}function ce(e,t,n){let r=k(e);if(!(!r||r.offeredBytes!==t||r.requiredBytes>n))return r}const A=`OOXML_RESOURCE_LIMIT:`;function j(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function M(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return j(t.archiveEntryCount)&&j(t.declaredInflatedBytes)&&(t.largestInflatedEntryBytes===void 0||j(t.largestInflatedEntryBytes))&&j(t.distinctInflatedBytes)&&j(t.operationInflatedBytes)}function N(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw TypeError(`OOXML resource usage checkpoint is not valid JSON`)}if(!M(t))throw TypeError(`OOXML resource usage checkpoint is invalid`);return t}function le(e){return e===`docx`||e===`xlsx`||e===`pptx`}function P(e){return e===`container`||e===`decompression`||e===`parsing`||e===`serialization`||e===`layout`||e===`rendering`||e===`worker`}function F(e,t){return typeof e==`string`&&e.length>0&&e.length<=t&&!/[\\u0000-\\u001f\\u007f]/u.test(e)}function I(e){return F(e,128)&&/^[a-z0-9][a-z0-9-]*$/u.test(e)}function L(e){return!F(e,4096)||e.startsWith(`/`)||e.startsWith(`\\\\`)||e.includes(`\\\\`)||e.includes(`?`)||e.includes(`#`)||e.includes(`://`)||/^[a-z]:/iu.test(e)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}const R=new Map([[`archive-entry:declared-inflated-bytes`,{stage:`container`,part:`required`}],[`archive-entry:actual-inflated-bytes`,{stage:`decompression`,part:`required`}],[`archive:entry-count`,{stage:`container`,part:`forbidden`}],[`archive:central-directory-bytes`,{stage:`container`,part:`forbidden`,configurable:!1}],[`archive:distinct-inflated-bytes`,{stage:`decompression`,part:`required`}],[`xml-event:bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`xml-context:bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`xml-tree:depth`,{stage:`parsing`,part:`optional`,configurable:!1}],[`worksheet-row:projected-bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`worksheet-shell:projected-bytes`,{stage:`parsing`,part:`optional`,configurable:!1}]]),z=new Set([...R.keys()].map(e=>e.slice(0,e.indexOf(`:`)))),B=new Set([...R.keys()].map(e=>e.slice(e.indexOf(`:`)+1)));function V(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return!le(t.format)||!F(t.operation,256)||!I(t.resource)||!I(t.metric)||!j(t.limit)||!j(t.observed)||typeof t.configurable!=`boolean`||!M(t.usage)?!1:!(`part`in t)||L(t.part)}function H(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;if(!P(t.stage)||!V(t.violation))return!1;let n=t.violation,r=R.get(`${n.resource}:${n.metric}`);return r?t.stage!==r.stage||r.configurable===!1&&n.configurable!==!1?!1:r.part===`required`?n.part!==void 0:r.part===`forbidden`?n.part===void 0:!0:!(z.has(n.resource)&&B.has(n.metric))}function U(e){return{archiveEntryCount:e.archiveEntryCount,declaredInflatedBytes:e.declaredInflatedBytes,...e.largestInflatedEntryBytes===void 0?{}:{largestInflatedEntryBytes:e.largestInflatedEntryBytes},distinctInflatedBytes:e.distinctInflatedBytes,operationInflatedBytes:e.operationInflatedBytes}}function ue(e){if(!H(e))return;let t=e.violation,n={stage:e.stage,violation:{format:t.format,operation:t.operation,resource:t.resource,metric:t.metric,...t.part===void 0?{}:{part:t.part},limit:t.limit,observed:t.observed,configurable:t.configurable,usage:U(t.usage)}};return H(n)?n:void 0}function W(e){let t=e.violation;return`OOXML resource limit exceeded${t.part?` for ${t.part}`:``}: ${t.metric} ${t.observed} > ${t.limit}`}function de(e){let t=e instanceof Error?e.message:String(e);if(!t.startsWith(A))return;let n;try{n=JSON.parse(t.slice(21))}catch{return}if(!n||typeof n!=`object`)return;let r=n;if(!(r.code!==`ooxml-resource-limit`||!H(r.details)))return new S(W(r.details),r.details)}function fe(e){if(e instanceof ne)return{message:e.message,errorName:e.name,code:e.code,decodedImage:{metric:e.metric,limit:e.limit,observed:e.observed}};let t=k(e);if(t)return{message:t.message,errorName:t.name,code:t.code,insufficientCredit:{requiredBytes:t.requiredBytes,offeredBytes:t.offeredBytes}};let n=e instanceof x||e instanceof S?e:de(e);if(n instanceof S){let e=ue(n.details);return e?{message:typeof n.message==`string`?n.message:W(e),errorName:`OoxmlResourceLimitError`,code:`ooxml-resource-limit`,resourceLimit:e}:{message:`Invalid OOXML resource-limit error payload`,errorName:`Error`}}if(n instanceof x)return{message:typeof n.message==`string`?n.message:String(n.message),errorName:F(n.name,128)?n.name:`OoxmlError`,...I(n.code)?{code:n.code}:{}};let r=e instanceof Error?e.message:String(e);if(typeof r==`string`&&r.startsWith(A))return{message:`Invalid OOXML resource-limit payload`,errorName:`Error`};let i=e instanceof Error?e:Error(r),a=i;return{message:typeof i.message==`string`?i.message:String(i.message),errorName:F(i.name,128)?i.name:`Error`,...typeof a.code==`string`?{code:a.code}:{}}}function G(e){try{return fe(e)}catch{return{message:`Worker operation failed with an unreadable error`,errorName:`Error`}}}function pe(e){return e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&e.buffer instanceof ArrayBuffer?e.buffer:e.slice().buffer}Object.freeze({maxArchiveEntryBytes:134217728,maxTotalInflatedBytes:268435456,maxArchiveEntries:4096});function me(e){return[e.maxArchiveEntryBytes===null?0n:BigInt(e.maxArchiveEntryBytes),e.maxTotalInflatedBytes===null?0n:BigInt(e.maxTotalInflatedBytes),e.maxArchiveEntries===null?0n:BigInt(e.maxArchiveEntries)]}const K=`ooxml-pull-v1`;function q(e,t){if(!Number.isSafeInteger(e)||e<=0)throw RangeError(`${t} must be a positive safe integer`)}function he(e){if(!(typeof e==`string`&&e.length>0||typeof e==`number`&&Number.isSafeInteger(e)&&e>0))throw RangeError(`session id must be a non-empty string or positive safe integer`)}var J=class{owner;queue=Promise.resolve();leases=new Map;retainedBytes=0;retainedCount=0;maxRetainedBytes;maxRetainedCount;cleanups=new Set;pendingFatalCleanups=[];poisonRunning=!1;fatal;constructor(e){this.maxRetainedBytes=e?.maxRetainedBytes??64*1024*1024,this.maxRetainedCount=e?.maxRetainedCount??256,q(this.maxRetainedBytes,`max retained lease bytes`),q(this.maxRetainedCount,`max retained lease count`)}enqueue(e){let t=this.queue.then(e,e);return this.queue=t.then(()=>void 0,()=>void 0),t}acquire(e){return this.owner===void 0?(this.owner=e,!0):this.owner===e}release(e){this.owner===e&&(this.owner=void 0)}retainLease(e,t,n){if(!Number.isSafeInteger(n)||n<0)throw RangeError(`retained lease bytes are invalid`);let r=this.leases.get(e)??new Map;if(r.has(t))throw Error(`driver returned a duplicate lease id`);if(this.retainedCount+1>this.maxRetainedCount)throw RangeError(`retained lease count exceeds limit`);if(this.retainedBytes+n>this.maxRetainedBytes)throw RangeError(`retained lease bytes exceed limit`);r.set(t,n),this.leases.set(e,r),this.retainedCount++,this.retainedBytes+=n}releaseLease(e,t){let n=this.leases.get(e),r=n?.get(t);r!==void 0&&(n?.delete(t),n?.size===0&&this.leases.delete(e),this.retainedCount--,this.retainedBytes-=r)}registerCleanup(e){return this.fatal?(this.poisonRunning?this.pendingFatalCleanups.push(e):this.enqueue(e).catch(()=>void 0),()=>void 0):(this.cleanups.add(e),()=>this.cleanups.delete(e))}get fatalError(){return this.fatal}get registeredHostCount(){return this.cleanups.size}async poison(e){if(this.fatal??=e,this.poisonRunning)return this.fatal;this.poisonRunning=!0,this.pendingFatalCleanups.push(...this.cleanups);try{let e;for(;(e=this.pendingFatalCleanups.shift())!==void 0;)await e().catch(()=>void 0)}finally{this.poisonRunning=!1}return this.fatal}},ge=class{options;coordinator;coordinatorOwner=Symbol(`pull-session-host`);unregisterCleanup;sequence=0;unacked;leases=new Map;activeDriverLeases=new Set;nextWireLeaseId;cancelRequested=!1;cancelComplete=!1;closeRequested=!1;closeComplete=!1;driverCancelComplete=!1;driverCloseComplete=!1;completed=!1;constructor(e){he(e.sessionId),q(e.operationId,`operation id`),q(e.generation,`generation`),q(e.maxByteCredit,`max byte credit`),e.wireLeaseIdStart!==void 0&&q(e.wireLeaseIdStart,`wire lease id start`),this.options=e,this.coordinator=e.coordinator,this.nextWireLeaseId=e.wireLeaseIdStart??1,this.unregisterCleanup=this.coordinator.registerCleanup(()=>this.forceFatalCleanup())}dispatch(e,t){return this.coordinator.enqueue(async()=>{let n=await this.execute(e);try{t(n.response,n.transfer)}catch(e){throw await this.rollbackFailedPost(n),e}})}async rollbackFailedPost(e){let t=e.response;if(t.kind===`chunk`){let n=t.leaseId===void 0?void 0:this.leases.get(t.leaseId);try{await this.options.driver.disposeInvalidChunk?.({payload:t.payload,byteLength:t.byteLength,done:t.done,leaseId:n?.driverLeaseId,retainedBytes:n?.retainedBytes,transfer:e.transfer})}catch{}}this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);for(let[e,t]of[...this.leases])try{await this.options.driver.releaseLease?.(t.driverLeaseId)}catch{}finally{this.leases.delete(e),this.activeDriverLeases.delete(t.driverLeaseId),this.coordinator.releaseLease(this.coordinatorOwner,e)}if(this.cancelRequested=!0,!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch{}this.unregisterCleanup()}async execute(e){try{if(this.isStaleLifecycle(e)){let t=e.kind===`cancel`?`cancel`:`close`;return this.sameOperationIdentity(e)?{response:this.accepted(e,t,!0)}:{response:this.errorResponse(e,{message:`stale lifecycle targets another session or operation`,errorName:`PullSessionProtocolError`,code:`ooxml-stale-lifecycle`})}}this.validateCommandIdentity(e);let t=this.coordinator.fatalError;if(t)return e.kind===`pull`?{response:this.errorResponse(e,t)}:(e.kind===`cancel`?await this.cancel():e.kind===`close`?await this.close():e.kind===`release`&&await this.release(e.leaseId),{response:this.accepted(e,e.kind)});switch(e.kind){case`pull`:return await this.pull(e);case`ack`:return await this.ack(e.sequence),{response:this.accepted(e,`ack`)};case`release`:return await this.release(e.leaseId),{response:this.accepted(e,`release`)};case`cancel`:return await this.cancel(),{response:this.accepted(e,`cancel`)};case`close`:return await this.close(),{response:this.accepted(e,`close`)}}}catch(t){let n=G(t);return n.code===`ooxml-resource-limit`&&(n=await this.coordinator.poison(n)),{response:this.errorResponse(e,n)}}}async pull(e){if(this.closeRequested||this.cancelRequested||this.completed)throw Error(`pull session is closed`);if(this.unacked)throw Error(`previous chunk is not acknowledged`);if(!Number.isSafeInteger(e.sequence)||e.sequence<0||e.sequence!==this.sequence)throw Error(`pull command sequence mismatch`);if(this.validateHostCredit(e.byteCredit),!this.coordinator.acquire(this.coordinatorOwner))throw Error(`another operation has an unacknowledged package chunk`);let t;try{t=await this.options.driver.pull(e.byteCredit)}catch(e){throw this.coordinator.release(this.coordinatorOwner),e}let n=!1,r=!1,i,a;try{let o=this.options.driver.measureChunk(t),s=this.arrayBufferTransferBytes(t.transfer);if(o<s)throw RangeError(`measured chunk bytes are below ArrayBuffer transfer bytes`);if(a=Math.max(o,s),t.leaseId!==void 0){if(q(t.leaseId,`lease id`),t.retainedBytes===void 0)throw Error(`retained lease bytes are required`);if(this.activeDriverLeases.has(t.leaseId))throw r=!0,Error(`driver returned an active duplicate lease id`);i=this.allocateWireLeaseId(),this.coordinator.retainLease(this.coordinatorOwner,i,t.retainedBytes),this.leases.set(i,{driverLeaseId:t.leaseId,retainedBytes:t.retainedBytes}),this.activeDriverLeases.add(t.leaseId),n=!0}else if(t.retainedBytes!==void 0)throw Error(`retained lease bytes require a lease id`);if(!Number.isSafeInteger(a)||a<0)throw RangeError(`host chunk byte length must be a non-negative safe integer`);if(a>e.byteCredit)throw RangeError(`host chunk exceeds byte credit`)}catch(e){let a;try{await this.options.driver.disposeInvalidChunk?.(t)}catch(e){a=e}if(n&&i!==void 0)try{await this.release(i)}catch(e){a??=e}else if(t.leaseId!==void 0&&!r)try{await this.options.driver.releaseLease?.(t.leaseId)}catch(e){a??=e}if(r)try{await this.cancel()}catch(e){a??=e}throw this.coordinator.release(this.coordinatorOwner),a||e}return this.unacked={sequence:this.sequence,done:t.done},{response:{kind:`chunk`,protocol:K,...this.identity(),requestId:e.requestId,sequence:this.sequence,byteLength:a,done:t.done,payload:t.payload,leaseId:i,usage:this.resourceUsage()},transfer:t.transfer}}async ack(e){if(!Number.isSafeInteger(e)||e<0)throw RangeError(`invalid ack sequence`);if(e<this.sequence)return;if(!this.unacked||e!==this.sequence)throw Error(`ack sequence mismatch`);let t=this.unacked.done;await this.options.driver.acknowledge?.(e),this.unacked=void 0,this.coordinator.release(this.coordinatorOwner),this.sequence++,t&&(this.completed=!0,this.maybeUnregisterCompleted())}async release(e){q(e,`wire lease id`);let t=this.leases.get(e);t&&(await this.options.driver.releaseLease?.(t.driverLeaseId),this.leases.delete(e),this.activeDriverLeases.delete(t.driverLeaseId),this.coordinator.releaseLease(this.coordinatorOwner,e),this.maybeUnregisterCompleted())}async cancel(){if(this.cancelComplete)return;this.cancelRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;try{await this.releaseAllLeases()}catch(t){e=t}if(!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch(t){e??=t}if(e)throw e;this.cancelComplete=!0,this.unregisterCleanup()}async close(){if(this.closeComplete)return;this.closeRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;try{await this.releaseAllLeases()}catch(t){e=t}if(!this.driverCloseComplete)try{await this.options.driver.close?.(),this.driverCloseComplete=!0}catch(t){e??=t}if(e)throw e;this.closeComplete=!0,this.unregisterCleanup()}async releaseAllLeases(){let e;for(let t of[...this.leases.keys()])try{await this.release(t)}catch(t){e??=t}if(e)throw e}validateCommandIdentity(e){if(e.protocol!==`ooxml-pull-v1`||e.sessionId!==this.options.sessionId||e.operationId!==this.options.operationId||e.generation!==this.options.generation||!Number.isSafeInteger(e.requestId)||e.requestId<=0)throw Error(`stale or mismatched pull session command`)}validateHostCredit(e){if(q(e,`byte credit`),e>this.options.maxByteCredit)throw RangeError(`byte credit exceeds host maximum`)}accepted(e,t,n=!1){return{kind:`accepted`,protocol:K,...n?{sessionId:e.sessionId,operationId:e.operationId,generation:e.generation}:this.identity(),requestId:e.requestId,command:t,usage:this.resourceUsage()}}identity(){return{sessionId:this.options.sessionId,operationId:this.options.operationId,generation:this.options.generation}}isStaleLifecycle(e){return(e.kind===`cancel`||e.kind===`close`)&&e.protocol===`ooxml-pull-v1`&&Number.isSafeInteger(e.requestId)&&e.requestId>0&&Number.isSafeInteger(e.generation)&&e.generation>0&&e.generation<this.options.generation}sameOperationIdentity(e){return e.sessionId===this.options.sessionId&&e.operationId===this.options.operationId}errorResponse(e,t){return{kind:`error`,protocol:K,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:t,usage:this.errorResourceUsage()}}async forceFatalCleanup(){this.cancelRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;for(let t of[...this.leases.keys()])try{await this.release(t)}catch(t){e??=t}if(!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch(t){e??=t}if(e)throw e;this.unregisterCleanup()}allocateWireLeaseId(){if(!Number.isSafeInteger(this.nextWireLeaseId)||this.nextWireLeaseId<=0)throw RangeError(`wire lease id space exhausted`);return this.nextWireLeaseId++}arrayBufferTransferBytes(e){let t=0;for(let n of e??[])if(n instanceof ArrayBuffer&&(t+=n.byteLength,!Number.isSafeInteger(t)))throw RangeError(`ArrayBuffer transfer bytes overflow`);return t}maybeUnregisterCompleted(){this.completed&&this.leases.size===0&&this.unregisterCleanup()}resourceUsage(){return this.options.driver.resourceUsage?.()}errorResourceUsage(){try{return this.resourceUsage()}catch{return}}};const Y=67108864;var _e=class{coordinator=new J;host=null;identity=null;constructor(e,t=e=>e(this.requireArchive())){this.archive=e,this.executeArchive=t}open(e){if(this.host)throw Error(`a DOCX document pull session is already active`);this.executeArchive(t=>{t.open_document_cursor(e.operationId,e.generation)});let t=0;this.identity=e,this.host=new ge({...e,maxByteCredit:Y,coordinator:this.coordinator,driver:{pull:n=>{let r;try{r=this.executeArchive(r=>r.pull_document_chunk(t,e.operationId,e.generation,n))}catch(e){throw ce(e,n,Y)||e}let i=pe(r);return{payload:i,byteLength:i.byteLength,done:this.executeArchive(e=>e.document_chunk_done()),transfer:[i]}},measureChunk:({payload:e})=>e.byteLength,acknowledge:n=>{if(n!==t)throw Error(`DOCX document acknowledgement sequence mismatch`);this.executeArchive(n=>n.acknowledge_document_chunk(t,e.operationId,e.generation)),t+=1},cancel:()=>this.executeArchive(e=>e.cancel_document_cursor()),close:()=>this.executeArchive(e=>e.close_document_session()),resourceUsage:()=>{let e=this.executeArchive(e=>e.document_cursor_resource_usage?.());return e?N(e):void 0}}})}dispatch(e,t){return!this.host||!this.identity?(t({protocol:K,kind:`error`,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:G(Error(`DOCX document pull session is not open`))}),Promise.resolve()):this.host.dispatch(e,t)}async reset(){if(this.host)try{this.archive()&&this.executeArchive(e=>e.close_document_session())}finally{this.host=null,this.identity=null,this.coordinator=new J}}requireArchive(){let e=this.archive();if(!e)throw Error(`No docx loaded`);return e}};function ve(e){return!!e&&typeof e==`object`&&e.protocol===`ooxml-pull-v1`}const X=new oe(y,{freeArchive:e=>e.free(),reinit:b}),Z=new _e(()=>X.archive,e=>X.run(()=>{let t=X.archive;if(!t)throw Error(`No docx loaded`);return e(t)}));let Q=0;const $=(e,t)=>self.postMessage(e,t);self.onmessage=async t=>{let n=t.data;if(ve(n)){try{await Z.dispatch(n,$)}catch(e){$({protocol:K,kind:`error`,sessionId:n.sessionId,operationId:n.operationId,generation:n.generation,requestId:n.requestId,error:G(e)})}return}if(n.type===`init`){X.setWasmInput(re(n.wasmUrl)??n.wasmUrl);return}let r=n.id;try{if(await X.ensureReady(),n.type!==`parse`&&X.archive){let e=X.archive;X.run(()=>e.assert_healthy())}if(n.type===`parse`){await Z.reset();let[t,i,a]=me(n.resourcePolicy),o=new Uint8Array(n.data);X.run(()=>{let n=new e(o,t,i,a);X.setArchive(n)}),Q+=1;let s={sessionId:Q,operationId:Q,generation:Q};Z.open(s),$({type:`documentSessionOpened`,id:r,...s});return}let t=X.archive;if(n.type===`extractImage`){if(!t)throw Error(`No docx loaded`);let e=X.run(()=>t.extract_image(n.path).buffer),i={type:`imageExtracted`,id:r,bytes:e};self.postMessage(i,[e]);return}if(n.type===`resourceUsage`){if(!t)throw Error(`No docx loaded`);$({type:`resourceUsage`,id:r,usage:N(X.run(()=>t.resource_usage()))});return}if(n.type===`toMarkdown`){if(!t)throw Error(`No docx loaded`);$({type:`markdownRendered`,id:r,markdown:X.run(()=>t.to_markdown())});return}}catch(e){$({type:`error`,id:r,...G(e)})}};", U = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", H], { type: "text/javascript;charset=utf-8" });
55
+ function Te(e) {
56
+ let t;
57
+ try {
58
+ if (t = U && (self.URL || self.webkitURL).createObjectURL(U), !t) throw "";
59
+ let n = new Worker(t, {
60
+ type: "module",
61
+ name: e?.name
62
+ });
63
+ return n.addEventListener("error", () => {
64
+ (self.URL || self.webkitURL).revokeObjectURL(t);
65
+ }), n;
66
+ } catch {
67
+ return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(H), {
68
+ type: "module",
69
+ name: e?.name
70
+ });
71
+ }
72
+ }
73
+ //#endregion
74
+ //#region packages/docx/src/wasm/docx_parser_bg.wasm?url
75
+ var Ee = new URL("docx_parser_bg.wasm", import.meta.url).href;
76
+ //#endregion
77
+ //#region packages/docx/src/bookmark-nav.ts
78
+ function De(e) {
79
+ let t = /* @__PURE__ */ new Map();
80
+ for (let n of e.pages) for (let e of n.bookmarkStarts) e.name !== "" && !t.has(e.name) && t.set(e.name, n.pageIndex);
81
+ return t;
82
+ }
83
+ //#endregion
84
+ //#region packages/docx/src/embedded-fonts.ts
85
+ async function Oe(e, t) {
86
+ let n = e.embeddedFonts;
87
+ if (!n || n.length === 0) return [];
88
+ let r = (await Promise.all(n.map(async (e) => {
89
+ try {
90
+ let n = await t(e.partPath);
91
+ return {
92
+ family: e.fontName,
93
+ bytes: n,
94
+ odttf: e.partPath.toLowerCase().endsWith(".odttf"),
95
+ fontKey: e.fontKey,
96
+ weight: ke(e.style),
97
+ style: Ae(e.style)
98
+ };
99
+ } catch {
100
+ return null;
101
+ }
102
+ }))).filter((e) => e !== null);
103
+ return r.length === 0 ? [] : Ce(r);
104
+ }
105
+ function ke(e) {
106
+ return e === "bold" || e === "boldItalic" ? "bold" : "normal";
107
+ }
108
+ function Ae(e) {
109
+ return e === "italic" || e === "boldItalic" ? "italic" : "normal";
110
+ }
111
+ //#endregion
112
+ //#region packages/docx/src/document.ts
113
+ var W = class e {
114
+ _metrics = null;
115
+ _document = null;
116
+ _source = null;
117
+ _meta = null;
118
+ _bookmarkPages = null;
119
+ _mode = "main";
120
+ _worker;
121
+ _bridge;
122
+ _rawParts = new he({
123
+ maxEntries: 64,
124
+ maxBytes: p
125
+ });
126
+ _embeddedFontFaces = [];
127
+ _googleFontFaces = [];
128
+ _localMetricFontFaces = [];
129
+ _fetchImage = (e, t) => this.getImage(e, t);
130
+ constructor(e, t, n, r) {
131
+ this._worker = e, this._mode = t, j(this, n), this._bridge = new E(this._worker, {
132
+ correlate: (e) => "protocol" in e && e.protocol === "ooxml-pull-v1" ? e.requestId : "id" in e ? e.id : void 0,
133
+ toError: (e) => {
134
+ if (!("protocol" in e || e.type !== "error")) return Object.assign(u(e), {
135
+ ...e.reason === void 0 ? {} : { reason: e.reason },
136
+ ...e.outgoingColumnIndex === void 0 ? {} : { outgoingColumnIndex: e.outgoingColumnIndex },
137
+ ...e.outgoingColumnCount === void 0 ? {} : { outgoingColumnCount: e.outgoingColumnCount },
138
+ ...e.incomingColumnCount === void 0 ? {} : { incomingColumnCount: e.incomingColumnCount }
139
+ });
140
+ }
141
+ });
142
+ let i = new URL(r ?? Ee, location.href).href;
143
+ this._bridge.post({
144
+ type: "init",
145
+ wasmUrl: i
146
+ });
147
+ }
148
+ static async load(n, r = {}) {
149
+ let i = t(r), o = Date.now(), s = r.mode ?? "main", c = new a({
150
+ enabled: !0,
151
+ format: "docx",
152
+ mode: s,
153
+ policy: i.policy,
154
+ onMetrics: i.onResourceMetrics,
155
+ emitToConsole: i.debug
156
+ });
157
+ try {
158
+ if (s === "worker" && (typeof Worker > "u" || typeof OffscreenCanvas > "u")) throw Error("mode: 'worker' requires Worker and OffscreenCanvas support");
159
+ let t;
160
+ if (typeof n == "string") {
161
+ let e = await fetch(n);
162
+ if (!e.ok) throw Error(`Failed to fetch: ${e.status} ${e.statusText}`);
163
+ t = await e.arrayBuffer();
164
+ } else t = n;
165
+ t = se(await _(t, r.password)), c.setSourceBytes(t.byteLength), c.checkpoint("container ready");
166
+ let a = s === "worker" ? (await import("./render-worker-host-B8HAb_sK.js")).createRenderWorker() : new Te(), l;
167
+ try {
168
+ if (l = new e(a, s, o, r.wasmUrl), l._metrics = c, await l._parse(t, i.policy, s === "worker" ? !!r.useGoogleFonts : !1, r.workerTimeoutMs, (e) => c.observeUsage(e)), s === "worker" && l._mode === "main" && (c.setMode("main"), console.warn("[ooxml] mode: 'worker' fell back to main-thread rendering because this document requires DOM OpenType vertical glyph selection.")), r.math && l._mode === "worker" && console.warn("[ooxml] the math engine is unavailable in mode: 'worker'; equations will be skipped. Use mode: 'main' for documents with equations."), l._mode === "main" && r.useGoogleFonts && l._document && (l._googleFontFaces = await de(L(l._document), A)), l._mode === "main" && l._document?.embeddedFonts?.length) {
169
+ let e = l;
170
+ l._embeddedFontFaces = await Oe(l._document, (t) => e.getFontBytes(t));
171
+ }
172
+ let n;
173
+ l._mode === "main" && l._document && (n = await k(l._document), l._localMetricFontFaces = n.faces);
174
+ let u;
175
+ if (l._mode === "main" && r.math && l._document && I(l._document) && (u = await _e(l._document, r.math)), l._mode === "main" && l._document && l._source) {
176
+ let e = D(l);
177
+ e.services = N(l._source, {
178
+ localMetrics: n?.metrics,
179
+ useGoogleFonts: !!r.useGoogleFonts,
180
+ embeddedFaces: l._embeddedFontFaces,
181
+ googleFaces: l._googleFontFaces,
182
+ mathResources: u?.records,
183
+ mathDrawables: u?.drawables
184
+ });
185
+ let t = e.services;
186
+ ge(l._source, t, e.defaultCurrentDateMs).layoutVariants.defaultLayout;
187
+ }
188
+ return await l._resourceUsage(r.workerTimeoutMs ?? 1e3).then((e) => c.observeUsage(e), () => void 0), c.checkpoint("model and layout ready"), c.succeed({ pages: l.pageCount }), l;
189
+ } catch (e) {
190
+ let t = l;
191
+ throw h(a, t ? () => t.destroy() : void 0), e;
192
+ }
193
+ } catch (e) {
194
+ throw c.fail(e), e;
195
+ }
196
+ }
197
+ async _parse(e, t, n = !1, r, i) {
198
+ let a = await this._bridge.request((r) => this._mode === "worker" ? {
199
+ type: "parse",
200
+ id: r,
201
+ data: e,
202
+ resourcePolicy: t,
203
+ useGoogleFonts: n,
204
+ defaultCurrentDateMs: D(this).defaultCurrentDateMs
205
+ } : {
206
+ type: "parse",
207
+ id: r,
208
+ data: e,
209
+ resourcePolicy: t
210
+ }, [e], { timeoutMs: r });
211
+ if ("protocol" in a) throw Error("DOCX parse open returned a pull-protocol response");
212
+ if (this._mode === "worker") if ("usage" in a && a.usage && i?.(a.usage), a.type === "mainThreadVerticalFallback") {
213
+ let e = await F(this._bridge.transport(R), a, {
214
+ timeoutMs: r,
215
+ onUsage: i
216
+ });
217
+ this._source = e.source, this._document = e.document, this._meta = null, this._mode = "main";
218
+ } else this._meta = a.meta;
219
+ else {
220
+ let e = a, t = await F(this._bridge.transport(R), e, {
221
+ timeoutMs: r,
222
+ onUsage: i
223
+ });
224
+ this._source = t.source, this._document = t.document;
225
+ }
226
+ }
227
+ destroy() {
228
+ this._bridge.terminate(), this._document = null, this._source = null, this._meta = null, D(this).services = null, this._bookmarkPages = null, this._rawParts.clear(), this._embeddedFontFaces.length > 0 && (we(this._embeddedFontFaces), this._embeddedFontFaces = []), this._googleFontFaces.length > 0 && (le(this._googleFontFaces), this._googleFontFaces = []), this._localMetricFontFaces.length > 0 && (z(this._localMetricFontFaces), this._localMetricFontFaces = []), d(this._fetchImage), n(this._fetchImage);
229
+ }
230
+ async getImage(e, t) {
231
+ return this._rawParts.get(e, t, () => this._bridge.request((t) => ({
232
+ type: "extractImage",
233
+ id: t,
234
+ path: e
235
+ })).then((e) => {
236
+ let n = e.bytes;
237
+ return new Blob([n], { type: t });
238
+ }));
239
+ }
240
+ async getFontBytes(e) {
241
+ let t = (await this._bridge.request((t) => ({
242
+ type: "extractImage",
243
+ id: t,
244
+ path: e
245
+ }))).bytes;
246
+ return new Uint8Array(t);
247
+ }
248
+ async _resourceUsage(e) {
249
+ return (await this._bridge.request((e) => ({
250
+ type: "resourceUsage",
251
+ id: e
252
+ }), void 0, { timeoutMs: e })).usage;
253
+ }
254
+ async getResourceMetrics() {
255
+ let e = this._metrics;
256
+ if (!e) throw Error("Document not loaded");
257
+ return m(e, (e) => this._resourceUsage(e));
258
+ }
259
+ async toMarkdown() {
260
+ return (await this._bridge.request((e) => ({
261
+ type: "toMarkdown",
262
+ id: e
263
+ }))).markdown;
264
+ }
265
+ get pageCount() {
266
+ return this._meta ? this._meta.pageCount : this._document ? this._getLayout()?.pages.length ?? 0 : 0;
267
+ }
268
+ get mode() {
269
+ return this._mode;
270
+ }
271
+ get document() {
272
+ if (this._meta && !this._document) throw Error("the raw document model stays in the worker in mode: 'worker'; use mode: 'main' if you need direct model access");
273
+ if (!this._document) throw Error("Document not loaded");
274
+ return this._document;
275
+ }
276
+ get comments() {
277
+ return this._meta?.comments ?? this._document?.comments ?? [];
278
+ }
279
+ get footnotes() {
280
+ return this._meta?.footnotes ?? this._document?.footnotes ?? [];
281
+ }
282
+ get endnotes() {
283
+ return this._meta?.endnotes ?? this._document?.endnotes ?? [];
284
+ }
285
+ _getLayout() {
286
+ if (!this._document) return null;
287
+ let e = D(this).services;
288
+ if (!e) throw Error("Document layout services are not initialized");
289
+ let t = ve(e);
290
+ if (!t) throw Error("Document layout variant store is not initialized");
291
+ return t.defaultLayout;
292
+ }
293
+ _getBookmarkPages() {
294
+ if (this._bookmarkPages) return this._bookmarkPages;
295
+ if (this._meta) return this._bookmarkPages = new Map(this._meta.bookmarkPages), this._bookmarkPages;
296
+ let e = this._getLayout();
297
+ return e ? (this._bookmarkPages = De(e), this._bookmarkPages) : null;
298
+ }
299
+ getBookmarkPage(e) {
300
+ return this._getBookmarkPages()?.get(e);
301
+ }
302
+ pageSize(e) {
303
+ if (this._meta) {
304
+ let t = this._meta.pageSizes, n = t[Math.max(0, Math.min(e, t.length - 1))];
305
+ return n ? {
306
+ widthPt: n.widthPt,
307
+ heightPt: n.heightPt
308
+ } : {
309
+ widthPt: 0,
310
+ heightPt: 0
311
+ };
312
+ }
313
+ if (!this._document) return {
314
+ widthPt: 0,
315
+ heightPt: 0
316
+ };
317
+ let t = this._getLayout();
318
+ if (!t || t.pages.length === 0) return {
319
+ widthPt: 0,
320
+ heightPt: 0
321
+ };
322
+ let n = Math.max(0, Math.min(e, t.pages.length - 1)), r = t.pages[n].geometry;
323
+ return {
324
+ widthPt: r.widthPt,
325
+ heightPt: r.heightPt
326
+ };
327
+ }
328
+ renderPage(e, t, n = {}) {
329
+ if (this._mode === "worker") throw Error("renderPage(canvas) is unavailable in mode: 'worker'; use renderPageToBitmap() and paint it via an ImageBitmapRenderingContext");
330
+ if (!this._source) throw Error("Document not loaded");
331
+ return O(this._source, e, t, {
332
+ ...n,
333
+ fetchImage: this._fetchImage,
334
+ layoutServices: D(this).services ?? void 0,
335
+ defaultCurrentDateMs: D(this).defaultCurrentDateMs
336
+ });
337
+ }
338
+ async renderPageToBitmap(e, t = {}) {
339
+ let { onTextRun: n, ...r } = t, i = {
340
+ ...r,
341
+ dpr: r.dpr ?? l()
342
+ };
343
+ if (this._mode === "worker") {
344
+ let t = await this._bridge.request((t) => ({
345
+ type: "renderPage",
346
+ id: t,
347
+ pageIndex: e,
348
+ opts: i
349
+ }));
350
+ if (n) for (let e of t.runs) n(e);
351
+ return t.bitmap;
352
+ }
353
+ let a = new OffscreenCanvas(1, 1);
354
+ return await this.renderPage(a, e, {
355
+ ...i,
356
+ onTextRun: n
357
+ }), a.transferToImageBitmap();
358
+ }
359
+ async collectPageRuns(e, t = {}) {
360
+ let n = {
361
+ ...t,
362
+ dpr: t.dpr ?? l()
363
+ };
364
+ if (this._mode === "worker") return (await this._bridge.request((t) => ({
365
+ type: "collectRuns",
366
+ id: t,
367
+ pageIndex: e,
368
+ opts: n
369
+ }))).runs;
370
+ let r = D(this), i = r.services;
371
+ if (!i) throw Error("Document layout services are not initialized");
372
+ return M(i, e, {
373
+ currentDate: n.currentDate,
374
+ defaultCurrentDateMs: r.defaultCurrentDateMs,
375
+ width: n.width
376
+ });
377
+ }
378
+ };
379
+ //#endregion
380
+ //#region packages/docx/src/tate-chu-yoko-overlay.ts
381
+ function G(e, t) {
382
+ if (!e.eastAsianVert) return 1;
383
+ let n = t(e.text);
384
+ return !(n > 0) || e.w >= n ? 1 : e.w / n;
385
+ }
386
+ //#endregion
387
+ //#region packages/docx/src/text-layer.ts
388
+ function K(e, t, n, r, i, a) {
389
+ e.innerHTML = "";
390
+ for (let o of t) {
391
+ let t = document.createElement("span");
392
+ t.textContent = o.text;
393
+ let s = o.transform ?? "";
394
+ if (a && o.eastAsianVert) {
395
+ let e = G(o, a(o.font));
396
+ e !== 1 && (s = `${s ? `${s} ` : ""}scaleX(${e})`);
397
+ }
398
+ let c = s ? `transform:${s};transform-origin:top left;` : "", l = i ? o.hyperlink : void 0, u = l ? "pointer" : "text", d = o.letterSpacingPx === void 0 ? "0" : `${o.letterSpacingPx}px`;
399
+ t.style.cssText = `position:absolute;left:${V(o.x, n)};top:${V(o.y, r)};font:${o.font};line-height:${o.h}px;letter-spacing:${d};` + c + `white-space:pre;color:transparent;cursor:${u};pointer-events:all;`, l && i && (t.title = l.kind === "external" ? l.url : l.ref, t.addEventListener("click", () => i(l))), e.appendChild(t);
400
+ }
401
+ }
402
+ function q(e, t, n, r, i, a, o = {}) {
403
+ e.innerHTML = "";
404
+ let s = o.match ?? "rgba(255, 214, 0, 0.42)", c = o.active ?? "rgba(255, 140, 0, 0.55)";
405
+ for (let o of n) {
406
+ let n = o.active ? c : s;
407
+ for (let s of o.slices) {
408
+ let o = t[s.runIndex];
409
+ if (!o) continue;
410
+ let c = a(o.font), l = ye(o.text, s.start, s.end, c), u = o.letterSpacingPx ?? 0, d = Math.max(0, Math.min(s.start, o.text.length)), f = Math.max(d, Math.min(s.end, o.text.length)), p = [...o.text.slice(0, d)].length, m = [...o.text.slice(d, f)].length, h = l.x + p * u, g = l.width + Math.max(0, m - 1) * u, _ = G(o, c), v = h * _, y = g * _;
411
+ if (y <= 0) continue;
412
+ let b = document.createElement("div"), x = o.transform ? `transform:${o.transform};transform-origin:top left;` : "";
413
+ b.style.cssText = `position:absolute;left:${V(o.x + v, r)};top:${V(o.y, i)};width:${V(y, r)};height:${V(o.h, i)};` + x + `background:${n};pointer-events:none;`, e.appendChild(b);
414
+ }
415
+ }
416
+ }
417
+ //#endregion
418
+ //#region packages/docx/src/find.ts
419
+ var J = class {
420
+ _pageRuns = /* @__PURE__ */ new Map();
421
+ _matches = [];
422
+ _active = -1;
423
+ _generation = 0;
424
+ _runsRevision = 0;
425
+ constructor(e, t) {
426
+ this._pageCount = e, this._collectPageRuns = t;
427
+ }
428
+ invalidate() {
429
+ this._generation++, this._runsRevision++, this._pageRuns.clear(), this._matches = [], this._active = -1;
430
+ }
431
+ pageRuns(e) {
432
+ return this._pageRuns.get(e);
433
+ }
434
+ setPageRuns(e, t) {
435
+ this._runsRevision++, this._pageRuns.set(e, t);
436
+ }
437
+ _matchAt(e) {
438
+ return this._matches[e];
439
+ }
440
+ pageHighlights(e) {
441
+ let t = [];
442
+ for (let n = 0; n < this._matches.length; n++) {
443
+ let r = this._matches[n];
444
+ r.page === e && t.push({
445
+ slices: r.slices,
446
+ active: n === this._active
447
+ });
448
+ }
449
+ return t;
450
+ }
451
+ activePage() {
452
+ let e = this._matchAt(this._active);
453
+ return e ? e.page : null;
454
+ }
455
+ matches() {
456
+ return this._matches.map((e, t) => ({
457
+ matchIndex: t,
458
+ text: e.text,
459
+ location: { page: e.page }
460
+ }));
461
+ }
462
+ async find(e, t = {}) {
463
+ let n = ++this._generation;
464
+ if (e.length === 0) return this._runsRevision++, this._pageRuns.clear(), this._matches = [], this._active = -1, [];
465
+ let r = this._runsRevision, i = new Map(this._pageRuns), a = this._pageCount();
466
+ for (let e = 0; e < a; e++) {
467
+ let t = i.get(e);
468
+ if (!t) {
469
+ try {
470
+ t = await this._collectPageRuns(e);
471
+ } catch (e) {
472
+ if (n !== this._generation) return [];
473
+ throw e;
474
+ }
475
+ if (n !== this._generation) return [];
476
+ i.set(e, t);
477
+ }
478
+ }
479
+ if (n !== this._generation) return [];
480
+ let o = r === this._runsRevision ? i : new Map([...i, ...this._pageRuns]), s = [];
481
+ for (let n = 0; n < a; n++) {
482
+ let r = o.get(n) ?? [], i = te(r);
483
+ for (let a of oe(i, e, t)) {
484
+ let e = a.slices.map((e) => r[e.runIndex].text.slice(e.start, e.end)).join("");
485
+ s.push({
486
+ page: n,
487
+ text: e,
488
+ slices: a.slices
489
+ });
490
+ }
491
+ }
492
+ return this._runsRevision++, this._pageRuns = o, this._matches = s, this._active = -1, this.matches();
493
+ }
494
+ next() {
495
+ return this._active = ie(this._active, this._matches.length), this._activePublic();
496
+ }
497
+ prev() {
498
+ return this._active = v(this._active, this._matches.length), this._activePublic();
499
+ }
500
+ _activePublic() {
501
+ let e = this._matchAt(this._active);
502
+ return e ? {
503
+ matchIndex: this._active,
504
+ text: e.text,
505
+ location: { page: e.page }
506
+ } : null;
507
+ }
508
+ }, Y = Symbol("DocxViewer.borrowedDocument"), X = class e {
509
+ _documentOwner;
510
+ get _doc() {
511
+ return this._documentOwner.current;
512
+ }
513
+ _borrowed;
514
+ _hostWindow;
515
+ _currentPage = 0;
516
+ _scale = null;
517
+ _canvas;
518
+ _wrapper;
519
+ _canvasMount;
520
+ _textLayer = null;
521
+ _highlightLayer = null;
522
+ _find;
523
+ _measureCtx = null;
524
+ _opts;
525
+ _mode;
526
+ _renderDispatcher;
527
+ _errorRouter;
528
+ _destroyed = !1;
529
+ static fromDocument(t, n, r = {}) {
530
+ return new e(t, {
531
+ ...r,
532
+ [Y]: n
533
+ });
534
+ }
535
+ constructor(e, t = {}) {
536
+ this._canvas = e, this._opts = t;
537
+ let n = t[Y];
538
+ this._borrowed = n !== void 0, this._mode = w("DocxViewer", t.mode, n), this._documentOwner = new g("DocxViewer", n ?? null, !1);
539
+ let r = e.ownerDocument?.defaultView ?? (typeof window < "u" ? window : null);
540
+ if (!r) throw Error("DocxViewer requires a canvas with an active Window");
541
+ this._hostWindow = r, this._canvasMount = new ae(e, {
542
+ wrapperCssText: "position:relative;display:inline-block;vertical-align:top;",
543
+ forceDisplayBlock: !0
544
+ }), this._wrapper = this._canvasMount.wrapper, this._renderDispatcher = new S(e, this._mode === "worker"), this._errorRouter = new re("DocxViewer", t.onError);
545
+ let i = new ne(this._wrapper, t.enableTextSelection === !0);
546
+ this._textLayer = i.textLayer, this._highlightLayer = i.highlightLayer, this._find = new J(() => this.pageCount, (e) => this._collectPageRuns(e));
547
+ }
548
+ async load(e) {
549
+ if (this._destroyed) throw Error("DocxViewer is destroyed");
550
+ if (this._borrowed) throw Error("DocxViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.");
551
+ try {
552
+ if (!await this._documentOwner.replace(() => W.load(e, {
553
+ useGoogleFonts: this._opts.useGoogleFonts,
554
+ maxZipEntryBytes: this._opts.maxZipEntryBytes,
555
+ resourceLimits: this._opts.resourceLimits,
556
+ debug: this._opts.debug,
557
+ onResourceMetrics: this._opts.onResourceMetrics,
558
+ workerTimeoutMs: this._opts.workerTimeoutMs,
559
+ wasmUrl: this._opts.wasmUrl,
560
+ math: this._opts.math,
561
+ mode: this._mode
562
+ }), () => {
563
+ this._renderDispatcher.begin(), this._find.invalidate();
564
+ })) return;
565
+ if (this._destroyed) throw Error("DocxViewer is destroyed");
566
+ this._currentPage = 0, this._find.invalidate(), await this._render();
567
+ } catch (e) {
568
+ if (this._destroyed) throw Error("DocxViewer is destroyed");
569
+ let t = e instanceof Error ? e : Error(String(e));
570
+ if (this._opts.onError) {
571
+ this._opts.onError(t);
572
+ return;
573
+ }
574
+ throw t;
575
+ }
576
+ }
577
+ get pageCount() {
578
+ return this._doc?.pageCount ?? 0;
579
+ }
580
+ get currentPage() {
581
+ return this._currentPage;
582
+ }
583
+ get canvasElement() {
584
+ return this._canvas;
585
+ }
586
+ async goToPage(e) {
587
+ this._doc && (this._currentPage = Math.max(0, Math.min(e, this.pageCount - 1)), await this._render());
588
+ }
589
+ async nextPage() {
590
+ await this.goToPage(this._currentPage + 1);
591
+ }
592
+ async prevPage() {
593
+ await this.goToPage(this._currentPage - 1);
594
+ }
595
+ _naturalWidthPx() {
596
+ return !this._doc || this._doc.pageCount === 0 ? 0 : this._doc.pageSize(this._currentPage).widthPt * s;
597
+ }
598
+ _renderWidth() {
599
+ if (this._scale === null) return this._opts.width;
600
+ let e = this._naturalWidthPx();
601
+ return e <= 0 ? this._opts.width : Math.round(e * this._scale);
602
+ }
603
+ getScale() {
604
+ if (this._scale !== null) return this._scale;
605
+ let e = this._naturalWidthPx();
606
+ return e <= 0 ? 1 : this._opts.width && this._opts.width > 0 ? this._opts.width / e : 1;
607
+ }
608
+ _zoomMin() {
609
+ return this._opts.zoomMin ?? .1;
610
+ }
611
+ _zoomMax() {
612
+ return this._opts.zoomMax ?? 4;
613
+ }
614
+ async setScale(e) {
615
+ let t = y(e, this._zoomMin(), this._zoomMax()), n = t !== this.getScale();
616
+ this._scale = t, await this._render(), n && this._opts.onScaleChange?.(t);
617
+ }
618
+ async zoomIn() {
619
+ await this.setScale(T(this.getScale()));
620
+ }
621
+ async zoomOut() {
622
+ await this.setScale(C(this.getScale()));
623
+ }
624
+ async fitWidth() {
625
+ await this._fit("width");
626
+ }
627
+ async fitPage() {
628
+ await this._fit("page");
629
+ }
630
+ async _fit(e) {
631
+ if (!this._doc || this._doc.pageCount === 0) return;
632
+ let t = this._doc.pageSize(this._currentPage), n = this._fitContainer();
633
+ if (!n) return;
634
+ let r = b({
635
+ contentWidth: t.widthPt * s,
636
+ contentHeight: t.heightPt * s,
637
+ containerWidth: n.clientWidth,
638
+ containerHeight: n.clientHeight
639
+ }, e);
640
+ r <= 0 || await this.setScale(r);
641
+ }
642
+ _fitContainer() {
643
+ return this._opts.container ?? this._wrapper.parentElement ?? null;
644
+ }
645
+ async findText(e, t = {}) {
646
+ if (!this._doc) return [];
647
+ let n = await this._find.find(e, t);
648
+ return this._redrawHighlights(), n;
649
+ }
650
+ async findNext() {
651
+ return this._activateMatch(this._find.next());
652
+ }
653
+ async findPrev() {
654
+ return this._activateMatch(this._find.prev());
655
+ }
656
+ clearFind() {
657
+ this._find.invalidate(), this._redrawHighlights();
658
+ }
659
+ async _activateMatch(e) {
660
+ return e ? (e.location.page === this._currentPage ? this._redrawHighlights() : await this.goToPage(e.location.page), e) : (this._redrawHighlights(), null);
661
+ }
662
+ _redrawHighlights() {
663
+ let e = this._find.pageRuns(this._currentPage) ?? [];
664
+ this._buildHighlightLayer(e);
665
+ }
666
+ async getResourceMetrics() {
667
+ if (!this._doc) throw Error("Document not loaded");
668
+ return await this._doc.getResourceMetrics();
669
+ }
670
+ destroy() {
671
+ this._destroyed || (this._destroyed = !0, this._errorRouter.close(), this._renderDispatcher.destroy(), P(this._canvas), this._documentOwner.close(), this._find.invalidate(), this._canvasMount.restore());
672
+ }
673
+ async _render() {
674
+ let e = this._renderDispatcher.begin();
675
+ try {
676
+ await this._renderPage(e);
677
+ } catch (t) {
678
+ this._renderDispatcher.isCurrent(e) && this._reportRenderError(t);
679
+ }
680
+ }
681
+ _reportRenderError(e) {
682
+ this._errorRouter.report(e);
683
+ }
684
+ async _renderPage(e) {
685
+ if (!this._doc) return;
686
+ let t = this._mode === "worker", n = this._renderWidth(), r = [], i = (e) => r.push(e);
687
+ if (t) {
688
+ let t = this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1), r = await this._doc.renderPageToBitmap(this._currentPage, {
689
+ width: n,
690
+ dpr: this._opts.dpr,
691
+ defaultTextColor: this._opts.defaultTextColor,
692
+ showTrackChanges: this._opts.showTrackChanges,
693
+ currentDate: this._opts.currentDate,
694
+ onTextRun: i
695
+ });
696
+ if (!this._renderDispatcher.commitBitmap(e, r, {
697
+ cssWidth: Math.round(r.width / t),
698
+ cssHeight: Math.round(r.height / t)
699
+ })) return;
700
+ } else if (await this._doc.renderPage(this._canvas, this._currentPage, {
701
+ ...this._opts,
702
+ width: n,
703
+ onTextRun: i
704
+ }), !this._renderDispatcher.isCurrent(e)) return;
705
+ this._textLayer && this._buildTextLayer(this._textLayer, r), this._find.setPageRuns(this._currentPage, r), this._buildHighlightLayer(r), this._opts.onPageChange?.(this._currentPage, this.pageCount);
706
+ }
707
+ _buildHighlightLayer(e) {
708
+ let t = this._highlightLayer;
709
+ if (!t) return;
710
+ let { width: n, height: r } = this._canvasCssPx();
711
+ q(t, e, this._find.pageHighlights(this._currentPage), n, r, (e) => this._measureForFont(e), this._opts.findHighlightColors);
712
+ }
713
+ _canvasCssPx() {
714
+ return {
715
+ width: parseFloat(this._canvas.style.width) || this._canvas.width,
716
+ height: parseFloat(this._canvas.style.height) || this._canvas.height
717
+ };
718
+ }
719
+ _measureForFont(e) {
720
+ this._measureCtx ||= document.createElement("canvas").getContext("2d");
721
+ let t = this._measureCtx;
722
+ return t ? (t.font = e, (e) => t.measureText(e).width) : (e) => e.length;
723
+ }
724
+ async _collectPageRuns(e) {
725
+ return this._doc ? this._doc.collectPageRuns(e, {
726
+ width: this._renderWidth(),
727
+ dpr: this._opts.dpr,
728
+ defaultTextColor: this._opts.defaultTextColor,
729
+ showTrackChanges: this._opts.showTrackChanges,
730
+ currentDate: this._opts.currentDate
731
+ }) : [];
732
+ }
733
+ _buildTextLayer(e, t) {
734
+ let { width: n, height: r } = this._canvasCssPx();
735
+ K(e, t, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e));
736
+ }
737
+ _hyperlinkHandler() {
738
+ return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
739
+ if (e.kind === "external") {
740
+ o(e.url, void 0, this._hostWindow);
741
+ return;
742
+ }
743
+ let t = this._doc?.getBookmarkPage(e.ref);
744
+ t !== void 0 && this.goToPage(t);
745
+ });
746
+ }
747
+ }, je = 150, Me = "0 1px 3px rgba(0,0,0,0.2)", Z = Symbol("DocxScrollViewer.borrowedDocument"), Q = class e {
748
+ _documentOwner;
749
+ get _doc() {
750
+ return this._documentOwner.current;
751
+ }
752
+ _borrowed;
753
+ _opts;
754
+ _container;
755
+ _wrapper;
756
+ _scrollHost;
757
+ _spacer;
758
+ _mode;
759
+ _scale = 1;
760
+ _scaleEstablished = !1;
761
+ _pendingScale = null;
762
+ _slots = /* @__PURE__ */ new Map();
763
+ _free = [];
764
+ _heights = [];
765
+ _lastRange = null;
766
+ _lastTopIndex = -1;
767
+ _scrollListener = null;
768
+ _destroyed = !1;
769
+ _measureCtx;
770
+ _bitmapInFlight = /* @__PURE__ */ new Set();
771
+ _renderEpoch = 0;
772
+ _settleTimer = null;
773
+ _wheelListener = null;
774
+ _pendingZoomAnchor = null;
775
+ _resizeObserver = null;
776
+ _prevBase = 0;
777
+ _lastFitWidth = 0;
778
+ _pageShadow;
779
+ _find = new J(() => this.pageCount, (e) => this._collectPageRuns(e));
780
+ _findActive = !1;
781
+ static fromDocument(t, n, r = {}) {
782
+ return new e(t, {
783
+ ...r,
784
+ [Z]: n
785
+ });
786
+ }
787
+ constructor(e, t = {}) {
788
+ if (e.tagName === "CANVAS") throw Error("DocxScrollViewer takes a container element (e.g. a <div>), not a <canvas> — the viewer creates and manages its own canvases. Pass a block container; for the single-page canvas API use DocxViewer.");
789
+ this._container = e, this._opts = t, this._pageShadow = t.pageShadow ?? Me;
790
+ let n = t[Z];
791
+ this._borrowed = n !== void 0, n ? (this._documentOwner = new g("DocxScrollViewer", n, !1), this._mode = w("DocxScrollViewer", t.mode, n)) : (this._documentOwner = new g("DocxScrollViewer"), this._mode = w("DocxScrollViewer", t.mode, void 0)), this._wrapper = document.createElement("div"), this._wrapper.style.cssText = "position:relative;width:100%;height:100%;overflow:hidden;", this._scrollHost = document.createElement("div"), this._scrollHost.style.cssText = "position:absolute;inset:0;overflow:auto;", this._scrollHost.style.scrollbarGutter = "stable", t.background && (this._scrollHost.style.background = t.background), this._spacer = document.createElement("div"), this._spacer.style.cssText = "position:absolute;top:0;left:0;width:1px;height:0;pointer-events:none;", this._scrollHost.appendChild(this._spacer), this._wrapper.appendChild(this._scrollHost), this._container.appendChild(this._wrapper), this._scrollListener = () => this._onScroll(), this._scrollHost.addEventListener("scroll", this._scrollListener), this._opts.enableZoom !== !1 && (this._wheelListener = (e) => {
792
+ if (!(e.ctrlKey || e.metaKey) || (e.preventDefault(), e.deltaY === 0)) return;
793
+ let t = this._scrollHost.getBoundingClientRect(), n = e.clientX - t.left, r = e.clientY - t.top;
794
+ this._pendingZoomAnchor = Number.isFinite(n) && Number.isFinite(r) ? {
795
+ x: n,
796
+ y: r
797
+ } : null, this.setScale(x(this._scale, e.deltaY));
798
+ }, this._scrollHost.addEventListener("wheel", this._wheelListener, { passive: !1 })), typeof ResizeObserver < "u" && (this._resizeObserver = new ResizeObserver(() => this._onResize()), this._resizeObserver.observe(this._container)), this._borrowed && this.relayout();
799
+ }
800
+ async load(e) {
801
+ if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
802
+ if (this._borrowed) throw Error("DocxScrollViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.");
803
+ try {
804
+ if (!await this._documentOwner.replace(() => W.load(e, {
805
+ useGoogleFonts: this._opts.useGoogleFonts,
806
+ maxZipEntryBytes: this._opts.maxZipEntryBytes,
807
+ resourceLimits: this._opts.resourceLimits,
808
+ debug: this._opts.debug,
809
+ onResourceMetrics: this._opts.onResourceMetrics,
810
+ workerTimeoutMs: this._opts.workerTimeoutMs,
811
+ wasmUrl: this._opts.wasmUrl,
812
+ math: this._opts.math,
813
+ mode: this._mode
814
+ }), (e) => {
815
+ if (this._find.invalidate(), this._findActive = !1, e) {
816
+ for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
817
+ this._lastTopIndex = -1;
818
+ }
819
+ })) return;
820
+ if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
821
+ this._find.invalidate(), this._findActive = !1, this.relayout();
822
+ } catch (e) {
823
+ if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
824
+ let t = e instanceof Error ? e : Error(String(e));
825
+ if (this._opts.onError) {
826
+ this._opts.onError(t);
827
+ return;
828
+ }
829
+ throw t;
830
+ }
831
+ }
832
+ get pageCount() {
833
+ return this._doc?.pageCount ?? 0;
834
+ }
835
+ _pageWidthPx(e) {
836
+ return this._doc.pageSize(e).widthPt * s * this._scale;
837
+ }
838
+ _pageHeightPx(e) {
839
+ return this._doc.pageSize(e).heightPt * s * this._scale;
840
+ }
841
+ _fitWidthPx() {
842
+ if (this._opts.width && this._opts.width > 0) return this._opts.width;
843
+ let e = this._scrollHost.clientWidth || this._container.clientWidth;
844
+ if (e <= 0) return 0;
845
+ let { left: t, right: n } = this._padH(), r = e - t - n;
846
+ return r > 0 ? r : 0;
847
+ }
848
+ _baseScale() {
849
+ if (!this._doc || this._doc.pageCount === 0) return 0;
850
+ let e = this._fitWidthPx();
851
+ if (e <= 0) return 0;
852
+ let t = this._doc.pageSize(0).widthPt;
853
+ return t <= 0 ? 0 : e / (t * s);
854
+ }
855
+ relayout() {
856
+ if (this._doc) {
857
+ if (!this._scaleEstablished) {
858
+ let e = this._baseScale();
859
+ if (e > 0) {
860
+ if (this._scale = e, this._prevBase = e, this._lastFitWidth = this._fitWidthPx(), this._scaleEstablished = !0, this._pendingScale !== null) {
861
+ let e = this._pendingScale;
862
+ this._pendingScale = null, e !== this._scale && (this._scale = e, this._opts.onScaleChange?.(e));
863
+ }
864
+ } else return;
865
+ }
866
+ this._recomputeHeights(), this._syncSpacer(), this._mountVisible();
867
+ }
868
+ }
869
+ _recomputeHeights() {
870
+ let e = this._doc.pageCount, t = Array(e);
871
+ for (let n = 0; n < e; n++) t[n] = this._pageHeightPx(n);
872
+ this._heights = t;
873
+ }
874
+ _gap() {
875
+ return this._opts.gap ?? 16;
876
+ }
877
+ _overscan() {
878
+ return this._opts.overscan ?? 1;
879
+ }
880
+ _pad() {
881
+ let e = this._gap();
882
+ return {
883
+ leading: this._opts.paddingTop ?? e,
884
+ trailing: this._opts.paddingBottom ?? e
885
+ };
886
+ }
887
+ _padH() {
888
+ let e = this._gap();
889
+ return {
890
+ left: this._opts.paddingLeft ?? e,
891
+ right: this._opts.paddingRight ?? e
892
+ };
893
+ }
894
+ _pageIndexAtOffset(e, t) {
895
+ let { offsets: n } = e, r = 0, i = n.length - 1, a = 0;
896
+ for (; r <= i;) {
897
+ let e = r + i >> 1;
898
+ n[e] <= t ? (a = e, r = e + 1) : i = e - 1;
899
+ }
900
+ return a;
901
+ }
902
+ _range() {
903
+ return B(this._heights, this._gap(), this._scrollHost.scrollTop, this._scrollHost.clientHeight, this._overscan(), this._pad());
904
+ }
905
+ _syncSpacer() {
906
+ let e = this._range();
907
+ this._lastRange = e, this._spacer.style.height = `${e.totalHeight}px`, this._syncSpacerWidth();
908
+ }
909
+ _syncSpacerWidth() {
910
+ let { left: e, right: t } = this._padH(), n = 0;
911
+ for (let e = 0; e < this._heights.length; e++) {
912
+ let t = this._pageWidthPx(e);
913
+ t > n && (n = t);
914
+ }
915
+ this._spacer.style.width = `${n + e + t}px`;
916
+ }
917
+ _onScroll() {
918
+ !this._doc || !this._scaleEstablished || this._mountVisible();
919
+ }
920
+ _mountVisible() {
921
+ if (!this._doc || this._doc.pageCount === 0) return;
922
+ let e = this._range();
923
+ this._lastRange = e;
924
+ for (let [t, n] of [...this._slots]) (t < e.start || t > e.end) && this._recycleSlot(t, n);
925
+ for (let t = e.start; t <= e.end; t++) if (this._slots.has(t)) this._positionSlot(this._slots.get(t), t, e);
926
+ else {
927
+ let n = this._acquireSlot();
928
+ this._positionSlot(n, t, e), this._slots.set(t, n), this._renderSlot(t, n);
929
+ }
930
+ e.topIndex !== this._lastTopIndex && (this._lastTopIndex = e.topIndex, this._opts.onVisiblePageChange?.(e.topIndex, this._doc.pageCount));
931
+ }
932
+ _applyPageShadow(e) {
933
+ this._pageShadow !== !1 && (e.style.boxShadow = this._pageShadow);
934
+ }
935
+ _acquireSlot() {
936
+ let e = this._free.pop();
937
+ if (e) return this._scrollHost.appendChild(e.wrapper), e;
938
+ let t = document.createElement("div");
939
+ t.style.cssText = "position:absolute;";
940
+ let n = document.createElement("canvas");
941
+ n.style.cssText = "display:block;background:#fff;", this._applyPageShadow(n), t.appendChild(n);
942
+ let r = null;
943
+ this._opts.enableTextSelection && (r = document.createElement("div"), r.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;user-select:text;-webkit-user-select:text;", t.appendChild(r));
944
+ let i = document.createElement("div");
945
+ return i.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;", t.appendChild(i), this._scrollHost.appendChild(t), {
946
+ wrapper: t,
947
+ canvas: n,
948
+ textLayer: r,
949
+ highlightLayer: i,
950
+ renderedPage: -1,
951
+ renderedScale: -1,
952
+ dispatcher: new S(n, this._mode === "worker")
953
+ };
954
+ }
955
+ _recycleSlot(e, t) {
956
+ this._slots.delete(e), t.dispatcher.destroy(), this._destroyed || (t.dispatcher = new S(t.canvas, this._mode === "worker")), t.textLayer && (t.textLayer.innerHTML = "", t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = ""), t.highlightLayer.innerHTML = "", t.highlightLayer.style.transform = "", t.highlightLayer.style.transformOrigin = "", t.renderedPage = -1, t.renderedScale = -1, t.wrapper.remove(), this._free.push(t);
957
+ }
958
+ _positionSlot(e, t, n) {
959
+ e.wrapper.style.top = `${n.offsets[t]}px`;
960
+ let r = this._pageWidthPx(t), i = this._pageHeightPx(t);
961
+ e.wrapper.style.width = `${r}px`, e.wrapper.style.height = `${i}px`;
962
+ let { left: a } = this._padH(), o = this._scrollHost.clientWidth;
963
+ e.wrapper.style.left = `${Math.max(a, (o - r) / 2)}px`;
964
+ }
965
+ _dpr() {
966
+ return this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1);
967
+ }
968
+ _renderSlot(e, t) {
969
+ if (!this._doc || t.renderedPage === e) return;
970
+ t.renderedPage = e;
971
+ let n = this._dpr(), r = this._pageWidthPx(e), i = this._renderEpoch, a = this._scale, o = t.dispatcher, s = o.begin();
972
+ if (this._mode === "worker") {
973
+ this._renderSlotBitmap(e, t, r, n, a, o, s);
974
+ return;
975
+ }
976
+ let c = [], l = !!this._opts.enableTextSelection && !!t.textLayer, u = l || this._findActive, d = u ? (e) => c.push(e) : void 0;
977
+ this._doc.renderPage(t.canvas, e, {
978
+ width: r,
979
+ dpr: n,
980
+ defaultTextColor: this._opts.defaultTextColor,
981
+ showTrackChanges: this._opts.showTrackChanges,
982
+ onTextRun: d
983
+ }).then(() => {
984
+ if (!(!o.isCurrent(s) || i !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e)) {
985
+ if (t.renderedScale = a, l && t.textLayer) {
986
+ let { width: e, height: n } = this._canvasCssPx(t.canvas);
987
+ K(t.textLayer, c, e, n, this._hyperlinkHandler(), (e) => this._measureForFont(e));
988
+ }
989
+ u && this._refreshFindRuns(e, c), this._redrawSlotHighlights(e, t);
990
+ }
991
+ }).catch((n) => {
992
+ o.isCurrent(s) && i === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e && this._reportRenderError(n);
993
+ });
994
+ }
995
+ _hyperlinkHandler() {
996
+ return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
997
+ if (e.kind === "external") {
998
+ o(e.url);
999
+ return;
1000
+ }
1001
+ let t = this._doc?.getBookmarkPage(e.ref);
1002
+ t !== void 0 && this.scrollToPage(t);
1003
+ });
1004
+ }
1005
+ _measureForFont(e) {
1006
+ this._measureCtx === void 0 && (this._measureCtx = document.createElement("canvas").getContext("2d"));
1007
+ let t = this._measureCtx;
1008
+ return !t || typeof t.measureText != "function" ? (e) => e.length : (t.font = e, (e) => t.measureText(e).width);
1009
+ }
1010
+ _canvasCssPx(e) {
1011
+ return {
1012
+ width: parseFloat(e.style.width) || e.width,
1013
+ height: parseFloat(e.style.height) || e.height
1014
+ };
1015
+ }
1016
+ _reportRenderError(e) {
1017
+ if (this._destroyed) return;
1018
+ let t = e instanceof Error ? e : Error(String(e));
1019
+ this._opts.onError ? this._opts.onError(t) : console.error("[ooxml] DocxScrollViewer render failed:", t);
1020
+ }
1021
+ async _renderSlotBitmap(e, t, n, r, i, a = t.dispatcher, o = a.begin()) {
1022
+ if (this._bitmapInFlight.has(e) || this._slots.get(e) !== t) return;
1023
+ let s = this._renderEpoch;
1024
+ this._bitmapInFlight.add(e);
1025
+ let c = !1, l = !!this._opts.enableTextSelection && !!t.textLayer, u = l || this._findActive, d = [];
1026
+ try {
1027
+ let f = await this._doc.renderPageToBitmap(e, {
1028
+ width: n,
1029
+ dpr: r,
1030
+ defaultTextColor: this._opts.defaultTextColor,
1031
+ showTrackChanges: this._opts.showTrackChanges,
1032
+ onTextRun: u ? (e) => d.push(e) : void 0
1033
+ });
1034
+ if (!a.isCurrent(o) || s !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) {
1035
+ f.close();
1036
+ return;
1037
+ }
1038
+ if (!a.commitBitmap(o, f, {
1039
+ cssWidth: Math.round(f.width / r),
1040
+ cssHeight: Math.round(f.height / r)
1041
+ })) return;
1042
+ if (t.renderedScale = i, t.textLayer && (t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = "", l)) {
1043
+ let { width: e, height: n } = this._canvasCssPx(t.canvas);
1044
+ K(t.textLayer, d, e, n, this._hyperlinkHandler(), (e) => this._measureForFont(e));
1045
+ }
1046
+ u && this._refreshFindRuns(e, d), this._redrawSlotHighlights(e, t), c = !0;
1047
+ } catch (n) {
1048
+ a.isCurrent(o) && s === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e && this._reportRenderError(n);
1049
+ } finally {
1050
+ this._bitmapInFlight.delete(e);
1051
+ let n = this._slots.get(e);
1052
+ !c && n && (n !== t || s !== this._renderEpoch || !a.isCurrent(o)) && !this._bitmapInFlight.has(e) && !this._destroyed && this._renderSlotBitmap(e, n, this._pageWidthPx(e), this._dpr(), this._scale);
1053
+ }
1054
+ }
1055
+ setScale(e) {
1056
+ let t = this._opts.zoomMin ?? .1, n = this._opts.zoomMax ?? 4, r = Math.min(n, Math.max(t, e)), i = this._pendingZoomAnchor;
1057
+ if (this._pendingZoomAnchor = null, !this._doc || this._doc.pageCount === 0 || !this._scaleEstablished) {
1058
+ this._pendingScale = r;
1059
+ return;
1060
+ }
1061
+ if (r === this._scale) return;
1062
+ let a = this._scale, o = i ? i.y : 0, s = this._range(), c = this._scrollHost.scrollTop, l = c + o, u = this._pageIndexAtOffset(s, l), d = this._heights[u] || 0, f = d > 0 ? (l - s.offsets[u]) / d : 0;
1063
+ f = Math.min(1, Math.max(0, f));
1064
+ let p = this._padH().left, m = this._scrollHost.scrollLeft || 0;
1065
+ this._renderEpoch++, this._scale = r, this._recomputeHeights();
1066
+ let h = B(this._heights, this._gap(), 0, this._scrollHost.clientHeight, this._overscan(), this._pad());
1067
+ this._spacer.style.height = `${h.totalHeight}px`, this._syncSpacerWidth();
1068
+ let g = Math.max(0, h.totalHeight - this._scrollHost.clientHeight), _ = (h.offsets[u] ?? 0) + f * (this._heights[u] || 0), v = l < (s.offsets[0] ?? 0) ? c : _ - o;
1069
+ if (this._scrollHost.scrollTop = Math.min(g, Math.max(0, v)), i) {
1070
+ let e = Math.max(0, (this._spacer.offsetWidth || 0) - this._scrollHost.clientWidth);
1071
+ this._scrollHost.scrollLeft = ee(m, i.x - p, a, r, { maxScroll: e });
1072
+ }
1073
+ this._previewVisible(), this._scheduleSettle(), this._opts.onScaleChange?.(r);
1074
+ }
1075
+ getScale() {
1076
+ return this._scaleEstablished ? this._scale : this._pendingScale ?? 1;
1077
+ }
1078
+ zoomIn() {
1079
+ this.setScale(T(this.getScale()));
1080
+ }
1081
+ zoomOut() {
1082
+ this.setScale(C(this.getScale()));
1083
+ }
1084
+ fitWidth() {
1085
+ this._fit("width");
1086
+ }
1087
+ fitPage() {
1088
+ this._fit("page");
1089
+ }
1090
+ _fit(e) {
1091
+ if (!this._doc || this._doc.pageCount === 0) return;
1092
+ let t = this._doc.pageSize(0), n = b({
1093
+ contentWidth: t.widthPt * s,
1094
+ contentHeight: t.heightPt * s,
1095
+ containerWidth: this._fitWidthPx(),
1096
+ containerHeight: this._scrollHost.clientHeight
1097
+ }, e);
1098
+ n <= 0 || this.setScale(n);
1099
+ }
1100
+ _previewVisible() {
1101
+ if (!this._doc || this._doc.pageCount === 0) return;
1102
+ let e = this._range();
1103
+ this._lastRange = e;
1104
+ for (let [t, n] of [...this._slots]) (t < e.start || t > e.end) && this._recycleSlot(t, n);
1105
+ for (let t = e.start; t <= e.end; t++) {
1106
+ let n = this._slots.get(t);
1107
+ if (n) this._previewSlot(n, t, e);
1108
+ else {
1109
+ let n = this._acquireSlot();
1110
+ this._positionSlot(n, t, e), this._slots.set(t, n), this._renderSlot(t, n);
1111
+ }
1112
+ }
1113
+ e.topIndex !== this._lastTopIndex && (this._lastTopIndex = e.topIndex, this._opts.onVisiblePageChange?.(e.topIndex, this._doc.pageCount));
1114
+ }
1115
+ _previewSlot(e, t, n) {
1116
+ if (this._positionSlot(e, t, n), e.canvas.style.width = `${this._pageWidthPx(t)}px`, e.canvas.style.height = `${this._pageHeightPx(t)}px`, e.textLayer && e.renderedScale > 0) {
1117
+ let t = this._scale / e.renderedScale;
1118
+ e.textLayer.style.transformOrigin = "0 0", e.textLayer.style.transform = `scale(${t})`;
1119
+ }
1120
+ }
1121
+ _scheduleSettle() {
1122
+ this._settleTimer !== null && clearTimeout(this._settleTimer), this._settleTimer = setTimeout(() => {
1123
+ this._settleTimer = null, this._settleRender();
1124
+ }, je);
1125
+ }
1126
+ _settleRender() {
1127
+ if (!(this._destroyed || !this._doc || this._doc.pageCount === 0)) for (let [e, t] of [...this._slots]) t.renderedScale !== this._scale && this._settleSlot(e, t);
1128
+ }
1129
+ _settleSlot(e, t) {
1130
+ if (!this._doc) return;
1131
+ let n = this._dpr(), r = this._pageWidthPx(e), i = this._scale, a = this._renderEpoch;
1132
+ if (this._mode === "worker") {
1133
+ this._renderSlotBitmap(e, t, r, n, i);
1134
+ return;
1135
+ }
1136
+ let o = document.createElement("canvas");
1137
+ o.style.cssText = "display:block;background:#fff;", this._applyPageShadow(o);
1138
+ let s = new S(o, !1), c = s.begin(), l = [], u = !!this._opts.enableTextSelection && !!t.textLayer, d = u || this._findActive, f = d ? (e) => l.push(e) : void 0;
1139
+ this._doc.renderPage(o, e, {
1140
+ width: r,
1141
+ dpr: n,
1142
+ defaultTextColor: this._opts.defaultTextColor,
1143
+ showTrackChanges: this._opts.showTrackChanges,
1144
+ onTextRun: f
1145
+ }).then(() => {
1146
+ if (!s.isCurrent(c) || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) {
1147
+ s.destroy();
1148
+ return;
1149
+ }
1150
+ let n = t.canvas;
1151
+ if (t.dispatcher.destroy(), t.wrapper.insertBefore(o, n), n.remove(), t.canvas = o, t.dispatcher = s, t.renderedScale = i, t.textLayer && (t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = "", u)) {
1152
+ let { width: e, height: n } = this._canvasCssPx(o);
1153
+ K(t.textLayer, l, e, n, this._hyperlinkHandler(), (e) => this._measureForFont(e));
1154
+ }
1155
+ d && this._refreshFindRuns(e, l), this._redrawSlotHighlights(e, t);
1156
+ }).catch((n) => {
1157
+ s.isCurrent(c) && a === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e && this._reportRenderError(n), s.destroy();
1158
+ });
1159
+ }
1160
+ scrollToPage(e, t) {
1161
+ if (!this._doc || this._doc.pageCount === 0 || !this._scaleEstablished) return;
1162
+ let n = Math.max(0, Math.min(e, this._doc.pageCount - 1)), r = B(this._heights, this._gap(), 0, this._scrollHost.clientHeight, this._overscan(), this._pad()), i = r.offsets[n] ?? 0, a = Math.max(0, r.totalHeight - this._scrollHost.clientHeight), o = Math.min(a, Math.max(0, i)), s = this._scrollHost;
1163
+ typeof s.scrollTo == "function" ? s.scrollTo({
1164
+ top: o,
1165
+ behavior: t?.behavior ?? "auto"
1166
+ }) : this._scrollHost.scrollTop = o, this._mountVisible();
1167
+ }
1168
+ async findText(e, t = {}) {
1169
+ if (!this._doc) return [];
1170
+ this._findActive = e.length > 0;
1171
+ let n = await this._find.find(e, t);
1172
+ return this._redrawHighlights(), n;
1173
+ }
1174
+ async findNext() {
1175
+ return this._activateMatch(this._find.next());
1176
+ }
1177
+ async findPrev() {
1178
+ return this._activateMatch(this._find.prev());
1179
+ }
1180
+ clearFind() {
1181
+ this._findActive = !1, this._find.invalidate(), this._redrawHighlights();
1182
+ }
1183
+ async _activateMatch(e) {
1184
+ return e && this.scrollToPage(e.location.page), this._redrawHighlights(), e;
1185
+ }
1186
+ async _collectPageRuns(e) {
1187
+ return this._doc ? this._doc.collectPageRuns(e, {
1188
+ width: this._pageWidthPx(e),
1189
+ defaultTextColor: this._opts.defaultTextColor,
1190
+ showTrackChanges: this._opts.showTrackChanges
1191
+ }) : [];
1192
+ }
1193
+ _redrawHighlights() {
1194
+ for (let [e, t] of this._slots) this._redrawSlotHighlights(e, t);
1195
+ }
1196
+ _refreshFindRuns(e, t) {
1197
+ this._findActive && this._find.setPageRuns(e, t);
1198
+ }
1199
+ _redrawSlotHighlights(e, t) {
1200
+ if (!this._findActive) {
1201
+ t.highlightLayer.innerHTML = "";
1202
+ return;
1203
+ }
1204
+ let n = this._find.pageRuns(e);
1205
+ if (!n) {
1206
+ t.highlightLayer.innerHTML = "";
1207
+ return;
1208
+ }
1209
+ q(t.highlightLayer, n, this._find.pageHighlights(e), this._pageWidthPx(e), this._pageHeightPx(e), (e) => this._measureForFont(e), this._opts.findHighlightColors);
1210
+ }
1211
+ _onResize() {
1212
+ if (!this._doc || this._doc.pageCount === 0) return;
1213
+ if (!this._scaleEstablished) {
1214
+ this.relayout();
1215
+ return;
1216
+ }
1217
+ if (this._opts.refitOnResize === !1) {
1218
+ this._lastFitWidth = this._fitWidthPx(), this._mountVisible();
1219
+ return;
1220
+ }
1221
+ let e = this._baseScale();
1222
+ if (e <= 0) return;
1223
+ let t = this._fitWidthPx();
1224
+ if (t === this._lastFitWidth) {
1225
+ this._mountVisible();
1226
+ return;
1227
+ }
1228
+ this._lastFitWidth = t;
1229
+ let n = this._prevBase > 0 ? this._scale / this._prevBase : 1;
1230
+ this._prevBase = e, this.setScale(e * n), this._mountVisible();
1231
+ }
1232
+ get topVisiblePage() {
1233
+ return this._lastRange?.topIndex ?? 0;
1234
+ }
1235
+ mountedPageIndicesForTest() {
1236
+ return [...this._slots.keys()];
1237
+ }
1238
+ scaleForTest() {
1239
+ return this._scale;
1240
+ }
1241
+ baseScaleForTest() {
1242
+ return this._baseScale();
1243
+ }
1244
+ renderEpochForTest() {
1245
+ return this._renderEpoch;
1246
+ }
1247
+ resizeForTest() {
1248
+ this._onResize();
1249
+ }
1250
+ contentAtViewportYForTest(e) {
1251
+ let t = this._range(), n = this._scrollHost.scrollTop + e, r = this._pageIndexAtOffset(t, n), i = this._heights[r] || 0;
1252
+ return {
1253
+ page: r,
1254
+ frac: i > 0 ? Math.min(1, Math.max(0, (n - t.offsets[r]) / i)) : 0
1255
+ };
1256
+ }
1257
+ viewportYOfForTest(e, t) {
1258
+ return (this._range().offsets[e] ?? 0) + t * (this._heights[e] || 0) - this._scrollHost.scrollTop;
1259
+ }
1260
+ async getResourceMetrics() {
1261
+ if (!this._doc) throw Error("Document not loaded");
1262
+ return await this._doc.getResourceMetrics();
1263
+ }
1264
+ destroy() {
1265
+ if (!this._destroyed) {
1266
+ this._destroyed = !0, this._find.invalidate(), this._findActive = !1, this._scrollListener &&= (this._scrollHost.removeEventListener("scroll", this._scrollListener), null), this._wheelListener &&= (this._scrollHost.removeEventListener("wheel", this._wheelListener), null), this._resizeObserver?.disconnect(), this._resizeObserver = null, this._settleTimer !== null && (clearTimeout(this._settleTimer), this._settleTimer = null);
1267
+ for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
1268
+ this._free.length = 0, this._documentOwner.close(), this._wrapper.remove();
1269
+ }
1270
+ }
1271
+ };
1272
+ //#endregion
1273
+ //#region packages/docx/src/types.ts
1274
+ function $(e) {
1275
+ let t = [];
1276
+ for (let n of e.content) {
1277
+ if (n.type !== "paragraph") continue;
1278
+ let e = "";
1279
+ for (let t of n.runs) t.type === "text" && !t.noteRef && (e += t.text);
1280
+ e = e.trim(), e && t.push(e);
1281
+ }
1282
+ return t.join(" ");
1283
+ }
1284
+ //#endregion
1285
+ //#region src/docx.ts
1286
+ var Ne = /* @__PURE__ */ e({
1287
+ DocxDocument: () => W,
1288
+ DocxScrollViewer: () => Q,
1289
+ DocxViewer: () => X,
1290
+ OoxmlDecodedImageLimitError: () => r,
1291
+ OoxmlError: () => f,
1292
+ OoxmlResourceLimitError: () => c,
1293
+ autoResize: () => ce,
1294
+ buildDocxHighlightLayer: () => q,
1295
+ buildDocxTextLayer: () => K,
1296
+ isOoxmlDecodedImageLimitError: () => i,
1297
+ noteText: () => $,
1298
+ openExternalHyperlink: () => o
1299
+ });
1300
+ //#endregion
1301
+ export { q as a, X as i, $ as n, K as o, Q as r, W as s, Ne as t };