@silurus/ooxml 0.80.3 → 0.82.0

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 (67) hide show
  1. package/README.md +61 -85
  2. package/dist/assets/render-worker-7-Zr7fSw.js +10 -0
  3. package/dist/assets/render-worker-B5gsW6b5.js +11 -0
  4. package/dist/assets/render-worker-Dw_wQRIh.js +24 -0
  5. package/dist/{canvas-viewer-mechanics-D-r6wHY_.js → canvas-viewer-mechanics-CS_qbr6T.js} +1 -1
  6. package/dist/chart-ex.mjs +1017 -0
  7. package/dist/comment-occurrence-C34fWs_F.js +6 -0
  8. package/dist/comment-ui-runtime-BAe30Ct9.js +112 -0
  9. package/dist/comment-ui-runtime-BUCj4hWn.js +171 -0
  10. package/dist/comment-ui-runtime-F4a3te6p.js +2 -0
  11. package/dist/comments-Cf9W7r3M.js +241 -0
  12. package/dist/{document-pull-client-vxk-Aomu.js → document-pull-client-BCgmytqI.js} +4682 -4541
  13. package/dist/docx-wokGKYfi.js +2162 -0
  14. package/dist/docx.mjs +6 -4
  15. package/dist/docx_parser_bg.wasm +0 -0
  16. package/dist/dom-interaction-boundary-C8F6HO5x.js +119 -0
  17. package/dist/highlight-rect-MaCt0om0.js +13 -0
  18. package/dist/index.mjs +3 -3
  19. package/dist/{line-distribute-Bvtp0Gt6.js → line-distribute-iXsUCIH-.js} +17 -16
  20. package/dist/{line-metrics-DdEJYxjx.js → line-metrics-B3syvDn2.js} +667 -7492
  21. package/dist/math.mjs +2 -2
  22. package/dist/node.mjs +248 -247
  23. package/dist/plot-area-frame-DHV02PJU.js +3670 -0
  24. package/dist/pptx-DU8L8I2T.js +2432 -0
  25. package/dist/pptx.mjs +6 -5
  26. package/dist/pptx_parser_bg.wasm +0 -0
  27. package/dist/read-only-comment-decoration-DcFevX_Q.js +96 -0
  28. package/dist/read-only-comment-margin-Dn2y55W6.js +189 -0
  29. package/dist/region-map.mjs +102 -97
  30. package/dist/{render-CoqMHcbF.js → render-CenWM4g1.js} +1 -1
  31. package/dist/{render-worker-host-IuQFpoJM.js → render-worker-host-BNENN3qP.js} +1 -1
  32. package/dist/{render-worker-host-CYPhmBtX.js → render-worker-host-BmH3kGSj.js} +1 -1
  33. package/dist/{render-worker-host-GlLR1rtF.js → render-worker-host-CmPBviYJ.js} +1 -1
  34. package/dist/renderer-CYr9YTXM.js +5856 -0
  35. package/dist/{renderer-module-contract-BNGz8HvO.js → renderer-module-contract-DLbb7zY0.js} +4 -3
  36. package/dist/{resource-measurement-CgMubiAI.js → resource-measurement-CsW4_eYt.js} +12 -11
  37. package/dist/{session-DkPblDiq.js → session-Cky_swUj.js} +8 -8
  38. package/dist/{slide-pull-client-m2blvngt.js → slide-pull-client-CqTVFb3W.js} +1004 -1091
  39. package/dist/source-key-BklvnEyQ.js +42 -0
  40. package/dist/three-d-7MaVzQuZ.js +1346 -0
  41. package/dist/three-d.mjs +1238 -797
  42. package/dist/types/chart-ex.d.ts +949 -0
  43. package/dist/types/docx.d.ts +497 -28
  44. package/dist/types/index.d.ts +649 -39
  45. package/dist/types/math.d.ts +1 -1
  46. package/dist/types/node.d.ts +385 -22
  47. package/dist/types/pptx.d.ts +435 -24
  48. package/dist/types/region-map.d.ts +318 -6
  49. package/dist/types/three-d.d.ts +318 -6
  50. package/dist/types/xlsx.d.ts +384 -19
  51. package/dist/units-BzZ0gAxs.js +4 -0
  52. package/dist/{worksheet-pull-client-BntP6RiO.js → worksheet-pull-client-CYtwXP5D.js} +19 -19
  53. package/dist/{xlsx-DqMe7J2C.js → xlsx-DlV37-0j.js} +1594 -1349
  54. package/dist/xlsx.mjs +6 -5
  55. package/dist/xlsx_parser_bg.wasm +0 -0
  56. package/package.json +7 -1
  57. package/dist/assets/render-worker-CRaEOHkw.js +0 -9
  58. package/dist/assets/render-worker-DQGLj5Zv.js +0 -22
  59. package/dist/assets/render-worker-rnrSLmqL.js +0 -8
  60. package/dist/chart-number-format-qLhnk6hj.js +0 -475
  61. package/dist/docx-DN0PRx2f.js +0 -1733
  62. package/dist/highlight-rect-BuX5rWP4.js +0 -48
  63. package/dist/pptx-B-Laftl1.js +0 -2134
  64. package/dist/three-d-C28kqDym.js +0 -1086
  65. /package/dist/{mathjax-DgAl7Yi5.js → mathjax-DwIrafQ6.js} +0 -0
  66. /package/dist/{transfer-CKZ79zFw.js → transfer-R6NjgBKD.js} +0 -0
  67. /package/dist/{visible-index-BjesVGhg.js → visible-index-BFE3PWiY.js} +0 -0
