@silurus/ooxml 0.76.1 → 0.77.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +144 -32
- package/dist/{canvas-viewer-mechanics-CwVSOYke.js → canvas-viewer-mechanics-DTkBvITv.js} +318 -152
- package/dist/{document-pull-client-AAnwzlig.js → document-pull-client-iWr8-S7P.js} +4829 -4210
- package/dist/{docx-CCksIXd5.js → docx-B1gYS6eU.js} +612 -191
- package/dist/docx.mjs +3 -3
- package/dist/docx_parser_bg.wasm +0 -0
- package/dist/index.mjs +3 -3
- package/dist/node.mjs +5 -5
- package/dist/{pptx-CKAk5e-J.js → pptx-CQjtK_o7.js} +646 -258
- package/dist/pptx.mjs +4 -4
- package/dist/pptx_parser_bg.wasm +0 -0
- package/dist/{render-CLcpSi0m.js → render-Ca80nlG5.js} +1 -1
- package/dist/{render-worker-host-Bkf1jUcW.js → render-worker-host-BozYMmxO.js} +1 -1
- package/dist/render-worker-host-C96AiK8e.js +27 -0
- package/dist/{render-worker-host-CKOmXdyr.js → render-worker-host-EHG5j8FK.js} +1 -1
- package/dist/{session-B4Y54cbT.js → session-KvKxQAeL.js} +1 -1
- package/dist/{slide-pull-client-WCuYCjio.js → slide-pull-client-BXb67StB.js} +15 -11
- package/dist/types/docx.d.ts +130 -28
- package/dist/types/index.d.ts +414 -87
- package/dist/types/node.d.ts +36 -20
- package/dist/types/pptx.d.ts +136 -10
- package/dist/types/xlsx.d.ts +176 -55
- package/dist/{xlsx-BBmmZNQn.js → xlsx-RLCmd1Bm.js} +2074 -1140
- package/dist/xlsx.mjs +4 -4
- package/package.json +3 -2
- package/dist/render-worker-host-B8HAb_sK.js +0 -27
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
import { t as e } from "./chunk-DmhlhrBa.js";
|
|
2
2
|
import { B as t, Et as n, It as r, Lt as i, R as a, a as o, an as s, hn as c, ht as l, it as u, kt as d, mn as f, q as p, z as m } from "./line-metrics-BdCACYlq.js";
|
|
3
|
-
import {
|
|
4
|
-
import { a as
|
|
5
|
-
import { _ as D, a as
|
|
6
|
-
import { n as
|
|
3
|
+
import { C as h, E as g, S as _, T as v, _ as y, a as b, b as x, c as S, d as ee, f as te, g as ne, h as re, i as C, l as w, 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 T, w as fe, x as pe, y as E } from "./canvas-viewer-mechanics-DTkBvITv.js";
|
|
4
|
+
import { a as me, c as he, i as ge, o as _e, r as ve, s as ye, t as be } from "./bounded-raw-part-cache-C6ro6Ezf.js";
|
|
5
|
+
import { C as xe, S as Se, _ as D, a as Ce, b as we, c as Te, d as Ee, f as De, g as Oe, h as ke, l as Ae, m as je, n as O, o as Me, p as Ne, s as Pe, t as k, v as A, w as Fe, x as j, y as Ie } from "./document-pull-client-iWr8-S7P.js";
|
|
6
|
+
import { n as Le, r as M, t as N } from "./highlight-rect-CAkCWJ37.js";
|
|
7
7
|
//#region packages/core/src/fonts/embedded.ts
|
|
8
|
-
function
|
|
9
|
-
let n =
|
|
8
|
+
function Re(e, t) {
|
|
9
|
+
let n = ze(t), r = e.slice(), i = Math.min(32, r.length);
|
|
10
10
|
for (let e = 0; e < i; e++) r[e] ^= n[e % 16];
|
|
11
11
|
return r;
|
|
12
12
|
}
|
|
13
|
-
function
|
|
13
|
+
function ze(e) {
|
|
14
14
|
let t = e.replace(/[{}\-\s]/g, "");
|
|
15
15
|
if (t.length !== 32 || /[^0-9a-fA-F]/.test(t)) throw Error(`invalid fontKey GUID: ${e}`);
|
|
16
16
|
let n = new Uint8Array(16);
|
|
17
17
|
for (let e = 0; e < 16; e++) n[e] = parseInt(t.slice(e * 2, e * 2 + 2), 16);
|
|
18
18
|
return n.reverse();
|
|
19
19
|
}
|
|
20
|
-
function
|
|
20
|
+
function Be(e, t, n, r) {
|
|
21
21
|
let i = 2166136261;
|
|
22
22
|
for (let e = 0; e < r.length; e++) i ^= r[e], i = Math.imul(i, 16777619);
|
|
23
23
|
return `${e}|${t}|${n}|${r.length}|${(i >>> 0).toString(16)}`;
|
|
24
24
|
}
|
|
25
|
-
async function
|
|
26
|
-
let n =
|
|
25
|
+
async function Ve(e, t = 30 * 1024 * 1024) {
|
|
26
|
+
let n = ve();
|
|
27
27
|
if (!n || typeof FontFace > "u") return [];
|
|
28
28
|
let r = [], i = [], a = [];
|
|
29
29
|
for (let o of e) try {
|
|
@@ -31,7 +31,7 @@ async function Ce(e, t = 30 * 1024 * 1024) {
|
|
|
31
31
|
a.push(o.family);
|
|
32
32
|
continue;
|
|
33
33
|
}
|
|
34
|
-
let e = o.odttf ?
|
|
34
|
+
let e = o.odttf ? Re(o.bytes, o.fontKey ?? "") : o.bytes, { face: s, isNew: c } = he(`embedded:${Be(o.family, o.weight, o.style, e)}`, n, () => {
|
|
35
35
|
let t = e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength), r = new FontFace(o.family, t, {
|
|
36
36
|
weight: o.weight,
|
|
37
37
|
style: o.style
|
|
@@ -42,20 +42,20 @@ async function Ce(e, t = 30 * 1024 * 1024) {
|
|
|
42
42
|
} catch {
|
|
43
43
|
a.push(o.family);
|
|
44
44
|
}
|
|
45
|
-
return i.length > 0 && await
|
|
45
|
+
return i.length > 0 && await _e(Promise.allSettled(i.map((e) => e.load())).then((e) => (e.forEach((e, t) => {
|
|
46
46
|
e.status === "rejected" && a.push(i[t].family);
|
|
47
47
|
}), n.ready))), a.length > 0 && console.warn(`[ooxml] failed to register embedded font(s): ${[...new Set(a)].join(", ")}; falling back to substitute fonts (text may shift or differ).`), r;
|
|
48
48
|
}
|
|
49
|
-
function
|
|
50
|
-
|
|
49
|
+
function He(e) {
|
|
50
|
+
ye(e);
|
|
51
51
|
}
|
|
52
52
|
//#endregion
|
|
53
53
|
//#region packages/docx/src/worker.ts?worker&inline
|
|
54
|
-
var H = "var e=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,n.unregister(this),e}free(){let e=this.__destroy_into_raw();g.__wbg_docxarchive_free(e,0)}acknowledge_document_chunk(e,t,n){let r=g.docxarchive_acknowledge_document_chunk(this.__wbg_ptr,e,t,n);if(r[1])throw d(r[0])}assert_healthy(){let e=g.docxarchive_assert_healthy(this.__wbg_ptr);if(e[1])throw d(e[0])}cancel_document_cursor(){g.docxarchive_cancel_document_cursor(this.__wbg_ptr)}close_document_session(){g.docxarchive_close_document_session(this.__wbg_ptr)}document_chunk_done(){let e=g.docxarchive_document_chunk_done(this.__wbg_ptr);if(e[2])throw d(e[1]);return e[0]!==0}document_cursor_resource_usage(){let e=g.docxarchive_document_cursor_resource_usage(this.__wbg_ptr);if(e[3])throw d(e[2]);var t=r(e[0],e[1]).slice();return g.__wbindgen_free(e[0],e[1]*1,1),t}extract_image(e){let t=u(e,g.__wbindgen_malloc,g.__wbindgen_realloc),n=h,i=g.docxarchive_extract_image(this.__wbg_ptr,t,n);if(i[3])throw d(i[2]);var a=r(i[0],i[1]).slice();return g.__wbindgen_free(i[0],i[1]*1,1),a}constructor(e,t,r,i){let a=ee(e,g.__wbindgen_malloc),o=h,s=g.docxarchive_new(a,o,!l(t),l(t)?BigInt(0):t,!l(r),l(r)?BigInt(0):r,!l(i),l(i)?BigInt(0):i);if(s[2])throw d(s[1]);return this.__wbg_ptr=s[0]>>>0,n.register(this,this.__wbg_ptr,this),this}open_document_cursor(e,t){let n=g.docxarchive_open_document_cursor(this.__wbg_ptr,e,t);if(n[1])throw d(n[0])}parse(){let e=g.docxarchive_parse(this.__wbg_ptr);if(e[3])throw d(e[2]);var t=r(e[0],e[1]).slice();return g.__wbindgen_free(e[0],e[1]*1,1),t}pull_document_chunk(e,t,n,i){let a=g.docxarchive_pull_document_chunk(this.__wbg_ptr,e,t,n,i);if(a[3])throw d(a[2]);var o=r(a[0],a[1]).slice();return g.__wbindgen_free(a[0],a[1]*1,1),o}resource_usage(){let e=g.docxarchive_resource_usage(this.__wbg_ptr);if(e[3])throw d(e[2]);var t=r(e[0],e[1]).slice();return g.__wbindgen_free(e[0],e[1]*1,1),t}to_markdown(){let e,t;try{let i=g.docxarchive_to_markdown(this.__wbg_ptr);var n=i[0],r=i[1];if(i[3])throw n=0,r=0,d(i[2]);return e=n,t=r,o(n,r)}finally{g.__wbindgen_free(e,t,1)}}};Symbol.dispose&&(e.prototype[Symbol.dispose]=e.prototype.free);function t(){return{__proto__:null,\"./docx_parser_bg.js\":{__proto__:null,__wbg___wbindgen_throw_6b64449b9b9ed33c:function(e,t){throw Error(o(e,t))},__wbg_error_a6fa202b58aa1cd3:function(e,t){let n,r;try{n=e,r=t,console.error(o(e,t))}finally{g.__wbindgen_free(n,r,1)}},__wbg_new_227d7c05414eb861:function(){return Error()},__wbg_stack_3b0d974bbf31e44f:function(e,t){let n=t.stack,r=u(n,g.__wbindgen_malloc,g.__wbindgen_realloc),i=h;a().setInt32(e+4,i,!0),a().setInt32(e+0,r,!0)},__wbindgen_cast_0000000000000001:function(e,t){return o(e,t)},__wbindgen_init_externref_table:function(){let e=g.__wbindgen_externrefs,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)}}}}const n=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>g.__wbg_docxarchive_free(e>>>0,1));function r(e,t){return e>>>=0,c().subarray(e/1,e/1+t)}let i=null;function a(){return(i===null||i.buffer.detached===!0||i.buffer.detached===void 0&&i.buffer!==g.memory.buffer)&&(i=new DataView(g.memory.buffer)),i}function o(e,t){return e>>>=0,te(e,t)}let s=null;function c(){return(s===null||s.byteLength===0)&&(s=new Uint8Array(g.memory.buffer)),s}function l(e){return e==null}function ee(e,t){let n=t(e.length*1,1)>>>0;return c().set(e,n/1),h=e.length,n}function u(e,t,n){if(n===void 0){let n=m.encode(e),r=t(n.length,1)>>>0;return c().subarray(r,r+n.length).set(n),h=n.length,r}let r=e.length,i=t(r,1)>>>0,a=c(),o=0;for(;o<r;o++){let t=e.charCodeAt(o);if(t>127)break;a[i+o]=t}if(o!==r){o!==0&&(e=e.slice(o)),i=n(i,r,r=o+e.length*3,1)>>>0;let t=c().subarray(i+o,i+r),a=m.encodeInto(e,t);o+=a.written,i=n(i,r,o,1)>>>0}return h=o,i}function d(e){let t=g.__wbindgen_externrefs.get(e);return g.__externref_table_dealloc(e),t}let f=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0});f.decode();let p=0;function te(e,t){return p+=t,p>=2146435072&&(f=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}),f.decode(),p=t),f.decode(c().subarray(e,e+t))}const m=new TextEncoder;`encodeInto`in m||(m.encodeInto=function(e,t){let n=m.encode(e);return t.set(n),{read:e.length,written:n.length}});let h=0,g;function _(e,t){return g=e.exports,i=null,s=null,g.__wbindgen_start(),g}async function v(e,t){if(typeof Response==`function`&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming==`function`)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if(e.ok&&n(e.type)&&e.headers.get(`Content-Type`)!==`application/wasm`)console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\",t);else throw t}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{let n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}function n(e){switch(e){case`basic`:case`cors`:case`default`:return!0}return!1}}async function y(e){if(g!==void 0)return g;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn(`using deprecated parameters for the initialization function; pass a single object instead`));let n=t();(typeof e==`string`||typeof Request==`function`&&e instanceof Request||typeof URL==`function`&&e instanceof URL)&&(e=fetch(e));let{instance:r,module:i}=await v(await e,n);return _(r,i)}async function b(e){return g=void 0,i=null,s=null,y(e)}var x=class e extends Error{code;constructor(t,n){super(n),this.name=`OoxmlError`,this.code=t,Object.setPrototypeOf(this,e.prototype)}},S=class e extends Error{code=`ooxml-resource-limit`;details;constructor(t,n){super(t),this.name=`OoxmlResourceLimitError`;let r=n.violation,i=Object.freeze({format:r.format,operation:r.operation,resource:r.resource,metric:r.metric,...r.part===void 0?{}:{part:r.part},limit:r.limit,observed:r.observed,configurable:r.configurable,usage:Object.freeze({archiveEntryCount:r.usage.archiveEntryCount,declaredInflatedBytes:r.usage.declaredInflatedBytes,...r.usage.largestInflatedEntryBytes===void 0?{}:{largestInflatedEntryBytes:r.usage.largestInflatedEntryBytes},distinctInflatedBytes:r.usage.distinctInflatedBytes,operationInflatedBytes:r.usage.operationInflatedBytes})});this.details=Object.freeze({stage:n.stage,violation:i}),Object.setPrototypeOf(this,e.prototype)}},ne=class e extends RangeError{code=`ooxml-decoded-image-limit`;constructor(t,n,r){super(`OOXML decoded image limit exceeded: ${t} ${r} > ${n}`),this.metric=t,this.limit=n,this.observed=r,this.name=`OoxmlDecodedImageLimitError`,Object.setPrototypeOf(this,e.prototype)}};function re(e){if(!e.startsWith(`data:`))return null;let t=e.indexOf(`,`);if(t===-1)return null;let n=atob(e.slice(t+1)),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r.buffer}var ie=class{state=`uninitialized`;generationValue=0;readiness;poisonListeners=new Set;constructor(e,t,n){this.initialize=e,this.reinitialize=t,this.normalizeFailure=n}get generation(){return this.generationValue}get poisoned(){return this.state===`poisoned`}onPoison(e){return this.poisonListeners.add(e),()=>this.poisonListeners.delete(e)}async ensureReady(){if(this.state!==`ready`){if(!this.readiness){let e=this.state===`uninitialized`?this.initialize:this.reinitialize;this.readiness=Promise.resolve().then(e).then(()=>{this.generationValue+=1,this.state=`ready`,this.readiness=void 0},e=>{throw this.readiness=void 0,e})}await this.readiness}}run(e){try{return e()}catch(e){let t=this.normalizeFailure(e);throw t?(this.poison(t),t):e}}tryRunReady(e){if(this.state!==`ready`)return{current:!1};let t=this.generationValue,n=this.run(e);return this.state!==`ready`||t!==this.generationValue?{current:!1}:{current:!0,generation:t,value:n}}poison(e){this.state=`poisoned`,this.readiness=void 0;for(let t of this.poisonListeners)t(e)}assertCurrent(e){if(this.state!==`ready`||e!==this.generationValue)throw Error(`WASM archive session belongs to a discarded runtime generation`)}},C=class e extends Error{code=`parser-crashed`;constructor(t){super(t),this.name=`WasmTrapError`,Object.setPrototypeOf(this,e.prototype)}};function ae(e){let t=globalThis.WebAssembly?.RuntimeError;return t&&e instanceof t||e instanceof RangeError?!0:e instanceof Error?e.name===`RuntimeError`||e.name===`CompileError`||e.name===`LinkError`||e.name===`InternalError`||e.name===`OOMError`:!1}function w(e){try{if((typeof e!=`object`||!e)&&typeof e!=`function`)return;let t=Reflect.get(e,`__destroy_into_raw`);typeof t==`function`&&Reflect.apply(t,e,[])}catch{}}function T(e,t){return e({module_or_path:t})}var oe=class{runtime;wasmInput=null;currentArchive=null;constructor(e,t={}){this.init=e,this.options=t,this.runtime=new ie(()=>this.invokeConfigured(this.init),()=>this.invokeConfigured(this.options.reinit??this.init),E),this.runtime.onPoison(()=>this.dropPoisonedArchive())}setWasmInput(e){this.wasmInput=e,this.runtime.ensureReady().catch(()=>void 0)}setWasmUrl(e){this.setWasmInput(e)}get archive(){return this.currentArchive}setArchive(e){this.freeArchive(),this.currentArchive=e}disposeArchive(){this.freeArchive()}get poisoned(){return this.runtime.poisoned}async ensureReady(){await this.runtime.ensureReady()}run(e){return this.runtime.run(e)}poison(){this.runtime.poison(new C(`WASM parser was recycled`))}invokeConfigured(e){return this.wasmInput===null?Promise.reject(Error(`WasmParserHost: setWasmInput was never called`)):T(e,this.wasmInput)}freeArchive(){this.currentArchive!==null&&this.options.freeArchive&&this.options.freeArchive(this.currentArchive),this.currentArchive=null}dropPoisonedArchive(){let e=this.currentArchive;this.currentArchive=null,w(e)}};function E(e){return ae(e)?new C(`WASM parser trapped and was recycled: ${e instanceof Error?e.message:String(e)}`):null}function D(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function se(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return D(t.requiredBytes)&&D(t.offeredBytes)&&t.requiredBytes>t.offeredBytes}var O=class e extends RangeError{code=`ooxml-insufficient-credit`;requiredBytes;offeredBytes;constructor(t){super(`Pull unit requires ${t.requiredBytes} bytes but credit is ${t.offeredBytes}`),this.name=`PullSessionInsufficientCreditError`,this.requiredBytes=t.requiredBytes,this.offeredBytes=t.offeredBytes,Object.setPrototypeOf(this,e.prototype)}};function k(e){if(e instanceof O)return e;let t=e instanceof Error?e.message:String(e);if(!t.startsWith(`OOXML_INSUFFICIENT_CREDIT:`))return;let n;try{n=JSON.parse(t.slice(26))}catch{return}if(!n||typeof n!=`object`||Array.isArray(n))return;let r=n;if(!(r.code!==`ooxml-insufficient-credit`||!se(r)))return new O(r)}function ce(e,t,n){let r=k(e);if(!(!r||r.offeredBytes!==t||r.requiredBytes>n))return r}const A=`OOXML_RESOURCE_LIMIT:`;function j(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function M(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return j(t.archiveEntryCount)&&j(t.declaredInflatedBytes)&&(t.largestInflatedEntryBytes===void 0||j(t.largestInflatedEntryBytes))&&j(t.distinctInflatedBytes)&&j(t.operationInflatedBytes)}function N(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw TypeError(`OOXML resource usage checkpoint is not valid JSON`)}if(!M(t))throw TypeError(`OOXML resource usage checkpoint is invalid`);return t}function le(e){return e===`docx`||e===`xlsx`||e===`pptx`}function P(e){return e===`container`||e===`decompression`||e===`parsing`||e===`serialization`||e===`layout`||e===`rendering`||e===`worker`}function F(e,t){return typeof e==`string`&&e.length>0&&e.length<=t&&!/[\\u0000-\\u001f\\u007f]/u.test(e)}function I(e){return F(e,128)&&/^[a-z0-9][a-z0-9-]*$/u.test(e)}function L(e){return!F(e,4096)||e.startsWith(`/`)||e.startsWith(`\\\\`)||e.includes(`\\\\`)||e.includes(`?`)||e.includes(`#`)||e.includes(`://`)||/^[a-z]:/iu.test(e)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}const R=new Map([[`archive-entry:declared-inflated-bytes`,{stage:`container`,part:`required`}],[`archive-entry:actual-inflated-bytes`,{stage:`decompression`,part:`required`}],[`archive:entry-count`,{stage:`container`,part:`forbidden`}],[`archive:central-directory-bytes`,{stage:`container`,part:`forbidden`,configurable:!1}],[`archive:distinct-inflated-bytes`,{stage:`decompression`,part:`required`}],[`xml-event:bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`xml-context:bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`xml-tree:depth`,{stage:`parsing`,part:`optional`,configurable:!1}],[`worksheet-row:projected-bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`worksheet-shell:projected-bytes`,{stage:`parsing`,part:`optional`,configurable:!1}]]),z=new Set([...R.keys()].map(e=>e.slice(0,e.indexOf(`:`)))),B=new Set([...R.keys()].map(e=>e.slice(e.indexOf(`:`)+1)));function V(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return!le(t.format)||!F(t.operation,256)||!I(t.resource)||!I(t.metric)||!j(t.limit)||!j(t.observed)||typeof t.configurable!=`boolean`||!M(t.usage)?!1:!(`part`in t)||L(t.part)}function H(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;if(!P(t.stage)||!V(t.violation))return!1;let n=t.violation,r=R.get(`${n.resource}:${n.metric}`);return r?t.stage!==r.stage||r.configurable===!1&&n.configurable!==!1?!1:r.part===`required`?n.part!==void 0:r.part===`forbidden`?n.part===void 0:!0:!(z.has(n.resource)&&B.has(n.metric))}function U(e){return{archiveEntryCount:e.archiveEntryCount,declaredInflatedBytes:e.declaredInflatedBytes,...e.largestInflatedEntryBytes===void 0?{}:{largestInflatedEntryBytes:e.largestInflatedEntryBytes},distinctInflatedBytes:e.distinctInflatedBytes,operationInflatedBytes:e.operationInflatedBytes}}function ue(e){if(!H(e))return;let t=e.violation,n={stage:e.stage,violation:{format:t.format,operation:t.operation,resource:t.resource,metric:t.metric,...t.part===void 0?{}:{part:t.part},limit:t.limit,observed:t.observed,configurable:t.configurable,usage:U(t.usage)}};return H(n)?n:void 0}function W(e){let t=e.violation;return`OOXML resource limit exceeded${t.part?` for ${t.part}`:``}: ${t.metric} ${t.observed} > ${t.limit}`}function de(e){let t=e instanceof Error?e.message:String(e);if(!t.startsWith(A))return;let n;try{n=JSON.parse(t.slice(21))}catch{return}if(!n||typeof n!=`object`)return;let r=n;if(!(r.code!==`ooxml-resource-limit`||!H(r.details)))return new S(W(r.details),r.details)}function fe(e){if(e instanceof ne)return{message:e.message,errorName:e.name,code:e.code,decodedImage:{metric:e.metric,limit:e.limit,observed:e.observed}};let t=k(e);if(t)return{message:t.message,errorName:t.name,code:t.code,insufficientCredit:{requiredBytes:t.requiredBytes,offeredBytes:t.offeredBytes}};let n=e instanceof x||e instanceof S?e:de(e);if(n instanceof S){let e=ue(n.details);return e?{message:typeof n.message==`string`?n.message:W(e),errorName:`OoxmlResourceLimitError`,code:`ooxml-resource-limit`,resourceLimit:e}:{message:`Invalid OOXML resource-limit error payload`,errorName:`Error`}}if(n instanceof x)return{message:typeof n.message==`string`?n.message:String(n.message),errorName:F(n.name,128)?n.name:`OoxmlError`,...I(n.code)?{code:n.code}:{}};let r=e instanceof Error?e.message:String(e);if(typeof r==`string`&&r.startsWith(A))return{message:`Invalid OOXML resource-limit payload`,errorName:`Error`};let i=e instanceof Error?e:Error(r),a=i;return{message:typeof i.message==`string`?i.message:String(i.message),errorName:F(i.name,128)?i.name:`Error`,...typeof a.code==`string`?{code:a.code}:{}}}function G(e){try{return fe(e)}catch{return{message:`Worker operation failed with an unreadable error`,errorName:`Error`}}}function pe(e){return e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&e.buffer instanceof ArrayBuffer?e.buffer:e.slice().buffer}Object.freeze({maxArchiveEntryBytes:134217728,maxTotalInflatedBytes:268435456,maxArchiveEntries:4096});function me(e){return[e.maxArchiveEntryBytes===null?0n:BigInt(e.maxArchiveEntryBytes),e.maxTotalInflatedBytes===null?0n:BigInt(e.maxTotalInflatedBytes),e.maxArchiveEntries===null?0n:BigInt(e.maxArchiveEntries)]}const K=`ooxml-pull-v1`;function q(e,t){if(!Number.isSafeInteger(e)||e<=0)throw RangeError(`${t} must be a positive safe integer`)}function he(e){if(!(typeof e==`string`&&e.length>0||typeof e==`number`&&Number.isSafeInteger(e)&&e>0))throw RangeError(`session id must be a non-empty string or positive safe integer`)}var J=class{owner;queue=Promise.resolve();leases=new Map;retainedBytes=0;retainedCount=0;maxRetainedBytes;maxRetainedCount;cleanups=new Set;pendingFatalCleanups=[];poisonRunning=!1;fatal;constructor(e){this.maxRetainedBytes=e?.maxRetainedBytes??64*1024*1024,this.maxRetainedCount=e?.maxRetainedCount??256,q(this.maxRetainedBytes,`max retained lease bytes`),q(this.maxRetainedCount,`max retained lease count`)}enqueue(e){let t=this.queue.then(e,e);return this.queue=t.then(()=>void 0,()=>void 0),t}acquire(e){return this.owner===void 0?(this.owner=e,!0):this.owner===e}release(e){this.owner===e&&(this.owner=void 0)}retainLease(e,t,n){if(!Number.isSafeInteger(n)||n<0)throw RangeError(`retained lease bytes are invalid`);let r=this.leases.get(e)??new Map;if(r.has(t))throw Error(`driver returned a duplicate lease id`);if(this.retainedCount+1>this.maxRetainedCount)throw RangeError(`retained lease count exceeds limit`);if(this.retainedBytes+n>this.maxRetainedBytes)throw RangeError(`retained lease bytes exceed limit`);r.set(t,n),this.leases.set(e,r),this.retainedCount++,this.retainedBytes+=n}releaseLease(e,t){let n=this.leases.get(e),r=n?.get(t);r!==void 0&&(n?.delete(t),n?.size===0&&this.leases.delete(e),this.retainedCount--,this.retainedBytes-=r)}registerCleanup(e){return this.fatal?(this.poisonRunning?this.pendingFatalCleanups.push(e):this.enqueue(e).catch(()=>void 0),()=>void 0):(this.cleanups.add(e),()=>this.cleanups.delete(e))}get fatalError(){return this.fatal}get registeredHostCount(){return this.cleanups.size}async poison(e){if(this.fatal??=e,this.poisonRunning)return this.fatal;this.poisonRunning=!0,this.pendingFatalCleanups.push(...this.cleanups);try{let e;for(;(e=this.pendingFatalCleanups.shift())!==void 0;)await e().catch(()=>void 0)}finally{this.poisonRunning=!1}return this.fatal}},ge=class{options;coordinator;coordinatorOwner=Symbol(`pull-session-host`);unregisterCleanup;sequence=0;unacked;leases=new Map;activeDriverLeases=new Set;nextWireLeaseId;cancelRequested=!1;cancelComplete=!1;closeRequested=!1;closeComplete=!1;driverCancelComplete=!1;driverCloseComplete=!1;completed=!1;constructor(e){he(e.sessionId),q(e.operationId,`operation id`),q(e.generation,`generation`),q(e.maxByteCredit,`max byte credit`),e.wireLeaseIdStart!==void 0&&q(e.wireLeaseIdStart,`wire lease id start`),this.options=e,this.coordinator=e.coordinator,this.nextWireLeaseId=e.wireLeaseIdStart??1,this.unregisterCleanup=this.coordinator.registerCleanup(()=>this.forceFatalCleanup())}dispatch(e,t){return this.coordinator.enqueue(async()=>{let n=await this.execute(e);try{t(n.response,n.transfer)}catch(e){throw await this.rollbackFailedPost(n),e}})}async rollbackFailedPost(e){let t=e.response;if(t.kind===`chunk`){let n=t.leaseId===void 0?void 0:this.leases.get(t.leaseId);try{await this.options.driver.disposeInvalidChunk?.({payload:t.payload,byteLength:t.byteLength,done:t.done,leaseId:n?.driverLeaseId,retainedBytes:n?.retainedBytes,transfer:e.transfer})}catch{}}this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);for(let[e,t]of[...this.leases])try{await this.options.driver.releaseLease?.(t.driverLeaseId)}catch{}finally{this.leases.delete(e),this.activeDriverLeases.delete(t.driverLeaseId),this.coordinator.releaseLease(this.coordinatorOwner,e)}if(this.cancelRequested=!0,!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch{}this.unregisterCleanup()}async execute(e){try{if(this.isStaleLifecycle(e)){let t=e.kind===`cancel`?`cancel`:`close`;return this.sameOperationIdentity(e)?{response:this.accepted(e,t,!0)}:{response:this.errorResponse(e,{message:`stale lifecycle targets another session or operation`,errorName:`PullSessionProtocolError`,code:`ooxml-stale-lifecycle`})}}this.validateCommandIdentity(e);let t=this.coordinator.fatalError;if(t)return e.kind===`pull`?{response:this.errorResponse(e,t)}:(e.kind===`cancel`?await this.cancel():e.kind===`close`?await this.close():e.kind===`release`&&await this.release(e.leaseId),{response:this.accepted(e,e.kind)});switch(e.kind){case`pull`:return await this.pull(e);case`ack`:return await this.ack(e.sequence),{response:this.accepted(e,`ack`)};case`release`:return await this.release(e.leaseId),{response:this.accepted(e,`release`)};case`cancel`:return await this.cancel(),{response:this.accepted(e,`cancel`)};case`close`:return await this.close(),{response:this.accepted(e,`close`)}}}catch(t){let n=G(t);return n.code===`ooxml-resource-limit`&&(n=await this.coordinator.poison(n)),{response:this.errorResponse(e,n)}}}async pull(e){if(this.closeRequested||this.cancelRequested||this.completed)throw Error(`pull session is closed`);if(this.unacked)throw Error(`previous chunk is not acknowledged`);if(!Number.isSafeInteger(e.sequence)||e.sequence<0||e.sequence!==this.sequence)throw Error(`pull command sequence mismatch`);if(this.validateHostCredit(e.byteCredit),!this.coordinator.acquire(this.coordinatorOwner))throw Error(`another operation has an unacknowledged package chunk`);let t;try{t=await this.options.driver.pull(e.byteCredit)}catch(e){throw this.coordinator.release(this.coordinatorOwner),e}let n=!1,r=!1,i,a;try{let o=this.options.driver.measureChunk(t),s=this.arrayBufferTransferBytes(t.transfer);if(o<s)throw RangeError(`measured chunk bytes are below ArrayBuffer transfer bytes`);if(a=Math.max(o,s),t.leaseId!==void 0){if(q(t.leaseId,`lease id`),t.retainedBytes===void 0)throw Error(`retained lease bytes are required`);if(this.activeDriverLeases.has(t.leaseId))throw r=!0,Error(`driver returned an active duplicate lease id`);i=this.allocateWireLeaseId(),this.coordinator.retainLease(this.coordinatorOwner,i,t.retainedBytes),this.leases.set(i,{driverLeaseId:t.leaseId,retainedBytes:t.retainedBytes}),this.activeDriverLeases.add(t.leaseId),n=!0}else if(t.retainedBytes!==void 0)throw Error(`retained lease bytes require a lease id`);if(!Number.isSafeInteger(a)||a<0)throw RangeError(`host chunk byte length must be a non-negative safe integer`);if(a>e.byteCredit)throw RangeError(`host chunk exceeds byte credit`)}catch(e){let a;try{await this.options.driver.disposeInvalidChunk?.(t)}catch(e){a=e}if(n&&i!==void 0)try{await this.release(i)}catch(e){a??=e}else if(t.leaseId!==void 0&&!r)try{await this.options.driver.releaseLease?.(t.leaseId)}catch(e){a??=e}if(r)try{await this.cancel()}catch(e){a??=e}throw this.coordinator.release(this.coordinatorOwner),a||e}return this.unacked={sequence:this.sequence,done:t.done},{response:{kind:`chunk`,protocol:K,...this.identity(),requestId:e.requestId,sequence:this.sequence,byteLength:a,done:t.done,payload:t.payload,leaseId:i,usage:this.resourceUsage()},transfer:t.transfer}}async ack(e){if(!Number.isSafeInteger(e)||e<0)throw RangeError(`invalid ack sequence`);if(e<this.sequence)return;if(!this.unacked||e!==this.sequence)throw Error(`ack sequence mismatch`);let t=this.unacked.done;await this.options.driver.acknowledge?.(e),this.unacked=void 0,this.coordinator.release(this.coordinatorOwner),this.sequence++,t&&(this.completed=!0,this.maybeUnregisterCompleted())}async release(e){q(e,`wire lease id`);let t=this.leases.get(e);t&&(await this.options.driver.releaseLease?.(t.driverLeaseId),this.leases.delete(e),this.activeDriverLeases.delete(t.driverLeaseId),this.coordinator.releaseLease(this.coordinatorOwner,e),this.maybeUnregisterCompleted())}async cancel(){if(this.cancelComplete)return;this.cancelRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;try{await this.releaseAllLeases()}catch(t){e=t}if(!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch(t){e??=t}if(e)throw e;this.cancelComplete=!0,this.unregisterCleanup()}async close(){if(this.closeComplete)return;this.closeRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;try{await this.releaseAllLeases()}catch(t){e=t}if(!this.driverCloseComplete)try{await this.options.driver.close?.(),this.driverCloseComplete=!0}catch(t){e??=t}if(e)throw e;this.closeComplete=!0,this.unregisterCleanup()}async releaseAllLeases(){let e;for(let t of[...this.leases.keys()])try{await this.release(t)}catch(t){e??=t}if(e)throw e}validateCommandIdentity(e){if(e.protocol!==`ooxml-pull-v1`||e.sessionId!==this.options.sessionId||e.operationId!==this.options.operationId||e.generation!==this.options.generation||!Number.isSafeInteger(e.requestId)||e.requestId<=0)throw Error(`stale or mismatched pull session command`)}validateHostCredit(e){if(q(e,`byte credit`),e>this.options.maxByteCredit)throw RangeError(`byte credit exceeds host maximum`)}accepted(e,t,n=!1){return{kind:`accepted`,protocol:K,...n?{sessionId:e.sessionId,operationId:e.operationId,generation:e.generation}:this.identity(),requestId:e.requestId,command:t,usage:this.resourceUsage()}}identity(){return{sessionId:this.options.sessionId,operationId:this.options.operationId,generation:this.options.generation}}isStaleLifecycle(e){return(e.kind===`cancel`||e.kind===`close`)&&e.protocol===`ooxml-pull-v1`&&Number.isSafeInteger(e.requestId)&&e.requestId>0&&Number.isSafeInteger(e.generation)&&e.generation>0&&e.generation<this.options.generation}sameOperationIdentity(e){return e.sessionId===this.options.sessionId&&e.operationId===this.options.operationId}errorResponse(e,t){return{kind:`error`,protocol:K,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:t,usage:this.errorResourceUsage()}}async forceFatalCleanup(){this.cancelRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;for(let t of[...this.leases.keys()])try{await this.release(t)}catch(t){e??=t}if(!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch(t){e??=t}if(e)throw e;this.unregisterCleanup()}allocateWireLeaseId(){if(!Number.isSafeInteger(this.nextWireLeaseId)||this.nextWireLeaseId<=0)throw RangeError(`wire lease id space exhausted`);return this.nextWireLeaseId++}arrayBufferTransferBytes(e){let t=0;for(let n of e??[])if(n instanceof ArrayBuffer&&(t+=n.byteLength,!Number.isSafeInteger(t)))throw RangeError(`ArrayBuffer transfer bytes overflow`);return t}maybeUnregisterCompleted(){this.completed&&this.leases.size===0&&this.unregisterCleanup()}resourceUsage(){return this.options.driver.resourceUsage?.()}errorResourceUsage(){try{return this.resourceUsage()}catch{return}}};const Y=67108864;var _e=class{coordinator=new J;host=null;identity=null;constructor(e,t=e=>e(this.requireArchive())){this.archive=e,this.executeArchive=t}open(e){if(this.host)throw Error(`a DOCX document pull session is already active`);this.executeArchive(t=>{t.open_document_cursor(e.operationId,e.generation)});let t=0;this.identity=e,this.host=new ge({...e,maxByteCredit:Y,coordinator:this.coordinator,driver:{pull:n=>{let r;try{r=this.executeArchive(r=>r.pull_document_chunk(t,e.operationId,e.generation,n))}catch(e){throw ce(e,n,Y)||e}let i=pe(r);return{payload:i,byteLength:i.byteLength,done:this.executeArchive(e=>e.document_chunk_done()),transfer:[i]}},measureChunk:({payload:e})=>e.byteLength,acknowledge:n=>{if(n!==t)throw Error(`DOCX document acknowledgement sequence mismatch`);this.executeArchive(n=>n.acknowledge_document_chunk(t,e.operationId,e.generation)),t+=1},cancel:()=>this.executeArchive(e=>e.cancel_document_cursor()),close:()=>this.executeArchive(e=>e.close_document_session()),resourceUsage:()=>{let e=this.executeArchive(e=>e.document_cursor_resource_usage?.());return e?N(e):void 0}}})}dispatch(e,t){return!this.host||!this.identity?(t({protocol:K,kind:`error`,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:G(Error(`DOCX document pull session is not open`))}),Promise.resolve()):this.host.dispatch(e,t)}async reset(){if(this.host)try{this.archive()&&this.executeArchive(e=>e.close_document_session())}finally{this.host=null,this.identity=null,this.coordinator=new J}}requireArchive(){let e=this.archive();if(!e)throw Error(`No docx loaded`);return e}};function ve(e){return!!e&&typeof e==`object`&&e.protocol===`ooxml-pull-v1`}const X=new oe(y,{freeArchive:e=>e.free(),reinit:b}),Z=new _e(()=>X.archive,e=>X.run(()=>{let t=X.archive;if(!t)throw Error(`No docx loaded`);return e(t)}));let Q=0;const $=(e,t)=>self.postMessage(e,t);self.onmessage=async t=>{let n=t.data;if(ve(n)){try{await Z.dispatch(n,$)}catch(e){$({protocol:K,kind:`error`,sessionId:n.sessionId,operationId:n.operationId,generation:n.generation,requestId:n.requestId,error:G(e)})}return}if(n.type===`init`){X.setWasmInput(re(n.wasmUrl)??n.wasmUrl);return}let r=n.id;try{if(await X.ensureReady(),n.type!==`parse`&&X.archive){let e=X.archive;X.run(()=>e.assert_healthy())}if(n.type===`parse`){await Z.reset();let[t,i,a]=me(n.resourcePolicy),o=new Uint8Array(n.data);X.run(()=>{let n=new e(o,t,i,a);X.setArchive(n)}),Q+=1;let s={sessionId:Q,operationId:Q,generation:Q};Z.open(s),$({type:`documentSessionOpened`,id:r,...s});return}let t=X.archive;if(n.type===`extractImage`){if(!t)throw Error(`No docx loaded`);let e=X.run(()=>t.extract_image(n.path).buffer),i={type:`imageExtracted`,id:r,bytes:e};self.postMessage(i,[e]);return}if(n.type===`resourceUsage`){if(!t)throw Error(`No docx loaded`);$({type:`resourceUsage`,id:r,usage:N(X.run(()=>t.resource_usage()))});return}if(n.type===`toMarkdown`){if(!t)throw Error(`No docx loaded`);$({type:`markdownRendered`,id:r,markdown:X.run(()=>t.to_markdown())});return}}catch(e){$({type:`error`,id:r,...G(e)})}};", U = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", H], { type: "text/javascript;charset=utf-8" });
|
|
55
|
-
function
|
|
54
|
+
var P = "var e=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,n.unregister(this),e}free(){let e=this.__destroy_into_raw();g.__wbg_docxarchive_free(e,0)}acknowledge_document_chunk(e,t,n){let r=g.docxarchive_acknowledge_document_chunk(this.__wbg_ptr,e,t,n);if(r[1])throw d(r[0])}assert_healthy(){let e=g.docxarchive_assert_healthy(this.__wbg_ptr);if(e[1])throw d(e[0])}cancel_document_cursor(){g.docxarchive_cancel_document_cursor(this.__wbg_ptr)}close_document_session(){g.docxarchive_close_document_session(this.__wbg_ptr)}document_chunk_done(){let e=g.docxarchive_document_chunk_done(this.__wbg_ptr);if(e[2])throw d(e[1]);return e[0]!==0}document_cursor_resource_usage(){let e=g.docxarchive_document_cursor_resource_usage(this.__wbg_ptr);if(e[3])throw d(e[2]);var t=r(e[0],e[1]).slice();return g.__wbindgen_free(e[0],e[1]*1,1),t}extract_image(e){let t=u(e,g.__wbindgen_malloc,g.__wbindgen_realloc),n=h,i=g.docxarchive_extract_image(this.__wbg_ptr,t,n);if(i[3])throw d(i[2]);var a=r(i[0],i[1]).slice();return g.__wbindgen_free(i[0],i[1]*1,1),a}constructor(e,t,r,i){let a=ee(e,g.__wbindgen_malloc),o=h,s=g.docxarchive_new(a,o,!l(t),l(t)?BigInt(0):t,!l(r),l(r)?BigInt(0):r,!l(i),l(i)?BigInt(0):i);if(s[2])throw d(s[1]);return this.__wbg_ptr=s[0]>>>0,n.register(this,this.__wbg_ptr,this),this}open_document_cursor(e,t){let n=g.docxarchive_open_document_cursor(this.__wbg_ptr,e,t);if(n[1])throw d(n[0])}parse(){let e=g.docxarchive_parse(this.__wbg_ptr);if(e[3])throw d(e[2]);var t=r(e[0],e[1]).slice();return g.__wbindgen_free(e[0],e[1]*1,1),t}pull_document_chunk(e,t,n,i){let a=g.docxarchive_pull_document_chunk(this.__wbg_ptr,e,t,n,i);if(a[3])throw d(a[2]);var o=r(a[0],a[1]).slice();return g.__wbindgen_free(a[0],a[1]*1,1),o}resource_usage(){let e=g.docxarchive_resource_usage(this.__wbg_ptr);if(e[3])throw d(e[2]);var t=r(e[0],e[1]).slice();return g.__wbindgen_free(e[0],e[1]*1,1),t}to_markdown(){let e,t;try{let i=g.docxarchive_to_markdown(this.__wbg_ptr);var n=i[0],r=i[1];if(i[3])throw n=0,r=0,d(i[2]);return e=n,t=r,o(n,r)}finally{g.__wbindgen_free(e,t,1)}}};Symbol.dispose&&(e.prototype[Symbol.dispose]=e.prototype.free);function t(){return{__proto__:null,\"./docx_parser_bg.js\":{__proto__:null,__wbg___wbindgen_throw_6b64449b9b9ed33c:function(e,t){throw Error(o(e,t))},__wbg_error_a6fa202b58aa1cd3:function(e,t){let n,r;try{n=e,r=t,console.error(o(e,t))}finally{g.__wbindgen_free(n,r,1)}},__wbg_new_227d7c05414eb861:function(){return Error()},__wbg_stack_3b0d974bbf31e44f:function(e,t){let n=t.stack,r=u(n,g.__wbindgen_malloc,g.__wbindgen_realloc),i=h;a().setInt32(e+4,i,!0),a().setInt32(e+0,r,!0)},__wbindgen_cast_0000000000000001:function(e,t){return o(e,t)},__wbindgen_init_externref_table:function(){let e=g.__wbindgen_externrefs,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)}}}}const n=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>g.__wbg_docxarchive_free(e>>>0,1));function r(e,t){return e>>>=0,c().subarray(e/1,e/1+t)}let i=null;function a(){return(i===null||i.buffer.detached===!0||i.buffer.detached===void 0&&i.buffer!==g.memory.buffer)&&(i=new DataView(g.memory.buffer)),i}function o(e,t){return e>>>=0,te(e,t)}let s=null;function c(){return(s===null||s.byteLength===0)&&(s=new Uint8Array(g.memory.buffer)),s}function l(e){return e==null}function ee(e,t){let n=t(e.length*1,1)>>>0;return c().set(e,n/1),h=e.length,n}function u(e,t,n){if(n===void 0){let n=m.encode(e),r=t(n.length,1)>>>0;return c().subarray(r,r+n.length).set(n),h=n.length,r}let r=e.length,i=t(r,1)>>>0,a=c(),o=0;for(;o<r;o++){let t=e.charCodeAt(o);if(t>127)break;a[i+o]=t}if(o!==r){o!==0&&(e=e.slice(o)),i=n(i,r,r=o+e.length*3,1)>>>0;let t=c().subarray(i+o,i+r),a=m.encodeInto(e,t);o+=a.written,i=n(i,r,o,1)>>>0}return h=o,i}function d(e){let t=g.__wbindgen_externrefs.get(e);return g.__externref_table_dealloc(e),t}let f=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0});f.decode();let p=0;function te(e,t){return p+=t,p>=2146435072&&(f=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}),f.decode(),p=t),f.decode(c().subarray(e,e+t))}const m=new TextEncoder;`encodeInto`in m||(m.encodeInto=function(e,t){let n=m.encode(e);return t.set(n),{read:e.length,written:n.length}});let h=0,g;function _(e,t){return g=e.exports,i=null,s=null,g.__wbindgen_start(),g}async function v(e,t){if(typeof Response==`function`&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming==`function`)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if(e.ok&&n(e.type)&&e.headers.get(`Content-Type`)!==`application/wasm`)console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\",t);else throw t}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{let n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}function n(e){switch(e){case`basic`:case`cors`:case`default`:return!0}return!1}}async function y(e){if(g!==void 0)return g;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn(`using deprecated parameters for the initialization function; pass a single object instead`));let n=t();(typeof e==`string`||typeof Request==`function`&&e instanceof Request||typeof URL==`function`&&e instanceof URL)&&(e=fetch(e));let{instance:r,module:i}=await v(await e,n);return _(r,i)}async function b(e){return g=void 0,i=null,s=null,y(e)}var x=class e extends Error{code;constructor(t,n){super(n),this.name=`OoxmlError`,this.code=t,Object.setPrototypeOf(this,e.prototype)}},S=class e extends Error{code=`ooxml-resource-limit`;details;constructor(t,n){super(t),this.name=`OoxmlResourceLimitError`;let r=n.violation,i=Object.freeze({format:r.format,operation:r.operation,resource:r.resource,metric:r.metric,...r.part===void 0?{}:{part:r.part},limit:r.limit,observed:r.observed,configurable:r.configurable,usage:Object.freeze({archiveEntryCount:r.usage.archiveEntryCount,declaredInflatedBytes:r.usage.declaredInflatedBytes,...r.usage.largestInflatedEntryBytes===void 0?{}:{largestInflatedEntryBytes:r.usage.largestInflatedEntryBytes},distinctInflatedBytes:r.usage.distinctInflatedBytes,operationInflatedBytes:r.usage.operationInflatedBytes})});this.details=Object.freeze({stage:n.stage,violation:i}),Object.setPrototypeOf(this,e.prototype)}},ne=class e extends RangeError{code=`ooxml-decoded-image-limit`;constructor(t,n,r){super(`OOXML decoded image limit exceeded: ${t} ${r} > ${n}`),this.metric=t,this.limit=n,this.observed=r,this.name=`OoxmlDecodedImageLimitError`,Object.setPrototypeOf(this,e.prototype)}};function re(e){if(!e.startsWith(`data:`))return null;let t=e.indexOf(`,`);if(t===-1)return null;let n=atob(e.slice(t+1)),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r.buffer}var ie=class{state=`uninitialized`;generationValue=0;readiness;poisonListeners=new Set;constructor(e,t,n){this.initialize=e,this.reinitialize=t,this.normalizeFailure=n}get generation(){return this.generationValue}get poisoned(){return this.state===`poisoned`}onPoison(e){return this.poisonListeners.add(e),()=>this.poisonListeners.delete(e)}async ensureReady(){if(this.state!==`ready`){if(!this.readiness){let e=this.state===`uninitialized`?this.initialize:this.reinitialize;this.readiness=Promise.resolve().then(e).then(()=>{this.generationValue+=1,this.state=`ready`,this.readiness=void 0},e=>{throw this.readiness=void 0,e})}await this.readiness}}run(e){try{return e()}catch(e){let t=this.normalizeFailure(e);throw t?(this.poison(t),t):e}}tryRunReady(e){if(this.state!==`ready`)return{current:!1};let t=this.generationValue,n=this.run(e);return this.state!==`ready`||t!==this.generationValue?{current:!1}:{current:!0,generation:t,value:n}}poison(e){this.state=`poisoned`,this.readiness=void 0;for(let t of this.poisonListeners)t(e)}assertCurrent(e){if(this.state!==`ready`||e!==this.generationValue)throw Error(`WASM archive session belongs to a discarded runtime generation`)}},C=class e extends Error{code=`parser-crashed`;constructor(t){super(t),this.name=`WasmTrapError`,Object.setPrototypeOf(this,e.prototype)}};function ae(e){let t=globalThis.WebAssembly?.RuntimeError;return t&&e instanceof t||e instanceof RangeError?!0:e instanceof Error?e.name===`RuntimeError`||e.name===`CompileError`||e.name===`LinkError`||e.name===`InternalError`||e.name===`OOMError`:!1}function w(e){try{if((typeof e!=`object`||!e)&&typeof e!=`function`)return;let t=Reflect.get(e,`__destroy_into_raw`);typeof t==`function`&&Reflect.apply(t,e,[])}catch{}}function T(e,t){return e({module_or_path:t})}var oe=class{runtime;wasmInput=null;currentArchive=null;constructor(e,t={}){this.init=e,this.options=t,this.runtime=new ie(()=>this.invokeConfigured(this.init),()=>this.invokeConfigured(this.options.reinit??this.init),E),this.runtime.onPoison(()=>this.dropPoisonedArchive())}setWasmInput(e){this.wasmInput=e,this.runtime.ensureReady().catch(()=>void 0)}setWasmUrl(e){this.setWasmInput(e)}get archive(){return this.currentArchive}setArchive(e){this.freeArchive(),this.currentArchive=e}disposeArchive(){this.freeArchive()}get poisoned(){return this.runtime.poisoned}async ensureReady(){await this.runtime.ensureReady()}run(e){return this.runtime.run(e)}poison(){this.runtime.poison(new C(`WASM parser was recycled`))}invokeConfigured(e){return this.wasmInput===null?Promise.reject(Error(`WasmParserHost: setWasmInput was never called`)):T(e,this.wasmInput)}freeArchive(){this.currentArchive!==null&&this.options.freeArchive&&this.options.freeArchive(this.currentArchive),this.currentArchive=null}dropPoisonedArchive(){let e=this.currentArchive;this.currentArchive=null,w(e)}};function E(e){return ae(e)?new C(`WASM parser trapped and was recycled: ${e instanceof Error?e.message:String(e)}`):null}function D(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function se(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return D(t.requiredBytes)&&D(t.offeredBytes)&&t.requiredBytes>t.offeredBytes}var O=class e extends RangeError{code=`ooxml-insufficient-credit`;requiredBytes;offeredBytes;constructor(t){super(`Pull unit requires ${t.requiredBytes} bytes but credit is ${t.offeredBytes}`),this.name=`PullSessionInsufficientCreditError`,this.requiredBytes=t.requiredBytes,this.offeredBytes=t.offeredBytes,Object.setPrototypeOf(this,e.prototype)}};function k(e){if(e instanceof O)return e;let t=e instanceof Error?e.message:String(e);if(!t.startsWith(`OOXML_INSUFFICIENT_CREDIT:`))return;let n;try{n=JSON.parse(t.slice(26))}catch{return}if(!n||typeof n!=`object`||Array.isArray(n))return;let r=n;if(!(r.code!==`ooxml-insufficient-credit`||!se(r)))return new O(r)}function ce(e,t,n){let r=k(e);if(!(!r||r.offeredBytes!==t||r.requiredBytes>n))return r}const A=`OOXML_RESOURCE_LIMIT:`;function j(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function M(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return j(t.archiveEntryCount)&&j(t.declaredInflatedBytes)&&(t.largestInflatedEntryBytes===void 0||j(t.largestInflatedEntryBytes))&&j(t.distinctInflatedBytes)&&j(t.operationInflatedBytes)}function N(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw TypeError(`OOXML resource usage checkpoint is not valid JSON`)}if(!M(t))throw TypeError(`OOXML resource usage checkpoint is invalid`);return t}function le(e){return e===`docx`||e===`xlsx`||e===`pptx`}function P(e){return e===`container`||e===`decompression`||e===`parsing`||e===`serialization`||e===`layout`||e===`rendering`||e===`worker`}function F(e,t){return typeof e==`string`&&e.length>0&&e.length<=t&&!/[\\u0000-\\u001f\\u007f]/u.test(e)}function I(e){return F(e,128)&&/^[a-z0-9][a-z0-9-]*$/u.test(e)}function L(e){return!F(e,4096)||e.startsWith(`/`)||e.startsWith(`\\\\`)||e.includes(`\\\\`)||e.includes(`?`)||e.includes(`#`)||e.includes(`://`)||/^[a-z]:/iu.test(e)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}const R=new Map([[`archive-entry:declared-inflated-bytes`,{stage:`container`,part:`required`}],[`archive-entry:actual-inflated-bytes`,{stage:`decompression`,part:`required`}],[`archive:entry-count`,{stage:`container`,part:`forbidden`}],[`archive:central-directory-bytes`,{stage:`container`,part:`forbidden`,configurable:!1}],[`archive:distinct-inflated-bytes`,{stage:`decompression`,part:`required`}],[`xml-event:bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`xml-context:bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`xml-tree:depth`,{stage:`parsing`,part:`optional`,configurable:!1}],[`worksheet-row:projected-bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`worksheet-shell:projected-bytes`,{stage:`parsing`,part:`optional`,configurable:!1}]]),z=new Set([...R.keys()].map(e=>e.slice(0,e.indexOf(`:`)))),B=new Set([...R.keys()].map(e=>e.slice(e.indexOf(`:`)+1)));function V(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return!le(t.format)||!F(t.operation,256)||!I(t.resource)||!I(t.metric)||!j(t.limit)||!j(t.observed)||typeof t.configurable!=`boolean`||!M(t.usage)?!1:!(`part`in t)||L(t.part)}function H(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;if(!P(t.stage)||!V(t.violation))return!1;let n=t.violation,r=R.get(`${n.resource}:${n.metric}`);return r?t.stage!==r.stage||r.configurable===!1&&n.configurable!==!1?!1:r.part===`required`?n.part!==void 0:r.part===`forbidden`?n.part===void 0:!0:!(z.has(n.resource)&&B.has(n.metric))}function U(e){return{archiveEntryCount:e.archiveEntryCount,declaredInflatedBytes:e.declaredInflatedBytes,...e.largestInflatedEntryBytes===void 0?{}:{largestInflatedEntryBytes:e.largestInflatedEntryBytes},distinctInflatedBytes:e.distinctInflatedBytes,operationInflatedBytes:e.operationInflatedBytes}}function ue(e){if(!H(e))return;let t=e.violation,n={stage:e.stage,violation:{format:t.format,operation:t.operation,resource:t.resource,metric:t.metric,...t.part===void 0?{}:{part:t.part},limit:t.limit,observed:t.observed,configurable:t.configurable,usage:U(t.usage)}};return H(n)?n:void 0}function W(e){let t=e.violation;return`OOXML resource limit exceeded${t.part?` for ${t.part}`:``}: ${t.metric} ${t.observed} > ${t.limit}`}function de(e){let t=e instanceof Error?e.message:String(e);if(!t.startsWith(A))return;let n;try{n=JSON.parse(t.slice(21))}catch{return}if(!n||typeof n!=`object`)return;let r=n;if(!(r.code!==`ooxml-resource-limit`||!H(r.details)))return new S(W(r.details),r.details)}function fe(e){if(e instanceof ne)return{message:e.message,errorName:e.name,code:e.code,decodedImage:{metric:e.metric,limit:e.limit,observed:e.observed}};let t=k(e);if(t)return{message:t.message,errorName:t.name,code:t.code,insufficientCredit:{requiredBytes:t.requiredBytes,offeredBytes:t.offeredBytes}};let n=e instanceof x||e instanceof S?e:de(e);if(n instanceof S){let e=ue(n.details);return e?{message:typeof n.message==`string`?n.message:W(e),errorName:`OoxmlResourceLimitError`,code:`ooxml-resource-limit`,resourceLimit:e}:{message:`Invalid OOXML resource-limit error payload`,errorName:`Error`}}if(n instanceof x)return{message:typeof n.message==`string`?n.message:String(n.message),errorName:F(n.name,128)?n.name:`OoxmlError`,...I(n.code)?{code:n.code}:{}};let r=e instanceof Error?e.message:String(e);if(typeof r==`string`&&r.startsWith(A))return{message:`Invalid OOXML resource-limit payload`,errorName:`Error`};let i=e instanceof Error?e:Error(r),a=i;return{message:typeof i.message==`string`?i.message:String(i.message),errorName:F(i.name,128)?i.name:`Error`,...typeof a.code==`string`?{code:a.code}:{}}}function G(e){try{return fe(e)}catch{return{message:`Worker operation failed with an unreadable error`,errorName:`Error`}}}function pe(e){return e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&e.buffer instanceof ArrayBuffer?e.buffer:e.slice().buffer}Object.freeze({maxArchiveEntryBytes:134217728,maxTotalInflatedBytes:268435456,maxArchiveEntries:4096});function me(e){return[e.maxArchiveEntryBytes===null?0n:BigInt(e.maxArchiveEntryBytes),e.maxTotalInflatedBytes===null?0n:BigInt(e.maxTotalInflatedBytes),e.maxArchiveEntries===null?0n:BigInt(e.maxArchiveEntries)]}const K=`ooxml-pull-v1`;function q(e,t){if(!Number.isSafeInteger(e)||e<=0)throw RangeError(`${t} must be a positive safe integer`)}function he(e){if(!(typeof e==`string`&&e.length>0||typeof e==`number`&&Number.isSafeInteger(e)&&e>0))throw RangeError(`session id must be a non-empty string or positive safe integer`)}var J=class{owner;queue=Promise.resolve();leases=new Map;retainedBytes=0;retainedCount=0;maxRetainedBytes;maxRetainedCount;cleanups=new Set;pendingFatalCleanups=[];poisonRunning=!1;fatal;constructor(e){this.maxRetainedBytes=e?.maxRetainedBytes??64*1024*1024,this.maxRetainedCount=e?.maxRetainedCount??256,q(this.maxRetainedBytes,`max retained lease bytes`),q(this.maxRetainedCount,`max retained lease count`)}enqueue(e){let t=this.queue.then(e,e);return this.queue=t.then(()=>void 0,()=>void 0),t}acquire(e){return this.owner===void 0?(this.owner=e,!0):this.owner===e}release(e){this.owner===e&&(this.owner=void 0)}retainLease(e,t,n){if(!Number.isSafeInteger(n)||n<0)throw RangeError(`retained lease bytes are invalid`);let r=this.leases.get(e)??new Map;if(r.has(t))throw Error(`driver returned a duplicate lease id`);if(this.retainedCount+1>this.maxRetainedCount)throw RangeError(`retained lease count exceeds limit`);if(this.retainedBytes+n>this.maxRetainedBytes)throw RangeError(`retained lease bytes exceed limit`);r.set(t,n),this.leases.set(e,r),this.retainedCount++,this.retainedBytes+=n}releaseLease(e,t){let n=this.leases.get(e),r=n?.get(t);r!==void 0&&(n?.delete(t),n?.size===0&&this.leases.delete(e),this.retainedCount--,this.retainedBytes-=r)}registerCleanup(e){return this.fatal?(this.poisonRunning?this.pendingFatalCleanups.push(e):this.enqueue(e).catch(()=>void 0),()=>void 0):(this.cleanups.add(e),()=>this.cleanups.delete(e))}get fatalError(){return this.fatal}get registeredHostCount(){return this.cleanups.size}async poison(e){if(this.fatal??=e,this.poisonRunning)return this.fatal;this.poisonRunning=!0,this.pendingFatalCleanups.push(...this.cleanups);try{let e;for(;(e=this.pendingFatalCleanups.shift())!==void 0;)await e().catch(()=>void 0)}finally{this.poisonRunning=!1}return this.fatal}},ge=class{options;coordinator;coordinatorOwner=Symbol(`pull-session-host`);unregisterCleanup;sequence=0;unacked;leases=new Map;activeDriverLeases=new Set;nextWireLeaseId;cancelRequested=!1;cancelComplete=!1;closeRequested=!1;closeComplete=!1;driverCancelComplete=!1;driverCloseComplete=!1;completed=!1;constructor(e){he(e.sessionId),q(e.operationId,`operation id`),q(e.generation,`generation`),q(e.maxByteCredit,`max byte credit`),e.wireLeaseIdStart!==void 0&&q(e.wireLeaseIdStart,`wire lease id start`),this.options=e,this.coordinator=e.coordinator,this.nextWireLeaseId=e.wireLeaseIdStart??1,this.unregisterCleanup=this.coordinator.registerCleanup(()=>this.forceFatalCleanup())}dispatch(e,t){return this.coordinator.enqueue(async()=>{let n=await this.execute(e);try{t(n.response,n.transfer)}catch(e){throw await this.rollbackFailedPost(n),e}})}async rollbackFailedPost(e){let t=e.response;if(t.kind===`chunk`){let n=t.leaseId===void 0?void 0:this.leases.get(t.leaseId);try{await this.options.driver.disposeInvalidChunk?.({payload:t.payload,byteLength:t.byteLength,done:t.done,leaseId:n?.driverLeaseId,retainedBytes:n?.retainedBytes,transfer:e.transfer})}catch{}}this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);for(let[e,t]of[...this.leases])try{await this.options.driver.releaseLease?.(t.driverLeaseId)}catch{}finally{this.leases.delete(e),this.activeDriverLeases.delete(t.driverLeaseId),this.coordinator.releaseLease(this.coordinatorOwner,e)}if(this.cancelRequested=!0,!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch{}this.unregisterCleanup()}async execute(e){try{if(this.isStaleLifecycle(e)){let t=e.kind===`cancel`?`cancel`:`close`;return this.sameOperationIdentity(e)?{response:this.accepted(e,t,!0)}:{response:this.errorResponse(e,{message:`stale lifecycle targets another session or operation`,errorName:`PullSessionProtocolError`,code:`ooxml-stale-lifecycle`})}}this.validateCommandIdentity(e);let t=this.coordinator.fatalError;if(t)return e.kind===`pull`?{response:this.errorResponse(e,t)}:(e.kind===`cancel`?await this.cancel():e.kind===`close`?await this.close():e.kind===`release`&&await this.release(e.leaseId),{response:this.accepted(e,e.kind)});switch(e.kind){case`pull`:return await this.pull(e);case`ack`:return await this.ack(e.sequence),{response:this.accepted(e,`ack`)};case`release`:return await this.release(e.leaseId),{response:this.accepted(e,`release`)};case`cancel`:return await this.cancel(),{response:this.accepted(e,`cancel`)};case`close`:return await this.close(),{response:this.accepted(e,`close`)}}}catch(t){let n=G(t);return n.code===`ooxml-resource-limit`&&(n=await this.coordinator.poison(n)),{response:this.errorResponse(e,n)}}}async pull(e){if(this.closeRequested||this.cancelRequested||this.completed)throw Error(`pull session is closed`);if(this.unacked)throw Error(`previous chunk is not acknowledged`);if(!Number.isSafeInteger(e.sequence)||e.sequence<0||e.sequence!==this.sequence)throw Error(`pull command sequence mismatch`);if(this.validateHostCredit(e.byteCredit),!this.coordinator.acquire(this.coordinatorOwner))throw Error(`another operation has an unacknowledged package chunk`);let t;try{t=await this.options.driver.pull(e.byteCredit)}catch(e){throw this.coordinator.release(this.coordinatorOwner),e}let n=!1,r=!1,i,a;try{let o=this.options.driver.measureChunk(t),s=this.arrayBufferTransferBytes(t.transfer);if(o<s)throw RangeError(`measured chunk bytes are below ArrayBuffer transfer bytes`);if(a=Math.max(o,s),t.leaseId!==void 0){if(q(t.leaseId,`lease id`),t.retainedBytes===void 0)throw Error(`retained lease bytes are required`);if(this.activeDriverLeases.has(t.leaseId))throw r=!0,Error(`driver returned an active duplicate lease id`);i=this.allocateWireLeaseId(),this.coordinator.retainLease(this.coordinatorOwner,i,t.retainedBytes),this.leases.set(i,{driverLeaseId:t.leaseId,retainedBytes:t.retainedBytes}),this.activeDriverLeases.add(t.leaseId),n=!0}else if(t.retainedBytes!==void 0)throw Error(`retained lease bytes require a lease id`);if(!Number.isSafeInteger(a)||a<0)throw RangeError(`host chunk byte length must be a non-negative safe integer`);if(a>e.byteCredit)throw RangeError(`host chunk exceeds byte credit`)}catch(e){let a;try{await this.options.driver.disposeInvalidChunk?.(t)}catch(e){a=e}if(n&&i!==void 0)try{await this.release(i)}catch(e){a??=e}else if(t.leaseId!==void 0&&!r)try{await this.options.driver.releaseLease?.(t.leaseId)}catch(e){a??=e}if(r)try{await this.cancel()}catch(e){a??=e}throw this.coordinator.release(this.coordinatorOwner),a||e}return this.unacked={sequence:this.sequence,done:t.done},{response:{kind:`chunk`,protocol:K,...this.identity(),requestId:e.requestId,sequence:this.sequence,byteLength:a,done:t.done,payload:t.payload,leaseId:i,usage:this.resourceUsage()},transfer:t.transfer}}async ack(e){if(!Number.isSafeInteger(e)||e<0)throw RangeError(`invalid ack sequence`);if(e<this.sequence)return;if(!this.unacked||e!==this.sequence)throw Error(`ack sequence mismatch`);let t=this.unacked.done;await this.options.driver.acknowledge?.(e),this.unacked=void 0,this.coordinator.release(this.coordinatorOwner),this.sequence++,t&&(this.completed=!0,this.maybeUnregisterCompleted())}async release(e){q(e,`wire lease id`);let t=this.leases.get(e);t&&(await this.options.driver.releaseLease?.(t.driverLeaseId),this.leases.delete(e),this.activeDriverLeases.delete(t.driverLeaseId),this.coordinator.releaseLease(this.coordinatorOwner,e),this.maybeUnregisterCompleted())}async cancel(){if(this.cancelComplete)return;this.cancelRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;try{await this.releaseAllLeases()}catch(t){e=t}if(!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch(t){e??=t}if(e)throw e;this.cancelComplete=!0,this.unregisterCleanup()}async close(){if(this.closeComplete)return;this.closeRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;try{await this.releaseAllLeases()}catch(t){e=t}if(!this.driverCloseComplete)try{await this.options.driver.close?.(),this.driverCloseComplete=!0}catch(t){e??=t}if(e)throw e;this.closeComplete=!0,this.unregisterCleanup()}async releaseAllLeases(){let e;for(let t of[...this.leases.keys()])try{await this.release(t)}catch(t){e??=t}if(e)throw e}validateCommandIdentity(e){if(e.protocol!==`ooxml-pull-v1`||e.sessionId!==this.options.sessionId||e.operationId!==this.options.operationId||e.generation!==this.options.generation||!Number.isSafeInteger(e.requestId)||e.requestId<=0)throw Error(`stale or mismatched pull session command`)}validateHostCredit(e){if(q(e,`byte credit`),e>this.options.maxByteCredit)throw RangeError(`byte credit exceeds host maximum`)}accepted(e,t,n=!1){return{kind:`accepted`,protocol:K,...n?{sessionId:e.sessionId,operationId:e.operationId,generation:e.generation}:this.identity(),requestId:e.requestId,command:t,usage:this.resourceUsage()}}identity(){return{sessionId:this.options.sessionId,operationId:this.options.operationId,generation:this.options.generation}}isStaleLifecycle(e){return(e.kind===`cancel`||e.kind===`close`)&&e.protocol===`ooxml-pull-v1`&&Number.isSafeInteger(e.requestId)&&e.requestId>0&&Number.isSafeInteger(e.generation)&&e.generation>0&&e.generation<this.options.generation}sameOperationIdentity(e){return e.sessionId===this.options.sessionId&&e.operationId===this.options.operationId}errorResponse(e,t){return{kind:`error`,protocol:K,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:t,usage:this.errorResourceUsage()}}async forceFatalCleanup(){this.cancelRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;for(let t of[...this.leases.keys()])try{await this.release(t)}catch(t){e??=t}if(!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch(t){e??=t}if(e)throw e;this.unregisterCleanup()}allocateWireLeaseId(){if(!Number.isSafeInteger(this.nextWireLeaseId)||this.nextWireLeaseId<=0)throw RangeError(`wire lease id space exhausted`);return this.nextWireLeaseId++}arrayBufferTransferBytes(e){let t=0;for(let n of e??[])if(n instanceof ArrayBuffer&&(t+=n.byteLength,!Number.isSafeInteger(t)))throw RangeError(`ArrayBuffer transfer bytes overflow`);return t}maybeUnregisterCompleted(){this.completed&&this.leases.size===0&&this.unregisterCleanup()}resourceUsage(){return this.options.driver.resourceUsage?.()}errorResourceUsage(){try{return this.resourceUsage()}catch{return}}};const Y=67108864;var _e=class{coordinator=new J;host=null;identity=null;constructor(e,t=e=>e(this.requireArchive())){this.archive=e,this.executeArchive=t}open(e){if(this.host)throw Error(`a DOCX document pull session is already active`);this.executeArchive(t=>{t.open_document_cursor(e.operationId,e.generation)});let t=0;this.identity=e,this.host=new ge({...e,maxByteCredit:Y,coordinator:this.coordinator,driver:{pull:n=>{let r;try{r=this.executeArchive(r=>r.pull_document_chunk(t,e.operationId,e.generation,n))}catch(e){throw ce(e,n,Y)||e}let i=pe(r);return{payload:i,byteLength:i.byteLength,done:this.executeArchive(e=>e.document_chunk_done()),transfer:[i]}},measureChunk:({payload:e})=>e.byteLength,acknowledge:n=>{if(n!==t)throw Error(`DOCX document acknowledgement sequence mismatch`);this.executeArchive(n=>n.acknowledge_document_chunk(t,e.operationId,e.generation)),t+=1},cancel:()=>this.executeArchive(e=>e.cancel_document_cursor()),close:()=>this.executeArchive(e=>e.close_document_session()),resourceUsage:()=>{let e=this.executeArchive(e=>e.document_cursor_resource_usage?.());return e?N(e):void 0}}})}dispatch(e,t){return!this.host||!this.identity?(t({protocol:K,kind:`error`,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:G(Error(`DOCX document pull session is not open`))}),Promise.resolve()):this.host.dispatch(e,t)}async reset(){if(this.host)try{this.archive()&&this.executeArchive(e=>e.close_document_session())}finally{this.host=null,this.identity=null,this.coordinator=new J}}requireArchive(){let e=this.archive();if(!e)throw Error(`No docx loaded`);return e}};function ve(e){return!!e&&typeof e==`object`&&e.protocol===`ooxml-pull-v1`}const X=new oe(y,{freeArchive:e=>e.free(),reinit:b}),Z=new _e(()=>X.archive,e=>X.run(()=>{let t=X.archive;if(!t)throw Error(`No docx loaded`);return e(t)}));let Q=0;const $=(e,t)=>self.postMessage(e,t);self.onmessage=async t=>{let n=t.data;if(ve(n)){try{await Z.dispatch(n,$)}catch(e){$({protocol:K,kind:`error`,sessionId:n.sessionId,operationId:n.operationId,generation:n.generation,requestId:n.requestId,error:G(e)})}return}if(n.type===`init`){X.setWasmInput(re(n.wasmUrl)??n.wasmUrl);return}let r=n.id;try{if(await X.ensureReady(),n.type!==`parse`&&X.archive){let e=X.archive;X.run(()=>e.assert_healthy())}if(n.type===`parse`){await Z.reset();let[t,i,a]=me(n.resourcePolicy),o=new Uint8Array(n.data);X.run(()=>{let n=new e(o,t,i,a);X.setArchive(n)}),Q+=1;let s={sessionId:Q,operationId:Q,generation:Q};Z.open(s),$({type:`documentSessionOpened`,id:r,...s});return}let t=X.archive;if(n.type===`extractImage`){if(!t)throw Error(`No docx loaded`);let e=X.run(()=>t.extract_image(n.path).buffer),i={type:`imageExtracted`,id:r,bytes:e};self.postMessage(i,[e]);return}if(n.type===`resourceUsage`){if(!t)throw Error(`No docx loaded`);$({type:`resourceUsage`,id:r,usage:N(X.run(()=>t.resource_usage()))});return}if(n.type===`toMarkdown`){if(!t)throw Error(`No docx loaded`);$({type:`markdownRendered`,id:r,markdown:X.run(()=>t.to_markdown())});return}}catch(e){$({type:`error`,id:r,...G(e)})}};", F = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", P], { type: "text/javascript;charset=utf-8" });
|
|
55
|
+
function Ue(e) {
|
|
56
56
|
let t;
|
|
57
57
|
try {
|
|
58
|
-
if (t =
|
|
58
|
+
if (t = F && (self.URL || self.webkitURL).createObjectURL(F), !t) throw "";
|
|
59
59
|
let n = new Worker(t, {
|
|
60
60
|
type: "module",
|
|
61
61
|
name: e?.name
|
|
@@ -64,7 +64,7 @@ function Te(e) {
|
|
|
64
64
|
(self.URL || self.webkitURL).revokeObjectURL(t);
|
|
65
65
|
}), n;
|
|
66
66
|
} catch {
|
|
67
|
-
return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(
|
|
67
|
+
return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(P), {
|
|
68
68
|
type: "module",
|
|
69
69
|
name: e?.name
|
|
70
70
|
});
|
|
@@ -72,17 +72,17 @@ function Te(e) {
|
|
|
72
72
|
}
|
|
73
73
|
//#endregion
|
|
74
74
|
//#region packages/docx/src/wasm/docx_parser_bg.wasm?url
|
|
75
|
-
var
|
|
75
|
+
var We = new URL("docx_parser_bg.wasm", import.meta.url).href;
|
|
76
76
|
//#endregion
|
|
77
77
|
//#region packages/docx/src/bookmark-nav.ts
|
|
78
|
-
function
|
|
78
|
+
function Ge(e) {
|
|
79
79
|
let t = /* @__PURE__ */ new Map();
|
|
80
80
|
for (let n of e.pages) for (let e of n.bookmarkStarts) e.name !== "" && !t.has(e.name) && t.set(e.name, n.pageIndex);
|
|
81
81
|
return t;
|
|
82
82
|
}
|
|
83
83
|
//#endregion
|
|
84
84
|
//#region packages/docx/src/embedded-fonts.ts
|
|
85
|
-
async function
|
|
85
|
+
async function Ke(e, t) {
|
|
86
86
|
let n = e.embeddedFonts;
|
|
87
87
|
if (!n || n.length === 0) return [];
|
|
88
88
|
let r = (await Promise.all(n.map(async (e) => {
|
|
@@ -93,24 +93,202 @@ async function Oe(e, t) {
|
|
|
93
93
|
bytes: n,
|
|
94
94
|
odttf: e.partPath.toLowerCase().endsWith(".odttf"),
|
|
95
95
|
fontKey: e.fontKey,
|
|
96
|
-
weight:
|
|
97
|
-
style:
|
|
96
|
+
weight: qe(e.style),
|
|
97
|
+
style: Je(e.style)
|
|
98
98
|
};
|
|
99
99
|
} catch {
|
|
100
100
|
return null;
|
|
101
101
|
}
|
|
102
102
|
}))).filter((e) => e !== null);
|
|
103
|
-
return r.length === 0 ? [] :
|
|
103
|
+
return r.length === 0 ? [] : Ve(r);
|
|
104
104
|
}
|
|
105
|
-
function
|
|
105
|
+
function qe(e) {
|
|
106
106
|
return e === "bold" || e === "boldItalic" ? "bold" : "normal";
|
|
107
107
|
}
|
|
108
|
-
function
|
|
108
|
+
function Je(e) {
|
|
109
109
|
return e === "italic" || e === "boldItalic" ? "italic" : "normal";
|
|
110
110
|
}
|
|
111
111
|
//#endregion
|
|
112
|
+
//#region packages/docx/src/element-context.ts
|
|
113
|
+
var I = de, Ye = 16384;
|
|
114
|
+
function L(e, t) {
|
|
115
|
+
let n = Math.min(e.length, t);
|
|
116
|
+
if (n > 0 && n < e.length) {
|
|
117
|
+
let t = e.charCodeAt(n - 1), r = e.charCodeAt(n);
|
|
118
|
+
t >= 55296 && t <= 56319 && r >= 56320 && r <= 57343 && n--;
|
|
119
|
+
}
|
|
120
|
+
return e.slice(0, n);
|
|
121
|
+
}
|
|
122
|
+
function Xe(e, t) {
|
|
123
|
+
let n = [], r = 0, i = !1;
|
|
124
|
+
for (let a of e) {
|
|
125
|
+
if (a.length === 0) continue;
|
|
126
|
+
if (r > 0) {
|
|
127
|
+
if (r >= t) {
|
|
128
|
+
i = !0;
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
n.push("\n"), r++;
|
|
132
|
+
}
|
|
133
|
+
let e = L(a, Math.max(0, t - r));
|
|
134
|
+
if (n.push(e), r += e.length, e.length < a.length) {
|
|
135
|
+
i = !0;
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
let a = n.join("");
|
|
140
|
+
return {
|
|
141
|
+
...a.length === 0 ? {} : { text: a },
|
|
142
|
+
truncated: i
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
function* R(e) {
|
|
146
|
+
if (e.kind === "paragraph") {
|
|
147
|
+
for (let t of e.lines) {
|
|
148
|
+
let e = t.placements.flatMap((e) => e.kind === "text" ? [e.text] : []).join("");
|
|
149
|
+
e && (yield e);
|
|
150
|
+
}
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
if (e.kind === "table") {
|
|
154
|
+
for (let t of e.rows) for (let e of t.cells) for (let t of e.blocks) yield* R(t.layout);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
if (e.kind === "note" || e.kind === "textbox") for (let t of e.story.blocks) yield* R(t);
|
|
158
|
+
}
|
|
159
|
+
function* Ze(e) {
|
|
160
|
+
for (let t of e.drawing.commands) (t.kind === "text" || t.kind === "watermark-text") && (yield t.text);
|
|
161
|
+
for (let t of e.textBoxes) yield* R(t);
|
|
162
|
+
}
|
|
163
|
+
function z(e) {
|
|
164
|
+
let t = e ?? Ye;
|
|
165
|
+
if (!Number.isFinite(t) || t < 0) throw RangeError("maxTextCharacters must be a finite non-negative number.");
|
|
166
|
+
return Math.min(I, Math.floor(t));
|
|
167
|
+
}
|
|
168
|
+
function Qe(e) {
|
|
169
|
+
return {
|
|
170
|
+
story: e.story,
|
|
171
|
+
storyInstance: e.storyInstance,
|
|
172
|
+
path: [...e.path]
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
function $e(e) {
|
|
176
|
+
return "drawing" in e ? e.drawing.inkBounds : e.placement.bounds;
|
|
177
|
+
}
|
|
178
|
+
function et(e) {
|
|
179
|
+
let t = $e(e), n = [
|
|
180
|
+
A(e.pointToPage, t),
|
|
181
|
+
A(e.pointToPage, {
|
|
182
|
+
xPt: t.xPt + t.widthPt,
|
|
183
|
+
yPt: t.yPt
|
|
184
|
+
}),
|
|
185
|
+
A(e.pointToPage, {
|
|
186
|
+
xPt: t.xPt,
|
|
187
|
+
yPt: t.yPt + t.heightPt
|
|
188
|
+
}),
|
|
189
|
+
A(e.pointToPage, {
|
|
190
|
+
xPt: t.xPt + t.widthPt,
|
|
191
|
+
yPt: t.yPt + t.heightPt
|
|
192
|
+
})
|
|
193
|
+
], 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));
|
|
194
|
+
return {
|
|
195
|
+
xPt: r,
|
|
196
|
+
yPt: i,
|
|
197
|
+
widthPt: a - r,
|
|
198
|
+
heightPt: o - i
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
function B(e, t) {
|
|
202
|
+
return t.xPt >= e.xPt && t.xPt <= e.xPt + e.widthPt && t.yPt >= e.yPt && t.yPt <= e.yPt + e.heightPt;
|
|
203
|
+
}
|
|
204
|
+
function tt(e, t) {
|
|
205
|
+
let n = !1;
|
|
206
|
+
for (let r = 0, i = t.length - 1; r < t.length; i = r++) {
|
|
207
|
+
let a = t[r], o = t[i];
|
|
208
|
+
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);
|
|
209
|
+
}
|
|
210
|
+
return n;
|
|
211
|
+
}
|
|
212
|
+
function nt(e, t) {
|
|
213
|
+
return B(e.inkBounds, t) ? e.clip ? e.clip.kind === "rect" ? B(e.clip.rect, t) : tt(t, e.clip.points) : !0 : !1;
|
|
214
|
+
}
|
|
215
|
+
function rt(e, t, n) {
|
|
216
|
+
for (let n of e.clips) {
|
|
217
|
+
let e = D(n.pointToPage, t);
|
|
218
|
+
if (!e || !B(n.bounds, e)) return !1;
|
|
219
|
+
}
|
|
220
|
+
return "drawing" in e ? nt(e.drawing, n) : B(e.placement.bounds, n);
|
|
221
|
+
}
|
|
222
|
+
function V(e, t) {
|
|
223
|
+
return e.commands.find((e) => e.kind === "resource" && e.resourceKind === t);
|
|
224
|
+
}
|
|
225
|
+
function it(e) {
|
|
226
|
+
return V(e, "chart") ? "chart" : e.commands.some((e) => e.kind === "drawingml-shape" || e.kind === "drawingml-image-fill" || e.kind === "fill-rect" || e.kind === "stroke-rect" || e.kind === "text" || e.kind === "watermark-text") ? "shape" : V(e, "image") ? "image" : null;
|
|
227
|
+
}
|
|
228
|
+
function at(e, t, n, r, i, a) {
|
|
229
|
+
let o = "drawing" in e ? it(e.drawing) : e.placement.resourceKind;
|
|
230
|
+
if (!o) return null;
|
|
231
|
+
let s, c = !1, l, u;
|
|
232
|
+
if (o === "chart") {
|
|
233
|
+
let t = "drawing" in e ? V(e.drawing, "chart").resourceKey : e.placement.resourceKey, n = i.resolve(t, "chart"), r = ee(n.model, a);
|
|
234
|
+
s = r.text, c = r.truncated, u = n.model.series.length;
|
|
235
|
+
} else if (o === "image") {
|
|
236
|
+
let t = "drawing" in e ? V(e.drawing, "image").resourceKey : e.placement.resourceKey, n = i.descriptors.find((e) => e.resourceKey === t && e.kind === "image" && "mimeType" in e);
|
|
237
|
+
if (!n) throw Error(`Unknown image paint resource: ${t}`);
|
|
238
|
+
l = n.mimeType;
|
|
239
|
+
} else {
|
|
240
|
+
let t = Xe(Ze(e), a);
|
|
241
|
+
s = t.text, c = t.truncated;
|
|
242
|
+
}
|
|
243
|
+
return {
|
|
244
|
+
format: "docx",
|
|
245
|
+
kind: "element",
|
|
246
|
+
pageIndex: t,
|
|
247
|
+
elementIndex: n,
|
|
248
|
+
elementType: o,
|
|
249
|
+
point: { ...r },
|
|
250
|
+
bounds: et(e),
|
|
251
|
+
source: Qe("drawing" in e ? e.drawing.source : e.source),
|
|
252
|
+
...s === void 0 ? {} : { text: s },
|
|
253
|
+
...l === void 0 ? {} : { mimeType: l },
|
|
254
|
+
...u === void 0 ? {} : { seriesCount: u },
|
|
255
|
+
truncated: c,
|
|
256
|
+
truncationReasons: c ? ["text"] : [],
|
|
257
|
+
textCharacters: s?.length ?? 0,
|
|
258
|
+
maxTextCharacters: a
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
function ot(e, t, n, r, i = {}) {
|
|
262
|
+
if (!Number.isFinite(n.xPt) || !Number.isFinite(n.yPt)) throw RangeError("DOCX hit-test point must contain finite page coordinates.");
|
|
263
|
+
let a = z(i.maxTextCharacters), o = Oe(e, t);
|
|
264
|
+
for (let e = o.length - 1; e >= 0; e--) {
|
|
265
|
+
let i = o[e], s = D(i.pointToPage, n);
|
|
266
|
+
if (!s || !rt(i, n, s)) continue;
|
|
267
|
+
let c = at(i, t, e, n, r, a);
|
|
268
|
+
if (c) return c;
|
|
269
|
+
}
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
function st(e, t, n, r) {
|
|
273
|
+
return ot(Ie(e, {
|
|
274
|
+
currentDate: r.currentDate,
|
|
275
|
+
defaultCurrentDateMs: r.defaultCurrentDateMs
|
|
276
|
+
}, t).layout, t, n, xe(e), r);
|
|
277
|
+
}
|
|
278
|
+
function H(e, t) {
|
|
279
|
+
let n = z(t), r = e.text === void 0 ? void 0 : L(e.text, n), i = e.truncated || e.text !== void 0 && r.length < e.text.length;
|
|
280
|
+
return {
|
|
281
|
+
...structuredClone(e),
|
|
282
|
+
...r === void 0 ? {} : { text: r },
|
|
283
|
+
truncated: i,
|
|
284
|
+
truncationReasons: i ? ["text"] : [],
|
|
285
|
+
textCharacters: r?.length ?? 0,
|
|
286
|
+
maxTextCharacters: n
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
//#endregion
|
|
112
290
|
//#region packages/docx/src/document.ts
|
|
113
|
-
var
|
|
291
|
+
var U = class e {
|
|
114
292
|
_metrics = null;
|
|
115
293
|
_document = null;
|
|
116
294
|
_source = null;
|
|
@@ -119,7 +297,7 @@ var W = class e {
|
|
|
119
297
|
_mode = "main";
|
|
120
298
|
_worker;
|
|
121
299
|
_bridge;
|
|
122
|
-
_rawParts = new
|
|
300
|
+
_rawParts = new be({
|
|
123
301
|
maxEntries: 64,
|
|
124
302
|
maxBytes: p
|
|
125
303
|
});
|
|
@@ -128,7 +306,7 @@ var W = class e {
|
|
|
128
306
|
_localMetricFontFaces = [];
|
|
129
307
|
_fetchImage = (e, t) => this.getImage(e, t);
|
|
130
308
|
constructor(e, t, n, r) {
|
|
131
|
-
this._worker = e, this._mode = t,
|
|
309
|
+
this._worker = e, this._mode = t, we(this, n), this._bridge = new h(this._worker, {
|
|
132
310
|
correlate: (e) => "protocol" in e && e.protocol === "ooxml-pull-v1" ? e.requestId : "id" in e ? e.id : void 0,
|
|
133
311
|
toError: (e) => {
|
|
134
312
|
if (!("protocol" in e || e.type !== "error")) return Object.assign(u(e), {
|
|
@@ -139,7 +317,7 @@ var W = class e {
|
|
|
139
317
|
});
|
|
140
318
|
}
|
|
141
319
|
});
|
|
142
|
-
let i = new URL(r ??
|
|
320
|
+
let i = new URL(r ?? We, location.href).href;
|
|
143
321
|
this._bridge.post({
|
|
144
322
|
type: "init",
|
|
145
323
|
wasmUrl: i
|
|
@@ -162,19 +340,19 @@ var W = class e {
|
|
|
162
340
|
if (!e.ok) throw Error(`Failed to fetch: ${e.status} ${e.statusText}`);
|
|
163
341
|
t = await e.arrayBuffer();
|
|
164
342
|
} else t = n;
|
|
165
|
-
t =
|
|
166
|
-
let a = s === "worker" ? (await import("./render-worker-host-
|
|
343
|
+
t = g(await v(t, r.password)), c.setSourceBytes(t.byteLength), c.checkpoint("container ready");
|
|
344
|
+
let a = s === "worker" ? (await import("./render-worker-host-C96AiK8e.js")).createRenderWorker() : new Ue(), l;
|
|
167
345
|
try {
|
|
168
|
-
if (l = new e(a, s, o, r.wasmUrl), l._metrics = c, await l._parse(t, i.policy, s === "worker" ? !!r.useGoogleFonts : !1, r.workerTimeoutMs, (e) => c.observeUsage(e)), s === "worker" && l._mode === "main" && (c.setMode("main"), console.warn("[ooxml] mode: 'worker' fell back to main-thread rendering because this document requires DOM OpenType vertical glyph selection.")), r.math && l._mode === "worker" && console.warn("[ooxml] the math engine is unavailable in mode: 'worker'; equations will be skipped. Use mode: 'main' for documents with equations."), l._mode === "main" && r.useGoogleFonts && l._document && (l._googleFontFaces = await
|
|
346
|
+
if (l = new e(a, s, o, r.wasmUrl), l._metrics = c, await l._parse(t, i.policy, s === "worker" ? !!r.useGoogleFonts : !1, r.workerTimeoutMs, (e) => c.observeUsage(e)), s === "worker" && l._mode === "main" && (c.setMode("main"), console.warn("[ooxml] mode: 'worker' fell back to main-thread rendering because this document requires DOM OpenType vertical glyph selection.")), r.math && l._mode === "worker" && console.warn("[ooxml] the math engine is unavailable in mode: 'worker'; equations will be skipped. Use mode: 'main' for documents with equations."), l._mode === "main" && r.useGoogleFonts && l._document && (l._googleFontFaces = await ge(Ne(l._document), De)), l._mode === "main" && l._document?.embeddedFonts?.length) {
|
|
169
347
|
let e = l;
|
|
170
|
-
l._embeddedFontFaces = await
|
|
348
|
+
l._embeddedFontFaces = await Ke(l._document, (t) => e.getFontBytes(t));
|
|
171
349
|
}
|
|
172
350
|
let n;
|
|
173
|
-
l._mode === "main" && l._document && (n = await
|
|
351
|
+
l._mode === "main" && l._document && (n = await Ee(l._document), l._localMetricFontFaces = n.faces);
|
|
174
352
|
let u;
|
|
175
|
-
if (l._mode === "main" && r.math && l._document &&
|
|
176
|
-
let e =
|
|
177
|
-
e.services =
|
|
353
|
+
if (l._mode === "main" && r.math && l._document && Me(l._document) && (u = await Pe(l._document, r.math)), l._mode === "main" && l._document && l._source) {
|
|
354
|
+
let e = j(l);
|
|
355
|
+
e.services = Ae(l._source, {
|
|
178
356
|
localMetrics: n?.metrics,
|
|
179
357
|
useGoogleFonts: !!r.useGoogleFonts,
|
|
180
358
|
embeddedFaces: l._embeddedFontFaces,
|
|
@@ -183,12 +361,12 @@ var W = class e {
|
|
|
183
361
|
mathDrawables: u?.drawables
|
|
184
362
|
});
|
|
185
363
|
let t = e.services;
|
|
186
|
-
|
|
364
|
+
Ce(l._source, t, e.defaultCurrentDateMs).layoutVariants.defaultLayout;
|
|
187
365
|
}
|
|
188
366
|
return await l._resourceUsage(r.workerTimeoutMs ?? 1e3).then((e) => c.observeUsage(e), () => void 0), c.checkpoint("model and layout ready"), c.succeed({ pages: l.pageCount }), l;
|
|
189
367
|
} catch (e) {
|
|
190
368
|
let t = l;
|
|
191
|
-
throw
|
|
369
|
+
throw _(a, t ? () => t.destroy() : void 0), e;
|
|
192
370
|
}
|
|
193
371
|
} catch (e) {
|
|
194
372
|
throw c.fail(e), e;
|
|
@@ -201,7 +379,7 @@ var W = class e {
|
|
|
201
379
|
data: e,
|
|
202
380
|
resourcePolicy: t,
|
|
203
381
|
useGoogleFonts: n,
|
|
204
|
-
defaultCurrentDateMs:
|
|
382
|
+
defaultCurrentDateMs: j(this).defaultCurrentDateMs
|
|
205
383
|
} : {
|
|
206
384
|
type: "parse",
|
|
207
385
|
id: r,
|
|
@@ -210,14 +388,14 @@ var W = class e {
|
|
|
210
388
|
}, [e], { timeoutMs: r });
|
|
211
389
|
if ("protocol" in a) throw Error("DOCX parse open returned a pull-protocol response");
|
|
212
390
|
if (this._mode === "worker") if ("usage" in a && a.usage && i?.(a.usage), a.type === "mainThreadVerticalFallback") {
|
|
213
|
-
let e = await
|
|
391
|
+
let e = await O(this._bridge.transport(k), a, {
|
|
214
392
|
timeoutMs: r,
|
|
215
393
|
onUsage: i
|
|
216
394
|
});
|
|
217
395
|
this._source = e.source, this._document = e.document, this._meta = null, this._mode = "main";
|
|
218
396
|
} else this._meta = a.meta;
|
|
219
397
|
else {
|
|
220
|
-
let e = a, t = await
|
|
398
|
+
let e = a, t = await O(this._bridge.transport(k), e, {
|
|
221
399
|
timeoutMs: r,
|
|
222
400
|
onUsage: i
|
|
223
401
|
});
|
|
@@ -225,7 +403,7 @@ var W = class e {
|
|
|
225
403
|
}
|
|
226
404
|
}
|
|
227
405
|
destroy() {
|
|
228
|
-
this._bridge.terminate(), this._document = null, this._source = null, this._meta = null,
|
|
406
|
+
this._bridge.terminate(), this._document = null, this._source = null, this._meta = null, j(this).services = null, this._bookmarkPages = null, this._rawParts.clear(), this._embeddedFontFaces.length > 0 && (He(this._embeddedFontFaces), this._embeddedFontFaces = []), this._googleFontFaces.length > 0 && (me(this._googleFontFaces), this._googleFontFaces = []), this._localMetricFontFaces.length > 0 && (Fe(this._localMetricFontFaces), this._localMetricFontFaces = []), d(this._fetchImage), n(this._fetchImage);
|
|
229
407
|
}
|
|
230
408
|
async getImage(e, t) {
|
|
231
409
|
return this._rawParts.get(e, t, () => this._bridge.request((t) => ({
|
|
@@ -284,9 +462,9 @@ var W = class e {
|
|
|
284
462
|
}
|
|
285
463
|
_getLayout() {
|
|
286
464
|
if (!this._document) return null;
|
|
287
|
-
let e =
|
|
465
|
+
let e = j(this).services;
|
|
288
466
|
if (!e) throw Error("Document layout services are not initialized");
|
|
289
|
-
let t =
|
|
467
|
+
let t = Se(e);
|
|
290
468
|
if (!t) throw Error("Document layout variant store is not initialized");
|
|
291
469
|
return t.defaultLayout;
|
|
292
470
|
}
|
|
@@ -294,7 +472,7 @@ var W = class e {
|
|
|
294
472
|
if (this._bookmarkPages) return this._bookmarkPages;
|
|
295
473
|
if (this._meta) return this._bookmarkPages = new Map(this._meta.bookmarkPages), this._bookmarkPages;
|
|
296
474
|
let e = this._getLayout();
|
|
297
|
-
return e ? (this._bookmarkPages =
|
|
475
|
+
return e ? (this._bookmarkPages = Ge(e), this._bookmarkPages) : null;
|
|
298
476
|
}
|
|
299
477
|
getBookmarkPage(e) {
|
|
300
478
|
return this._getBookmarkPages()?.get(e);
|
|
@@ -328,11 +506,11 @@ var W = class e {
|
|
|
328
506
|
renderPage(e, t, n = {}) {
|
|
329
507
|
if (this._mode === "worker") throw Error("renderPage(canvas) is unavailable in mode: 'worker'; use renderPageToBitmap() and paint it via an ImageBitmapRenderingContext");
|
|
330
508
|
if (!this._source) throw Error("Document not loaded");
|
|
331
|
-
return
|
|
509
|
+
return Te(this._source, e, t, {
|
|
332
510
|
...n,
|
|
333
511
|
fetchImage: this._fetchImage,
|
|
334
|
-
layoutServices:
|
|
335
|
-
defaultCurrentDateMs:
|
|
512
|
+
layoutServices: j(this).services ?? void 0,
|
|
513
|
+
defaultCurrentDateMs: j(this).defaultCurrentDateMs
|
|
336
514
|
});
|
|
337
515
|
}
|
|
338
516
|
async renderPageToBitmap(e, t = {}) {
|
|
@@ -357,46 +535,64 @@ var W = class e {
|
|
|
357
535
|
}), a.transferToImageBitmap();
|
|
358
536
|
}
|
|
359
537
|
async collectPageRuns(e, t = {}) {
|
|
360
|
-
let n = {
|
|
361
|
-
...t,
|
|
362
|
-
dpr: t.dpr ?? l()
|
|
363
|
-
};
|
|
538
|
+
let n = { ...t };
|
|
364
539
|
if (this._mode === "worker") return (await this._bridge.request((t) => ({
|
|
365
540
|
type: "collectRuns",
|
|
366
541
|
id: t,
|
|
367
542
|
pageIndex: e,
|
|
368
543
|
opts: n
|
|
369
544
|
}))).runs;
|
|
370
|
-
let r =
|
|
545
|
+
let r = j(this), i = r.services;
|
|
371
546
|
if (!i) throw Error("Document layout services are not initialized");
|
|
372
|
-
return
|
|
547
|
+
return ke(i, e, {
|
|
373
548
|
currentDate: n.currentDate,
|
|
374
549
|
defaultCurrentDateMs: r.defaultCurrentDateMs,
|
|
375
550
|
width: n.width
|
|
376
551
|
});
|
|
377
552
|
}
|
|
553
|
+
async getElementContextAt(e, t, n = {}) {
|
|
554
|
+
if (this._mode === "worker") return (await this._bridge.request((r) => ({
|
|
555
|
+
type: "hitTestElement",
|
|
556
|
+
id: r,
|
|
557
|
+
pageIndex: e,
|
|
558
|
+
point: t,
|
|
559
|
+
opts: n
|
|
560
|
+
}))).context;
|
|
561
|
+
let r = j(this), i = r.services;
|
|
562
|
+
if (!i) throw Error("Document layout services are not initialized");
|
|
563
|
+
return st(i, e, t, {
|
|
564
|
+
...n,
|
|
565
|
+
defaultCurrentDateMs: r.defaultCurrentDateMs
|
|
566
|
+
});
|
|
567
|
+
}
|
|
378
568
|
};
|
|
379
569
|
//#endregion
|
|
380
570
|
//#region packages/docx/src/tate-chu-yoko-overlay.ts
|
|
381
|
-
function
|
|
571
|
+
function W(e, t) {
|
|
382
572
|
if (!e.eastAsianVert) return 1;
|
|
383
573
|
let n = t(e.text);
|
|
384
574
|
return !(n > 0) || e.w >= n ? 1 : e.w / n;
|
|
385
575
|
}
|
|
386
576
|
//#endregion
|
|
387
577
|
//#region packages/docx/src/text-layer.ts
|
|
388
|
-
function
|
|
389
|
-
e.
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
578
|
+
function G(e, t, n) {
|
|
579
|
+
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);
|
|
580
|
+
}
|
|
581
|
+
function K(e, t, n, r, i, a, o) {
|
|
582
|
+
e.innerHTML = "", G(e, "ooxmlSelectionSurface", "docx"), G(e, "pageIndex", o === void 0 ? void 0 : String(o));
|
|
583
|
+
let s = e.ownerDocument ?? document;
|
|
584
|
+
for (let [o, c] of t.entries()) {
|
|
585
|
+
let t = s.createElement("span");
|
|
586
|
+
G(t, "ooxmlSelectionRun", "docx"), G(t, "runIndex", String(o)), c.paragraphId !== void 0 && G(t, "paragraphId", c.paragraphId), c.source !== void 0 && (G(t, "sourceStory", c.source.story), G(t, "sourceStoryInstance", c.source.storyInstance), G(t, "sourcePath", JSON.stringify(c.source.path))), t.textContent = c.text;
|
|
587
|
+
let l = c.transform ?? "";
|
|
588
|
+
if (a && c.eastAsianVert) {
|
|
589
|
+
let e = W(c, a(c.font));
|
|
590
|
+
e !== 1 && (l = `${l ? `${l} ` : ""}scaleX(${e})`);
|
|
397
591
|
}
|
|
398
|
-
let
|
|
399
|
-
t.style.cssText = `position:absolute;left:${
|
|
592
|
+
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`;
|
|
593
|
+
t.style.cssText = `position:absolute;left:${N(c.x, n)};top:${N(c.y, r)};font:${c.font};line-height:${c.h}px;letter-spacing:${p};` + u + `white-space:pre;color:transparent;cursor:${f};pointer-events:all;`, d && i && (t.title = d.kind === "external" ? d.url : d.ref, t.addEventListener("click", (e) => {
|
|
594
|
+
e.preventDefault(), i(d);
|
|
595
|
+
})), e.appendChild(t);
|
|
400
596
|
}
|
|
401
597
|
}
|
|
402
598
|
function q(e, t, n, r, i, a, o = {}) {
|
|
@@ -407,10 +603,10 @@ function q(e, t, n, r, i, a, o = {}) {
|
|
|
407
603
|
for (let s of o.slices) {
|
|
408
604
|
let o = t[s.runIndex];
|
|
409
605
|
if (!o) continue;
|
|
410
|
-
let c = a(o.font), l =
|
|
606
|
+
let c = a(o.font), l = Le(o.text, s.start, s.end, c), u = o.letterSpacingPx ?? 0, d = Math.max(0, Math.min(s.start, o.text.length)), f = Math.max(d, Math.min(s.end, o.text.length)), p = [...o.text.slice(0, d)].length, m = [...o.text.slice(d, f)].length, h = l.x + p * u, g = l.width + Math.max(0, m - 1) * u, _ = W(o, c), v = h * _, y = g * _;
|
|
411
607
|
if (y <= 0) continue;
|
|
412
608
|
let b = document.createElement("div"), x = o.transform ? `transform:${o.transform};transform-origin:top left;` : "";
|
|
413
|
-
b.style.cssText = `position:absolute;left:${
|
|
609
|
+
b.style.cssText = `position:absolute;left:${N(o.x + v, r)};top:${N(o.y, i)};width:${N(y, r)};height:${N(o.h, i)};` + x + `background:${n};pointer-events:none;`, e.appendChild(b);
|
|
414
610
|
}
|
|
415
611
|
}
|
|
416
612
|
}
|
|
@@ -479,8 +675,8 @@ var J = class {
|
|
|
479
675
|
if (n !== this._generation) return [];
|
|
480
676
|
let o = r === this._runsRevision ? i : new Map([...i, ...this._pageRuns]), s = [];
|
|
481
677
|
for (let n = 0; n < a; n++) {
|
|
482
|
-
let r = o.get(n) ?? [], i =
|
|
483
|
-
for (let a of
|
|
678
|
+
let r = o.get(n) ?? [], i = ie(r);
|
|
679
|
+
for (let a of re(i, e, t)) {
|
|
484
680
|
let e = a.slices.map((e) => r[e.runIndex].text.slice(e.start, e.end)).join("");
|
|
485
681
|
s.push({
|
|
486
682
|
page: n,
|
|
@@ -492,10 +688,10 @@ var J = class {
|
|
|
492
688
|
return this._runsRevision++, this._pageRuns = o, this._matches = s, this._active = -1, this.matches();
|
|
493
689
|
}
|
|
494
690
|
next() {
|
|
495
|
-
return this._active =
|
|
691
|
+
return this._active = te(this._active, this._matches.length), this._activePublic();
|
|
496
692
|
}
|
|
497
693
|
prev() {
|
|
498
|
-
return this._active =
|
|
694
|
+
return this._active = se(this._active, this._matches.length), this._activePublic();
|
|
499
695
|
}
|
|
500
696
|
_activePublic() {
|
|
501
697
|
let e = this._matchAt(this._active);
|
|
@@ -505,7 +701,75 @@ var J = class {
|
|
|
505
701
|
location: { page: e.page }
|
|
506
702
|
} : null;
|
|
507
703
|
}
|
|
508
|
-
}
|
|
704
|
+
};
|
|
705
|
+
//#endregion
|
|
706
|
+
//#region packages/docx/src/selection-context.ts
|
|
707
|
+
function Y(e) {
|
|
708
|
+
if (e === void 0 || !/^\d+$/.test(e)) return null;
|
|
709
|
+
let t = Number(e);
|
|
710
|
+
return Number.isSafeInteger(t) ? t : null;
|
|
711
|
+
}
|
|
712
|
+
function ct(e) {
|
|
713
|
+
for (let t = e; t; t = t.parentElement) {
|
|
714
|
+
let e = Y(t.dataset.pageIndex);
|
|
715
|
+
if (e !== null) return e;
|
|
716
|
+
}
|
|
717
|
+
return null;
|
|
718
|
+
}
|
|
719
|
+
var lt = new Set([
|
|
720
|
+
"body",
|
|
721
|
+
"header",
|
|
722
|
+
"footer",
|
|
723
|
+
"footnote",
|
|
724
|
+
"endnote",
|
|
725
|
+
"textbox"
|
|
726
|
+
]);
|
|
727
|
+
function X(e) {
|
|
728
|
+
let t = e.dataset.sourceStory, n = e.dataset.sourceStoryInstance, r = e.dataset.sourcePath;
|
|
729
|
+
if (!t || !lt.has(t) || !n || !r) return null;
|
|
730
|
+
try {
|
|
731
|
+
let e = JSON.parse(r);
|
|
732
|
+
return !Array.isArray(e) || e.length === 0 || e.length > 32 || !e.every((e) => Number.isSafeInteger(e) && e >= 0) ? null : {
|
|
733
|
+
story: t,
|
|
734
|
+
storyInstance: n,
|
|
735
|
+
path: [...e]
|
|
736
|
+
};
|
|
737
|
+
} catch {
|
|
738
|
+
return null;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
function Z(e, t, n = {}) {
|
|
742
|
+
let r = le(e, t, (e) => {
|
|
743
|
+
let t = ct(e), n = Y(e.dataset.runIndex);
|
|
744
|
+
return t === null || n === null ? null : {
|
|
745
|
+
pageIndex: t,
|
|
746
|
+
runIndex: n,
|
|
747
|
+
...e.dataset.paragraphId === void 0 ? {} : { paragraphId: e.dataset.paragraphId },
|
|
748
|
+
...X(e) === null ? {} : { source: X(e) }
|
|
749
|
+
};
|
|
750
|
+
}, {
|
|
751
|
+
maxChars: n.maxTextCharacters,
|
|
752
|
+
maxLocators: n.maxRunLocators
|
|
753
|
+
});
|
|
754
|
+
if (!r) return null;
|
|
755
|
+
let i = [...r.locators].sort((e, t) => e.pageIndex - t.pageIndex || e.runIndex - t.runIndex);
|
|
756
|
+
return {
|
|
757
|
+
format: "docx",
|
|
758
|
+
kind: "text",
|
|
759
|
+
text: r.text,
|
|
760
|
+
pageIndexes: [...new Set(i.map((e) => e.pageIndex))],
|
|
761
|
+
paragraphIds: [...new Set(i.flatMap((e) => e.paragraphId ? [e.paragraphId] : []))],
|
|
762
|
+
runs: i,
|
|
763
|
+
truncated: r.truncated,
|
|
764
|
+
truncationReasons: r.truncationReasons,
|
|
765
|
+
textCharacters: r.textCharacters,
|
|
766
|
+
maxTextCharacters: r.maxTextCharacters,
|
|
767
|
+
maxRunLocators: r.maxLocators
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
//#endregion
|
|
771
|
+
//#region packages/docx/src/viewer.ts
|
|
772
|
+
var Q = Symbol("DocxViewer.borrowedDocument"), ut = class e {
|
|
509
773
|
_documentOwner;
|
|
510
774
|
get _doc() {
|
|
511
775
|
return this._documentOwner.current;
|
|
@@ -519,6 +783,7 @@ var J = class {
|
|
|
519
783
|
_canvasMount;
|
|
520
784
|
_textLayer = null;
|
|
521
785
|
_highlightLayer = null;
|
|
786
|
+
_elementLayer = null;
|
|
522
787
|
_find;
|
|
523
788
|
_measureCtx = null;
|
|
524
789
|
_opts;
|
|
@@ -526,30 +791,40 @@ var J = class {
|
|
|
526
791
|
_renderDispatcher;
|
|
527
792
|
_errorRouter;
|
|
528
793
|
_destroyed = !1;
|
|
794
|
+
_selectionChangeListener = null;
|
|
795
|
+
_selectionContextKey = "null";
|
|
796
|
+
_elementContext = null;
|
|
797
|
+
_elementHitGeneration = 0;
|
|
798
|
+
_elementClickListener = null;
|
|
799
|
+
_contextMenuListener = null;
|
|
529
800
|
static fromDocument(t, n, r = {}) {
|
|
530
801
|
return new e(t, {
|
|
531
802
|
...r,
|
|
532
|
-
[
|
|
803
|
+
[Q]: n
|
|
533
804
|
});
|
|
534
805
|
}
|
|
535
806
|
constructor(e, t = {}) {
|
|
536
807
|
this._canvas = e, this._opts = t;
|
|
537
|
-
let n = t[
|
|
538
|
-
this._borrowed = n !== void 0, this._mode = w("DocxViewer", t.mode, n), this._documentOwner = new
|
|
808
|
+
let n = t[Q];
|
|
809
|
+
this._borrowed = n !== void 0, this._mode = w("DocxViewer", t.mode, n), this._documentOwner = new b("DocxViewer", n ?? null, !1);
|
|
539
810
|
let r = e.ownerDocument?.defaultView ?? (typeof window < "u" ? window : null);
|
|
540
811
|
if (!r) throw Error("DocxViewer requires a canvas with an active Window");
|
|
541
|
-
this._hostWindow = r, this._canvasMount = new
|
|
812
|
+
this._hostWindow = r, this._canvasMount = new ue(e, {
|
|
542
813
|
wrapperCssText: "position:relative;display:inline-block;vertical-align:top;",
|
|
543
814
|
forceDisplayBlock: !0
|
|
544
|
-
}), this._wrapper = this._canvasMount.wrapper, this._renderDispatcher = new
|
|
545
|
-
let i = new
|
|
546
|
-
this._textLayer = i.textLayer, this._highlightLayer = i.highlightLayer, this.
|
|
815
|
+
}), this._wrapper = this._canvasMount.wrapper, this._renderDispatcher = new C(e, this._mode === "worker"), this._errorRouter = new ce("DocxViewer", t.onError);
|
|
816
|
+
let i = new ae(this._wrapper, t.enableTextSelection === !0, t.enableElementSelection === !0);
|
|
817
|
+
this._textLayer = i.textLayer, this._highlightLayer = i.highlightLayer, this._elementLayer = i.elementLayer, this._textLayer && (t.onSelectionContextChange || t.enableElementSelection) && (this._selectionChangeListener = () => this._emitSelectionContextChange(), this._wrapper.ownerDocument.addEventListener("selectionchange", this._selectionChangeListener)), t.enableElementSelection && (this._elementClickListener = (e) => {
|
|
818
|
+
this._onElementClick(e).catch((e) => this._reportRenderError(e));
|
|
819
|
+
}, this._wrapper.addEventListener("click", this._elementClickListener)), t.onContextMenu && (this._contextMenuListener = (e) => this._onContextMenu(e), this._wrapper.addEventListener("contextmenu", this._contextMenuListener)), this._find = new J(() => this.pageCount, (e) => this._collectPageRuns(e));
|
|
547
820
|
}
|
|
548
821
|
async load(e) {
|
|
549
822
|
if (this._destroyed) throw Error("DocxViewer is destroyed");
|
|
550
823
|
if (this._borrowed) throw Error("DocxViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.");
|
|
824
|
+
let t = !1;
|
|
551
825
|
try {
|
|
552
|
-
if (!await this._documentOwner.replace(() =>
|
|
826
|
+
if (!await this._documentOwner.replace(() => U.load(e, {
|
|
827
|
+
password: this._opts.password,
|
|
553
828
|
useGoogleFonts: this._opts.useGoogleFonts,
|
|
554
829
|
maxZipEntryBytes: this._opts.maxZipEntryBytes,
|
|
555
830
|
resourceLimits: this._opts.resourceLimits,
|
|
@@ -560,19 +835,14 @@ var J = class {
|
|
|
560
835
|
math: this._opts.math,
|
|
561
836
|
mode: this._mode
|
|
562
837
|
}), () => {
|
|
563
|
-
this._renderDispatcher.begin(), this._find.invalidate();
|
|
838
|
+
this._invalidateElementContext(!1), t = !0, this._renderDispatcher.begin(), this._find.invalidate();
|
|
564
839
|
})) return;
|
|
565
840
|
if (this._destroyed) throw Error("DocxViewer is destroyed");
|
|
566
841
|
this._currentPage = 0, this._find.invalidate(), await this._render();
|
|
567
842
|
} catch (e) {
|
|
568
|
-
|
|
569
|
-
let t = e instanceof Error ? e : Error(String(e));
|
|
570
|
-
if (this._opts.onError) {
|
|
571
|
-
this._opts.onError(t);
|
|
572
|
-
return;
|
|
573
|
-
}
|
|
574
|
-
throw t;
|
|
843
|
+
throw this._destroyed ? Error("DocxViewer is destroyed") : e instanceof Error ? e : Error(String(e));
|
|
575
844
|
}
|
|
845
|
+
t && !this._destroyed && this._emitSelectionContextChange();
|
|
576
846
|
}
|
|
577
847
|
get pageCount() {
|
|
578
848
|
return this._doc?.pageCount ?? 0;
|
|
@@ -584,7 +854,9 @@ var J = class {
|
|
|
584
854
|
return this._canvas;
|
|
585
855
|
}
|
|
586
856
|
async goToPage(e) {
|
|
587
|
-
|
|
857
|
+
if (!this._doc) return;
|
|
858
|
+
let t = Math.max(0, Math.min(e, this.pageCount - 1)), n = t !== this._currentPage;
|
|
859
|
+
n && this._invalidateElementContext(!1), this._currentPage = t, await this._render(), n && !this._destroyed && this._emitSelectionContextChange();
|
|
588
860
|
}
|
|
589
861
|
async nextPage() {
|
|
590
862
|
await this.goToPage(this._currentPage + 1);
|
|
@@ -612,14 +884,14 @@ var J = class {
|
|
|
612
884
|
return this._opts.zoomMax ?? 4;
|
|
613
885
|
}
|
|
614
886
|
async setScale(e) {
|
|
615
|
-
let t =
|
|
887
|
+
let t = ne(e, this._zoomMin(), this._zoomMax()), n = t !== this.getScale();
|
|
616
888
|
this._scale = t, await this._render(), n && this._opts.onScaleChange?.(t);
|
|
617
889
|
}
|
|
618
890
|
async zoomIn() {
|
|
619
891
|
await this.setScale(T(this.getScale()));
|
|
620
892
|
}
|
|
621
893
|
async zoomOut() {
|
|
622
|
-
await this.setScale(
|
|
894
|
+
await this.setScale(E(this.getScale()));
|
|
623
895
|
}
|
|
624
896
|
async fitWidth() {
|
|
625
897
|
await this._fit("width");
|
|
@@ -631,7 +903,7 @@ var J = class {
|
|
|
631
903
|
if (!this._doc || this._doc.pageCount === 0) return;
|
|
632
904
|
let t = this._doc.pageSize(this._currentPage), n = this._fitContainer();
|
|
633
905
|
if (!n) return;
|
|
634
|
-
let r =
|
|
906
|
+
let r = y({
|
|
635
907
|
contentWidth: t.widthPt * s,
|
|
636
908
|
contentHeight: t.heightPt * s,
|
|
637
909
|
containerWidth: n.clientWidth,
|
|
@@ -667,15 +939,80 @@ var J = class {
|
|
|
667
939
|
if (!this._doc) throw Error("Document not loaded");
|
|
668
940
|
return await this._doc.getResourceMetrics();
|
|
669
941
|
}
|
|
942
|
+
getSelectionContext(e = {}) {
|
|
943
|
+
if (this._destroyed) throw Error("DocxViewer is destroyed");
|
|
944
|
+
return (this._textLayer ? Z(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null, e) : null) ?? (this._elementContext ? H(this._elementContext, e.maxTextCharacters) : null);
|
|
945
|
+
}
|
|
946
|
+
_emitSelectionContextChange() {
|
|
947
|
+
let e = this.getSelectionContext();
|
|
948
|
+
e?.kind === "text" && (this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutline());
|
|
949
|
+
let t = JSON.stringify(e);
|
|
950
|
+
t !== this._selectionContextKey && (this._selectionContextKey = t, this._opts.onSelectionContextChange?.(e ? structuredClone(e) : null));
|
|
951
|
+
}
|
|
952
|
+
_setElementContext(e) {
|
|
953
|
+
this._elementContext = e ? structuredClone(e) : null, this._redrawElementOutline(), this._emitSelectionContextChange();
|
|
954
|
+
}
|
|
955
|
+
_invalidateElementContext(e = !0) {
|
|
956
|
+
this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutline(), e && this._emitSelectionContextChange();
|
|
957
|
+
}
|
|
958
|
+
_redrawElementOutline() {
|
|
959
|
+
let e = this._elementContext, t = this._doc;
|
|
960
|
+
if (!e || !t || e.pageIndex !== this._currentPage) {
|
|
961
|
+
S(this._elementLayer, null);
|
|
962
|
+
return;
|
|
963
|
+
}
|
|
964
|
+
let n = t.pageSize(e.pageIndex);
|
|
965
|
+
S(this._elementLayer, {
|
|
966
|
+
x: e.bounds.xPt / n.widthPt,
|
|
967
|
+
y: e.bounds.yPt / n.heightPt,
|
|
968
|
+
width: e.bounds.widthPt / n.widthPt,
|
|
969
|
+
height: e.bounds.heightPt / n.heightPt
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
async _onElementClick(e) {
|
|
973
|
+
this._destroyed || e.defaultPrevented || e.button !== 0 || await this._resolveContextAt(e);
|
|
974
|
+
}
|
|
975
|
+
_onContextMenu(e) {
|
|
976
|
+
let t;
|
|
977
|
+
this._opts.onContextMenu?.({
|
|
978
|
+
originalEvent: e,
|
|
979
|
+
getContext: () => t ??= this._resolveContextAt(e)
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
async _resolveContextAt(e) {
|
|
983
|
+
let t = this._doc;
|
|
984
|
+
if (this._destroyed || !t) return null;
|
|
985
|
+
if (this._textLayer && Z(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null)) return this._emitSelectionContextChange(), this._destroyed ? null : this.getSelectionContext();
|
|
986
|
+
if (!this._opts.enableElementSelection) return this.getSelectionContext();
|
|
987
|
+
let n = this._canvas.getBoundingClientRect();
|
|
988
|
+
if (n.width <= 0 || n.height <= 0) return this._invalidateElementContext(), null;
|
|
989
|
+
let r = e.clientX - n.left, i = e.clientY - n.top;
|
|
990
|
+
if (r < 0 || i < 0 || r > n.width || i > n.height) return this._invalidateElementContext(), null;
|
|
991
|
+
let a = ++this._elementHitGeneration, o = this._currentPage, s = t.pageSize(o), c;
|
|
992
|
+
try {
|
|
993
|
+
c = await t.getElementContextAt(o, {
|
|
994
|
+
xPt: r / n.width * s.widthPt,
|
|
995
|
+
yPt: i / n.height * s.heightPt
|
|
996
|
+
}, {
|
|
997
|
+
currentDate: this._opts.currentDate,
|
|
998
|
+
maxTextCharacters: I
|
|
999
|
+
});
|
|
1000
|
+
} catch (e) {
|
|
1001
|
+
if (this._destroyed || a !== this._elementHitGeneration || o !== this._currentPage || t !== this._doc) return null;
|
|
1002
|
+
throw e;
|
|
1003
|
+
}
|
|
1004
|
+
return this._destroyed || a !== this._elementHitGeneration || o !== this._currentPage || t !== this._doc ? null : (this._setElementContext(c), this._destroyed ? null : this.getSelectionContext());
|
|
1005
|
+
}
|
|
670
1006
|
destroy() {
|
|
671
|
-
this._destroyed || (this._destroyed = !0, this._errorRouter.close(), this._renderDispatcher.destroy(),
|
|
1007
|
+
this._destroyed || (this._destroyed = !0, this._errorRouter.close(), this._renderDispatcher.destroy(), je(this._canvas), this._documentOwner.close(), this._find.invalidate(), this._selectionChangeListener &&= (this._wrapper.ownerDocument.removeEventListener("selectionchange", this._selectionChangeListener), null), this._elementHitGeneration++, this._elementClickListener &&= (this._wrapper.removeEventListener("click", this._elementClickListener), null), this._contextMenuListener &&= (this._wrapper.removeEventListener("contextmenu", this._contextMenuListener), null), this._elementContext = null, this._canvasMount.restore());
|
|
672
1008
|
}
|
|
673
1009
|
async _render() {
|
|
674
1010
|
let e = this._renderDispatcher.begin();
|
|
675
1011
|
try {
|
|
676
1012
|
await this._renderPage(e);
|
|
677
1013
|
} catch (t) {
|
|
678
|
-
this._renderDispatcher.isCurrent(e)
|
|
1014
|
+
if (!this._renderDispatcher.isCurrent(e)) return;
|
|
1015
|
+
throw t;
|
|
679
1016
|
}
|
|
680
1017
|
}
|
|
681
1018
|
_reportRenderError(e) {
|
|
@@ -689,7 +1026,6 @@ var J = class {
|
|
|
689
1026
|
width: n,
|
|
690
1027
|
dpr: this._opts.dpr,
|
|
691
1028
|
defaultTextColor: this._opts.defaultTextColor,
|
|
692
|
-
showTrackChanges: this._opts.showTrackChanges,
|
|
693
1029
|
currentDate: this._opts.currentDate,
|
|
694
1030
|
onTextRun: i
|
|
695
1031
|
});
|
|
@@ -724,15 +1060,12 @@ var J = class {
|
|
|
724
1060
|
async _collectPageRuns(e) {
|
|
725
1061
|
return this._doc ? this._doc.collectPageRuns(e, {
|
|
726
1062
|
width: this._renderWidth(),
|
|
727
|
-
dpr: this._opts.dpr,
|
|
728
|
-
defaultTextColor: this._opts.defaultTextColor,
|
|
729
|
-
showTrackChanges: this._opts.showTrackChanges,
|
|
730
1063
|
currentDate: this._opts.currentDate
|
|
731
1064
|
}) : [];
|
|
732
1065
|
}
|
|
733
1066
|
_buildTextLayer(e, t) {
|
|
734
1067
|
let { width: n, height: r } = this._canvasCssPx();
|
|
735
|
-
K(e, t, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e));
|
|
1068
|
+
K(e, t, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), this._currentPage);
|
|
736
1069
|
}
|
|
737
1070
|
_hyperlinkHandler() {
|
|
738
1071
|
return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
|
|
@@ -741,10 +1074,10 @@ var J = class {
|
|
|
741
1074
|
return;
|
|
742
1075
|
}
|
|
743
1076
|
let t = this._doc?.getBookmarkPage(e.ref);
|
|
744
|
-
t !== void 0 && this.goToPage(t);
|
|
1077
|
+
t !== void 0 && this.goToPage(t).catch((e) => this._reportRenderError(e));
|
|
745
1078
|
});
|
|
746
1079
|
}
|
|
747
|
-
},
|
|
1080
|
+
}, dt = 150, ft = "0 1px 3px rgba(0,0,0,0.2)", pt = Symbol("DocxScrollViewer.borrowedDocument"), mt = class e {
|
|
748
1081
|
_documentOwner;
|
|
749
1082
|
get _doc() {
|
|
750
1083
|
return this._documentOwner.current;
|
|
@@ -765,6 +1098,12 @@ var J = class {
|
|
|
765
1098
|
_lastRange = null;
|
|
766
1099
|
_lastTopIndex = -1;
|
|
767
1100
|
_scrollListener = null;
|
|
1101
|
+
_selectionChangeListener = null;
|
|
1102
|
+
_selectionContextKey = "null";
|
|
1103
|
+
_elementClickListener = null;
|
|
1104
|
+
_contextMenuListener = null;
|
|
1105
|
+
_elementContext = null;
|
|
1106
|
+
_elementHitGeneration = 0;
|
|
768
1107
|
_destroyed = !1;
|
|
769
1108
|
_measureCtx;
|
|
770
1109
|
_bitmapInFlight = /* @__PURE__ */ new Set();
|
|
@@ -781,27 +1120,31 @@ var J = class {
|
|
|
781
1120
|
static fromDocument(t, n, r = {}) {
|
|
782
1121
|
return new e(t, {
|
|
783
1122
|
...r,
|
|
784
|
-
[
|
|
1123
|
+
[pt]: n
|
|
785
1124
|
});
|
|
786
1125
|
}
|
|
787
1126
|
constructor(e, t = {}) {
|
|
788
1127
|
if (e.tagName === "CANVAS") throw Error("DocxScrollViewer takes a container element (e.g. a <div>), not a <canvas> — the viewer creates and manages its own canvases. Pass a block container; for the single-page canvas API use DocxViewer.");
|
|
789
|
-
this._container = e, this._opts = t, this._pageShadow = t.pageShadow ??
|
|
790
|
-
let n = t[
|
|
791
|
-
this._borrowed = n !== void 0, n ? (this._documentOwner = new
|
|
1128
|
+
this._container = e, this._opts = t, this._pageShadow = t.pageShadow ?? ft;
|
|
1129
|
+
let n = t[pt];
|
|
1130
|
+
this._borrowed = n !== void 0, n ? (this._documentOwner = new b("DocxScrollViewer", n, !1), this._mode = w("DocxScrollViewer", t.mode, n)) : (this._documentOwner = new b("DocxScrollViewer"), this._mode = w("DocxScrollViewer", t.mode, void 0)), this._wrapper = document.createElement("div"), this._wrapper.style.cssText = "position:relative;width:100%;height:100%;overflow:hidden;", this._scrollHost = document.createElement("div"), this._scrollHost.style.cssText = "position:absolute;inset:0;overflow:auto;", this._scrollHost.style.scrollbarGutter = "stable", t.background && (this._scrollHost.style.background = t.background), this._spacer = document.createElement("div"), this._spacer.style.cssText = "position:absolute;top:0;left:0;width:1px;height:0;pointer-events:none;", this._scrollHost.appendChild(this._spacer), this._wrapper.appendChild(this._scrollHost), this._container.appendChild(this._wrapper), t.enableTextSelection && (t.onSelectionContextChange || t.enableElementSelection) && (this._selectionChangeListener = () => this._emitSelectionContextChange(), this._wrapper.ownerDocument.addEventListener("selectionchange", this._selectionChangeListener)), t.enableElementSelection && (this._elementClickListener = (e) => {
|
|
1131
|
+
this._onElementClick(e).catch((e) => this._reportRenderError(e));
|
|
1132
|
+
}, this._scrollHost.addEventListener("click", this._elementClickListener)), t.onContextMenu && (this._contextMenuListener = (e) => this._onContextMenu(e), this._scrollHost.addEventListener("contextmenu", this._contextMenuListener)), this._scrollListener = () => this._onScroll(), this._scrollHost.addEventListener("scroll", this._scrollListener), this._opts.enableZoom !== !1 && (this._wheelListener = (e) => {
|
|
792
1133
|
if (!(e.ctrlKey || e.metaKey) || (e.preventDefault(), e.deltaY === 0)) return;
|
|
793
1134
|
let t = this._scrollHost.getBoundingClientRect(), n = e.clientX - t.left, r = e.clientY - t.top;
|
|
794
1135
|
this._pendingZoomAnchor = Number.isFinite(n) && Number.isFinite(r) ? {
|
|
795
1136
|
x: n,
|
|
796
1137
|
y: r
|
|
797
|
-
} : null, this.setScale(
|
|
1138
|
+
} : null, this.setScale(pe(this._scale, e.deltaY));
|
|
798
1139
|
}, this._scrollHost.addEventListener("wheel", this._wheelListener, { passive: !1 })), typeof ResizeObserver < "u" && (this._resizeObserver = new ResizeObserver(() => this._onResize()), this._resizeObserver.observe(this._container)), this._borrowed && this.relayout();
|
|
799
1140
|
}
|
|
800
1141
|
async load(e) {
|
|
801
1142
|
if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
|
|
802
1143
|
if (this._borrowed) throw Error("DocxScrollViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.");
|
|
1144
|
+
let t = !1;
|
|
803
1145
|
try {
|
|
804
|
-
if (!await this._documentOwner.replace(() =>
|
|
1146
|
+
if (!await this._documentOwner.replace(() => U.load(e, {
|
|
1147
|
+
password: this._opts.password,
|
|
805
1148
|
useGoogleFonts: this._opts.useGoogleFonts,
|
|
806
1149
|
maxZipEntryBytes: this._opts.maxZipEntryBytes,
|
|
807
1150
|
resourceLimits: this._opts.resourceLimits,
|
|
@@ -812,22 +1155,19 @@ var J = class {
|
|
|
812
1155
|
math: this._opts.math,
|
|
813
1156
|
mode: this._mode
|
|
814
1157
|
}), (e) => {
|
|
815
|
-
if (this._find.invalidate(), this._findActive = !1, e) {
|
|
1158
|
+
if (this._invalidateElementContext(!1), t = !0, this._find.invalidate(), this._findActive = !1, e) {
|
|
816
1159
|
for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
|
|
817
1160
|
this._lastTopIndex = -1;
|
|
818
1161
|
}
|
|
819
1162
|
})) return;
|
|
820
1163
|
if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
|
|
821
|
-
this._find.invalidate(), this._findActive = !1
|
|
1164
|
+
this._find.invalidate(), this._findActive = !1;
|
|
1165
|
+
let n = [];
|
|
1166
|
+
this._relayout(n), await Promise.all(n);
|
|
822
1167
|
} catch (e) {
|
|
823
|
-
|
|
824
|
-
let t = e instanceof Error ? e : Error(String(e));
|
|
825
|
-
if (this._opts.onError) {
|
|
826
|
-
this._opts.onError(t);
|
|
827
|
-
return;
|
|
828
|
-
}
|
|
829
|
-
throw t;
|
|
1168
|
+
throw this._destroyed ? Error("DocxScrollViewer is destroyed") : e instanceof Error ? e : Error(String(e));
|
|
830
1169
|
}
|
|
1170
|
+
t && !this._destroyed && this._emitSelectionContextChange();
|
|
831
1171
|
}
|
|
832
1172
|
get pageCount() {
|
|
833
1173
|
return this._doc?.pageCount ?? 0;
|
|
@@ -853,6 +1193,9 @@ var J = class {
|
|
|
853
1193
|
return t <= 0 ? 0 : e / (t * s);
|
|
854
1194
|
}
|
|
855
1195
|
relayout() {
|
|
1196
|
+
this._relayout();
|
|
1197
|
+
}
|
|
1198
|
+
_relayout(e) {
|
|
856
1199
|
if (this._doc) {
|
|
857
1200
|
if (!this._scaleEstablished) {
|
|
858
1201
|
let e = this._baseScale();
|
|
@@ -863,7 +1206,7 @@ var J = class {
|
|
|
863
1206
|
}
|
|
864
1207
|
} else return;
|
|
865
1208
|
}
|
|
866
|
-
this._recomputeHeights(), this._syncSpacer(), this._mountVisible();
|
|
1209
|
+
this._recomputeHeights(), this._syncSpacer(), this._mountVisible(e);
|
|
867
1210
|
}
|
|
868
1211
|
}
|
|
869
1212
|
_recomputeHeights() {
|
|
@@ -900,7 +1243,7 @@ var J = class {
|
|
|
900
1243
|
return a;
|
|
901
1244
|
}
|
|
902
1245
|
_range() {
|
|
903
|
-
return
|
|
1246
|
+
return M(this._heights, this._gap(), this._scrollHost.scrollTop, this._scrollHost.clientHeight, this._overscan(), this._pad());
|
|
904
1247
|
}
|
|
905
1248
|
_syncSpacer() {
|
|
906
1249
|
let e = this._range();
|
|
@@ -917,17 +1260,19 @@ var J = class {
|
|
|
917
1260
|
_onScroll() {
|
|
918
1261
|
!this._doc || !this._scaleEstablished || this._mountVisible();
|
|
919
1262
|
}
|
|
920
|
-
_mountVisible() {
|
|
1263
|
+
_mountVisible(e) {
|
|
921
1264
|
if (!this._doc || this._doc.pageCount === 0) return;
|
|
922
|
-
let
|
|
923
|
-
this._lastRange =
|
|
924
|
-
for (let [
|
|
925
|
-
for (let
|
|
1265
|
+
let t = this._range();
|
|
1266
|
+
this._lastRange = t;
|
|
1267
|
+
for (let [e, n] of [...this._slots]) (e < t.start || e > t.end) && this._recycleSlot(e, n);
|
|
1268
|
+
for (let n = t.start; n <= t.end; n++) if (this._slots.has(n)) this._positionSlot(this._slots.get(n), n, t);
|
|
926
1269
|
else {
|
|
927
|
-
let
|
|
928
|
-
this._positionSlot(n, t
|
|
1270
|
+
let r = this._acquireSlot();
|
|
1271
|
+
this._positionSlot(r, n, t), this._slots.set(n, r);
|
|
1272
|
+
let i = this._renderSlot(n, r, e === void 0);
|
|
1273
|
+
e && i && e.push(i);
|
|
929
1274
|
}
|
|
930
|
-
|
|
1275
|
+
t.topIndex !== this._lastTopIndex && (this._lastTopIndex = t.topIndex, this._opts.onVisiblePageChange?.(t.topIndex, this._doc.pageCount));
|
|
931
1276
|
}
|
|
932
1277
|
_applyPageShadow(e) {
|
|
933
1278
|
this._pageShadow !== !1 && (e.style.boxShadow = this._pageShadow);
|
|
@@ -942,54 +1287,60 @@ var J = class {
|
|
|
942
1287
|
let r = null;
|
|
943
1288
|
this._opts.enableTextSelection && (r = document.createElement("div"), r.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;user-select:text;-webkit-user-select:text;", t.appendChild(r));
|
|
944
1289
|
let i = document.createElement("div");
|
|
945
|
-
|
|
1290
|
+
i.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;", t.appendChild(i);
|
|
1291
|
+
let a = oe(t, this._opts.enableElementSelection === !0);
|
|
1292
|
+
return this._scrollHost.appendChild(t), {
|
|
946
1293
|
wrapper: t,
|
|
947
1294
|
canvas: n,
|
|
948
1295
|
textLayer: r,
|
|
949
1296
|
highlightLayer: i,
|
|
1297
|
+
elementLayer: a,
|
|
950
1298
|
renderedPage: -1,
|
|
951
1299
|
renderedScale: -1,
|
|
952
|
-
dispatcher: new
|
|
1300
|
+
dispatcher: new C(n, this._mode === "worker")
|
|
953
1301
|
};
|
|
954
1302
|
}
|
|
955
1303
|
_recycleSlot(e, t) {
|
|
956
|
-
this._slots.delete(e), t.dispatcher.destroy(), this._destroyed || (t.dispatcher = new
|
|
1304
|
+
this._slots.delete(e), t.dispatcher.destroy(), this._destroyed || (t.dispatcher = new C(t.canvas, this._mode === "worker")), t.textLayer && (t.textLayer.innerHTML = "", t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = ""), t.highlightLayer.innerHTML = "", t.highlightLayer.style.transform = "", t.highlightLayer.style.transformOrigin = "", S(t.elementLayer, null), t.renderedPage = -1, t.renderedScale = -1, t.wrapper.remove(), this._free.push(t);
|
|
957
1305
|
}
|
|
958
1306
|
_positionSlot(e, t, n) {
|
|
959
1307
|
e.wrapper.style.top = `${n.offsets[t]}px`;
|
|
960
1308
|
let r = this._pageWidthPx(t), i = this._pageHeightPx(t);
|
|
961
|
-
e.wrapper.style.width = `${r}px`, e.wrapper.style.height = `${i}px
|
|
1309
|
+
e.wrapper.style.width = `${r}px`, e.wrapper.style.height = `${i}px`, this._redrawElementOutlineForSlot(t, e);
|
|
962
1310
|
let { left: a } = this._padH(), o = this._scrollHost.clientWidth;
|
|
963
1311
|
e.wrapper.style.left = `${Math.max(a, (o - r) / 2)}px`;
|
|
964
1312
|
}
|
|
965
1313
|
_dpr() {
|
|
966
1314
|
return this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1);
|
|
967
1315
|
}
|
|
968
|
-
_renderSlot(e, t) {
|
|
969
|
-
if (!this._doc || t.renderedPage === e) return;
|
|
1316
|
+
_renderSlot(e, t, n = !0) {
|
|
1317
|
+
if (!this._doc || t.renderedPage === e) return null;
|
|
970
1318
|
t.renderedPage = e;
|
|
971
|
-
let
|
|
972
|
-
if (this._mode === "worker")
|
|
973
|
-
|
|
974
|
-
|
|
1319
|
+
let r = this._dpr(), i = this._pageWidthPx(e), a = this._renderEpoch, o = this._scale, s = t.dispatcher, c = s.begin();
|
|
1320
|
+
if (this._mode === "worker") return this._renderSlotBitmap(e, t, i, r, o, s, c, n);
|
|
1321
|
+
let l = [], u = !!this._opts.enableTextSelection && !!t.textLayer, d = u || this._findActive, f = d ? (e) => l.push(e) : void 0, p;
|
|
1322
|
+
try {
|
|
1323
|
+
p = this._doc.renderPage(t.canvas, e, {
|
|
1324
|
+
width: i,
|
|
1325
|
+
dpr: r,
|
|
1326
|
+
defaultTextColor: this._opts.defaultTextColor,
|
|
1327
|
+
currentDate: this._opts.currentDate,
|
|
1328
|
+
onTextRun: f
|
|
1329
|
+
});
|
|
1330
|
+
} catch (e) {
|
|
1331
|
+
return n ? (this._reportRenderError(e), Promise.resolve()) : Promise.reject(e);
|
|
975
1332
|
}
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
showTrackChanges: this._opts.showTrackChanges,
|
|
982
|
-
onTextRun: d
|
|
983
|
-
}).then(() => {
|
|
984
|
-
if (!(!o.isCurrent(s) || i !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e)) {
|
|
985
|
-
if (t.renderedScale = a, l && t.textLayer) {
|
|
986
|
-
let { width: e, height: n } = this._canvasCssPx(t.canvas);
|
|
987
|
-
K(t.textLayer, c, e, n, this._hyperlinkHandler(), (e) => this._measureForFont(e));
|
|
1333
|
+
return p.then(() => {
|
|
1334
|
+
if (!(!s.isCurrent(c) || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e)) {
|
|
1335
|
+
if (t.renderedScale = o, u && t.textLayer) {
|
|
1336
|
+
let { width: n, height: r } = this._canvasCssPx(t.canvas);
|
|
1337
|
+
K(t.textLayer, l, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
|
|
988
1338
|
}
|
|
989
|
-
|
|
1339
|
+
d && this._refreshFindRuns(e, l), this._redrawSlotHighlights(e, t);
|
|
990
1340
|
}
|
|
991
|
-
}).catch((
|
|
992
|
-
|
|
1341
|
+
}).catch((r) => {
|
|
1342
|
+
if (s.isCurrent(c) && a === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e) if (n) this._reportRenderError(r);
|
|
1343
|
+
else throw r;
|
|
993
1344
|
});
|
|
994
1345
|
}
|
|
995
1346
|
_hyperlinkHandler() {
|
|
@@ -1018,38 +1369,39 @@ var J = class {
|
|
|
1018
1369
|
let t = e instanceof Error ? e : Error(String(e));
|
|
1019
1370
|
this._opts.onError ? this._opts.onError(t) : console.error("[ooxml] DocxScrollViewer render failed:", t);
|
|
1020
1371
|
}
|
|
1021
|
-
async _renderSlotBitmap(e, t, n, r, i, a = t.dispatcher, o = a.begin()) {
|
|
1372
|
+
async _renderSlotBitmap(e, t, n, r, i, a = t.dispatcher, o = a.begin(), s = !0) {
|
|
1022
1373
|
if (this._bitmapInFlight.has(e) || this._slots.get(e) !== t) return;
|
|
1023
|
-
let
|
|
1374
|
+
let c = this._renderEpoch;
|
|
1024
1375
|
this._bitmapInFlight.add(e);
|
|
1025
|
-
let
|
|
1376
|
+
let l = !1, u = !!this._opts.enableTextSelection && !!t.textLayer, d = u || this._findActive, f = [];
|
|
1026
1377
|
try {
|
|
1027
|
-
let
|
|
1378
|
+
let s = await this._doc.renderPageToBitmap(e, {
|
|
1028
1379
|
width: n,
|
|
1029
1380
|
dpr: r,
|
|
1030
1381
|
defaultTextColor: this._opts.defaultTextColor,
|
|
1031
|
-
|
|
1032
|
-
onTextRun:
|
|
1382
|
+
currentDate: this._opts.currentDate,
|
|
1383
|
+
onTextRun: d ? (e) => f.push(e) : void 0
|
|
1033
1384
|
});
|
|
1034
|
-
if (!a.isCurrent(o) ||
|
|
1035
|
-
|
|
1385
|
+
if (!a.isCurrent(o) || c !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) {
|
|
1386
|
+
s.close();
|
|
1036
1387
|
return;
|
|
1037
1388
|
}
|
|
1038
|
-
if (!a.commitBitmap(o,
|
|
1039
|
-
cssWidth: Math.round(
|
|
1040
|
-
cssHeight: Math.round(
|
|
1389
|
+
if (!a.commitBitmap(o, s, {
|
|
1390
|
+
cssWidth: Math.round(s.width / r),
|
|
1391
|
+
cssHeight: Math.round(s.height / r)
|
|
1041
1392
|
})) return;
|
|
1042
|
-
if (t.renderedScale = i, t.textLayer && (t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = "",
|
|
1043
|
-
let { width:
|
|
1044
|
-
K(t.textLayer,
|
|
1393
|
+
if (t.renderedScale = i, t.textLayer && (t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = "", u)) {
|
|
1394
|
+
let { width: n, height: r } = this._canvasCssPx(t.canvas);
|
|
1395
|
+
K(t.textLayer, f, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
|
|
1045
1396
|
}
|
|
1046
|
-
|
|
1397
|
+
d && this._refreshFindRuns(e, f), this._redrawSlotHighlights(e, t), l = !0;
|
|
1047
1398
|
} catch (n) {
|
|
1048
|
-
a.isCurrent(o) &&
|
|
1399
|
+
if (a.isCurrent(o) && c === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e) if (s) this._reportRenderError(n);
|
|
1400
|
+
else throw n;
|
|
1049
1401
|
} finally {
|
|
1050
1402
|
this._bitmapInFlight.delete(e);
|
|
1051
1403
|
let n = this._slots.get(e);
|
|
1052
|
-
!
|
|
1404
|
+
!l && n && (n !== t || c !== this._renderEpoch || !a.isCurrent(o)) && !this._bitmapInFlight.has(e) && !this._destroyed && this._renderSlotBitmap(e, n, this._pageWidthPx(e), this._dpr(), this._scale);
|
|
1053
1405
|
}
|
|
1054
1406
|
}
|
|
1055
1407
|
setScale(e) {
|
|
@@ -1063,12 +1415,12 @@ var J = class {
|
|
|
1063
1415
|
f = Math.min(1, Math.max(0, f));
|
|
1064
1416
|
let p = this._padH().left, m = this._scrollHost.scrollLeft || 0;
|
|
1065
1417
|
this._renderEpoch++, this._scale = r, this._recomputeHeights();
|
|
1066
|
-
let h =
|
|
1418
|
+
let h = M(this._heights, this._gap(), 0, this._scrollHost.clientHeight, this._overscan(), this._pad());
|
|
1067
1419
|
this._spacer.style.height = `${h.totalHeight}px`, this._syncSpacerWidth();
|
|
1068
1420
|
let g = Math.max(0, h.totalHeight - this._scrollHost.clientHeight), _ = (h.offsets[u] ?? 0) + f * (this._heights[u] || 0), v = l < (s.offsets[0] ?? 0) ? c : _ - o;
|
|
1069
1421
|
if (this._scrollHost.scrollTop = Math.min(g, Math.max(0, v)), i) {
|
|
1070
1422
|
let e = Math.max(0, (this._spacer.offsetWidth || 0) - this._scrollHost.clientWidth);
|
|
1071
|
-
this._scrollHost.scrollLeft =
|
|
1423
|
+
this._scrollHost.scrollLeft = x(m, i.x - p, a, r, { maxScroll: e });
|
|
1072
1424
|
}
|
|
1073
1425
|
this._previewVisible(), this._scheduleSettle(), this._opts.onScaleChange?.(r);
|
|
1074
1426
|
}
|
|
@@ -1079,7 +1431,7 @@ var J = class {
|
|
|
1079
1431
|
this.setScale(T(this.getScale()));
|
|
1080
1432
|
}
|
|
1081
1433
|
zoomOut() {
|
|
1082
|
-
this.setScale(
|
|
1434
|
+
this.setScale(E(this.getScale()));
|
|
1083
1435
|
}
|
|
1084
1436
|
fitWidth() {
|
|
1085
1437
|
this._fit("width");
|
|
@@ -1089,7 +1441,7 @@ var J = class {
|
|
|
1089
1441
|
}
|
|
1090
1442
|
_fit(e) {
|
|
1091
1443
|
if (!this._doc || this._doc.pageCount === 0) return;
|
|
1092
|
-
let t = this._doc.pageSize(0), n =
|
|
1444
|
+
let t = this._doc.pageSize(0), n = y({
|
|
1093
1445
|
contentWidth: t.widthPt * s,
|
|
1094
1446
|
contentHeight: t.heightPt * s,
|
|
1095
1447
|
containerWidth: this._fitWidthPx(),
|
|
@@ -1121,7 +1473,7 @@ var J = class {
|
|
|
1121
1473
|
_scheduleSettle() {
|
|
1122
1474
|
this._settleTimer !== null && clearTimeout(this._settleTimer), this._settleTimer = setTimeout(() => {
|
|
1123
1475
|
this._settleTimer = null, this._settleRender();
|
|
1124
|
-
},
|
|
1476
|
+
}, dt);
|
|
1125
1477
|
}
|
|
1126
1478
|
_settleRender() {
|
|
1127
1479
|
if (!(this._destroyed || !this._doc || this._doc.pageCount === 0)) for (let [e, t] of [...this._slots]) t.renderedScale !== this._scale && this._settleSlot(e, t);
|
|
@@ -1135,12 +1487,12 @@ var J = class {
|
|
|
1135
1487
|
}
|
|
1136
1488
|
let o = document.createElement("canvas");
|
|
1137
1489
|
o.style.cssText = "display:block;background:#fff;", this._applyPageShadow(o);
|
|
1138
|
-
let s = new
|
|
1490
|
+
let s = new C(o, !1), c = s.begin(), l = [], u = !!this._opts.enableTextSelection && !!t.textLayer, d = u || this._findActive, f = d ? (e) => l.push(e) : void 0;
|
|
1139
1491
|
this._doc.renderPage(o, e, {
|
|
1140
1492
|
width: r,
|
|
1141
1493
|
dpr: n,
|
|
1142
1494
|
defaultTextColor: this._opts.defaultTextColor,
|
|
1143
|
-
|
|
1495
|
+
currentDate: this._opts.currentDate,
|
|
1144
1496
|
onTextRun: f
|
|
1145
1497
|
}).then(() => {
|
|
1146
1498
|
if (!s.isCurrent(c) || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) {
|
|
@@ -1149,8 +1501,8 @@ var J = class {
|
|
|
1149
1501
|
}
|
|
1150
1502
|
let n = t.canvas;
|
|
1151
1503
|
if (t.dispatcher.destroy(), t.wrapper.insertBefore(o, n), n.remove(), t.canvas = o, t.dispatcher = s, t.renderedScale = i, t.textLayer && (t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = "", u)) {
|
|
1152
|
-
let { width:
|
|
1153
|
-
K(t.textLayer, l,
|
|
1504
|
+
let { width: n, height: r } = this._canvasCssPx(o);
|
|
1505
|
+
K(t.textLayer, l, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
|
|
1154
1506
|
}
|
|
1155
1507
|
d && this._refreshFindRuns(e, l), this._redrawSlotHighlights(e, t);
|
|
1156
1508
|
}).catch((n) => {
|
|
@@ -1159,7 +1511,7 @@ var J = class {
|
|
|
1159
1511
|
}
|
|
1160
1512
|
scrollToPage(e, t) {
|
|
1161
1513
|
if (!this._doc || this._doc.pageCount === 0 || !this._scaleEstablished) return;
|
|
1162
|
-
let n = Math.max(0, Math.min(e, this._doc.pageCount - 1)), r =
|
|
1514
|
+
let n = Math.max(0, Math.min(e, this._doc.pageCount - 1)), r = M(this._heights, this._gap(), 0, this._scrollHost.clientHeight, this._overscan(), this._pad()), i = r.offsets[n] ?? 0, a = Math.max(0, r.totalHeight - this._scrollHost.clientHeight), o = Math.min(a, Math.max(0, i)), s = this._scrollHost;
|
|
1163
1515
|
typeof s.scrollTo == "function" ? s.scrollTo({
|
|
1164
1516
|
top: o,
|
|
1165
1517
|
behavior: t?.behavior ?? "auto"
|
|
@@ -1186,8 +1538,7 @@ var J = class {
|
|
|
1186
1538
|
async _collectPageRuns(e) {
|
|
1187
1539
|
return this._doc ? this._doc.collectPageRuns(e, {
|
|
1188
1540
|
width: this._pageWidthPx(e),
|
|
1189
|
-
|
|
1190
|
-
showTrackChanges: this._opts.showTrackChanges
|
|
1541
|
+
currentDate: this._opts.currentDate
|
|
1191
1542
|
}) : [];
|
|
1192
1543
|
}
|
|
1193
1544
|
_redrawHighlights() {
|
|
@@ -1261,9 +1612,78 @@ var J = class {
|
|
|
1261
1612
|
if (!this._doc) throw Error("Document not loaded");
|
|
1262
1613
|
return await this._doc.getResourceMetrics();
|
|
1263
1614
|
}
|
|
1615
|
+
getSelectionContext(e = {}) {
|
|
1616
|
+
if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
|
|
1617
|
+
return (this._opts.enableTextSelection ? Z(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null, e) : null) ?? (this._elementContext ? H(this._elementContext, e.maxTextCharacters) : null);
|
|
1618
|
+
}
|
|
1619
|
+
_emitSelectionContextChange() {
|
|
1620
|
+
let e = this.getSelectionContext();
|
|
1621
|
+
e?.kind === "text" && (this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutlines());
|
|
1622
|
+
let t = JSON.stringify(e);
|
|
1623
|
+
t !== this._selectionContextKey && (this._selectionContextKey = t, this._opts.onSelectionContextChange?.(e ? structuredClone(e) : null));
|
|
1624
|
+
}
|
|
1625
|
+
_setElementContext(e) {
|
|
1626
|
+
this._elementContext = e ? structuredClone(e) : null, this._redrawElementOutlines(), this._emitSelectionContextChange();
|
|
1627
|
+
}
|
|
1628
|
+
_invalidateElementContext(e = !0) {
|
|
1629
|
+
this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutlines(), e && this._emitSelectionContextChange();
|
|
1630
|
+
}
|
|
1631
|
+
_redrawElementOutlines() {
|
|
1632
|
+
for (let [e, t] of this._slots) this._redrawElementOutlineForSlot(e, t);
|
|
1633
|
+
}
|
|
1634
|
+
_redrawElementOutlineForSlot(e, t) {
|
|
1635
|
+
let n = this._elementContext, r = this._doc;
|
|
1636
|
+
if (!n || !r || n.pageIndex !== e) {
|
|
1637
|
+
S(t.elementLayer, null);
|
|
1638
|
+
return;
|
|
1639
|
+
}
|
|
1640
|
+
let i = r.pageSize(e);
|
|
1641
|
+
S(t.elementLayer, {
|
|
1642
|
+
x: n.bounds.xPt / i.widthPt,
|
|
1643
|
+
y: n.bounds.yPt / i.heightPt,
|
|
1644
|
+
width: n.bounds.widthPt / i.widthPt,
|
|
1645
|
+
height: n.bounds.heightPt / i.heightPt
|
|
1646
|
+
});
|
|
1647
|
+
}
|
|
1648
|
+
async _onElementClick(e) {
|
|
1649
|
+
this._destroyed || e.defaultPrevented || e.button !== 0 || await this._resolveContextAt(e);
|
|
1650
|
+
}
|
|
1651
|
+
_onContextMenu(e) {
|
|
1652
|
+
let t;
|
|
1653
|
+
this._opts.onContextMenu?.({
|
|
1654
|
+
originalEvent: e,
|
|
1655
|
+
getContext: () => t ??= this._resolveContextAt(e)
|
|
1656
|
+
});
|
|
1657
|
+
}
|
|
1658
|
+
async _resolveContextAt(e) {
|
|
1659
|
+
let t = this._doc;
|
|
1660
|
+
if (this._destroyed || !t) return null;
|
|
1661
|
+
if (this._opts.enableTextSelection && Z(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null)) return this._emitSelectionContextChange(), this._destroyed ? null : this.getSelectionContext();
|
|
1662
|
+
if (!this._opts.enableElementSelection) return this.getSelectionContext();
|
|
1663
|
+
let n = e.target, r = [...this._slots].find(([, e]) => n !== null && e.wrapper.contains(n));
|
|
1664
|
+
if (!r) return this._invalidateElementContext(), null;
|
|
1665
|
+
let [i, a] = r, o = a.canvas.getBoundingClientRect();
|
|
1666
|
+
if (o.width <= 0 || o.height <= 0) return this._invalidateElementContext(), null;
|
|
1667
|
+
let s = e.clientX - o.left, c = e.clientY - o.top;
|
|
1668
|
+
if (s < 0 || c < 0 || s > o.width || c > o.height) return this._invalidateElementContext(), null;
|
|
1669
|
+
let l = ++this._elementHitGeneration, u = t.pageSize(i), d;
|
|
1670
|
+
try {
|
|
1671
|
+
d = await t.getElementContextAt(i, {
|
|
1672
|
+
xPt: s / o.width * u.widthPt,
|
|
1673
|
+
yPt: c / o.height * u.heightPt
|
|
1674
|
+
}, {
|
|
1675
|
+
currentDate: this._opts.currentDate,
|
|
1676
|
+
maxTextCharacters: I
|
|
1677
|
+
});
|
|
1678
|
+
} catch (e) {
|
|
1679
|
+
if (this._destroyed || l !== this._elementHitGeneration || t !== this._doc) return null;
|
|
1680
|
+
throw e;
|
|
1681
|
+
}
|
|
1682
|
+
return this._destroyed || l !== this._elementHitGeneration || t !== this._doc ? null : (this._setElementContext(d), this._destroyed ? null : this.getSelectionContext());
|
|
1683
|
+
}
|
|
1264
1684
|
destroy() {
|
|
1265
1685
|
if (!this._destroyed) {
|
|
1266
|
-
this._destroyed = !0, this._find.invalidate(), this._findActive = !1, this._scrollListener &&= (this._scrollHost.removeEventListener("scroll", this._scrollListener), null), this._wheelListener &&= (this._scrollHost.removeEventListener("wheel", this._wheelListener), null), this._resizeObserver?.disconnect(), this._resizeObserver = null, this._settleTimer !== null && (clearTimeout(this._settleTimer), this._settleTimer = null);
|
|
1686
|
+
this._destroyed = !0, this._find.invalidate(), this._findActive = !1, this._selectionChangeListener &&= (this._wrapper.ownerDocument.removeEventListener("selectionchange", this._selectionChangeListener), null), this._elementHitGeneration++, this._elementClickListener &&= (this._scrollHost.removeEventListener("click", this._elementClickListener), null), this._contextMenuListener &&= (this._scrollHost.removeEventListener("contextmenu", this._contextMenuListener), null), this._elementContext = null, this._scrollListener &&= (this._scrollHost.removeEventListener("scroll", this._scrollListener), null), this._wheelListener &&= (this._scrollHost.removeEventListener("wheel", this._wheelListener), null), this._resizeObserver?.disconnect(), this._resizeObserver = null, this._settleTimer !== null && (clearTimeout(this._settleTimer), this._settleTimer = null);
|
|
1267
1687
|
for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
|
|
1268
1688
|
this._free.length = 0, this._documentOwner.close(), this._wrapper.remove();
|
|
1269
1689
|
}
|
|
@@ -1283,19 +1703,20 @@ function $(e) {
|
|
|
1283
1703
|
}
|
|
1284
1704
|
//#endregion
|
|
1285
1705
|
//#region src/docx.ts
|
|
1286
|
-
var
|
|
1287
|
-
DocxDocument: () =>
|
|
1288
|
-
DocxScrollViewer: () =>
|
|
1289
|
-
DocxViewer: () =>
|
|
1706
|
+
var ht = /* @__PURE__ */ e({
|
|
1707
|
+
DocxDocument: () => U,
|
|
1708
|
+
DocxScrollViewer: () => mt,
|
|
1709
|
+
DocxViewer: () => ut,
|
|
1290
1710
|
OoxmlDecodedImageLimitError: () => r,
|
|
1291
1711
|
OoxmlError: () => f,
|
|
1292
1712
|
OoxmlResourceLimitError: () => c,
|
|
1293
|
-
autoResize: () =>
|
|
1713
|
+
autoResize: () => fe,
|
|
1294
1714
|
buildDocxHighlightLayer: () => q,
|
|
1295
1715
|
buildDocxTextLayer: () => K,
|
|
1296
1716
|
isOoxmlDecodedImageLimitError: () => i,
|
|
1297
1717
|
noteText: () => $,
|
|
1298
|
-
openExternalHyperlink: () => o
|
|
1718
|
+
openExternalHyperlink: () => o,
|
|
1719
|
+
readDocxTextSelectionContext: () => Z
|
|
1299
1720
|
});
|
|
1300
1721
|
//#endregion
|
|
1301
|
-
export {
|
|
1722
|
+
export { Z as a, U as c, ut as i, $ as n, q as o, mt as r, K as s, ht as t };
|