@silurus/ooxml 0.82.1 → 0.83.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +74 -5
  2. package/dist/assets/render-worker-4GSYWsM3.js +11 -0
  3. package/dist/assets/{render-worker-Cy-QsDge.js → render-worker-DwFpY197.js} +4 -4
  4. package/dist/{canvas-viewer-mechanics-CS_qbr6T.js → canvas-viewer-mechanics-h07vpVOQ.js} +42 -2
  5. package/dist/{comment-ui-runtime-C1RV_3iu.js → comment-ui-runtime-BelHJt73.js} +2 -2
  6. package/dist/{comment-ui-runtime-DgCZpPR0.js → comment-ui-runtime-DD5a3x3k.js} +2 -2
  7. package/dist/{comments-Cf9W7r3M.js → comments-AAaNnQTi.js} +7 -2
  8. package/dist/{document-pull-client-B1WOjA0z.js → document-pull-client-DSx36ZsB.js} +4519 -3952
  9. package/dist/docx-BF-WKW73.js +2784 -0
  10. package/dist/docx.mjs +6 -6
  11. package/dist/docx_parser_bg.wasm +0 -0
  12. package/dist/dom-interaction-boundary-CepOlXt6.js +217 -0
  13. package/dist/index.mjs +4 -4
  14. package/dist/line-distribute-D7A_wnJg.js +1003 -0
  15. package/dist/{line-metrics-B3syvDn2.js → line-metrics-Bpn7OeZD.js} +616 -616
  16. package/dist/node.mjs +308 -308
  17. package/dist/pptx-CA-Q09yW.js +3010 -0
  18. package/dist/pptx.mjs +5 -5
  19. package/dist/pptx_parser_bg.wasm +0 -0
  20. package/dist/{render-BC8p7vZQ.js → render-DtbFbO5c.js} +1 -1
  21. package/dist/{render-worker-host-BNnXCtAu.js → render-worker-host-D1jcACJV.js} +1 -1
  22. package/dist/{render-worker-host-DhnkTyjj.js → render-worker-host-DCLyw6UR.js} +1 -1
  23. package/dist/{resource-measurement-CsW4_eYt.js → resource-measurement-DuiFWzam.js} +3 -3
  24. package/dist/{session-Da7LEQUB.js → session-CxT-t0BX.js} +107 -94
  25. package/dist/{slide-pull-client-Bg9DusLX.js → slide-pull-client-B9rcJdO4.js} +1190 -937
  26. package/dist/types/docx.d.ts +103 -8
  27. package/dist/types/index.d.ts +195 -13
  28. package/dist/types/node.d.ts +2 -2
  29. package/dist/types/pptx.d.ts +100 -5
  30. package/dist/types/xlsx.d.ts +2 -2
  31. package/dist/{worksheet-pull-client-CYtwXP5D.js → worksheet-pull-client-DyFsDF4A.js} +32 -32
  32. package/dist/{xlsx-DMWeXT-c.js → xlsx-BibrHQ52.js} +476 -476
  33. package/dist/xlsx.mjs +5 -5
  34. package/dist/xlsx_parser_bg.wasm +0 -0
  35. package/package.json +3 -1
  36. package/dist/assets/render-worker-aHayzR7v.js +0 -11
  37. package/dist/docx-HoZXZUPA.js +0 -2162
  38. package/dist/dom-interaction-boundary-C8F6HO5x.js +0 -119
  39. package/dist/line-distribute-iXsUCIH-.js +0 -1003
  40. package/dist/pptx-DEUP4Yq5.js +0 -2432
  41. /package/dist/{comment-occurrence-C34fWs_F.js → comment-occurrence-X54si2ob.js} +0 -0
  42. /package/dist/{highlight-rect-MaCt0om0.js → highlight-rect-Hes0z_Mj.js} +0 -0