@@ -1,1733 +0,0 @@
1
- import { t as e } from "./chunk-DmhlhrBa.js";
2
- import { B as t, Ot as n, R as r, Rt as i, a, cn as o, it as s, jt as c, ln as l, mt as u, q as d, z as f, zt as p } from "./line-metrics-DdEJYxjx.js";
3
- import { C as m, E as h, S as g, T as _, _ as v, a as y, b, c as x, d as ee, f as te, g as ne, h as re, i as S, l as C, m as ie, n as ae, o as oe, p as se, r as ce, s as le, t as ue, u as de, v as w, w as fe, x as pe, y as T } from "./canvas-viewer-mechanics-D-r6wHY_.js";
4
- import { a as me, c as he, i as ge, o as _e, r as ve, s as ye, t as be } from "./bounded-raw-part-cache-C6ro6Ezf.js";
5
- import { C as xe, S as Se, _ as E, a as Ce, b as we, c as Te, d as Ee, f as De, g as Oe, h as ke, l as Ae, m as je, n as D, o as Me, p as Ne, s as Pe, t as O, v as k, w as Fe, x as A, y as Ie } from "./document-pull-client-vxk-Aomu.js";
6
- import { N as j } from "./three-d-C28kqDym.js";
7
- import { n as Le } from "./renderer-module-contract-BNGz8HvO.js";
8
- import { n as Re, r as M, t as N } from "./highlight-rect-BuX5rWP4.js";
9
- //#region packages/core/src/fonts/embedded.ts
10
- function ze(e, t) {
11
- let n = Be(t), r = e.slice(), i = Math.min(32, r.length);
12
- for (let e = 0; e < i; e++) r[e] ^= n[e % 16];
13
- return r;
14
- }
15
- function Be(e) {
16
- let t = e.replace(/[{}\-\s]/g, "");
17
- if (t.length !== 32 || /[^0-9a-fA-F]/.test(t)) throw Error(`invalid fontKey GUID: ${e}`);
18
- let n = new Uint8Array(16);
19
- for (let e = 0; e < 16; e++) n[e] = parseInt(t.slice(e * 2, e * 2 + 2), 16);
20
- return n.reverse();
21
- }
22
- function Ve(e, t, n, r) {
23
- let i = 2166136261;
24
- for (let e = 0; e < r.length; e++) i ^= r[e], i = Math.imul(i, 16777619);
25
- return `${e}|${t}|${n}|${r.length}|${(i >>> 0).toString(16)}`;
26
- }
27
- async function He(e, t = 30 * 1024 * 1024) {
28
- let n = ve();
29
- if (!n || typeof FontFace > "u") return [];
30
- let r = [], i = [], a = [];
31
- for (let o of e) try {
32
- if (o.bytes.length === 0 || o.bytes.length > t) {
33
- a.push(o.family);
34
- continue;
35
- }
36
- let e = o.odttf ? ze(o.bytes, o.fontKey ?? "") : o.bytes, { face: s, isNew: c } = he(`embedded:${Ve(o.family, o.weight, o.style, e)}`, n, () => {
37
- let t = e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength), r = new FontFace(o.family, t, {
38
- weight: o.weight,
39
- style: o.style
40
- });
41
- return n.add(r), r;
42
- });
43
- r.push(s), c && i.push(s);
44
- } catch {
45
- a.push(o.family);
46
- }
47
- return i.length > 0 && await _e(Promise.allSettled(i.map((e) => e.load())).then((e) => (e.forEach((e, t) => {
48
- e.status === "rejected" && a.push(i[t].family);
49
- }), 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;
50
- }
51
- function Ue(e) {
52
- ye(e);
53
- }
54
- //#endregion
55
- //#region packages/docx/src/worker.ts?worker&inline
56
- var P = "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)})}};", F = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", P], { type: "text/javascript;charset=utf-8" });
57
- function We(e) {
58
- let t;
59
- try {
60
- if (t = F && (self.URL || self.webkitURL).createObjectURL(F), !t) throw "";
61
- let n = new Worker(t, {
62
- type: "module",
63
- name: e?.name
64
- });
65
- return n.addEventListener("error", () => {
66
- (self.URL || self.webkitURL).revokeObjectURL(t);
67
- }), n;
68
- } catch {
69
- return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(P), {
70
- type: "module",
71
- name: e?.name
72
- });
73
- }
74
- }
75
- //#endregion
76
- //#region packages/docx/src/wasm/docx_parser_bg.wasm?url
77
- var Ge = new URL("docx_parser_bg.wasm", import.meta.url).href;
78
- //#endregion
79
- //#region packages/docx/src/bookmark-nav.ts
80
- function Ke(e) {
81
- let t = /* @__PURE__ */ new Map();
82
- for (let n of e.pages) for (let e of n.bookmarkStarts) e.name !== "" && !t.has(e.name) && t.set(e.name, n.pageIndex);
83
- return t;
84
- }
85
- //#endregion
86
- //#region packages/docx/src/embedded-fonts.ts
87
- async function qe(e, t) {
88
- let n = e.embeddedFonts;
89
- if (!n || n.length === 0) return [];
90
- let r = (await Promise.all(n.map(async (e) => {
91
- try {
92
- let n = await t(e.partPath);
93
- return {
94
- family: e.fontName,
95
- bytes: n,
96
- odttf: e.partPath.toLowerCase().endsWith(".odttf"),
97
- fontKey: e.fontKey,
98
- weight: Je(e.style),
99
- style: Ye(e.style)
100
- };
101
- } catch {
102
- return null;
103
- }
104
- }))).filter((e) => e !== null);
105
- return r.length === 0 ? [] : He(r);
106
- }
107
- function Je(e) {
108
- return e === "bold" || e === "boldItalic" ? "bold" : "normal";
109
- }
110
- function Ye(e) {
111
- return e === "italic" || e === "boldItalic" ? "italic" : "normal";
112
- }
113
- //#endregion
114
- //#region packages/docx/src/element-context.ts
115
- var I = de, Xe = 16384;
116
- function L(e, t) {
117
- let n = Math.min(e.length, t);
118
- if (n > 0 && n < e.length) {
119
- let t = e.charCodeAt(n - 1), r = e.charCodeAt(n);
120
- t >= 55296 && t <= 56319 && r >= 56320 && r <= 57343 && n--;
121
- }
122
- return e.slice(0, n);
123
- }
124
- function Ze(e, t) {
125
- let n = [], r = 0, i = !1;
126
- for (let a of e) {
127
- if (a.length === 0) continue;
128
- if (r > 0) {
129
- if (r >= t) {
130
- i = !0;
131
- break;
132
- }
133
- n.push("\n"), r++;
134
- }
135
- let e = L(a, Math.max(0, t - r));
136
- if (n.push(e), r += e.length, e.length < a.length) {
137
- i = !0;
138
- break;
139
- }
140
- }
141
- let a = n.join("");
142
- return {
143
- ...a.length === 0 ? {} : { text: a },
144
- truncated: i
145
- };
146
- }
147
- function* R(e) {
148
- if (e.kind === "paragraph") {
149
- for (let t of e.lines) {
150
- let e = t.placements.flatMap((e) => e.kind === "text" ? [e.text] : []).join("");
151
- e && (yield e);
152
- }
153
- return;
154
- }
155
- if (e.kind === "table") {
156
- for (let t of e.rows) for (let e of t.cells) for (let t of e.blocks) yield* R(t.layout);
157
- return;
158
- }
159
- if (e.kind === "note" || e.kind === "textbox") for (let t of e.story.blocks) yield* R(t);
160
- }
161
- function* Qe(e) {
162
- for (let t of e.drawing.commands) (t.kind === "text" || t.kind === "watermark-text") && (yield t.text);
163
- for (let t of e.textBoxes) yield* R(t);
164
- }
165
- function z(e) {
166
- let t = e ?? Xe;
167
- if (!Number.isFinite(t) || t < 0) throw RangeError("maxTextCharacters must be a finite non-negative number.");
168
- return Math.min(I, Math.floor(t));
169
- }
170
- function $e(e) {
171
- return {
172
- story: e.story,
173
- storyInstance: e.storyInstance,
174
- path: [...e.path]
175
- };
176
- }
177
- function et(e) {
178
- return "drawing" in e ? e.drawing.inkBounds : e.placement.bounds;
179
- }
180
- function tt(e) {
181
- let t = et(e), n = [
182
- k(e.pointToPage, t),
183
- k(e.pointToPage, {
184
- xPt: t.xPt + t.widthPt,
185
- yPt: t.yPt
186
- }),
187
- k(e.pointToPage, {
188
- xPt: t.xPt,
189
- yPt: t.yPt + t.heightPt
190
- }),
191
- k(e.pointToPage, {
192
- xPt: t.xPt + t.widthPt,
193
- yPt: t.yPt + t.heightPt
194
- })
195
- ], r = Math.min(...n.map((e) => e.xPt)), i = Math.min(...n.map((e) => e.yPt)), a = Math.max(...n.map((e) => e.xPt)), o = Math.max(...n.map((e) => e.yPt));
196
- return {
197
- xPt: r,
198
- yPt: i,
199
- widthPt: a - r,
200
- heightPt: o - i
201
- };
202
- }
203
- function B(e, t) {
204
- return t.xPt >= e.xPt && t.xPt <= e.xPt + e.widthPt && t.yPt >= e.yPt && t.yPt <= e.yPt + e.heightPt;
205
- }
206
- function nt(e, t) {
207
- let n = !1;
208
- for (let r = 0, i = t.length - 1; r < t.length; i = r++) {
209
- let a = t[r], o = t[i];
210
- a.yPt > e.yPt != o.yPt > e.yPt && e.xPt < (o.xPt - a.xPt) * (e.yPt - a.yPt) / (o.yPt - a.yPt) + a.xPt && (n = !n);
211
- }
212
- return n;
213
- }
214
- function rt(e, t) {
215
- return B(e.inkBounds, t) ? e.clip ? e.clip.kind === "rect" ? B(e.clip.rect, t) : nt(t, e.clip.points) : !0 : !1;
216
- }
217
- function it(e, t, n) {
218
- for (let n of e.clips) {
219
- let e = E(n.pointToPage, t);
220
- if (!e || !B(n.bounds, e)) return !1;
221
- }
222
- return "drawing" in e ? rt(e.drawing, n) : B(e.placement.bounds, n);
223
- }
224
- function V(e, t) {
225
- return e.commands.find((e) => e.kind === "resource" && e.resourceKind === t);
226
- }
227
- function at(e) {
228
- return V(e, "chart") ? "chart" : e.commands.some((e) => e.kind === "drawingml-shape" || e.kind === "drawingml-image-fill" || e.kind === "fill-rect" || e.kind === "stroke-rect" || e.kind === "text" || e.kind === "watermark-text") ? "shape" : V(e, "image") ? "image" : null;
229
- }
230
- function ot(e, t, n, r, i, a) {
231
- let o = "drawing" in e ? at(e.drawing) : e.placement.resourceKind;
232
- if (!o) return null;
233
- let s, c = !1, l, u;
234
- if (o === "chart") {
235
- let t = "drawing" in e ? V(e.drawing, "chart").resourceKey : e.placement.resourceKey, n = i.resolve(t, "chart"), r = ee(n.model, a);
236
- s = r.text, c = r.truncated, u = n.model.series.length;
237
- } else if (o === "image") {
238
- let t = "drawing" in e ? V(e.drawing, "image").resourceKey : e.placement.resourceKey, n = i.descriptors.find((e) => e.resourceKey === t && e.kind === "image" && "mimeType" in e);
239
- if (!n) throw Error(`Unknown image paint resource: ${t}`);
240
- l = n.mimeType;
241
- } else {
242
- let t = Ze(Qe(e), a);
243
- s = t.text, c = t.truncated;
244
- }
245
- return {
246
- format: "docx",
247
- kind: "element",
248
- pageIndex: t,
249
- elementIndex: n,
250
- elementType: o,
251
- point: { ...r },
252
- bounds: tt(e),
253
- source: $e("drawing" in e ? e.drawing.source : e.source),
254
- ...s === void 0 ? {} : { text: s },
255
- ...l === void 0 ? {} : { mimeType: l },
256
- ...u === void 0 ? {} : { seriesCount: u },
257
- truncated: c,
258
- truncationReasons: c ? ["text"] : [],
259
- textCharacters: s?.length ?? 0,
260
- maxTextCharacters: a
261
- };
262
- }
263
- function st(e, t, n, r, i = {}) {
264
- if (!Number.isFinite(n.xPt) || !Number.isFinite(n.yPt)) throw RangeError("DOCX hit-test point must contain finite page coordinates.");
265
- let a = z(i.maxTextCharacters), o = Oe(e, t);
266
- for (let e = o.length - 1; e >= 0; e--) {
267
- let i = o[e], s = E(i.pointToPage, n);
268
- if (!s || !it(i, n, s)) continue;
269
- let c = ot(i, t, e, n, r, a);
270
- if (c) return c;
271
- }
272
- return null;
273
- }
274
- function ct(e, t, n, r) {
275
- return st(Ie(e, {
276
- currentDate: r.currentDate,
277
- defaultCurrentDateMs: r.defaultCurrentDateMs
278
- }, t).layout, t, n, xe(e), r);
279
- }
280
- function H(e, t) {
281
- let n = z(t), r = e.text === void 0 ? void 0 : L(e.text, n), i = e.truncated || e.text !== void 0 && r.length < e.text.length;
282
- return {
283
- ...structuredClone(e),
284
- ...r === void 0 ? {} : { text: r },
285
- truncated: i,
286
- truncationReasons: i ? ["text"] : [],
287
- textCharacters: r?.length ?? 0,
288
- maxTextCharacters: n
289
- };
290
- }
291
- //#endregion
292
- //#region packages/docx/src/document.ts
293
- var U = class e {
294
- _metrics = null;
295
- _document = null;
296
- _source = null;
297
- _meta = null;
298
- _bookmarkPages = null;
299
- _mode = "main";
300
- _threeD;
301
- _regionMap;
302
- _worker;
303
- _bridge;
304
- _rawParts = new be({
305
- maxEntries: 64,
306
- maxBytes: d
307
- });
308
- _embeddedFontFaces = [];
309
- _googleFontFaces = [];
310
- _localMetricFontFaces = [];
311
- _fetchImage = (e, t) => this.getImage(e, t);
312
- constructor(e, t, n, r) {
313
- this._worker = e, this._mode = t, we(this, n), this._bridge = new m(this._worker, {
314
- correlate: (e) => "protocol" in e && e.protocol === "ooxml-pull-v1" ? e.requestId : "id" in e ? e.id : void 0,
315
- toError: (e) => {
316
- if (!("protocol" in e || e.type !== "error")) return Object.assign(s(e), {
317
- ...e.reason === void 0 ? {} : { reason: e.reason },
318
- ...e.outgoingColumnIndex === void 0 ? {} : { outgoingColumnIndex: e.outgoingColumnIndex },
319
- ...e.outgoingColumnCount === void 0 ? {} : { outgoingColumnCount: e.outgoingColumnCount },
320
- ...e.incomingColumnCount === void 0 ? {} : { incomingColumnCount: e.incomingColumnCount }
321
- });
322
- }
323
- });
324
- let i = new URL(r ?? Ge, location.href).href;
325
- this._bridge.post({
326
- type: "init",
327
- wasmUrl: i
328
- });
329
- }
330
- static async load(n, i = {}) {
331
- let a = t(i), o = Date.now(), s = i.mode ?? "main", c = new r({
332
- enabled: !0,
333
- format: "docx",
334
- mode: s,
335
- policy: a.policy,
336
- onMetrics: a.onResourceMetrics,
337
- emitToConsole: a.debug
338
- });
339
- try {
340
- if (s === "worker" && (typeof Worker > "u" || typeof OffscreenCanvas > "u")) throw Error("mode: 'worker' requires Worker and OffscreenCanvas support");
341
- let t;
342
- if (typeof n == "string") {
343
- let e = await fetch(n);
344
- if (!e.ok) throw Error(`Failed to fetch: ${e.status} ${e.statusText}`);
345
- t = await e.arrayBuffer();
346
- } else t = n;
347
- t = h(await _(t, i.password)), c.setSourceBytes(t.byteLength), c.checkpoint("container ready");
348
- let r = s === "worker" ? (await import("./render-worker-host-IuQFpoJM.js")).createRenderWorker() : new We(), l = s === "worker" ? Le(i) : void 0, u;
349
- try {
350
- if (u = new e(r, s, o, i.wasmUrl), u._metrics = c, await u._parse(t, a.policy, s === "worker" ? !!i.useGoogleFonts : !1, i.workerTimeoutMs, (e) => c.observeUsage(e), l), s === "worker" && u._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.")), i.math && u._mode === "worker" && !l?.math && console.warn("[ooxml] a custom math renderer cannot cross the worker boundary; equations will be skipped in mode: 'worker'. Use the math renderer from @silurus/ooxml/math."), i.threeD && u._mode === "worker" && !l?.threeD && console.warn("[ooxml] a custom 3-D chart renderer cannot cross the worker boundary; charts use their 2-D family fallback in mode: 'worker'. Use the renderer from @silurus/ooxml/three-d."), u._threeD = u._mode === "worker" ? void 0 : i.threeD, i.regionMap && u._mode === "worker" && !l?.regionMap && console.warn("[ooxml] a custom Region Map renderer cannot cross the worker boundary; geospatial charts use the unsupported-chart placeholder in mode: 'worker'. Use the renderer from @silurus/ooxml/region-map."), u._regionMap = u._mode === "worker" ? void 0 : i.regionMap, u._mode === "main" && i.useGoogleFonts && u._document && (u._googleFontFaces = await ge(Ne(u._document), De)), u._mode === "main" && u._document?.embeddedFonts?.length) {
351
- let e = u;
352
- u._embeddedFontFaces = await qe(u._document, (t) => e.getFontBytes(t));
353
- }
354
- let n;
355
- u._mode === "main" && u._document && (n = await Ee(u._document), u._localMetricFontFaces = n.faces);
356
- let d;
357
- if (u._mode === "main" && i.math && u._document && Me(u._document) && (d = await Pe(u._document, i.math)), u._mode === "main" && u._document && u._source) {
358
- let e = A(u);
359
- e.services = Ae(u._source, {
360
- localMetrics: n?.metrics,
361
- useGoogleFonts: !!i.useGoogleFonts,
362
- embeddedFaces: u._embeddedFontFaces,
363
- googleFaces: u._googleFontFaces,
364
- mathResources: d?.records,
365
- mathDrawables: d?.drawables
366
- });
367
- let t = e.services;
368
- Ce(u._source, t, e.defaultCurrentDateMs).layoutVariants.defaultLayout;
369
- }
370
- return await u._resourceUsage(i.workerTimeoutMs ?? 1e3).then((e) => c.observeUsage(e), () => void 0), c.checkpoint("model and layout ready"), c.succeed({ pages: u.pageCount }), u;
371
- } catch (e) {
372
- let t = u;
373
- throw g(r, t ? () => t.destroy() : void 0), e;
374
- }
375
- } catch (e) {
376
- throw c.fail(e), e;
377
- }
378
- }
379
- async _parse(e, t, n = !1, r, i, a) {
380
- let o = await this._bridge.request((r) => this._mode === "worker" ? {
381
- type: "parse",
382
- id: r,
383
- data: e,
384
- resourcePolicy: t,
385
- useGoogleFonts: n,
386
- defaultCurrentDateMs: A(this).defaultCurrentDateMs,
387
- renderers: a
388
- } : {
389
- type: "parse",
390
- id: r,
391
- data: e,
392
- resourcePolicy: t
393
- }, [e], { timeoutMs: r });
394
- if ("protocol" in o) throw Error("DOCX parse open returned a pull-protocol response");
395
- if (this._mode === "worker") if ("usage" in o && o.usage && i?.(o.usage), o.type === "mainThreadVerticalFallback") {
396
- let e = await D(this._bridge.transport(O), o, {
397
- timeoutMs: r,
398
- onUsage: i
399
- });
400
- this._source = e.source, this._document = e.document, this._meta = null, this._mode = "main";
401
- } else this._meta = o.meta;
402
- else {
403
- let e = o, t = await D(this._bridge.transport(O), e, {
404
- timeoutMs: r,
405
- onUsage: i
406
- });
407
- this._source = t.source, this._document = t.document;
408
- }
409
- }
410
- destroy() {
411
- this._bridge.terminate(), this._document = null, this._source = null, this._meta = null, A(this).services = null, this._bookmarkPages = null, this._rawParts.clear(), this._embeddedFontFaces.length > 0 && (Ue(this._embeddedFontFaces), this._embeddedFontFaces = []), this._googleFontFaces.length > 0 && (me(this._googleFontFaces), this._googleFontFaces = []), this._localMetricFontFaces.length > 0 && (Fe(this._localMetricFontFaces), this._localMetricFontFaces = []), c(this._fetchImage), n(this._fetchImage);
412
- }
413
- async getImage(e, t) {
414
- return this._rawParts.get(e, t, () => this._bridge.request((t) => ({
415
- type: "extractImage",
416
- id: t,
417
- path: e
418
- })).then((e) => {
419
- let n = e.bytes;
420
- return new Blob([n], { type: t });
421
- }));
422
- }
423
- async getFontBytes(e) {
424
- let t = (await this._bridge.request((t) => ({
425
- type: "extractImage",
426
- id: t,
427
- path: e
428
- }))).bytes;
429
- return new Uint8Array(t);
430
- }
431
- async _resourceUsage(e) {
432
- return (await this._bridge.request((e) => ({
433
- type: "resourceUsage",
434
- id: e
435
- }), void 0, { timeoutMs: e })).usage;
436
- }
437
- async getResourceMetrics() {
438
- let e = this._metrics;
439
- if (!e) throw Error("Document not loaded");
440
- return f(e, (e) => this._resourceUsage(e));
441
- }
442
- async toMarkdown() {
443
- return (await this._bridge.request((e) => ({
444
- type: "toMarkdown",
445
- id: e
446
- }))).markdown;
447
- }
448
- get pageCount() {
449
- return this._meta ? this._meta.pageCount : this._document ? this._getLayout()?.pages.length ?? 0 : 0;
450
- }
451
- get mode() {
452
- return this._mode;
453
- }
454
- get document() {
455
- 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");
456
- if (!this._document) throw Error("Document not loaded");
457
- return this._document;
458
- }
459
- get comments() {
460
- return this._meta?.comments ?? this._document?.comments ?? [];
461
- }
462
- get footnotes() {
463
- return this._meta?.footnotes ?? this._document?.footnotes ?? [];
464
- }
465
- get endnotes() {
466
- return this._meta?.endnotes ?? this._document?.endnotes ?? [];
467
- }
468
- _getLayout() {
469
- if (!this._document) return null;
470
- let e = A(this).services;
471
- if (!e) throw Error("Document layout services are not initialized");
472
- let t = Se(e);
473
- if (!t) throw Error("Document layout variant store is not initialized");
474
- return t.defaultLayout;
475
- }
476
- _getBookmarkPages() {
477
- if (this._bookmarkPages) return this._bookmarkPages;
478
- if (this._meta) return this._bookmarkPages = new Map(this._meta.bookmarkPages), this._bookmarkPages;
479
- let e = this._getLayout();
480
- return e ? (this._bookmarkPages = Ke(e), this._bookmarkPages) : null;
481
- }
482
- getBookmarkPage(e) {
483
- return this._getBookmarkPages()?.get(e);
484
- }
485
- pageSize(e) {
486
- if (this._meta) {
487
- let t = this._meta.pageSizes, n = t[Math.max(0, Math.min(e, t.length - 1))];
488
- return n ? {
489
- widthPt: n.widthPt,
490
- heightPt: n.heightPt
491
- } : {
492
- widthPt: 0,
493
- heightPt: 0
494
- };
495
- }
496
- if (!this._document) return {
497
- widthPt: 0,
498
- heightPt: 0
499
- };
500
- let t = this._getLayout();
501
- if (!t || t.pages.length === 0) return {
502
- widthPt: 0,
503
- heightPt: 0
504
- };
505
- let n = Math.max(0, Math.min(e, t.pages.length - 1)), r = t.pages[n].geometry;
506
- return {
507
- widthPt: r.widthPt,
508
- heightPt: r.heightPt
509
- };
510
- }
511
- renderPage(e, t, n = {}) {
512
- if (this._mode === "worker") throw Error("renderPage(canvas) is unavailable in mode: 'worker'; use renderPageToBitmap() and paint it via an ImageBitmapRenderingContext");
513
- if (!this._source) throw Error("Document not loaded");
514
- return Te(this._source, e, t, {
515
- ...n,
516
- fetchImage: this._fetchImage,
517
- layoutServices: A(this).services ?? void 0,
518
- defaultCurrentDateMs: A(this).defaultCurrentDateMs,
519
- threeD: this._threeD,
520
- regionMap: this._regionMap
521
- });
522
- }
523
- async renderPageToBitmap(e, t = {}) {
524
- let { onTextRun: n, ...r } = t, i = {
525
- ...r,
526
- dpr: r.dpr ?? u()
527
- };
528
- if (this._mode === "worker") {
529
- let t = await this._bridge.request((t) => ({
530
- type: "renderPage",
531
- id: t,
532
- pageIndex: e,
533
- opts: i
534
- }));
535
- if (n) for (let e of t.runs) n(e);
536
- return t.bitmap;
537
- }
538
- let a = new OffscreenCanvas(1, 1);
539
- return await this.renderPage(a, e, {
540
- ...i,
541
- onTextRun: n
542
- }), a.transferToImageBitmap();
543
- }
544
- async collectPageRuns(e, t = {}) {
545
- let n = { ...t };
546
- if (this._mode === "worker") return (await this._bridge.request((t) => ({
547
- type: "collectRuns",
548
- id: t,
549
- pageIndex: e,
550
- opts: n
551
- }))).runs;
552
- let r = A(this), i = r.services;
553
- if (!i) throw Error("Document layout services are not initialized");
554
- return ke(i, e, {
555
- currentDate: n.currentDate,
556
- defaultCurrentDateMs: r.defaultCurrentDateMs,
557
- width: n.width
558
- });
559
- }
560
- async getElementContextAt(e, t, n = {}) {
561
- if (this._mode === "worker") return (await this._bridge.request((r) => ({
562
- type: "hitTestElement",
563
- id: r,
564
- pageIndex: e,
565
- point: t,
566
- opts: n
567
- }))).context;
568
- let r = A(this), i = r.services;
569
- if (!i) throw Error("Document layout services are not initialized");
570
- return ct(i, e, t, {
571
- ...n,
572
- defaultCurrentDateMs: r.defaultCurrentDateMs
573
- });
574
- }
575
- };
576
- //#endregion
577
- //#region packages/docx/src/tate-chu-yoko-overlay.ts
578
- function W(e, t) {
579
- if (!e.eastAsianVert) return 1;
580
- let n = t(e.text);
581
- return !(n > 0) || e.w >= n ? 1 : e.w / n;
582
- }
583
- //#endregion
584
- //#region packages/docx/src/text-layer.ts
585
- function G(e, t, n) {
586
- e.dataset ? n === void 0 ? delete e.dataset[t] : e.dataset[t] = n : n !== void 0 && e.setAttribute?.(`data-${t.replace(/[A-Z]/g, (e) => `-${e.toLowerCase()}`)}`, n);
587
- }
588
- function K(e, t, n, r, i, a, o) {
589
- e.innerHTML = "", G(e, "ooxmlSelectionSurface", "docx"), G(e, "pageIndex", o === void 0 ? void 0 : String(o));
590
- let s = e.ownerDocument ?? document;
591
- for (let [o, c] of t.entries()) {
592
- let t = s.createElement("span");
593
- G(t, "ooxmlSelectionRun", "docx"), G(t, "runIndex", String(o)), c.paragraphId !== void 0 && G(t, "paragraphId", c.paragraphId), c.source !== void 0 && (G(t, "sourceStory", c.source.story), G(t, "sourceStoryInstance", c.source.storyInstance), G(t, "sourcePath", JSON.stringify(c.source.path))), t.textContent = c.text;
594
- let l = c.transform ?? "";
595
- if (a && c.eastAsianVert) {
596
- let e = W(c, a(c.font));
597
- e !== 1 && (l = `${l ? `${l} ` : ""}scaleX(${e})`);
598
- }
599
- let u = l ? `transform:${l};transform-origin:top left;` : "", d = i ? c.hyperlink : void 0, f = d ? "pointer" : "text", p = c.letterSpacingPx === void 0 ? "0" : `${c.letterSpacingPx}px`;
600
- t.style.cssText = `position:absolute;left:${N(c.x, n)};top:${N(c.y, r)};font:${c.font};line-height:${c.h}px;letter-spacing:${p};` + u + `white-space:pre;color:transparent;cursor:${f};pointer-events:all;`, d && i && (t.title = d.kind === "external" ? d.url : d.ref, t.addEventListener("click", (e) => {
601
- e.preventDefault(), i(d);
602
- })), e.appendChild(t);
603
- }
604
- }
605
- function q(e, t, n, r, i, a, o = {}) {
606
- e.innerHTML = "";
607
- let s = o.match ?? "rgba(255, 214, 0, 0.42)", c = o.active ?? "rgba(255, 140, 0, 0.55)";
608
- for (let o of n) {
609
- let n = o.active ? c : s;
610
- for (let s of o.slices) {
611
- let o = t[s.runIndex];
612
- if (!o) continue;
613
- let c = a(o.font), l = Re(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, _ = W(o, c), v = h * _, y = g * _;
614
- if (y <= 0) continue;
615
- let b = document.createElement("div"), x = o.transform ? `transform:${o.transform};transform-origin:top left;` : "";
616
- b.style.cssText = `position:absolute;left:${N(o.x + v, r)};top:${N(o.y, i)};width:${N(y, r)};height:${N(o.h, i)};` + x + `background:${n};pointer-events:none;`, e.appendChild(b);
617
- }
618
- }
619
- }
620
- //#endregion
621
- //#region packages/docx/src/find.ts
622
- var J = class {
623
- _pageRuns = /* @__PURE__ */ new Map();
624
- _matches = [];
625
- _active = -1;
626
- _generation = 0;
627
- _runsRevision = 0;
628
- constructor(e, t) {
629
- this._pageCount = e, this._collectPageRuns = t;
630
- }
631
- invalidate() {
632
- this._generation++, this._runsRevision++, this._pageRuns.clear(), this._matches = [], this._active = -1;
633
- }
634
- pageRuns(e) {
635
- return this._pageRuns.get(e);
636
- }
637
- setPageRuns(e, t) {
638
- this._runsRevision++, this._pageRuns.set(e, t);
639
- }
640
- _matchAt(e) {
641
- return this._matches[e];
642
- }
643
- pageHighlights(e) {
644
- let t = [];
645
- for (let n = 0; n < this._matches.length; n++) {
646
- let r = this._matches[n];
647
- r.page === e && t.push({
648
- slices: r.slices,
649
- active: n === this._active
650
- });
651
- }
652
- return t;
653
- }
654
- activePage() {
655
- let e = this._matchAt(this._active);
656
- return e ? e.page : null;
657
- }
658
- matches() {
659
- return this._matches.map((e, t) => ({
660
- matchIndex: t,
661
- text: e.text,
662
- location: { page: e.page }
663
- }));
664
- }
665
- async find(e, t = {}) {
666
- let n = ++this._generation;
667
- if (e.length === 0) return this._runsRevision++, this._pageRuns.clear(), this._matches = [], this._active = -1, [];
668
- let r = this._runsRevision, i = new Map(this._pageRuns), a = this._pageCount();
669
- for (let e = 0; e < a; e++) {
670
- let t = i.get(e);
671
- if (!t) {
672
- try {
673
- t = await this._collectPageRuns(e);
674
- } catch (e) {
675
- if (n !== this._generation) return [];
676
- throw e;
677
- }
678
- if (n !== this._generation) return [];
679
- i.set(e, t);
680
- }
681
- }
682
- if (n !== this._generation) return [];
683
- let o = r === this._runsRevision ? i : new Map([...i, ...this._pageRuns]), s = [];
684
- for (let n = 0; n < a; n++) {
685
- let r = o.get(n) ?? [], i = ie(r);
686
- for (let a of re(i, e, t)) {
687
- let e = a.slices.map((e) => r[e.runIndex].text.slice(e.start, e.end)).join("");
688
- s.push({
689
- page: n,
690
- text: e,
691
- slices: a.slices
692
- });
693
- }
694
- }
695
- return this._runsRevision++, this._pageRuns = o, this._matches = s, this._active = -1, this.matches();
696
- }
697
- next() {
698
- return this._active = te(this._active, this._matches.length), this._activePublic();
699
- }
700
- prev() {
701
- return this._active = se(this._active, this._matches.length), this._activePublic();
702
- }
703
- _activePublic() {
704
- let e = this._matchAt(this._active);
705
- return e ? {
706
- matchIndex: this._active,
707
- text: e.text,
708
- location: { page: e.page }
709
- } : null;
710
- }
711
- };
712
- //#endregion
713
- //#region packages/docx/src/selection-context.ts
714
- function Y(e) {
715
- if (e === void 0 || !/^\d+$/.test(e)) return null;
716
- let t = Number(e);
717
- return Number.isSafeInteger(t) ? t : null;
718
- }
719
- function lt(e) {
720
- for (let t = e; t; t = t.parentElement) {
721
- let e = Y(t.dataset.pageIndex);
722
- if (e !== null) return e;
723
- }
724
- return null;
725
- }
726
- var ut = new Set([
727
- "body",
728
- "header",
729
- "footer",
730
- "footnote",
731
- "endnote",
732
- "textbox"
733
- ]);
734
- function X(e) {
735
- let t = e.dataset.sourceStory, n = e.dataset.sourceStoryInstance, r = e.dataset.sourcePath;
736
- if (!t || !ut.has(t) || !n || !r) return null;
737
- try {
738
- let e = JSON.parse(r);
739
- return !Array.isArray(e) || e.length === 0 || e.length > 32 || !e.every((e) => Number.isSafeInteger(e) && e >= 0) ? null : {
740
- story: t,
741
- storyInstance: n,
742
- path: [...e]
743
- };
744
- } catch {
745
- return null;
746
- }
747
- }
748
- function Z(e, t, n = {}) {
749
- let r = le(e, t, (e) => {
750
- let t = lt(e), n = Y(e.dataset.runIndex);
751
- return t === null || n === null ? null : {
752
- pageIndex: t,
753
- runIndex: n,
754
- ...e.dataset.paragraphId === void 0 ? {} : { paragraphId: e.dataset.paragraphId },
755
- ...X(e) === null ? {} : { source: X(e) }
756
- };
757
- }, {
758
- maxChars: n.maxTextCharacters,
759
- maxLocators: n.maxRunLocators
760
- });
761
- if (!r) return null;
762
- let i = [...r.locators].sort((e, t) => e.pageIndex - t.pageIndex || e.runIndex - t.runIndex);
763
- return {
764
- format: "docx",
765
- kind: "text",
766
- text: r.text,
767
- pageIndexes: [...new Set(i.map((e) => e.pageIndex))],
768
- paragraphIds: [...new Set(i.flatMap((e) => e.paragraphId ? [e.paragraphId] : []))],
769
- runs: i,
770
- truncated: r.truncated,
771
- truncationReasons: r.truncationReasons,
772
- textCharacters: r.textCharacters,
773
- maxTextCharacters: r.maxTextCharacters,
774
- maxRunLocators: r.maxLocators
775
- };
776
- }
777
- //#endregion
778
- //#region packages/docx/src/viewer.ts
779
- var Q = Symbol("DocxViewer.borrowedDocument"), dt = class e {
780
- _documentOwner;
781
- get _doc() {
782
- return this._documentOwner.current;
783
- }
784
- _borrowed;
785
- _hostWindow;
786
- _currentPage = 0;
787
- _scale = null;
788
- _canvas;
789
- _wrapper;
790
- _canvasMount;
791
- _textLayer = null;
792
- _highlightLayer = null;
793
- _elementLayer = null;
794
- _find;
795
- _measureCtx = null;
796
- _opts;
797
- _mode;
798
- _renderDispatcher;
799
- _errorRouter;
800
- _destroyed = !1;
801
- _selectionChangeListener = null;
802
- _selectionContextKey = "null";
803
- _elementContext = null;
804
- _elementHitGeneration = 0;
805
- _elementClickListener = null;
806
- _contextMenuListener = null;
807
- static fromDocument(t, n, r = {}) {
808
- return new e(t, {
809
- ...r,
810
- [Q]: n
811
- });
812
- }
813
- constructor(e, t = {}) {
814
- this._canvas = e, this._opts = t;
815
- let n = t[Q];
816
- this._borrowed = n !== void 0, this._mode = C("DocxViewer", t.mode, n), this._documentOwner = new y("DocxViewer", n ?? null, !1);
817
- let r = e.ownerDocument?.defaultView ?? (typeof window < "u" ? window : null);
818
- if (!r) throw Error("DocxViewer requires a canvas with an active Window");
819
- this._hostWindow = r, this._canvasMount = new ue(e, {
820
- wrapperCssText: "position:relative;display:inline-block;vertical-align:top;",
821
- forceDisplayBlock: !0
822
- }), this._wrapper = this._canvasMount.wrapper, this._renderDispatcher = new S(e, this._mode === "worker"), this._errorRouter = new ce("DocxViewer", t.onError);
823
- let i = new ae(this._wrapper, t.enableTextSelection === !0, t.enableElementSelection === !0);
824
- this._textLayer = i.textLayer, this._highlightLayer = i.highlightLayer, this._elementLayer = i.elementLayer, this._textLayer && (t.onSelectionContextChange || t.enableElementSelection) && (this._selectionChangeListener = () => this._emitSelectionContextChange(), this._wrapper.ownerDocument.addEventListener("selectionchange", this._selectionChangeListener)), t.enableElementSelection && (this._elementClickListener = (e) => {
825
- this._onElementClick(e).catch((e) => this._reportRenderError(e));
826
- }, this._wrapper.addEventListener("click", this._elementClickListener)), t.onContextMenu && (this._contextMenuListener = (e) => this._onContextMenu(e), this._wrapper.addEventListener("contextmenu", this._contextMenuListener)), this._find = new J(() => this.pageCount, (e) => this._collectPageRuns(e));
827
- }
828
- async load(e) {
829
- if (this._destroyed) throw Error("DocxViewer is destroyed");
830
- if (this._borrowed) throw Error("DocxViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.");
831
- let t = !1;
832
- try {
833
- if (!await this._documentOwner.replace(() => U.load(e, {
834
- password: this._opts.password,
835
- useGoogleFonts: this._opts.useGoogleFonts,
836
- maxZipEntryBytes: this._opts.maxZipEntryBytes,
837
- resourceLimits: this._opts.resourceLimits,
838
- debug: this._opts.debug,
839
- onResourceMetrics: this._opts.onResourceMetrics,
840
- workerTimeoutMs: this._opts.workerTimeoutMs,
841
- wasmUrl: this._opts.wasmUrl,
842
- math: this._opts.math,
843
- threeD: this._opts.threeD,
844
- regionMap: this._opts.regionMap,
845
- mode: this._mode
846
- }), () => {
847
- this._invalidateElementContext(!1), t = !0, this._renderDispatcher.begin(), this._find.invalidate();
848
- })) return;
849
- if (this._destroyed) throw Error("DocxViewer is destroyed");
850
- this._currentPage = 0, this._find.invalidate(), await this._render();
851
- } catch (e) {
852
- throw this._destroyed ? Error("DocxViewer is destroyed") : e instanceof Error ? e : Error(String(e));
853
- }
854
- t && !this._destroyed && this._emitSelectionContextChange();
855
- }
856
- get pageCount() {
857
- return this._doc?.pageCount ?? 0;
858
- }
859
- get currentPage() {
860
- return this._currentPage;
861
- }
862
- get canvasElement() {
863
- return this._canvas;
864
- }
865
- async goToPage(e) {
866
- if (!this._doc) return;
867
- let t = Math.max(0, Math.min(e, this.pageCount - 1)), n = t !== this._currentPage;
868
- n && this._invalidateElementContext(!1), this._currentPage = t, await this._render(), n && !this._destroyed && this._emitSelectionContextChange();
869
- }
870
- async nextPage() {
871
- await this.goToPage(this._currentPage + 1);
872
- }
873
- async prevPage() {
874
- await this.goToPage(this._currentPage - 1);
875
- }
876
- _naturalWidthPx() {
877
- return !this._doc || this._doc.pageCount === 0 ? 0 : this._doc.pageSize(this._currentPage).widthPt * j;
878
- }
879
- _renderWidth() {
880
- if (this._scale === null) return this._opts.width;
881
- let e = this._naturalWidthPx();
882
- return e <= 0 ? this._opts.width : Math.round(e * this._scale);
883
- }
884
- getScale() {
885
- if (this._scale !== null) return this._scale;
886
- let e = this._naturalWidthPx();
887
- return e <= 0 ? 1 : this._opts.width && this._opts.width > 0 ? this._opts.width / e : 1;
888
- }
889
- _zoomMin() {
890
- return this._opts.zoomMin ?? .1;
891
- }
892
- _zoomMax() {
893
- return this._opts.zoomMax ?? 4;
894
- }
895
- async setScale(e) {
896
- let t = ne(e, this._zoomMin(), this._zoomMax()), n = t !== this.getScale();
897
- this._scale = t, await this._render(), n && this._opts.onScaleChange?.(t);
898
- }
899
- async zoomIn() {
900
- await this.setScale(w(this.getScale()));
901
- }
902
- async zoomOut() {
903
- await this.setScale(T(this.getScale()));
904
- }
905
- async fitWidth() {
906
- await this._fit("width");
907
- }
908
- async fitPage() {
909
- await this._fit("page");
910
- }
911
- async _fit(e) {
912
- if (!this._doc || this._doc.pageCount === 0) return;
913
- let t = this._doc.pageSize(this._currentPage), n = this._fitContainer();
914
- if (!n) return;
915
- let r = v({
916
- contentWidth: t.widthPt * j,
917
- contentHeight: t.heightPt * j,
918
- containerWidth: n.clientWidth,
919
- containerHeight: n.clientHeight
920
- }, e);
921
- r <= 0 || await this.setScale(r);
922
- }
923
- _fitContainer() {
924
- return this._opts.container ?? this._wrapper.parentElement ?? null;
925
- }
926
- async findText(e, t = {}) {
927
- if (!this._doc) return [];
928
- let n = await this._find.find(e, t);
929
- return this._redrawHighlights(), n;
930
- }
931
- async findNext() {
932
- return this._activateMatch(this._find.next());
933
- }
934
- async findPrev() {
935
- return this._activateMatch(this._find.prev());
936
- }
937
- clearFind() {
938
- this._find.invalidate(), this._redrawHighlights();
939
- }
940
- async _activateMatch(e) {
941
- return e ? (e.location.page === this._currentPage ? this._redrawHighlights() : await this.goToPage(e.location.page), e) : (this._redrawHighlights(), null);
942
- }
943
- _redrawHighlights() {
944
- let e = this._find.pageRuns(this._currentPage) ?? [];
945
- this._buildHighlightLayer(e);
946
- }
947
- async getResourceMetrics() {
948
- if (!this._doc) throw Error("Document not loaded");
949
- return await this._doc.getResourceMetrics();
950
- }
951
- getSelectionContext(e = {}) {
952
- if (this._destroyed) throw Error("DocxViewer is destroyed");
953
- return (this._textLayer ? Z(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null, e) : null) ?? (this._elementContext ? H(this._elementContext, e.maxTextCharacters) : null);
954
- }
955
- _emitSelectionContextChange() {
956
- let e = this.getSelectionContext();
957
- e?.kind === "text" && (this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutline());
958
- let t = JSON.stringify(e);
959
- t !== this._selectionContextKey && (this._selectionContextKey = t, this._opts.onSelectionContextChange?.(e ? structuredClone(e) : null));
960
- }
961
- _setElementContext(e) {
962
- this._elementContext = e ? structuredClone(e) : null, this._redrawElementOutline(), this._emitSelectionContextChange();
963
- }
964
- _invalidateElementContext(e = !0) {
965
- this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutline(), e && this._emitSelectionContextChange();
966
- }
967
- _redrawElementOutline() {
968
- let e = this._elementContext, t = this._doc;
969
- if (!e || !t || e.pageIndex !== this._currentPage) {
970
- x(this._elementLayer, null);
971
- return;
972
- }
973
- let n = t.pageSize(e.pageIndex);
974
- x(this._elementLayer, {
975
- x: e.bounds.xPt / n.widthPt,
976
- y: e.bounds.yPt / n.heightPt,
977
- width: e.bounds.widthPt / n.widthPt,
978
- height: e.bounds.heightPt / n.heightPt
979
- });
980
- }
981
- async _onElementClick(e) {
982
- this._destroyed || e.defaultPrevented || e.button !== 0 || await this._resolveContextAt(e);
983
- }
984
- _onContextMenu(e) {
985
- let t;
986
- this._opts.onContextMenu?.({
987
- originalEvent: e,
988
- getContext: () => t ??= this._resolveContextAt(e)
989
- });
990
- }
991
- async _resolveContextAt(e) {
992
- let t = this._doc;
993
- if (this._destroyed || !t) return null;
994
- if (this._textLayer && Z(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null)) return this._emitSelectionContextChange(), this._destroyed ? null : this.getSelectionContext();
995
- if (!this._opts.enableElementSelection) return this.getSelectionContext();
996
- let n = this._canvas.getBoundingClientRect();
997
- if (n.width <= 0 || n.height <= 0) return this._invalidateElementContext(), null;
998
- let r = e.clientX - n.left, i = e.clientY - n.top;
999
- if (r < 0 || i < 0 || r > n.width || i > n.height) return this._invalidateElementContext(), null;
1000
- let a = ++this._elementHitGeneration, o = this._currentPage, s = t.pageSize(o), c;
1001
- try {
1002
- c = await t.getElementContextAt(o, {
1003
- xPt: r / n.width * s.widthPt,
1004
- yPt: i / n.height * s.heightPt
1005
- }, {
1006
- currentDate: this._opts.currentDate,
1007
- maxTextCharacters: I
1008
- });
1009
- } catch (e) {
1010
- if (this._destroyed || a !== this._elementHitGeneration || o !== this._currentPage || t !== this._doc) return null;
1011
- throw e;
1012
- }
1013
- return this._destroyed || a !== this._elementHitGeneration || o !== this._currentPage || t !== this._doc ? null : (this._setElementContext(c), this._destroyed ? null : this.getSelectionContext());
1014
- }
1015
- destroy() {
1016
- this._destroyed || (this._destroyed = !0, this._errorRouter.close(), this._renderDispatcher.destroy(), je(this._canvas), this._documentOwner.close(), this._find.invalidate(), this._selectionChangeListener &&= (this._wrapper.ownerDocument.removeEventListener("selectionchange", this._selectionChangeListener), null), this._elementHitGeneration++, this._elementClickListener &&= (this._wrapper.removeEventListener("click", this._elementClickListener), null), this._contextMenuListener &&= (this._wrapper.removeEventListener("contextmenu", this._contextMenuListener), null), this._elementContext = null, this._canvasMount.restore());
1017
- }
1018
- async _render() {
1019
- let e = this._renderDispatcher.begin();
1020
- try {
1021
- await this._renderPage(e);
1022
- } catch (t) {
1023
- if (!this._renderDispatcher.isCurrent(e)) return;
1024
- throw t;
1025
- }
1026
- }
1027
- _reportRenderError(e) {
1028
- this._errorRouter.report(e);
1029
- }
1030
- async _renderPage(e) {
1031
- if (!this._doc) return;
1032
- let t = this._mode === "worker", n = this._renderWidth(), r = [], i = (e) => r.push(e);
1033
- if (t) {
1034
- let t = this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1), r = await this._doc.renderPageToBitmap(this._currentPage, {
1035
- width: n,
1036
- dpr: this._opts.dpr,
1037
- defaultTextColor: this._opts.defaultTextColor,
1038
- currentDate: this._opts.currentDate,
1039
- onTextRun: i
1040
- });
1041
- if (!this._renderDispatcher.commitBitmap(e, r, {
1042
- cssWidth: Math.round(r.width / t),
1043
- cssHeight: Math.round(r.height / t)
1044
- })) return;
1045
- } else if (await this._doc.renderPage(this._canvas, this._currentPage, {
1046
- ...this._opts,
1047
- width: n,
1048
- onTextRun: i
1049
- }), !this._renderDispatcher.isCurrent(e)) return;
1050
- this._textLayer && this._buildTextLayer(this._textLayer, r), this._find.setPageRuns(this._currentPage, r), this._buildHighlightLayer(r), this._opts.onPageChange?.(this._currentPage, this.pageCount);
1051
- }
1052
- _buildHighlightLayer(e) {
1053
- let t = this._highlightLayer;
1054
- if (!t) return;
1055
- let { width: n, height: r } = this._canvasCssPx();
1056
- q(t, e, this._find.pageHighlights(this._currentPage), n, r, (e) => this._measureForFont(e), this._opts.findHighlightColors);
1057
- }
1058
- _canvasCssPx() {
1059
- return {
1060
- width: parseFloat(this._canvas.style.width) || this._canvas.width,
1061
- height: parseFloat(this._canvas.style.height) || this._canvas.height
1062
- };
1063
- }
1064
- _measureForFont(e) {
1065
- this._measureCtx ||= document.createElement("canvas").getContext("2d");
1066
- let t = this._measureCtx;
1067
- return t ? (t.font = e, (e) => t.measureText(e).width) : (e) => e.length;
1068
- }
1069
- async _collectPageRuns(e) {
1070
- return this._doc ? this._doc.collectPageRuns(e, {
1071
- width: this._renderWidth(),
1072
- currentDate: this._opts.currentDate
1073
- }) : [];
1074
- }
1075
- _buildTextLayer(e, t) {
1076
- let { width: n, height: r } = this._canvasCssPx();
1077
- K(e, t, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), this._currentPage);
1078
- }
1079
- _hyperlinkHandler() {
1080
- return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
1081
- if (e.kind === "external") {
1082
- a(e.url, void 0, this._hostWindow);
1083
- return;
1084
- }
1085
- let t = this._doc?.getBookmarkPage(e.ref);
1086
- t !== void 0 && this.goToPage(t).catch((e) => this._reportRenderError(e));
1087
- });
1088
- }
1089
- }, ft = 150, pt = "0 1px 3px rgba(0,0,0,0.2)", mt = Symbol("DocxScrollViewer.borrowedDocument"), ht = class e {
1090
- _documentOwner;
1091
- get _doc() {
1092
- return this._documentOwner.current;
1093
- }
1094
- _borrowed;
1095
- _opts;
1096
- _container;
1097
- _wrapper;
1098
- _scrollHost;
1099
- _spacer;
1100
- _mode;
1101
- _scale = 1;
1102
- _scaleEstablished = !1;
1103
- _pendingScale = null;
1104
- _slots = /* @__PURE__ */ new Map();
1105
- _free = [];
1106
- _heights = [];
1107
- _lastRange = null;
1108
- _lastTopIndex = -1;
1109
- _scrollListener = null;
1110
- _selectionChangeListener = null;
1111
- _selectionContextKey = "null";
1112
- _elementClickListener = null;
1113
- _contextMenuListener = null;
1114
- _elementContext = null;
1115
- _elementHitGeneration = 0;
1116
- _destroyed = !1;
1117
- _measureCtx;
1118
- _bitmapInFlight = /* @__PURE__ */ new Set();
1119
- _renderEpoch = 0;
1120
- _settleTimer = null;
1121
- _wheelListener = null;
1122
- _pendingZoomAnchor = null;
1123
- _resizeObserver = null;
1124
- _prevBase = 0;
1125
- _lastFitWidth = 0;
1126
- _pageShadow;
1127
- _find = new J(() => this.pageCount, (e) => this._collectPageRuns(e));
1128
- _findActive = !1;
1129
- static fromDocument(t, n, r = {}) {
1130
- return new e(t, {
1131
- ...r,
1132
- [mt]: n
1133
- });
1134
- }
1135
- constructor(e, t = {}) {
1136
- 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.");
1137
- this._container = e, this._opts = t, this._pageShadow = t.pageShadow ?? pt;
1138
- let n = t[mt];
1139
- this._borrowed = n !== void 0, n ? (this._documentOwner = new y("DocxScrollViewer", n, !1), this._mode = C("DocxScrollViewer", t.mode, n)) : (this._documentOwner = new y("DocxScrollViewer"), this._mode = C("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), t.enableTextSelection && (t.onSelectionContextChange || t.enableElementSelection) && (this._selectionChangeListener = () => this._emitSelectionContextChange(), this._wrapper.ownerDocument.addEventListener("selectionchange", this._selectionChangeListener)), t.enableElementSelection && (this._elementClickListener = (e) => {
1140
- this._onElementClick(e).catch((e) => this._reportRenderError(e));
1141
- }, this._scrollHost.addEventListener("click", this._elementClickListener)), t.onContextMenu && (this._contextMenuListener = (e) => this._onContextMenu(e), this._scrollHost.addEventListener("contextmenu", this._contextMenuListener)), this._scrollListener = () => this._onScroll(), this._scrollHost.addEventListener("scroll", this._scrollListener), this._opts.enableZoom !== !1 && (this._wheelListener = (e) => {
1142
- if (!(e.ctrlKey || e.metaKey) || (e.preventDefault(), e.deltaY === 0)) return;
1143
- let t = this._scrollHost.getBoundingClientRect(), n = e.clientX - t.left, r = e.clientY - t.top;
1144
- this._pendingZoomAnchor = Number.isFinite(n) && Number.isFinite(r) ? {
1145
- x: n,
1146
- y: r
1147
- } : null, this.setScale(pe(this._scale, e.deltaY));
1148
- }, 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();
1149
- }
1150
- async load(e) {
1151
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
1152
- if (this._borrowed) throw Error("DocxScrollViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.");
1153
- let t = !1;
1154
- try {
1155
- if (!await this._documentOwner.replace(() => U.load(e, {
1156
- password: this._opts.password,
1157
- useGoogleFonts: this._opts.useGoogleFonts,
1158
- maxZipEntryBytes: this._opts.maxZipEntryBytes,
1159
- resourceLimits: this._opts.resourceLimits,
1160
- debug: this._opts.debug,
1161
- onResourceMetrics: this._opts.onResourceMetrics,
1162
- workerTimeoutMs: this._opts.workerTimeoutMs,
1163
- wasmUrl: this._opts.wasmUrl,
1164
- math: this._opts.math,
1165
- threeD: this._opts.threeD,
1166
- regionMap: this._opts.regionMap,
1167
- mode: this._mode
1168
- }), (e) => {
1169
- if (this._invalidateElementContext(!1), t = !0, this._find.invalidate(), this._findActive = !1, e) {
1170
- for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
1171
- this._lastTopIndex = -1;
1172
- }
1173
- })) return;
1174
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
1175
- this._find.invalidate(), this._findActive = !1;
1176
- let n = [];
1177
- this._relayout(n), await Promise.all(n);
1178
- } catch (e) {
1179
- throw this._destroyed ? Error("DocxScrollViewer is destroyed") : e instanceof Error ? e : Error(String(e));
1180
- }
1181
- t && !this._destroyed && this._emitSelectionContextChange();
1182
- }
1183
- get pageCount() {
1184
- return this._doc?.pageCount ?? 0;
1185
- }
1186
- _pageWidthPx(e) {
1187
- return this._doc.pageSize(e).widthPt * j * this._scale;
1188
- }
1189
- _pageHeightPx(e) {
1190
- return this._doc.pageSize(e).heightPt * j * this._scale;
1191
- }
1192
- _fitWidthPx() {
1193
- if (this._opts.width && this._opts.width > 0) return this._opts.width;
1194
- let e = this._scrollHost.clientWidth || this._container.clientWidth;
1195
- if (e <= 0) return 0;
1196
- let { left: t, right: n } = this._padH(), r = e - t - n;
1197
- return r > 0 ? r : 0;
1198
- }
1199
- _baseScale() {
1200
- if (!this._doc || this._doc.pageCount === 0) return 0;
1201
- let e = this._fitWidthPx();
1202
- if (e <= 0) return 0;
1203
- let t = this._doc.pageSize(0).widthPt;
1204
- return t <= 0 ? 0 : e / (t * j);
1205
- }
1206
- relayout() {
1207
- this._relayout();
1208
- }
1209
- _relayout(e) {
1210
- if (this._doc) {
1211
- if (!this._scaleEstablished) {
1212
- let e = this._baseScale();
1213
- if (e > 0) {
1214
- if (this._scale = e, this._prevBase = e, this._lastFitWidth = this._fitWidthPx(), this._scaleEstablished = !0, this._pendingScale !== null) {
1215
- let e = this._pendingScale;
1216
- this._pendingScale = null, e !== this._scale && (this._scale = e, this._opts.onScaleChange?.(e));
1217
- }
1218
- } else return;
1219
- }
1220
- this._recomputeHeights(), this._syncSpacer(), this._mountVisible(e);
1221
- }
1222
- }
1223
- _recomputeHeights() {
1224
- let e = this._doc.pageCount, t = Array(e);
1225
- for (let n = 0; n < e; n++) t[n] = this._pageHeightPx(n);
1226
- this._heights = t;
1227
- }
1228
- _gap() {
1229
- return this._opts.gap ?? 16;
1230
- }
1231
- _overscan() {
1232
- return this._opts.overscan ?? 1;
1233
- }
1234
- _pad() {
1235
- let e = this._gap();
1236
- return {
1237
- leading: this._opts.paddingTop ?? e,
1238
- trailing: this._opts.paddingBottom ?? e
1239
- };
1240
- }
1241
- _padH() {
1242
- let e = this._gap();
1243
- return {
1244
- left: this._opts.paddingLeft ?? e,
1245
- right: this._opts.paddingRight ?? e
1246
- };
1247
- }
1248
- _pageIndexAtOffset(e, t) {
1249
- let { offsets: n } = e, r = 0, i = n.length - 1, a = 0;
1250
- for (; r <= i;) {
1251
- let e = r + i >> 1;
1252
- n[e] <= t ? (a = e, r = e + 1) : i = e - 1;
1253
- }
1254
- return a;
1255
- }
1256
- _range() {
1257
- return M(this._heights, this._gap(), this._scrollHost.scrollTop, this._scrollHost.clientHeight, this._overscan(), this._pad());
1258
- }
1259
- _syncSpacer() {
1260
- let e = this._range();
1261
- this._lastRange = e, this._spacer.style.height = `${e.totalHeight}px`, this._syncSpacerWidth();
1262
- }
1263
- _syncSpacerWidth() {
1264
- let { left: e, right: t } = this._padH(), n = 0;
1265
- for (let e = 0; e < this._heights.length; e++) {
1266
- let t = this._pageWidthPx(e);
1267
- t > n && (n = t);
1268
- }
1269
- this._spacer.style.width = `${n + e + t}px`;
1270
- }
1271
- _onScroll() {
1272
- !this._doc || !this._scaleEstablished || this._mountVisible();
1273
- }
1274
- _mountVisible(e) {
1275
- if (!this._doc || this._doc.pageCount === 0) return;
1276
- let t = this._range();
1277
- this._lastRange = t;
1278
- for (let [e, n] of [...this._slots]) (e < t.start || e > t.end) && this._recycleSlot(e, n);
1279
- for (let n = t.start; n <= t.end; n++) if (this._slots.has(n)) this._positionSlot(this._slots.get(n), n, t);
1280
- else {
1281
- let r = this._acquireSlot();
1282
- this._positionSlot(r, n, t), this._slots.set(n, r);
1283
- let i = this._renderSlot(n, r, e === void 0);
1284
- e && i && e.push(i);
1285
- }
1286
- t.topIndex !== this._lastTopIndex && (this._lastTopIndex = t.topIndex, this._opts.onVisiblePageChange?.(t.topIndex, this._doc.pageCount));
1287
- }
1288
- _applyPageShadow(e) {
1289
- this._pageShadow !== !1 && (e.style.boxShadow = this._pageShadow);
1290
- }
1291
- _acquireSlot() {
1292
- let e = this._free.pop();
1293
- if (e) return this._scrollHost.appendChild(e.wrapper), e;
1294
- let t = document.createElement("div");
1295
- t.style.cssText = "position:absolute;";
1296
- let n = document.createElement("canvas");
1297
- n.style.cssText = "display:block;background:#fff;", this._applyPageShadow(n), t.appendChild(n);
1298
- let r = null;
1299
- 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));
1300
- let i = document.createElement("div");
1301
- i.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;", t.appendChild(i);
1302
- let a = oe(t, this._opts.enableElementSelection === !0);
1303
- return this._scrollHost.appendChild(t), {
1304
- wrapper: t,
1305
- canvas: n,
1306
- textLayer: r,
1307
- highlightLayer: i,
1308
- elementLayer: a,
1309
- renderedPage: -1,
1310
- renderedScale: -1,
1311
- dispatcher: new S(n, this._mode === "worker")
1312
- };
1313
- }
1314
- _recycleSlot(e, t) {
1315
- 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 = "", x(t.elementLayer, null), t.renderedPage = -1, t.renderedScale = -1, t.wrapper.remove(), this._free.push(t);
1316
- }
1317
- _positionSlot(e, t, n) {
1318
- e.wrapper.style.top = `${n.offsets[t]}px`;
1319
- let r = this._pageWidthPx(t), i = this._pageHeightPx(t);
1320
- e.wrapper.style.width = `${r}px`, e.wrapper.style.height = `${i}px`, this._redrawElementOutlineForSlot(t, e);
1321
- let { left: a } = this._padH(), o = this._scrollHost.clientWidth;
1322
- e.wrapper.style.left = `${Math.max(a, (o - r) / 2)}px`;
1323
- }
1324
- _dpr() {
1325
- return this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1);
1326
- }
1327
- _renderSlot(e, t, n = !0) {
1328
- if (!this._doc || t.renderedPage === e) return null;
1329
- t.renderedPage = e;
1330
- let r = this._dpr(), i = this._pageWidthPx(e), a = this._renderEpoch, o = this._scale, s = t.dispatcher, c = s.begin();
1331
- if (this._mode === "worker") return this._renderSlotBitmap(e, t, i, r, o, s, c, n);
1332
- let l = [], u = !!this._opts.enableTextSelection && !!t.textLayer, d = u || this._findActive, f = d ? (e) => l.push(e) : void 0, p;
1333
- try {
1334
- p = this._doc.renderPage(t.canvas, e, {
1335
- width: i,
1336
- dpr: r,
1337
- defaultTextColor: this._opts.defaultTextColor,
1338
- currentDate: this._opts.currentDate,
1339
- onTextRun: f
1340
- });
1341
- } catch (e) {
1342
- return n ? (this._reportRenderError(e), Promise.resolve()) : Promise.reject(e);
1343
- }
1344
- return p.then(() => {
1345
- if (!(!s.isCurrent(c) || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e)) {
1346
- if (t.renderedScale = o, u && t.textLayer) {
1347
- let { width: n, height: r } = this._canvasCssPx(t.canvas);
1348
- K(t.textLayer, l, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
1349
- }
1350
- d && this._refreshFindRuns(e, l), this._redrawSlotHighlights(e, t);
1351
- }
1352
- }).catch((r) => {
1353
- if (s.isCurrent(c) && a === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e) if (n) this._reportRenderError(r);
1354
- else throw r;
1355
- });
1356
- }
1357
- _hyperlinkHandler() {
1358
- return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
1359
- if (e.kind === "external") {
1360
- a(e.url);
1361
- return;
1362
- }
1363
- let t = this._doc?.getBookmarkPage(e.ref);
1364
- t !== void 0 && this.scrollToPage(t);
1365
- });
1366
- }
1367
- _measureForFont(e) {
1368
- this._measureCtx === void 0 && (this._measureCtx = document.createElement("canvas").getContext("2d"));
1369
- let t = this._measureCtx;
1370
- return !t || typeof t.measureText != "function" ? (e) => e.length : (t.font = e, (e) => t.measureText(e).width);
1371
- }
1372
- _canvasCssPx(e) {
1373
- return {
1374
- width: parseFloat(e.style.width) || e.width,
1375
- height: parseFloat(e.style.height) || e.height
1376
- };
1377
- }
1378
- _reportRenderError(e) {
1379
- if (this._destroyed) return;
1380
- let t = e instanceof Error ? e : Error(String(e));
1381
- this._opts.onError ? this._opts.onError(t) : console.error("[ooxml] DocxScrollViewer render failed:", t);
1382
- }
1383
- async _renderSlotBitmap(e, t, n, r, i, a = t.dispatcher, o = a.begin(), s = !0) {
1384
- if (this._bitmapInFlight.has(e) || this._slots.get(e) !== t) return;
1385
- let c = this._renderEpoch;
1386
- this._bitmapInFlight.add(e);
1387
- let l = !1, u = !!this._opts.enableTextSelection && !!t.textLayer, d = u || this._findActive, f = [];
1388
- try {
1389
- let s = await this._doc.renderPageToBitmap(e, {
1390
- width: n,
1391
- dpr: r,
1392
- defaultTextColor: this._opts.defaultTextColor,
1393
- currentDate: this._opts.currentDate,
1394
- onTextRun: d ? (e) => f.push(e) : void 0
1395
- });
1396
- if (!a.isCurrent(o) || c !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) {
1397
- s.close();
1398
- return;
1399
- }
1400
- if (!a.commitBitmap(o, s, {
1401
- cssWidth: Math.round(s.width / r),
1402
- cssHeight: Math.round(s.height / r)
1403
- })) return;
1404
- if (t.renderedScale = i, t.textLayer && (t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = "", u)) {
1405
- let { width: n, height: r } = this._canvasCssPx(t.canvas);
1406
- K(t.textLayer, f, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
1407
- }
1408
- d && this._refreshFindRuns(e, f), this._redrawSlotHighlights(e, t), l = !0;
1409
- } catch (n) {
1410
- if (a.isCurrent(o) && c === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e) if (s) this._reportRenderError(n);
1411
- else throw n;
1412
- } finally {
1413
- this._bitmapInFlight.delete(e);
1414
- let n = this._slots.get(e);
1415
- !l && n && (n !== t || c !== this._renderEpoch || !a.isCurrent(o)) && !this._bitmapInFlight.has(e) && !this._destroyed && this._renderSlotBitmap(e, n, this._pageWidthPx(e), this._dpr(), this._scale);
1416
- }
1417
- }
1418
- setScale(e) {
1419
- let t = this._opts.zoomMin ?? .1, n = this._opts.zoomMax ?? 4, r = Math.min(n, Math.max(t, e)), i = this._pendingZoomAnchor;
1420
- if (this._pendingZoomAnchor = null, !this._doc || this._doc.pageCount === 0 || !this._scaleEstablished) {
1421
- this._pendingScale = r;
1422
- return;
1423
- }
1424
- if (r === this._scale) return;
1425
- 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;
1426
- f = Math.min(1, Math.max(0, f));
1427
- let p = this._padH().left, m = this._scrollHost.scrollLeft || 0;
1428
- this._renderEpoch++, this._scale = r, this._recomputeHeights();
1429
- let h = M(this._heights, this._gap(), 0, this._scrollHost.clientHeight, this._overscan(), this._pad());
1430
- this._spacer.style.height = `${h.totalHeight}px`, this._syncSpacerWidth();
1431
- 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;
1432
- if (this._scrollHost.scrollTop = Math.min(g, Math.max(0, v)), i) {
1433
- let e = Math.max(0, (this._spacer.offsetWidth || 0) - this._scrollHost.clientWidth);
1434
- this._scrollHost.scrollLeft = b(m, i.x - p, a, r, { maxScroll: e });
1435
- }
1436
- this._previewVisible(), this._scheduleSettle(), this._opts.onScaleChange?.(r);
1437
- }
1438
- getScale() {
1439
- return this._scaleEstablished ? this._scale : this._pendingScale ?? 1;
1440
- }
1441
- zoomIn() {
1442
- this.setScale(w(this.getScale()));
1443
- }
1444
- zoomOut() {
1445
- this.setScale(T(this.getScale()));
1446
- }
1447
- fitWidth() {
1448
- this._fit("width");
1449
- }
1450
- fitPage() {
1451
- this._fit("page");
1452
- }
1453
- _fit(e) {
1454
- if (!this._doc || this._doc.pageCount === 0) return;
1455
- let t = this._doc.pageSize(0), n = v({
1456
- contentWidth: t.widthPt * j,
1457
- contentHeight: t.heightPt * j,
1458
- containerWidth: this._fitWidthPx(),
1459
- containerHeight: this._scrollHost.clientHeight
1460
- }, e);
1461
- n <= 0 || this.setScale(n);
1462
- }
1463
- _previewVisible() {
1464
- if (!this._doc || this._doc.pageCount === 0) return;
1465
- let e = this._range();
1466
- this._lastRange = e;
1467
- for (let [t, n] of [...this._slots]) (t < e.start || t > e.end) && this._recycleSlot(t, n);
1468
- for (let t = e.start; t <= e.end; t++) {
1469
- let n = this._slots.get(t);
1470
- if (n) this._previewSlot(n, t, e);
1471
- else {
1472
- let n = this._acquireSlot();
1473
- this._positionSlot(n, t, e), this._slots.set(t, n), this._renderSlot(t, n);
1474
- }
1475
- }
1476
- e.topIndex !== this._lastTopIndex && (this._lastTopIndex = e.topIndex, this._opts.onVisiblePageChange?.(e.topIndex, this._doc.pageCount));
1477
- }
1478
- _previewSlot(e, t, n) {
1479
- 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) {
1480
- let t = this._scale / e.renderedScale;
1481
- e.textLayer.style.transformOrigin = "0 0", e.textLayer.style.transform = `scale(${t})`;
1482
- }
1483
- }
1484
- _scheduleSettle() {
1485
- this._settleTimer !== null && clearTimeout(this._settleTimer), this._settleTimer = setTimeout(() => {
1486
- this._settleTimer = null, this._settleRender();
1487
- }, ft);
1488
- }
1489
- _settleRender() {
1490
- if (!(this._destroyed || !this._doc || this._doc.pageCount === 0)) for (let [e, t] of [...this._slots]) t.renderedScale !== this._scale && this._settleSlot(e, t);
1491
- }
1492
- _settleSlot(e, t) {
1493
- if (!this._doc) return;
1494
- let n = this._dpr(), r = this._pageWidthPx(e), i = this._scale, a = this._renderEpoch;
1495
- if (this._mode === "worker") {
1496
- this._renderSlotBitmap(e, t, r, n, i);
1497
- return;
1498
- }
1499
- let o = document.createElement("canvas");
1500
- o.style.cssText = "display:block;background:#fff;", this._applyPageShadow(o);
1501
- 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;
1502
- this._doc.renderPage(o, e, {
1503
- width: r,
1504
- dpr: n,
1505
- defaultTextColor: this._opts.defaultTextColor,
1506
- currentDate: this._opts.currentDate,
1507
- onTextRun: f
1508
- }).then(() => {
1509
- if (!s.isCurrent(c) || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) {
1510
- s.destroy();
1511
- return;
1512
- }
1513
- let n = t.canvas;
1514
- 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)) {
1515
- let { width: n, height: r } = this._canvasCssPx(o);
1516
- K(t.textLayer, l, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
1517
- }
1518
- d && this._refreshFindRuns(e, l), this._redrawSlotHighlights(e, t);
1519
- }).catch((n) => {
1520
- s.isCurrent(c) && a === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e && this._reportRenderError(n), s.destroy();
1521
- });
1522
- }
1523
- scrollToPage(e, t) {
1524
- if (!this._doc || this._doc.pageCount === 0 || !this._scaleEstablished) return;
1525
- let n = Math.max(0, Math.min(e, this._doc.pageCount - 1)), r = M(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;
1526
- typeof s.scrollTo == "function" ? s.scrollTo({
1527
- top: o,
1528
- behavior: t?.behavior ?? "auto"
1529
- }) : this._scrollHost.scrollTop = o, this._mountVisible();
1530
- }
1531
- async findText(e, t = {}) {
1532
- if (!this._doc) return [];
1533
- this._findActive = e.length > 0;
1534
- let n = await this._find.find(e, t);
1535
- return this._redrawHighlights(), n;
1536
- }
1537
- async findNext() {
1538
- return this._activateMatch(this._find.next());
1539
- }
1540
- async findPrev() {
1541
- return this._activateMatch(this._find.prev());
1542
- }
1543
- clearFind() {
1544
- this._findActive = !1, this._find.invalidate(), this._redrawHighlights();
1545
- }
1546
- async _activateMatch(e) {
1547
- return e && this.scrollToPage(e.location.page), this._redrawHighlights(), e;
1548
- }
1549
- async _collectPageRuns(e) {
1550
- return this._doc ? this._doc.collectPageRuns(e, {
1551
- width: this._pageWidthPx(e),
1552
- currentDate: this._opts.currentDate
1553
- }) : [];
1554
- }
1555
- _redrawHighlights() {
1556
- for (let [e, t] of this._slots) this._redrawSlotHighlights(e, t);
1557
- }
1558
- _refreshFindRuns(e, t) {
1559
- this._findActive && this._find.setPageRuns(e, t);
1560
- }
1561
- _redrawSlotHighlights(e, t) {
1562
- if (!this._findActive) {
1563
- t.highlightLayer.innerHTML = "";
1564
- return;
1565
- }
1566
- let n = this._find.pageRuns(e);
1567
- if (!n) {
1568
- t.highlightLayer.innerHTML = "";
1569
- return;
1570
- }
1571
- q(t.highlightLayer, n, this._find.pageHighlights(e), this._pageWidthPx(e), this._pageHeightPx(e), (e) => this._measureForFont(e), this._opts.findHighlightColors);
1572
- }
1573
- _onResize() {
1574
- if (!this._doc || this._doc.pageCount === 0) return;
1575
- if (!this._scaleEstablished) {
1576
- this.relayout();
1577
- return;
1578
- }
1579
- if (this._opts.refitOnResize === !1) {
1580
- this._lastFitWidth = this._fitWidthPx(), this._mountVisible();
1581
- return;
1582
- }
1583
- let e = this._baseScale();
1584
- if (e <= 0) return;
1585
- let t = this._fitWidthPx();
1586
- if (t === this._lastFitWidth) {
1587
- this._mountVisible();
1588
- return;
1589
- }
1590
- this._lastFitWidth = t;
1591
- let n = this._prevBase > 0 ? this._scale / this._prevBase : 1;
1592
- this._prevBase = e, this.setScale(e * n), this._mountVisible();
1593
- }
1594
- get topVisiblePage() {
1595
- return this._lastRange?.topIndex ?? 0;
1596
- }
1597
- mountedPageIndicesForTest() {
1598
- return [...this._slots.keys()];
1599
- }
1600
- scaleForTest() {
1601
- return this._scale;
1602
- }
1603
- baseScaleForTest() {
1604
- return this._baseScale();
1605
- }
1606
- renderEpochForTest() {
1607
- return this._renderEpoch;
1608
- }
1609
- resizeForTest() {
1610
- this._onResize();
1611
- }
1612
- contentAtViewportYForTest(e) {
1613
- let t = this._range(), n = this._scrollHost.scrollTop + e, r = this._pageIndexAtOffset(t, n), i = this._heights[r] || 0;
1614
- return {
1615
- page: r,
1616
- frac: i > 0 ? Math.min(1, Math.max(0, (n - t.offsets[r]) / i)) : 0
1617
- };
1618
- }
1619
- viewportYOfForTest(e, t) {
1620
- return (this._range().offsets[e] ?? 0) + t * (this._heights[e] || 0) - this._scrollHost.scrollTop;
1621
- }
1622
- async getResourceMetrics() {
1623
- if (!this._doc) throw Error("Document not loaded");
1624
- return await this._doc.getResourceMetrics();
1625
- }
1626
- getSelectionContext(e = {}) {
1627
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
1628
- return (this._opts.enableTextSelection ? Z(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null, e) : null) ?? (this._elementContext ? H(this._elementContext, e.maxTextCharacters) : null);
1629
- }
1630
- _emitSelectionContextChange() {
1631
- let e = this.getSelectionContext();
1632
- e?.kind === "text" && (this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutlines());
1633
- let t = JSON.stringify(e);
1634
- t !== this._selectionContextKey && (this._selectionContextKey = t, this._opts.onSelectionContextChange?.(e ? structuredClone(e) : null));
1635
- }
1636
- _setElementContext(e) {
1637
- this._elementContext = e ? structuredClone(e) : null, this._redrawElementOutlines(), this._emitSelectionContextChange();
1638
- }
1639
- _invalidateElementContext(e = !0) {
1640
- this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutlines(), e && this._emitSelectionContextChange();
1641
- }
1642
- _redrawElementOutlines() {
1643
- for (let [e, t] of this._slots) this._redrawElementOutlineForSlot(e, t);
1644
- }
1645
- _redrawElementOutlineForSlot(e, t) {
1646
- let n = this._elementContext, r = this._doc;
1647
- if (!n || !r || n.pageIndex !== e) {
1648
- x(t.elementLayer, null);
1649
- return;
1650
- }
1651
- let i = r.pageSize(e);
1652
- x(t.elementLayer, {
1653
- x: n.bounds.xPt / i.widthPt,
1654
- y: n.bounds.yPt / i.heightPt,
1655
- width: n.bounds.widthPt / i.widthPt,
1656
- height: n.bounds.heightPt / i.heightPt
1657
- });
1658
- }
1659
- async _onElementClick(e) {
1660
- this._destroyed || e.defaultPrevented || e.button !== 0 || await this._resolveContextAt(e);
1661
- }
1662
- _onContextMenu(e) {
1663
- let t;
1664
- this._opts.onContextMenu?.({
1665
- originalEvent: e,
1666
- getContext: () => t ??= this._resolveContextAt(e)
1667
- });
1668
- }
1669
- async _resolveContextAt(e) {
1670
- let t = this._doc;
1671
- if (this._destroyed || !t) return null;
1672
- if (this._opts.enableTextSelection && Z(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null)) return this._emitSelectionContextChange(), this._destroyed ? null : this.getSelectionContext();
1673
- if (!this._opts.enableElementSelection) return this.getSelectionContext();
1674
- let n = e.target, r = [...this._slots].find(([, e]) => n !== null && e.wrapper.contains(n));
1675
- if (!r) return this._invalidateElementContext(), null;
1676
- let [i, a] = r, o = a.canvas.getBoundingClientRect();
1677
- if (o.width <= 0 || o.height <= 0) return this._invalidateElementContext(), null;
1678
- let s = e.clientX - o.left, c = e.clientY - o.top;
1679
- if (s < 0 || c < 0 || s > o.width || c > o.height) return this._invalidateElementContext(), null;
1680
- let l = ++this._elementHitGeneration, u = t.pageSize(i), d;
1681
- try {
1682
- d = await t.getElementContextAt(i, {
1683
- xPt: s / o.width * u.widthPt,
1684
- yPt: c / o.height * u.heightPt
1685
- }, {
1686
- currentDate: this._opts.currentDate,
1687
- maxTextCharacters: I
1688
- });
1689
- } catch (e) {
1690
- if (this._destroyed || l !== this._elementHitGeneration || t !== this._doc) return null;
1691
- throw e;
1692
- }
1693
- return this._destroyed || l !== this._elementHitGeneration || t !== this._doc ? null : (this._setElementContext(d), this._destroyed ? null : this.getSelectionContext());
1694
- }
1695
- destroy() {
1696
- if (!this._destroyed) {
1697
- this._destroyed = !0, this._find.invalidate(), this._findActive = !1, this._selectionChangeListener &&= (this._wrapper.ownerDocument.removeEventListener("selectionchange", this._selectionChangeListener), null), this._elementHitGeneration++, this._elementClickListener &&= (this._scrollHost.removeEventListener("click", this._elementClickListener), null), this._contextMenuListener &&= (this._scrollHost.removeEventListener("contextmenu", this._contextMenuListener), null), this._elementContext = null, 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);
1698
- for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
1699
- this._free.length = 0, this._documentOwner.close(), this._wrapper.remove();
1700
- }
1701
- }
1702
- };
1703
- //#endregion
1704
- //#region packages/docx/src/types.ts
1705
- function $(e) {
1706
- let t = [];
1707
- for (let n of e.content) {
1708
- if (n.type !== "paragraph") continue;
1709
- let e = "";
1710
- for (let t of n.runs) t.type === "text" && !t.noteRef && (e += t.text);
1711
- e = e.trim(), e && t.push(e);
1712
- }
1713
- return t.join(" ");
1714
- }
1715
- //#endregion
1716
- //#region src/docx.ts
1717
- var gt = /* @__PURE__ */ e({
1718
- DocxDocument: () => U,
1719
- DocxScrollViewer: () => ht,
1720
- DocxViewer: () => dt,
1721
- OoxmlDecodedImageLimitError: () => i,
1722
- OoxmlError: () => o,
1723
- OoxmlResourceLimitError: () => l,
1724
- autoResize: () => fe,
1725
- buildDocxHighlightLayer: () => q,
1726
- buildDocxTextLayer: () => K,
1727
- isOoxmlDecodedImageLimitError: () => p,
1728
- noteText: () => $,
1729
- openExternalHyperlink: () => a,
1730
- readDocxTextSelectionContext: () => Z
1731
- });
1732
- //#endregion
1733
- export { Z as a, U as c, dt as i, $ as n, q as o, ht as r, K as s, gt as t };