@@ -0,0 +1,2784 @@
1
+ import { t as e } from "./chunk-DmhlhrBa.js";
2
+ import { B as t, Qt as n, R as r, Vt as i, W as a, Zt as o, a as s, et as c, ft as l, lt as u, z as d } from "./line-metrics-Bpn7OeZD.js";
3
+ import { C as f, E as p, S as m, T as h, _ as g, a as _, b as ee, c as v, d as y, f as te, g as ne, h as re, i as b, l as x, 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 fe, w as pe, x as me, y as he } from "./canvas-viewer-mechanics-h07vpVOQ.js";
4
+ import { a as ge, i as _e, t as ve } from "./bounded-raw-part-cache-C6ro6Ezf.js";
5
+ import { c as ye, i as be, l as xe, n as Se, o as S, r as Ce, s as we, t as Te } from "./dom-interaction-boundary-CepOlXt6.js";
6
+ import { A as Ee, C, D as w, E as De, O as T, S as Oe, T as E, _ as ke, a as Ae, b as je, c as Me, d as Ne, f as Pe, g as Fe, h as Ie, j as Le, k as Re, l as ze, m as Be, n as D, o as Ve, p as He, s as Ue, t as O, v as We, w as Ge, x as Ke, y as qe } from "./document-pull-client-DSx36ZsB.js";
7
+ import { cn as Je, ln as Ye } from "./plot-area-frame-DHV02PJU.js";
8
+ import { a as k } from "./units-BzZ0gAxs.js";
9
+ import { n as Xe } from "./renderer-module-contract-DLbb7zY0.js";
10
+ import { n as Ze, t as A } from "./highlight-rect-Hes0z_Mj.js";
11
+ import { o as j } from "./source-key-BklvnEyQ.js";
12
+ import { i as Qe, n as M, r as $e, t as et } from "./comments-AAaNnQTi.js";
13
+ //#region packages/docx/src/worker.ts?worker&inline
14
+ var tt = "var e=(e,t)=>()=>(e&&(t=e(e=0)),t),t=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,r.unregister(this),e}free(){let e=this.__destroy_into_raw();_.__wbg_docxarchive_free(e,0)}acknowledge_document_chunk(e,t,n){let r=_.docxarchive_acknowledge_document_chunk(this.__wbg_ptr,e,t,n);if(r[1])throw f(r[0])}assert_healthy(){let e=_.docxarchive_assert_healthy(this.__wbg_ptr);if(e[1])throw f(e[0])}cancel_document_cursor(){_.docxarchive_cancel_document_cursor(this.__wbg_ptr)}close_document_session(){_.docxarchive_close_document_session(this.__wbg_ptr)}document_chunk_done(){let e=_.docxarchive_document_chunk_done(this.__wbg_ptr);if(e[2])throw f(e[1]);return e[0]!==0}document_cursor_resource_usage(){let e=_.docxarchive_document_cursor_resource_usage(this.__wbg_ptr);if(e[3])throw f(e[2]);var t=i(e[0],e[1]).slice();return _.__wbindgen_free(e[0],e[1]*1,1),t}extract_image(e){let t=d(e,_.__wbindgen_malloc,_.__wbindgen_realloc),n=g,r=_.docxarchive_extract_image(this.__wbg_ptr,t,n);if(r[3])throw f(r[2]);var a=i(r[0],r[1]).slice();return _.__wbindgen_free(r[0],r[1]*1,1),a}constructor(e,t,n,i){let a=ee(e,_.__wbindgen_malloc),o=g,s=_.docxarchive_new(a,o,!u(t),u(t)?BigInt(0):t,!u(n),u(n)?BigInt(0):n,!u(i),u(i)?BigInt(0):i);if(s[2])throw f(s[1]);return this.__wbg_ptr=s[0]>>>0,r.register(this,this.__wbg_ptr,this),this}open_document_cursor(e,t){let n=_.docxarchive_open_document_cursor(this.__wbg_ptr,e,t);if(n[1])throw f(n[0])}parse(){let e=_.docxarchive_parse(this.__wbg_ptr);if(e[3])throw f(e[2]);var t=i(e[0],e[1]).slice();return _.__wbindgen_free(e[0],e[1]*1,1),t}pull_document_chunk(e,t,n,r){let a=_.docxarchive_pull_document_chunk(this.__wbg_ptr,e,t,n,r);if(a[3])throw f(a[2]);var o=i(a[0],a[1]).slice();return _.__wbindgen_free(a[0],a[1]*1,1),o}resource_usage(){let e=_.docxarchive_resource_usage(this.__wbg_ptr);if(e[3])throw f(e[2]);var t=i(e[0],e[1]).slice();return _.__wbindgen_free(e[0],e[1]*1,1),t}to_markdown(){let e,t;try{let i=_.docxarchive_to_markdown(this.__wbg_ptr);var n=i[0],r=i[1];if(i[3])throw n=0,r=0,f(i[2]);return e=n,t=r,s(n,r)}finally{_.__wbindgen_free(e,t,1)}}};Symbol.dispose&&(t.prototype[Symbol.dispose]=t.prototype.free);function n(){return{__proto__:null,\"./docx_parser_bg.js\":{__proto__:null,__wbg___wbindgen_throw_6b64449b9b9ed33c:function(e,t){throw Error(s(e,t))},__wbg_error_a6fa202b58aa1cd3:function(e,t){let n,r;try{n=e,r=t,console.error(s(e,t))}finally{_.__wbindgen_free(n,r,1)}},__wbg_new_227d7c05414eb861:function(){return Error()},__wbg_stack_3b0d974bbf31e44f:function(e,t){let n=t.stack,r=d(n,_.__wbindgen_malloc,_.__wbindgen_realloc),i=g;o().setInt32(e+4,i,!0),o().setInt32(e+0,r,!0)},__wbindgen_cast_0000000000000001:function(e,t){return s(e,t)},__wbindgen_init_externref_table:function(){let e=_.__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 r=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>_.__wbg_docxarchive_free(e>>>0,1));function i(e,t){return e>>>=0,l().subarray(e/1,e/1+t)}let a=null;function o(){return(a===null||a.buffer.detached===!0||a.buffer.detached===void 0&&a.buffer!==_.memory.buffer)&&(a=new DataView(_.memory.buffer)),a}function s(e,t){return e>>>=0,te(e,t)}let c=null;function l(){return(c===null||c.byteLength===0)&&(c=new Uint8Array(_.memory.buffer)),c}function u(e){return e==null}function ee(e,t){let n=t(e.length*1,1)>>>0;return l().set(e,n/1),g=e.length,n}function d(e,t,n){if(n===void 0){let n=h.encode(e),r=t(n.length,1)>>>0;return l().subarray(r,r+n.length).set(n),g=n.length,r}let r=e.length,i=t(r,1)>>>0,a=l(),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=l().subarray(i+o,i+r),a=h.encodeInto(e,t);o+=a.written,i=n(i,r,o,1)>>>0}return g=o,i}function f(e){let t=_.__wbindgen_externrefs.get(e);return _.__externref_table_dealloc(e),t}let p=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0});p.decode();let m=0;function te(e,t){return m+=t,m>=2146435072&&(p=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}),p.decode(),m=t),p.decode(l().subarray(e,e+t))}const h=new TextEncoder;`encodeInto`in h||(h.encodeInto=function(e,t){let n=h.encode(e);return t.set(n),{read:e.length,written:n.length}});let g=0,_;function v(e,t){return _=e.exports,a=null,c=null,_.__wbindgen_start(),_}async function y(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 b(e){if(_!==void 0)return _;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 t=n();(typeof e==`string`||typeof Request==`function`&&e instanceof Request||typeof URL==`function`&&e instanceof URL)&&(e=fetch(e));let{instance:r,module:i}=await y(await e,t);return v(r,i)}async function ne(e){return _=void 0,a=null,c=null,b(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)}},C,w,re=e((()=>{C=1<<25,C*4,w=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 ie(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 ae=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`)}},T=class e extends Error{code=`parser-crashed`;constructor(t){super(t),this.name=`WasmTrapError`,Object.setPrototypeOf(this,e.prototype)}};function E(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 oe(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 se(e,t){return e({module_or_path:t})}var ce=class{runtime;wasmInput=null;currentArchive=null;constructor(e,t={}){this.init=e,this.options=t,this.runtime=new ae(()=>this.invokeConfigured(this.init),()=>this.invokeConfigured(this.options.reinit??this.init),le),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 T(`WASM parser was recycled`))}invokeConfigured(e){return this.wasmInput===null?Promise.reject(Error(`WasmParserHost: setWasmInput was never called`)):se(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,oe(e)}};function le(e){return E(e)?new T(`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 O(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 k=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 A(e){if(e instanceof k)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`||!O(r)))return new k(r)}function ue(e,t,n){let r=A(e);if(!(!r||r.offeredBytes!==t||r.requiredBytes>n))return r}re();const j=`OOXML_RESOURCE_LIMIT:`;function M(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function N(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return M(t.archiveEntryCount)&&M(t.declaredInflatedBytes)&&(t.largestInflatedEntryBytes===void 0||M(t.largestInflatedEntryBytes))&&M(t.distinctInflatedBytes)&&M(t.operationInflatedBytes)}function P(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw TypeError(`OOXML resource usage checkpoint is not valid JSON`)}if(!N(t))throw TypeError(`OOXML resource usage checkpoint is invalid`);return t}function F(e){return e===`docx`||e===`xlsx`||e===`pptx`}function I(e){return e===`container`||e===`decompression`||e===`parsing`||e===`serialization`||e===`layout`||e===`rendering`||e===`worker`}function L(e,t){return typeof e==`string`&&e.length>0&&e.length<=t&&!/[\\u0000-\\u001f\\u007f]/u.test(e)}function R(e){return L(e,128)&&/^[a-z0-9][a-z0-9-]*$/u.test(e)}function z(e){return!L(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 B=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}]]),V=new Set([...B.keys()].map(e=>e.slice(0,e.indexOf(`:`)))),H=new Set([...B.keys()].map(e=>e.slice(e.indexOf(`:`)+1)));function de(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return!F(t.format)||!L(t.operation,256)||!R(t.resource)||!R(t.metric)||!M(t.limit)||!M(t.observed)||typeof t.configurable!=`boolean`||!N(t.usage)?!1:!(`part`in t)||z(t.part)}function U(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;if(!I(t.stage)||!de(t.violation))return!1;let n=t.violation,r=B.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:!(V.has(n.resource)&&H.has(n.metric))}function fe(e){return{archiveEntryCount:e.archiveEntryCount,declaredInflatedBytes:e.declaredInflatedBytes,...e.largestInflatedEntryBytes===void 0?{}:{largestInflatedEntryBytes:e.largestInflatedEntryBytes},distinctInflatedBytes:e.distinctInflatedBytes,operationInflatedBytes:e.operationInflatedBytes}}function pe(e){if(!U(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:fe(t.usage)}};return U(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 me(e){let t=e instanceof Error?e.message:String(e);if(!t.startsWith(j))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`||!U(r.details)))return new S(W(r.details),r.details)}function he(e){if(e instanceof w)return{message:e.message,errorName:e.name,code:e.code,decodedImage:{metric:e.metric,limit:e.limit,observed:e.observed}};let t=A(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:me(e);if(n instanceof S){let e=pe(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:L(n.name,128)?n.name:`OoxmlError`,...R(n.code)?{code:n.code}:{}};let r=e instanceof Error?e.message:String(e);if(typeof r==`string`&&r.startsWith(j))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:L(i.name,128)?i.name:`Error`,...typeof a.code==`string`?{code:a.code}:{}}}function G(e){try{return he(e)}catch{return{message:`Worker operation failed with an unreadable error`,errorName:`Error`}}}function ge(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 _e(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 ve(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}},ye=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){ve(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 be=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 ye({...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 ue(e,n,Y)||e}let i=ge(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?P(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 xe(e){return!!e&&typeof e==`object`&&e.protocol===`ooxml-pull-v1`}const X=new ce(b,{freeArchive:e=>e.free(),reinit:ne}),Z=new be(()=>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 e=>{let n=e.data;if(xe(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(ie(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[e,i,a]=_e(n.resourcePolicy),o=new Uint8Array(n.data);X.run(()=>{let n=new t(o,e,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 e=X.archive;if(n.type===`extractImage`){if(!e)throw Error(`No docx loaded`);let t=X.run(()=>e.extract_image(n.path).buffer),i={type:`imageExtracted`,id:r,bytes:t};self.postMessage(i,[t]);return}if(n.type===`resourceUsage`){if(!e)throw Error(`No docx loaded`);$({type:`resourceUsage`,id:r,usage:P(X.run(()=>e.resource_usage()))});return}if(n.type===`toMarkdown`){if(!e)throw Error(`No docx loaded`);$({type:`markdownRendered`,id:r,markdown:X.run(()=>e.to_markdown())});return}}catch(e){$({type:`error`,id:r,...G(e)})}};", nt = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", tt], { type: "text/javascript;charset=utf-8" });
15
+ function rt(e) {
16
+ let t;
17
+ try {
18
+ if (t = nt && (self.URL || self.webkitURL).createObjectURL(nt), !t) throw "";
19
+ let n = new Worker(t, {
20
+ type: "module",
21
+ name: e?.name
22
+ });
23
+ return n.addEventListener("error", () => {
24
+ (self.URL || self.webkitURL).revokeObjectURL(t);
25
+ }), n;
26
+ } catch {
27
+ return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(tt), {
28
+ type: "module",
29
+ name: e?.name
30
+ });
31
+ }
32
+ }
33
+ //#endregion
34
+ //#region packages/docx/src/wasm/docx_parser_bg.wasm?url
35
+ var it = new URL("docx_parser_bg.wasm", import.meta.url).href;
36
+ //#endregion
37
+ //#region packages/docx/src/bookmark-nav.ts
38
+ function at(e) {
39
+ let t = /* @__PURE__ */ new Map();
40
+ for (let n of e.pages) for (let e of n.bookmarkStarts) e.name !== "" && !t.has(e.name) && t.set(e.name, n.pageIndex);
41
+ return t;
42
+ }
43
+ //#endregion
44
+ //#region packages/docx/src/embedded-fonts.ts
45
+ async function ot(e, t) {
46
+ let n = e.embeddedFonts;
47
+ if (!n || n.length === 0) return [];
48
+ let r = (await Promise.all(n.map(async (e) => {
49
+ try {
50
+ let n = await t(e.partPath);
51
+ return {
52
+ family: e.fontName,
53
+ bytes: n,
54
+ odttf: e.partPath.toLowerCase().endsWith(".odttf"),
55
+ fontKey: e.fontKey,
56
+ weight: st(e.style),
57
+ style: ct(e.style)
58
+ };
59
+ } catch {
60
+ return null;
61
+ }
62
+ }))).filter((e) => e !== null);
63
+ return r.length === 0 ? [] : ye(r);
64
+ }
65
+ function st(e) {
66
+ return e === "bold" || e === "boldItalic" ? "bold" : "normal";
67
+ }
68
+ function ct(e) {
69
+ return e === "italic" || e === "boldItalic" ? "italic" : "normal";
70
+ }
71
+ //#endregion
72
+ //#region packages/docx/src/element-context.ts
73
+ var N = de, lt = 16384;
74
+ function ut(e, t) {
75
+ let n = Math.min(e.length, t);
76
+ if (n > 0 && n < e.length) {
77
+ let t = e.charCodeAt(n - 1), r = e.charCodeAt(n);
78
+ t >= 55296 && t <= 56319 && r >= 56320 && r <= 57343 && n--;
79
+ }
80
+ return e.slice(0, n);
81
+ }
82
+ function dt(e, t) {
83
+ let n = [], r = 0, i = !1;
84
+ for (let a of e) {
85
+ if (a.length === 0) continue;
86
+ if (r > 0) {
87
+ if (r >= t) {
88
+ i = !0;
89
+ break;
90
+ }
91
+ n.push("\n"), r++;
92
+ }
93
+ let e = ut(a, Math.max(0, t - r));
94
+ if (n.push(e), r += e.length, e.length < a.length) {
95
+ i = !0;
96
+ break;
97
+ }
98
+ }
99
+ let a = n.join("");
100
+ return {
101
+ ...a.length === 0 ? {} : { text: a },
102
+ truncated: i
103
+ };
104
+ }
105
+ function* P(e) {
106
+ if (e.kind === "paragraph") {
107
+ for (let t of e.lines) {
108
+ let e = t.placements.flatMap((e) => e.kind === "text" ? [e.text] : []).join("");
109
+ e && (yield e);
110
+ }
111
+ return;
112
+ }
113
+ if (e.kind === "table") {
114
+ for (let t of e.rows) for (let e of t.cells) for (let t of e.blocks) yield* P(t.layout);
115
+ return;
116
+ }
117
+ if (e.kind === "note" || e.kind === "textbox") for (let t of e.story.blocks) yield* P(t);
118
+ }
119
+ function* ft(e) {
120
+ for (let t of e.drawing.commands) (t.kind === "text" || t.kind === "watermark-text") && (yield t.text);
121
+ for (let t of e.textBoxes) yield* P(t);
122
+ }
123
+ function pt(e) {
124
+ let t = e ?? lt;
125
+ if (!Number.isFinite(t) || t < 0) throw RangeError("maxTextCharacters must be a finite non-negative number.");
126
+ return Math.min(N, Math.floor(t));
127
+ }
128
+ function mt(e) {
129
+ return {
130
+ story: e.story,
131
+ storyInstance: e.storyInstance,
132
+ path: [...e.path]
133
+ };
134
+ }
135
+ function ht(e) {
136
+ return "drawing" in e ? e.drawing.inkBounds : e.placement.bounds;
137
+ }
138
+ function gt(e) {
139
+ let t = ht(e), n = [
140
+ C(e.pointToPage, t),
141
+ C(e.pointToPage, {
142
+ xPt: t.xPt + t.widthPt,
143
+ yPt: t.yPt
144
+ }),
145
+ C(e.pointToPage, {
146
+ xPt: t.xPt,
147
+ yPt: t.yPt + t.heightPt
148
+ }),
149
+ C(e.pointToPage, {
150
+ xPt: t.xPt + t.widthPt,
151
+ yPt: t.yPt + t.heightPt
152
+ })
153
+ ], 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));
154
+ return {
155
+ xPt: r,
156
+ yPt: i,
157
+ widthPt: a - r,
158
+ heightPt: o - i
159
+ };
160
+ }
161
+ function F(e, t) {
162
+ return t.xPt >= e.xPt && t.xPt <= e.xPt + e.widthPt && t.yPt >= e.yPt && t.yPt <= e.yPt + e.heightPt;
163
+ }
164
+ function _t(e, t) {
165
+ let n = !1;
166
+ for (let r = 0, i = t.length - 1; r < t.length; i = r++) {
167
+ let a = t[r], o = t[i];
168
+ 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);
169
+ }
170
+ return n;
171
+ }
172
+ function vt(e, t) {
173
+ return F(e.inkBounds, t) ? e.clip ? e.clip.kind === "rect" ? F(e.clip.rect, t) : _t(t, e.clip.points) : !0 : !1;
174
+ }
175
+ function yt(e, t, n) {
176
+ for (let n of e.clips) {
177
+ let e = Oe(n.pointToPage, t);
178
+ if (!e || !F(n.bounds, e)) return !1;
179
+ }
180
+ return "drawing" in e ? vt(e.drawing, n) : F(e.placement.bounds, n);
181
+ }
182
+ function I(e, t) {
183
+ return e.commands.find((e) => e.kind === "resource" && e.resourceKind === t);
184
+ }
185
+ function bt(e) {
186
+ return I(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" : I(e, "image") ? "image" : null;
187
+ }
188
+ function xt(e, t, n, r, i, a) {
189
+ let o = "drawing" in e ? bt(e.drawing) : e.placement.resourceKind;
190
+ if (!o) return null;
191
+ let s, c = !1, l, u;
192
+ if (o === "chart") {
193
+ let t = "drawing" in e ? I(e.drawing, "chart").resourceKey : e.placement.resourceKey, n = i.resolve(t, "chart"), r = y(n.model, a);
194
+ s = r.text, c = r.truncated, u = n.model.series.length;
195
+ } else if (o === "image") {
196
+ let t = "drawing" in e ? I(e.drawing, "image").resourceKey : e.placement.resourceKey, n = i.descriptors.find((e) => e.resourceKey === t && e.kind === "image" && "mimeType" in e);
197
+ if (!n) throw Error(`Unknown image paint resource: ${t}`);
198
+ l = n.mimeType;
199
+ } else {
200
+ let t = dt(ft(e), a);
201
+ s = t.text, c = t.truncated;
202
+ }
203
+ return {
204
+ format: "docx",
205
+ kind: "element",
206
+ pageIndex: t,
207
+ elementIndex: n,
208
+ elementType: o,
209
+ point: { ...r },
210
+ bounds: gt(e),
211
+ source: mt("drawing" in e ? e.drawing.source : e.source),
212
+ ...s === void 0 ? {} : { text: s },
213
+ ...l === void 0 ? {} : { mimeType: l },
214
+ ...u === void 0 ? {} : { seriesCount: u },
215
+ truncated: c,
216
+ truncationReasons: c ? ["text"] : [],
217
+ textCharacters: s?.length ?? 0,
218
+ maxTextCharacters: a
219
+ };
220
+ }
221
+ function St(e, t, n, r, i = {}) {
222
+ if (!Number.isFinite(n.xPt) || !Number.isFinite(n.yPt)) throw RangeError("DOCX hit-test point must contain finite page coordinates.");
223
+ let a = pt(i.maxTextCharacters), o = je(e, t);
224
+ for (let e = o.length - 1; e >= 0; e--) {
225
+ let i = o[e], s = Oe(i.pointToPage, n);
226
+ if (!s || !yt(i, n, s)) continue;
227
+ let c = xt(i, t, e, n, r, a);
228
+ if (c) return c;
229
+ }
230
+ return null;
231
+ }
232
+ function Ct(e, t, n, r) {
233
+ return St(Ge(e, {
234
+ currentDate: r.currentDate,
235
+ defaultCurrentDateMs: r.defaultCurrentDateMs,
236
+ showTrackedChanges: r.showTrackedChanges
237
+ }, t).layout, t, n, Re(e), r);
238
+ }
239
+ function L(e, t) {
240
+ let n = pt(t), r = e.text === void 0 ? void 0 : ut(e.text, n), i = e.truncated || e.text !== void 0 && r.length < e.text.length;
241
+ return {
242
+ ...structuredClone(e),
243
+ ...r === void 0 ? {} : { text: r },
244
+ truncated: i,
245
+ truncationReasons: i ? ["text"] : [],
246
+ textCharacters: r?.length ?? 0,
247
+ maxTextCharacters: n
248
+ };
249
+ }
250
+ //#endregion
251
+ //#region packages/docx/src/revisions.ts
252
+ function R(e) {
253
+ let t = Qe(e.id);
254
+ return t === void 0 ? void 0 : `${e.kind}\u0000${t}`;
255
+ }
256
+ function z(e) {
257
+ return Object.freeze({
258
+ ...e,
259
+ path: Object.freeze([...e.path])
260
+ });
261
+ }
262
+ function wt(e, t) {
263
+ return e !== void 0 && e.story === t.story && e.storyInstance === t.storyInstance && e.path.length === t.path.length && e.path.every((e, n) => e === t.path[n]);
264
+ }
265
+ function B(e, t) {
266
+ let n = 0, r = e.length;
267
+ for (; n < r;) {
268
+ let i = n + Math.floor((r - n) / 2);
269
+ e[i] < t ? n = i + 1 : r = i;
270
+ }
271
+ return n;
272
+ }
273
+ function Tt(e, t) {
274
+ let n = Array(e.length), r;
275
+ for (let i = e.length - 1; i >= 0; --i) {
276
+ n[i] = r;
277
+ let a = e[i], o = t.get(j(a.source))?.[0];
278
+ o !== void 0 && (r = Object.freeze({
279
+ source: z(a.source),
280
+ sourceRunIndex: o
281
+ }));
282
+ }
283
+ let i = Array(e.length), a;
284
+ for (let n = 0; n < e.length; n += 1) {
285
+ i[n] = a;
286
+ let r = e[n], o = t.get(j(r.source))?.at(-1);
287
+ o !== void 0 && (a = Object.freeze({
288
+ source: z(r.source),
289
+ sourceRunIndex: o
290
+ }));
291
+ }
292
+ return {
293
+ following: n,
294
+ preceding: i
295
+ };
296
+ }
297
+ function Et(e, t, n, r, i, a) {
298
+ let o = r[e], s = i.get(j(o.source)) ?? [], c = s[B(s, n)], l = s[B(s, t) - 1], u = c ?? l;
299
+ return u === void 0 ? a.following[e] ?? a.preceding[e] : Object.freeze({
300
+ source: z(o.source),
301
+ sourceRunIndex: u
302
+ });
303
+ }
304
+ function Dt(e, t, n = /* @__PURE__ */ new Map()) {
305
+ let r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Set();
306
+ e.forEach((e, t) => {
307
+ let n = R(e);
308
+ n === void 0 || i.has(n) || (r.has(n) ? (r.delete(n), i.add(n)) : r.set(n, t));
309
+ });
310
+ let a = t.blocks.sources.flatMap((e) => {
311
+ if (e.story !== "body") return [];
312
+ let n = t.blocks.resolve(e);
313
+ return n.type === "paragraph" ? [{
314
+ source: e,
315
+ runs: n.runs
316
+ }] : [];
317
+ }), o = new Map([...n].map(([e, t]) => [e, Object.freeze([...t].sort((e, t) => e - t))])), s = Tt(a, o), c = [];
318
+ for (let [e, t] of a.entries()) {
319
+ let n = 0;
320
+ for (; n < t.runs.length;) {
321
+ let i = t.runs[n], l = i.revision?.kind ? R({
322
+ kind: i.revision.kind,
323
+ id: i.revision.id
324
+ }) : void 0, u = l === void 0 ? void 0 : r.get(l);
325
+ if (u === void 0) {
326
+ n += 1;
327
+ continue;
328
+ }
329
+ let d = n;
330
+ for (n += 1; n < t.runs.length;) {
331
+ let e = t.runs[n].revision;
332
+ if (!e?.kind || R({
333
+ kind: e.kind,
334
+ id: e.id
335
+ }) !== l) break;
336
+ n += 1;
337
+ }
338
+ let f = n, p = o.get(j(t.source)) ?? [], m = (p[B(p, d)] ?? f) < f ? void 0 : Et(e, d, f, a, o, s);
339
+ c.push(Object.freeze({
340
+ revisionIndex: u,
341
+ source: z(t.source),
342
+ startRunIndex: d,
343
+ endRunIndex: f,
344
+ ...m === void 0 ? {} : { geometryFallback: m }
345
+ }));
346
+ }
347
+ }
348
+ return c;
349
+ }
350
+ function Ot(e, t, n = /* @__PURE__ */ new Map(), r = {}) {
351
+ if ((e?.length ?? 0) === 0) return [];
352
+ let i = Dt(e ?? [], t, n), a = r.completedSourceKeys;
353
+ return a === void 0 ? i : i.filter((e) => {
354
+ let t = n.get(j(e.source));
355
+ return t !== void 0 && [...t].some((t) => t >= e.startRunIndex && t < e.endRunIndex) || a.has(j(e.source));
356
+ });
357
+ }
358
+ function kt(e, t) {
359
+ let n = t.filter((t) => t.sourceRunIndex !== void 0 && wt(t.source, e.source) && t.sourceRunIndex >= e.startRunIndex && t.sourceRunIndex < e.endRunIndex);
360
+ if (n.length > 0) return n;
361
+ let r = e.geometryFallback;
362
+ return r === void 0 ? [] : t.filter((e) => e.sourceRunIndex === r.sourceRunIndex && wt(e.source, r.source));
363
+ }
364
+ //#endregion
365
+ //#region packages/docx/src/layout/progressive.ts
366
+ var At = 12;
367
+ async function jt(e, t, n, r = {}) {
368
+ let { onPreview: i, scheduler: a } = r;
369
+ return Fe(ke(e, t, n, i && e.sequence.length > At ? { onPages: (e, t) => {
370
+ i(Object.freeze({
371
+ layout: e,
372
+ exact: !1,
373
+ coveredEntries: t
374
+ }));
375
+ } } : void 0), a);
376
+ }
377
+ //#endregion
378
+ //#region packages/docx/src/document-layout-events.ts
379
+ var V = /* @__PURE__ */ new WeakMap();
380
+ function H(e, t) {
381
+ let n = Object.freeze({ ...t });
382
+ for (let t of [...V.get(e) ?? []]) try {
383
+ t.notify(n);
384
+ } catch (e) {
385
+ try {
386
+ t.report(e);
387
+ } catch {}
388
+ }
389
+ }
390
+ function Mt(e, t, n, r) {
391
+ let i = V.get(e);
392
+ i || (i = /* @__PURE__ */ new Set(), V.set(e, i));
393
+ let a = Object.freeze({
394
+ notify: n,
395
+ report: r
396
+ });
397
+ i.add(a);
398
+ try {
399
+ n(Object.freeze({ ...t() }));
400
+ } catch (e) {
401
+ try {
402
+ r(e);
403
+ } catch {}
404
+ }
405
+ return () => {
406
+ i?.delete(a), i?.size === 0 && V.delete(e);
407
+ };
408
+ }
409
+ //#endregion
410
+ //#region packages/docx/src/document-layout-view.ts
411
+ var U = /* @__PURE__ */ new WeakMap(), Nt = /* @__PURE__ */ new WeakMap(), Pt = Symbol("docxLayoutViewRequester");
412
+ function W(e) {
413
+ let t = w(e), n = t.activeLayoutOptions;
414
+ return {
415
+ showTrackedChanges: n?.showTrackedChanges === !0,
416
+ currentDate: n?.currentDateMs ?? t.defaultCurrentDateMs
417
+ };
418
+ }
419
+ async function G(e, t, n) {
420
+ let r = w(e), i = E(t.currentDate, r.defaultCurrentDateMs, t.showTrackedChanges === !0), a = Object.freeze({
421
+ showTrackedChanges: i.showTrackedChanges === !0,
422
+ currentDate: i.currentDateMs
423
+ }), o = {
424
+ showTrackedChanges: a.showTrackedChanges,
425
+ currentDate: a.currentDate,
426
+ [Pt]: n
427
+ };
428
+ await e.setLayoutView(o);
429
+ let s = W(e);
430
+ return s.currentDate === a.currentDate && s.showTrackedChanges === a.showTrackedChanges;
431
+ }
432
+ function Ft(e, t) {
433
+ let n = Object.freeze({ ...W(e) }), r = (Nt.get(e) ?? 0) + 1;
434
+ Nt.set(e, r);
435
+ let i = Object.freeze({
436
+ view: n,
437
+ generation: r,
438
+ requester: t
439
+ });
440
+ for (let t of [...U.get(e) ?? []]) try {
441
+ t.notify(i);
442
+ } catch (e) {
443
+ try {
444
+ t.report(e);
445
+ } catch {}
446
+ }
447
+ }
448
+ function It(e, t, n) {
449
+ let r = U.get(e);
450
+ r || (r = /* @__PURE__ */ new Set(), U.set(e, r));
451
+ let i = Object.freeze({
452
+ notify: t,
453
+ report: n
454
+ });
455
+ return r.add(i), () => {
456
+ r?.delete(i), r?.size === 0 && U.delete(e);
457
+ };
458
+ }
459
+ //#endregion
460
+ //#region packages/docx/src/document.ts
461
+ function Lt(e, t) {
462
+ return e !== null && e.currentDateMs === t.currentDateMs && e.showTrackedChanges === !0 == (t.showTrackedChanges === !0);
463
+ }
464
+ function Rt() {
465
+ let e, t;
466
+ return {
467
+ promise: new Promise((n, r) => {
468
+ e = n, t = r;
469
+ }),
470
+ resolve: e,
471
+ reject: t
472
+ };
473
+ }
474
+ var zt = Object.freeze([]), Bt = Object.freeze([]), Vt = Object.freeze({
475
+ comments: Object.freeze([]),
476
+ revisions: Object.freeze([])
477
+ });
478
+ function K(e, t) {
479
+ return Ee({
480
+ comments: e,
481
+ revisions: t
482
+ }, "DOCX review metadata");
483
+ }
484
+ var q = class e {
485
+ _metrics = null;
486
+ _document = null;
487
+ _source = null;
488
+ _meta = null;
489
+ _review = Vt;
490
+ _layoutLifecycle = new be();
491
+ _layoutObservers = new Ce();
492
+ _layoutCompletion = null;
493
+ _layoutAbort = null;
494
+ _bookmarkPages = null;
495
+ _commentAnchorRanges = null;
496
+ _revisionAnchorRanges = null;
497
+ _reviewProjectionIndex = null;
498
+ _parseRequestId = null;
499
+ _progressive = null;
500
+ _parseWatchdog;
501
+ _parseWatchdogMs;
502
+ _layoutViewGeneration = 0;
503
+ _mode = "main";
504
+ _threeD;
505
+ _regionMap;
506
+ _chartEx;
507
+ _worker;
508
+ _bridge;
509
+ _rawParts = new ve({
510
+ maxEntries: 64,
511
+ maxBytes: i
512
+ });
513
+ _embeddedFontFaces = [];
514
+ _googleFontFaces = [];
515
+ _localMetricFontFaces = [];
516
+ _fetchImage = (e, t) => this.getImage(e, t);
517
+ constructor(e, t, n, r) {
518
+ this._worker = e, this._mode = t, De(this, n), this._bridge = new f(this._worker, {
519
+ correlate: (e) => "protocol" in e && e.protocol === "ooxml-pull-v1" ? e.requestId : "id" in e ? e.id : void 0,
520
+ onUnsolicited: (e) => this._onWorkerLayoutPush(e),
521
+ toError: (e) => {
522
+ if (!("protocol" in e || e.type !== "error")) return Object.assign(a(e), {
523
+ ...e.reason === void 0 ? {} : { reason: e.reason },
524
+ ...e.outgoingColumnIndex === void 0 ? {} : { outgoingColumnIndex: e.outgoingColumnIndex },
525
+ ...e.outgoingColumnCount === void 0 ? {} : { outgoingColumnCount: e.outgoingColumnCount },
526
+ ...e.incomingColumnCount === void 0 ? {} : { incomingColumnCount: e.incomingColumnCount }
527
+ });
528
+ }
529
+ });
530
+ let i = new URL(r ?? it, location.href).href;
531
+ this._bridge.post({
532
+ type: "init",
533
+ wasmUrl: i
534
+ });
535
+ }
536
+ static async load(n, i = {}) {
537
+ let a = t(i), o = Date.now(), s = i.mode ?? "main", c = new r({
538
+ enabled: !0,
539
+ format: "docx",
540
+ mode: s,
541
+ policy: a.policy,
542
+ onMetrics: a.onResourceMetrics,
543
+ emitToConsole: a.debug
544
+ });
545
+ try {
546
+ if (s === "worker" && (typeof Worker > "u" || typeof OffscreenCanvas > "u")) throw Error("mode: 'worker' requires Worker and OffscreenCanvas support");
547
+ let t;
548
+ if (typeof n == "string") {
549
+ let e = await fetch(n);
550
+ if (!e.ok) throw Error(`Failed to fetch: ${e.status} ${e.statusText}`);
551
+ t = await e.arrayBuffer();
552
+ } else t = n;
553
+ t = p(await h(t, i.password)), c.setSourceBytes(t.byteLength), c.checkpoint("container ready");
554
+ let r = s === "worker" ? (await import("./render-worker-host-DCLyw6UR.js")).createRenderWorker() : new rt(), l = s === "worker" ? Xe(i) : void 0, u = s === "worker" && !!i.progressiveLayout, d;
555
+ try {
556
+ d = new e(r, s, o, i.wasmUrl), d._metrics = c;
557
+ let n = w(d), f = E(i.currentDate, n.defaultCurrentDateMs, i.showTrackedChanges === !0);
558
+ if (n.activeLayoutOptions = f, await d._parse(t, a.policy, s === "worker" ? !!i.useGoogleFonts : !1, i.workerTimeoutMs, (e) => c.observeUsage(e), l, u ? {
559
+ onPartial: i.onLayoutPartial,
560
+ onComplete: i.onLayoutComplete,
561
+ onProgress: i.onLayoutProgress,
562
+ layoutOptions: f,
563
+ abort: new AbortController(),
564
+ firstPublication: Rt(),
565
+ published: !1,
566
+ settled: !1
567
+ } : void 0), s === "worker" && d._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 && d._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 && d._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."), d._threeD = d._mode === "worker" ? void 0 : i.threeD, i.regionMap && d._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."), d._regionMap = d._mode === "worker" ? void 0 : i.regionMap, i.chartEx && d._mode === "worker" && !l?.chartEx && console.warn("[ooxml] a custom ChartEx renderer cannot cross the worker boundary; ChartEx charts use the unsupported-chart placeholder in mode: 'worker'. Use the renderer from @silurus/ooxml/chart-ex."), d._chartEx = d._mode === "worker" ? void 0 : i.chartEx, d._mode === "main" && i.useGoogleFonts && d._document && (d._googleFontFaces = await _e(He(d._document), Pe)), d._mode === "main" && d._document?.embeddedFonts?.length) {
568
+ let e = d;
569
+ d._embeddedFontFaces = await ot(d._document, (t) => e.getFontBytes(t));
570
+ }
571
+ let p;
572
+ d._mode === "main" && d._document && (p = await Ne(d._document), d._localMetricFontFaces = p.faces);
573
+ let m;
574
+ if (d._mode === "main" && i.math && d._document && Ve(d._document) && (m = await Ue(d._document, i.math)), d._mode === "main" && d._document && d._source) {
575
+ let e = d, t = w(d);
576
+ t.services = ze(d._source, {
577
+ localMetrics: p?.metrics,
578
+ useGoogleFonts: !!i.useGoogleFonts,
579
+ embeddedFaces: d._embeddedFontFaces,
580
+ googleFaces: d._googleFontFaces,
581
+ mathResources: m?.records,
582
+ mathDrawables: m?.drawables
583
+ });
584
+ let n = t.services, r = Ae(d._source, n, t.defaultCurrentDateMs), a = d._source.fatalParse === null, o = t.activeLayoutOptions;
585
+ if (!o) throw Error("Active layout view was not recorded at load");
586
+ let s = { onProgress: i.onLayoutProgress ? (t) => e._layoutObservers.notify("onLayoutProgress", i.onLayoutProgress, { committedUnits: t }) : void 0 };
587
+ if (a && i.progressiveLayout) {
588
+ let e = r.layoutVariants, t = d, a = new AbortController();
589
+ t._layoutAbort = a;
590
+ let c = Rt(), l = null, u = !0;
591
+ t._layoutCompletion = jt(d._source.bodyLayoutInput, n, o, {
592
+ scheduler: {
593
+ ...s,
594
+ signal: a.signal
595
+ },
596
+ onPreview: (n) => {
597
+ if (!u) return;
598
+ let r = l === null, a = t._replaceMainLayoutPublication(e, o, l, n.layout);
599
+ if (a === null) {
600
+ u = !1;
601
+ return;
602
+ }
603
+ if (l = a, r) t._layoutLifecycle.begin(), H(t, {
604
+ pageCount: n.layout.pages.length,
605
+ exact: n.exact,
606
+ complete: !1
607
+ }), c.resolve();
608
+ else {
609
+ if (!t._isLayoutViewActive(o)) return;
610
+ H(t, {
611
+ pageCount: n.layout.pages.length,
612
+ exact: n.exact,
613
+ complete: !1
614
+ }), t._layoutObservers.notify("onLayoutPartial", i.onLayoutPartial, {
615
+ availableUnits: n.layout.pages.length,
616
+ exact: n.exact
617
+ });
618
+ }
619
+ }
620
+ }).then((n) => {
621
+ u && t._replaceMainLayoutPublication(e, o, l, n) === null && (u = !1), t._layoutLifecycle.succeed(), H(t, {
622
+ pageCount: t.pageCount,
623
+ exact: !0,
624
+ complete: !0
625
+ }), l !== null && t._layoutObservers.notify("onLayoutComplete", i.onLayoutComplete), c.resolve();
626
+ }).catch((e) => {
627
+ if (l === null) {
628
+ c.reject(e);
629
+ return;
630
+ }
631
+ if (e instanceof Ie) {
632
+ t._layoutLifecycle.succeed();
633
+ return;
634
+ }
635
+ let n = t._layoutLifecycle.fail(e);
636
+ H(t, {
637
+ pageCount: t.pageCount,
638
+ exact: !1,
639
+ complete: !1,
640
+ error: n
641
+ }), t._layoutObservers.notify("onLayoutComplete", i.onLayoutComplete, n);
642
+ }), await c.promise;
643
+ } else if (a && (i.sliceLayout || i.onLayoutProgress)) {
644
+ let e = await Be(d._source.bodyLayoutInput, n, o, s);
645
+ r.layoutVariants.prime(o, e);
646
+ } else r.layoutVariants.layoutFor(o);
647
+ }
648
+ return await d._resourceUsage(i.workerTimeoutMs ?? 1e3).then((e) => c.observeUsage(e), () => void 0), c.checkpoint("model and layout ready"), c.succeed({ pages: d.pageCount }), d;
649
+ } catch (e) {
650
+ let t = d;
651
+ throw m(r, t ? () => t.destroy() : void 0), e;
652
+ }
653
+ } catch (e) {
654
+ throw c.fail(e), e;
655
+ }
656
+ }
657
+ async _parse(e, t, n = !1, r, i, a, o) {
658
+ if (o) {
659
+ await this._parseProgressively(e, t, n, r, i, a, o);
660
+ return;
661
+ }
662
+ let s = await this._bridge.request((r) => this._mode === "worker" ? {
663
+ type: "parse",
664
+ id: r,
665
+ data: e,
666
+ resourcePolicy: t,
667
+ useGoogleFonts: n,
668
+ defaultCurrentDateMs: w(this).defaultCurrentDateMs,
669
+ ...this._parseViewFields(),
670
+ renderers: a
671
+ } : {
672
+ type: "parse",
673
+ id: r,
674
+ data: e,
675
+ resourcePolicy: t
676
+ }, [e], { timeoutMs: r });
677
+ if ("protocol" in s) throw Error("DOCX parse open returned a pull-protocol response");
678
+ if (this._mode === "worker") if ("usage" in s && s.usage && i?.(s.usage), s.type === "mainThreadVerticalFallback") {
679
+ let e = await D(this._bridge.transport(O), s, {
680
+ timeoutMs: r,
681
+ onUsage: i
682
+ });
683
+ this._source = e.source, this._document = e.document, this._meta = null, this._mode = "main";
684
+ } else this._meta = s.meta;
685
+ else {
686
+ let e = s, t = await D(this._bridge.transport(O), e, {
687
+ timeoutMs: r,
688
+ onUsage: i
689
+ });
690
+ this._source = t.source, this._document = t.document;
691
+ }
692
+ this._review = K(this._meta?.comments ?? this._document?.comments ?? [], this._meta?.revisions ?? this._document?.revisions ?? []);
693
+ }
694
+ _onWorkerLayoutPush(e) {
695
+ if (!("forId" in e) || e.forId !== this._parseRequestId) return;
696
+ this._rearmParseWatchdog();
697
+ let t = this._progressive;
698
+ if (t?.settled) return;
699
+ if (e.type === "layoutProgress") {
700
+ this._layoutObservers.notify("onLayoutProgress", t?.onProgress, { committedUnits: e.committedPages });
701
+ return;
702
+ }
703
+ if (e.type !== "layoutPartial" || !t) return;
704
+ let n = !t.published || this._isLayoutViewActive(t.layoutOptions);
705
+ if (n && this._applyLayoutPartial(e.partial), t.published) {
706
+ if (!n) return;
707
+ H(this, {
708
+ pageCount: e.partial.pageCount,
709
+ exact: e.partial.exact,
710
+ complete: !1
711
+ }), this._layoutObservers.notify("onLayoutPartial", t.onPartial, {
712
+ availableUnits: e.partial.pageCount,
713
+ exact: e.partial.exact
714
+ });
715
+ return;
716
+ }
717
+ t.published = !0, this._layoutLifecycle.begin(), H(this, {
718
+ pageCount: e.partial.pageCount,
719
+ exact: e.partial.exact,
720
+ complete: !1
721
+ }), t.firstPublication.resolve();
722
+ }
723
+ _applyLayoutPartial(e) {
724
+ let t = e.review ?? this._meta;
725
+ this._meta = {
726
+ pageCount: e.pageCount,
727
+ pageSizes: e.pageSizes,
728
+ bookmarkPages: e.bookmarkPages,
729
+ revisions: t?.revisions ?? [],
730
+ comments: t?.comments ?? [],
731
+ footnotes: t?.footnotes ?? [],
732
+ endnotes: t?.endnotes ?? [],
733
+ commentAnchorRanges: e.commentAnchorRanges,
734
+ revisionAnchorRanges: e.revisionAnchorRanges
735
+ }, e.review && (this._review = K(e.review.comments, e.review.revisions)), this._invalidateLayoutDerivedCaches();
736
+ }
737
+ _onAuthoritativeMeta(e) {
738
+ this._clearParseWatchdog();
739
+ let t = this._progressive;
740
+ if (!t?.settled) {
741
+ if (!t || this._isLayoutViewActive(t.layoutOptions) || !this._meta) this._meta = e;
742
+ else {
743
+ let t = this._meta;
744
+ this._meta = {
745
+ ...e,
746
+ pageCount: t.pageCount,
747
+ pageSizes: t.pageSizes,
748
+ bookmarkPages: t.bookmarkPages,
749
+ commentAnchorRanges: t.commentAnchorRanges,
750
+ revisionAnchorRanges: t.revisionAnchorRanges
751
+ };
752
+ }
753
+ this._invalidateLayoutDerivedCaches(), this._review = K(e.comments, e.revisions), t && (t.settled = !0, this._layoutLifecycle.succeed(), H(this, {
754
+ pageCount: this.pageCount,
755
+ exact: !0,
756
+ complete: !0
757
+ }), t.firstPublication.resolve(), t.published && this._layoutObservers.notify("onLayoutComplete", t.onComplete));
758
+ }
759
+ }
760
+ _invalidateLayoutDerivedCaches() {
761
+ this._bookmarkPages = null, this._commentAnchorRanges = null, this._revisionAnchorRanges = null, this._reviewProjectionIndex = null;
762
+ }
763
+ _replaceMainLayoutPublication(e, t, n, r) {
764
+ let i = e.replaceIfCurrent(t, n, r);
765
+ return i !== null && this._isLayoutViewActive(t) && this._invalidateLayoutDerivedCaches(), i;
766
+ }
767
+ _isLayoutViewActive(e) {
768
+ return Lt(w(this).activeLayoutOptions, e);
769
+ }
770
+ _rearmParseWatchdog() {
771
+ this._parseWatchdogMs !== void 0 && (clearTimeout(this._parseWatchdog), this._parseWatchdog = setTimeout(() => this._onParseWentSilent(), this._parseWatchdogMs));
772
+ }
773
+ _clearParseWatchdog() {
774
+ clearTimeout(this._parseWatchdog), this._parseWatchdog = void 0, this._parseWatchdogMs = void 0;
775
+ }
776
+ _onParseWentSilent() {
777
+ let e = this._progressive, t = this._parseWatchdogMs;
778
+ this._clearParseWatchdog();
779
+ let n = /* @__PURE__ */ Error(`worker layout produced no progress for ${t}ms`);
780
+ e && this._failWorkerProgressive(e, n), this._bridge.terminate();
781
+ }
782
+ _failWorkerProgressive(e, t) {
783
+ if (e.settled) return;
784
+ if (e.settled = !0, this._clearParseWatchdog(), !e.published) {
785
+ e.firstPublication.reject(t);
786
+ return;
787
+ }
788
+ let n = this._layoutLifecycle.fail(t);
789
+ H(this, {
790
+ pageCount: this.pageCount,
791
+ exact: !1,
792
+ complete: !1,
793
+ error: n
794
+ }), this._layoutObservers.notify("onLayoutComplete", e.onComplete, n);
795
+ }
796
+ _parseViewFields() {
797
+ let e = w(this), t = e.activeLayoutOptions;
798
+ return t ? {
799
+ ...t.currentDateMs === e.defaultCurrentDateMs ? {} : { currentDateMs: t.currentDateMs },
800
+ ...t.showTrackedChanges === !0 ? { showTrackedChanges: !0 } : {}
801
+ } : {};
802
+ }
803
+ async _parseProgressively(e, t, n, r, i, a, o) {
804
+ this._progressive = o, this._layoutAbort = o.abort, this._parseWatchdogMs = r, this._layoutCompletion = this._bridge.request((r) => (this._parseRequestId = r, {
805
+ type: "parse",
806
+ id: r,
807
+ data: e,
808
+ resourcePolicy: t,
809
+ useGoogleFonts: n,
810
+ defaultCurrentDateMs: w(this).defaultCurrentDateMs,
811
+ ...this._parseViewFields(),
812
+ renderers: a,
813
+ progressiveLayout: !0
814
+ }), [e], { timeoutMs: !1 }).then(async (e) => {
815
+ if (this._parseRequestId = null, "protocol" in e) throw Error("DOCX parse open returned a pull-protocol response");
816
+ if ("usage" in e && e.usage && i?.(e.usage), e.type === "mainThreadVerticalFallback") {
817
+ this._clearParseWatchdog(), o.settled = !0, this._progressive = null, this._layoutAbort = null;
818
+ let t = await D(this._bridge.transport(O), e, {
819
+ timeoutMs: r,
820
+ onUsage: i
821
+ });
822
+ this._source = t.source, this._document = t.document, this._meta = null, this._mode = "main", this._review = K(t.document.comments ?? [], t.document.revisions ?? []), o.firstPublication.resolve();
823
+ return;
824
+ }
825
+ this._onAuthoritativeMeta(e.meta);
826
+ }, (e) => {
827
+ if (this._parseRequestId = null, this._clearParseWatchdog(), !o.settled) {
828
+ if (o.abort.signal.aborted) {
829
+ o.settled = !0, this._layoutLifecycle.succeed(), o.firstPublication.resolve();
830
+ return;
831
+ }
832
+ this._failWorkerProgressive(o, e);
833
+ }
834
+ }), this._rearmParseWatchdog(), await o.firstPublication.promise;
835
+ }
836
+ destroy() {
837
+ this._layoutAbort?.abort(), this._layoutAbort = null, this._clearParseWatchdog(), this._parseRequestId = null, this._progressive = null, this._layoutViewGeneration++, this._bridge.terminate(), this._document = null, this._source = null, this._meta = null, this._review = Vt, w(this).services = null, this._bookmarkPages = null, this._commentAnchorRanges = null, this._revisionAnchorRanges = null, this._reviewProjectionIndex = null, this._rawParts.clear(), this._embeddedFontFaces.length > 0 && (xe(this._embeddedFontFaces), this._embeddedFontFaces = []), this._googleFontFaces.length > 0 && (ge(this._googleFontFaces), this._googleFontFaces = []), this._localMetricFontFaces.length > 0 && (Le(this._localMetricFontFaces), this._localMetricFontFaces = []), l(this._fetchImage), u(this._fetchImage);
838
+ }
839
+ async getImage(e, t) {
840
+ return this._rawParts.get(e, t, () => this._bridge.request((t) => ({
841
+ type: "extractImage",
842
+ id: t,
843
+ path: e
844
+ })).then((e) => {
845
+ let n = e.bytes;
846
+ return new Blob([n], { type: t });
847
+ }));
848
+ }
849
+ async getFontBytes(e) {
850
+ let t = (await this._bridge.request((t) => ({
851
+ type: "extractImage",
852
+ id: t,
853
+ path: e
854
+ }))).bytes;
855
+ return new Uint8Array(t);
856
+ }
857
+ async _resourceUsage(e) {
858
+ return (await this._bridge.request((e) => ({
859
+ type: "resourceUsage",
860
+ id: e
861
+ }), void 0, { timeoutMs: e })).usage;
862
+ }
863
+ async getResourceMetrics() {
864
+ let e = this._metrics;
865
+ if (!e) throw Error("Document not loaded");
866
+ return d(e, (e) => this._resourceUsage(e));
867
+ }
868
+ async toMarkdown() {
869
+ return (await this._bridge.request((e) => ({
870
+ type: "toMarkdown",
871
+ id: e
872
+ }))).markdown;
873
+ }
874
+ get pageCount() {
875
+ return this._meta ? this._meta.pageCount : this._document ? this._getLayout()?.pages.length ?? 0 : 0;
876
+ }
877
+ get layoutComplete() {
878
+ return this._layoutLifecycle.complete;
879
+ }
880
+ async waitUntilLayoutComplete() {
881
+ this._layoutCompletion && await this._layoutCompletion, this._layoutLifecycle.throwIfFailed();
882
+ }
883
+ get mode() {
884
+ return this._mode;
885
+ }
886
+ get document() {
887
+ 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");
888
+ if (!this._document) throw Error("Document not loaded");
889
+ return this._document;
890
+ }
891
+ get comments() {
892
+ return this._reviewSnapshot().comments;
893
+ }
894
+ get revisions() {
895
+ return this._reviewSnapshot().revisions;
896
+ }
897
+ commentAnchorRanges() {
898
+ if (this._meta) return this._meta.commentAnchorRanges ?? zt;
899
+ if (!this._document || !this._source) return [];
900
+ let e = this._reviewSnapshot().comments;
901
+ if (e.length === 0) return zt;
902
+ let t = w(this), n = t.services;
903
+ if (!n) throw Error("Document layout services are not initialized");
904
+ let r = T(n);
905
+ if (!r) throw Error("Document layout variant store is not initialized");
906
+ let i = t.activeLayoutOptions, a = i ? r.layoutFor(i) : r.defaultLayout;
907
+ this._reviewProjectionIndex ??= Ke(a);
908
+ let o = this._layoutLifecycle?.complete ?? !0 ? void 0 : { completedSourceKeys: this._reviewProjectionIndex.completedSourceKeys };
909
+ return this._commentAnchorRanges ??= et(e, this._source, this._reviewProjectionIndex.renderedRunIndex, o), this._commentAnchorRanges;
910
+ }
911
+ revisionAnchorRanges() {
912
+ if (this._meta) return this._meta.revisionAnchorRanges ?? Bt;
913
+ if (!this._document || !this._source) return [];
914
+ let e = this._reviewSnapshot().revisions;
915
+ if (e.length === 0) return Bt;
916
+ let t = w(this), n = t.services;
917
+ if (!n) throw Error("Document layout services are not initialized");
918
+ let r = T(n);
919
+ if (!r) throw Error("Document layout variant store is not initialized");
920
+ let i = t.activeLayoutOptions, a = i ? r.layoutFor(i) : r.defaultLayout;
921
+ this._reviewProjectionIndex ??= Ke(a);
922
+ let o = this._layoutLifecycle?.complete ?? !0 ? void 0 : { completedSourceKeys: this._reviewProjectionIndex.completedSourceKeys };
923
+ return this._revisionAnchorRanges ??= Ot(e, this._source, this._reviewProjectionIndex.renderedRunIndex, o), this._revisionAnchorRanges;
924
+ }
925
+ _reviewSnapshot() {
926
+ return this._review ||= K(this._meta?.comments ?? this._document?.comments ?? [], this._meta?.revisions ?? this._document?.revisions ?? []), this._review;
927
+ }
928
+ get footnotes() {
929
+ return this._meta?.footnotes ?? this._document?.footnotes ?? [];
930
+ }
931
+ get endnotes() {
932
+ return this._meta?.endnotes ?? this._document?.endnotes ?? [];
933
+ }
934
+ _getLayout() {
935
+ if (!this._document) return null;
936
+ let e = w(this), t = e.services;
937
+ if (!t) throw Error("Document layout services are not initialized");
938
+ let n = T(t);
939
+ if (!n) throw Error("Document layout variant store is not initialized");
940
+ let r = e.activeLayoutOptions;
941
+ return r ? n.layoutFor(r) : n.defaultLayout;
942
+ }
943
+ async setLayoutView(e = {}) {
944
+ let t = e[Pt], n = w(this), r = E(e.currentDate, n.defaultCurrentDateMs, e.showTrackedChanges === !0), i = ++this._layoutViewGeneration, a = n.activeLayoutOptions;
945
+ if (!Lt(a, r)) {
946
+ if (this._mode === "worker" && this._meta) {
947
+ let e = await this._bridge.request((e) => ({
948
+ type: "selectLayoutView",
949
+ id: e,
950
+ currentDateMs: r.currentDateMs,
951
+ showTrackedChanges: r.showTrackedChanges === !0
952
+ }));
953
+ if (i !== this._layoutViewGeneration) return;
954
+ let a = e;
955
+ n.activeLayoutOptions = r, this._meta = {
956
+ ...this._meta,
957
+ ...a.meta
958
+ }, this._invalidateLayoutDerivedCaches(), Ft(this, t);
959
+ return;
960
+ }
961
+ n.activeLayoutOptions = r, this._invalidateLayoutDerivedCaches(), Ft(this, t);
962
+ }
963
+ }
964
+ _getBookmarkPages() {
965
+ if (this._bookmarkPages) return this._bookmarkPages;
966
+ if (this._meta) return this._bookmarkPages = new Map(this._meta.bookmarkPages), this._bookmarkPages;
967
+ let e = this._getLayout();
968
+ return e ? (this._bookmarkPages = at(e), this._bookmarkPages) : null;
969
+ }
970
+ getBookmarkPage(e) {
971
+ return this._getBookmarkPages()?.get(e);
972
+ }
973
+ pageSize(e) {
974
+ if (this._meta) {
975
+ let t = this._meta.pageSizes, n = t[Math.max(0, Math.min(e, t.length - 1))];
976
+ return n ? {
977
+ widthPt: n.widthPt,
978
+ heightPt: n.heightPt
979
+ } : {
980
+ widthPt: 0,
981
+ heightPt: 0
982
+ };
983
+ }
984
+ if (!this._document) return {
985
+ widthPt: 0,
986
+ heightPt: 0
987
+ };
988
+ let t = this._getLayout();
989
+ if (!t || t.pages.length === 0) return {
990
+ widthPt: 0,
991
+ heightPt: 0
992
+ };
993
+ let n = Math.max(0, Math.min(e, t.pages.length - 1)), r = t.pages[n].geometry;
994
+ return {
995
+ widthPt: r.widthPt,
996
+ heightPt: r.heightPt
997
+ };
998
+ }
999
+ _withActiveView(e) {
1000
+ let t = w(this).activeLayoutOptions;
1001
+ if (!t) return e;
1002
+ let n = { ...e };
1003
+ return e.currentDate === void 0 && (n.currentDate = t.currentDateMs), e.showTrackedChanges === void 0 && t.showTrackedChanges === !0 && (n.showTrackedChanges = !0), n;
1004
+ }
1005
+ renderPage(e, t, n = {}) {
1006
+ if (this._mode === "worker") throw Error("renderPage(canvas) is unavailable in mode: 'worker'; use renderPageToBitmap() and paint it via an ImageBitmapRenderingContext");
1007
+ if (!this._source) throw Error("Document not loaded");
1008
+ return Me(this._source, e, t, {
1009
+ ...this._withActiveView(n),
1010
+ fetchImage: this._fetchImage,
1011
+ layoutServices: w(this).services ?? void 0,
1012
+ defaultCurrentDateMs: w(this).defaultCurrentDateMs,
1013
+ threeD: this._threeD,
1014
+ regionMap: this._regionMap,
1015
+ chartEx: this._chartEx
1016
+ });
1017
+ }
1018
+ async renderPageToBitmap(e, t = {}) {
1019
+ let { onTextRun: n, ...r } = t, i = {
1020
+ ...this._withActiveView(r),
1021
+ dpr: r.dpr ?? c()
1022
+ };
1023
+ if (this._mode === "worker") {
1024
+ let t = await this._bridge.request((t) => ({
1025
+ type: "renderPage",
1026
+ id: t,
1027
+ pageIndex: e,
1028
+ opts: i
1029
+ }));
1030
+ if (n) for (let e of t.runs) n(e);
1031
+ return t.bitmap;
1032
+ }
1033
+ let a = new OffscreenCanvas(1, 1);
1034
+ return await this.renderPage(a, e, {
1035
+ ...i,
1036
+ onTextRun: n
1037
+ }), a.transferToImageBitmap();
1038
+ }
1039
+ async collectPageRuns(e, t = {}) {
1040
+ let n = { ...this._withActiveView(t) };
1041
+ if (this._mode === "worker") return (await this._bridge.request((t) => ({
1042
+ type: "collectRuns",
1043
+ id: t,
1044
+ pageIndex: e,
1045
+ opts: n
1046
+ }))).runs;
1047
+ let r = w(this), i = r.services;
1048
+ if (!i) throw Error("Document layout services are not initialized");
1049
+ return qe(i, e, {
1050
+ currentDate: n.currentDate,
1051
+ defaultCurrentDateMs: r.defaultCurrentDateMs,
1052
+ width: n.width,
1053
+ showTrackedChanges: n.showTrackedChanges
1054
+ });
1055
+ }
1056
+ async getCommentThreads(e, t = {}) {
1057
+ let { includeResolved: n, ...r } = t, i = await this.collectPageRuns(e, r);
1058
+ return $e(this.comments, this.commentAnchorRanges(), i, { includeResolved: n });
1059
+ }
1060
+ async getElementContextAt(e, t, n = {}) {
1061
+ let r = this._withActiveView(n);
1062
+ if (this._mode === "worker") return (await this._bridge.request((n) => ({
1063
+ type: "hitTestElement",
1064
+ id: n,
1065
+ pageIndex: e,
1066
+ point: t,
1067
+ opts: r
1068
+ }))).context;
1069
+ let i = w(this), a = i.services;
1070
+ if (!a) throw Error("Document layout services are not initialized");
1071
+ return Ct(a, e, t, {
1072
+ ...r,
1073
+ defaultCurrentDateMs: i.defaultCurrentDateMs
1074
+ });
1075
+ }
1076
+ };
1077
+ //#endregion
1078
+ //#region packages/docx/src/tate-chu-yoko-overlay.ts
1079
+ function Ht(e, t) {
1080
+ if (!e.eastAsianVert) return 1;
1081
+ let n = t(e.text);
1082
+ return !(n > 0) || e.w >= n ? 1 : e.w / n;
1083
+ }
1084
+ //#endregion
1085
+ //#region packages/docx/src/text-layer.ts
1086
+ function J(e, t, n) {
1087
+ 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);
1088
+ }
1089
+ function Y(e, t, n, r, i, a, o) {
1090
+ e.innerHTML = "", J(e, "ooxmlSelectionSurface", "docx"), J(e, "pageIndex", o === void 0 ? void 0 : String(o));
1091
+ let s = e.ownerDocument ?? document;
1092
+ for (let [o, c] of t.entries()) {
1093
+ let t = s.createElement("span");
1094
+ J(t, "ooxmlSelectionRun", "docx"), J(t, "runIndex", String(o)), c.paragraphId !== void 0 && J(t, "paragraphId", c.paragraphId), c.source !== void 0 && (J(t, "sourceStory", c.source.story), J(t, "sourceStoryInstance", c.source.storyInstance), J(t, "sourcePath", JSON.stringify(c.source.path))), t.textContent = c.text;
1095
+ let l = c.transform ?? "";
1096
+ if (a && c.eastAsianVert) {
1097
+ let e = Ht(c, a(c.font));
1098
+ e !== 1 && (l = `${l ? `${l} ` : ""}scaleX(${e})`);
1099
+ }
1100
+ 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`;
1101
+ t.style.cssText = `position:absolute;left:${A(c.x, n)};top:${A(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) => {
1102
+ e.preventDefault(), i(d);
1103
+ })), e.appendChild(t);
1104
+ }
1105
+ }
1106
+ function X(e, t, n, r, i, a, o = {}) {
1107
+ e.innerHTML = "";
1108
+ let s = o.match ?? "rgba(255, 214, 0, 0.42)", c = o.active ?? "rgba(255, 140, 0, 0.55)";
1109
+ for (let o of n) {
1110
+ let n = o.active ? c : s;
1111
+ for (let s of o.slices) {
1112
+ let o = t[s.runIndex];
1113
+ if (!o) continue;
1114
+ let c = a(o.font), l = Ze(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, _ = Ht(o, c), ee = h * _, v = g * _;
1115
+ if (v <= 0) continue;
1116
+ let y = document.createElement("div"), te = o.transform ? `transform:${o.transform};transform-origin:top left;` : "";
1117
+ y.style.cssText = `position:absolute;left:${A(o.x + ee, r)};top:${A(o.y, i)};width:${A(v, r)};height:${A(o.h, i)};` + te + `background:${n};pointer-events:none;`, e.appendChild(y);
1118
+ }
1119
+ }
1120
+ }
1121
+ //#endregion
1122
+ //#region packages/docx/src/find.ts
1123
+ var Ut = class {
1124
+ _pageRuns = /* @__PURE__ */ new Map();
1125
+ _matches = [];
1126
+ _active = -1;
1127
+ _generation = 0;
1128
+ _runsRevision = 0;
1129
+ constructor(e, t) {
1130
+ this._pageCount = e, this._collectPageRuns = t;
1131
+ }
1132
+ invalidate() {
1133
+ this._generation++, this._runsRevision++, this._pageRuns.clear(), this._matches = [], this._active = -1;
1134
+ }
1135
+ pageRuns(e) {
1136
+ return this._pageRuns.get(e);
1137
+ }
1138
+ setPageRuns(e, t) {
1139
+ this._runsRevision++, this._pageRuns.set(e, t);
1140
+ }
1141
+ _matchAt(e) {
1142
+ return this._matches[e];
1143
+ }
1144
+ pageHighlights(e) {
1145
+ let t = [];
1146
+ for (let n = 0; n < this._matches.length; n++) {
1147
+ let r = this._matches[n];
1148
+ r.page === e && t.push({
1149
+ slices: r.slices,
1150
+ active: n === this._active
1151
+ });
1152
+ }
1153
+ return t;
1154
+ }
1155
+ activePage() {
1156
+ let e = this._matchAt(this._active);
1157
+ return e ? e.page : null;
1158
+ }
1159
+ matches() {
1160
+ return this._matches.map((e, t) => ({
1161
+ matchIndex: t,
1162
+ text: e.text,
1163
+ location: { page: e.page }
1164
+ }));
1165
+ }
1166
+ async find(e, t = {}) {
1167
+ let n = ++this._generation;
1168
+ if (e.length === 0) return this._runsRevision++, this._pageRuns.clear(), this._matches = [], this._active = -1, [];
1169
+ let r = this._runsRevision, i = new Map(this._pageRuns), a = this._pageCount();
1170
+ for (let e = 0; e < a; e++) {
1171
+ let t = i.get(e);
1172
+ if (!t) {
1173
+ try {
1174
+ t = await this._collectPageRuns(e);
1175
+ } catch (e) {
1176
+ if (n !== this._generation) return [];
1177
+ throw e;
1178
+ }
1179
+ if (n !== this._generation) return [];
1180
+ i.set(e, t);
1181
+ }
1182
+ }
1183
+ if (n !== this._generation) return [];
1184
+ let o = r === this._runsRevision ? i : new Map([...i, ...this._pageRuns]), s = [];
1185
+ for (let n = 0; n < a; n++) {
1186
+ let r = o.get(n) ?? [], i = ie(r);
1187
+ for (let a of re(i, e, t)) {
1188
+ let e = a.slices.map((e) => r[e.runIndex].text.slice(e.start, e.end)).join("");
1189
+ s.push({
1190
+ page: n,
1191
+ text: e,
1192
+ slices: a.slices
1193
+ });
1194
+ }
1195
+ }
1196
+ return this._runsRevision++, this._pageRuns = o, this._matches = s, this._active = -1, this.matches();
1197
+ }
1198
+ next() {
1199
+ return this._active = te(this._active, this._matches.length), this._activePublic();
1200
+ }
1201
+ prev() {
1202
+ return this._active = se(this._active, this._matches.length), this._activePublic();
1203
+ }
1204
+ _activePublic() {
1205
+ let e = this._matchAt(this._active);
1206
+ return e ? {
1207
+ matchIndex: this._active,
1208
+ text: e.text,
1209
+ location: { page: e.page }
1210
+ } : null;
1211
+ }
1212
+ };
1213
+ //#endregion
1214
+ //#region packages/docx/src/selection-context.ts
1215
+ function Wt(e, t, n, r, i = {}) {
1216
+ let a = e.find((e) => e.id === n && e.parentId === void 0);
1217
+ if (!a) return null;
1218
+ let o = new Map(e.map((e) => [e.id, e])), s = e.filter((e) => {
1219
+ if (e.parentId === void 0) return !1;
1220
+ let t = e, n = /* @__PURE__ */ new Set();
1221
+ for (; t.parentId !== void 0 && !n.has(t.id);) {
1222
+ n.add(t.id);
1223
+ let e = o.get(t.parentId);
1224
+ if (!e) return !1;
1225
+ if (e.id === a.id) return !0;
1226
+ t = e;
1227
+ }
1228
+ return !1;
1229
+ }), c = Se({
1230
+ id: a.id,
1231
+ author: a.author,
1232
+ date: a.date,
1233
+ text: a.paragraphs?.join("\n") ?? a.text,
1234
+ status: a.resolved ? "resolved" : "active"
1235
+ }, s.map((e) => ({
1236
+ id: e.id,
1237
+ author: e.author,
1238
+ date: e.date,
1239
+ text: e.paragraphs?.join("\n") ?? e.text,
1240
+ status: e.resolved ? "resolved" : "active"
1241
+ })), i.maxTextCharacters), l = t.find((e) => e.commentId === n)?.source;
1242
+ return Object.freeze({
1243
+ format: "docx",
1244
+ kind: "comment",
1245
+ pageIndex: r,
1246
+ commentId: n,
1247
+ ...l ? { source: Object.freeze({
1248
+ ...l,
1249
+ path: Object.freeze([...l.path])
1250
+ }) } : {},
1251
+ thread: c.thread,
1252
+ truncated: c.truncated,
1253
+ truncationReasons: c.truncated ? ["text"] : [],
1254
+ textCharacters: c.textCharacters,
1255
+ maxTextCharacters: c.maxTextCharacters
1256
+ });
1257
+ }
1258
+ function Z(e) {
1259
+ if (e === void 0 || !/^\d+$/.test(e)) return null;
1260
+ let t = Number(e);
1261
+ return Number.isSafeInteger(t) ? t : null;
1262
+ }
1263
+ function Gt(e) {
1264
+ for (let t = e; t; t = t.parentElement) {
1265
+ let e = Z(t.dataset.pageIndex);
1266
+ if (e !== null) return e;
1267
+ }
1268
+ return null;
1269
+ }
1270
+ var Kt = new Set([
1271
+ "body",
1272
+ "header",
1273
+ "footer",
1274
+ "footnote",
1275
+ "endnote",
1276
+ "textbox"
1277
+ ]);
1278
+ function qt(e) {
1279
+ let t = e.dataset.sourceStory, n = e.dataset.sourceStoryInstance, r = e.dataset.sourcePath;
1280
+ if (!t || !Kt.has(t) || !n || !r) return null;
1281
+ try {
1282
+ let e = JSON.parse(r);
1283
+ return !Array.isArray(e) || e.length === 0 || e.length > 32 || !e.every((e) => Number.isSafeInteger(e) && e >= 0) ? null : {
1284
+ story: t,
1285
+ storyInstance: n,
1286
+ path: [...e]
1287
+ };
1288
+ } catch {
1289
+ return null;
1290
+ }
1291
+ }
1292
+ function Q(e, t, n = {}) {
1293
+ let r = le(e, t, (e) => {
1294
+ let t = Gt(e), n = Z(e.dataset.runIndex);
1295
+ return t === null || n === null ? null : {
1296
+ pageIndex: t,
1297
+ runIndex: n,
1298
+ ...e.dataset.paragraphId === void 0 ? {} : { paragraphId: e.dataset.paragraphId },
1299
+ ...qt(e) === null ? {} : { source: qt(e) }
1300
+ };
1301
+ }, {
1302
+ maxChars: n.maxTextCharacters,
1303
+ maxLocators: n.maxRunLocators
1304
+ });
1305
+ if (!r) return null;
1306
+ let i = [...r.locators].sort((e, t) => e.pageIndex - t.pageIndex || e.runIndex - t.runIndex);
1307
+ return {
1308
+ format: "docx",
1309
+ kind: "text",
1310
+ text: r.text,
1311
+ pageIndexes: [...new Set(i.map((e) => e.pageIndex))],
1312
+ paragraphIds: [...new Set(i.flatMap((e) => e.paragraphId ? [e.paragraphId] : []))],
1313
+ runs: i,
1314
+ truncated: r.truncated,
1315
+ truncationReasons: r.truncationReasons,
1316
+ textCharacters: r.textCharacters,
1317
+ maxTextCharacters: r.maxTextCharacters,
1318
+ maxRunLocators: r.maxLocators
1319
+ };
1320
+ }
1321
+ //#endregion
1322
+ //#region packages/docx/src/focused-view-runtime.ts
1323
+ function $(e, t, n, r, i) {
1324
+ return r === "worker" ? e.renderPageToBitmap(n, i) : e.renderPage(t, n, i);
1325
+ }
1326
+ //#endregion
1327
+ //#region packages/docx/src/viewer.ts
1328
+ var Jt = Symbol("DocxViewer.borrowedDocument"), Yt = class e {
1329
+ _documentOwner;
1330
+ get _doc() {
1331
+ return this._documentOwner.current;
1332
+ }
1333
+ _borrowed;
1334
+ _hostWindow;
1335
+ _currentPage = 0;
1336
+ _scale = null;
1337
+ _canvas;
1338
+ _wrapper;
1339
+ _canvasMount;
1340
+ _textLayer = null;
1341
+ _highlightLayer = null;
1342
+ _elementLayer = null;
1343
+ _find;
1344
+ _findRequestGeneration = 0;
1345
+ _measureCtx = null;
1346
+ _opts;
1347
+ _mode;
1348
+ _renderDispatcher;
1349
+ _errorRouter;
1350
+ _destroyed = !1;
1351
+ _selectionChangeListener = null;
1352
+ _selectionContextKey = "null";
1353
+ _elementContext = null;
1354
+ _elementHitGeneration = 0;
1355
+ _layoutViewGeneration = 0;
1356
+ _layoutViewPublicationGeneration = 0;
1357
+ _navigationGeneration = 0;
1358
+ _layoutUnsubscribe = null;
1359
+ _internalHyperlinkGeneration = 0;
1360
+ _layoutWaiters = /* @__PURE__ */ new Set();
1361
+ _layoutFailed = !1;
1362
+ _loadingLayer;
1363
+ _elementClickListener = null;
1364
+ _contextMenuListener = null;
1365
+ static fromDocument(t, n, r = {}) {
1366
+ let i = W(n);
1367
+ return new e(t, {
1368
+ ...r,
1369
+ currentDate: i.currentDate,
1370
+ showTrackedChanges: i.showTrackedChanges,
1371
+ [Jt]: n
1372
+ });
1373
+ }
1374
+ constructor(e, t = {}) {
1375
+ this._canvas = e, this._opts = t;
1376
+ let n = t[Jt];
1377
+ this._borrowed = n !== void 0, this._mode = x("DocxViewer", t.mode, n), this._documentOwner = new _("DocxViewer", n ?? null, !1);
1378
+ let r = e.ownerDocument?.defaultView ?? (typeof window < "u" ? window : null);
1379
+ if (!r) throw Error("DocxViewer requires a canvas with an active Window");
1380
+ this._hostWindow = r, this._canvasMount = new ue(e, {
1381
+ wrapperCssText: "position:relative;display:inline-block;vertical-align:top;",
1382
+ forceDisplayBlock: !0
1383
+ }), this._wrapper = this._canvasMount.wrapper, this._renderDispatcher = new b(e, this._mode === "worker"), this._errorRouter = new ce("DocxViewer", t.onError);
1384
+ let i = new ae(this._wrapper, t.enableTextSelection === !0, t.enableElementSelection === !0);
1385
+ this._textLayer = i.textLayer, this._highlightLayer = i.highlightLayer, this._elementLayer = i.elementLayer, this._loadingLayer = this._wrapper.ownerDocument.createElement("div"), this._loadingLayer.style.cssText = [
1386
+ "position:absolute",
1387
+ "inset:0",
1388
+ "display:none",
1389
+ "align-items:center",
1390
+ "justify-content:center",
1391
+ "background:rgba(255,255,255,0.72)",
1392
+ "pointer-events:none",
1393
+ "z-index:4"
1394
+ ].join(";"), this._loadingLayer.setAttribute("role", "status"), this._loadingLayer.setAttribute("aria-live", "polite"), this._loadingLayer.setAttribute("aria-label", "Loading page");
1395
+ let a = this._wrapper.ownerDocument.createElement("progress");
1396
+ a.setAttribute("aria-hidden", "true"), this._loadingLayer.appendChild(a), this._wrapper.insertBefore(this._loadingLayer, this._elementLayer), this._textLayer && (t.onSelectionContextChange || t.enableElementSelection) && (this._selectionChangeListener = () => this._emitSelectionContextChange(), this._wrapper.ownerDocument.addEventListener("selectionchange", this._selectionChangeListener)), t.enableElementSelection && (this._elementClickListener = (e) => {
1397
+ this._onElementClick(e).catch((e) => this._reportRenderError(e));
1398
+ }, this._wrapper.addEventListener("click", this._elementClickListener)), t.onContextMenu && (this._contextMenuListener = (e) => this._onContextMenu(e), this._wrapper.addEventListener("contextmenu", this._contextMenuListener)), this._find = new Ut(() => this.pageCount, (e) => this._collectPageRuns(e)), n && this._bindLayoutDocument(n);
1399
+ }
1400
+ async load(e) {
1401
+ if (this._destroyed) throw Error("DocxViewer is destroyed");
1402
+ if (this._borrowed) throw Error("DocxViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.");
1403
+ let t = !1;
1404
+ try {
1405
+ let n = await this._documentOwner.replace(() => q.load(e, {
1406
+ password: this._opts.password,
1407
+ useGoogleFonts: this._opts.useGoogleFonts,
1408
+ maxZipEntryBytes: this._opts.maxZipEntryBytes,
1409
+ resourceLimits: this._opts.resourceLimits,
1410
+ debug: this._opts.debug,
1411
+ onResourceMetrics: this._opts.onResourceMetrics,
1412
+ workerTimeoutMs: this._opts.workerTimeoutMs,
1413
+ wasmUrl: this._opts.wasmUrl,
1414
+ math: this._opts.math,
1415
+ threeD: this._opts.threeD,
1416
+ regionMap: this._opts.regionMap,
1417
+ chartEx: this._opts.chartEx,
1418
+ mode: this._mode,
1419
+ ...this._opts.progressiveLayout ? { progressiveLayout: !0 } : {},
1420
+ ...this._opts.sliceLayout ? { sliceLayout: !0 } : {},
1421
+ onLayoutProgress: this._opts.onLayoutProgress,
1422
+ onLayoutPartial: this._opts.onLayoutPartial,
1423
+ onLayoutComplete: this._opts.onLayoutComplete,
1424
+ ...this._opts.showTrackedChanges === !0 ? { showTrackedChanges: !0 } : {},
1425
+ ...this._opts.currentDate === void 0 ? {} : { currentDate: this._opts.currentDate }
1426
+ }), () => {
1427
+ this._invalidateElementContext(!1), t = !0, this._renderDispatcher.begin(), this._findRequestGeneration++, this._find.invalidate(), this._unbindLayoutDocument();
1428
+ });
1429
+ if (!n) return;
1430
+ if (this._destroyed) throw Error("DocxViewer is destroyed");
1431
+ this._currentPage = 0, this._bindLayoutDocument(n), this._find.invalidate(), await this._render();
1432
+ } catch (e) {
1433
+ throw this._destroyed ? Error("DocxViewer is destroyed") : e instanceof Error ? e : Error(String(e));
1434
+ }
1435
+ t && !this._destroyed && this._emitSelectionContextChange();
1436
+ }
1437
+ get pageCount() {
1438
+ return this._doc?.pageCount ?? 0;
1439
+ }
1440
+ get currentPage() {
1441
+ return this._currentPage;
1442
+ }
1443
+ get layoutComplete() {
1444
+ return this._doc?.layoutComplete ?? !0;
1445
+ }
1446
+ async waitUntilLayoutComplete() {
1447
+ await this._errorRouter.ownBackgroundLifecycle(async () => {
1448
+ await this._doc?.waitUntilLayoutComplete?.();
1449
+ });
1450
+ }
1451
+ get canvasElement() {
1452
+ return this._canvas;
1453
+ }
1454
+ async goToPage(e) {
1455
+ let t = this._doc;
1456
+ if (!t) return;
1457
+ let n = this._cancelPendingNavigation(), r = Math.max(0, Number.isNaN(e) ? 0 : Math.trunc(e));
1458
+ if (r >= this.pageCount && !this.layoutComplete) {
1459
+ this._setLoading(!0);
1460
+ try {
1461
+ await this._waitForPage(t, r, n);
1462
+ } finally {
1463
+ n === this._navigationGeneration && this._setLoading(!1);
1464
+ }
1465
+ }
1466
+ if (this._destroyed || n !== this._navigationGeneration || t !== this._doc) return;
1467
+ let i = Math.max(0, Math.min(r, this.pageCount - 1)), a = i !== this._currentPage;
1468
+ a && this._invalidateElementContext(!1), this._currentPage = i, await this._render(), a && !this._destroyed && this._emitSelectionContextChange();
1469
+ }
1470
+ async nextPage() {
1471
+ await this.goToPage(this._currentPage + 1);
1472
+ }
1473
+ async prevPage() {
1474
+ await this.goToPage(this._currentPage - 1);
1475
+ }
1476
+ _naturalWidthPx() {
1477
+ return !this._doc || this._doc.pageCount === 0 ? 0 : this._doc.pageSize(this._currentPage).widthPt * k;
1478
+ }
1479
+ _renderWidth() {
1480
+ if (this._scale === null) return this._opts.width;
1481
+ let e = this._naturalWidthPx();
1482
+ return e <= 0 ? this._opts.width : Math.round(e * this._scale);
1483
+ }
1484
+ getScale() {
1485
+ if (this._scale !== null) return this._scale;
1486
+ let e = this._naturalWidthPx();
1487
+ return e <= 0 ? 1 : this._opts.width && this._opts.width > 0 ? this._opts.width / e : 1;
1488
+ }
1489
+ _zoomMin() {
1490
+ return this._opts.zoomMin ?? .1;
1491
+ }
1492
+ _zoomMax() {
1493
+ return this._opts.zoomMax ?? 4;
1494
+ }
1495
+ async setScale(e) {
1496
+ let t = ne(e, this._zoomMin(), this._zoomMax()), n = t !== this.getScale();
1497
+ this._scale = t, await this._render(), n && this._opts.onScaleChange?.(t);
1498
+ }
1499
+ async zoomIn() {
1500
+ await this.setScale(fe(this.getScale()));
1501
+ }
1502
+ async zoomOut() {
1503
+ await this.setScale(he(this.getScale()));
1504
+ }
1505
+ async fitWidth() {
1506
+ await this._fit("width");
1507
+ }
1508
+ async fitPage() {
1509
+ await this._fit("page");
1510
+ }
1511
+ async _fit(e) {
1512
+ if (!this._doc || this._doc.pageCount === 0) return;
1513
+ let t = this._doc.pageSize(this._currentPage), n = this._fitContainer();
1514
+ if (!n) return;
1515
+ let r = g({
1516
+ contentWidth: t.widthPt * k,
1517
+ contentHeight: t.heightPt * k,
1518
+ containerWidth: n.clientWidth,
1519
+ containerHeight: n.clientHeight
1520
+ }, e);
1521
+ r <= 0 || await this.setScale(r);
1522
+ }
1523
+ _fitContainer() {
1524
+ return this._opts.container ?? this._wrapper.parentElement ?? null;
1525
+ }
1526
+ async findText(e, t = {}) {
1527
+ let n = this._doc;
1528
+ if (!n) return [];
1529
+ let r = ++this._findRequestGeneration;
1530
+ if (e.length > 0 && !n.layoutComplete && (await this._errorRouter.ownBackgroundLifecycle(() => n.waitUntilLayoutComplete()), this._destroyed || this._doc !== n || r !== this._findRequestGeneration)) return [];
1531
+ let i = await this._errorRouter.ownAwaitable(() => this._find.find(e, t));
1532
+ return this._redrawHighlights(), i;
1533
+ }
1534
+ async findNext() {
1535
+ return this._activateMatch(this._find.next());
1536
+ }
1537
+ async findPrev() {
1538
+ return this._activateMatch(this._find.prev());
1539
+ }
1540
+ clearFind() {
1541
+ this._findRequestGeneration++, this._find.invalidate(), this._redrawHighlights();
1542
+ }
1543
+ async _activateMatch(e) {
1544
+ return e ? (e.location.page === this._currentPage ? this._redrawHighlights() : await this.goToPage(e.location.page), e) : (this._redrawHighlights(), null);
1545
+ }
1546
+ _redrawHighlights() {
1547
+ let e = this._find.pageRuns(this._currentPage) ?? [];
1548
+ this._buildHighlightLayer(e);
1549
+ }
1550
+ async getResourceMetrics() {
1551
+ if (!this._doc) throw Error("Document not loaded");
1552
+ return await this._doc.getResourceMetrics();
1553
+ }
1554
+ getSelectionContext(e = {}) {
1555
+ if (this._destroyed) throw Error("DocxViewer is destroyed");
1556
+ return (this._textLayer ? Q(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null, e) : null) ?? (this._elementContext ? L(this._elementContext, e.maxTextCharacters) : null);
1557
+ }
1558
+ _emitSelectionContextChange() {
1559
+ let e = this.getSelectionContext();
1560
+ e?.kind === "text" && (this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutline());
1561
+ let t = JSON.stringify(e);
1562
+ t !== this._selectionContextKey && (this._selectionContextKey = t, this._opts.onSelectionContextChange?.(e ? structuredClone(e) : null));
1563
+ }
1564
+ _setElementContext(e) {
1565
+ this._elementContext = e ? structuredClone(e) : null, this._redrawElementOutline(), this._emitSelectionContextChange();
1566
+ }
1567
+ _invalidateElementContext(e = !0) {
1568
+ this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutline(), e && this._emitSelectionContextChange();
1569
+ }
1570
+ _redrawElementOutline() {
1571
+ let e = this._elementContext, t = this._doc;
1572
+ if (!e || !t || e.pageIndex !== this._currentPage) {
1573
+ v(this._elementLayer, null);
1574
+ return;
1575
+ }
1576
+ let n = t.pageSize(e.pageIndex);
1577
+ v(this._elementLayer, {
1578
+ x: e.bounds.xPt / n.widthPt,
1579
+ y: e.bounds.yPt / n.heightPt,
1580
+ width: e.bounds.widthPt / n.widthPt,
1581
+ height: e.bounds.heightPt / n.heightPt
1582
+ });
1583
+ }
1584
+ async _onElementClick(e) {
1585
+ this._destroyed || e.defaultPrevented || e.button !== 0 || await this._resolveContextAt(e);
1586
+ }
1587
+ _onContextMenu(e) {
1588
+ let t;
1589
+ this._opts.onContextMenu?.({
1590
+ originalEvent: e,
1591
+ getContext: () => t ??= this._resolveContextAt(e)
1592
+ });
1593
+ }
1594
+ async _resolveContextAt(e) {
1595
+ let t = this._doc;
1596
+ if (this._destroyed || !t) return null;
1597
+ if (this._textLayer && Q(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null)) return this._emitSelectionContextChange(), this._destroyed ? null : this.getSelectionContext();
1598
+ if (!this._opts.enableElementSelection) return this.getSelectionContext();
1599
+ let n = this._canvas.getBoundingClientRect();
1600
+ if (n.width <= 0 || n.height <= 0) return this._invalidateElementContext(), null;
1601
+ let r = e.clientX - n.left, i = e.clientY - n.top;
1602
+ if (r < 0 || i < 0 || r > n.width || i > n.height) return this._invalidateElementContext(), null;
1603
+ let a = ++this._elementHitGeneration, o = this._currentPage, s = t.pageSize(o), c;
1604
+ try {
1605
+ c = await t.getElementContextAt(o, {
1606
+ xPt: r / n.width * s.widthPt,
1607
+ yPt: i / n.height * s.heightPt
1608
+ }, {
1609
+ currentDate: this._opts.currentDate,
1610
+ showTrackedChanges: this._opts.showTrackedChanges,
1611
+ maxTextCharacters: N
1612
+ });
1613
+ } catch (e) {
1614
+ if (this._destroyed || a !== this._elementHitGeneration || o !== this._currentPage || t !== this._doc) return null;
1615
+ throw e;
1616
+ }
1617
+ return this._destroyed || a !== this._elementHitGeneration || o !== this._currentPage || t !== this._doc ? null : (this._setElementContext(c), this._destroyed ? null : this.getSelectionContext());
1618
+ }
1619
+ destroy() {
1620
+ this._destroyed || (this._destroyed = !0, this._findRequestGeneration++, this._layoutViewGeneration++, this._unbindLayoutDocument(), this._errorRouter.close(), this._renderDispatcher.destroy(), We(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());
1621
+ }
1622
+ async _render() {
1623
+ let e = this._renderDispatcher.begin();
1624
+ try {
1625
+ await this._renderPage(e);
1626
+ } catch (t) {
1627
+ if (!this._renderDispatcher.isCurrent(e)) return;
1628
+ throw t;
1629
+ }
1630
+ }
1631
+ _reportRenderError(e) {
1632
+ this._errorRouter.report(e);
1633
+ }
1634
+ async _renderPage(e) {
1635
+ if (!this._doc) return;
1636
+ let t = this._mode === "worker", n = this._renderWidth(), r = this._doc.pageSize(this._currentPage), i = n ?? r.widthPt * 1.3333333333333333, a = r.widthPt > 0 ? i * r.heightPt / r.widthPt : 0, o = [], s = (e) => o.push(e), c = this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1), l = {
1637
+ width: n,
1638
+ dpr: this._opts.dpr,
1639
+ defaultTextColor: this._opts.defaultTextColor,
1640
+ currentDate: this._opts.currentDate,
1641
+ showTrackedChanges: this._opts.showTrackedChanges,
1642
+ onTextRun: s
1643
+ };
1644
+ if (t) {
1645
+ let t = await $(this._doc, this._canvas, this._currentPage, "worker", l);
1646
+ if (!this._renderDispatcher.commitBitmap(e, t, {
1647
+ cssWidth: i > 0 ? i : Math.round(t.width / c),
1648
+ cssHeight: a > 0 ? a : Math.round(t.height / c)
1649
+ })) return;
1650
+ } else if (await $(this._doc, this._canvas, this._currentPage, "main", l), !this._renderDispatcher.isCurrent(e)) return;
1651
+ this._textLayer && this._buildTextLayer(this._textLayer, o), this._find.setPageRuns(this._currentPage, o), this._buildHighlightLayer(o), this._opts.onPageChange?.(this._currentPage, this.pageCount, this.layoutComplete);
1652
+ }
1653
+ _bindLayoutDocument(e) {
1654
+ this._unbindLayoutDocument(), this._layoutFailed = !1, this._layoutViewPublicationGeneration = 0;
1655
+ let t = It(e, (t) => this._onLayoutViewPublication(e, t), (e) => this._reportRenderError(e)), n = !0, r = Mt(e, () => ({
1656
+ pageCount: e.pageCount,
1657
+ exact: e.layoutComplete,
1658
+ complete: e.layoutComplete
1659
+ }), (t) => {
1660
+ if (n) {
1661
+ n = !1;
1662
+ return;
1663
+ }
1664
+ this._onLayoutPublication(e, t);
1665
+ }, (e) => this._reportRenderError(e));
1666
+ this._layoutUnsubscribe = () => {
1667
+ r(), t();
1668
+ };
1669
+ }
1670
+ _unbindLayoutDocument() {
1671
+ this._layoutUnsubscribe?.(), this._layoutUnsubscribe = null, this._layoutFailed = !1, this._cancelPendingNavigation();
1672
+ }
1673
+ _onLayoutPublication(e, t) {
1674
+ if (!(this._destroyed || e !== this._doc)) {
1675
+ if (this._wakeLayoutWaiters(), t.error !== void 0) {
1676
+ this._layoutFailed = !0, this._errorRouter.reportBackground(t.error, this._opts.onLayoutComplete !== void 0);
1677
+ return;
1678
+ }
1679
+ this._find.invalidate(), this._currentPage = Math.max(0, Math.min(this._currentPage, t.pageCount - 1)), this._render().catch((e) => this._reportRenderError(e));
1680
+ }
1681
+ }
1682
+ _onLayoutViewPublication(e, t) {
1683
+ this._destroyed || e !== this._doc || t.generation <= this._layoutViewPublicationGeneration || (this._layoutViewPublicationGeneration = t.generation, t.requester !== this && (this._layoutViewGeneration++, this._opts = {
1684
+ ...this._opts,
1685
+ currentDate: t.view.currentDate,
1686
+ showTrackedChanges: t.view.showTrackedChanges
1687
+ }, this._find.invalidate(), this._currentPage = Math.max(0, Math.min(this._currentPage, e.pageCount - 1)), this._render().catch((e) => this._reportRenderError(e))));
1688
+ }
1689
+ async _waitForPage(e, t, n) {
1690
+ await this._errorRouter.ownBackgroundLifecycle(async () => {
1691
+ for (; !this._destroyed && n === this._navigationGeneration && e === this._doc && t >= e.pageCount && !e.layoutComplete && !this._layoutFailed;) await new Promise((e) => {
1692
+ this._layoutWaiters.add(e);
1693
+ });
1694
+ e === this._doc && (e.layoutComplete || this._layoutFailed) && await e.waitUntilLayoutComplete();
1695
+ });
1696
+ }
1697
+ _wakeLayoutWaiters() {
1698
+ for (let e of this._layoutWaiters) e();
1699
+ this._layoutWaiters.clear();
1700
+ }
1701
+ _cancelPendingNavigation() {
1702
+ let e = ++this._navigationGeneration;
1703
+ return this._wakeLayoutWaiters(), this._setLoading(!1), e;
1704
+ }
1705
+ _setLoading(e) {
1706
+ this._loadingLayer.style.display = e ? "flex" : "none";
1707
+ }
1708
+ async setShowTrackedChanges(e) {
1709
+ let t = ++this._layoutViewGeneration, n = this._doc;
1710
+ if (this._opts.showTrackedChanges === !0 === e) {
1711
+ n && await G(n, {
1712
+ showTrackedChanges: e,
1713
+ currentDate: this._opts.currentDate
1714
+ }, this);
1715
+ return;
1716
+ }
1717
+ let r = {
1718
+ ...this._opts,
1719
+ showTrackedChanges: e
1720
+ };
1721
+ (!n || await G(n, {
1722
+ showTrackedChanges: e,
1723
+ currentDate: r.currentDate
1724
+ }, this)) && (this._destroyed || t !== this._layoutViewGeneration || n !== this._doc || (this._opts = r, this._find.invalidate(), this._currentPage = Math.max(0, Math.min(this._currentPage, this.pageCount - 1)), await this._render()));
1725
+ }
1726
+ _buildHighlightLayer(e) {
1727
+ let t = this._highlightLayer;
1728
+ if (!t) return;
1729
+ let { width: n, height: r } = this._canvasCssPx();
1730
+ X(t, e, this._find.pageHighlights(this._currentPage), n, r, (e) => this._measureForFont(e), this._opts.findHighlightColors);
1731
+ }
1732
+ _canvasCssPx() {
1733
+ return {
1734
+ width: parseFloat(this._canvas.style.width) || this._canvas.width,
1735
+ height: parseFloat(this._canvas.style.height) || this._canvas.height
1736
+ };
1737
+ }
1738
+ _measureForFont(e) {
1739
+ this._measureCtx ||= document.createElement("canvas").getContext("2d");
1740
+ let t = this._measureCtx;
1741
+ return t ? (t.font = e, (e) => t.measureText(e).width) : (e) => e.length;
1742
+ }
1743
+ async _collectPageRuns(e) {
1744
+ return this._doc ? this._doc.collectPageRuns(e, {
1745
+ width: this._renderWidth(),
1746
+ currentDate: this._opts.currentDate,
1747
+ showTrackedChanges: this._opts.showTrackedChanges
1748
+ }) : [];
1749
+ }
1750
+ _buildTextLayer(e, t) {
1751
+ let { width: n, height: r } = this._canvasCssPx();
1752
+ Y(e, t, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), this._currentPage);
1753
+ }
1754
+ _hyperlinkHandler() {
1755
+ return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
1756
+ if (e.kind === "external") {
1757
+ s(e.url, void 0, this._hostWindow);
1758
+ return;
1759
+ }
1760
+ let t = this._doc;
1761
+ if (!t) return;
1762
+ let n = ++this._internalHyperlinkGeneration;
1763
+ this._navigateInternalHyperlink(t, e.ref, n).catch((e) => this._reportRenderError(e));
1764
+ });
1765
+ }
1766
+ async _navigateInternalHyperlink(e, t, n) {
1767
+ if (e.layoutComplete || await e.waitUntilLayoutComplete(), this._destroyed || this._doc !== e || n !== this._internalHyperlinkGeneration) return;
1768
+ let r = e.getBookmarkPage(t);
1769
+ r !== void 0 && await this.goToPage(r);
1770
+ }
1771
+ }, Xt = 150, Zt = "0 1px 3px rgba(0,0,0,0.2)", Qt = 12, $t = 13, en = Symbol("DocxScrollViewer.borrowedDocument"), tn;
1772
+ function nn() {
1773
+ return tn ??= import("./comment-ui-runtime-DD5a3x3k.js");
1774
+ }
1775
+ var rn = class e {
1776
+ _documentOwner;
1777
+ get _doc() {
1778
+ return this._documentOwner.current;
1779
+ }
1780
+ _borrowed;
1781
+ _opts;
1782
+ _errorRouter;
1783
+ _container;
1784
+ _wrapper;
1785
+ _scrollHost;
1786
+ _spacer;
1787
+ _mode;
1788
+ _scale = 1;
1789
+ _scaleEstablished = !1;
1790
+ _pendingScale = null;
1791
+ _slots = /* @__PURE__ */ new Map();
1792
+ _free = [];
1793
+ _heights = [];
1794
+ _scrollGeometry = {
1795
+ offsets: [],
1796
+ totalHeight: 0
1797
+ };
1798
+ _lastRange = null;
1799
+ _lastTopIndex = -1;
1800
+ _lastReportedTotal = -1;
1801
+ _lastReportedLayoutComplete = null;
1802
+ _layoutUnsubscribe = null;
1803
+ _presentedPageCount = 0;
1804
+ _pendingLayoutPublication = null;
1805
+ _scrollListener = null;
1806
+ _selectionChangeListener = null;
1807
+ _selectionContextKey = "null";
1808
+ _elementClickListener = null;
1809
+ _contextMenuListener = null;
1810
+ _commentOutsidePointerListener = null;
1811
+ _elementContext = null;
1812
+ _activeCommentId = null;
1813
+ _activeCommentPage = null;
1814
+ _commentUi = null;
1815
+ _commentPageById = /* @__PURE__ */ new Map();
1816
+ _commentRunsByPage = /* @__PURE__ */ new Map();
1817
+ _commentIndexedPages = /* @__PURE__ */ new Set();
1818
+ _commentScanFrontier = 0;
1819
+ _commentNavigationGeneration = 0;
1820
+ _internalHyperlinkGeneration = 0;
1821
+ _commentAnchorRangesForMargin = null;
1822
+ _commentAnchorIds = /* @__PURE__ */ new Set();
1823
+ _reviewOriginPx = 0;
1824
+ _commentGeometryScheduled = !1;
1825
+ _commentGeometryFrame = null;
1826
+ _pendingCommentGeometry = /* @__PURE__ */ new Map();
1827
+ _elementHitGeneration = 0;
1828
+ _destroyed = !1;
1829
+ _measureCtx;
1830
+ _bitmapInFlight = /* @__PURE__ */ new Set();
1831
+ _renderEpoch = 0;
1832
+ _settleTimer = null;
1833
+ _wheelListener = null;
1834
+ _pendingZoomAnchor = null;
1835
+ _resizeObserver = null;
1836
+ _prevBase = 0;
1837
+ _lastFitWidth = 0;
1838
+ _pageShadow;
1839
+ _find = new Ut(() => this.pageCount, (e) => this._collectPageRuns(e));
1840
+ _findActive = !1;
1841
+ _findRequestGeneration = 0;
1842
+ _showTrackedChanges;
1843
+ _currentDate;
1844
+ _layoutViewGeneration = 0;
1845
+ _layoutViewPublicationGeneration = 0;
1846
+ static fromDocument(t, n, r = {}) {
1847
+ let i = W(n);
1848
+ return new e(t, {
1849
+ ...r,
1850
+ currentDate: i.currentDate,
1851
+ showTrackedChanges: i.showTrackedChanges,
1852
+ [en]: n
1853
+ });
1854
+ }
1855
+ constructor(e, t = {}) {
1856
+ 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.");
1857
+ this._container = e, this._opts = t, this._errorRouter = new ce("DocxScrollViewer", t.onError), this._showTrackedChanges = t.showTrackedChanges === !0, this._currentDate = t.currentDate, this._pageShadow = t.pageShadow ?? Zt;
1858
+ let n = t[en];
1859
+ this._borrowed = n !== void 0, n ? (this._documentOwner = new _("DocxScrollViewer", n, !1), this._mode = x("DocxScrollViewer", t.mode, n)) : (this._documentOwner = new _("DocxScrollViewer"), this._mode = x("DocxScrollViewer", t.mode, void 0)), this._wrapper = document.createElement("div"), this._wrapper.style.cssText = "position:relative;width:100%;height:100%;overflow:hidden;", this._scrollHost = document.createElement("div"), this._scrollHost.style.cssText = "position:absolute;inset:0;overflow:auto;", this._scrollHost.style.scrollbarGutter = "stable", t.background && (this._scrollHost.style.background = t.background), this._spacer = document.createElement("div"), this._spacer.style.cssText = "position:absolute;top:0;left:0;width:1px;height:0;pointer-events:none;", this._scrollHost.appendChild(this._spacer), this._wrapper.appendChild(this._scrollHost), this._container.appendChild(this._wrapper), this._commentsEnabled() && nn().then((e) => {
1860
+ if (!this._destroyed) {
1861
+ this._commentUi = e;
1862
+ for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
1863
+ }
1864
+ }).catch((e) => this._reportRenderError(e)), t.enableTextSelection && (t.onSelectionContextChange || t.enableElementSelection) && (this._selectionChangeListener = () => this._emitSelectionContextChange(), this._wrapper.ownerDocument.addEventListener("selectionchange", this._selectionChangeListener)), t.enableElementSelection && (this._elementClickListener = (e) => {
1865
+ this._onElementClick(e).catch((e) => this._reportRenderError(e));
1866
+ }, 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), t.comments && (this._commentOutsidePointerListener = (e) => {
1867
+ if (!Te(e, this._wrapper, "ooxmlCommentId") && this._activeCommentId !== null) {
1868
+ this._activeCommentId = null, this._activeCommentPage = null;
1869
+ for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
1870
+ this._emitSelectionContextChange();
1871
+ }
1872
+ }, this._wrapper.ownerDocument.addEventListener("pointerdown", this._commentOutsidePointerListener)), this._opts.enableZoom !== !1 && (this._wheelListener = (e) => {
1873
+ if (!(e.ctrlKey || e.metaKey) || (e.preventDefault(), e.deltaY === 0)) return;
1874
+ let t = this._scrollHost.getBoundingClientRect(), n = e.clientX - t.left, r = e.clientY - t.top;
1875
+ this._pendingZoomAnchor = Number.isFinite(n) && Number.isFinite(r) ? {
1876
+ x: n,
1877
+ y: r
1878
+ } : null, this.setScale(me(this._scale, e.deltaY));
1879
+ }, 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._bindLayoutDocument(n), this.relayout());
1880
+ }
1881
+ async load(e) {
1882
+ if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
1883
+ if (this._borrowed) throw Error("DocxScrollViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.");
1884
+ let t = !1;
1885
+ try {
1886
+ let n = await this._documentOwner.replace(() => q.load(e, {
1887
+ password: this._opts.password,
1888
+ useGoogleFonts: this._opts.useGoogleFonts,
1889
+ maxZipEntryBytes: this._opts.maxZipEntryBytes,
1890
+ resourceLimits: this._opts.resourceLimits,
1891
+ debug: this._opts.debug,
1892
+ onResourceMetrics: this._opts.onResourceMetrics,
1893
+ workerTimeoutMs: this._opts.workerTimeoutMs,
1894
+ wasmUrl: this._opts.wasmUrl,
1895
+ math: this._opts.math,
1896
+ threeD: this._opts.threeD,
1897
+ regionMap: this._opts.regionMap,
1898
+ chartEx: this._opts.chartEx,
1899
+ mode: this._mode,
1900
+ ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
1901
+ ...this._currentDate === void 0 ? {} : { currentDate: this._currentDate },
1902
+ ...this._opts.progressiveLayout ? { progressiveLayout: !0 } : {},
1903
+ ...this._opts.sliceLayout ? { sliceLayout: !0 } : {},
1904
+ onLayoutProgress: this._opts.onLayoutProgress,
1905
+ onLayoutPartial: this._opts.onLayoutPartial,
1906
+ onLayoutComplete: this._opts.onLayoutComplete
1907
+ }), (e) => {
1908
+ if (this._invalidateElementContext(!1), t = !0, this._findRequestGeneration++, this._find.invalidate(), this._findActive = !1, this._activeCommentId = null, this._activeCommentPage = null, this._resetCommentNavigation(), this._unbindLayoutDocument(), e) {
1909
+ for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
1910
+ this._lastTopIndex = -1, this._lastReportedTotal = -1, this._lastReportedLayoutComplete = null;
1911
+ }
1912
+ });
1913
+ if (!n) return;
1914
+ if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
1915
+ this._bindLayoutDocument(n), this._find.invalidate(), this._findActive = !1, this._activeCommentId = null, this._activeCommentPage = null, this._resetCommentNavigation();
1916
+ let r = [];
1917
+ this._relayout(r), await Promise.all(r);
1918
+ } catch (e) {
1919
+ throw this._destroyed ? Error("DocxScrollViewer is destroyed") : e instanceof Error ? e : Error(String(e));
1920
+ }
1921
+ t && !this._destroyed && this._emitSelectionContextChange();
1922
+ }
1923
+ get pageCount() {
1924
+ return this._doc?.pageCount ?? 0;
1925
+ }
1926
+ get layoutComplete() {
1927
+ return this._doc?.layoutComplete ?? !0;
1928
+ }
1929
+ async waitUntilLayoutComplete() {
1930
+ await this._errorRouter.ownBackgroundLifecycle(async () => {
1931
+ await this._doc?.waitUntilLayoutComplete?.();
1932
+ });
1933
+ }
1934
+ _bindLayoutDocument(e) {
1935
+ this._unbindLayoutDocument(), this._layoutViewPublicationGeneration = 0, this._presentedPageCount = e.pageCount, this._pendingLayoutPublication = null;
1936
+ let t = It(e, (t) => this._onLayoutViewPublication(e, t), (e) => this._reportRenderError(e)), n = !0, r = Mt(e, () => ({
1937
+ pageCount: e.pageCount,
1938
+ exact: e.layoutComplete,
1939
+ complete: e.layoutComplete
1940
+ }), (t) => {
1941
+ if (n) {
1942
+ n = !1;
1943
+ return;
1944
+ }
1945
+ this._onLayoutPublication(e, t);
1946
+ }, (e) => this._reportRenderError(e));
1947
+ this._layoutUnsubscribe = () => {
1948
+ r(), t();
1949
+ };
1950
+ }
1951
+ _unbindLayoutDocument() {
1952
+ this._layoutUnsubscribe?.(), this._layoutUnsubscribe = null, this._presentedPageCount = 0, this._pendingLayoutPublication = null;
1953
+ }
1954
+ _onLayoutPublication(e, t) {
1955
+ if (!(this._destroyed || e !== this._doc)) {
1956
+ if (t.error !== void 0) {
1957
+ this._errorRouter.reportBackground(t.error, this._opts.onLayoutComplete !== void 0);
1958
+ return;
1959
+ }
1960
+ if (this._find.invalidate(), this._refreshCommentSurface(), !t.complete) {
1961
+ if (this._pendingLayoutPublication = t, this._lastRange && this._emitVisiblePageChange(this._lastRange), this._presentedPageCount === 0 || t.pageCount < this._presentedPageCount) {
1962
+ this._pendingLayoutPublication = null, this._applyLayoutPublication(t);
1963
+ return;
1964
+ }
1965
+ this._revealPendingLayoutAtPresentedTail();
1966
+ return;
1967
+ }
1968
+ this._pendingLayoutPublication = null, this._applyLayoutPublication(t);
1969
+ }
1970
+ }
1971
+ _onLayoutViewPublication(e, t) {
1972
+ this._destroyed || e !== this._doc || t.generation <= this._layoutViewPublicationGeneration || (this._layoutViewPublicationGeneration = t.generation, t.requester !== this && (this._layoutViewGeneration++, this._showTrackedChanges = t.view.showTrackedChanges, this._currentDate = t.view.currentDate, this._find.invalidate(), this._pendingLayoutPublication = null, this._applyLayoutPublication({
1973
+ pageCount: e.pageCount,
1974
+ exact: !0,
1975
+ complete: e.layoutComplete
1976
+ })));
1977
+ }
1978
+ _refreshCommentSurface() {
1979
+ if (!(!this._commentsEnabled() || this._slots.size === 0)) {
1980
+ this._syncSpacerWidth();
1981
+ for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
1982
+ }
1983
+ }
1984
+ _applyLayoutPublication(e) {
1985
+ let t = [...this._slots];
1986
+ this._presentedPageCount = e.pageCount, this._renderEpoch++, this.relayout();
1987
+ for (let [e, n] of t) e >= this._presentedPageCount || this._slots.get(e) !== n || this._refreshSlotAtomically(e, n);
1988
+ }
1989
+ _revealPendingLayoutAtPresentedTail() {
1990
+ let e = this._pendingLayoutPublication;
1991
+ !e || this._presentedPageCount === 0 || S(this._scrollGeometry, this._scrollHost.scrollTop, this._scrollHost.clientHeight, 0).end < this._presentedPageCount - 1 || (this._pendingLayoutPublication = null, this._applyLayoutPublication(e));
1992
+ }
1993
+ _revealPendingLayoutThroughPage(e) {
1994
+ let t = this._pendingLayoutPublication;
1995
+ !t || e < this._presentedPageCount || (this._pendingLayoutPublication = null, this._applyLayoutPublication(t));
1996
+ }
1997
+ _pageWidthPx(e) {
1998
+ return this._doc.pageSize(e).widthPt * k * this._scale;
1999
+ }
2000
+ _pageHeightPx(e) {
2001
+ return this._doc.pageSize(e).heightPt * k * this._scale;
2002
+ }
2003
+ _fitWidthPx() {
2004
+ if (this._opts.width && this._opts.width > 0) return this._opts.width;
2005
+ let e = this._scrollHost.clientWidth || this._container.clientWidth;
2006
+ if (e <= 0) return 0;
2007
+ let { left: t, right: n } = this._padH(), r = e - t - n;
2008
+ return r <= 0 ? 0 : r;
2009
+ }
2010
+ _hasCommentMargin() {
2011
+ return this._hasDisplayableComments() && this._commentsOptions()?.cards !== !1;
2012
+ }
2013
+ _hasDisplayableComments() {
2014
+ if (!this._commentsEnabled()) return !1;
2015
+ let e = this._doc;
2016
+ if (!e) return !1;
2017
+ let t = e.commentAnchorRanges();
2018
+ if (this._commentAnchorRangesForMargin !== t && (this._commentAnchorRangesForMargin = t, this._commentAnchorIds = new Set(t.map((e) => e.commentId))), this._commentAnchorIds.size === 0) return !1;
2019
+ let n = this._commentsOptions()?.includeResolved === !0;
2020
+ return e.comments.some((e) => this._commentAnchorIds.has(e.id) && e.parentId === void 0 && (n || e.resolved !== !0));
2021
+ }
2022
+ _commentMarginExtent() {
2023
+ return this._hasCommentMargin() ? (Qt + 280) * this._commentZoom() : 0;
2024
+ }
2025
+ _commentZoom() {
2026
+ return this._scaleEstablished ? this._scale : 1;
2027
+ }
2028
+ _commentsEnabled() {
2029
+ return this._opts.comments === !0 || typeof this._opts.comments == "object";
2030
+ }
2031
+ _commentsOptions() {
2032
+ return typeof this._opts.comments == "object" ? this._opts.comments : void 0;
2033
+ }
2034
+ _commentSide() {
2035
+ let e = this._commentsOptions()?.side;
2036
+ return e === "left" || e === "right" ? e : (this._container.ownerDocument.defaultView?.getComputedStyle?.(this._container).direction || this._container.dir || this._container.style.direction) === "rtl" ? "left" : "right";
2037
+ }
2038
+ _syncCommentMarginGeometry(e) {
2039
+ if (!e) return;
2040
+ let t = this._commentZoom(), n = `calc(100% + ${Qt * t}px)`;
2041
+ e.style.left = this._commentSide() === "right" ? n : "", e.style.right = this._commentSide() === "left" ? n : "", e.style.width = `${280 * t}px`, e.style.fontSize = `${$t}px`, e.dataset.ooxmlCommentZoom = String(t);
2042
+ }
2043
+ _baseScale() {
2044
+ if (!this._doc || this._doc.pageCount === 0) return 0;
2045
+ let e = this._fitWidthPx();
2046
+ if (e <= 0) return 0;
2047
+ let t = this._doc.pageSize(0).widthPt;
2048
+ return t <= 0 ? 0 : e / (t * k);
2049
+ }
2050
+ relayout() {
2051
+ this._relayout();
2052
+ }
2053
+ _relayout(e) {
2054
+ if (this._doc) {
2055
+ if (this._doc.layoutComplete !== !1 && this._pendingLayoutPublication === null && (this._presentedPageCount = this._doc.pageCount), !this._scaleEstablished) {
2056
+ let e = this._baseScale();
2057
+ if (e > 0) {
2058
+ if (this._scale = e, this._prevBase = e, this._lastFitWidth = this._fitWidthPx(), this._scaleEstablished = !0, this._pendingScale !== null) {
2059
+ let e = this._pendingScale;
2060
+ this._pendingScale = null, e !== this._scale && (this._scale = e, this._opts.onScaleChange?.(e));
2061
+ }
2062
+ } else return;
2063
+ }
2064
+ this._recomputeHeights(), this._syncSpacer(), this._mountVisible(e);
2065
+ for (let [e, t] of this._slots) t.renderedPage === e && t.renderedScale >= 0 && this._redrawSlotComments(e, t);
2066
+ }
2067
+ }
2068
+ _recomputeHeights() {
2069
+ let e = Math.min(this._presentedPageCount, this._doc.pageCount), t = Array(e);
2070
+ for (let n = 0; n < e; n++) t[n] = this._pageHeightPx(n);
2071
+ this._heights = t, this._scrollGeometry = we(t, this._gap(), this._pad());
2072
+ }
2073
+ _gap() {
2074
+ return this._opts.gap ?? 16;
2075
+ }
2076
+ _overscan() {
2077
+ return this._opts.overscan ?? 1;
2078
+ }
2079
+ _pad() {
2080
+ let e = this._gap();
2081
+ return {
2082
+ leading: this._opts.paddingTop ?? e,
2083
+ trailing: this._opts.paddingBottom ?? e
2084
+ };
2085
+ }
2086
+ _padH() {
2087
+ let e = this._gap();
2088
+ return {
2089
+ left: this._opts.paddingLeft ?? e,
2090
+ right: this._opts.paddingRight ?? e
2091
+ };
2092
+ }
2093
+ _pageIndexAtOffset(e, t) {
2094
+ let { offsets: n } = e, r = 0, i = n.length - 1, a = 0;
2095
+ for (; r <= i;) {
2096
+ let e = r + i >> 1;
2097
+ n[e] <= t ? (a = e, r = e + 1) : i = e - 1;
2098
+ }
2099
+ return a;
2100
+ }
2101
+ _range() {
2102
+ return S(this._scrollGeometry, this._scrollHost.scrollTop, this._scrollHost.clientHeight, this._overscan());
2103
+ }
2104
+ _syncSpacer() {
2105
+ let e = this._range();
2106
+ this._lastRange = e, this._spacer.style.height = `${e.totalHeight}px`, this._syncSpacerWidth();
2107
+ }
2108
+ _syncSpacerWidth() {
2109
+ let { left: e, right: t } = this._padH(), n = 0;
2110
+ for (let e = 0; e < this._heights.length; e++) {
2111
+ let t = this._pageWidthPx(e);
2112
+ t > n && (n = t);
2113
+ }
2114
+ let r = this._commentMarginExtent(), i = this._commentSide() === "left" ? r : 0, a = i - this._reviewOriginPx, o = Math.max(0, this._scrollHost.scrollLeft + a);
2115
+ this._spacer.style.width = `${n + r + e + t}px`, a !== 0 && (this._reviewOriginPx = i, this._scrollHost.style["--ooxml-review-origin-x"] = `${i}px`, this._scrollHost.scrollLeft = o);
2116
+ }
2117
+ _onScroll() {
2118
+ !this._doc || !this._scaleEstablished || (this._revealPendingLayoutAtPresentedTail(), this._mountVisible(void 0, !1));
2119
+ }
2120
+ _mountVisible(e, t = !0) {
2121
+ if (!this._doc || this._doc.pageCount === 0) return;
2122
+ let n = this._range();
2123
+ this._lastRange = n;
2124
+ for (let [e, t] of [...this._slots]) (e < n.start || e > n.end) && this._recycleSlot(e, t);
2125
+ for (let r = n.start; r <= n.end; r++) if (!this._slots.has(r)) {
2126
+ let t = this._acquireSlot();
2127
+ this._positionSlot(t, r, n), this._slots.set(r, t);
2128
+ let i = this._renderSlot(r, t, e === void 0);
2129
+ e && i && e.push(i);
2130
+ } else if (t) {
2131
+ let t = this._slots.get(r);
2132
+ this._positionSlot(t, r, n);
2133
+ let i = this._renderSlot(r, t, e === void 0);
2134
+ e && i && e.push(i);
2135
+ }
2136
+ this._emitVisiblePageChange(n);
2137
+ }
2138
+ _emitVisiblePageChange(e) {
2139
+ if (!this._doc) return;
2140
+ let t = this._doc.pageCount, n = this.layoutComplete;
2141
+ e.topIndex === this._lastTopIndex && t === this._lastReportedTotal && n === this._lastReportedLayoutComplete || (this._lastTopIndex = e.topIndex, this._lastReportedTotal = t, this._lastReportedLayoutComplete = n, this._opts.onVisiblePageChange?.(e.topIndex, t, n));
2142
+ }
2143
+ _applyPageShadow(e) {
2144
+ this._pageShadow !== !1 && (e.style.boxShadow = this._pageShadow);
2145
+ }
2146
+ _acquireSlot() {
2147
+ let e = this._free.pop();
2148
+ if (e) return this._scrollHost.appendChild(e.wrapper), e;
2149
+ let t = document.createElement("div");
2150
+ t.style.cssText = "position:absolute;";
2151
+ let n = document.createElement("canvas");
2152
+ n.style.cssText = "display:block;background:#fff;", this._applyPageShadow(n), t.appendChild(n);
2153
+ let r = null;
2154
+ 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));
2155
+ let i = document.createElement("div");
2156
+ i.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;", t.appendChild(i);
2157
+ let a = null, o = null, s = null;
2158
+ this._commentsEnabled() && (a = document.createElement("div"), a.style.cssText = "position:absolute;inset:0;overflow:hidden;pointer-events:none;", t.appendChild(a), this._commentsOptions()?.cards !== !1 && (o = document.createElement("div"), o.style.cssText = "position:absolute;top:0;height:100%;box-sizing:border-box;overflow-x:hidden;overflow-y:auto;pointer-events:auto;", this._syncCommentMarginGeometry(o), this._commentsOptions()?.connectors !== void 0 && (s = document.createElement("div"), s.style.cssText = "position:absolute;top:0;left:0;overflow:visible;pointer-events:none;", t.appendChild(s)), t.appendChild(o)));
2159
+ let c = oe(t, this._opts.enableElementSelection === !0);
2160
+ return this._scrollHost.appendChild(t), {
2161
+ wrapper: t,
2162
+ canvas: n,
2163
+ textLayer: r,
2164
+ highlightLayer: i,
2165
+ elementLayer: c,
2166
+ commentTintLayer: a,
2167
+ commentMargin: o,
2168
+ commentDecorationLayer: s,
2169
+ commentRuns: Object.freeze([]),
2170
+ commentGeometry: null,
2171
+ renderedPage: -1,
2172
+ renderedScale: -1,
2173
+ dispatcher: new b(n, this._mode === "worker")
2174
+ };
2175
+ }
2176
+ _recycleSlot(e, t) {
2177
+ this._slots.delete(e), t.dispatcher.destroy(), this._destroyed || (t.dispatcher = new b(t.canvas, this._mode === "worker")), t.textLayer && (t.textLayer.innerHTML = "", this._clearTextLayerPreview(t.textLayer)), t.highlightLayer.innerHTML = "", t.highlightLayer.style.transform = "", t.highlightLayer.style.transformOrigin = "", t.commentTintLayer && (t.commentTintLayer.replaceChildren(), t.commentTintLayer.style.transform = "", t.commentTintLayer.style.transformOrigin = "", t.commentTintLayer.style.visibility = ""), t.commentMargin && (this._commentUi?.disposeReadOnlyCommentMargin(t.commentMargin), this._commentUi || t.commentMargin.replaceChildren(), t.commentMargin.style.visibility = ""), t.commentDecorationLayer && (this._commentUi?.disposeReadOnlyCommentDecoration(t.commentDecorationLayer), this._commentUi || t.commentDecorationLayer.replaceChildren()), t.commentRuns = Object.freeze([]), t.commentGeometry = null, v(t.elementLayer, null), t.renderedPage = -1, t.renderedScale = -1, t.wrapper.remove(), this._free.push(t);
2178
+ }
2179
+ _positionSlot(e, t, n) {
2180
+ e.wrapper.style.top = `${n.offsets[t]}px`;
2181
+ let r = this._pageWidthPx(t), i = this._pageHeightPx(t);
2182
+ if (e.wrapper.style.width = `${r}px`, e.wrapper.style.height = `${i}px`, this._syncCommentMarginGeometry(e.commentMargin), e.commentDecorationLayer) {
2183
+ let t = this._commentMarginExtent();
2184
+ e.commentDecorationLayer.style.left = this._commentSide() === "left" ? `${-t}px` : "0px", e.commentDecorationLayer.style.width = `${r + t}px`, e.commentDecorationLayer.style.height = `${i}px`;
2185
+ }
2186
+ this._redrawElementOutlineForSlot(t, e);
2187
+ let { left: a } = this._padH(), o = Math.max(a, (this._scrollHost.clientWidth - r) / 2);
2188
+ e.wrapper.style.left = this._commentSide() === "left" && this._commentsEnabled() ? `calc(${o}px + var(--ooxml-review-origin-x, 0px))` : `${o}px`;
2189
+ }
2190
+ _dpr() {
2191
+ return this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1);
2192
+ }
2193
+ _renderSlot(e, t, n = !0) {
2194
+ if (!this._doc || t.renderedPage === e) return null;
2195
+ t.renderedPage = e;
2196
+ let r = this._dpr(), i = this._pageWidthPx(e), a = this._renderEpoch, o = this._scale, s = t.dispatcher, c = s.begin();
2197
+ if (this._mode === "worker") return this._renderSlotBitmap(e, t, i, r, o, s, c, n);
2198
+ let l = [], u = !!this._opts.enableTextSelection && !!t.textLayer, d = u || this._findActive || !!t.commentTintLayer, f = d ? (e) => l.push(e) : void 0, p;
2199
+ try {
2200
+ p = $(this._doc, t.canvas, e, "main", {
2201
+ width: i,
2202
+ dpr: r,
2203
+ defaultTextColor: this._opts.defaultTextColor,
2204
+ currentDate: this._currentDate,
2205
+ ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2206
+ onTextRun: f
2207
+ });
2208
+ } catch (e) {
2209
+ return n ? (this._reportRenderError(e), Promise.resolve()) : Promise.reject(e);
2210
+ }
2211
+ return p.then(() => {
2212
+ if (!(!s.isCurrent(c) || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e)) {
2213
+ if (t.renderedScale = o, u && t.textLayer) {
2214
+ let { width: n, height: r } = this._canvasCssPx(t.canvas);
2215
+ Y(t.textLayer, l, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
2216
+ }
2217
+ d && this._refreshFindRuns(e, l), this._commitCommentRuns(e, t, l), this._redrawSlotHighlights(e, t);
2218
+ }
2219
+ }).catch((r) => {
2220
+ if (s.isCurrent(c) && a === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e) if (n) this._reportRenderError(r);
2221
+ else throw r;
2222
+ });
2223
+ }
2224
+ _hyperlinkHandler() {
2225
+ return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
2226
+ if (e.kind === "external") {
2227
+ s(e.url);
2228
+ return;
2229
+ }
2230
+ let t = this._doc;
2231
+ if (!t) return;
2232
+ let n = ++this._internalHyperlinkGeneration;
2233
+ this._navigateInternalHyperlink(t, e.ref, n).catch((e) => this._reportRenderError(e));
2234
+ });
2235
+ }
2236
+ async _navigateInternalHyperlink(e, t, n) {
2237
+ if (e.layoutComplete || await e.waitUntilLayoutComplete(), this._destroyed || this._doc !== e || n !== this._internalHyperlinkGeneration) return;
2238
+ let r = e.getBookmarkPage(t);
2239
+ r !== void 0 && this.scrollToPage(r);
2240
+ }
2241
+ _measureForFont(e) {
2242
+ this._measureCtx === void 0 && (this._measureCtx = document.createElement("canvas").getContext("2d"));
2243
+ let t = this._measureCtx;
2244
+ return !t || typeof t.measureText != "function" ? (e) => e.length : (t.font = e, (e) => t.measureText(e).width);
2245
+ }
2246
+ _canvasCssPx(e) {
2247
+ return {
2248
+ width: parseFloat(e.style.width) || e.width,
2249
+ height: parseFloat(e.style.height) || e.height
2250
+ };
2251
+ }
2252
+ _reportRenderError(e) {
2253
+ this._errorRouter.report(e);
2254
+ }
2255
+ async _renderSlotBitmap(e, t, n, r, i, a = t.dispatcher, o = a.begin(), s = !0) {
2256
+ if (this._bitmapInFlight.has(e) || this._slots.get(e) !== t) return;
2257
+ let c = this._renderEpoch, l = this._pageHeightPx(e);
2258
+ this._bitmapInFlight.add(e);
2259
+ let u = !1, d = !!this._opts.enableTextSelection && !!t.textLayer, f = d || this._findActive || !!t.commentTintLayer, p = [];
2260
+ try {
2261
+ let s = await $(this._doc, t.canvas, e, "worker", {
2262
+ width: n,
2263
+ dpr: r,
2264
+ defaultTextColor: this._opts.defaultTextColor,
2265
+ currentDate: this._currentDate,
2266
+ ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2267
+ onTextRun: f ? (e) => p.push(e) : void 0
2268
+ });
2269
+ if (!a.isCurrent(o) || c !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) {
2270
+ s.close();
2271
+ return;
2272
+ }
2273
+ if (!a.commitBitmap(o, s, {
2274
+ cssWidth: n,
2275
+ cssHeight: l
2276
+ })) return;
2277
+ if (t.renderedScale = i, t.textLayer && (this._clearTextLayerPreview(t.textLayer), d)) {
2278
+ let { width: n, height: r } = this._canvasCssPx(t.canvas);
2279
+ Y(t.textLayer, p, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
2280
+ }
2281
+ f && this._refreshFindRuns(e, p), this._commitCommentRuns(e, t, p), this._redrawSlotHighlights(e, t), u = !0;
2282
+ } catch (n) {
2283
+ if (a.isCurrent(o) && c === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e) if (s) this._reportRenderError(n);
2284
+ else throw n;
2285
+ } finally {
2286
+ this._bitmapInFlight.delete(e);
2287
+ let n = this._slots.get(e);
2288
+ !u && 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);
2289
+ }
2290
+ }
2291
+ setScale(e) {
2292
+ let t = this._opts.zoomMin ?? .1, n = this._opts.zoomMax ?? 4, r = Math.min(n, Math.max(t, e)), i = this._pendingZoomAnchor;
2293
+ if (this._pendingZoomAnchor = null, !this._doc || this._doc.pageCount === 0 || !this._scaleEstablished) {
2294
+ this._pendingScale = r;
2295
+ return;
2296
+ }
2297
+ if (r === this._scale) return;
2298
+ 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;
2299
+ f = Math.min(1, Math.max(0, f));
2300
+ let p = this._padH().left, m = this._scrollHost.scrollLeft || 0;
2301
+ this._renderEpoch++, this._scale = r, this._recomputeHeights();
2302
+ let h = S(this._scrollGeometry, 0, this._scrollHost.clientHeight, this._overscan());
2303
+ this._spacer.style.height = `${h.totalHeight}px`, this._syncSpacerWidth();
2304
+ 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;
2305
+ if (this._scrollHost.scrollTop = Math.min(g, Math.max(0, v)), i) {
2306
+ let e = Math.max(0, (this._spacer.offsetWidth || 0) - this._scrollHost.clientWidth);
2307
+ this._scrollHost.scrollLeft = ee(m, i.x - p, a, r, { maxScroll: e });
2308
+ }
2309
+ this._previewVisible(), this._scheduleSettle(), this._opts.onScaleChange?.(r);
2310
+ }
2311
+ getScale() {
2312
+ return this._scaleEstablished ? this._scale : this._pendingScale ?? 1;
2313
+ }
2314
+ zoomIn() {
2315
+ this.setScale(fe(this.getScale()));
2316
+ }
2317
+ zoomOut() {
2318
+ this.setScale(he(this.getScale()));
2319
+ }
2320
+ fitWidth() {
2321
+ this._fit("width");
2322
+ }
2323
+ fitPage() {
2324
+ this._fit("page");
2325
+ }
2326
+ _fit(e) {
2327
+ if (!this._doc || this._doc.pageCount === 0) return;
2328
+ let t = this._doc.pageSize(0), n = g({
2329
+ contentWidth: t.widthPt * k,
2330
+ contentHeight: t.heightPt * k,
2331
+ containerWidth: this._fitWidthPx(),
2332
+ containerHeight: this._scrollHost.clientHeight
2333
+ }, e);
2334
+ n <= 0 || this.setScale(n);
2335
+ }
2336
+ _previewVisible() {
2337
+ if (!this._doc || this._doc.pageCount === 0) return;
2338
+ let e = this._range();
2339
+ this._lastRange = e;
2340
+ for (let [t, n] of [...this._slots]) (t < e.start || t > e.end) && this._recycleSlot(t, n);
2341
+ for (let t = e.start; t <= e.end; t++) {
2342
+ let n = this._slots.get(t);
2343
+ if (n) this._previewSlot(n, t, e);
2344
+ else {
2345
+ let n = this._acquireSlot();
2346
+ this._positionSlot(n, t, e), this._slots.set(t, n), this._renderSlot(t, n);
2347
+ }
2348
+ }
2349
+ this._emitVisiblePageChange(e);
2350
+ }
2351
+ _previewSlot(e, t, n) {
2352
+ if (this._positionSlot(e, t, n), e.canvas.style.width = `${this._pageWidthPx(t)}px`, e.canvas.style.height = `${this._pageHeightPx(t)}px`, e.renderedScale > 0) {
2353
+ let n = this._scale / e.renderedScale;
2354
+ e.textLayer && (e.textLayer.style.transformOrigin = "0 0", e.textLayer.style.width = `${this._pageWidthPx(t) / n}px`, e.textLayer.style.height = `${this._pageHeightPx(t) / n}px`, e.textLayer.style.transform = `scale(${n})`), e.commentMargin && this._commentUi?.previewReadOnlyCommentMargin(e.commentMargin, n);
2355
+ for (let t of e.commentTintLayer?.children ?? []) t.dataset.ooxmlCommentMarker !== void 0 && (t.style.transform = `translate(-50%,-50%) scale(${n})`);
2356
+ e.commentTintLayer && (e.commentTintLayer.style.visibility = ""), e.commentMargin && (e.commentMargin.style.visibility = ""), e.commentDecorationLayer && (e.commentDecorationLayer.style.visibility = "");
2357
+ return;
2358
+ }
2359
+ e.commentTintLayer && (e.commentTintLayer.style.visibility = "hidden"), e.commentMargin && (e.commentMargin.style.visibility = "hidden"), e.commentDecorationLayer && (e.commentDecorationLayer.style.visibility = "hidden");
2360
+ }
2361
+ _clearTextLayerPreview(e) {
2362
+ e.style.transform = "", e.style.transformOrigin = "", e.style.width = "100%", e.style.height = "100%";
2363
+ }
2364
+ _scheduleSettle() {
2365
+ this._settleTimer !== null && clearTimeout(this._settleTimer), this._settleTimer = setTimeout(() => {
2366
+ this._settleTimer = null, this._settleRender();
2367
+ }, Xt);
2368
+ }
2369
+ _settleRender() {
2370
+ if (!(this._destroyed || !this._doc || this._doc.pageCount === 0)) for (let [e, t] of [...this._slots]) t.renderedScale !== this._scale && this._refreshSlotAtomically(e, t);
2371
+ }
2372
+ _refreshSlotAtomically(e, t) {
2373
+ if (!this._doc) return;
2374
+ let n = this._dpr(), r = this._pageWidthPx(e), i = this._scale, a = this._renderEpoch;
2375
+ if (this._mode === "worker") {
2376
+ this._renderSlotBitmap(e, t, r, n, i);
2377
+ return;
2378
+ }
2379
+ let o = document.createElement("canvas");
2380
+ o.style.cssText = "display:block;background:#fff;", this._applyPageShadow(o);
2381
+ let s = new b(o, !1), c = s.begin(), l = [], u = !!this._opts.enableTextSelection && !!t.textLayer, d = u || this._findActive || !!t.commentTintLayer, f = d ? (e) => l.push(e) : void 0;
2382
+ $(this._doc, o, e, "main", {
2383
+ width: r,
2384
+ dpr: n,
2385
+ defaultTextColor: this._opts.defaultTextColor,
2386
+ currentDate: this._currentDate,
2387
+ ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2388
+ onTextRun: f
2389
+ }).then(() => {
2390
+ if (!s.isCurrent(c) || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) {
2391
+ s.destroy();
2392
+ return;
2393
+ }
2394
+ let n = t.canvas;
2395
+ if (t.dispatcher.destroy(), t.wrapper.insertBefore(o, n), n.remove(), t.canvas = o, t.dispatcher = s, t.renderedScale = i, t.textLayer && (this._clearTextLayerPreview(t.textLayer), u)) {
2396
+ let { width: n, height: r } = this._canvasCssPx(o);
2397
+ Y(t.textLayer, l, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
2398
+ }
2399
+ d && this._refreshFindRuns(e, l), this._commitCommentRuns(e, t, l), this._redrawSlotHighlights(e, t);
2400
+ }).catch((n) => {
2401
+ s.isCurrent(c) && a === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e && this._reportRenderError(n), s.destroy();
2402
+ });
2403
+ }
2404
+ async setShowTrackedChanges(e) {
2405
+ let t = ++this._layoutViewGeneration, n = this._doc;
2406
+ if (this._showTrackedChanges === e) {
2407
+ n && await G(n, {
2408
+ showTrackedChanges: e,
2409
+ currentDate: this._currentDate
2410
+ }, this);
2411
+ return;
2412
+ }
2413
+ (!n || await G(n, {
2414
+ showTrackedChanges: e,
2415
+ currentDate: this._currentDate
2416
+ }, this)) && (this._destroyed || t !== this._layoutViewGeneration || n !== this._doc || (this._showTrackedChanges = e, this._find.invalidate(), this._pendingLayoutPublication = null, this._applyLayoutPublication({
2417
+ pageCount: n?.pageCount ?? 0,
2418
+ exact: !0,
2419
+ complete: n?.layoutComplete !== !1
2420
+ })));
2421
+ }
2422
+ scrollToPage(e, t) {
2423
+ if (!this._doc || this._doc.pageCount === 0 || !this._scaleEstablished) return;
2424
+ let n = Math.max(0, Math.min(e, this._doc.pageCount - 1));
2425
+ this._revealPendingLayoutThroughPage(n);
2426
+ let r = S(this._scrollGeometry, 0, this._scrollHost.clientHeight, this._overscan()), 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;
2427
+ typeof s.scrollTo == "function" ? s.scrollTo({
2428
+ top: o,
2429
+ behavior: t?.behavior ?? "auto"
2430
+ }) : this._scrollHost.scrollTop = o, this._mountVisible();
2431
+ }
2432
+ _scrollToPageTarget(e, t, n) {
2433
+ this._revealPendingLayoutThroughPage(e);
2434
+ let r = S(this._scrollGeometry, 0, this._scrollHost.clientHeight, this._overscan()), i = this._pageWidthPx(e), { left: a } = this._padH(), o = Math.max(a, (this._scrollHost.clientWidth - i) / 2) + this._reviewOriginPx, s = Math.max(0, r.totalHeight - this._scrollHost.clientHeight), c = this._spacer.offsetWidth || Number.parseFloat(this._spacer.style.width) || 0, l = Math.max(0, c - this._scrollHost.clientWidth), u = Math.min(s, Math.max(0, (r.offsets[e] ?? 0) + t.y + t.h / 2 - this._scrollHost.clientHeight / 2)), d = Math.min(l, Math.max(0, o + t.x + t.w / 2 - this._scrollHost.clientWidth / 2)), f = this._scrollHost;
2435
+ typeof f.scrollTo == "function" ? f.scrollTo({
2436
+ top: u,
2437
+ left: d,
2438
+ behavior: n?.behavior ?? "auto"
2439
+ }) : (this._scrollHost.scrollTop = u, this._scrollHost.scrollLeft = d), this._mountVisible();
2440
+ }
2441
+ _resetCommentNavigation() {
2442
+ this._commentNavigationGeneration++, this._commentPageById.clear(), this._commentRunsByPage.clear(), this._commentIndexedPages.clear(), this._commentScanFrontier = 0;
2443
+ }
2444
+ _advanceCommentScanFrontier() {
2445
+ for (; this._commentIndexedPages.has(this._commentScanFrontier);) this._commentScanFrontier++;
2446
+ }
2447
+ _indexCommentPages(e, t, n) {
2448
+ if (!this._commentIndexedPages.has(e)) {
2449
+ for (let r of n) this._commentPageById.has(r.commentId) || M(r, t).length > 0 && this._commentPageById.set(r.commentId, e);
2450
+ this._commentIndexedPages.add(e), this._advanceCommentScanFrontier();
2451
+ }
2452
+ }
2453
+ async _commentRunsForPage(e, t) {
2454
+ for (; !this._destroyed && this._doc === t;) {
2455
+ let n = this._scale, r = this._commentRunsByPage.get(e);
2456
+ (!r || r.scale !== n) && (r = {
2457
+ scale: n,
2458
+ runs: t.collectPageRuns(e, {
2459
+ width: this._pageWidthPx(e),
2460
+ currentDate: this._currentDate,
2461
+ ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {}
2462
+ })
2463
+ }, this._commentRunsByPage.set(e, r));
2464
+ try {
2465
+ let e = await r.runs;
2466
+ if (this._destroyed || this._doc !== t) return null;
2467
+ if (this._scale !== n) continue;
2468
+ return e;
2469
+ } catch (t) {
2470
+ throw this._commentRunsByPage.get(e) === r && this._commentRunsByPage.delete(e), t;
2471
+ }
2472
+ }
2473
+ return null;
2474
+ }
2475
+ async goToComment(e, t) {
2476
+ if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2477
+ let n = this._doc;
2478
+ if (!n || !n.comments.some((t) => t.id === e && t.parentId === void 0)) return !1;
2479
+ let r = ++this._commentNavigationGeneration, i = !n.layoutComplete, a = n.commentAnchorRanges().filter((t) => t.commentId === e), o = t?.pageIndex;
2480
+ if (o !== void 0 && (!Number.isInteger(o) || o < 0)) return !1;
2481
+ let s = o ?? this._commentPageById.get(e), c, l = async () => {
2482
+ let t = n.commentAnchorRanges();
2483
+ for (; s === void 0 && this._commentScanFrontier < n.pageCount;) {
2484
+ let i = this._commentScanFrontier, a = await this._commentRunsForPage(i, n);
2485
+ if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2486
+ if (this._doc !== n || r !== this._commentNavigationGeneration || !a) return;
2487
+ this._indexCommentPages(i, a, t), s = this._commentPageById.get(e);
2488
+ }
2489
+ return s;
2490
+ };
2491
+ if (o === void 0 && s === void 0 && a.length > 0 && await l(), i && (o !== void 0 && o >= n.pageCount || o === void 0 && s === void 0)) {
2492
+ if (await this._errorRouter.ownBackgroundLifecycle(() => n.waitUntilLayoutComplete()), this._destroyed) throw Error("DocxScrollViewer is destroyed");
2493
+ if (this._doc !== n || r !== this._commentNavigationGeneration) return !1;
2494
+ a = n.commentAnchorRanges().filter((t) => t.commentId === e), this._commentPageById.clear(), this._commentRunsByPage.clear(), this._commentIndexedPages.clear(), this._commentScanFrontier = 0, s = o, o === void 0 && a.length > 0 && await l();
2495
+ }
2496
+ if (a.length === 0 || o !== void 0 && o >= n.pageCount || s === void 0) return !1;
2497
+ let u = await this._commentRunsForPage(s, n);
2498
+ if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2499
+ if (this._doc !== n || r !== this._commentNavigationGeneration || !u || (c = a.flatMap((e) => M(e, u))[0], !c)) return !1;
2500
+ this._activeCommentId = e, this._activeCommentPage = s, this._elementContext = null, this._scrollToPageTarget(s, c, t);
2501
+ for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
2502
+ return this._emitSelectionContextChange(), !0;
2503
+ }
2504
+ async findText(e, t = {}) {
2505
+ if (!this._doc) return [];
2506
+ let n = ++this._findRequestGeneration;
2507
+ if (this._doc.layoutComplete === !1) {
2508
+ let e = this._doc;
2509
+ if (await this._errorRouter.ownBackgroundLifecycle(() => e.waitUntilLayoutComplete()), this._destroyed || this._doc !== e || n !== this._findRequestGeneration) return [];
2510
+ }
2511
+ this._findActive = e.length > 0;
2512
+ let r = await this._errorRouter.ownAwaitable(() => this._find.find(e, t));
2513
+ return this._redrawHighlights(), r;
2514
+ }
2515
+ async findNext() {
2516
+ return this._activateMatch(this._find.next());
2517
+ }
2518
+ async findPrev() {
2519
+ return this._activateMatch(this._find.prev());
2520
+ }
2521
+ clearFind() {
2522
+ this._findRequestGeneration++, this._findActive = !1, this._find.invalidate(), this._redrawHighlights();
2523
+ }
2524
+ async _activateMatch(e) {
2525
+ return e && this.scrollToPage(e.location.page), this._redrawHighlights(), e;
2526
+ }
2527
+ async _collectPageRuns(e) {
2528
+ return this._doc ? this._doc.collectPageRuns(e, {
2529
+ width: this._pageWidthPx(e),
2530
+ currentDate: this._currentDate,
2531
+ ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {}
2532
+ }) : [];
2533
+ }
2534
+ _redrawHighlights() {
2535
+ for (let [e, t] of this._slots) this._redrawSlotHighlights(e, t);
2536
+ }
2537
+ _refreshFindRuns(e, t) {
2538
+ this._findActive && this._find.setPageRuns(e, t);
2539
+ }
2540
+ _commitCommentRuns(e, t, n) {
2541
+ t.commentTintLayer && (t.commentRuns = Object.freeze([...n]), this._commentRunsByPage.set(e, {
2542
+ scale: this._scale,
2543
+ runs: Promise.resolve(t.commentRuns)
2544
+ }), this._doc && e === this._commentScanFrontier && this._indexCommentPages(e, t.commentRuns, this._doc.commentAnchorRanges()), t.commentTintLayer.style.transform = "", t.commentTintLayer.style.transformOrigin = "", this._redrawSlotComments(e, t), t.commentTintLayer.style.visibility = "", t.commentMargin && (t.commentMargin.style.visibility = ""), t.commentDecorationLayer && (t.commentDecorationLayer.style.visibility = ""));
2545
+ }
2546
+ _redrawSlotComments(e, t) {
2547
+ if (!this._doc || !t.commentTintLayer) return;
2548
+ let n = this._commentUi;
2549
+ if (!n) {
2550
+ t.commentTintLayer.replaceChildren(), t.commentMargin?.replaceChildren(), t.commentDecorationLayer?.replaceChildren(), t.commentGeometry = null;
2551
+ return;
2552
+ }
2553
+ t.commentGeometry = n.buildDocxCommentMargin(t.commentTintLayer, t.commentMargin, t.commentRuns, {
2554
+ comments: this._doc.comments,
2555
+ anchors: this._doc.commentAnchorRanges()
2556
+ }, this._pageWidthPx(e), this._pageHeightPx(e), this._activeCommentId, (t, n) => {
2557
+ let r = n ? t : this._activeCommentId === t ? null : this._activeCommentId;
2558
+ if (r !== this._activeCommentId) {
2559
+ this._activeCommentId = r, this._activeCommentPage = r ? e : null, this._elementContext = null;
2560
+ for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
2561
+ this._emitSelectionContextChange();
2562
+ }
2563
+ }, this._commentZoom(), 280, this._commentsOptions()?.markers !== !1, this._commentsOptions()?.includeResolved === !0, t.commentDecorationLayer ? () => this._scheduleCommentGeometry(e, t, !1) : void 0, t.commentDecorationLayer ? () => this._scheduleCommentGeometry(e, t, !0) : void 0), this._redrawSlotCommentConnectors(e, t);
2564
+ }
2565
+ _redrawSlotCommentConnectors(e, t) {
2566
+ let n = t.commentDecorationLayer, r = t.commentMargin, i = t.commentGeometry, a = this._commentsOptions()?.connectors;
2567
+ if (!n || !r || !i || !a) return;
2568
+ let o = this._pageWidthPx(e), s = this._pageHeightPx(e), c = this._commentSide(), l = this._commentMarginExtent(), u = this._commentUi;
2569
+ u && u.buildReadOnlyCommentDecoration(n, Object.freeze({
2570
+ surfaceBounds: Object.freeze({
2571
+ x: c === "left" ? -l : 0,
2572
+ y: 0,
2573
+ width: o + l,
2574
+ height: s
2575
+ }),
2576
+ contentBounds: Object.freeze({
2577
+ x: 0,
2578
+ y: 0,
2579
+ width: o,
2580
+ height: s
2581
+ }),
2582
+ side: c,
2583
+ threads: u.projectReadOnlyCommentMarginScroll(i, r.scrollTop)
2584
+ }), {
2585
+ route: a.route ?? "bezier",
2586
+ stroke: a.stroke ?? "solid",
2587
+ color: a.color,
2588
+ activeColor: a.activeColor
2589
+ });
2590
+ }
2591
+ _scheduleCommentGeometry(e, t, n = !1) {
2592
+ let r = this._pendingCommentGeometry.get(e);
2593
+ if (this._pendingCommentGeometry.set(e, {
2594
+ slot: t,
2595
+ connectorsOnly: r?.slot === t ? r.connectorsOnly && n : n
2596
+ }), this._commentGeometryScheduled) return;
2597
+ this._commentGeometryScheduled = !0;
2598
+ let i = () => {
2599
+ this._commentGeometryScheduled = !1, this._commentGeometryFrame = null;
2600
+ let e = [...this._pendingCommentGeometry];
2601
+ if (this._pendingCommentGeometry.clear(), !this._destroyed) for (let [t, n] of e) {
2602
+ let { slot: e, connectorsOnly: r } = n;
2603
+ this._slots.get(t) === e && e.renderedScale === this._scale && (r ? this._redrawSlotCommentConnectors(t, e) : this._redrawSlotComments(t, e));
2604
+ }
2605
+ }, a = this._wrapper.ownerDocument.defaultView;
2606
+ a?.requestAnimationFrame ? this._commentGeometryFrame = a.requestAnimationFrame(i) : queueMicrotask(i);
2607
+ }
2608
+ _redrawSlotHighlights(e, t) {
2609
+ if (!this._findActive) {
2610
+ t.highlightLayer.innerHTML = "";
2611
+ return;
2612
+ }
2613
+ let n = this._find.pageRuns(e);
2614
+ if (!n) {
2615
+ t.highlightLayer.innerHTML = "";
2616
+ return;
2617
+ }
2618
+ X(t.highlightLayer, n, this._find.pageHighlights(e), this._pageWidthPx(e), this._pageHeightPx(e), (e) => this._measureForFont(e), this._opts.findHighlightColors);
2619
+ }
2620
+ _onResize() {
2621
+ if (!this._doc || this._doc.pageCount === 0) return;
2622
+ if (!this._scaleEstablished) {
2623
+ this.relayout();
2624
+ return;
2625
+ }
2626
+ if (this._opts.refitOnResize === !1) {
2627
+ this._lastFitWidth = this._fitWidthPx(), this._mountVisible();
2628
+ return;
2629
+ }
2630
+ let e = this._baseScale();
2631
+ if (e <= 0) return;
2632
+ let t = this._fitWidthPx();
2633
+ if (t === this._lastFitWidth) {
2634
+ this._mountVisible();
2635
+ return;
2636
+ }
2637
+ this._lastFitWidth = t;
2638
+ let n = this._prevBase > 0 ? this._scale / this._prevBase : 1;
2639
+ this._prevBase = e, this.setScale(e * n), this._mountVisible();
2640
+ }
2641
+ get topVisiblePage() {
2642
+ return this._lastRange?.topIndex ?? 0;
2643
+ }
2644
+ mountedPageIndicesForTest() {
2645
+ return [...this._slots.keys()];
2646
+ }
2647
+ scaleForTest() {
2648
+ return this._scale;
2649
+ }
2650
+ baseScaleForTest() {
2651
+ return this._baseScale();
2652
+ }
2653
+ renderEpochForTest() {
2654
+ return this._renderEpoch;
2655
+ }
2656
+ resizeForTest() {
2657
+ this._onResize();
2658
+ }
2659
+ contentAtViewportYForTest(e) {
2660
+ let t = this._range(), n = this._scrollHost.scrollTop + e, r = this._pageIndexAtOffset(t, n), i = this._heights[r] || 0;
2661
+ return {
2662
+ page: r,
2663
+ frac: i > 0 ? Math.min(1, Math.max(0, (n - t.offsets[r]) / i)) : 0
2664
+ };
2665
+ }
2666
+ viewportYOfForTest(e, t) {
2667
+ return (this._range().offsets[e] ?? 0) + t * (this._heights[e] || 0) - this._scrollHost.scrollTop;
2668
+ }
2669
+ async getResourceMetrics() {
2670
+ if (!this._doc) throw Error("Document not loaded");
2671
+ return await this._doc.getResourceMetrics();
2672
+ }
2673
+ getSelectionContext(e = {}) {
2674
+ if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2675
+ return (this._doc && this._activeCommentId !== null && this._activeCommentPage !== null ? Wt(this._doc.comments, this._doc.commentAnchorRanges(), this._activeCommentId, this._activeCommentPage, e) : null) || ((this._opts.enableTextSelection ? Q(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null, e) : null) ?? (this._elementContext ? L(this._elementContext, e.maxTextCharacters) : null));
2676
+ }
2677
+ _emitSelectionContextChange() {
2678
+ let e = this.getSelectionContext();
2679
+ e?.kind === "text" && (this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutlines());
2680
+ let t = JSON.stringify(e);
2681
+ t !== this._selectionContextKey && (this._selectionContextKey = t, this._opts.onSelectionContextChange?.(e ? structuredClone(e) : null));
2682
+ }
2683
+ _setElementContext(e) {
2684
+ this._elementContext = e ? structuredClone(e) : null, this._redrawElementOutlines(), this._emitSelectionContextChange();
2685
+ }
2686
+ _invalidateElementContext(e = !0) {
2687
+ this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutlines(), e && this._emitSelectionContextChange();
2688
+ }
2689
+ _redrawElementOutlines() {
2690
+ for (let [e, t] of this._slots) this._redrawElementOutlineForSlot(e, t);
2691
+ }
2692
+ _redrawElementOutlineForSlot(e, t) {
2693
+ let n = this._elementContext, r = this._doc;
2694
+ if (!n || !r || n.pageIndex !== e) {
2695
+ v(t.elementLayer, null);
2696
+ return;
2697
+ }
2698
+ let i = r.pageSize(e);
2699
+ v(t.elementLayer, {
2700
+ x: n.bounds.xPt / i.widthPt,
2701
+ y: n.bounds.yPt / i.heightPt,
2702
+ width: n.bounds.widthPt / i.widthPt,
2703
+ height: n.bounds.heightPt / i.heightPt
2704
+ });
2705
+ }
2706
+ async _onElementClick(e) {
2707
+ this._destroyed || e.defaultPrevented || e.button !== 0 || await this._resolveContextAt(e);
2708
+ }
2709
+ _onContextMenu(e) {
2710
+ let t;
2711
+ this._opts.onContextMenu?.({
2712
+ originalEvent: e,
2713
+ getContext: () => t ??= this._resolveContextAt(e)
2714
+ });
2715
+ }
2716
+ async _resolveContextAt(e) {
2717
+ let t = this._doc;
2718
+ if (this._destroyed || !t) return null;
2719
+ if (this._opts.enableTextSelection && Q(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null)) return this._emitSelectionContextChange(), this._destroyed ? null : this.getSelectionContext();
2720
+ if (!this._opts.enableElementSelection) return this.getSelectionContext();
2721
+ let n = e.target, r = [...this._slots].find(([, e]) => n !== null && e.wrapper.contains(n));
2722
+ if (!r) return this._invalidateElementContext(), null;
2723
+ let [i, a] = r, o = a.canvas.getBoundingClientRect();
2724
+ if (o.width <= 0 || o.height <= 0) return this._invalidateElementContext(), null;
2725
+ let s = e.clientX - o.left, c = e.clientY - o.top;
2726
+ if (s < 0 || c < 0 || s > o.width || c > o.height) return this._invalidateElementContext(), null;
2727
+ let l = ++this._elementHitGeneration, u = t.pageSize(i), d;
2728
+ try {
2729
+ d = await t.getElementContextAt(i, {
2730
+ xPt: s / o.width * u.widthPt,
2731
+ yPt: c / o.height * u.heightPt
2732
+ }, {
2733
+ currentDate: this._currentDate,
2734
+ ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2735
+ maxTextCharacters: N
2736
+ });
2737
+ } catch (e) {
2738
+ if (this._destroyed || l !== this._elementHitGeneration || t !== this._doc) return null;
2739
+ throw e;
2740
+ }
2741
+ return this._destroyed || l !== this._elementHitGeneration || t !== this._doc ? null : (this._setElementContext(d), this._destroyed ? null : this.getSelectionContext());
2742
+ }
2743
+ destroy() {
2744
+ if (!this._destroyed) {
2745
+ this._destroyed = !0, this._findRequestGeneration++, this._errorRouter.close(), this._unbindLayoutDocument(), this._layoutViewGeneration++, this._resetCommentNavigation(), 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._commentOutsidePointerListener &&= (this._wrapper.ownerDocument.removeEventListener("pointerdown", this._commentOutsidePointerListener), null), this._commentGeometryFrame !== null && (this._wrapper.ownerDocument.defaultView?.cancelAnimationFrame?.(this._commentGeometryFrame), this._commentGeometryFrame = null), this._commentGeometryScheduled = !1, this._pendingCommentGeometry.clear(), 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);
2746
+ for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
2747
+ this._free.length = 0, this._documentOwner.close(), this._wrapper.remove();
2748
+ }
2749
+ }
2750
+ };
2751
+ //#endregion
2752
+ //#region packages/docx/src/types.ts
2753
+ function an(e) {
2754
+ let t = [];
2755
+ for (let n of e.content) {
2756
+ if (n.type !== "paragraph") continue;
2757
+ let e = "";
2758
+ for (let t of n.runs) t.type === "text" && !t.noteRef && (e += t.text);
2759
+ e = e.trim(), e && t.push(e);
2760
+ }
2761
+ return t.join(" ");
2762
+ }
2763
+ //#endregion
2764
+ //#region src/docx.ts
2765
+ var on = /* @__PURE__ */ e({
2766
+ DocxDocument: () => q,
2767
+ DocxScrollViewer: () => rn,
2768
+ DocxViewer: () => Yt,
2769
+ OoxmlDecodedImageLimitError: () => Je,
2770
+ OoxmlError: () => o,
2771
+ OoxmlResourceLimitError: () => n,
2772
+ autoResize: () => pe,
2773
+ buildDocxHighlightLayer: () => X,
2774
+ buildDocxTextLayer: () => Y,
2775
+ isOoxmlDecodedImageLimitError: () => Ye,
2776
+ noteText: () => an,
2777
+ openExternalHyperlink: () => s,
2778
+ readDocxTextSelectionContext: () => Q,
2779
+ resolveCommentAnchorRuns: () => M,
2780
+ resolveDocxCommentThreads: () => $e,
2781
+ resolveRevisionAnchorRuns: () => kt
2782
+ });
2783
+ //#endregion
2784
+ export { Q as a, q as c, Yt as i, kt as l, an as n, X as o, rn as r, Y as s, on as t };