@d-i-t-a/reader 2.4.3 → 2.4.4
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/dist/esm/index.js +27 -10
- package/dist/esm/index.js.map +2 -2
- package/dist/reader.js +2 -2
- package/dist/reader.js.map +2 -2
- package/package.json +1 -1
package/dist/reader.js
CHANGED
|
@@ -70,7 +70,7 @@ function print() { __p += __j.call(arguments, '') }
|
|
|
70
70
|
`?"\\n":ee==="\r"?"\\r":`\\${ee}`)}function ie(pe){return/^[\x00-\x7F]*$/.test(pe)}function be(pe){let ee=["\xFE\xFF"];for(let de=0,je=pe.length;de<je;de++){let Be=pe.charCodeAt(de);ee.push(String.fromCharCode(Be>>8&255),String.fromCharCode(Be&255))}return ee.join("")}function Ee(pe){return decodeURIComponent(escape(pe))}function Re(pe){return unescape(encodeURIComponent(pe))}function Ke(pe){return typeof pe=="object"&&pe!==null&&pe.byteLength!==void 0}function ze(pe,ee){if(pe.length!==ee.length)return!1;for(let de=0,je=pe.length;de<je;de++)if(pe[de]!==ee[de])return!1;return!0}function Ve(pe=new Date){return[pe.getUTCFullYear().toString(),(pe.getUTCMonth()+1).toString().padStart(2,"0"),pe.getUTCDate().toString().padStart(2,"0"),pe.getUTCHours().toString().padStart(2,"0"),pe.getUTCMinutes().toString().padStart(2,"0"),pe.getUTCSeconds().toString().padStart(2,"0")].join("")}function qe(){let pe=Object.create(null),ee=!1;return Object.defineProperty(pe,"settled",{get(){return ee}}),pe.promise=new Promise(function(de,je){pe.resolve=function(Be){ee=!0,de(Be)},pe.reject=function(Be){ee=!0,je(Be)}}),pe}},(r,e,t)=>{var n=t(3)},(r,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isNodeJS=void 0;let t=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser");e.isNodeJS=t},(__unused_webpack_module,exports,__w_pdfjs_require__)=>{var r,t,n,i,o,s,c,f,u,rm,m;Object.defineProperty(exports,"__esModule",{value:!0}),exports.build=exports.RenderTask=exports.PDFWorkerUtil=exports.PDFWorker=exports.PDFPageProxy=exports.PDFDocumentProxy=exports.PDFDocumentLoadingTask=exports.PDFDataRangeTransport=exports.LoopbackPort=exports.DefaultStandardFontDataFactory=exports.DefaultCanvasFactory=exports.DefaultCMapReaderFactory=void 0,exports.getDocument=getDocument,exports.setPDFNetworkStreamFactory=setPDFNetworkStreamFactory,exports.version=void 0;var _util=__w_pdfjs_require__(1),_display_utils=__w_pdfjs_require__(5),_font_loader=__w_pdfjs_require__(7),_annotation_storage=__w_pdfjs_require__(8),_canvas=__w_pdfjs_require__(10),_worker_options=__w_pdfjs_require__(13),_is_node=__w_pdfjs_require__(3),_message_handler=__w_pdfjs_require__(14),_metadata=__w_pdfjs_require__(15),_optional_content_config=__w_pdfjs_require__(16),_transport_stream=__w_pdfjs_require__(17),_xfa_text=__w_pdfjs_require__(18);let DEFAULT_RANGE_CHUNK_SIZE=65536,RENDERING_CANCELLED_TIMEOUT=100,DefaultCanvasFactory=_display_utils.DOMCanvasFactory;exports.DefaultCanvasFactory=DefaultCanvasFactory;let DefaultCMapReaderFactory=_display_utils.DOMCMapReaderFactory;exports.DefaultCMapReaderFactory=DefaultCMapReaderFactory;let DefaultStandardFontDataFactory=_display_utils.DOMStandardFontDataFactory;if(exports.DefaultStandardFontDataFactory=DefaultStandardFontDataFactory,_is_node.isNodeJS){let{NodeCanvasFactory:v,NodeCMapReaderFactory:g,NodeStandardFontDataFactory:h}=__w_pdfjs_require__(19);exports.DefaultCanvasFactory=DefaultCanvasFactory=v,exports.DefaultCMapReaderFactory=DefaultCMapReaderFactory=g,exports.DefaultStandardFontDataFactory=DefaultStandardFontDataFactory=h}let createPDFNetworkStream;function setPDFNetworkStreamFactory(v){createPDFNetworkStream=v}function getDocument(v){let g=new PDFDocumentLoadingTask,h;if(typeof v=="string"||v instanceof URL)h={url:v};else if((0,_util.isArrayBuffer)(v))h={data:v};else if(v instanceof PDFDataRangeTransport)h={range:v};else{if(typeof v!="object")throw new Error("Invalid parameter in getDocument, need either string, URL, Uint8Array, or parameter object.");if(!v.url&&!v.data&&!v.range)throw new Error("Invalid parameter object: need either .data, .range or .url");h=v}let l=Object.create(null),p=null,w=null;for(let C in h){let b=h[C];switch(C){case"url":if(typeof window<"u")try{l[C]=new URL(b,window.location).href;continue}catch(E){(0,_util.warn)(`Cannot create valid URL: "${E}".`)}else if(typeof b=="string"||b instanceof URL){l[C]=b.toString();continue}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.");case"range":p=b;continue;case"worker":w=b;continue;case"data":if(_is_node.isNodeJS&&typeof Buffer<"u"&&b instanceof Buffer)l[C]=new Uint8Array(b);else{if(b instanceof Uint8Array)break;if(typeof b=="string")l[C]=(0,_util.stringToBytes)(b);else if(typeof b=="object"&&b!==null&&!isNaN(b.length))l[C]=new Uint8Array(b);else if((0,_util.isArrayBuffer)(b))l[C]=new Uint8Array(b);else throw new Error("Invalid PDF binary data: either typed array, string, or array-like object is expected in the data property.")}continue}l[C]=b}if(l.CMapReaderFactory=l.CMapReaderFactory||DefaultCMapReaderFactory,l.StandardFontDataFactory=l.StandardFontDataFactory||DefaultStandardFontDataFactory,l.ignoreErrors=l.stopAtErrors!==!0,l.fontExtraProperties=l.fontExtraProperties===!0,l.pdfBug=l.pdfBug===!0,l.enableXfa=l.enableXfa===!0,(!Number.isInteger(l.rangeChunkSize)||l.rangeChunkSize<1)&&(l.rangeChunkSize=DEFAULT_RANGE_CHUNK_SIZE),(typeof l.docBaseUrl!="string"||(0,_display_utils.isDataScheme)(l.docBaseUrl))&&(l.docBaseUrl=null),(!Number.isInteger(l.maxImageSize)||l.maxImageSize<-1)&&(l.maxImageSize=-1),typeof l.cMapUrl!="string"&&(l.cMapUrl=null),typeof l.standardFontDataUrl!="string"&&(l.standardFontDataUrl=null),typeof l.useWorkerFetch!="boolean"&&(l.useWorkerFetch=l.CMapReaderFactory===_display_utils.DOMCMapReaderFactory&&l.StandardFontDataFactory===_display_utils.DOMStandardFontDataFactory),typeof l.isEvalSupported!="boolean"&&(l.isEvalSupported=!0),typeof l.disableFontFace!="boolean"&&(l.disableFontFace=_is_node.isNodeJS),typeof l.useSystemFonts!="boolean"&&(l.useSystemFonts=!_is_node.isNodeJS&&!l.disableFontFace),(typeof l.ownerDocument!="object"||l.ownerDocument===null)&&(l.ownerDocument=globalThis.document),typeof l.disableRange!="boolean"&&(l.disableRange=!1),typeof l.disableStream!="boolean"&&(l.disableStream=!1),typeof l.disableAutoFetch!="boolean"&&(l.disableAutoFetch=!1),(0,_util.setVerbosityLevel)(l.verbosity),!w){let C={verbosity:l.verbosity,port:_worker_options.GlobalWorkerOptions.workerPort};w=C.port?PDFWorker.fromPort(C):new PDFWorker(C),g._worker=w}let A=g.docId;return w.promise.then(function(){if(g.destroyed)throw new Error("Loading aborted");let C=_fetchDocument(w,l,p,A),b=new Promise(function(E){let k;p?k=new _transport_stream.PDFDataTransportStream({length:l.length,initialData:l.initialData,progressiveDone:l.progressiveDone,contentDispositionFilename:l.contentDispositionFilename,disableRange:l.disableRange,disableStream:l.disableStream},p):l.data||(k=createPDFNetworkStream({url:l.url,length:l.length,httpHeaders:l.httpHeaders,withCredentials:l.withCredentials,rangeChunkSize:l.rangeChunkSize,disableRange:l.disableRange,disableStream:l.disableStream})),E(k)});return Promise.all([C,b]).then(function([E,k]){if(g.destroyed)throw new Error("Loading aborted");let P=new _message_handler.MessageHandler(A,E,w.port),N=new WorkerTransport(P,g,k,l);g._transport=N,P.send("Ready",null)})}).catch(g._capability.reject),g}async function _fetchDocument(v,g,h,l){if(v.destroyed)throw new Error("Worker was destroyed");h&&(g.length=h.length,g.initialData=h.initialData,g.progressiveDone=h.progressiveDone,g.contentDispositionFilename=h.contentDispositionFilename);let p=await v.messageHandler.sendWithPromise("GetDocRequest",{docId:l,apiVersion:"2.14.305",source:{data:g.data,url:g.url,password:g.password,disableAutoFetch:g.disableAutoFetch,rangeChunkSize:g.rangeChunkSize,length:g.length},maxImageSize:g.maxImageSize,disableFontFace:g.disableFontFace,docBaseUrl:g.docBaseUrl,ignoreErrors:g.ignoreErrors,isEvalSupported:g.isEvalSupported,fontExtraProperties:g.fontExtraProperties,enableXfa:g.enableXfa,useSystemFonts:g.useSystemFonts,cMapUrl:g.useWorkerFetch?g.cMapUrl:null,standardFontDataUrl:g.useWorkerFetch?g.standardFontDataUrl:null});if(v.destroyed)throw new Error("Worker was destroyed");return p}let e=class e{constructor(){this._capability=(0,_util.createPromiseCapability)(),this._transport=null,this._worker=null,this.docId=`d${Rb(e,r)._++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null,this.onUnsupportedFeature=null}get promise(){return this._capability.promise}async destroy(){var g;this.destroyed=!0,await((g=this._transport)==null?void 0:g.destroy()),this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}};r=new WeakMap,Er(e,r,0);let PDFDocumentLoadingTask=e;exports.PDFDocumentLoadingTask=PDFDocumentLoadingTask;class PDFDataRangeTransport{constructor(g,h,l=!1,p=null){this.length=g,this.initialData=h,this.progressiveDone=l,this.contentDispositionFilename=p,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=(0,_util.createPromiseCapability)()}addRangeListener(g){this._rangeListeners.push(g)}addProgressListener(g){this._progressListeners.push(g)}addProgressiveReadListener(g){this._progressiveReadListeners.push(g)}addProgressiveDoneListener(g){this._progressiveDoneListeners.push(g)}onDataRange(g,h){for(let l of this._rangeListeners)l(g,h)}onDataProgress(g,h){this._readyCapability.promise.then(()=>{for(let l of this._progressListeners)l(g,h)})}onDataProgressiveRead(g){this._readyCapability.promise.then(()=>{for(let h of this._progressiveReadListeners)h(g)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(let g of this._progressiveDoneListeners)g()})}transportReady(){this._readyCapability.resolve()}requestDataRange(g,h){(0,_util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}exports.PDFDataRangeTransport=PDFDataRangeTransport;class PDFDocumentProxy{constructor(g,h){this._pdfInfo=g,this._transport=h,Object.defineProperty(this,"fingerprint",{get(){return(0,_display_utils.deprecated)("`PDFDocumentProxy.fingerprint`, please use `PDFDocumentProxy.fingerprints` instead."),this.fingerprints[0]}}),Object.defineProperty(this,"getStats",{value:async()=>((0,_display_utils.deprecated)("`PDFDocumentProxy.getStats`, please use the `PDFDocumentProxy.stats`-getter instead."),this.stats||{streamTypes:{},fontTypes:{}})})}get annotationStorage(){return this._transport.annotationStorage}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get stats(){return this._transport.stats}get isPureXfa(){return!!this._transport._htmlForXfa}get allXfaHtml(){return this._transport._htmlForXfa}getPage(g){return this._transport.getPage(g)}getPageIndex(g){return this._transport.getPageIndex(g)}getDestinations(){return this._transport.getDestinations()}getDestination(g){return this._transport.getDestination(g)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJavaScript(){return this._transport.getJavaScript()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig(){return this._transport.getOptionalContentConfig()}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(g=!1){return this._transport.startCleanup(g||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}saveDocument(){return this._transport.annotationStorage.size<=0&&(0,_display_utils.deprecated)("saveDocument called while `annotationStorage` is empty, please use the getData-method instead."),this._transport.saveDocument()}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}exports.PDFDocumentProxy=PDFDocumentProxy;class PDFPageProxy{constructor(g,h,l,p,w=!1){this._pageIndex=g,this._pageInfo=h,this._ownerDocument=p,this._transport=l,this._stats=w?new _display_utils.StatTimer:null,this._pdfBug=w,this.commonObjs=l.commonObjs,this.objs=new PDFObjects,this._bitmaps=new Set,this.cleanupAfterRender=!1,this.pendingCleanup=!1,this._intentStates=new Map,this._annotationPromises=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:g,rotation:h=this.rotate,offsetX:l=0,offsetY:p=0,dontFlip:w=!1}={}){return new _display_utils.PageViewport({viewBox:this.view,scale:g,rotation:h,offsetX:l,offsetY:p,dontFlip:w})}getAnnotations({intent:g="display"}={}){let h=this._transport.getRenderingIntent(g),l=this._annotationPromises.get(h.cacheKey);return l||(l=this._transport.getAnnotations(this._pageIndex,h.renderingIntent),this._annotationPromises.set(h.cacheKey,l),l=l.then(p=>{for(let w of p)w.titleObj!==void 0&&Object.defineProperty(w,"title",{get(){return(0,_display_utils.deprecated)("`title`-property on annotation, please use `titleObj` instead."),w.titleObj.str}}),w.contentsObj!==void 0&&Object.defineProperty(w,"contents",{get(){return(0,_display_utils.deprecated)("`contents`-property on annotation, please use `contentsObj` instead."),w.contentsObj.str}});return p})),l}getJSActions(){return this._jsActionsPromise||=this._transport.getPageJSActions(this._pageIndex)}async getXfa(){var g;return((g=this._transport._htmlForXfa)==null?void 0:g.children[this._pageIndex])||null}render({canvasContext:g,viewport:h,intent:l="display",annotationMode:p=_util.AnnotationMode.ENABLE,transform:w=null,imageLayer:A=null,canvasFactory:C=null,background:b=null,optionalContentConfigPromise:E=null,annotationCanvasMap:k=null,pageColors:P=null}){var Y,X;((Y=arguments[0])==null?void 0:Y.renderInteractiveForms)!==void 0&&((0,_display_utils.deprecated)("render no longer accepts the `renderInteractiveForms`-option, please use the `annotationMode`-option instead."),arguments[0].renderInteractiveForms===!0&&p===_util.AnnotationMode.ENABLE&&(p=_util.AnnotationMode.ENABLE_FORMS)),((X=arguments[0])==null?void 0:X.includeAnnotationStorage)!==void 0&&((0,_display_utils.deprecated)("render no longer accepts the `includeAnnotationStorage`-option, please use the `annotationMode`-option instead."),arguments[0].includeAnnotationStorage===!0&&p===_util.AnnotationMode.ENABLE&&(p=_util.AnnotationMode.ENABLE_STORAGE)),this._stats&&this._stats.time("Overall");let N=this._transport.getRenderingIntent(l,p);this.pendingCleanup=!1,E||(E=this._transport.getOptionalContentConfig());let D=this._intentStates.get(N.cacheKey);D||(D=Object.create(null),this._intentStates.set(N.cacheKey,D)),D.streamReaderCancelTimeout&&(clearTimeout(D.streamReaderCancelTimeout),D.streamReaderCancelTimeout=null);let F=C||new DefaultCanvasFactory({ownerDocument:this._ownerDocument}),B=!!(N.renderingIntent&_util.RenderingIntentFlag.PRINT);D.displayReadyCapability||(D.displayReadyCapability=(0,_util.createPromiseCapability)(),D.operatorList={fnArray:[],argsArray:[],lastChunk:!1},this._stats&&this._stats.time("Page Request"),this._pumpOperatorList(N));let V=Q=>{D.renderTasks.delete(q),(this.cleanupAfterRender||B)&&(this.pendingCleanup=!0),this._tryCleanup(),Q?(q.capability.reject(Q),this._abortOperatorList({intentState:D,reason:Q instanceof Error?Q:new Error(Q)})):q.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"))},q=new InternalRenderTask({callback:V,params:{canvasContext:g,viewport:h,transform:w,imageLayer:A,background:b},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:k,operatorList:D.operatorList,pageIndex:this._pageIndex,canvasFactory:F,useRequestAnimationFrame:!B,pdfBug:this._pdfBug,pageColors:P});(D.renderTasks||=new Set).add(q);let G=q.task;return Promise.all([D.displayReadyCapability.promise,E]).then(([Q,le])=>{if(this.pendingCleanup){V();return}this._stats&&this._stats.time("Rendering"),q.initializeGraphics({transparency:Q,optionalContentConfig:le}),q.operatorListChanged()}).catch(V),G}getOperatorList({intent:g="display",annotationMode:h=_util.AnnotationMode.ENABLE}={}){function l(){w.operatorList.lastChunk&&(w.opListReadCapability.resolve(w.operatorList),w.renderTasks.delete(A))}let p=this._transport.getRenderingIntent(g,h,!0),w=this._intentStates.get(p.cacheKey);w||(w=Object.create(null),this._intentStates.set(p.cacheKey,w));let A;return w.opListReadCapability||(A=Object.create(null),A.operatorListChanged=l,w.opListReadCapability=(0,_util.createPromiseCapability)(),(w.renderTasks||=new Set).add(A),w.operatorList={fnArray:[],argsArray:[],lastChunk:!1},this._stats&&this._stats.time("Page Request"),this._pumpOperatorList(p)),w.opListReadCapability.promise}streamTextContent({disableCombineTextItems:g=!1,includeMarkedContent:h=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,combineTextItems:g!==!0,includeMarkedContent:h===!0},{highWaterMark:100,size(p){return p.items.length}})}getTextContent(g={}){if(this._transport._htmlForXfa)return this.getXfa().then(l=>_xfa_text.XfaText.textContent(l));let h=this.streamTextContent(g);return new Promise(function(l,p){function w(){A.read().then(function({value:b,done:E}){if(E){l(C);return}Object.assign(C.styles,b.styles),C.items.push(...b.items),w()},p)}let A=h.getReader(),C={items:[],styles:Object.create(null)};w()})}getStructTree(){return this._structTreePromise||=this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let g=[];for(let h of this._intentStates.values())if(this._abortOperatorList({intentState:h,reason:new Error("Page was destroyed."),force:!0}),!h.opListReadCapability)for(let l of h.renderTasks)g.push(l.completed),l.cancel();this.objs.clear();for(let h of this._bitmaps)h.close();return this._bitmaps.clear(),this._annotationPromises.clear(),this._jsActionsPromise=null,this._structTreePromise=null,this.pendingCleanup=!1,Promise.all(g)}cleanup(g=!1){return this.pendingCleanup=!0,this._tryCleanup(g)}_tryCleanup(g=!1){if(!this.pendingCleanup)return!1;for(let{renderTasks:h,operatorList:l}of this._intentStates.values())if(h.size>0||!l.lastChunk)return!1;this._intentStates.clear(),this.objs.clear(),this._annotationPromises.clear(),this._jsActionsPromise=null,this._structTreePromise=null,g&&this._stats&&(this._stats=new _display_utils.StatTimer);for(let h of this._bitmaps)h.close();return this._bitmaps.clear(),this.pendingCleanup=!1,!0}_startRenderPage(g,h){let l=this._intentStates.get(h);l&&(this._stats&&this._stats.timeEnd("Page Request"),l.displayReadyCapability&&l.displayReadyCapability.resolve(g))}_renderPageChunk(g,h){for(let l=0,p=g.length;l<p;l++)h.operatorList.fnArray.push(g.fnArray[l]),h.operatorList.argsArray.push(g.argsArray[l]);h.operatorList.lastChunk=g.lastChunk;for(let l of h.renderTasks)l.operatorListChanged();g.lastChunk&&this._tryCleanup()}_pumpOperatorList({renderingIntent:g,cacheKey:h}){let p=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:g,cacheKey:h,annotationStorage:g&_util.RenderingIntentFlag.ANNOTATIONS_STORAGE?this._transport.annotationStorage.serializable:null}).getReader(),w=this._intentStates.get(h);w.streamReader=p;let A=()=>{p.read().then(({value:C,done:b})=>{if(b){w.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(C,w),A())},C=>{if(w.streamReader=null,!this._transport.destroyed){if(w.operatorList){w.operatorList.lastChunk=!0;for(let b of w.renderTasks)b.operatorListChanged();this._tryCleanup()}if(w.displayReadyCapability)w.displayReadyCapability.reject(C);else if(w.opListReadCapability)w.opListReadCapability.reject(C);else throw C}})};A()}_abortOperatorList({intentState:g,reason:h,force:l=!1}){if(g.streamReader){if(!l){if(g.renderTasks.size>0)return;if(h instanceof _display_utils.RenderingCancelledException){g.streamReaderCancelTimeout=setTimeout(()=>{this._abortOperatorList({intentState:g,reason:h,force:!0}),g.streamReaderCancelTimeout=null},RENDERING_CANCELLED_TIMEOUT);return}}if(g.streamReader.cancel(new _util.AbortException(h.message)).catch(()=>{}),g.streamReader=null,!this._transport.destroyed){for(let[p,w]of this._intentStates)if(w===g){this._intentStates.delete(p);break}this.cleanup()}}}get stats(){return this._stats}}exports.PDFPageProxy=PDFPageProxy;class LoopbackPort{constructor(){this._listeners=[],this._deferred=Promise.resolve()}postMessage(g,h){let l={data:structuredClone(g,h)};this._deferred.then(()=>{for(let p of this._listeners)p.call(this,l)})}addEventListener(g,h){this._listeners.push(h)}removeEventListener(g,h){let l=this._listeners.indexOf(h);this._listeners.splice(l,1)}terminate(){this._listeners.length=0}}exports.LoopbackPort=LoopbackPort;let PDFWorkerUtil={isWorkerDisabled:!1,fallbackWorkerSrc:null,fakeWorkerId:0};exports.PDFWorkerUtil=PDFWorkerUtil;{if(_is_node.isNodeJS&&typeof Eu=="function")PDFWorkerUtil.isWorkerDisabled=!0,PDFWorkerUtil.fallbackWorkerSrc="./pdf.worker.js";else if(typeof document=="object"){let v=(t=document==null?void 0:document.currentScript)==null?void 0:t.src;v&&(PDFWorkerUtil.fallbackWorkerSrc=v.replace(/(\.(?:min\.)?js)(\?.*)?$/i,".worker$1$2"))}PDFWorkerUtil.isSameOrigin=function(v,g){let h;try{if(h=new URL(v),!h.origin||h.origin==="null")return!1}catch{return!1}let l=new URL(g,h);return h.origin===l.origin},PDFWorkerUtil.createCDNWrapper=function(v){let g=`importScripts("${v}");`;return URL.createObjectURL(new Blob([g]))}}let _PDFWorker=class _PDFWorker{constructor({name:v=null,port:g=null,verbosity:h=(0,_util.getVerbosityLevel)()}={}){if(g&&Lt(_PDFWorker,n).has(g))throw new Error("Cannot use more than one PDFWorker per port.");if(this.name=v,this.destroyed=!1,this.verbosity=h,this._readyCapability=(0,_util.createPromiseCapability)(),this._port=null,this._webWorker=null,this._messageHandler=null,g){Lt(_PDFWorker,n).set(g,this),this._initializeFromPort(g);return}this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(v){this._port=v,this._messageHandler=new _message_handler.MessageHandler("main","worker",v),this._messageHandler.on("ready",function(){}),this._readyCapability.resolve()}_initialize(){if(typeof Worker<"u"&&!PDFWorkerUtil.isWorkerDisabled&&!_PDFWorker._mainThreadWorkerMessageHandler){let v=_PDFWorker.workerSrc;try{PDFWorkerUtil.isSameOrigin(window.location.href,v)||(v=PDFWorkerUtil.createCDNWrapper(new URL(v,window.location).href));let g=new Worker(v),h=new _message_handler.MessageHandler("main","worker",g),l=()=>{g.removeEventListener("error",p),h.destroy(),g.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},p=()=>{this._webWorker||l()};g.addEventListener("error",p),h.on("test",A=>{if(g.removeEventListener("error",p),this.destroyed){l();return}A?(this._messageHandler=h,this._port=g,this._webWorker=g,this._readyCapability.resolve(),h.send("configure",{verbosity:this.verbosity})):(this._setupFakeWorker(),h.destroy(),g.terminate())}),h.on("ready",A=>{if(g.removeEventListener("error",p),this.destroyed){l();return}try{w()}catch{this._setupFakeWorker()}});let w=()=>{let A=new Uint8Array;h.send("test",A,[A.buffer])};w();return}catch{(0,_util.info)("The worker has been disabled.")}}this._setupFakeWorker()}_setupFakeWorker(){PDFWorkerUtil.isWorkerDisabled||((0,_util.warn)("Setting up fake worker."),PDFWorkerUtil.isWorkerDisabled=!0),_PDFWorker._setupFakeWorkerGlobal.then(v=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}let g=new LoopbackPort;this._port=g;let h=`fake${PDFWorkerUtil.fakeWorkerId++}`,l=new _message_handler.MessageHandler(h+"_worker",h,g);v.setup(l,g);let p=new _message_handler.MessageHandler(h,h+"_worker",g);this._messageHandler=p,this._readyCapability.resolve(),p.send("configure",{verbosity:this.verbosity})}).catch(v=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${v.message}".`))})}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),Lt(_PDFWorker,n).delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(v){if(!(v!=null&&v.port))throw new Error("PDFWorker.fromPort - invalid method signature.");return Lt(this,n).has(v.port)?Lt(this,n).get(v.port):new _PDFWorker(v)}static get workerSrc(){if(_worker_options.GlobalWorkerOptions.workerSrc)return _worker_options.GlobalWorkerOptions.workerSrc;if(PDFWorkerUtil.fallbackWorkerSrc!==null)return _is_node.isNodeJS||(0,_display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.'),PDFWorkerUtil.fallbackWorkerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _mainThreadWorkerMessageHandler(){var v;try{return((v=globalThis.pdfjsWorker)==null?void 0:v.WorkerMessageHandler)||null}catch{return null}}static get _setupFakeWorkerGlobal(){let loader=async()=>{let mainWorkerMessageHandler=this._mainThreadWorkerMessageHandler;if(mainWorkerMessageHandler)return mainWorkerMessageHandler;if(_is_node.isNodeJS&&typeof Eu=="function"){let worker=eval("require")(this.workerSrc);return worker.WorkerMessageHandler}return await(0,_display_utils.loadScript)(this.workerSrc),window.pdfjsWorker.WorkerMessageHandler};return(0,_util.shadow)(this,"_setupFakeWorkerGlobal",loader())}};n=new WeakMap,Er(_PDFWorker,n,new WeakMap);let PDFWorker=_PDFWorker;exports.PDFWorker=PDFWorker,PDFWorker.getWorkerSrc=function(){return(0,_display_utils.deprecated)("`PDFWorker.getWorkerSrc()`, please use `PDFWorker.workerSrc` instead."),this.workerSrc};class WorkerTransport{constructor(g,h,l,p){Er(this,i,null);Er(this,o,new Map);Er(this,s,new Map);Er(this,c,null);this.messageHandler=g,this.loadingTask=h,this.commonObjs=new PDFObjects,this.fontLoader=new _font_loader.FontLoader({docId:h.docId,onUnsupportedFeature:this._onUnsupportedFeature.bind(this),ownerDocument:p.ownerDocument,styleElement:p.styleElement}),this._params=p,p.useWorkerFetch||(this.CMapReaderFactory=new p.CMapReaderFactory({baseUrl:p.cMapUrl,isCompressed:p.cMapPacked}),this.StandardFontDataFactory=new p.StandardFontDataFactory({baseUrl:p.standardFontDataUrl})),this.destroyed=!1,this.destroyCapability=null,this._passwordCapability=null,this._networkStream=l,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=(0,_util.createPromiseCapability)(),this.setupMessageHandler()}get annotationStorage(){return(0,_util.shadow)(this,"annotationStorage",new _annotation_storage.AnnotationStorage)}get stats(){return Lt(this,i)}getRenderingIntent(g,h=_util.AnnotationMode.ENABLE,l=!1){let p=_util.RenderingIntentFlag.DISPLAY,w="";switch(g){case"any":p=_util.RenderingIntentFlag.ANY;break;case"display":break;case"print":p=_util.RenderingIntentFlag.PRINT;break;default:(0,_util.warn)(`getRenderingIntent - invalid intent: ${g}`)}switch(h){case _util.AnnotationMode.DISABLE:p+=_util.RenderingIntentFlag.ANNOTATIONS_DISABLE;break;case _util.AnnotationMode.ENABLE:break;case _util.AnnotationMode.ENABLE_FORMS:p+=_util.RenderingIntentFlag.ANNOTATIONS_FORMS;break;case _util.AnnotationMode.ENABLE_STORAGE:p+=_util.RenderingIntentFlag.ANNOTATIONS_STORAGE,w=this.annotationStorage.hash;break;default:(0,_util.warn)(`getRenderingIntent - invalid annotationMode: ${h}`)}return l&&(p+=_util.RenderingIntentFlag.OPLIST),{renderingIntent:p,cacheKey:`${p}_${w}`}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=(0,_util.createPromiseCapability)(),this._passwordCapability&&this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));let g=[];for(let l of Lt(this,o).values())g.push(l._destroy());Lt(this,o).clear(),Lt(this,s).clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();let h=this.messageHandler.sendWithPromise("Terminate",null);return g.push(h),Promise.all(g).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),Zi(this,c,null),this._getFieldObjectsPromise=null,this._hasJSActionsPromise=null,this._networkStream&&this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:g,loadingTask:h}=this;g.on("GetReader",(l,p)=>{(0,_util.assert)(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=w=>{this._lastProgress={loaded:w.loaded,total:w.total}},p.onPull=()=>{this._fullReader.read().then(function({value:w,done:A}){if(A){p.close();return}(0,_util.assert)((0,_util.isArrayBuffer)(w),"GetReader - expected an ArrayBuffer."),p.enqueue(new Uint8Array(w),1,[w])}).catch(w=>{p.error(w)})},p.onCancel=w=>{this._fullReader.cancel(w),p.ready.catch(A=>{if(!this.destroyed)throw A})}}),g.on("ReaderHeadersReady",l=>{let p=(0,_util.createPromiseCapability)(),w=this._fullReader;return w.headersReady.then(()=>{var A;(!w.isStreamingSupported||!w.isRangeSupported)&&(this._lastProgress&&((A=h.onProgress)==null||A.call(h,this._lastProgress)),w.onProgress=C=>{var b;(b=h.onProgress)==null||b.call(h,{loaded:C.loaded,total:C.total})}),p.resolve({isStreamingSupported:w.isStreamingSupported,isRangeSupported:w.isRangeSupported,contentLength:w.contentLength})},p.reject),p.promise}),g.on("GetRangeReader",(l,p)=>{(0,_util.assert)(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");let w=this._networkStream.getRangeReader(l.begin,l.end);if(!w){p.close();return}p.onPull=()=>{w.read().then(function({value:A,done:C}){if(C){p.close();return}(0,_util.assert)((0,_util.isArrayBuffer)(A),"GetRangeReader - expected an ArrayBuffer."),p.enqueue(new Uint8Array(A),1,[A])}).catch(A=>{p.error(A)})},p.onCancel=A=>{w.cancel(A),p.ready.catch(C=>{if(!this.destroyed)throw C})}}),g.on("GetDoc",({pdfInfo:l})=>{this._numPages=l.numPages,this._htmlForXfa=l.htmlForXfa,delete l.htmlForXfa,h._capability.resolve(new PDFDocumentProxy(l,this))}),g.on("DocException",function(l){let p;switch(l.name){case"PasswordException":p=new _util.PasswordException(l.message,l.code);break;case"InvalidPDFException":p=new _util.InvalidPDFException(l.message);break;case"MissingPDFException":p=new _util.MissingPDFException(l.message);break;case"UnexpectedResponseException":p=new _util.UnexpectedResponseException(l.message,l.status);break;case"UnknownErrorException":p=new _util.UnknownErrorException(l.message,l.details);break;default:(0,_util.unreachable)("DocException - expected a valid Error.")}h._capability.reject(p)}),g.on("PasswordRequest",l=>{if(this._passwordCapability=(0,_util.createPromiseCapability)(),h.onPassword){let p=w=>{w instanceof Error?this._passwordCapability.reject(w):this._passwordCapability.resolve({password:w})};try{h.onPassword(p,l.code)}catch(w){this._passwordCapability.reject(w)}}else this._passwordCapability.reject(new _util.PasswordException(l.message,l.code));return this._passwordCapability.promise}),g.on("DataLoaded",l=>{var p;(p=h.onProgress)==null||p.call(h,{loaded:l.length,total:l.length}),this.downloadInfoCapability.resolve(l)}),g.on("StartRenderPage",l=>{if(this.destroyed)return;Lt(this,o).get(l.pageIndex)._startRenderPage(l.transparency,l.cacheKey)}),g.on("commonobj",([l,p,w])=>{var A;if(!this.destroyed&&!this.commonObjs.has(l))switch(p){case"Font":let C=this._params;if("error"in w){let k=w.error;(0,_util.warn)(`Error during font loading: ${k}`),this.commonObjs.resolve(l,k);break}let b=null;C.pdfBug&&((A=globalThis.FontInspector)!=null&&A.enabled)&&(b={registerFont(k,P){globalThis.FontInspector.fontAdded(k,P)}});let E=new _font_loader.FontFaceObject(w,{isEvalSupported:C.isEvalSupported,disableFontFace:C.disableFontFace,ignoreErrors:C.ignoreErrors,onUnsupportedFeature:this._onUnsupportedFeature.bind(this),fontRegistry:b});this.fontLoader.bind(E).catch(k=>g.sendWithPromise("FontFallback",{id:l})).finally(()=>{!C.fontExtraProperties&&E.data&&(E.data=null),this.commonObjs.resolve(l,E)});break;case"FontPath":case"Image":this.commonObjs.resolve(l,w);break;default:throw new Error(`Got unknown common object type ${p}`)}}),g.on("obj",([l,p,w,A])=>{var b;if(this.destroyed)return;let C=Lt(this,o).get(p);if(!C.objs.has(l))switch(w){case"Image":C.objs.resolve(l,A);let E=8e6;if(A){let k;if(A.bitmap){let{bitmap:P,width:N,height:D}=A;k=N*D*4,C._bitmaps.add(P)}else k=((b=A.data)==null?void 0:b.length)||0;k>E&&(C.cleanupAfterRender=!0)}break;case"Pattern":C.objs.resolve(l,A);break;default:throw new Error(`Got unknown object type ${w}`)}}),g.on("DocProgress",l=>{var p;this.destroyed||(p=h.onProgress)==null||p.call(h,{loaded:l.loaded,total:l.total})}),g.on("DocStats",l=>{this.destroyed||Zi(this,i,Object.freeze({streamTypes:Object.freeze(l.streamTypes),fontTypes:Object.freeze(l.fontTypes)}))}),g.on("UnsupportedFeature",this._onUnsupportedFeature.bind(this)),g.on("FetchBuiltInCMap",l=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.CMapReaderFactory?this.CMapReaderFactory.fetch(l):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."))),g.on("FetchStandardFontData",l=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.StandardFontDataFactory?this.StandardFontDataFactory.fetch(l):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.")))}_onUnsupportedFeature({featureId:g}){var h,l;this.destroyed||(l=(h=this.loadingTask).onUnsupportedFeature)==null||l.call(h,g)}getData(){return this.messageHandler.sendWithPromise("GetData",null)}getPage(g){if(!Number.isInteger(g)||g<=0||g>this._numPages)return Promise.reject(new Error("Invalid page request."));let h=g-1,l=Lt(this,s).get(h);if(l)return l;let p=this.messageHandler.sendWithPromise("GetPage",{pageIndex:h}).then(w=>{if(this.destroyed)throw new Error("Transport destroyed");let A=new PDFPageProxy(h,w,this,this._params.ownerDocument,this._params.pdfBug);return Lt(this,o).set(h,A),A});return Lt(this,s).set(h,p),p}getPageIndex(g){return typeof g!="object"||g===null||!Number.isInteger(g.num)||g.num<0||!Number.isInteger(g.gen)||g.gen<0?Promise.reject(new Error("Invalid pageIndex request.")):this.messageHandler.sendWithPromise("GetPageIndex",{num:g.num,gen:g.gen})}getAnnotations(g,h){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:g,intent:h})}saveDocument(){var g;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:this.annotationStorage.serializable,filename:((g=this._fullReader)==null?void 0:g.filename)??null}).finally(()=>{this.annotationStorage.resetModified()})}getFieldObjects(){return this._getFieldObjectsPromise||=this.messageHandler.sendWithPromise("GetFieldObjects",null)}hasJSActions(){return this._hasJSActionsPromise||=this.messageHandler.sendWithPromise("HasJSActions",null)}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(g){return typeof g!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:g})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getJavaScript(){return this.messageHandler.sendWithPromise("GetJavaScript",null)}getDocJSActions(){return this.messageHandler.sendWithPromise("GetDocJSActions",null)}getPageJSActions(g){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:g})}getStructTree(g){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:g})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(){return this.messageHandler.sendWithPromise("GetOptionalContentConfig",null).then(g=>new _optional_content_config.OptionalContentConfig(g))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){return Lt(this,c)||Zi(this,c,this.messageHandler.sendWithPromise("GetMetadata",null).then(g=>{var h,l;return{info:g[0],metadata:g[1]?new _metadata.Metadata(g[1]):null,contentDispositionFilename:((h=this._fullReader)==null?void 0:h.filename)??null,contentLength:((l=this._fullReader)==null?void 0:l.contentLength)??null}}))}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(g=!1){if(await this.messageHandler.sendWithPromise("Cleanup",null),!this.destroyed){for(let h of Lt(this,o).values())if(!h.cleanup())throw new Error(`startCleanup: Page ${h.pageNumber} is currently rendering.`);this.commonObjs.clear(),g||this.fontLoader.clear(),Zi(this,c,null),this._getFieldObjectsPromise=null,this._hasJSActionsPromise=null}}get loadingParams(){let g=this._params;return(0,_util.shadow)(this,"loadingParams",{disableAutoFetch:g.disableAutoFetch,enableXfa:g.enableXfa})}}i=new WeakMap,o=new WeakMap,s=new WeakMap,c=new WeakMap;class PDFObjects{constructor(){Er(this,u);Er(this,f,Object.create(null))}get(g,h=null){if(h){let p=eo(this,u,rm).call(this,g);return p.capability.promise.then(()=>h(p.data)),null}let l=Lt(this,f)[g];if(!(l!=null&&l.capability.settled))throw new Error(`Requesting object that isn't resolved yet ${g}.`);return l.data}has(g){let h=Lt(this,f)[g];return(h==null?void 0:h.capability.settled)||!1}resolve(g,h=null){let l=eo(this,u,rm).call(this,g);l.data=h,l.capability.resolve()}clear(){Zi(this,f,Object.create(null))}}f=new WeakMap,u=new WeakSet,rm=function(g){let h=Lt(this,f)[g];return h||(Lt(this,f)[g]={capability:(0,_util.createPromiseCapability)(),data:null})};class RenderTask{constructor(g){this._internalRenderTask=g,this.onContinue=null}get promise(){return this._internalRenderTask.capability.promise}cancel(){this._internalRenderTask.cancel()}}exports.RenderTask=RenderTask;let _=class _{constructor({callback:g,params:h,objs:l,commonObjs:p,annotationCanvasMap:w,operatorList:A,pageIndex:C,canvasFactory:b,useRequestAnimationFrame:E=!1,pdfBug:k=!1,pageColors:P=null}){this.callback=g,this.params=h,this.objs=l,this.commonObjs=p,this.annotationCanvasMap=w,this.operatorListIdx=null,this.operatorList=A,this._pageIndex=C,this.canvasFactory=b,this._pdfBug=k,this.pageColors=P,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=E===!0&&typeof window<"u",this.cancelled=!1,this.capability=(0,_util.createPromiseCapability)(),this.task=new RenderTask(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=h.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:g=!1,optionalContentConfig:h}){var b;if(this.cancelled)return;if(this._canvas){if(Lt(_,m).has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");Lt(_,m).add(this._canvas)}this._pdfBug&&((b=globalThis.StepperManager)!=null&&b.enabled)&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());let{canvasContext:l,viewport:p,transform:w,imageLayer:A,background:C}=this.params;this.gfx=new _canvas.CanvasGraphics(l,this.commonObjs,this.objs,this.canvasFactory,A,h,this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:w,viewport:p,transparency:g,background:C}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback&&this.graphicsReadyCallback()}cancel(g=null){this.running=!1,this.cancelled=!0,this.gfx&&this.gfx.endDrawing(),this._canvas&&Lt(_,m).delete(this._canvas),this.callback(g||new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,"canvas"))}operatorListChanged(){if(!this.graphicsReady){this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound);return}this.stepper&&this.stepper.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?window.requestAnimationFrame(()=>{this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),this._canvas&&Lt(_,m).delete(this._canvas),this.callback())))}};m=new WeakMap,Er(_,m,new WeakSet);let InternalRenderTask=_,version="2.14.305";exports.version=version;let build="eaaa8b4ad";exports.build=build},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.StatTimer=e.RenderingCancelledException=e.PixelsPerInch=e.PageViewport=e.PDFDateString=e.DOMStandardFontDataFactory=e.DOMSVGFactory=e.DOMCanvasFactory=e.DOMCMapReaderFactory=void 0,e.deprecated=b,e.getFilenameFromUrl=l,e.getPdfFilenameFromUrl=p,e.getXfaPageViewport=P,e.isDataScheme=g,e.isPdfFile=h,e.isValidFetchUrl=A,e.loadScript=C;var n=t(6),i=t(1);let o="http://www.w3.org/2000/svg",N=class N{};Ic(N,"CSS",96),Ic(N,"PDF",72),Ic(N,"PDF_TO_CSS_UNITS",N.CSS/N.PDF);let s=N;e.PixelsPerInch=s;class c extends n.BaseCanvasFactory{constructor({ownerDocument:F=globalThis.document}={}){super(),this._document=F}_createCanvas(F,B){let V=this._document.createElement("canvas");return V.width=F,V.height=B,V}}e.DOMCanvasFactory=c;async function f(D,F=!1){if(A(D,document.baseURI)){let B=await fetch(D);if(!B.ok)throw new Error(B.statusText);return F?new Uint8Array(await B.arrayBuffer()):(0,i.stringToBytes)(await B.text())}return new Promise((B,V)=>{let q=new XMLHttpRequest;q.open("GET",D,!0),F&&(q.responseType="arraybuffer"),q.onreadystatechange=()=>{if(q.readyState===XMLHttpRequest.DONE){if(q.status===200||q.status===0){let G;if(F&&q.response?G=new Uint8Array(q.response):!F&&q.responseText&&(G=(0,i.stringToBytes)(q.responseText)),G){B(G);return}}V(new Error(q.statusText))}},q.send(null)})}class u extends n.BaseCMapReaderFactory{_fetchData(F,B){return f(F,this.isCompressed).then(V=>({cMapData:V,compressionType:B}))}}e.DOMCMapReaderFactory=u;class y extends n.BaseStandardFontDataFactory{_fetchData(F){return f(F,!0)}}e.DOMStandardFontDataFactory=y;class m extends n.BaseSVGFactory{_createSVG(F){return document.createElementNS(o,F)}}e.DOMSVGFactory=m;class _{constructor({viewBox:F,scale:B,rotation:V,offsetX:q=0,offsetY:G=0,dontFlip:Y=!1}){this.viewBox=F,this.scale=B,this.rotation=V,this.offsetX=q,this.offsetY=G;let X=(F[2]+F[0])/2,Q=(F[3]+F[1])/2,le,ve,ce,W;switch(V%=360,V<0&&(V+=360),V){case 180:le=-1,ve=0,ce=0,W=1;break;case 90:le=0,ve=1,ce=1,W=0;break;case 270:le=0,ve=-1,ce=-1,W=0;break;case 0:le=1,ve=0,ce=0,W=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}Y&&(ce=-ce,W=-W);let H,R,x,T;le===0?(H=Math.abs(Q-F[1])*B+q,R=Math.abs(X-F[0])*B+G,x=Math.abs(F[3]-F[1])*B,T=Math.abs(F[2]-F[0])*B):(H=Math.abs(X-F[0])*B+q,R=Math.abs(Q-F[1])*B+G,x=Math.abs(F[2]-F[0])*B,T=Math.abs(F[3]-F[1])*B),this.transform=[le*B,ve*B,ce*B,W*B,H-le*B*X-ce*B*Q,R-ve*B*X-W*B*Q],this.width=x,this.height=T}clone({scale:F=this.scale,rotation:B=this.rotation,offsetX:V=this.offsetX,offsetY:q=this.offsetY,dontFlip:G=!1}={}){return new _({viewBox:this.viewBox.slice(),scale:F,rotation:B,offsetX:V,offsetY:q,dontFlip:G})}convertToViewportPoint(F,B){return i.Util.applyTransform([F,B],this.transform)}convertToViewportRectangle(F){let B=i.Util.applyTransform([F[0],F[1]],this.transform),V=i.Util.applyTransform([F[2],F[3]],this.transform);return[B[0],B[1],V[0],V[1]]}convertToPdfPoint(F,B){return i.Util.applyInverseTransform([F,B],this.transform)}}e.PageViewport=_;class v extends i.BaseException{constructor(F,B){super(F,"RenderingCancelledException"),this.type=B}}e.RenderingCancelledException=v;function g(D){let F=D.length,B=0;for(;B<F&&D[B].trim()==="";)B++;return D.substring(B,B+5).toLowerCase()==="data:"}function h(D){return typeof D=="string"&&/\.pdf$/i.test(D)}function l(D){let F=D.indexOf("#"),B=D.indexOf("?"),V=Math.min(F>0?F:D.length,B>0?B:D.length);return D.substring(D.lastIndexOf("/",V)+1,V)}function p(D,F="document.pdf"){if(typeof D!="string")return F;if(g(D))return(0,i.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),F;let B=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,V=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,q=B.exec(D),G=V.exec(q[1])||V.exec(q[2])||V.exec(q[3]);if(G&&(G=G[0],G.includes("%")))try{G=V.exec(decodeURIComponent(G))[0]}catch{}return G||F}class w{constructor(){this.started=Object.create(null),this.times=[]}time(F){F in this.started&&(0,i.warn)(`Timer is already running for ${F}`),this.started[F]=Date.now()}timeEnd(F){F in this.started||(0,i.warn)(`Timer has not been started for ${F}`),this.times.push({name:F,start:this.started[F],end:Date.now()}),delete this.started[F]}toString(){let F=[],B=0;for(let V of this.times){let q=V.name;q.length>B&&(B=q.length)}for(let V of this.times){let q=V.end-V.start;F.push(`${V.name.padEnd(B)} ${q}ms
|
|
71
71
|
`)}return F.join("")}}e.StatTimer=w;function A(D,F){try{let{protocol:B}=F?new URL(D,F):new URL(D);return B==="http:"||B==="https:"}catch{return!1}}function C(D,F=!1){return new Promise((B,V)=>{let q=document.createElement("script");q.src=D,q.onload=function(G){F&&q.remove(),B(G)},q.onerror=function(){V(new Error(`Cannot load script at: ${q.src}`))},(document.head||document.documentElement).appendChild(q)})}function b(D){console.log("Deprecated API usage: "+D)}let E;class k{static toDateObject(F){if(!F||typeof F!="string")return null;E||(E=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"));let B=E.exec(F);if(!B)return null;let V=parseInt(B[1],10),q=parseInt(B[2],10);q=q>=1&&q<=12?q-1:0;let G=parseInt(B[3],10);G=G>=1&&G<=31?G:1;let Y=parseInt(B[4],10);Y=Y>=0&&Y<=23?Y:0;let X=parseInt(B[5],10);X=X>=0&&X<=59?X:0;let Q=parseInt(B[6],10);Q=Q>=0&&Q<=59?Q:0;let le=B[7]||"Z",ve=parseInt(B[8],10);ve=ve>=0&&ve<=23?ve:0;let ce=parseInt(B[9],10)||0;return ce=ce>=0&&ce<=59?ce:0,le==="-"?(Y+=ve,X+=ce):le==="+"&&(Y-=ve,X-=ce),new Date(Date.UTC(V,q,G,Y,X,Q))}}e.PDFDateString=k;function P(D,{scale:F=1,rotation:B=0}){let{width:V,height:q}=D.attributes.style,G=[0,0,parseInt(V),parseInt(q)];return new _({viewBox:G,scale:F,rotation:B})}},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BaseStandardFontDataFactory=e.BaseSVGFactory=e.BaseCanvasFactory=e.BaseCMapReaderFactory=void 0;var n=t(1);class i{constructor(){this.constructor===i&&(0,n.unreachable)("Cannot initialize BaseCanvasFactory.")}create(u,y){if(u<=0||y<=0)throw new Error("Invalid canvas size");let m=this._createCanvas(u,y);return{canvas:m,context:m.getContext("2d")}}reset(u,y,m){if(!u.canvas)throw new Error("Canvas is not specified");if(y<=0||m<=0)throw new Error("Invalid canvas size");u.canvas.width=y,u.canvas.height=m}destroy(u){if(!u.canvas)throw new Error("Canvas is not specified");u.canvas.width=0,u.canvas.height=0,u.canvas=null,u.context=null}_createCanvas(u,y){(0,n.unreachable)("Abstract method `_createCanvas` called.")}}e.BaseCanvasFactory=i;class o{constructor({baseUrl:u=null,isCompressed:y=!1}){this.constructor===o&&(0,n.unreachable)("Cannot initialize BaseCMapReaderFactory."),this.baseUrl=u,this.isCompressed=y}async fetch({name:u}){if(!this.baseUrl)throw new Error('The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.');if(!u)throw new Error("CMap name must be specified.");let y=this.baseUrl+u+(this.isCompressed?".bcmap":""),m=this.isCompressed?n.CMapCompressionType.BINARY:n.CMapCompressionType.NONE;return this._fetchData(y,m).catch(_=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${y}`)})}_fetchData(u,y){(0,n.unreachable)("Abstract method `_fetchData` called.")}}e.BaseCMapReaderFactory=o;class s{constructor({baseUrl:u=null}){this.constructor===s&&(0,n.unreachable)("Cannot initialize BaseStandardFontDataFactory."),this.baseUrl=u}async fetch({filename:u}){if(!this.baseUrl)throw new Error('The standard font "baseUrl" parameter must be specified, ensure that the "standardFontDataUrl" API parameter is provided.');if(!u)throw new Error("Font filename must be specified.");let y=`${this.baseUrl}${u}`;return this._fetchData(y).catch(m=>{throw new Error(`Unable to load font data at: ${y}`)})}_fetchData(u){(0,n.unreachable)("Abstract method `_fetchData` called.")}}e.BaseStandardFontDataFactory=s;class c{constructor(){this.constructor===c&&(0,n.unreachable)("Cannot initialize BaseSVGFactory.")}create(u,y){if(u<=0||y<=0)throw new Error("Invalid SVG dimensions");let m=this._createSVG("svg:svg");return m.setAttribute("version","1.1"),m.setAttribute("width",`${u}px`),m.setAttribute("height",`${y}px`),m.setAttribute("preserveAspectRatio","none"),m.setAttribute("viewBox",`0 0 ${u} ${y}`),m}createElement(u){if(typeof u!="string")throw new Error("Invalid SVG element type");return this._createSVG(u)}_createSVG(u){(0,n.unreachable)("Abstract method `_createSVG` called.")}}e.BaseSVGFactory=c},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FontLoader=e.FontFaceObject=void 0;var n=t(1);class i{constructor({docId:f,onUnsupportedFeature:u,ownerDocument:y=globalThis.document,styleElement:m=null}){this.constructor===i&&(0,n.unreachable)("Cannot initialize BaseFontLoader."),this.docId=f,this._onUnsupportedFeature=u,this._document=y,this.nativeFontFaces=[],this.styleElement=null}addNativeFontFace(f){this.nativeFontFaces.push(f),this._document.fonts.add(f)}insertRule(f){let u=this.styleElement;u||(u=this.styleElement=this._document.createElement("style"),u.id=`PDFJS_FONT_STYLE_TAG_${this.docId}`,this._document.documentElement.getElementsByTagName("head")[0].appendChild(u));let y=u.sheet;y.insertRule(f,y.cssRules.length)}clear(){for(let f of this.nativeFontFaces)this._document.fonts.delete(f);this.nativeFontFaces.length=0,this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async bind(f){if(f.attached||f.missingFile)return;if(f.attached=!0,this.isFontLoadingAPISupported){let y=f.createNativeFontFace();if(y){this.addNativeFontFace(y);try{await y.loaded}catch(m){throw this._onUnsupportedFeature({featureId:n.UNSUPPORTED_FEATURES.errorFontLoadNative}),(0,n.warn)(`Failed to load font '${y.family}': '${m}'.`),f.disableFontFace=!0,m}}return}let u=f.createFontFaceRule();if(u){if(this.insertRule(u),this.isSyncFontLoadingSupported)return;await new Promise(y=>{let m=this._queueLoadingCallback(y);this._prepareFontLoadEvent([u],[f],m)})}}_queueLoadingCallback(f){(0,n.unreachable)("Abstract method `_queueLoadingCallback`.")}get isFontLoadingAPISupported(){var u;let f=!!((u=this._document)!=null&&u.fonts);return(0,n.shadow)(this,"isFontLoadingAPISupported",f)}get isSyncFontLoadingSupported(){(0,n.unreachable)("Abstract method `isSyncFontLoadingSupported`.")}get _loadTestFont(){(0,n.unreachable)("Abstract method `_loadTestFont`.")}_prepareFontLoadEvent(f,u,y){(0,n.unreachable)("Abstract method `_prepareFontLoadEvent`.")}}let o;e.FontLoader=o,e.FontLoader=o=class extends i{constructor(f){super(f),this.loadingContext={requests:[],nextRequestId:0},this.loadTestFontId=0}get isSyncFontLoadingSupported(){let f=!1;if(typeof navigator>"u")f=!0;else{let u=/Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);(u==null?void 0:u[1])>=14&&(f=!0)}return(0,n.shadow)(this,"isSyncFontLoadingSupported",f)}_queueLoadingCallback(f){function u(){for((0,n.assert)(!m.done,"completeRequest() cannot be called twice."),m.done=!0;y.requests.length>0&&y.requests[0].done;){let _=y.requests.shift();setTimeout(_.callback,0)}}let y=this.loadingContext,m={id:`pdfjs-font-loading-${y.nextRequestId++}`,done:!1,complete:u,callback:f};return y.requests.push(m),m}get _loadTestFont(){let f=function(){return atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==")};return(0,n.shadow)(this,"_loadTestFont",f())}_prepareFontLoadEvent(f,u,y){function m(V,q){return V.charCodeAt(q)<<24|V.charCodeAt(q+1)<<16|V.charCodeAt(q+2)<<8|V.charCodeAt(q+3)&255}function _(V,q,G,Y){let X=V.substring(0,q),Q=V.substring(q+G);return X+Y+Q}let v,g,h=this._document.createElement("canvas");h.width=1,h.height=1;let l=h.getContext("2d"),p=0;function w(V,q){if(p++,p>30){(0,n.warn)("Load test font never loaded."),q();return}if(l.font="30px "+V,l.fillText(".",0,20),l.getImageData(0,0,1,1).data[3]>0){q();return}setTimeout(w.bind(null,V,q))}let A=`lt${Date.now()}${this.loadTestFontId++}`,C=this._loadTestFont;C=_(C,976,A.length,A);let E=16,k=1482184792,P=m(C,E);for(v=0,g=A.length-3;v<g;v+=4)P=P-k+m(A,v)|0;v<A.length&&(P=P-k+m(A+"XXX",v)|0),C=_(C,E,4,(0,n.string32)(P));let N=`url(data:font/opentype;base64,${btoa(C)});`,D=`@font-face {font-family:"${A}";src:${N}}`;this.insertRule(D);let F=[];for(let V of u)F.push(V.loadedName);F.push(A);let B=this._document.createElement("div");B.style.visibility="hidden",B.style.width=B.style.height="10px",B.style.position="absolute",B.style.top=B.style.left="0px";for(let V of F){let q=this._document.createElement("span");q.textContent="Hi",q.style.fontFamily=V,B.appendChild(q)}this._document.body.appendChild(B),w(A,()=>{B.remove(),y.complete()})}};class s{constructor(f,{isEvalSupported:u=!0,disableFontFace:y=!1,ignoreErrors:m=!1,onUnsupportedFeature:_,fontRegistry:v=null}){this.compiledGlyphs=Object.create(null);for(let g in f)this[g]=f[g];this.isEvalSupported=u!==!1,this.disableFontFace=y===!0,this.ignoreErrors=m===!0,this._onUnsupportedFeature=_,this.fontRegistry=v}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let f;if(!this.cssFontInfo)f=new FontFace(this.loadedName,this.data,{});else{let u={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(u.style=`oblique ${this.cssFontInfo.italicAngle}deg`),f=new FontFace(this.cssFontInfo.fontFamily,this.data,u)}return this.fontRegistry&&this.fontRegistry.registerFont(this),f}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let f=(0,n.bytesToString)(this.data),u=`url(data:${this.mimetype};base64,${btoa(f)});`,y;if(!this.cssFontInfo)y=`@font-face {font-family:"${this.loadedName}";src:${u}}`;else{let m=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(m+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),y=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${m}src:${u}}`}return this.fontRegistry&&this.fontRegistry.registerFont(this,u),y}getPathGenerator(f,u){if(this.compiledGlyphs[u]!==void 0)return this.compiledGlyphs[u];let y;try{y=f.get(this.loadedName+"_path_"+u)}catch(m){if(!this.ignoreErrors)throw m;return this._onUnsupportedFeature({featureId:n.UNSUPPORTED_FEATURES.errorFontGetPath}),(0,n.warn)(`getPathGenerator - ignoring character: "${m}".`),this.compiledGlyphs[u]=function(_,v){}}if(this.isEvalSupported&&n.FeatureTest.isEvalSupported){let m=[];for(let _ of y){let v=_.args!==void 0?_.args.join(","):"";m.push("c.",_.cmd,"(",v,`);
|
|
72
72
|
`)}return this.compiledGlyphs[u]=new Function("c","size",m.join(""))}return this.compiledGlyphs[u]=function(m,_){for(let v of y)v.cmd==="scale"&&(v.args=[_,-_]),m[v.cmd].apply(m,v.args)}}}e.FontFaceObject=s},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AnnotationStorage=void 0;var n=t(9),i=t(1);class o{constructor(){this._storage=new Map,this._modified=!1,this.onSetModified=null,this.onResetModified=null}getValue(c,f){let u=this._storage.get(c);return u===void 0?f:Object.assign(f,u)}getRawValue(c){return this._storage.get(c)}setValue(c,f){let u=this._storage.get(c),y=!1;if(u!==void 0)for(let[m,_]of Object.entries(f))u[m]!==_&&(y=!0,u[m]=_);else y=!0,this._storage.set(c,f);y&&this._setModified()}getAll(){return this._storage.size>0?(0,i.objectFromMap)(this._storage):null}get size(){return this._storage.size}_setModified(){this._modified||(this._modified=!0,typeof this.onSetModified=="function"&&this.onSetModified())}resetModified(){this._modified&&(this._modified=!1,typeof this.onResetModified=="function"&&this.onResetModified())}get serializable(){return this._storage.size>0?this._storage:null}get hash(){let c=new n.MurmurHash3_64;for(let[f,u]of this._storage)c.update(`${f}:${JSON.stringify(u)}`);return c.hexdigest()}}e.AnnotationStorage=o},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MurmurHash3_64=void 0;var n=t(1);let i=3285377520,o=4294901760,s=65535;class c{constructor(u){this.h1=u?u&4294967295:i,this.h2=u?u&4294967295:i}update(u){let y,m;if(typeof u=="string"){y=new Uint8Array(u.length*2),m=0;for(let k=0,P=u.length;k<P;k++){let N=u.charCodeAt(k);N<=255?y[m++]=N:(y[m++]=N>>>8,y[m++]=N&255)}}else if((0,n.isArrayBuffer)(u))y=u.slice(),m=y.byteLength;else throw new Error("Wrong data format in MurmurHash3_64_update. Input must be a string or array.");let _=m>>2,v=m-_*4,g=new Uint32Array(y.buffer,0,_),h=0,l=0,p=this.h1,w=this.h2,A=3432918353,C=461845907,b=A&s,E=C&s;for(let k=0;k<_;k++)k&1?(h=g[k],h=h*A&o|h*b&s,h=h<<15|h>>>17,h=h*C&o|h*E&s,p^=h,p=p<<13|p>>>19,p=p*5+3864292196):(l=g[k],l=l*A&o|l*b&s,l=l<<15|l>>>17,l=l*C&o|l*E&s,w^=l,w=w<<13|w>>>19,w=w*5+3864292196);switch(h=0,v){case 3:h^=y[_*4+2]<<16;case 2:h^=y[_*4+1]<<8;case 1:h^=y[_*4],h=h*A&o|h*b&s,h=h<<15|h>>>17,h=h*C&o|h*E&s,_&1?p^=h:w^=h}this.h1=p,this.h2=w}hexdigest(){let u=this.h1,y=this.h2;u^=y>>>1,u=u*3981806797&o|u*36045&s,y=y*4283543511&o|((y<<16|u>>>16)*2950163797&o)>>>16,u^=y>>>1,u=u*444984403&o|u*60499&s,y=y*3301882366&o|((y<<16|u>>>16)*3120437893&o)>>>16,u^=y>>>1;let m=(u>>>0).toString(16),_=(y>>>0).toString(16);return m.padStart(8,"0")+_.padStart(8,"0")}}e.MurmurHash3_64=c},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CanvasGraphics=void 0;var n=t(1),i=t(11),o=t(12),s=t(3),c=t(5);let f=16,u=100,y=4096,m=15,_=10,v=!0,g=1e3,h=16,l=1.000001;function p(W,H){if(W._removeMirroring)throw new Error("Context is already forwarding operations.");W.__originalSave=W.save,W.__originalRestore=W.restore,W.__originalRotate=W.rotate,W.__originalScale=W.scale,W.__originalTranslate=W.translate,W.__originalTransform=W.transform,W.__originalSetTransform=W.setTransform,W.__originalResetTransform=W.resetTransform,W.__originalClip=W.clip,W.__originalMoveTo=W.moveTo,W.__originalLineTo=W.lineTo,W.__originalBezierCurveTo=W.bezierCurveTo,W.__originalRect=W.rect,W.__originalClosePath=W.closePath,W.__originalBeginPath=W.beginPath,W._removeMirroring=()=>{W.save=W.__originalSave,W.restore=W.__originalRestore,W.rotate=W.__originalRotate,W.scale=W.__originalScale,W.translate=W.__originalTranslate,W.transform=W.__originalTransform,W.setTransform=W.__originalSetTransform,W.resetTransform=W.__originalResetTransform,W.clip=W.__originalClip,W.moveTo=W.__originalMoveTo,W.lineTo=W.__originalLineTo,W.bezierCurveTo=W.__originalBezierCurveTo,W.rect=W.__originalRect,W.closePath=W.__originalClosePath,W.beginPath=W.__originalBeginPath,delete W._removeMirroring},W.save=function(){H.save(),this.__originalSave()},W.restore=function(){H.restore(),this.__originalRestore()},W.translate=function(x,T){H.translate(x,T),this.__originalTranslate(x,T)},W.scale=function(x,T){H.scale(x,T),this.__originalScale(x,T)},W.transform=function(x,T,O,I,U,z){H.transform(x,T,O,I,U,z),this.__originalTransform(x,T,O,I,U,z)},W.setTransform=function(x,T,O,I,U,z){H.setTransform(x,T,O,I,U,z),this.__originalSetTransform(x,T,O,I,U,z)},W.resetTransform=function(){H.resetTransform(),this.__originalResetTransform()},W.rotate=function(x){H.rotate(x),this.__originalRotate(x)},W.clip=function(x){H.clip(x),this.__originalClip(x)},W.moveTo=function(R,x){H.moveTo(R,x),this.__originalMoveTo(R,x)},W.lineTo=function(R,x){H.lineTo(R,x),this.__originalLineTo(R,x)},W.bezierCurveTo=function(R,x,T,O,I,U){H.bezierCurveTo(R,x,T,O,I,U),this.__originalBezierCurveTo(R,x,T,O,I,U)},W.rect=function(R,x,T,O){H.rect(R,x,T,O),this.__originalRect(R,x,T,O)},W.closePath=function(){H.closePath(),this.__originalClosePath()},W.beginPath=function(){H.beginPath(),this.__originalBeginPath()}}function w(W){if(W._transformStack&&(W._transformStack=[]),!W.mozCurrentTransform){W._originalSave=W.save,W._originalRestore=W.restore,W._originalRotate=W.rotate,W._originalScale=W.scale,W._originalTranslate=W.translate,W._originalTransform=W.transform,W._originalSetTransform=W.setTransform,W._originalResetTransform=W.resetTransform,W._transformMatrix=W._transformMatrix||[1,0,0,1,0,0],W._transformStack=[];try{let H=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(W),"lineWidth");W._setLineWidth=H.set,W._getLineWidth=H.get,Object.defineProperty(W,"lineWidth",{set:function(x){this._setLineWidth(x*l)},get:function(){return this._getLineWidth()}})}catch{}Object.defineProperty(W,"mozCurrentTransform",{get:function(){return this._transformMatrix}}),Object.defineProperty(W,"mozCurrentTransformInverse",{get:function(){let[R,x,T,O,I,U]=this._transformMatrix,z=R*O-x*T,Z=x*T-R*O;return[O/z,x/Z,T/Z,R/z,(O*I-T*U)/Z,(x*I-R*U)/z]}}),W.save=function(){let R=this._transformMatrix;this._transformStack.push(R),this._transformMatrix=R.slice(0,6),this._originalSave()},W.restore=function(){this._transformStack.length===0&&(0,n.warn)("Tried to restore a ctx when the stack was already empty.");let R=this._transformStack.pop();R&&(this._transformMatrix=R,this._originalRestore())},W.translate=function(R,x){let T=this._transformMatrix;T[4]=T[0]*R+T[2]*x+T[4],T[5]=T[1]*R+T[3]*x+T[5],this._originalTranslate(R,x)},W.scale=function(R,x){let T=this._transformMatrix;T[0]*=R,T[1]*=R,T[2]*=x,T[3]*=x,this._originalScale(R,x)},W.transform=function(R,x,T,O,I,U){let z=this._transformMatrix;this._transformMatrix=[z[0]*R+z[2]*x,z[1]*R+z[3]*x,z[0]*T+z[2]*O,z[1]*T+z[3]*O,z[0]*I+z[2]*U+z[4],z[1]*I+z[3]*U+z[5]],W._originalTransform(R,x,T,O,I,U)},W.setTransform=function(R,x,T,O,I,U){this._transformMatrix=[R,x,T,O,I,U],W._originalSetTransform(R,x,T,O,I,U)},W.resetTransform=function(){this._transformMatrix=[1,0,0,1,0,0],W._originalResetTransform()},W.rotate=function(R){let x=Math.cos(R),T=Math.sin(R),O=this._transformMatrix;this._transformMatrix=[O[0]*x+O[2]*T,O[1]*x+O[3]*T,O[0]*-T+O[2]*x,O[1]*-T+O[3]*x,O[4],O[5]],this._originalRotate(R)}}}class A{constructor(H){this.canvasFactory=H,this.cache=Object.create(null)}getCanvas(H,R,x,T){let O;return this.cache[H]!==void 0?(O=this.cache[H],this.canvasFactory.reset(O,R,x),O.context.setTransform(1,0,0,1,0,0)):(O=this.canvasFactory.create(R,x),this.cache[H]=O),T&&w(O.context),O}delete(H){delete this.cache[H]}clear(){for(let H in this.cache){let R=this.cache[H];this.canvasFactory.destroy(R),delete this.cache[H]}}}function C(W,H,R,x,T,O,I,U,z,Z){let[re,ne,se,fe,he,Te]=W.mozCurrentTransform;if(ne===0&&se===0){let ye=I*re+he,oe=Math.round(ye),Ce=U*fe+Te,xe=Math.round(Ce),K=(I+z)*re+he,ie=Math.abs(Math.round(K)-oe)||1,be=(U+Z)*fe+Te,Ee=Math.abs(Math.round(be)-xe)||1;return W.setTransform(Math.sign(re),0,0,Math.sign(fe),oe,xe),W.drawImage(H,R,x,T,O,0,0,ie,Ee),W.setTransform(re,ne,se,fe,he,Te),[ie,Ee]}if(re===0&&fe===0){let ye=U*se+he,oe=Math.round(ye),Ce=I*ne+Te,xe=Math.round(Ce),K=(U+Z)*se+he,ie=Math.abs(Math.round(K)-oe)||1,be=(I+z)*ne+Te,Ee=Math.abs(Math.round(be)-xe)||1;return W.setTransform(0,Math.sign(ne),Math.sign(se),0,oe,xe),W.drawImage(H,R,x,T,O,0,0,Ee,ie),W.setTransform(re,ne,se,fe,he,Te),[Ee,ie]}W.drawImage(H,R,x,T,O,I,U,z,Z);let Ie=Math.hypot(re,ne),we=Math.hypot(se,fe);return[Ie*z,we*Z]}function b(W){let{width:H,height:R}=W;if(!v||H>g||R>g)return null;let x=1e3,T=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),O=H+1,I=new Uint8Array(O*(R+1)),U,z,Z,re=H+7&-8,ne=new Uint8Array(re*R),se=0;for(let oe of W.data){let Ce=128;for(;Ce>0;)ne[se++]=oe&Ce?0:255,Ce>>=1}let fe=0;for(se=0,ne[se]!==0&&(I[0]=1,++fe),z=1;z<H;z++)ne[se]!==ne[se+1]&&(I[z]=ne[se]?2:1,++fe),se++;for(ne[se]!==0&&(I[z]=2,++fe),U=1;U<R;U++){se=U*re,Z=U*O,ne[se-re]!==ne[se]&&(I[Z]=ne[se]?1:8,++fe);let oe=(ne[se]?4:0)+(ne[se-re]?8:0);for(z=1;z<H;z++)oe=(oe>>2)+(ne[se+1]?4:0)+(ne[se-re+1]?8:0),T[oe]&&(I[Z+z]=T[oe],++fe),se++;if(ne[se-re]!==ne[se]&&(I[Z+z]=ne[se]?2:4,++fe),fe>x)return null}for(se=re*(R-1),Z=U*O,ne[se]!==0&&(I[Z]=8,++fe),z=1;z<H;z++)ne[se]!==ne[se+1]&&(I[Z+z]=ne[se]?4:8,++fe),se++;if(ne[se]!==0&&(I[Z+z]=4,++fe),fe>x)return null;let he=new Int32Array([0,O,-1,0,-O,0,0,0,1]),Te,Ie,we;for(s.isNodeJS?Ie=[]:Te=new Path2D,U=0;fe&&U<=R;U++){let oe=U*O,Ce=oe+H;for(;oe<Ce&&!I[oe];)oe++;if(oe===Ce)continue;Te?Te.moveTo(oe%O,U):we=[oe%O,U];let xe=oe,K=I[oe];do{let ie=he[K];do oe+=ie;while(!I[oe]);let be=I[oe];be!==5&&be!==10?(K=be,I[oe]=0):(K=be&51*K>>4,I[oe]&=K>>2|K<<2),Te?Te.lineTo(oe%O,oe/O|0):we.push(oe%O,oe/O|0),I[oe]||--fe}while(xe!==oe);Te||Ie.push(we),--U}return ne=null,I=null,function(oe){if(oe.save(),oe.scale(1/H,-1/R),oe.translate(0,-R),Te)oe.fill(Te);else{oe.beginPath();for(let Ce of Ie){oe.moveTo(Ce[0],Ce[1]);for(let xe=2,K=Ce.length;xe<K;xe+=2)oe.lineTo(Ce[xe],Ce[xe+1])}oe.fill()}oe.beginPath(),oe.restore()}}class E{constructor(H,R){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=n.IDENTITY_MATRIX,this.textMatrixScale=1,this.fontMatrix=n.FONT_IDENTITY_MATRIX,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=n.TextRenderingMode.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps=null,this.startNewPathAndClipBox([0,0,H,R])}clone(){let H=Object.create(this);return H.clipBox=this.clipBox.slice(),H}setCurrentPoint(H,R){this.x=H,this.y=R}updatePathMinMax(H,R,x){[R,x]=n.Util.applyTransform([R,x],H),this.minX=Math.min(this.minX,R),this.minY=Math.min(this.minY,x),this.maxX=Math.max(this.maxX,R),this.maxY=Math.max(this.maxY,x)}updateRectMinMax(H,R){let x=n.Util.applyTransform(R,H),T=n.Util.applyTransform(R.slice(2),H);this.minX=Math.min(this.minX,x[0],T[0]),this.minY=Math.min(this.minY,x[1],T[1]),this.maxX=Math.max(this.maxX,x[0],T[0]),this.maxY=Math.max(this.maxY,x[1],T[1])}updateScalingPathMinMax(H,R){n.Util.scaleMinMax(H,R),this.minX=Math.min(this.minX,R[0]),this.maxX=Math.max(this.maxX,R[1]),this.minY=Math.min(this.minY,R[2]),this.maxY=Math.max(this.maxY,R[3])}updateCurvePathMinMax(H,R,x,T,O,I,U,z,Z,re){let ne=n.Util.bezierBoundingBox(R,x,T,O,I,U,z,Z);if(re){re[0]=Math.min(re[0],ne[0],ne[2]),re[1]=Math.max(re[1],ne[0],ne[2]),re[2]=Math.min(re[2],ne[1],ne[3]),re[3]=Math.max(re[3],ne[1],ne[3]);return}this.updateRectMinMax(H,ne)}getPathBoundingBox(H=i.PathType.FILL,R=null){let x=[this.minX,this.minY,this.maxX,this.maxY];if(H===i.PathType.STROKE){R||(0,n.unreachable)("Stroke bounding box must include transform.");let T=n.Util.singularValueDecompose2dScale(R),O=T[0]*this.lineWidth/2,I=T[1]*this.lineWidth/2;x[0]-=O,x[1]-=I,x[2]+=O,x[3]+=I}return x}updateClipFromPath(){let H=n.Util.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(H||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(H){this.clipBox=H,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(H=i.PathType.FILL,R=null){return n.Util.intersect(this.clipBox,this.getPathBoundingBox(H,R))}}function k(W,H,R=null){if(typeof ImageData<"u"&&H instanceof ImageData){W.putImageData(H,0,0);return}let x=H.height,T=H.width,O=x%h,I=(x-O)/h,U=O===0?I:I+1,z=W.createImageData(T,h),Z=0,re,ne=H.data,se=z.data,fe,he,Te,Ie,we,ye,oe,Ce;if(R)switch(R.length){case 1:we=R[0],ye=R[0],oe=R[0],Ce=R[0];break;case 4:we=R[0],ye=R[1],oe=R[2],Ce=R[3];break}if(H.kind===n.ImageKind.GRAYSCALE_1BPP){let xe=ne.byteLength,K=new Uint32Array(se.buffer,0,se.byteLength>>2),ie=K.length,be=T+7>>3,Ee=4294967295,Re=n.FeatureTest.isLittleEndian?4278190080:255;for(Ce&&Ce[0]===255&&Ce[255]===0&&([Ee,Re]=[Re,Ee]),fe=0;fe<U;fe++){for(Te=fe<I?h:O,re=0,he=0;he<Te;he++){let Ke=xe-Z,ze=0,Ve=Ke>be?T:Ke*8-7,qe=Ve&-8,pe=0,ee=0;for(;ze<qe;ze+=8)ee=ne[Z++],K[re++]=ee&128?Ee:Re,K[re++]=ee&64?Ee:Re,K[re++]=ee&32?Ee:Re,K[re++]=ee&16?Ee:Re,K[re++]=ee&8?Ee:Re,K[re++]=ee&4?Ee:Re,K[re++]=ee&2?Ee:Re,K[re++]=ee&1?Ee:Re;for(;ze<Ve;ze++)pe===0&&(ee=ne[Z++],pe=128),K[re++]=ee&pe?Ee:Re,pe>>=1}for(;re<ie;)K[re++]=0;W.putImageData(z,0,fe*h)}}else if(H.kind===n.ImageKind.RGBA_32BPP){let xe=!!(we||ye||oe);for(he=0,Ie=T*h*4,fe=0;fe<I;fe++){if(se.set(ne.subarray(Z,Z+Ie)),Z+=Ie,xe)for(let K=0;K<Ie;K+=4)we&&(se[K+0]=we[se[K+0]]),ye&&(se[K+1]=ye[se[K+1]]),oe&&(se[K+2]=oe[se[K+2]]);W.putImageData(z,0,he),he+=h}if(fe<U){if(Ie=T*O*4,se.set(ne.subarray(Z,Z+Ie)),xe)for(let K=0;K<Ie;K+=4)we&&(se[K+0]=we[se[K+0]]),ye&&(se[K+1]=ye[se[K+1]]),oe&&(se[K+2]=oe[se[K+2]]);W.putImageData(z,0,he)}}else if(H.kind===n.ImageKind.RGB_24BPP){let xe=!!(we||ye||oe);for(Te=h,Ie=T*Te,fe=0;fe<U;fe++){for(fe>=I&&(Te=O,Ie=T*Te),re=0,he=Ie;he--;)se[re++]=ne[Z++],se[re++]=ne[Z++],se[re++]=ne[Z++],se[re++]=255;if(xe)for(let K=0;K<re;K+=4)we&&(se[K+0]=we[se[K+0]]),ye&&(se[K+1]=ye[se[K+1]]),oe&&(se[K+2]=oe[se[K+2]]);W.putImageData(z,0,fe*h)}}else throw new Error(`bad image kind: ${H.kind}`)}function P(W,H){if(H.bitmap){W.drawImage(H.bitmap,0,0);return}let R=H.height,x=H.width,T=R%h,O=(R-T)/h,I=T===0?O:O+1,U=W.createImageData(x,h),z=0,Z=H.data,re=U.data;for(let ne=0;ne<I;ne++){let se=ne<O?h:T;({srcPos:z}=(0,o.applyMaskImageData)({src:Z,srcPos:z,dest:re,width:x,height:se})),W.putImageData(U,0,ne*h)}}function N(W,H){let R=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font"];for(let x=0,T=R.length;x<T;x++){let O=R[x];W[O]!==void 0&&(H[O]=W[O])}W.setLineDash!==void 0&&(H.setLineDash(W.getLineDash()),H.lineDashOffset=W.lineDashOffset)}function D(W,H){W.strokeStyle=W.fillStyle=H||"#000000",W.fillRule="nonzero",W.globalAlpha=1,W.lineWidth=1,W.lineCap="butt",W.lineJoin="miter",W.miterLimit=10,W.globalCompositeOperation="source-over",W.font="10px sans-serif",W.setLineDash!==void 0&&(W.setLineDash([]),W.lineDashOffset=0)}function F(W,H,R,x){let T=W.length;for(let O=3;O<T;O+=4){let I=W[O];if(I===0)W[O-3]=H,W[O-2]=R,W[O-1]=x;else if(I<255){let U=255-I;W[O-3]=W[O-3]*I+H*U>>8,W[O-2]=W[O-2]*I+R*U>>8,W[O-1]=W[O-1]*I+x*U>>8}}}function B(W,H,R){let x=W.length,T=1/255;for(let O=3;O<x;O+=4){let I=R?R[W[O]]:W[O];H[O]=H[O]*I*T|0}}function V(W,H,R){let x=W.length;for(let T=3;T<x;T+=4){let O=W[T-3]*77+W[T-2]*152+W[T-1]*28;H[T]=R?H[T]*R[O>>8]>>8:H[T]*O>>16}}function q(W,H,R,x,T,O,I,U,z,Z,re){let ne=!!O,se=ne?O[0]:0,fe=ne?O[1]:0,he=ne?O[2]:0,Te;T==="Luminosity"?Te=V:Te=B;let we=Math.min(x,Math.ceil(1048576/R));for(let ye=0;ye<x;ye+=we){let oe=Math.min(we,x-ye),Ce=W.getImageData(U-Z,ye+(z-re),R,oe),xe=H.getImageData(U,ye+z,R,oe);ne&&F(Ce.data,se,fe,he),Te(Ce.data,xe.data,I),H.putImageData(xe,U,ye+z)}}function G(W,H,R,x){let T=x[0],O=x[1],I=x[2]-T,U=x[3]-O;I===0||U===0||(q(H.context,R,I,U,H.subtype,H.backdrop,H.transferMap,T,O,H.offsetX,H.offsetY),W.save(),W.globalAlpha=1,W.globalCompositeOperation="source-over",W.setTransform(1,0,0,1,0,0),W.drawImage(R.canvas,0,0),W.restore())}function Y(W,H){let R=n.Util.singularValueDecompose2dScale(W);R[0]=Math.fround(R[0]),R[1]=Math.fround(R[1]);let x=Math.fround((globalThis.devicePixelRatio||1)*c.PixelsPerInch.PDF_TO_CSS_UNITS);return H!==void 0?H:R[0]<=x||R[1]<=x}let X=["butt","round","square"],Q=["miter","round","bevel"],le={},ve={};class ce{constructor(H,R,x,T,O,I,U,z){this.ctx=H,this.current=new E(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=R,this.objs=x,this.canvasFactory=T,this.imageLayer=O,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=[],this.optionalContentConfig=I,this.cachedCanvases=new A(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=U,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.backgroundColor=(z==null?void 0:z.background)||null,this.foregroundColor=(z==null?void 0:z.foreground)||null,H&&w(H),this._cachedScaleForStroking=null,this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(H,R=null){return typeof H=="string"?H.startsWith("g_")?this.commonObjs.get(H):this.objs.get(H):R}beginDrawing({transform:H,viewport:R,transparency:x=!1,background:T=null}){let O=this.ctx.canvas.width,I=this.ctx.canvas.height,U=T||"#ffffff";if(this.ctx.save(),this.foregroundColor&&this.backgroundColor){this.ctx.fillStyle=this.foregroundColor;let z=this.foregroundColor=this.ctx.fillStyle;this.ctx.fillStyle=this.backgroundColor;let Z=this.backgroundColor=this.ctx.fillStyle,re=!0,ne=U;if(this.ctx.fillStyle=U,ne=this.ctx.fillStyle,re=typeof ne=="string"&&/^#[0-9A-Fa-f]{6}$/.test(ne),z==="#000000"&&Z==="#ffffff"||z===Z||!re)this.foregroundColor=this.backgroundColor=null;else{let se=parseInt(ne.slice(1),16),fe=(se&&16711680)>>16,he=(se&&65280)>>8,Te=se&&255,Ie=ye=>(ye/=255,ye<=.03928?ye/12.92:((ye+.055)/1.055)**2.4),we=Math.round(.2126*Ie(fe)+.7152*Ie(he)+.0722*Ie(Te));this.selectColor=(ye,oe,Ce)=>{let xe=.2126*Ie(ye)+.7152*Ie(oe)+.0722*Ie(Ce);return Math.round(xe)===we?Z:z}}}if(this.ctx.fillStyle=this.backgroundColor||U,this.ctx.fillRect(0,0,O,I),this.ctx.restore(),x){let z=this.cachedCanvases.getCanvas("transparent",O,I,!0);this.compositeCtx=this.ctx,this.transparentCanvas=z.canvas,this.ctx=z.context,this.ctx.save(),this.ctx.transform.apply(this.ctx,this.compositeCtx.mozCurrentTransform)}this.ctx.save(),D(this.ctx,this.foregroundColor),H&&(this.ctx.transform.apply(this.ctx,H),this.outputScaleX=H[0],this.outputScaleY=H[0]),this.ctx.transform.apply(this.ctx,R.transform),this.viewportScale=R.scale,this.baseTransform=this.ctx.mozCurrentTransform.slice(),this.imageLayer&&this.imageLayer.beginLayout()}executeOperatorList(H,R,x,T){let O=H.argsArray,I=H.fnArray,U=R||0,z=O.length;if(z===U)return U;let Z=z-U>_&&typeof x=="function",re=Z?Date.now()+m:0,ne=0,se=this.commonObjs,fe=this.objs,he;for(;;){if(T!==void 0&&U===T.nextBreakPoint)return T.breakIt(U,x),U;if(he=I[U],he!==n.OPS.dependency)this[he].apply(this,O[U]);else for(let Te of O[U]){let Ie=Te.startsWith("g_")?se:fe;if(!Ie.has(Te))return Ie.get(Te,x),U}if(U++,U===z)return U;if(Z&&++ne>_){if(Date.now()>re)return x(),U;ne=0}}}endDrawing(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(let H of this._cachedBitmapsMap.values()){for(let R of H.values())typeof HTMLCanvasElement<"u"&&R instanceof HTMLCanvasElement&&(R.width=R.height=0);H.clear()}this._cachedBitmapsMap.clear(),this.imageLayer&&this.imageLayer.endLayout()}_scaleImage(H,R){let x=H.width,T=H.height,O=Math.max(Math.hypot(R[0],R[1]),1),I=Math.max(Math.hypot(R[2],R[3]),1),U=x,z=T,Z="prescale1",re,ne;for(;O>2&&U>1||I>2&&z>1;){let se=U,fe=z;O>2&&U>1&&(se=Math.ceil(U/2),O/=U/se),I>2&&z>1&&(fe=Math.ceil(z/2),I/=z/fe),re=this.cachedCanvases.getCanvas(Z,se,fe,!1),ne=re.context,ne.clearRect(0,0,se,fe),ne.drawImage(H,0,0,U,z,0,0,se,fe),H=re.canvas,U=se,z=fe,Z=Z==="prescale1"?"prescale2":"prescale1"}return{img:H,paintWidth:U,paintHeight:z}}_createMaskCanvas(H){let R=this.ctx,{width:x,height:T}=H,O=this.current.fillColor,I=this.current.patternFill,U=R.mozCurrentTransform,z,Z,re,ne;if((H.bitmap||H.data)&&H.count>1){let ie=H.bitmap||H.data.buffer,be=U.slice(0,4);Z=JSON.stringify(I?be:[be,O]),z=this._cachedBitmapsMap.get(ie),z||(z=new Map,this._cachedBitmapsMap.set(ie,z));let Ee=z.get(Z);if(Ee&&!I){let Re=Math.round(Math.min(U[0],U[2])+U[4]),Ke=Math.round(Math.min(U[1],U[3])+U[5]);return{canvas:Ee,offsetX:Re,offsetY:Ke}}re=Ee}re||(ne=this.cachedCanvases.getCanvas("maskCanvas",x,T,!1),P(ne.context,H));let se=n.Util.transform(U,[1/x,0,0,-1/T,0,0]);se=n.Util.transform(se,[1,0,0,1,0,-T]);let fe=n.Util.applyTransform([0,0],se),he=n.Util.applyTransform([x,T],se),Te=n.Util.normalizeRect([fe[0],fe[1],he[0],he[1]]),Ie=Math.round(Te[2]-Te[0])||1,we=Math.round(Te[3]-Te[1])||1,ye=this.cachedCanvases.getCanvas("fillCanvas",Ie,we,!0),oe=ye.context,Ce=Math.min(fe[0],he[0]),xe=Math.min(fe[1],he[1]);oe.translate(-Ce,-xe),oe.transform.apply(oe,se),re||(re=this._scaleImage(ne.canvas,oe.mozCurrentTransformInverse),re=re.img,z&&I&&z.set(Z,re)),oe.imageSmoothingEnabled=Y(oe.mozCurrentTransform,H.interpolate),C(oe,re,0,0,re.width,re.height,0,0,x,T),oe.globalCompositeOperation="source-in";let K=n.Util.transform(oe.mozCurrentTransformInverse,[1,0,0,1,-Ce,-xe]);return oe.fillStyle=I?O.getPattern(R,this,K,i.PathType.FILL):O,oe.fillRect(0,0,x,T),z&&!I&&(this.cachedCanvases.delete("fillCanvas"),z.set(Z,ye.canvas)),{canvas:ye.canvas,offsetX:Math.round(Ce),offsetY:Math.round(xe)}}setLineWidth(H){H!==this.current.lineWidth&&(this._cachedScaleForStroking=null),this.current.lineWidth=H,this.ctx.lineWidth=H}setLineCap(H){this.ctx.lineCap=X[H]}setLineJoin(H){this.ctx.lineJoin=Q[H]}setMiterLimit(H){this.ctx.miterLimit=H}setDash(H,R){let x=this.ctx;x.setLineDash!==void 0&&(x.setLineDash(H),x.lineDashOffset=R)}setRenderingIntent(H){}setFlatness(H){}setGState(H){for(let R=0,x=H.length;R<x;R++){let T=H[R],O=T[0],I=T[1];switch(O){case"LW":this.setLineWidth(I);break;case"LC":this.setLineCap(I);break;case"LJ":this.setLineJoin(I);break;case"ML":this.setMiterLimit(I);break;case"D":this.setDash(I[0],I[1]);break;case"RI":this.setRenderingIntent(I);break;case"FL":this.setFlatness(I);break;case"Font":this.setFont(I[0],I[1]);break;case"CA":this.current.strokeAlpha=T[1];break;case"ca":this.current.fillAlpha=T[1],this.ctx.globalAlpha=T[1];break;case"BM":this.ctx.globalCompositeOperation=I;break;case"SMask":this.current.activeSMask=I?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.current.transferMaps=I}}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){let H=this.inSMaskMode;this.current.activeSMask&&!H?this.beginSMaskMode():!this.current.activeSMask&&H&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");let H=this.ctx.canvas.width,R=this.ctx.canvas.height,x="smaskGroupAt"+this.groupLevel,T=this.cachedCanvases.getCanvas(x,H,R,!0);this.suspendedCtx=this.ctx,this.ctx=T.context;let O=this.ctx;O.setTransform.apply(O,this.suspendedCtx.mozCurrentTransform),N(this.suspendedCtx,O),p(O,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),N(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(H){if(!this.current.activeSMask)return;H?(H[0]=Math.floor(H[0]),H[1]=Math.floor(H[1]),H[2]=Math.ceil(H[2]),H[3]=Math.ceil(H[3])):H=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let R=this.current.activeSMask,x=this.suspendedCtx;G(x,R,this.ctx,H),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}save(){this.inSMaskMode?(N(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();let H=this.current;this.stateStack.push(H),this.current=H.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),N(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking=null,this._cachedGetSinglePixelWidth=null)}transform(H,R,x,T,O,I){this.ctx.transform(H,R,x,T,O,I),this._cachedScaleForStroking=null,this._cachedGetSinglePixelWidth=null}constructPath(H,R,x){let T=this.ctx,O=this.current,I=O.x,U=O.y,z,Z,re=T.mozCurrentTransform,ne=re[0]===0&&re[3]===0||re[1]===0&&re[2]===0,se=ne?x.slice(0):null;for(let fe=0,he=0,Te=H.length;fe<Te;fe++)switch(H[fe]|0){case n.OPS.rectangle:I=R[he++],U=R[he++];let Ie=R[he++],we=R[he++],ye=I+Ie,oe=U+we;T.moveTo(I,U),Ie===0||we===0?T.lineTo(ye,oe):(T.lineTo(ye,U),T.lineTo(ye,oe),T.lineTo(I,oe)),ne||O.updateRectMinMax(re,[I,U,ye,oe]),T.closePath();break;case n.OPS.moveTo:I=R[he++],U=R[he++],T.moveTo(I,U),ne||O.updatePathMinMax(re,I,U);break;case n.OPS.lineTo:I=R[he++],U=R[he++],T.lineTo(I,U),ne||O.updatePathMinMax(re,I,U);break;case n.OPS.curveTo:z=I,Z=U,I=R[he+4],U=R[he+5],T.bezierCurveTo(R[he],R[he+1],R[he+2],R[he+3],I,U),O.updateCurvePathMinMax(re,z,Z,R[he],R[he+1],R[he+2],R[he+3],I,U,se),he+=6;break;case n.OPS.curveTo2:z=I,Z=U,T.bezierCurveTo(I,U,R[he],R[he+1],R[he+2],R[he+3]),O.updateCurvePathMinMax(re,z,Z,I,U,R[he],R[he+1],R[he+2],R[he+3],se),I=R[he+2],U=R[he+3],he+=4;break;case n.OPS.curveTo3:z=I,Z=U,I=R[he+2],U=R[he+3],T.bezierCurveTo(R[he],R[he+1],I,U,I,U),O.updateCurvePathMinMax(re,z,Z,R[he],R[he+1],I,U,I,U,se),he+=4;break;case n.OPS.closePath:T.closePath();break}ne&&O.updateScalingPathMinMax(re,se),O.setCurrentPoint(I,U)}closePath(){this.ctx.closePath()}stroke(H){H=typeof H<"u"?H:!0;let R=this.ctx,x=this.current.strokeColor;R.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof x=="object"&&(x!=null&&x.getPattern)?(R.save(),R.strokeStyle=x.getPattern(R,this,R.mozCurrentTransformInverse,i.PathType.STROKE),this.rescaleAndStroke(!1),R.restore()):this.rescaleAndStroke(!0)),H&&this.consumePath(this.current.getClippedPathBoundingBox()),R.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(H){H=typeof H<"u"?H:!0;let R=this.ctx,x=this.current.fillColor,T=this.current.patternFill,O=!1;T&&(R.save(),R.fillStyle=x.getPattern(R,this,R.mozCurrentTransformInverse,i.PathType.FILL),O=!0);let I=this.current.getClippedPathBoundingBox();this.contentVisible&&I!==null&&(this.pendingEOFill?(R.fill("evenodd"),this.pendingEOFill=!1):R.fill()),O&&R.restore(),H&&this.consumePath(I)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=le}eoClip(){this.pendingClip=ve}beginText(){this.current.textMatrix=n.IDENTITY_MATRIX,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){let H=this.pendingTextPaths,R=this.ctx;if(H===void 0){R.beginPath();return}R.save(),R.beginPath();for(let x=0;x<H.length;x++){let T=H[x];R.setTransform.apply(R,T.transform),R.translate(T.x,T.y),T.addToPath(R,T.fontSize)}R.restore(),R.clip(),R.beginPath(),delete this.pendingTextPaths}setCharSpacing(H){this.current.charSpacing=H}setWordSpacing(H){this.current.wordSpacing=H}setHScale(H){this.current.textHScale=H/100}setLeading(H){this.current.leading=-H}setFont(H,R){let x=this.commonObjs.get(H),T=this.current;if(!x)throw new Error(`Can't find font for ${H}`);if(T.fontMatrix=x.fontMatrix||n.FONT_IDENTITY_MATRIX,(T.fontMatrix[0]===0||T.fontMatrix[3]===0)&&(0,n.warn)("Invalid font matrix for font "+H),R<0?(R=-R,T.fontDirection=-1):T.fontDirection=1,this.current.font=x,this.current.fontSize=R,x.isType3Font)return;let O=x.loadedName||"sans-serif",I="normal";x.black?I="900":x.bold&&(I="bold");let U=x.italic?"italic":"normal",z=`"${O}", ${x.fallbackName}`,Z=R;R<f?Z=f:R>u&&(Z=u),this.current.fontSizeScale=R/Z,this.ctx.font=`${U} ${I} ${Z}px ${z}`}setTextRenderingMode(H){this.current.textRenderingMode=H}setTextRise(H){this.current.textRise=H}moveText(H,R){this.current.x=this.current.lineX+=H,this.current.y=this.current.lineY+=R}setLeadingMoveText(H,R){this.setLeading(-R),this.moveText(H,R)}setTextMatrix(H,R,x,T,O,I){this.current.textMatrix=[H,R,x,T,O,I],this.current.textMatrixScale=Math.hypot(H,R),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(H,R,x,T){let O=this.ctx,I=this.current,U=I.font,z=I.textRenderingMode,Z=I.fontSize/I.fontSizeScale,re=z&n.TextRenderingMode.FILL_STROKE_MASK,ne=!!(z&n.TextRenderingMode.ADD_TO_PATH_FLAG),se=I.patternFill&&!U.missingFile,fe;(U.disableFontFace||ne||se)&&(fe=U.getPathGenerator(this.commonObjs,H)),U.disableFontFace||se?(O.save(),O.translate(R,x),O.beginPath(),fe(O,Z),T&&O.setTransform.apply(O,T),(re===n.TextRenderingMode.FILL||re===n.TextRenderingMode.FILL_STROKE)&&O.fill(),(re===n.TextRenderingMode.STROKE||re===n.TextRenderingMode.FILL_STROKE)&&O.stroke(),O.restore()):((re===n.TextRenderingMode.FILL||re===n.TextRenderingMode.FILL_STROKE)&&O.fillText(H,R,x),(re===n.TextRenderingMode.STROKE||re===n.TextRenderingMode.FILL_STROKE)&&O.strokeText(H,R,x)),ne&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:O.mozCurrentTransform,x:R,y:x,fontSize:Z,addToPath:fe})}get isFontSubpixelAAEnabled(){let{context:H}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10,!1);H.scale(1.5,1),H.fillText("I",0,10);let R=H.getImageData(0,0,10,10).data,x=!1;for(let T=3;T<R.length;T+=4)if(R[T]>0&&R[T]<255){x=!0;break}return(0,n.shadow)(this,"isFontSubpixelAAEnabled",x)}showText(H){let R=this.current,x=R.font;if(x.isType3Font)return this.showType3Text(H);let T=R.fontSize;if(T===0)return;let O=this.ctx,I=R.fontSizeScale,U=R.charSpacing,z=R.wordSpacing,Z=R.fontDirection,re=R.textHScale*Z,ne=H.length,se=x.vertical,fe=se?1:-1,he=x.defaultVMetrics,Te=T*R.fontMatrix[0],Ie=R.textRenderingMode===n.TextRenderingMode.FILL&&!x.disableFontFace&&!R.patternFill;O.save(),O.transform.apply(O,R.textMatrix),O.translate(R.x,R.y+R.textRise),Z>0?O.scale(re,-1):O.scale(re,1);let we;if(R.patternFill){O.save();let K=R.fillColor.getPattern(O,this,O.mozCurrentTransformInverse,i.PathType.FILL);we=O.mozCurrentTransform,O.restore(),O.fillStyle=K}let ye=R.lineWidth,oe=R.textMatrixScale;if(oe===0||ye===0){let K=R.textRenderingMode&n.TextRenderingMode.FILL_STROKE_MASK;(K===n.TextRenderingMode.STROKE||K===n.TextRenderingMode.FILL_STROKE)&&(ye=this.getSinglePixelWidth())}else ye/=oe;I!==1&&(O.scale(I,I),ye/=I),O.lineWidth=ye;let Ce=0,xe;for(xe=0;xe<ne;++xe){let K=H[xe];if(typeof K=="number"){Ce+=fe*K*T/1e3;continue}let ie=!1,be=(K.isSpace?z:0)+U,Ee=K.fontChar,Re=K.accent,Ke,ze,Ve=K.width;if(se){let pe=K.vmetric||he,ee=-(K.vmetric?pe[1]:Ve*.5)*Te,de=pe[2]*Te;Ve=pe?-pe[0]:Ve,Ke=ee/I,ze=(Ce+de)/I}else Ke=Ce/I,ze=0;if(x.remeasure&&Ve>0){let pe=O.measureText(Ee).width*1e3/T*I;if(Ve<pe&&this.isFontSubpixelAAEnabled){let ee=Ve/pe;ie=!0,O.save(),O.scale(ee,1),Ke/=ee}else Ve!==pe&&(Ke+=(Ve-pe)/2e3*T/I)}if(this.contentVisible&&(K.isInFont||x.missingFile)){if(Ie&&!Re)O.fillText(Ee,Ke,ze);else if(this.paintChar(Ee,Ke,ze,we),Re){let pe=Ke+T*Re.offset.x/I,ee=ze-T*Re.offset.y/I;this.paintChar(Re.fontChar,pe,ee,we)}}let qe;se?qe=Ve*Te-be*Z:qe=Ve*Te+be*Z,Ce+=qe,ie&&O.restore()}se?R.y-=Ce:R.x+=Ce*re,O.restore(),this.compose()}showType3Text(H){let R=this.ctx,x=this.current,T=x.font,O=x.fontSize,I=x.fontDirection,U=T.vertical?1:-1,z=x.charSpacing,Z=x.wordSpacing,re=x.textHScale*I,ne=x.fontMatrix||n.FONT_IDENTITY_MATRIX,se=H.length,fe=x.textRenderingMode===n.TextRenderingMode.INVISIBLE,he,Te,Ie,we;if(!(fe||O===0)){for(this._cachedScaleForStroking=null,this._cachedGetSinglePixelWidth=null,R.save(),R.transform.apply(R,x.textMatrix),R.translate(x.x,x.y),R.scale(re,I),he=0;he<se;++he){if(Te=H[he],typeof Te=="number"){we=U*Te*O/1e3,this.ctx.translate(we,0),x.x+=we*re;continue}let ye=(Te.isSpace?Z:0)+z,oe=T.charProcOperatorList[Te.operatorListId];if(!oe){(0,n.warn)(`Type3 character "${Te.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=Te,this.save(),R.scale(O,O),R.transform.apply(R,ne),this.executeOperatorList(oe),this.restore()),Ie=n.Util.applyTransform([Te.width,0],ne)[0]*O+ye,R.translate(Ie,0),x.x+=Ie*re}R.restore(),this.processingType3=null}}setCharWidth(H,R){}setCharWidthAndBounds(H,R,x,T,O,I){this.ctx.rect(x,T,O-x,I-T),this.ctx.clip(),this.endPath()}getColorN_Pattern(H){let R;if(H[0]==="TilingPattern"){let x=H[1],T=this.baseTransform||this.ctx.mozCurrentTransform.slice(),O={createCanvasGraphics:I=>new ce(I,this.commonObjs,this.objs,this.canvasFactory)};R=new i.TilingPattern(H,x,this.ctx,O,T)}else R=this._getPattern(H[1],H[2]);return R}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(H,R,x){var O;let T=((O=this.selectColor)==null?void 0:O.call(this,H,R,x))||n.Util.makeHexColor(H,R,x);this.ctx.strokeStyle=T,this.current.strokeColor=T}setFillRGBColor(H,R,x){var O;let T=((O=this.selectColor)==null?void 0:O.call(this,H,R,x))||n.Util.makeHexColor(H,R,x);this.ctx.fillStyle=T,this.current.fillColor=T,this.current.patternFill=!1}_getPattern(H,R=null){let x;return this.cachedPatterns.has(H)?x=this.cachedPatterns.get(H):(x=(0,i.getShadingPattern)(this.objs.get(H)),this.cachedPatterns.set(H,x)),R&&(x.matrix=R),x}shadingFill(H){if(!this.contentVisible)return;let R=this.ctx;this.save();let x=this._getPattern(H);R.fillStyle=x.getPattern(R,this,R.mozCurrentTransformInverse,i.PathType.SHADING);let T=R.mozCurrentTransformInverse;if(T){let O=R.canvas,I=O.width,U=O.height,z=n.Util.applyTransform([0,0],T),Z=n.Util.applyTransform([0,U],T),re=n.Util.applyTransform([I,0],T),ne=n.Util.applyTransform([I,U],T),se=Math.min(z[0],Z[0],re[0],ne[0]),fe=Math.min(z[1],Z[1],re[1],ne[1]),he=Math.max(z[0],Z[0],re[0],ne[0]),Te=Math.max(z[1],Z[1],re[1],ne[1]);this.ctx.fillRect(se,fe,he-se,Te-fe)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){(0,n.unreachable)("Should not call beginInlineImage")}beginImageData(){(0,n.unreachable)("Should not call beginImageData")}paintFormXObjectBegin(H,R){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),Array.isArray(H)&&H.length===6&&this.transform.apply(this,H),this.baseTransform=this.ctx.mozCurrentTransform,R)){let x=R[2]-R[0],T=R[3]-R[1];this.ctx.rect(R[0],R[1],x,T),this.current.updateRectMinMax(this.ctx.mozCurrentTransform,R),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(H){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);let R=this.ctx;H.isolated||(0,n.info)("TODO: Support non-isolated groups."),H.knockout&&(0,n.warn)("Knockout groups not supported.");let x=R.mozCurrentTransform;if(H.matrix&&R.transform.apply(R,H.matrix),!H.bbox)throw new Error("Bounding box is required.");let T=n.Util.getAxialAlignedBoundingBox(H.bbox,R.mozCurrentTransform),O=[0,0,R.canvas.width,R.canvas.height];T=n.Util.intersect(T,O)||[0,0,0,0];let I=Math.floor(T[0]),U=Math.floor(T[1]),z=Math.max(Math.ceil(T[2])-I,1),Z=Math.max(Math.ceil(T[3])-U,1),re=1,ne=1;z>y&&(re=z/y,z=y),Z>y&&(ne=Z/y,Z=y),this.current.startNewPathAndClipBox([0,0,z,Z]);let se="groupAt"+this.groupLevel;H.smask&&(se+="_smask_"+this.smaskCounter++%2);let fe=this.cachedCanvases.getCanvas(se,z,Z,!0),he=fe.context;he.scale(1/re,1/ne),he.translate(-I,-U),he.transform.apply(he,x),H.smask?this.smaskStack.push({canvas:fe.canvas,context:he,offsetX:I,offsetY:U,scaleX:re,scaleY:ne,subtype:H.smask.subtype,backdrop:H.smask.backdrop,transferMap:H.smask.transferMap||null,startTransformInverse:null}):(R.setTransform(1,0,0,1,0,0),R.translate(I,U),R.scale(re,ne),R.save()),N(R,he),this.ctx=he,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(R),this.groupLevel++}endGroup(H){if(!this.contentVisible)return;this.groupLevel--;let R=this.ctx,x=this.groupStack.pop();if(this.ctx=x,this.ctx.imageSmoothingEnabled=!1,H.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();let T=this.ctx.mozCurrentTransform;this.restore(),this.ctx.save(),this.ctx.setTransform.apply(this.ctx,T);let O=n.Util.getAxialAlignedBoundingBox([0,0,R.canvas.width,R.canvas.height],T);this.ctx.drawImage(R.canvas,0,0),this.ctx.restore(),this.compose(O)}}beginAnnotations(){this.save(),this.baseTransform&&this.ctx.setTransform.apply(this.ctx,this.baseTransform)}endAnnotations(){this.restore()}beginAnnotation(H,R,x,T,O){if(this.save(),Array.isArray(R)&&R.length===4){let I=R[2]-R[0],U=R[3]-R[1];if(O&&this.annotationCanvasMap){x=x.slice(),x[4]-=R[0],x[5]-=R[1],R=R.slice(),R[0]=R[1]=0,R[2]=I,R[3]=U;let[z,Z]=n.Util.singularValueDecompose2dScale(this.ctx.mozCurrentTransform),{viewportScale:re}=this,ne=Math.ceil(I*this.outputScaleX*re),se=Math.ceil(U*this.outputScaleY*re);this.annotationCanvas=this.canvasFactory.create(ne,se);let{canvas:fe,context:he}=this.annotationCanvas,Te=`var(--zoom-factor) * ${c.PixelsPerInch.PDF_TO_CSS_UNITS}`;fe.style.width=`calc(${I}px * ${Te})`,fe.style.height=`calc(${U}px * ${Te})`,this.annotationCanvasMap.set(H,fe),this.annotationCanvas.savedCtx=this.ctx,this.ctx=he,this.ctx.setTransform(z,0,0,-Z,0,U*Z),w(this.ctx),D(this.ctx,this.foregroundColor)}else D(this.ctx,this.foregroundColor),this.ctx.rect(R[0],R[1],I,U),this.ctx.clip(),this.endPath()}this.current=new E(this.ctx.canvas.width,this.ctx.canvas.height),this.transform.apply(this,x),this.transform.apply(this,T)}endAnnotation(){this.annotationCanvas&&(this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas),this.restore()}paintImageMaskXObject(H){if(!this.contentVisible)return;let R=H.count;H=this.getObject(H.data,H),H.count=R;let x=this.ctx,T=this.processingType3;if(T&&(T.compiled===void 0&&(T.compiled=b(H)),T.compiled)){T.compiled(x);return}let O=this._createMaskCanvas(H),I=O.canvas;x.save(),x.setTransform(1,0,0,1,0,0),x.drawImage(I,O.offsetX,O.offsetY),x.restore(),this.compose()}paintImageMaskXObjectRepeat(H,R,x=0,T=0,O,I){if(!this.contentVisible)return;H=this.getObject(H.data,H);let U=this.ctx;U.save();let z=U.mozCurrentTransform;U.transform(R,x,T,O,0,0);let Z=this._createMaskCanvas(H);U.setTransform(1,0,0,1,0,0);for(let re=0,ne=I.length;re<ne;re+=2){let se=n.Util.transform(z,[R,x,T,O,I[re],I[re+1]]),[fe,he]=n.Util.applyTransform([0,0],se);U.drawImage(Z.canvas,fe,he)}U.restore(),this.compose()}paintImageMaskXObjectGroup(H){if(!this.contentVisible)return;let R=this.ctx,x=this.current.fillColor,T=this.current.patternFill;for(let O=0,I=H.length;O<I;O++){let U=H[O],z=U.width,Z=U.height,re=this.cachedCanvases.getCanvas("maskCanvas",z,Z,!1),ne=re.context;ne.save(),P(ne,U),ne.globalCompositeOperation="source-in",ne.fillStyle=T?x.getPattern(ne,this,R.mozCurrentTransformInverse,i.PathType.FILL):x,ne.fillRect(0,0,z,Z),ne.restore(),R.save(),R.transform.apply(R,U.transform),R.scale(1,-1),C(R,re.canvas,0,0,z,Z,0,-1,1,1),R.restore()}this.compose()}paintImageXObject(H){if(!this.contentVisible)return;let R=this.getObject(H);if(!R){(0,n.warn)("Dependent image isn't ready yet");return}this.paintInlineImageXObject(R)}paintImageXObjectRepeat(H,R,x,T){if(!this.contentVisible)return;let O=this.getObject(H);if(!O){(0,n.warn)("Dependent image isn't ready yet");return}let I=O.width,U=O.height,z=[];for(let Z=0,re=T.length;Z<re;Z+=2)z.push({transform:[R,0,0,x,T[Z],T[Z+1]],x:0,y:0,w:I,h:U});this.paintInlineImageXObjectGroup(O,z)}paintInlineImageXObject(H){if(!this.contentVisible)return;let R=H.width,x=H.height,T=this.ctx;this.save(),T.scale(1/R,-1/x);let O;if(typeof HTMLElement=="function"&&H instanceof HTMLElement||!H.data)O=H;else{let Z=this.cachedCanvases.getCanvas("inlineImage",R,x,!1),re=Z.context;k(re,H,this.current.transferMaps),O=Z.canvas}let I=this._scaleImage(O,T.mozCurrentTransformInverse);T.imageSmoothingEnabled=Y(T.mozCurrentTransform,H.interpolate);let[U,z]=C(T,I.img,0,0,I.paintWidth,I.paintHeight,0,-x,R,x);if(this.imageLayer){let Z=this.getCanvasPosition(0,-x);this.imageLayer.appendImage({imgData:H,left:Z[0],top:Z[1],width:U,height:z})}this.compose(),this.restore()}paintInlineImageXObjectGroup(H,R){if(!this.contentVisible)return;let x=this.ctx,T=H.width,O=H.height,I=this.cachedCanvases.getCanvas("inlineImage",T,O,!1),U=I.context;k(U,H,this.current.transferMaps);for(let z=0,Z=R.length;z<Z;z++){let re=R[z];if(x.save(),x.transform.apply(x,re.transform),x.scale(1,-1),C(x,I.canvas,re.x,re.y,re.w,re.h,0,-1,1,1),this.imageLayer){let ne=this.getCanvasPosition(re.x,re.y);this.imageLayer.appendImage({imgData:H,left:ne[0],top:ne[1],width:T,height:O})}x.restore()}this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(H){}markPointProps(H,R){}beginMarkedContent(H){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(H,R){H==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(R)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(H){let R=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(H);let x=this.ctx;this.pendingClip&&(R||(this.pendingClip===ve?x.clip("evenodd"):x.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),x.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){let H=this.ctx.mozCurrentTransform;if(H[1]===0&&H[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(H[0]),Math.abs(H[3]));else{let R=Math.abs(H[0]*H[3]-H[2]*H[1]),x=Math.hypot(H[0],H[2]),T=Math.hypot(H[1],H[3]);this._cachedGetSinglePixelWidth=Math.max(x,T)/R}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(!this._cachedScaleForStroking){let{lineWidth:H}=this.current,R=this.ctx.mozCurrentTransform,x,T;if(R[1]===0&&R[2]===0){let O=Math.abs(R[0]),I=Math.abs(R[3]);if(H===0)x=1/O,T=1/I;else{let U=O*H,z=I*H;x=U<1?1/U:1,T=z<1?1/z:1}}else{let O=Math.abs(R[0]*R[3]-R[2]*R[1]),I=Math.hypot(R[0],R[1]),U=Math.hypot(R[2],R[3]);if(H===0)x=U/O,T=I/O;else{let z=H*O;x=U>z?U/z:1,T=I>z?I/z:1}}this._cachedScaleForStroking=[x,T]}return this._cachedScaleForStroking}rescaleAndStroke(H){let{ctx:R}=this,{lineWidth:x}=this.current,[T,O]=this.getScaleForStroking();if(R.lineWidth=x||1,T===1&&O===1){R.stroke();return}let I,U,z;H&&(I=R.mozCurrentTransform.slice(),U=R.getLineDash().slice(),z=R.lineDashOffset),R.scale(T,O);let Z=Math.max(T,O);R.setLineDash(R.getLineDash().map(re=>re/Z)),R.lineDashOffset/=Z,R.stroke(),H&&(R.setTransform(...I),R.setLineDash(U),R.lineDashOffset=z)}getCanvasPosition(H,R){let x=this.ctx.mozCurrentTransform;return[x[0]*H+x[2]*R+x[4],x[1]*H+x[3]*R+x[5]]}isContentVisible(){for(let H=this.markedContentStack.length-1;H>=0;H--)if(!this.markedContentStack[H].visible)return!1;return!0}}e.CanvasGraphics=ce;for(let W in n.OPS)ce.prototype[W]!==void 0&&(ce.prototype[n.OPS[W]]=ce.prototype[W])},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TilingPattern=e.PathType=void 0,e.getShadingPattern=v;var n=t(1),i=t(3);let o={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};e.PathType=o;function s(l,p){if(!p||i.isNodeJS)return;let w=p[2]-p[0],A=p[3]-p[1],C=new Path2D;C.rect(p[0],p[1],w,A),l.clip(C)}class c{constructor(){this.constructor===c&&(0,n.unreachable)("Cannot initialize BaseShadingPattern.")}getPattern(){(0,n.unreachable)("Abstract method `getPattern` called.")}}class f extends c{constructor(p){super(),this._type=p[1],this._bbox=p[2],this._colorStops=p[3],this._p0=p[4],this._p1=p[5],this._r0=p[6],this._r1=p[7],this.matrix=null}_createGradient(p){let w;this._type==="axial"?w=p.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(w=p.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(let A of this._colorStops)w.addColorStop(A[0],A[1]);return w}getPattern(p,w,A,C){let b;if(C===o.STROKE||C===o.FILL){let E=w.current.getClippedPathBoundingBox(C,p.mozCurrentTransform)||[0,0,0,0],k=Math.ceil(E[2]-E[0])||1,P=Math.ceil(E[3]-E[1])||1,N=w.cachedCanvases.getCanvas("pattern",k,P,!0),D=N.context;D.clearRect(0,0,D.canvas.width,D.canvas.height),D.beginPath(),D.rect(0,0,D.canvas.width,D.canvas.height),D.translate(-E[0],-E[1]),A=n.Util.transform(A,[1,0,0,1,E[0],E[1]]),D.transform.apply(D,w.baseTransform),this.matrix&&D.transform.apply(D,this.matrix),s(D,this._bbox),D.fillStyle=this._createGradient(D),D.fill(),b=p.createPattern(N.canvas,"no-repeat");let F=new DOMMatrix(A);try{b.setTransform(F)}catch(B){(0,n.warn)(`RadialAxialShadingPattern.getPattern: "${B==null?void 0:B.message}".`)}}else s(p,this._bbox),b=this._createGradient(p);return b}}function u(l,p,w,A,C,b,E,k){let P=p.coords,N=p.colors,D=l.data,F=l.width*4,B;P[w+1]>P[A+1]&&(B=w,w=A,A=B,B=b,b=E,E=B),P[A+1]>P[C+1]&&(B=A,A=C,C=B,B=E,E=k,k=B),P[w+1]>P[A+1]&&(B=w,w=A,A=B,B=b,b=E,E=B);let V=(P[w]+p.offsetX)*p.scaleX,q=(P[w+1]+p.offsetY)*p.scaleY,G=(P[A]+p.offsetX)*p.scaleX,Y=(P[A+1]+p.offsetY)*p.scaleY,X=(P[C]+p.offsetX)*p.scaleX,Q=(P[C+1]+p.offsetY)*p.scaleY;if(q>=Q)return;let le=N[b],ve=N[b+1],ce=N[b+2],W=N[E],H=N[E+1],R=N[E+2],x=N[k],T=N[k+1],O=N[k+2],I=Math.round(q),U=Math.round(Q),z,Z,re,ne,se,fe,he,Te;for(let Ie=I;Ie<=U;Ie++){if(Ie<Y){let xe;Ie<q?xe=0:xe=(q-Ie)/(q-Y),z=V-(V-G)*xe,Z=le-(le-W)*xe,re=ve-(ve-H)*xe,ne=ce-(ce-R)*xe}else{let xe;Ie>Q?xe=1:Y===Q?xe=0:xe=(Y-Ie)/(Y-Q),z=G-(G-X)*xe,Z=W-(W-x)*xe,re=H-(H-T)*xe,ne=R-(R-O)*xe}let we;Ie<q?we=0:Ie>Q?we=1:we=(q-Ie)/(q-Q),se=V-(V-X)*we,fe=le-(le-x)*we,he=ve-(ve-T)*we,Te=ce-(ce-O)*we;let ye=Math.round(Math.min(z,se)),oe=Math.round(Math.max(z,se)),Ce=F*Ie+ye*4;for(let xe=ye;xe<=oe;xe++)we=(z-xe)/(z-se),we<0?we=0:we>1&&(we=1),D[Ce++]=Z-(Z-fe)*we|0,D[Ce++]=re-(re-he)*we|0,D[Ce++]=ne-(ne-Te)*we|0,D[Ce++]=255}}function y(l,p,w){let A=p.coords,C=p.colors,b,E;switch(p.type){case"lattice":let k=p.verticesPerRow,P=Math.floor(A.length/k)-1,N=k-1;for(b=0;b<P;b++){let D=b*k;for(let F=0;F<N;F++,D++)u(l,w,A[D],A[D+1],A[D+k],C[D],C[D+1],C[D+k]),u(l,w,A[D+k+1],A[D+1],A[D+k],C[D+k+1],C[D+1],C[D+k])}break;case"triangles":for(b=0,E=A.length;b<E;b+=3)u(l,w,A[b],A[b+1],A[b+2],C[b],C[b+1],C[b+2]);break;default:throw new Error("illegal figure")}}class m extends c{constructor(p){super(),this._coords=p[2],this._colors=p[3],this._figures=p[4],this._bounds=p[5],this._bbox=p[7],this._background=p[8],this.matrix=null}_createMeshCanvas(p,w,A){let k=Math.floor(this._bounds[0]),P=Math.floor(this._bounds[1]),N=Math.ceil(this._bounds[2])-k,D=Math.ceil(this._bounds[3])-P,F=Math.min(Math.ceil(Math.abs(N*p[0]*1.1)),3e3),B=Math.min(Math.ceil(Math.abs(D*p[1]*1.1)),3e3),V=N/F,q=D/B,G={coords:this._coords,colors:this._colors,offsetX:-k,offsetY:-P,scaleX:1/V,scaleY:1/q},Y=F+2*2,X=B+2*2,Q=A.getCanvas("mesh",Y,X,!1),le=Q.context,ve=le.createImageData(F,B);if(w){let W=ve.data;for(let H=0,R=W.length;H<R;H+=4)W[H]=w[0],W[H+1]=w[1],W[H+2]=w[2],W[H+3]=255}for(let W of this._figures)y(ve,W,G);return le.putImageData(ve,2,2),{canvas:Q.canvas,offsetX:k-2*V,offsetY:P-2*q,scaleX:V,scaleY:q}}getPattern(p,w,A,C){s(p,this._bbox);let b;if(C===o.SHADING)b=n.Util.singularValueDecompose2dScale(p.mozCurrentTransform);else if(b=n.Util.singularValueDecompose2dScale(w.baseTransform),this.matrix){let k=n.Util.singularValueDecompose2dScale(this.matrix);b=[b[0]*k[0],b[1]*k[1]]}let E=this._createMeshCanvas(b,C===o.SHADING?null:this._background,w.cachedCanvases);return C!==o.SHADING&&(p.setTransform.apply(p,w.baseTransform),this.matrix&&p.transform.apply(p,this.matrix)),p.translate(E.offsetX,E.offsetY),p.scale(E.scaleX,E.scaleY),p.createPattern(E.canvas,"no-repeat")}}class _ extends c{getPattern(){return"hotpink"}}function v(l){switch(l[0]){case"RadialAxial":return new f(l);case"Mesh":return new m(l);case"Dummy":return new _}throw new Error(`Unknown IR type: ${l[0]}`)}let g={COLORED:1,UNCOLORED:2};class h{static get MAX_PATTERN_SIZE(){return(0,n.shadow)(this,"MAX_PATTERN_SIZE",3e3)}constructor(p,w,A,C,b){this.operatorList=p[2],this.matrix=p[3]||[1,0,0,1,0,0],this.bbox=p[4],this.xstep=p[5],this.ystep=p[6],this.paintType=p[7],this.tilingType=p[8],this.color=w,this.ctx=A,this.canvasGraphicsFactory=C,this.baseTransform=b}createPatternCanvas(p){let w=this.operatorList,A=this.bbox,C=this.xstep,b=this.ystep,E=this.paintType,k=this.tilingType,P=this.color,N=this.canvasGraphicsFactory;(0,n.info)("TilingType: "+k);let D=A[0],F=A[1],B=A[2],V=A[3],q=n.Util.singularValueDecompose2dScale(this.matrix),G=n.Util.singularValueDecompose2dScale(this.baseTransform),Y=[q[0]*G[0],q[1]*G[1]],X=this.getSizeAndScale(C,this.ctx.canvas.width,Y[0]),Q=this.getSizeAndScale(b,this.ctx.canvas.height,Y[1]),le=p.cachedCanvases.getCanvas("pattern",X.size,Q.size,!0),ve=le.context,ce=N.createCanvasGraphics(ve);ce.groupLevel=p.groupLevel,this.setFillAndStrokeStyleToContext(ce,E,P);let W=D,H=F,R=B,x=V;return D<0&&(W=0,R+=Math.abs(D)),F<0&&(H=0,x+=Math.abs(F)),ve.translate(-(X.scale*W),-(Q.scale*H)),ce.transform(X.scale,0,0,Q.scale,0,0),ve.save(),this.clipBbox(ce,W,H,R,x),ce.baseTransform=ce.ctx.mozCurrentTransform.slice(),ce.executeOperatorList(w),ce.endDrawing(),{canvas:le.canvas,scaleX:X.scale,scaleY:Q.scale,offsetX:W,offsetY:H}}getSizeAndScale(p,w,A){p=Math.abs(p);let C=Math.max(h.MAX_PATTERN_SIZE,w),b=Math.ceil(p*A);return b>=C?b=C:A=b/p,{scale:A,size:b}}clipBbox(p,w,A,C,b){let E=C-w,k=b-A;p.ctx.rect(w,A,E,k),p.current.updateRectMinMax(p.ctx.mozCurrentTransform,[w,A,C,b]),p.clip(),p.endPath()}setFillAndStrokeStyleToContext(p,w,A){let C=p.ctx,b=p.current;switch(w){case g.COLORED:let E=this.ctx;C.fillStyle=E.fillStyle,C.strokeStyle=E.strokeStyle,b.fillColor=E.fillStyle,b.strokeColor=E.strokeStyle;break;case g.UNCOLORED:let k=n.Util.makeHexColor(A[0],A[1],A[2]);C.fillStyle=k,C.strokeStyle=k,b.fillColor=k,b.strokeColor=k;break;default:throw new n.FormatError(`Unsupported paint type: ${w}`)}}getPattern(p,w,A,C){let b=A;C!==o.SHADING&&(b=n.Util.transform(b,w.baseTransform),this.matrix&&(b=n.Util.transform(b,this.matrix)));let E=this.createPatternCanvas(w),k=new DOMMatrix(b);k=k.translate(E.offsetX,E.offsetY),k=k.scale(1/E.scaleX,1/E.scaleY);let P=p.createPattern(E.canvas,"repeat");try{P.setTransform(k)}catch(N){(0,n.warn)(`TilingPattern.getPattern: "${N==null?void 0:N.message}".`)}return P}}e.TilingPattern=h},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.applyMaskImageData=i;var n=t(1);function i({src:o,srcPos:s=0,dest:c,destPos:f=0,width:u,height:y,inverseDecode:m=!1}){let _=n.FeatureTest.isLittleEndian?4278190080:255,[v,g]=m?[0,_]:[_,0],h=u>>3,l=u&7,p=o.length;c=new Uint32Array(c.buffer);for(let w=0;w<y;w++){for(let C=s+h;s<C;s++){let b=s<p?o[s]:255;c[f++]=b&128?g:v,c[f++]=b&64?g:v,c[f++]=b&32?g:v,c[f++]=b&16?g:v,c[f++]=b&8?g:v,c[f++]=b&4?g:v,c[f++]=b&2?g:v,c[f++]=b&1?g:v}if(l===0)continue;let A=s<p?o[s++]:255;for(let C=0;C<l;C++)c[f++]=A&1<<7-C?g:v}return{srcPos:s,destPos:f}}},(r,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.GlobalWorkerOptions=void 0;let t=Object.create(null);e.GlobalWorkerOptions=t,t.workerPort=t.workerPort===void 0?null:t.workerPort,t.workerSrc=t.workerSrc===void 0?"":t.workerSrc},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MessageHandler=void 0;var n=t(1);let i={UNKNOWN:0,DATA:1,ERROR:2},o={UNKNOWN:0,CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function s(f){switch(f instanceof Error||typeof f=="object"&&f!==null||(0,n.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),f.name){case"AbortException":return new n.AbortException(f.message);case"MissingPDFException":return new n.MissingPDFException(f.message);case"PasswordException":return new n.PasswordException(f.message,f.code);case"UnexpectedResponseException":return new n.UnexpectedResponseException(f.message,f.status);case"UnknownErrorException":return new n.UnknownErrorException(f.message,f.details);default:return new n.UnknownErrorException(f.message,f.toString())}}class c{constructor(u,y,m){this.sourceName=u,this.targetName=y,this.comObj=m,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),this._onComObjOnMessage=_=>{let v=_.data;if(v.targetName!==this.sourceName)return;if(v.stream){this._processStreamMessage(v);return}if(v.callback){let h=v.callbackId,l=this.callbackCapabilities[h];if(!l)throw new Error(`Cannot resolve callback ${h}`);if(delete this.callbackCapabilities[h],v.callback===i.DATA)l.resolve(v.data);else if(v.callback===i.ERROR)l.reject(s(v.reason));else throw new Error("Unexpected callback case");return}let g=this.actionHandler[v.action];if(!g)throw new Error(`Unknown action from worker: ${v.action}`);if(v.callbackId){let h=this.sourceName,l=v.sourceName;new Promise(function(p){p(g(v.data))}).then(function(p){m.postMessage({sourceName:h,targetName:l,callback:i.DATA,callbackId:v.callbackId,data:p})},function(p){m.postMessage({sourceName:h,targetName:l,callback:i.ERROR,callbackId:v.callbackId,reason:s(p)})});return}if(v.streamId){this._createStreamSink(v);return}g(v.data)},m.addEventListener("message",this._onComObjOnMessage)}on(u,y){let m=this.actionHandler;if(m[u])throw new Error(`There is already an actionName called "${u}"`);m[u]=y}send(u,y,m){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:u,data:y},m)}sendWithPromise(u,y,m){let _=this.callbackId++,v=(0,n.createPromiseCapability)();this.callbackCapabilities[_]=v;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:u,callbackId:_,data:y},m)}catch(g){v.reject(g)}return v.promise}sendWithStream(u,y,m,_){let v=this.streamId++,g=this.sourceName,h=this.targetName,l=this.comObj;return new ReadableStream({start:p=>{let w=(0,n.createPromiseCapability)();return this.streamControllers[v]={controller:p,startCall:w,pullCall:null,cancelCall:null,isClosed:!1},l.postMessage({sourceName:g,targetName:h,action:u,streamId:v,data:y,desiredSize:p.desiredSize},_),w.promise},pull:p=>{let w=(0,n.createPromiseCapability)();return this.streamControllers[v].pullCall=w,l.postMessage({sourceName:g,targetName:h,stream:o.PULL,streamId:v,desiredSize:p.desiredSize}),w.promise},cancel:p=>{(0,n.assert)(p instanceof Error,"cancel must have a valid reason");let w=(0,n.createPromiseCapability)();return this.streamControllers[v].cancelCall=w,this.streamControllers[v].isClosed=!0,l.postMessage({sourceName:g,targetName:h,stream:o.CANCEL,streamId:v,reason:s(p)}),w.promise}},m)}_createStreamSink(u){let y=u.streamId,m=this.sourceName,_=u.sourceName,v=this.comObj,g=this,h=this.actionHandler[u.action],l={enqueue(p,w=1,A){if(this.isCancelled)return;let C=this.desiredSize;this.desiredSize-=w,C>0&&this.desiredSize<=0&&(this.sinkCapability=(0,n.createPromiseCapability)(),this.ready=this.sinkCapability.promise),v.postMessage({sourceName:m,targetName:_,stream:o.ENQUEUE,streamId:y,chunk:p},A)},close(){this.isCancelled||(this.isCancelled=!0,v.postMessage({sourceName:m,targetName:_,stream:o.CLOSE,streamId:y}),delete g.streamSinks[y])},error(p){(0,n.assert)(p instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,v.postMessage({sourceName:m,targetName:_,stream:o.ERROR,streamId:y,reason:s(p)}))},sinkCapability:(0,n.createPromiseCapability)(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:u.desiredSize,ready:null};l.sinkCapability.resolve(),l.ready=l.sinkCapability.promise,this.streamSinks[y]=l,new Promise(function(p){p(h(u.data,l))}).then(function(){v.postMessage({sourceName:m,targetName:_,stream:o.START_COMPLETE,streamId:y,success:!0})},function(p){v.postMessage({sourceName:m,targetName:_,stream:o.START_COMPLETE,streamId:y,reason:s(p)})})}_processStreamMessage(u){let y=u.streamId,m=this.sourceName,_=u.sourceName,v=this.comObj,g=this.streamControllers[y],h=this.streamSinks[y];switch(u.stream){case o.START_COMPLETE:u.success?g.startCall.resolve():g.startCall.reject(s(u.reason));break;case o.PULL_COMPLETE:u.success?g.pullCall.resolve():g.pullCall.reject(s(u.reason));break;case o.PULL:if(!h){v.postMessage({sourceName:m,targetName:_,stream:o.PULL_COMPLETE,streamId:y,success:!0});break}h.desiredSize<=0&&u.desiredSize>0&&h.sinkCapability.resolve(),h.desiredSize=u.desiredSize,new Promise(function(l){l(h.onPull&&h.onPull())}).then(function(){v.postMessage({sourceName:m,targetName:_,stream:o.PULL_COMPLETE,streamId:y,success:!0})},function(l){v.postMessage({sourceName:m,targetName:_,stream:o.PULL_COMPLETE,streamId:y,reason:s(l)})});break;case o.ENQUEUE:if((0,n.assert)(g,"enqueue should have stream controller"),g.isClosed)break;g.controller.enqueue(u.chunk);break;case o.CLOSE:if((0,n.assert)(g,"close should have stream controller"),g.isClosed)break;g.isClosed=!0,g.controller.close(),this._deleteStreamController(g,y);break;case o.ERROR:(0,n.assert)(g,"error should have stream controller"),g.controller.error(s(u.reason)),this._deleteStreamController(g,y);break;case o.CANCEL_COMPLETE:u.success?g.cancelCall.resolve():g.cancelCall.reject(s(u.reason)),this._deleteStreamController(g,y);break;case o.CANCEL:if(!h)break;new Promise(function(l){l(h.onCancel&&h.onCancel(s(u.reason)))}).then(function(){v.postMessage({sourceName:m,targetName:_,stream:o.CANCEL_COMPLETE,streamId:y,success:!0})},function(l){v.postMessage({sourceName:m,targetName:_,stream:o.CANCEL_COMPLETE,streamId:y,reason:s(l)})}),h.sinkCapability.reject(s(u.reason)),h.isCancelled=!0,delete this.streamSinks[y];break;default:throw new Error("Unexpected stream case")}}async _deleteStreamController(u,y){await Promise.allSettled([u.startCall&&u.startCall.promise,u.pullCall&&u.pullCall.promise,u.cancelCall&&u.cancelCall.promise]),delete this.streamControllers[y]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}e.MessageHandler=c},(r,e,t)=>{var o,s;Object.defineProperty(e,"__esModule",{value:!0}),e.Metadata=void 0;var n=t(1);class i{constructor({parsedData:f,rawData:u}){Er(this,o,void 0);Er(this,s,void 0);Zi(this,o,f),Zi(this,s,u)}getRaw(){return Lt(this,s)}get(f){return Lt(this,o).get(f)??null}getAll(){return(0,n.objectFromMap)(Lt(this,o))}has(f){return Lt(this,o).has(f)}}o=new WeakMap,s=new WeakMap,e.Metadata=i},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OptionalContentConfig=void 0;var n=t(1);class i{constructor(c,f){this.visible=!0,this.name=c,this.intent=f}}class o{constructor(c){if(this.name=null,this.creator=null,this._order=null,this._groups=new Map,c!==null){this.name=c.name,this.creator=c.creator,this._order=c.order;for(let f of c.groups)this._groups.set(f.id,new i(f.name,f.intent));if(c.baseState==="OFF")for(let f of this._groups)f.visible=!1;for(let f of c.on)this._groups.get(f).visible=!0;for(let f of c.off)this._groups.get(f).visible=!1}}_evaluateVisibilityExpression(c){let f=c.length;if(f<2)return!0;let u=c[0];for(let y=1;y<f;y++){let m=c[y],_;if(Array.isArray(m))_=this._evaluateVisibilityExpression(m);else if(this._groups.has(m))_=this._groups.get(m).visible;else return(0,n.warn)(`Optional content group not found: ${m}`),!0;switch(u){case"And":if(!_)return!1;break;case"Or":if(_)return!0;break;case"Not":return!_;default:return!0}}return u==="And"}isVisible(c){if(this._groups.size===0)return!0;if(!c)return(0,n.warn)("Optional content group not defined."),!0;if(c.type==="OCG")return this._groups.has(c.id)?this._groups.get(c.id).visible:((0,n.warn)(`Optional content group not found: ${c.id}`),!0);if(c.type==="OCMD"){if(c.expression)return this._evaluateVisibilityExpression(c.expression);if(!c.policy||c.policy==="AnyOn"){for(let f of c.ids){if(!this._groups.has(f))return(0,n.warn)(`Optional content group not found: ${f}`),!0;if(this._groups.get(f).visible)return!0}return!1}else if(c.policy==="AllOn"){for(let f of c.ids){if(!this._groups.has(f))return(0,n.warn)(`Optional content group not found: ${f}`),!0;if(!this._groups.get(f).visible)return!1}return!0}else if(c.policy==="AnyOff"){for(let f of c.ids){if(!this._groups.has(f))return(0,n.warn)(`Optional content group not found: ${f}`),!0;if(!this._groups.get(f).visible)return!0}return!1}else if(c.policy==="AllOff"){for(let f of c.ids){if(!this._groups.has(f))return(0,n.warn)(`Optional content group not found: ${f}`),!0;if(this._groups.get(f).visible)return!1}return!0}return(0,n.warn)(`Unknown optional content policy ${c.policy}.`),!0}return(0,n.warn)(`Unknown group type ${c.type}.`),!0}setVisibility(c,f=!0){if(!this._groups.has(c)){(0,n.warn)(`Optional content group not found: ${c}`);return}this._groups.get(c).visible=!!f}getOrder(){return this._groups.size?this._order?this._order.slice():Array.from(this._groups.keys()):null}getGroups(){return this._groups.size>0?(0,n.objectFromMap)(this._groups):null}getGroup(c){return this._groups.get(c)||null}}e.OptionalContentConfig=o},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PDFDataTransportStream=void 0;var n=t(1),i=t(5);class o{constructor(u,y){(0,n.assert)(y,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.'),this._queuedChunks=[],this._progressiveDone=u.progressiveDone||!1,this._contentDispositionFilename=u.contentDispositionFilename||null;let m=u.initialData;if((m==null?void 0:m.length)>0){let _=new Uint8Array(m).buffer;this._queuedChunks.push(_)}this._pdfDataRangeTransport=y,this._isStreamingSupported=!u.disableStream,this._isRangeSupported=!u.disableRange,this._contentLength=u.length,this._fullRequestReader=null,this._rangeReaders=[],this._pdfDataRangeTransport.addRangeListener((_,v)=>{this._onReceiveData({begin:_,chunk:v})}),this._pdfDataRangeTransport.addProgressListener((_,v)=>{this._onProgress({loaded:_,total:v})}),this._pdfDataRangeTransport.addProgressiveReadListener(_=>{this._onReceiveData({chunk:_})}),this._pdfDataRangeTransport.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),this._pdfDataRangeTransport.transportReady()}_onReceiveData(u){let y=new Uint8Array(u.chunk).buffer;if(u.begin===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(y):this._queuedChunks.push(y);else{let m=this._rangeReaders.some(function(_){return _._begin!==u.begin?!1:(_._enqueue(y),!0)});(0,n.assert)(m,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){var u;return((u=this._fullRequestReader)==null?void 0:u._loaded)??0}_onProgress(u){if(u.total===void 0){let y=this._rangeReaders[0];y!=null&&y.onProgress&&y.onProgress({loaded:u.loaded})}else{let y=this._fullRequestReader;y!=null&&y.onProgress&&y.onProgress({loaded:u.loaded,total:u.total})}}_onProgressiveDone(){this._fullRequestReader&&this._fullRequestReader.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(u){let y=this._rangeReaders.indexOf(u);y>=0&&this._rangeReaders.splice(y,1)}getFullReader(){(0,n.assert)(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");let u=this._queuedChunks;return this._queuedChunks=null,new s(this,u,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(u,y){if(y<=this._progressiveDataLength)return null;let m=new c(this,u,y);return this._pdfDataRangeTransport.requestDataRange(u,y),this._rangeReaders.push(m),m}cancelAllRequests(u){this._fullRequestReader&&this._fullRequestReader.cancel(u);for(let y of this._rangeReaders.slice(0))y.cancel(u);this._pdfDataRangeTransport.abort()}}e.PDFDataTransportStream=o;class s{constructor(u,y,m=!1,_=null){this._stream=u,this._done=m||!1,this._filename=(0,i.isPdfFile)(_)?_:null,this._queuedChunks=y||[],this._loaded=0;for(let v of this._queuedChunks)this._loaded+=v.byteLength;this._requests=[],this._headersReady=Promise.resolve(),u._fullRequestReader=this,this.onProgress=null}_enqueue(u){this._done||(this._requests.length>0?this._requests.shift().resolve({value:u,done:!1}):this._queuedChunks.push(u),this._loaded+=u.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let u=(0,n.createPromiseCapability)();return this._requests.push(u),u.promise}cancel(u){this._done=!0;for(let y of this._requests)y.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class c{constructor(u,y,m){this._stream=u,this._begin=y,this._end=m,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(u){if(!this._done){if(this._requests.length===0)this._queuedChunk=u;else{this._requests.shift().resolve({value:u,done:!1});for(let m of this._requests)m.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){let y=this._queuedChunk;return this._queuedChunk=null,{value:y,done:!1}}if(this._done)return{value:void 0,done:!0};let u=(0,n.createPromiseCapability)();return this._requests.push(u),u.promise}cancel(u){this._done=!0;for(let y of this._requests)y.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}},(r,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.XfaText=void 0;class t{static textContent(i){let o=[],s={items:o,styles:Object.create(null)};function c(f){var m;if(!f)return;let u=null,y=f.name;if(y==="#text")u=f.value;else if(t.shouldBuildText(y))(m=f==null?void 0:f.attributes)!=null&&m.textContent?u=f.attributes.textContent:f.value&&(u=f.value);else return;if(u!==null&&o.push({str:u}),!!f.children)for(let _ of f.children)c(_)}return c(i),s}static shouldBuildText(i){return!(i==="textarea"||i==="input"||i==="option"||i==="select")}}e.XfaText=t},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NodeStandardFontDataFactory=e.NodeCanvasFactory=e.NodeCMapReaderFactory=void 0;var n=t(6);let i=function(f){return new Promise((u,y)=>{gf().readFile(f,(_,v)=>{if(_||!v){y(new Error(_));return}u(new Uint8Array(v))})})};class o extends n.BaseCanvasFactory{_createCanvas(u,y){return BC().createCanvas(u,y)}}e.NodeCanvasFactory=o;class s extends n.BaseCMapReaderFactory{_fetchData(u,y){return i(u).then(m=>({cMapData:m,compressionType:y}))}}e.NodeCMapReaderFactory=s;class c extends n.BaseStandardFontDataFactory{_fetchData(u){return i(u)}}e.NodeStandardFontDataFactory=c},(r,e,t)=>{var W,nm;Object.defineProperty(e,"__esModule",{value:!0}),e.AnnotationLayer=void 0;var n=t(1),i=t(5),o=t(8),s=t(21),c=t(22);let f=1e3,u=new WeakSet;function y(R){return{width:R[2]-R[0],height:R[3]-R[1]}}class m{static create(x){switch(x.data.annotationType){case n.AnnotationType.LINK:return new v(x);case n.AnnotationType.TEXT:return new g(x);case n.AnnotationType.WIDGET:switch(x.data.fieldType){case"Tx":return new l(x);case"Btn":return x.data.radioButton?new w(x):x.data.checkBox?new p(x):new A(x);case"Ch":return new C(x)}return new h(x);case n.AnnotationType.POPUP:return new b(x);case n.AnnotationType.FREETEXT:return new k(x);case n.AnnotationType.LINE:return new P(x);case n.AnnotationType.SQUARE:return new N(x);case n.AnnotationType.CIRCLE:return new D(x);case n.AnnotationType.POLYLINE:return new F(x);case n.AnnotationType.CARET:return new V(x);case n.AnnotationType.INK:return new q(x);case n.AnnotationType.POLYGON:return new B(x);case n.AnnotationType.HIGHLIGHT:return new G(x);case n.AnnotationType.UNDERLINE:return new Y(x);case n.AnnotationType.SQUIGGLY:return new X(x);case n.AnnotationType.STRIKEOUT:return new Q(x);case n.AnnotationType.STAMP:return new le(x);case n.AnnotationType.FILEATTACHMENT:return new ve(x);default:return new _(x)}}}class _{constructor(x,{isRenderable:T=!1,ignoreBorder:O=!1,createQuadrilaterals:I=!1}={}){this.isRenderable=T,this.data=x.data,this.layer=x.layer,this.page=x.page,this.viewport=x.viewport,this.linkService=x.linkService,this.downloadManager=x.downloadManager,this.imageResourcesPath=x.imageResourcesPath,this.renderForms=x.renderForms,this.svgFactory=x.svgFactory,this.annotationStorage=x.annotationStorage,this.enableScripting=x.enableScripting,this.hasJSActions=x.hasJSActions,this._fieldObjects=x.fieldObjects,this._mouseState=x.mouseState,T&&(this.container=this._createContainer(O)),I&&(this.quadrilaterals=this._createQuadrilaterals(O))}_createContainer(x=!1){let T=this.data,O=this.page,I=this.viewport,U=document.createElement("section"),{width:z,height:Z}=y(T.rect);U.setAttribute("data-annotation-id",T.id);let re=n.Util.normalizeRect([T.rect[0],O.view[3]-T.rect[1]+O.view[1],T.rect[2],O.view[3]-T.rect[3]+O.view[1]]);if(T.hasOwnCanvas){let ne=I.transform.slice(),[se,fe]=n.Util.singularValueDecompose2dScale(ne);z=Math.ceil(z*se),Z=Math.ceil(Z*fe),re[0]*=se,re[1]*=fe;for(let he=0;he<4;he++)ne[he]=Math.sign(ne[he]);U.style.transform=`matrix(${ne.join(",")})`}else U.style.transform=`matrix(${I.transform.join(",")})`;if(U.style.transformOrigin=`${-re[0]}px ${-re[1]}px`,!x&&T.borderStyle.width>0){U.style.borderWidth=`${T.borderStyle.width}px`,T.borderStyle.style!==n.AnnotationBorderStyleType.UNDERLINE&&(z-=2*T.borderStyle.width,Z-=2*T.borderStyle.width);let ne=T.borderStyle.horizontalCornerRadius,se=T.borderStyle.verticalCornerRadius;if(ne>0||se>0){let he=`${ne}px / ${se}px`;U.style.borderRadius=he}switch(T.borderStyle.style){case n.AnnotationBorderStyleType.SOLID:U.style.borderStyle="solid";break;case n.AnnotationBorderStyleType.DASHED:U.style.borderStyle="dashed";break;case n.AnnotationBorderStyleType.BEVELED:(0,n.warn)("Unimplemented border style: beveled");break;case n.AnnotationBorderStyleType.INSET:(0,n.warn)("Unimplemented border style: inset");break;case n.AnnotationBorderStyleType.UNDERLINE:U.style.borderBottomStyle="solid";break;default:break}T.borderColor||T.color||null?U.style.borderColor=n.Util.makeHexColor(T.color[0]|0,T.color[1]|0,T.color[2]|0):U.style.borderWidth=0}return U.style.left=`${re[0]}px`,U.style.top=`${re[1]}px`,T.hasOwnCanvas?U.style.width=U.style.height="auto":(U.style.width=`${z}px`,U.style.height=`${Z}px`),U}get _commonActions(){let x=(T,O,I)=>{let U=I.detail[T];I.target.style[O]=s.ColorConverters[`${U[0]}_HTML`](U.slice(1))};return(0,n.shadow)(this,"_commonActions",{display:T=>{let O=T.detail.display%2===1;T.target.style.visibility=O?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{hidden:O,print:T.detail.display===0||T.detail.display===3})},print:T=>{this.annotationStorage.setValue(this.data.id,{print:T.detail.print})},hidden:T=>{T.target.style.visibility=T.detail.hidden?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{hidden:T.detail.hidden})},focus:T=>{setTimeout(()=>T.target.focus({preventScroll:!1}),0)},userName:T=>{T.target.title=T.detail.userName},readonly:T=>{T.detail.readonly?T.target.setAttribute("readonly",""):T.target.removeAttribute("readonly")},required:T=>{T.detail.required?T.target.setAttribute("required",""):T.target.removeAttribute("required")},bgColor:T=>{x("bgColor","backgroundColor",T)},fillColor:T=>{x("fillColor","backgroundColor",T)},fgColor:T=>{x("fgColor","color",T)},textColor:T=>{x("textColor","color",T)},borderColor:T=>{x("borderColor","borderColor",T)},strokeColor:T=>{x("strokeColor","borderColor",T)}})}_dispatchEventFromSandbox(x,T){let O=this._commonActions;for(let I of Object.keys(T.detail)){let U=x[I]||O[I];U&&U(T)}}_setDefaultPropertiesFromJS(x){if(!this.enableScripting)return;let T=this.annotationStorage.getRawValue(this.data.id);if(!T)return;let O=this._commonActions;for(let[I,U]of Object.entries(T)){let z=O[I];z&&(z({detail:U,target:x}),delete T[I])}}_createQuadrilaterals(x=!1){if(!this.data.quadPoints)return null;let T=[],O=this.data.rect;for(let I of this.data.quadPoints)this.data.rect=[I[2].x,I[2].y,I[1].x,I[1].y],T.push(this._createContainer(x));return this.data.rect=O,T}_createPopup(x,T){let O=this.container;this.quadrilaterals&&(x=x||this.quadrilaterals,O=this.quadrilaterals[0]),x||(x=document.createElement("div"),x.style.height=O.style.height,x.style.width=O.style.width,O.appendChild(x));let U=new E({container:O,trigger:x,color:T.color,titleObj:T.titleObj,modificationDate:T.modificationDate,contentsObj:T.contentsObj,richText:T.richText,hideWrapper:!0}).render();U.style.left=O.style.width,O.appendChild(U)}_renderQuadrilaterals(x){for(let T of this.quadrilaterals)T.className=x;return this.quadrilaterals}render(){(0,n.unreachable)("Abstract method `AnnotationElement.render` called")}_getElementsByName(x,T=null){let O=[];if(this._fieldObjects){let I=this._fieldObjects[x];if(I)for(let{page:U,id:z,exportValues:Z}of I){if(U===-1||z===T)continue;let re=typeof Z=="string"?Z:null,ne=document.getElementById(z);if(ne&&!u.has(ne)){(0,n.warn)(`_getElementsByName - element not allowed: ${z}`);continue}O.push({id:z,exportValue:re,domElement:ne})}return O}for(let I of document.getElementsByName(x)){let{id:U,exportValue:z}=I;U!==T&&u.has(I)&&O.push({id:U,exportValue:z,domElement:I})}return O}static get platform(){let x=typeof navigator<"u"?navigator.platform:"";return(0,n.shadow)(this,"platform",{isWin:x.includes("Win"),isMac:x.includes("Mac")})}}class v extends _{constructor(x,T=null){let O=!!(x.data.url||x.data.dest||x.data.action||x.data.isTooltipOnly||x.data.resetForm||x.data.actions&&(x.data.actions.Action||x.data.actions["Mouse Up"]||x.data.actions["Mouse Down"]));super(x,{isRenderable:O,ignoreBorder:!!(T!=null&&T.ignoreBorder),createQuadrilaterals:!0})}render(){let{data:x,linkService:T}=this,O=document.createElement("a");if(x.url)T.addLinkAttributes(O,x.url,x.newWindow);else if(x.action)this._bindNamedAction(O,x.action);else if(x.dest)this._bindLink(O,x.dest);else{let I=!1;x.actions&&(x.actions.Action||x.actions["Mouse Up"]||x.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(I=!0,this._bindJSAction(O,x)),x.resetForm?this._bindResetFormAction(O,x.resetForm):I||this._bindLink(O,"")}return this.quadrilaterals?this._renderQuadrilaterals("linkAnnotation").map((I,U)=>{let z=U===0?O:O.cloneNode();return I.appendChild(z),I}):(this.container.className="linkAnnotation",this.container.appendChild(O),this.container)}_bindLink(x,T){x.href=this.linkService.getDestinationHash(T),x.onclick=()=>(T&&this.linkService.goToDestination(T),!1),(T||T==="")&&(x.className="internalLink")}_bindNamedAction(x,T){x.href=this.linkService.getAnchorUrl(""),x.onclick=()=>(this.linkService.executeNamedAction(T),!1),x.className="internalLink"}_bindJSAction(x,T){x.href=this.linkService.getAnchorUrl("");let O=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(let I of Object.keys(T.actions)){let U=O.get(I);U&&(x[U]=()=>{var z;return(z=this.linkService.eventBus)==null||z.dispatch("dispatcheventinsandbox",{source:this,detail:{id:T.id,name:I}}),!1})}x.onclick||(x.onclick=()=>!1),x.className="internalLink"}_bindResetFormAction(x,T){let O=x.onclick;if(O||(x.href=this.linkService.getAnchorUrl("")),x.className="internalLink",!this._fieldObjects){(0,n.warn)('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),O||(x.onclick=()=>!1);return}x.onclick=()=>{var se;O&&O();let{fields:I,refs:U,include:z}=T,Z=[];if(I.length!==0||U.length!==0){let fe=new Set(U);for(let he of I){let Te=this._fieldObjects[he]||[];for(let{id:Ie}of Te)fe.add(Ie)}for(let he of Object.values(this._fieldObjects))for(let Te of he)fe.has(Te.id)===z&&Z.push(Te)}else for(let fe of Object.values(this._fieldObjects))Z.push(...fe);let re=this.annotationStorage,ne=[];for(let fe of Z){let{id:he}=fe;switch(ne.push(he),fe.type){case"text":{let Ie=fe.defaultValue||"";re.setValue(he,{value:Ie});break}case"checkbox":case"radiobutton":{let Ie=fe.defaultValue===fe.exportValues;re.setValue(he,{value:Ie});break}case"combobox":case"listbox":{let Ie=fe.defaultValue||"";re.setValue(he,{value:Ie});break}default:continue}let Te=document.getElementById(he);!Te||!u.has(Te)||Te.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((se=this.linkService.eventBus)==null||se.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:ne,name:"ResetForm"}})),!1}}}class g extends _{constructor(x){var O,I,U;let T=!!(x.data.hasPopup||(O=x.data.titleObj)!=null&&O.str||(I=x.data.contentsObj)!=null&&I.str||(U=x.data.richText)!=null&&U.str);super(x,{isRenderable:T})}render(){this.container.className="textAnnotation";let x=document.createElement("img");return x.style.height=this.container.style.height,x.style.width=this.container.style.width,x.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",x.alt="[{{type}} Annotation]",x.dataset.l10nId="text_annotation_type",x.dataset.l10nArgs=JSON.stringify({type:this.data.name}),this.data.hasPopup||this._createPopup(x,this.data),this.container.appendChild(x),this.container}}class h extends _{render(){return this.data.alternativeText&&(this.container.title=this.data.alternativeText),this.container}_getKeyModifier(x){let{isWin:T,isMac:O}=_.platform;return T&&x.ctrlKey||O&&x.metaKey}_setEventListener(x,T,O,I){T.includes("mouse")?x.addEventListener(T,U=>{var z;(z=this.linkService.eventBus)==null||z.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:O,value:I(U),shift:U.shiftKey,modifier:this._getKeyModifier(U)}})}):x.addEventListener(T,U=>{var z;(z=this.linkService.eventBus)==null||z.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:O,value:I(U)}})})}_setEventListeners(x,T,O){var I;for(let[U,z]of T)(z==="Action"||(I=this.data.actions)!=null&&I[z])&&this._setEventListener(x,U,z,O)}_setBackgroundColor(x){let T=this.data.backgroundColor||null;x.style.backgroundColor=T===null?"transparent":n.Util.makeHexColor(T[0],T[1],T[2])}}class l extends h{constructor(x){let T=x.renderForms||!x.data.hasAppearance&&!!x.data.fieldValue;super(x,{isRenderable:T})}setPropertyOnSiblings(x,T,O,I){let U=this.annotationStorage;for(let z of this._getElementsByName(x.name,x.id))z.domElement&&(z.domElement[T]=O),U.setValue(z.id,{[I]:O})}render(){var I;let x=this.annotationStorage,T=this.data.id;this.container.className="textWidgetAnnotation";let O=null;if(this.renderForms){let U=x.getValue(T,{value:this.data.fieldValue}),z=U.formattedValue||U.value||"",Z={userValue:null,formattedValue:null,valueOnFocus:""};this.data.multiLine?(O=document.createElement("textarea"),O.textContent=z):(O=document.createElement("input"),O.type="text",O.setAttribute("value",z)),u.add(O),O.disabled=this.data.readOnly,O.name=this.data.fieldName,O.tabIndex=f,Z.userValue=z,O.setAttribute("id",T),O.addEventListener("input",ne=>{x.setValue(T,{value:ne.target.value}),this.setPropertyOnSiblings(O,"value",ne.target.value,"value")}),O.addEventListener("resetform",ne=>{let se=this.data.defaultFieldValue??"";O.value=Z.userValue=se,Z.formattedValue=null});let re=ne=>{let{formattedValue:se}=Z;se!=null&&(ne.target.value=se),ne.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){O.addEventListener("focus",se=>{Z.userValue&&(se.target.value=Z.userValue),Z.valueOnFocus=se.target.value}),O.addEventListener("updatefromsandbox",se=>{let fe={value(he){Z.userValue=he.detail.value??"",x.setValue(T,{value:Z.userValue.toString()}),he.target.value=Z.userValue},formattedValue(he){let{formattedValue:Te}=he.detail;Z.formattedValue=Te,Te!=null&&he.target!==document.activeElement&&(he.target.value=Te),x.setValue(T,{formattedValue:Te})},selRange(he){he.target.setSelectionRange(...he.detail.selRange)}};this._dispatchEventFromSandbox(fe,se)}),O.addEventListener("keydown",se=>{var Te;let fe=-1;if(se.key==="Escape"?fe=0:se.key==="Enter"?fe=2:se.key==="Tab"&&(fe=3),fe===-1)return;let{value:he}=se.target;Z.valueOnFocus!==he&&(Z.userValue=he,(Te=this.linkService.eventBus)==null||Te.dispatch("dispatcheventinsandbox",{source:this,detail:{id:T,name:"Keystroke",value:he,willCommit:!0,commitKey:fe,selStart:se.target.selectionStart,selEnd:se.target.selectionEnd}}))});let ne=re;re=null,O.addEventListener("blur",se=>{var he;let{value:fe}=se.target;Z.userValue=fe,this._mouseState.isDown&&Z.valueOnFocus!==fe&&((he=this.linkService.eventBus)==null||he.dispatch("dispatcheventinsandbox",{source:this,detail:{id:T,name:"Keystroke",value:fe,willCommit:!0,commitKey:1,selStart:se.target.selectionStart,selEnd:se.target.selectionEnd}})),ne(se)}),(I=this.data.actions)!=null&&I.Keystroke&&O.addEventListener("beforeinput",se=>{var Ce;let{data:fe,target:he}=se,{value:Te,selectionStart:Ie,selectionEnd:we}=he,ye=Ie,oe=we;switch(se.inputType){case"deleteWordBackward":{let xe=Te.substring(0,Ie).match(/\w*[^\w]*$/);xe&&(ye-=xe[0].length);break}case"deleteWordForward":{let xe=Te.substring(Ie).match(/^[^\w]*\w*/);xe&&(oe+=xe[0].length);break}case"deleteContentBackward":Ie===we&&(ye-=1);break;case"deleteContentForward":Ie===we&&(oe+=1);break}se.preventDefault(),(Ce=this.linkService.eventBus)==null||Ce.dispatch("dispatcheventinsandbox",{source:this,detail:{id:T,name:"Keystroke",value:Te,change:fe||"",willCommit:!1,selStart:ye,selEnd:oe}})}),this._setEventListeners(O,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],se=>se.target.value)}if(re&&O.addEventListener("blur",re),this.data.maxLen!==null&&(O.maxLength=this.data.maxLen),this.data.comb){let se=(this.data.rect[2]-this.data.rect[0])/this.data.maxLen;O.classList.add("comb"),O.style.letterSpacing=`calc(${se}px - 1ch)`}}else O=document.createElement("div"),O.textContent=this.data.fieldValue,O.style.verticalAlign="middle",O.style.display="table-cell";return this._setTextStyle(O),this._setBackgroundColor(O),this._setDefaultPropertiesFromJS(O),this.container.appendChild(O),this.container}_setTextStyle(x){let T=["left","center","right"],{fontSize:O,fontColor:I}=this.data.defaultAppearanceData,U=x.style;O&&(U.fontSize=`${O}px`),U.color=n.Util.makeHexColor(I[0],I[1],I[2]),this.data.textAlignment!==null&&(U.textAlign=T[this.data.textAlignment])}}class p extends h{constructor(x){super(x,{isRenderable:x.renderForms})}render(){let x=this.annotationStorage,T=this.data,O=T.id,I=x.getValue(O,{value:T.exportValue===T.fieldValue}).value;typeof I=="string"&&(I=I!=="Off",x.setValue(O,{value:I})),this.container.className="buttonWidgetAnnotation checkBox";let U=document.createElement("input");return u.add(U),U.disabled=T.readOnly,U.type="checkbox",U.name=T.fieldName,I&&U.setAttribute("checked",!0),U.setAttribute("id",O),U.setAttribute("exportValue",T.exportValue),U.tabIndex=f,U.addEventListener("change",z=>{let{name:Z,checked:re}=z.target;for(let ne of this._getElementsByName(Z,O)){let se=re&&ne.exportValue===T.exportValue;ne.domElement&&(ne.domElement.checked=se),x.setValue(ne.id,{value:se})}x.setValue(O,{value:re})}),U.addEventListener("resetform",z=>{let Z=T.defaultFieldValue||"Off";z.target.checked=Z===T.exportValue}),this.enableScripting&&this.hasJSActions&&(U.addEventListener("updatefromsandbox",z=>{let Z={value(re){re.target.checked=re.detail.value!=="Off",x.setValue(O,{value:re.target.checked})}};this._dispatchEventFromSandbox(Z,z)}),this._setEventListeners(U,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],z=>z.target.checked)),this._setBackgroundColor(U),this._setDefaultPropertiesFromJS(U),this.container.appendChild(U),this.container}}class w extends h{constructor(x){super(x,{isRenderable:x.renderForms})}render(){this.container.className="buttonWidgetAnnotation radioButton";let x=this.annotationStorage,T=this.data,O=T.id,I=x.getValue(O,{value:T.fieldValue===T.buttonValue}).value;typeof I=="string"&&(I=I!==T.buttonValue,x.setValue(O,{value:I}));let U=document.createElement("input");if(u.add(U),U.disabled=T.readOnly,U.type="radio",U.name=T.fieldName,I&&U.setAttribute("checked",!0),U.setAttribute("id",O),U.tabIndex=f,U.addEventListener("change",z=>{let{name:Z,checked:re}=z.target;for(let ne of this._getElementsByName(Z,O))x.setValue(ne.id,{value:!1});x.setValue(O,{value:re})}),U.addEventListener("resetform",z=>{let Z=T.defaultFieldValue;z.target.checked=Z!=null&&Z===T.buttonValue}),this.enableScripting&&this.hasJSActions){let z=T.buttonValue;U.addEventListener("updatefromsandbox",Z=>{let re={value:ne=>{let se=z===ne.detail.value;for(let fe of this._getElementsByName(ne.target.name)){let he=se&&fe.id===O;fe.domElement&&(fe.domElement.checked=he),x.setValue(fe.id,{value:he})}}};this._dispatchEventFromSandbox(re,Z)}),this._setEventListeners(U,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],Z=>Z.target.checked)}return this._setBackgroundColor(U),this._setDefaultPropertiesFromJS(U),this.container.appendChild(U),this.container}}class A extends v{constructor(x){super(x,{ignoreBorder:x.data.hasAppearance})}render(){let x=super.render();return x.className="buttonWidgetAnnotation pushButton",this.data.alternativeText&&(x.title=this.data.alternativeText),this._setDefaultPropertiesFromJS(x),x}}class C extends h{constructor(x){super(x,{isRenderable:x.renderForms})}render(){this.container.className="choiceWidgetAnnotation";let x=this.annotationStorage,T=this.data.id,O=x.getValue(T,{value:this.data.fieldValue}),{fontSize:I}=this.data.defaultAppearanceData;I||(I=9);let U=`calc(${I}px * var(--zoom-factor))`,z=document.createElement("select");u.add(z),z.disabled=this.data.readOnly,z.name=this.data.fieldName,z.setAttribute("id",T),z.tabIndex=f,z.style.fontSize=`${I}px`,this.data.combo||(z.size=this.data.options.length,this.data.multiSelect&&(z.multiple=!0)),z.addEventListener("resetform",ne=>{let se=this.data.defaultFieldValue;for(let fe of z.options)fe.selected=fe.value===se});for(let ne of this.data.options){let se=document.createElement("option");se.textContent=ne.displayValue,se.value=ne.exportValue,this.data.combo&&(se.style.fontSize=U),O.value.includes(ne.exportValue)&&se.setAttribute("selected",!0),z.appendChild(se)}let Z=(ne,se)=>{let fe=se?"value":"textContent",he=ne.target.options;return ne.target.multiple?Array.prototype.filter.call(he,Te=>Te.selected).map(Te=>Te[fe]):he.selectedIndex===-1?null:he[he.selectedIndex][fe]},re=ne=>{let se=ne.target.options;return Array.prototype.map.call(se,fe=>({displayValue:fe.textContent,exportValue:fe.value}))};return this.enableScripting&&this.hasJSActions?(z.addEventListener("updatefromsandbox",ne=>{let se={value(fe){let he=fe.detail.value,Te=new Set(Array.isArray(he)?he:[he]);for(let Ie of z.options)Ie.selected=Te.has(Ie.value);x.setValue(T,{value:Z(fe,!0)})},multipleSelection(fe){z.multiple=!0},remove(fe){let he=z.options,Te=fe.detail.remove;he[Te].selected=!1,z.remove(Te),he.length>0&&Array.prototype.findIndex.call(he,we=>we.selected)===-1&&(he[0].selected=!0),x.setValue(T,{value:Z(fe,!0),items:re(fe)})},clear(fe){for(;z.length!==0;)z.remove(0);x.setValue(T,{value:null,items:[]})},insert(fe){let{index:he,displayValue:Te,exportValue:Ie}=fe.detail.insert,we=document.createElement("option");we.textContent=Te,we.value=Ie,z.insertBefore(we,z.children[he]),x.setValue(T,{value:Z(fe,!0),items:re(fe)})},items(fe){let{items:he}=fe.detail;for(;z.length!==0;)z.remove(0);for(let Te of he){let{displayValue:Ie,exportValue:we}=Te,ye=document.createElement("option");ye.textContent=Ie,ye.value=we,z.appendChild(ye)}z.options.length>0&&(z.options[0].selected=!0),x.setValue(T,{value:Z(fe,!0),items:re(fe)})},indices(fe){let he=new Set(fe.detail.indices);for(let Te of fe.target.options)Te.selected=he.has(Te.index);x.setValue(T,{value:Z(fe,!0)})},editable(fe){fe.target.disabled=!fe.detail.editable}};this._dispatchEventFromSandbox(se,ne)}),z.addEventListener("input",ne=>{var he;let se=Z(ne,!0),fe=Z(ne,!1);x.setValue(T,{value:se}),(he=this.linkService.eventBus)==null||he.dispatch("dispatcheventinsandbox",{source:this,detail:{id:T,name:"Keystroke",value:fe,changeEx:se,willCommit:!0,commitKey:1,keyDown:!1}})}),this._setEventListeners(z,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"]],ne=>ne.target.checked)):z.addEventListener("input",function(ne){x.setValue(T,{value:Z(ne,!0)})}),this._setBackgroundColor(z),this._setDefaultPropertiesFromJS(z),this.container.appendChild(z),this.container}}class b extends _{constructor(x){var O,I,U;let T=!!((O=x.data.titleObj)!=null&&O.str||(I=x.data.contentsObj)!=null&&I.str||(U=x.data.richText)!=null&&U.str);super(x,{isRenderable:T})}render(){let x=["Line","Square","Circle","PolyLine","Polygon","Ink"];if(this.container.className="popupAnnotation",x.includes(this.data.parentType))return this.container;let T=`[data-annotation-id="${this.data.parentId}"]`,O=this.layer.querySelectorAll(T);if(O.length===0)return this.container;let I=new E({container:this.container,trigger:Array.from(O),color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText}),U=this.page,z=n.Util.normalizeRect([this.data.parentRect[0],U.view[3]-this.data.parentRect[1]+U.view[1],this.data.parentRect[2],U.view[3]-this.data.parentRect[3]+U.view[1]]),Z=z[0]+this.data.parentRect[2]-this.data.parentRect[0],re=z[1];return this.container.style.transformOrigin=`${-Z}px ${-re}px`,this.container.style.left=`${Z}px`,this.container.style.top=`${re}px`,this.container.appendChild(I.render()),this.container}}class E{constructor(x){this.container=x.container,this.trigger=x.trigger,this.color=x.color,this.titleObj=x.titleObj,this.modificationDate=x.modificationDate,this.contentsObj=x.contentsObj,this.richText=x.richText,this.hideWrapper=x.hideWrapper||!1,this.pinned=!1}render(){var Z,re;let T=document.createElement("div");T.className="popupWrapper",this.hideElement=this.hideWrapper?T:this.container,this.hideElement.hidden=!0;let O=document.createElement("div");O.className="popup";let I=this.color;if(I){let ne=.7*(255-I[0])+I[0],se=.7*(255-I[1])+I[1],fe=.7*(255-I[2])+I[2];O.style.backgroundColor=n.Util.makeHexColor(ne|0,se|0,fe|0)}let U=document.createElement("h1");U.dir=this.titleObj.dir,U.textContent=this.titleObj.str,O.appendChild(U);let z=i.PDFDateString.toDateObject(this.modificationDate);if(z){let ne=document.createElement("span");ne.className="popupDate",ne.textContent="{{date}}, {{time}}",ne.dataset.l10nId="annotation_date_string",ne.dataset.l10nArgs=JSON.stringify({date:z.toLocaleDateString(),time:z.toLocaleTimeString()}),O.appendChild(ne)}if((Z=this.richText)!=null&&Z.str&&(!((re=this.contentsObj)!=null&&re.str)||this.contentsObj.str===this.richText.str))c.XfaLayer.render({xfaHtml:this.richText.html,intent:"richText",div:O}),O.lastChild.className="richText popupContent";else{let ne=this._formatContents(this.contentsObj);O.appendChild(ne)}Array.isArray(this.trigger)||(this.trigger=[this.trigger]);for(let ne of this.trigger)ne.addEventListener("click",this._toggle.bind(this)),ne.addEventListener("mouseover",this._show.bind(this,!1)),ne.addEventListener("mouseout",this._hide.bind(this,!1));return O.addEventListener("click",this._hide.bind(this,!0)),T.appendChild(O),T}_formatContents({str:x,dir:T}){let O=document.createElement("p");O.className="popupContent",O.dir=T;let I=x.split(/(?:\r\n?|\n)/);for(let U=0,z=I.length;U<z;++U){let Z=I[U];O.appendChild(document.createTextNode(Z)),U<z-1&&O.appendChild(document.createElement("br"))}return O}_toggle(){this.pinned?this._hide(!0):this._show(!0)}_show(x=!1){x&&(this.pinned=!0),this.hideElement.hidden&&(this.hideElement.hidden=!1,this.container.style.zIndex+=1)}_hide(x=!0){x&&(this.pinned=!1),!this.hideElement.hidden&&!this.pinned&&(this.hideElement.hidden=!0,this.container.style.zIndex-=1)}}class k extends _{constructor(x){var O,I,U;let T=!!(x.data.hasPopup||(O=x.data.titleObj)!=null&&O.str||(I=x.data.contentsObj)!=null&&I.str||(U=x.data.richText)!=null&&U.str);super(x,{isRenderable:T,ignoreBorder:!0})}render(){return this.container.className="freeTextAnnotation",this.data.hasPopup||this._createPopup(null,this.data),this.container}}class P extends _{constructor(x){var O,I,U;let T=!!(x.data.hasPopup||(O=x.data.titleObj)!=null&&O.str||(I=x.data.contentsObj)!=null&&I.str||(U=x.data.richText)!=null&&U.str);super(x,{isRenderable:T,ignoreBorder:!0})}render(){this.container.className="lineAnnotation";let x=this.data,{width:T,height:O}=y(x.rect),I=this.svgFactory.create(T,O),U=this.svgFactory.createElement("svg:line");return U.setAttribute("x1",x.rect[2]-x.lineCoordinates[0]),U.setAttribute("y1",x.rect[3]-x.lineCoordinates[1]),U.setAttribute("x2",x.rect[2]-x.lineCoordinates[2]),U.setAttribute("y2",x.rect[3]-x.lineCoordinates[3]),U.setAttribute("stroke-width",x.borderStyle.width||1),U.setAttribute("stroke","transparent"),U.setAttribute("fill","transparent"),I.appendChild(U),this.container.append(I),this._createPopup(U,x),this.container}}class N extends _{constructor(x){var O,I,U;let T=!!(x.data.hasPopup||(O=x.data.titleObj)!=null&&O.str||(I=x.data.contentsObj)!=null&&I.str||(U=x.data.richText)!=null&&U.str);super(x,{isRenderable:T,ignoreBorder:!0})}render(){this.container.className="squareAnnotation";let x=this.data,{width:T,height:O}=y(x.rect),I=this.svgFactory.create(T,O),U=x.borderStyle.width,z=this.svgFactory.createElement("svg:rect");return z.setAttribute("x",U/2),z.setAttribute("y",U/2),z.setAttribute("width",T-U),z.setAttribute("height",O-U),z.setAttribute("stroke-width",U||1),z.setAttribute("stroke","transparent"),z.setAttribute("fill","transparent"),I.appendChild(z),this.container.append(I),this._createPopup(z,x),this.container}}class D extends _{constructor(x){var O,I,U;let T=!!(x.data.hasPopup||(O=x.data.titleObj)!=null&&O.str||(I=x.data.contentsObj)!=null&&I.str||(U=x.data.richText)!=null&&U.str);super(x,{isRenderable:T,ignoreBorder:!0})}render(){this.container.className="circleAnnotation";let x=this.data,{width:T,height:O}=y(x.rect),I=this.svgFactory.create(T,O),U=x.borderStyle.width,z=this.svgFactory.createElement("svg:ellipse");return z.setAttribute("cx",T/2),z.setAttribute("cy",O/2),z.setAttribute("rx",T/2-U/2),z.setAttribute("ry",O/2-U/2),z.setAttribute("stroke-width",U||1),z.setAttribute("stroke","transparent"),z.setAttribute("fill","transparent"),I.appendChild(z),this.container.append(I),this._createPopup(z,x),this.container}}class F extends _{constructor(x){var O,I,U;let T=!!(x.data.hasPopup||(O=x.data.titleObj)!=null&&O.str||(I=x.data.contentsObj)!=null&&I.str||(U=x.data.richText)!=null&&U.str);super(x,{isRenderable:T,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.className=this.containerClassName;let x=this.data,{width:T,height:O}=y(x.rect),I=this.svgFactory.create(T,O),U=[];for(let Z of x.vertices){let re=Z.x-x.rect[0],ne=x.rect[3]-Z.y;U.push(re+","+ne)}U=U.join(" ");let z=this.svgFactory.createElement(this.svgElementName);return z.setAttribute("points",U),z.setAttribute("stroke-width",x.borderStyle.width||1),z.setAttribute("stroke","transparent"),z.setAttribute("fill","transparent"),I.appendChild(z),this.container.append(I),this._createPopup(z,x),this.container}}class B extends F{constructor(x){super(x),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class V extends _{constructor(x){var O,I,U;let T=!!(x.data.hasPopup||(O=x.data.titleObj)!=null&&O.str||(I=x.data.contentsObj)!=null&&I.str||(U=x.data.richText)!=null&&U.str);super(x,{isRenderable:T,ignoreBorder:!0})}render(){return this.container.className="caretAnnotation",this.data.hasPopup||this._createPopup(null,this.data),this.container}}class q extends _{constructor(x){var O,I,U;let T=!!(x.data.hasPopup||(O=x.data.titleObj)!=null&&O.str||(I=x.data.contentsObj)!=null&&I.str||(U=x.data.richText)!=null&&U.str);super(x,{isRenderable:T,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline"}render(){this.container.className=this.containerClassName;let x=this.data,{width:T,height:O}=y(x.rect),I=this.svgFactory.create(T,O);for(let U of x.inkLists){let z=[];for(let re of U){let ne=re.x-x.rect[0],se=x.rect[3]-re.y;z.push(`${ne},${se}`)}z=z.join(" ");let Z=this.svgFactory.createElement(this.svgElementName);Z.setAttribute("points",z),Z.setAttribute("stroke-width",x.borderStyle.width||1),Z.setAttribute("stroke","transparent"),Z.setAttribute("fill","transparent"),this._createPopup(Z,x),I.appendChild(Z)}return this.container.append(I),this.container}}class G extends _{constructor(x){var O,I,U;let T=!!(x.data.hasPopup||(O=x.data.titleObj)!=null&&O.str||(I=x.data.contentsObj)!=null&&I.str||(U=x.data.richText)!=null&&U.str);super(x,{isRenderable:T,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return this.data.hasPopup||this._createPopup(null,this.data),this.quadrilaterals?this._renderQuadrilaterals("highlightAnnotation"):(this.container.className="highlightAnnotation",this.container)}}class Y extends _{constructor(x){var O,I,U;let T=!!(x.data.hasPopup||(O=x.data.titleObj)!=null&&O.str||(I=x.data.contentsObj)!=null&&I.str||(U=x.data.richText)!=null&&U.str);super(x,{isRenderable:T,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return this.data.hasPopup||this._createPopup(null,this.data),this.quadrilaterals?this._renderQuadrilaterals("underlineAnnotation"):(this.container.className="underlineAnnotation",this.container)}}class X extends _{constructor(x){var O,I,U;let T=!!(x.data.hasPopup||(O=x.data.titleObj)!=null&&O.str||(I=x.data.contentsObj)!=null&&I.str||(U=x.data.richText)!=null&&U.str);super(x,{isRenderable:T,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return this.data.hasPopup||this._createPopup(null,this.data),this.quadrilaterals?this._renderQuadrilaterals("squigglyAnnotation"):(this.container.className="squigglyAnnotation",this.container)}}class Q extends _{constructor(x){var O,I,U;let T=!!(x.data.hasPopup||(O=x.data.titleObj)!=null&&O.str||(I=x.data.contentsObj)!=null&&I.str||(U=x.data.richText)!=null&&U.str);super(x,{isRenderable:T,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return this.data.hasPopup||this._createPopup(null,this.data),this.quadrilaterals?this._renderQuadrilaterals("strikeoutAnnotation"):(this.container.className="strikeoutAnnotation",this.container)}}class le extends _{constructor(x){var O,I,U;let T=!!(x.data.hasPopup||(O=x.data.titleObj)!=null&&O.str||(I=x.data.contentsObj)!=null&&I.str||(U=x.data.richText)!=null&&U.str);super(x,{isRenderable:T,ignoreBorder:!0})}render(){return this.container.className="stampAnnotation",this.data.hasPopup||this._createPopup(null,this.data),this.container}}class ve extends _{constructor(x){var I;super(x,{isRenderable:!0});let{filename:T,content:O}=this.data.file;this.filename=(0,i.getFilenameFromUrl)(T),this.content=O,(I=this.linkService.eventBus)==null||I.dispatch("fileattachmentannotation",{source:this,filename:T,content:O})}render(){var T,O;this.container.className="fileAttachmentAnnotation";let x=document.createElement("div");return x.style.height=this.container.style.height,x.style.width=this.container.style.width,x.addEventListener("dblclick",this._download.bind(this)),!this.data.hasPopup&&((T=this.data.titleObj)!=null&&T.str||(O=this.data.contentsObj)!=null&&O.str||this.data.richText)&&this._createPopup(x,this.data),this.container.appendChild(x),this.container}_download(){var x;(x=this.downloadManager)==null||x.openOrDownloadData(this.container,this.content,this.filename)}}class ce{static render(x){let T=[],O=[];for(let U of x.annotations){if(!U)continue;let{width:z,height:Z}=y(U.rect);if(!(z<=0||Z<=0)){if(U.annotationType===n.AnnotationType.POPUP){O.push(U);continue}T.push(U)}}O.length&&T.push(...O);let I=x.div;for(let U of T){let z=m.create({data:U,layer:I,page:x.page,viewport:x.viewport,linkService:x.linkService,downloadManager:x.downloadManager,imageResourcesPath:x.imageResourcesPath||"",renderForms:x.renderForms!==!1,svgFactory:new i.DOMSVGFactory,annotationStorage:x.annotationStorage||new o.AnnotationStorage,enableScripting:x.enableScripting,hasJSActions:x.hasJSActions,fieldObjects:x.fieldObjects,mouseState:x.mouseState||{isDown:!1}});if(z.isRenderable){let Z=z.render();if(U.hidden&&(Z.style.visibility="hidden"),Array.isArray(Z))for(let re of Z)I.appendChild(re);else z instanceof b?I.prepend(Z):I.appendChild(Z)}}eo(this,W,nm).call(this,I,x.annotationCanvasMap)}static update(x){let{page:T,viewport:O,annotations:I,annotationCanvasMap:U,div:z}=x,Z=O.transform,re=`matrix(${Z.join(",")})`,ne,se;for(let fe of I){let he=z.querySelectorAll(`[data-annotation-id="${fe.id}"]`);if(he)for(let Te of he)if(fe.hasOwnCanvas){let Ie=n.Util.normalizeRect([fe.rect[0],T.view[3]-fe.rect[1]+T.view[1],fe.rect[2],T.view[3]-fe.rect[3]+T.view[1]]);if(!se){ne=Math.abs(Z[0]||Z[1]);let oe=Z.slice();for(let Ce=0;Ce<4;Ce++)oe[Ce]=Math.sign(oe[Ce]);se=`matrix(${oe.join(",")})`}let we=Ie[0]*ne,ye=Ie[1]*ne;Te.style.left=`${we}px`,Te.style.top=`${ye}px`,Te.style.transformOrigin=`${-we}px ${-ye}px`,Te.style.transform=se}else Te.style.transform=re}eo(this,W,nm).call(this,z,U),z.hidden=!1}}W=new WeakSet,nm=function(x,T){if(T){for(let[O,I]of T){let U=x.querySelector(`[data-annotation-id="${O}"]`);if(!U)continue;let{firstChild:z}=U;z.nodeName==="CANVAS"?U.replaceChild(I,z):U.insertBefore(I,z)}T.clear()}},Er(ce,W),e.AnnotationLayer=ce},(r,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ColorConverters=void 0;function t(i){return Math.floor(Math.max(0,Math.min(1,i))*255).toString(16).padStart(2,"0")}class n{static CMYK_G([o,s,c,f]){return["G",1-Math.min(1,.3*o+.59*c+.11*s+f)]}static G_CMYK([o]){return["CMYK",0,0,0,1-o]}static G_RGB([o]){return["RGB",o,o,o]}static G_HTML([o]){let s=t(o);return`#${s}${s}${s}`}static RGB_G([o,s,c]){return["G",.3*o+.59*s+.11*c]}static RGB_HTML([o,s,c]){let f=t(o),u=t(s),y=t(c);return`#${f}${u}${y}`}static T_HTML(){return"#00000000"}static CMYK_RGB([o,s,c,f]){return["RGB",1-Math.min(1,o+f),1-Math.min(1,c+f),1-Math.min(1,s+f)]}static CMYK_HTML(o){return this.RGB_HTML(this.CMYK_RGB(o))}static RGB_CMYK([o,s,c]){let f=1-o,u=1-s,y=1-c,m=Math.min(f,u,y);return["CMYK",f,u,y,m]}}e.ColorConverters=n},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.XfaLayer=void 0;var n=t(18);class i{static setupStorage(s,c,f,u,y){let m=u.getValue(c,{value:null});switch(f.name){case"textarea":if(m.value!==null&&(s.textContent=m.value),y==="print")break;s.addEventListener("input",_=>{u.setValue(c,{value:_.target.value})});break;case"input":if(f.attributes.type==="radio"||f.attributes.type==="checkbox"){if(m.value===f.attributes.xfaOn?s.setAttribute("checked",!0):m.value===f.attributes.xfaOff&&s.removeAttribute("checked"),y==="print")break;s.addEventListener("change",_=>{u.setValue(c,{value:_.target.checked?_.target.getAttribute("xfaOn"):_.target.getAttribute("xfaOff")})})}else{if(m.value!==null&&s.setAttribute("value",m.value),y==="print")break;s.addEventListener("input",_=>{u.setValue(c,{value:_.target.value})})}break;case"select":if(m.value!==null)for(let _ of f.children)_.attributes.value===m.value&&(_.attributes.selected=!0);s.addEventListener("input",_=>{let v=_.target.options,g=v.selectedIndex===-1?"":v[v.selectedIndex].value;u.setValue(c,{value:g})});break}}static setAttributes({html:s,element:c,storage:f=null,intent:u,linkService:y}){let{attributes:m}=c,_=s instanceof HTMLAnchorElement;m.type==="radio"&&(m.name=`${m.name}-${u}`);for(let[v,g]of Object.entries(m))if(!(g==null||v==="dataId"))if(v!=="style")if(v==="textContent")s.textContent=g;else if(v==="class")g.length&&s.setAttribute(v,g.join(" "));else{if(_&&(v==="href"||v==="newWindow"))continue;s.setAttribute(v,g)}else Object.assign(s.style,g);_&&y.addLinkAttributes(s,m.href,m.newWindow),f&&m.dataId&&this.setupStorage(s,m.dataId,c,f)}static render(s){var h;let c=s.annotationStorage,f=s.linkService,u=s.xfaHtml,y=s.intent||"display",m=document.createElement(u.name);u.attributes&&this.setAttributes({html:m,element:u,intent:y,linkService:f});let _=[[u,-1,m]],v=s.div;if(v.appendChild(m),s.viewport){let l=`matrix(${s.viewport.transform.join(",")})`;v.style.transform=l}y!=="richText"&&v.setAttribute("class","xfaLayer xfaFont");let g=[];for(;_.length>0;){let[l,p,w]=_[_.length-1];if(p+1===l.children.length){_.pop();continue}let A=l.children[++_[_.length-1][1]];if(A===null)continue;let{name:C}=A;if(C==="#text"){let E=document.createTextNode(A.value);g.push(E),w.appendChild(E);continue}let b;if((h=A==null?void 0:A.attributes)!=null&&h.xmlns?b=document.createElementNS(A.attributes.xmlns,C):b=document.createElement(C),w.appendChild(b),A.attributes&&this.setAttributes({html:b,element:A,storage:c,intent:y,linkService:f}),A.children&&A.children.length>0)_.push([A,-1,b]);else if(A.value){let E=document.createTextNode(A.value);n.XfaText.shouldBuildText(C)&&g.push(E),b.appendChild(E)}}for(let l of v.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))l.setAttribute("readOnly",!0);return{textDivs:g}}static update(s){let c=`matrix(${s.viewport.transform.join(",")})`;s.div.style.transform=c,s.div.hidden=!1}}e.XfaLayer=i},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.renderTextLayer=p;var n=t(1);let i=1e5,o=30,s=.8,c=new Map,f=/^\s+$/g;function u(w,A){let C=c.get(w);if(C)return C;A.save(),A.font=`${o}px ${w}`;let b=A.measureText(""),E=b.fontBoundingBoxAscent,k=Math.abs(b.fontBoundingBoxDescent);if(E){A.restore();let N=E/(E+k);return c.set(w,N),N}A.strokeStyle="red",A.clearRect(0,0,o,o),A.strokeText("g",0,0);let P=A.getImageData(0,0,o,o).data;k=0;for(let N=P.length-1-3;N>=0;N-=4)if(P[N]>0){k=Math.ceil(N/4/o);break}A.clearRect(0,0,o,o),A.strokeText("A",0,o),P=A.getImageData(0,0,o,o).data,E=0;for(let N=0,D=P.length;N<D;N+=4)if(P[N]>0){E=o-Math.floor(N/4/o);break}if(A.restore(),E){let N=E/(E+k);return c.set(w,N),N}return c.set(w,s),s}function y(w,A,C,b){let E=document.createElement("span"),k=w._enhanceTextSelection?{angle:0,canvasWidth:0,hasText:A.str!=="",hasEOL:A.hasEOL,originalTransform:null,paddingBottom:0,paddingLeft:0,paddingRight:0,paddingTop:0,scale:1}:{angle:0,canvasWidth:0,hasText:A.str!=="",hasEOL:A.hasEOL};w._textDivs.push(E);let P=n.Util.transform(w._viewport.transform,A.transform),N=Math.atan2(P[1],P[0]),D=C[A.fontName];D.vertical&&(N+=Math.PI/2);let F=Math.hypot(P[2],P[3]),B=F*u(D.fontFamily,b),V,q;N===0?(V=P[4],q=P[5]-B):(V=P[4]+B*Math.sin(N),q=P[5]-B*Math.cos(N)),E.style.left=`${V}px`,E.style.top=`${q}px`,E.style.fontSize=`${F}px`,E.style.fontFamily=D.fontFamily,E.setAttribute("role","presentation"),E.textContent=A.str,E.dir=A.dir,w._fontInspectorEnabled&&(E.dataset.fontName=A.fontName),N!==0&&(k.angle=N*(180/Math.PI));let G=!1;if(A.str.length>1||w._enhanceTextSelection&&f.test(A.str))G=!0;else if(A.str!==" "&&A.transform[0]!==A.transform[3]){let Y=Math.abs(A.transform[0]),X=Math.abs(A.transform[3]);Y!==X&&Math.max(Y,X)/Math.min(Y,X)>1.5&&(G=!0)}if(G&&(D.vertical?k.canvasWidth=A.height*w._viewport.scale:k.canvasWidth=A.width*w._viewport.scale),w._textDivProperties.set(E,k),w._textContentStream&&w._layoutText(E),w._enhanceTextSelection&&k.hasText){let Y=1,X=0;N!==0&&(Y=Math.cos(N),X=Math.sin(N));let Q=(D.vertical?A.height:A.width)*w._viewport.scale,le=F,ve,ce;N!==0?(ve=[Y,X,-X,Y,V,q],ce=n.Util.getAxialAlignedBoundingBox([0,0,Q,le],ve)):ce=[V,q,V+Q,q+le],w._bounds.push({left:ce[0],top:ce[1],right:ce[2],bottom:ce[3],div:E,size:[Q,le],m:ve})}}function m(w){if(w._canceled)return;let A=w._textDivs,C=w._capability,b=A.length;if(b>i){w._renderingDone=!0,C.resolve();return}if(!w._textContentStream)for(let E=0;E<b;E++)w._layoutText(A[E]);w._renderingDone=!0,C.resolve()}function _(w,A,C){let b=0;for(let E=0;E<C;E++){let k=w[A++];k>0&&(b=b?Math.min(k,b):k)}return b}function v(w){let A=w._bounds,C=w._viewport,b=g(C.width,C.height,A);for(let E=0;E<b.length;E++){let k=A[E].div,P=w._textDivProperties.get(k);if(P.angle===0){P.paddingLeft=A[E].left-b[E].left,P.paddingTop=A[E].top-b[E].top,P.paddingRight=b[E].right-A[E].right,P.paddingBottom=b[E].bottom-A[E].bottom,w._textDivProperties.set(k,P);continue}let N=b[E],D=A[E],F=D.m,B=F[0],V=F[1],q=[[0,0],[0,D.size[1]],[D.size[0],0],D.size],G=new Float64Array(64);for(let X=0,Q=q.length;X<Q;X++){let le=n.Util.applyTransform(q[X],F);G[X+0]=B&&(N.left-le[0])/B,G[X+4]=V&&(N.top-le[1])/V,G[X+8]=B&&(N.right-le[0])/B,G[X+12]=V&&(N.bottom-le[1])/V,G[X+16]=V&&(N.left-le[0])/-V,G[X+20]=B&&(N.top-le[1])/B,G[X+24]=V&&(N.right-le[0])/-V,G[X+28]=B&&(N.bottom-le[1])/B,G[X+32]=B&&(N.left-le[0])/-B,G[X+36]=V&&(N.top-le[1])/-V,G[X+40]=B&&(N.right-le[0])/-B,G[X+44]=V&&(N.bottom-le[1])/-V,G[X+48]=V&&(N.left-le[0])/V,G[X+52]=B&&(N.top-le[1])/-B,G[X+56]=V&&(N.right-le[0])/V,G[X+60]=B&&(N.bottom-le[1])/-B}let Y=1+Math.min(Math.abs(B),Math.abs(V));P.paddingLeft=_(G,32,16)/Y,P.paddingTop=_(G,48,16)/Y,P.paddingRight=_(G,0,16)/Y,P.paddingBottom=_(G,16,16)/Y,w._textDivProperties.set(k,P)}}function g(w,A,C){let b=C.map(function(k,P){return{x1:k.left,y1:k.top,x2:k.right,y2:k.bottom,index:P,x1New:void 0,x2New:void 0}});h(w,b);let E=new Array(C.length);for(let k of b){let P=k.index;E[P]={left:k.x1New,top:0,right:k.x2New,bottom:0}}C.map(function(k,P){let N=E[P],D=b[P];D.x1=k.top,D.y1=w-N.right,D.x2=k.bottom,D.y2=w-N.left,D.index=P,D.x1New=void 0,D.x2New=void 0}),h(A,b);for(let k of b){let P=k.index;E[P].top=k.x1New,E[P].bottom=k.x2New}return E}function h(w,A){A.sort(function(E,k){return E.x1-k.x1||E.index-k.index});let b=[{start:-1/0,end:1/0,boundary:{x1:-1/0,y1:-1/0,x2:0,y2:1/0,index:-1,x1New:0,x2New:0}}];for(let E of A){let k=0;for(;k<b.length&&b[k].end<=E.y1;)k++;let P=b.length-1;for(;P>=0&&b[P].start>=E.y2;)P--;let N,D,F,B,V=-1/0;for(F=k;F<=P;F++){N=b[F],D=N.boundary;let Y;D.x2>E.x1?Y=D.index>E.index?D.x1New:E.x1:D.x2New===void 0?Y=(D.x2+E.x1)/2:Y=D.x2New,Y>V&&(V=Y)}for(E.x1New=V,F=k;F<=P;F++)N=b[F],D=N.boundary,D.x2New===void 0?D.x2>E.x1?D.index>E.index&&(D.x2New=D.x2):D.x2New=V:D.x2New>V&&(D.x2New=Math.max(V,D.x2));let q=[],G=null;for(F=k;F<=P;F++){N=b[F],D=N.boundary;let Y=D.x2>E.x2?D:E;G===Y?q[q.length-1].end=N.end:(q.push({start:N.start,end:N.end,boundary:Y}),G=Y)}for(b[k].start<E.y1&&(q[0].start=E.y1,q.unshift({start:b[k].start,end:E.y1,boundary:b[k].boundary})),E.y2<b[P].end&&(q[q.length-1].end=E.y2,q.push({start:E.y2,end:b[P].end,boundary:b[P].boundary})),F=k;F<=P;F++){if(N=b[F],D=N.boundary,D.x2New!==void 0)continue;let Y=!1;for(B=k-1;!Y&&B>=0&&b[B].start>=D.y1;B--)Y=b[B].boundary===D;for(B=P+1;!Y&&B<b.length&&b[B].end<=D.y2;B++)Y=b[B].boundary===D;for(B=0;!Y&&B<q.length;B++)Y=q[B].boundary===D;Y||(D.x2New=V)}Array.prototype.splice.apply(b,[k,P-k+1].concat(q))}for(let E of b){let k=E.boundary;k.x2New===void 0&&(k.x2New=Math.max(w,k.x2))}}class l{constructor({textContent:A,textContentStream:C,container:b,viewport:E,textDivs:k,textContentItemsStr:P,enhanceTextSelection:N}){var D;this._textContent=A,this._textContentStream=C,this._container=b,this._document=b.ownerDocument,this._viewport=E,this._textDivs=k||[],this._textContentItemsStr=P||[],this._enhanceTextSelection=!!N,this._fontInspectorEnabled=!!((D=globalThis.FontInspector)!=null&&D.enabled),this._reader=null,this._layoutTextLastFontSize=null,this._layoutTextLastFontFamily=null,this._layoutTextCtx=null,this._textDivProperties=new WeakMap,this._renderingDone=!1,this._canceled=!1,this._capability=(0,n.createPromiseCapability)(),this._renderTimer=null,this._bounds=[],this._capability.promise.finally(()=>{this._enhanceTextSelection||(this._textDivProperties=null),this._layoutTextCtx&&(this._layoutTextCtx.canvas.width=0,this._layoutTextCtx.canvas.height=0,this._layoutTextCtx=null)}).catch(()=>{})}get promise(){return this._capability.promise}cancel(){this._canceled=!0,this._reader&&(this._reader.cancel(new n.AbortException("TextLayer task cancelled.")).catch(()=>{}),this._reader=null),this._renderTimer!==null&&(clearTimeout(this._renderTimer),this._renderTimer=null),this._capability.reject(new Error("TextLayer task cancelled."))}_processItems(A,C){for(let b=0,E=A.length;b<E;b++){if(A[b].str===void 0){if(A[b].type==="beginMarkedContentProps"||A[b].type==="beginMarkedContent"){let k=this._container;this._container=document.createElement("span"),this._container.classList.add("markedContent"),A[b].id!==null&&this._container.setAttribute("id",`${A[b].id}`),k.appendChild(this._container)}else A[b].type==="endMarkedContent"&&(this._container=this._container.parentNode);continue}this._textContentItemsStr.push(A[b].str),y(this,A[b],C,this._layoutTextCtx)}}_layoutText(A){let C=this._textDivProperties.get(A),b="";if(C.canvasWidth!==0&&C.hasText){let{fontSize:E,fontFamily:k}=A.style;(E!==this._layoutTextLastFontSize||k!==this._layoutTextLastFontFamily)&&(this._layoutTextCtx.font=`${E} ${k}`,this._layoutTextLastFontSize=E,this._layoutTextLastFontFamily=k);let{width:P}=this._layoutTextCtx.measureText(A.textContent);if(P>0){let N=C.canvasWidth/P;this._enhanceTextSelection&&(C.scale=N),b=`scaleX(${N})`}}if(C.angle!==0&&(b=`rotate(${C.angle}deg) ${b}`),b.length>0&&(this._enhanceTextSelection&&(C.originalTransform=b),A.style.transform=b),C.hasText&&this._container.appendChild(A),C.hasEOL){let E=document.createElement("br");E.setAttribute("role","presentation"),this._container.appendChild(E)}}_render(A=0){let C=(0,n.createPromiseCapability)(),b=Object.create(null),E=this._document.createElement("canvas");if(E.height=E.width=o,this._layoutTextCtx=E.getContext("2d",{alpha:!1}),this._textContent){let k=this._textContent.items,P=this._textContent.styles;this._processItems(k,P),C.resolve()}else if(this._textContentStream){let k=()=>{this._reader.read().then(({value:P,done:N})=>{if(N){C.resolve();return}Object.assign(b,P.styles),this._processItems(P.items,b),k()},C.reject)};this._reader=this._textContentStream.getReader(),k()}else throw new Error('Neither "textContent" nor "textContentStream" parameters specified.');C.promise.then(()=>{b=null,A?this._renderTimer=setTimeout(()=>{m(this),this._renderTimer=null},A):m(this)},this._capability.reject)}expandTextDivs(A=!1){if(!this._enhanceTextSelection||!this._renderingDone)return;this._bounds!==null&&(v(this),this._bounds=null);let C=[],b=[];for(let E=0,k=this._textDivs.length;E<k;E++){let P=this._textDivs[E],N=this._textDivProperties.get(P);N.hasText&&(A?(C.length=0,b.length=0,N.originalTransform&&C.push(N.originalTransform),N.paddingTop>0?(b.push(`${N.paddingTop}px`),C.push(`translateY(${-N.paddingTop}px)`)):b.push(0),N.paddingRight>0?b.push(`${N.paddingRight/N.scale}px`):b.push(0),N.paddingBottom>0?b.push(`${N.paddingBottom}px`):b.push(0),N.paddingLeft>0?(b.push(`${N.paddingLeft/N.scale}px`),C.push(`translateX(${-N.paddingLeft/N.scale}px)`)):b.push(0),P.style.padding=b.join(" "),C.length&&(P.style.transform=C.join(" "))):(P.style.padding=null,P.style.transform=N.originalTransform))}}}function p(w){let A=new l({textContent:w.textContent,textContentStream:w.textContentStream,container:w.container,viewport:w.viewport,textDivs:w.textDivs,textContentItemsStr:w.textContentItemsStr,enhanceTextSelection:w.enhanceTextSelection});return A._render(w.timeout),A}},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SVGGraphics=void 0;var n=t(1),i=t(5),o=t(3);let s=class{constructor(){(0,n.unreachable)("Not implemented: SVGGraphics")}};e.SVGGraphics=s;{let h=function(b){let E=[],k=[];for(let P of b){if(P.fn==="save"){E.push({fnId:92,fn:"group",items:[]}),k.push(E),E=E[E.length-1].items;continue}P.fn==="restore"?E=k.pop():E.push(P)}return E},l=function(b){if(Number.isInteger(b))return b.toString();let E=b.toFixed(10),k=E.length-1;if(E[k]!=="0")return E;do k--;while(E[k]==="0");return E.substring(0,E[k]==="."?k:k+1)},p=function(b){if(b[4]===0&&b[5]===0){if(b[1]===0&&b[2]===0)return b[0]===1&&b[3]===1?"":`scale(${l(b[0])} ${l(b[3])})`;if(b[0]===b[3]&&b[1]===-b[2]){let E=Math.acos(b[0])*180/Math.PI;return`rotate(${l(E)})`}}else if(b[0]===1&&b[1]===0&&b[2]===0&&b[3]===1)return`translate(${l(b[4])} ${l(b[5])})`;return`matrix(${l(b[0])} ${l(b[1])} ${l(b[2])} ${l(b[3])} ${l(b[4])} ${l(b[5])})`},c={fontStyle:"normal",fontWeight:"normal",fillColor:"#000000"},f="http://www.w3.org/XML/1998/namespace",u="http://www.w3.org/1999/xlink",y=["butt","round","square"],m=["miter","round","bevel"],_=function(b,E="",k=!1){if(URL.createObjectURL&&typeof Blob<"u"&&!k)return URL.createObjectURL(new Blob([b],{type:E}));let P="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",N=`data:${E};base64,`;for(let D=0,F=b.length;D<F;D+=3){let B=b[D]&255,V=b[D+1]&255,q=b[D+2]&255,G=B>>2,Y=(B&3)<<4|V>>4,X=D+1<F?(V&15)<<2|q>>6:64,Q=D+2<F?q&63:64;N+=P[G]+P[Y]+P[X]+P[Q]}return N},v=function(){let b=new Uint8Array([137,80,78,71,13,10,26,10]),E=12,k=new Int32Array(256);for(let q=0;q<256;q++){let G=q;for(let Y=0;Y<8;Y++)G&1?G=3988292384^G>>1&2147483647:G=G>>1&2147483647;k[q]=G}function P(q,G,Y){let X=-1;for(let Q=G;Q<Y;Q++){let le=(X^q[Q])&255,ve=k[le];X=X>>>8^ve}return X^-1}function N(q,G,Y,X){let Q=X,le=G.length;Y[Q]=le>>24&255,Y[Q+1]=le>>16&255,Y[Q+2]=le>>8&255,Y[Q+3]=le&255,Q+=4,Y[Q]=q.charCodeAt(0)&255,Y[Q+1]=q.charCodeAt(1)&255,Y[Q+2]=q.charCodeAt(2)&255,Y[Q+3]=q.charCodeAt(3)&255,Q+=4,Y.set(G,Q),Q+=G.length;let ve=P(Y,X+4,Q);Y[Q]=ve>>24&255,Y[Q+1]=ve>>16&255,Y[Q+2]=ve>>8&255,Y[Q+3]=ve&255}function D(q,G,Y){let X=1,Q=0;for(let le=G;le<Y;++le)X=(X+(q[le]&255))%65521,Q=(Q+X)%65521;return Q<<16|X}function F(q){if(!o.isNodeJS)return B(q);try{let G;parseInt(process.versions.node)>=8?G=q:G=Buffer.from(q);let Y=DC().deflateSync(G,{level:9});return Y instanceof Uint8Array?Y:new Uint8Array(Y)}catch(G){(0,n.warn)("Not compressing PNG because zlib.deflateSync is unavailable: "+G)}return B(q)}function B(q){let G=q.length,Y=65535,X=Math.ceil(G/Y),Q=new Uint8Array(2+G+X*5+4),le=0;Q[le++]=120,Q[le++]=156;let ve=0;for(;G>Y;)Q[le++]=0,Q[le++]=255,Q[le++]=255,Q[le++]=0,Q[le++]=0,Q.set(q.subarray(ve,ve+Y),le),le+=Y,ve+=Y,G-=Y;Q[le++]=1,Q[le++]=G&255,Q[le++]=G>>8&255,Q[le++]=~G&65535&255,Q[le++]=(~G&65535)>>8&255,Q.set(q.subarray(ve),le),le+=q.length-ve;let ce=D(q,0,q.length);return Q[le++]=ce>>24&255,Q[le++]=ce>>16&255,Q[le++]=ce>>8&255,Q[le++]=ce&255,Q}function V(q,G,Y,X){let Q=q.width,le=q.height,ve,ce,W,H=q.data;switch(G){case n.ImageKind.GRAYSCALE_1BPP:ce=0,ve=1,W=Q+7>>3;break;case n.ImageKind.RGB_24BPP:ce=2,ve=8,W=Q*3;break;case n.ImageKind.RGBA_32BPP:ce=6,ve=8,W=Q*4;break;default:throw new Error("invalid format")}let R=new Uint8Array((1+W)*le),x=0,T=0;for(let re=0;re<le;++re)R[x++]=0,R.set(H.subarray(T,T+W),x),T+=W,x+=W;if(G===n.ImageKind.GRAYSCALE_1BPP&&X){x=0;for(let re=0;re<le;re++){x++;for(let ne=0;ne<W;ne++)R[x++]^=255}}let O=new Uint8Array([Q>>24&255,Q>>16&255,Q>>8&255,Q&255,le>>24&255,le>>16&255,le>>8&255,le&255,ve,ce,0,0,0]),I=F(R),U=b.length+E*3+O.length+I.length,z=new Uint8Array(U),Z=0;return z.set(b,Z),Z+=b.length,N("IHDR",O,z,Z),Z+=E+O.length,N("IDATA",I,z,Z),Z+=E+I.length,N("IEND",new Uint8Array(0),z,Z),_(z,"image/png",Y)}return function(G,Y,X){let Q=G.kind===void 0?n.ImageKind.GRAYSCALE_1BPP:G.kind;return V(G,Q,Y,X)}}();class g{constructor(){this.fontSizeScale=1,this.fontWeight=c.fontWeight,this.fontSize=0,this.textMatrix=n.IDENTITY_MATRIX,this.fontMatrix=n.FONT_IDENTITY_MATRIX,this.leading=0,this.textRenderingMode=n.TextRenderingMode.FILL,this.textMatrixScale=1,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRise=0,this.fillColor=c.fillColor,this.strokeColor="#000000",this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.lineJoin="",this.lineCap="",this.miterLimit=0,this.dashArray=[],this.dashPhase=0,this.dependencies=[],this.activeClipUrl=null,this.clipGroup=null,this.maskId=""}clone(){return Object.create(this)}setCurrentPoint(E,k){this.x=E,this.y=k}}let w=0,A=0,C=0;e.SVGGraphics=s=class{constructor(b,E,k=!1){this.svgFactory=new i.DOMSVGFactory,this.current=new g,this.transformMatrix=n.IDENTITY_MATRIX,this.transformStack=[],this.extraStack=[],this.commonObjs=b,this.objs=E,this.pendingClip=null,this.pendingEOFill=!1,this.embedFonts=!1,this.embeddedFonts=Object.create(null),this.cssStyle=null,this.forceDataSchema=!!k,this._operatorIdMapping=[];for(let P in n.OPS)this._operatorIdMapping[n.OPS[P]]=P}save(){this.transformStack.push(this.transformMatrix);let b=this.current;this.extraStack.push(b),this.current=b.clone()}restore(){this.transformMatrix=this.transformStack.pop(),this.current=this.extraStack.pop(),this.pendingClip=null,this.tgrp=null}group(b){this.save(),this.executeOpTree(b),this.restore()}loadDependencies(b){let E=b.fnArray,k=b.argsArray;for(let P=0,N=E.length;P<N;P++)if(E[P]===n.OPS.dependency)for(let D of k[P]){let F=D.startsWith("g_")?this.commonObjs:this.objs,B=new Promise(V=>{F.get(D,V)});this.current.dependencies.push(B)}return Promise.all(this.current.dependencies)}transform(b,E,k,P,N,D){let F=[b,E,k,P,N,D];this.transformMatrix=n.Util.transform(this.transformMatrix,F),this.tgrp=null}getSVG(b,E){this.viewport=E;let k=this._initialize(E);return this.loadDependencies(b).then(()=>(this.transformMatrix=n.IDENTITY_MATRIX,this.executeOpTree(this.convertOpList(b)),k))}convertOpList(b){let E=this._operatorIdMapping,k=b.argsArray,P=b.fnArray,N=[];for(let D=0,F=P.length;D<F;D++){let B=P[D];N.push({fnId:B,fn:E[B],args:k[D]})}return h(N)}executeOpTree(b){for(let E of b){let k=E.fn,P=E.fnId,N=E.args;switch(P|0){case n.OPS.beginText:this.beginText();break;case n.OPS.dependency:break;case n.OPS.setLeading:this.setLeading(N);break;case n.OPS.setLeadingMoveText:this.setLeadingMoveText(N[0],N[1]);break;case n.OPS.setFont:this.setFont(N);break;case n.OPS.showText:this.showText(N[0]);break;case n.OPS.showSpacedText:this.showText(N[0]);break;case n.OPS.endText:this.endText();break;case n.OPS.moveText:this.moveText(N[0],N[1]);break;case n.OPS.setCharSpacing:this.setCharSpacing(N[0]);break;case n.OPS.setWordSpacing:this.setWordSpacing(N[0]);break;case n.OPS.setHScale:this.setHScale(N[0]);break;case n.OPS.setTextMatrix:this.setTextMatrix(N[0],N[1],N[2],N[3],N[4],N[5]);break;case n.OPS.setTextRise:this.setTextRise(N[0]);break;case n.OPS.setTextRenderingMode:this.setTextRenderingMode(N[0]);break;case n.OPS.setLineWidth:this.setLineWidth(N[0]);break;case n.OPS.setLineJoin:this.setLineJoin(N[0]);break;case n.OPS.setLineCap:this.setLineCap(N[0]);break;case n.OPS.setMiterLimit:this.setMiterLimit(N[0]);break;case n.OPS.setFillRGBColor:this.setFillRGBColor(N[0],N[1],N[2]);break;case n.OPS.setStrokeRGBColor:this.setStrokeRGBColor(N[0],N[1],N[2]);break;case n.OPS.setStrokeColorN:this.setStrokeColorN(N);break;case n.OPS.setFillColorN:this.setFillColorN(N);break;case n.OPS.shadingFill:this.shadingFill(N[0]);break;case n.OPS.setDash:this.setDash(N[0],N[1]);break;case n.OPS.setRenderingIntent:this.setRenderingIntent(N[0]);break;case n.OPS.setFlatness:this.setFlatness(N[0]);break;case n.OPS.setGState:this.setGState(N[0]);break;case n.OPS.fill:this.fill();break;case n.OPS.eoFill:this.eoFill();break;case n.OPS.stroke:this.stroke();break;case n.OPS.fillStroke:this.fillStroke();break;case n.OPS.eoFillStroke:this.eoFillStroke();break;case n.OPS.clip:this.clip("nonzero");break;case n.OPS.eoClip:this.clip("evenodd");break;case n.OPS.paintSolidColorImageMask:this.paintSolidColorImageMask();break;case n.OPS.paintImageXObject:this.paintImageXObject(N[0]);break;case n.OPS.paintInlineImageXObject:this.paintInlineImageXObject(N[0]);break;case n.OPS.paintImageMaskXObject:this.paintImageMaskXObject(N[0]);break;case n.OPS.paintFormXObjectBegin:this.paintFormXObjectBegin(N[0],N[1]);break;case n.OPS.paintFormXObjectEnd:this.paintFormXObjectEnd();break;case n.OPS.closePath:this.closePath();break;case n.OPS.closeStroke:this.closeStroke();break;case n.OPS.closeFillStroke:this.closeFillStroke();break;case n.OPS.closeEOFillStroke:this.closeEOFillStroke();break;case n.OPS.nextLine:this.nextLine();break;case n.OPS.transform:this.transform(N[0],N[1],N[2],N[3],N[4],N[5]);break;case n.OPS.constructPath:this.constructPath(N[0],N[1]);break;case n.OPS.endPath:this.endPath();break;case 92:this.group(E.items);break;default:(0,n.warn)(`Unimplemented operator ${k}`);break}}}setWordSpacing(b){this.current.wordSpacing=b}setCharSpacing(b){this.current.charSpacing=b}nextLine(){this.moveText(0,this.current.leading)}setTextMatrix(b,E,k,P,N,D){let F=this.current;F.textMatrix=F.lineMatrix=[b,E,k,P,N,D],F.textMatrixScale=Math.hypot(b,E),F.x=F.lineX=0,F.y=F.lineY=0,F.xcoords=[],F.ycoords=[],F.tspan=this.svgFactory.createElement("svg:tspan"),F.tspan.setAttributeNS(null,"font-family",F.fontFamily),F.tspan.setAttributeNS(null,"font-size",`${l(F.fontSize)}px`),F.tspan.setAttributeNS(null,"y",l(-F.y)),F.txtElement=this.svgFactory.createElement("svg:text"),F.txtElement.appendChild(F.tspan)}beginText(){let b=this.current;b.x=b.lineX=0,b.y=b.lineY=0,b.textMatrix=n.IDENTITY_MATRIX,b.lineMatrix=n.IDENTITY_MATRIX,b.textMatrixScale=1,b.tspan=this.svgFactory.createElement("svg:tspan"),b.txtElement=this.svgFactory.createElement("svg:text"),b.txtgrp=this.svgFactory.createElement("svg:g"),b.xcoords=[],b.ycoords=[]}moveText(b,E){let k=this.current;k.x=k.lineX+=b,k.y=k.lineY+=E,k.xcoords=[],k.ycoords=[],k.tspan=this.svgFactory.createElement("svg:tspan"),k.tspan.setAttributeNS(null,"font-family",k.fontFamily),k.tspan.setAttributeNS(null,"font-size",`${l(k.fontSize)}px`),k.tspan.setAttributeNS(null,"y",l(-k.y))}showText(b){let E=this.current,k=E.font,P=E.fontSize;if(P===0)return;let N=E.fontSizeScale,D=E.charSpacing,F=E.wordSpacing,B=E.fontDirection,V=E.textHScale*B,q=k.vertical,G=q?1:-1,Y=k.defaultVMetrics,X=P*E.fontMatrix[0],Q=0;for(let ce of b){if(ce===null){Q+=B*F;continue}else if(typeof ce=="number"){Q+=G*ce*P/1e3;continue}let W=(ce.isSpace?F:0)+D,H=ce.fontChar,R,x,T=ce.width;if(q){let I,U=ce.vmetric||Y;I=ce.vmetric?U[1]:T*.5,I=-I*X;let z=U[2]*X;T=U?-U[0]:T,R=I/N,x=(Q+z)/N}else R=Q/N,x=0;(ce.isInFont||k.missingFile)&&(E.xcoords.push(E.x+R),q&&E.ycoords.push(-E.y+x),E.tspan.textContent+=H);let O;q?O=T*X-W*B:O=T*X+W*B,Q+=O}E.tspan.setAttributeNS(null,"x",E.xcoords.map(l).join(" ")),q?E.tspan.setAttributeNS(null,"y",E.ycoords.map(l).join(" ")):E.tspan.setAttributeNS(null,"y",l(-E.y)),q?E.y-=Q:E.x+=Q*V,E.tspan.setAttributeNS(null,"font-family",E.fontFamily),E.tspan.setAttributeNS(null,"font-size",`${l(E.fontSize)}px`),E.fontStyle!==c.fontStyle&&E.tspan.setAttributeNS(null,"font-style",E.fontStyle),E.fontWeight!==c.fontWeight&&E.tspan.setAttributeNS(null,"font-weight",E.fontWeight);let le=E.textRenderingMode&n.TextRenderingMode.FILL_STROKE_MASK;if(le===n.TextRenderingMode.FILL||le===n.TextRenderingMode.FILL_STROKE?(E.fillColor!==c.fillColor&&E.tspan.setAttributeNS(null,"fill",E.fillColor),E.fillAlpha<1&&E.tspan.setAttributeNS(null,"fill-opacity",E.fillAlpha)):E.textRenderingMode===n.TextRenderingMode.ADD_TO_PATH?E.tspan.setAttributeNS(null,"fill","transparent"):E.tspan.setAttributeNS(null,"fill","none"),le===n.TextRenderingMode.STROKE||le===n.TextRenderingMode.FILL_STROKE){let ce=1/(E.textMatrixScale||1);this._setStrokeAttributes(E.tspan,ce)}let ve=E.textMatrix;E.textRise!==0&&(ve=ve.slice(),ve[5]+=E.textRise),E.txtElement.setAttributeNS(null,"transform",`${p(ve)} scale(${l(V)}, -1)`),E.txtElement.setAttributeNS(f,"xml:space","preserve"),E.txtElement.appendChild(E.tspan),E.txtgrp.appendChild(E.txtElement),this._ensureTransformGroup().appendChild(E.txtElement)}setLeadingMoveText(b,E){this.setLeading(-E),this.moveText(b,E)}addFontStyle(b){if(!b.data)throw new Error('addFontStyle: No font data available, ensure that the "fontExtraProperties" API parameter is set.');this.cssStyle||(this.cssStyle=this.svgFactory.createElement("svg:style"),this.cssStyle.setAttributeNS(null,"type","text/css"),this.defs.appendChild(this.cssStyle));let E=_(b.data,b.mimetype,this.forceDataSchema);this.cssStyle.textContent+=`@font-face { font-family: "${b.loadedName}"; src: url(${E}); }
|
|
73
|
-
`}setFont(b){let E=this.current,k=this.commonObjs.get(b[0]),P=b[1];E.font=k,this.embedFonts&&!k.missingFile&&!this.embeddedFonts[k.loadedName]&&(this.addFontStyle(k),this.embeddedFonts[k.loadedName]=k),E.fontMatrix=k.fontMatrix||n.FONT_IDENTITY_MATRIX;let N="normal";k.black?N="900":k.bold&&(N="bold");let D=k.italic?"italic":"normal";P<0?(P=-P,E.fontDirection=-1):E.fontDirection=1,E.fontSize=P,E.fontFamily=k.loadedName,E.fontWeight=N,E.fontStyle=D,E.tspan=this.svgFactory.createElement("svg:tspan"),E.tspan.setAttributeNS(null,"y",l(-E.y)),E.xcoords=[],E.ycoords=[]}endText(){var E;let b=this.current;b.textRenderingMode&n.TextRenderingMode.ADD_TO_PATH_FLAG&&((E=b.txtElement)!=null&&E.hasChildNodes())&&(b.element=b.txtElement,this.clip("nonzero"),this.endPath())}setLineWidth(b){b>0&&(this.current.lineWidth=b)}setLineCap(b){this.current.lineCap=y[b]}setLineJoin(b){this.current.lineJoin=m[b]}setMiterLimit(b){this.current.miterLimit=b}setStrokeAlpha(b){this.current.strokeAlpha=b}setStrokeRGBColor(b,E,k){this.current.strokeColor=n.Util.makeHexColor(b,E,k)}setFillAlpha(b){this.current.fillAlpha=b}setFillRGBColor(b,E,k){this.current.fillColor=n.Util.makeHexColor(b,E,k),this.current.tspan=this.svgFactory.createElement("svg:tspan"),this.current.xcoords=[],this.current.ycoords=[]}setStrokeColorN(b){this.current.strokeColor=this._makeColorN_Pattern(b)}setFillColorN(b){this.current.fillColor=this._makeColorN_Pattern(b)}shadingFill(b){let E=this.viewport.width,k=this.viewport.height,P=n.Util.inverseTransform(this.transformMatrix),N=n.Util.applyTransform([0,0],P),D=n.Util.applyTransform([0,k],P),F=n.Util.applyTransform([E,0],P),B=n.Util.applyTransform([E,k],P),V=Math.min(N[0],D[0],F[0],B[0]),q=Math.min(N[1],D[1],F[1],B[1]),G=Math.max(N[0],D[0],F[0],B[0]),Y=Math.max(N[1],D[1],F[1],B[1]),X=this.svgFactory.createElement("svg:rect");X.setAttributeNS(null,"x",V),X.setAttributeNS(null,"y",q),X.setAttributeNS(null,"width",G-V),X.setAttributeNS(null,"height",Y-q),X.setAttributeNS(null,"fill",this._makeShadingPattern(b)),this.current.fillAlpha<1&&X.setAttributeNS(null,"fill-opacity",this.current.fillAlpha),this._ensureTransformGroup().appendChild(X)}_makeColorN_Pattern(b){return b[0]==="TilingPattern"?this._makeTilingPattern(b):this._makeShadingPattern(b)}_makeTilingPattern(b){let E=b[1],k=b[2],P=b[3]||n.IDENTITY_MATRIX,[N,D,F,B]=b[4],V=b[5],q=b[6],G=b[7],Y=`shading${C++}`,[X,Q,le,ve]=n.Util.normalizeRect([...n.Util.applyTransform([N,D],P),...n.Util.applyTransform([F,B],P)]),[ce,W]=n.Util.singularValueDecompose2dScale(P),H=V*ce,R=q*W,x=this.svgFactory.createElement("svg:pattern");x.setAttributeNS(null,"id",Y),x.setAttributeNS(null,"patternUnits","userSpaceOnUse"),x.setAttributeNS(null,"width",H),x.setAttributeNS(null,"height",R),x.setAttributeNS(null,"x",`${X}`),x.setAttributeNS(null,"y",`${Q}`);let T=this.svg,O=this.transformMatrix,I=this.current.fillColor,U=this.current.strokeColor,z=this.svgFactory.create(le-X,ve-Q);if(this.svg=z,this.transformMatrix=P,G===2){let Z=n.Util.makeHexColor(...E);this.current.fillColor=Z,this.current.strokeColor=Z}return this.executeOpTree(this.convertOpList(k)),this.svg=T,this.transformMatrix=O,this.current.fillColor=I,this.current.strokeColor=U,x.appendChild(z.childNodes[0]),this.defs.appendChild(x),`url(#${Y})`}_makeShadingPattern(b){switch(typeof b=="string"&&(b=this.objs.get(b)),b[0]){case"RadialAxial":let E=`shading${C++}`,k=b[3],P;switch(b[1]){case"axial":let N=b[4],D=b[5];P=this.svgFactory.createElement("svg:linearGradient"),P.setAttributeNS(null,"id",E),P.setAttributeNS(null,"gradientUnits","userSpaceOnUse"),P.setAttributeNS(null,"x1",N[0]),P.setAttributeNS(null,"y1",N[1]),P.setAttributeNS(null,"x2",D[0]),P.setAttributeNS(null,"y2",D[1]);break;case"radial":let F=b[4],B=b[5],V=b[6],q=b[7];P=this.svgFactory.createElement("svg:radialGradient"),P.setAttributeNS(null,"id",E),P.setAttributeNS(null,"gradientUnits","userSpaceOnUse"),P.setAttributeNS(null,"cx",B[0]),P.setAttributeNS(null,"cy",B[1]),P.setAttributeNS(null,"r",q),P.setAttributeNS(null,"fx",F[0]),P.setAttributeNS(null,"fy",F[1]),P.setAttributeNS(null,"fr",V);break;default:throw new Error(`Unknown RadialAxial type: ${b[1]}`)}for(let N of k){let D=this.svgFactory.createElement("svg:stop");D.setAttributeNS(null,"offset",N[0]),D.setAttributeNS(null,"stop-color",N[1]),P.appendChild(D)}return this.defs.appendChild(P),`url(#${E})`;case"Mesh":return(0,n.warn)("Unimplemented pattern Mesh"),null;case"Dummy":return"hotpink";default:throw new Error(`Unknown IR type: ${b[0]}`)}}setDash(b,E){this.current.dashArray=b,this.current.dashPhase=E}constructPath(b,E){let k=this.current,P=k.x,N=k.y,D=[],F=0;for(let B of b)switch(B|0){case n.OPS.rectangle:P=E[F++],N=E[F++];let V=E[F++],q=E[F++],G=P+V,Y=N+q;D.push("M",l(P),l(N),"L",l(G),l(N),"L",l(G),l(Y),"L",l(P),l(Y),"Z");break;case n.OPS.moveTo:P=E[F++],N=E[F++],D.push("M",l(P),l(N));break;case n.OPS.lineTo:P=E[F++],N=E[F++],D.push("L",l(P),l(N));break;case n.OPS.curveTo:P=E[F+4],N=E[F+5],D.push("C",l(E[F]),l(E[F+1]),l(E[F+2]),l(E[F+3]),l(P),l(N)),F+=6;break;case n.OPS.curveTo2:D.push("C",l(P),l(N),l(E[F]),l(E[F+1]),l(E[F+2]),l(E[F+3])),P=E[F+2],N=E[F+3],F+=4;break;case n.OPS.curveTo3:P=E[F+2],N=E[F+3],D.push("C",l(E[F]),l(E[F+1]),l(P),l(N),l(P),l(N)),F+=4;break;case n.OPS.closePath:D.push("Z");break}D=D.join(" "),k.path&&b.length>0&&b[0]!==n.OPS.rectangle&&b[0]!==n.OPS.moveTo?D=k.path.getAttributeNS(null,"d")+D:(k.path=this.svgFactory.createElement("svg:path"),this._ensureTransformGroup().appendChild(k.path)),k.path.setAttributeNS(null,"d",D),k.path.setAttributeNS(null,"fill","none"),k.element=k.path,k.setCurrentPoint(P,N)}endPath(){let b=this.current;if(b.path=null,!this.pendingClip)return;if(!b.element){this.pendingClip=null;return}let E=`clippath${w++}`,k=this.svgFactory.createElement("svg:clipPath");k.setAttributeNS(null,"id",E),k.setAttributeNS(null,"transform",p(this.transformMatrix));let P=b.element.cloneNode(!0);if(this.pendingClip==="evenodd"?P.setAttributeNS(null,"clip-rule","evenodd"):P.setAttributeNS(null,"clip-rule","nonzero"),this.pendingClip=null,k.appendChild(P),this.defs.appendChild(k),b.activeClipUrl){b.clipGroup=null;for(let N of this.extraStack)N.clipGroup=null;k.setAttributeNS(null,"clip-path",b.activeClipUrl)}b.activeClipUrl=`url(#${E})`,this.tgrp=null}clip(b){this.pendingClip=b}closePath(){let b=this.current;if(b.path){let E=`${b.path.getAttributeNS(null,"d")}Z`;b.path.setAttributeNS(null,"d",E)}}setLeading(b){this.current.leading=-b}setTextRise(b){this.current.textRise=b}setTextRenderingMode(b){this.current.textRenderingMode=b}setHScale(b){this.current.textHScale=b/100}setRenderingIntent(b){}setFlatness(b){}setGState(b){for(let[E,k]of b)switch(E){case"LW":this.setLineWidth(k);break;case"LC":this.setLineCap(k);break;case"LJ":this.setLineJoin(k);break;case"ML":this.setMiterLimit(k);break;case"D":this.setDash(k[0],k[1]);break;case"RI":this.setRenderingIntent(k);break;case"FL":this.setFlatness(k);break;case"Font":this.setFont(k);break;case"CA":this.setStrokeAlpha(k);break;case"ca":this.setFillAlpha(k);break;default:(0,n.warn)(`Unimplemented graphic state operator ${E}`);break}}fill(){let b=this.current;b.element&&(b.element.setAttributeNS(null,"fill",b.fillColor),b.element.setAttributeNS(null,"fill-opacity",b.fillAlpha),this.endPath())}stroke(){let b=this.current;b.element&&(this._setStrokeAttributes(b.element),b.element.setAttributeNS(null,"fill","none"),this.endPath())}_setStrokeAttributes(b,E=1){let k=this.current,P=k.dashArray;E!==1&&P.length>0&&(P=P.map(function(N){return E*N})),b.setAttributeNS(null,"stroke",k.strokeColor),b.setAttributeNS(null,"stroke-opacity",k.strokeAlpha),b.setAttributeNS(null,"stroke-miterlimit",l(k.miterLimit)),b.setAttributeNS(null,"stroke-linecap",k.lineCap),b.setAttributeNS(null,"stroke-linejoin",k.lineJoin),b.setAttributeNS(null,"stroke-width",l(E*k.lineWidth)+"px"),b.setAttributeNS(null,"stroke-dasharray",P.map(l).join(" ")),b.setAttributeNS(null,"stroke-dashoffset",l(E*k.dashPhase)+"px")}eoFill(){this.current.element&&this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fill()}fillStroke(){this.stroke(),this.fill()}eoFillStroke(){this.current.element&&this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fillStroke()}closeStroke(){this.closePath(),this.stroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.closePath(),this.eoFillStroke()}paintSolidColorImageMask(){let b=this.svgFactory.createElement("svg:rect");b.setAttributeNS(null,"x","0"),b.setAttributeNS(null,"y","0"),b.setAttributeNS(null,"width","1px"),b.setAttributeNS(null,"height","1px"),b.setAttributeNS(null,"fill",this.current.fillColor),this._ensureTransformGroup().appendChild(b)}paintImageXObject(b){let E=b.startsWith("g_")?this.commonObjs.get(b):this.objs.get(b);if(!E){(0,n.warn)(`Dependent image with object ID ${b} is not ready yet`);return}this.paintInlineImageXObject(E)}paintInlineImageXObject(b,E){let k=b.width,P=b.height,N=v(b,this.forceDataSchema,!!E),D=this.svgFactory.createElement("svg:rect");D.setAttributeNS(null,"x","0"),D.setAttributeNS(null,"y","0"),D.setAttributeNS(null,"width",l(k)),D.setAttributeNS(null,"height",l(P)),this.current.element=D,this.clip("nonzero");let F=this.svgFactory.createElement("svg:image");F.setAttributeNS(u,"xlink:href",N),F.setAttributeNS(null,"x","0"),F.setAttributeNS(null,"y",l(-P)),F.setAttributeNS(null,"width",l(k)+"px"),F.setAttributeNS(null,"height",l(P)+"px"),F.setAttributeNS(null,"transform",`scale(${l(1/k)} ${l(-1/P)})`),E?E.appendChild(F):this._ensureTransformGroup().appendChild(F)}paintImageMaskXObject(b){let E=this.current,k=b.width,P=b.height,N=E.fillColor;E.maskId=`mask${A++}`;let D=this.svgFactory.createElement("svg:mask");D.setAttributeNS(null,"id",E.maskId);let F=this.svgFactory.createElement("svg:rect");F.setAttributeNS(null,"x","0"),F.setAttributeNS(null,"y","0"),F.setAttributeNS(null,"width",l(k)),F.setAttributeNS(null,"height",l(P)),F.setAttributeNS(null,"fill",N),F.setAttributeNS(null,"mask",`url(#${E.maskId})`),this.defs.appendChild(D),this._ensureTransformGroup().appendChild(F),this.paintInlineImageXObject(b,D)}paintFormXObjectBegin(b,E){if(Array.isArray(b)&&b.length===6&&this.transform(b[0],b[1],b[2],b[3],b[4],b[5]),E){let k=E[2]-E[0],P=E[3]-E[1],N=this.svgFactory.createElement("svg:rect");N.setAttributeNS(null,"x",E[0]),N.setAttributeNS(null,"y",E[1]),N.setAttributeNS(null,"width",l(k)),N.setAttributeNS(null,"height",l(P)),this.current.element=N,this.clip("nonzero"),this.endPath()}}paintFormXObjectEnd(){}_initialize(b){let E=this.svgFactory.create(b.width,b.height),k=this.svgFactory.createElement("svg:defs");E.appendChild(k),this.defs=k;let P=this.svgFactory.createElement("svg:g");return P.setAttributeNS(null,"transform",p(b.transform)),E.appendChild(P),this.svg=P,E}_ensureClipGroup(){if(!this.current.clipGroup){let b=this.svgFactory.createElement("svg:g");b.setAttributeNS(null,"clip-path",this.current.activeClipUrl),this.svg.appendChild(b),this.current.clipGroup=b}return this.current.clipGroup}_ensureTransformGroup(){return this.tgrp||(this.tgrp=this.svgFactory.createElement("svg:g"),this.tgrp.setAttributeNS(null,"transform",p(this.transformMatrix)),this.current.activeClipUrl?this._ensureClipGroup().appendChild(this.tgrp):this.svg.appendChild(this.tgrp)),this.tgrp}}}},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PDFNodeStream=void 0;var n=t(1),i=t(26);let o=gf(),s=FC(),c=HC(),f=pf(),u=/^file:\/\/\/[a-zA-Z]:\//;function y(A){let C=f.parse(A);return C.protocol==="file:"||C.host?C:/^[a-z]:[/\\]/i.test(A)?f.parse(`file:///${A}`):(C.host||(C.protocol="file:"),C)}class m{constructor(C){this.source=C,this.url=y(C.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=this.isHttp&&C.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){var C;return((C=this._fullRequestReader)==null?void 0:C._loaded)??0}getFullReader(){return(0,n.assert)(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new p(this):new h(this),this._fullRequestReader}getRangeReader(C,b){if(b<=this._progressiveDataLength)return null;let E=this.isFsUrl?new w(this,C,b):new l(this,C,b);return this._rangeRequestReaders.push(E),E}cancelAllRequests(C){this._fullRequestReader&&this._fullRequestReader.cancel(C);for(let b of this._rangeRequestReaders.slice(0))b.cancel(C)}}e.PDFNodeStream=m;class _{constructor(C){this._url=C.url,this._done=!1,this._storedError=null,this.onProgress=null;let b=C.source;this._contentLength=b.length,this._loaded=0,this._filename=null,this._disableRange=b.disableRange||!1,this._rangeChunkSize=b.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!b.disableStream,this._isRangeSupported=!b.disableRange,this._readableStream=null,this._readCapability=(0,n.createPromiseCapability)(),this._headersCapability=(0,n.createPromiseCapability)()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let C=this._readableStream.read();return C===null?(this._readCapability=(0,n.createPromiseCapability)(),this.read()):(this._loaded+=C.length,this.onProgress&&this.onProgress({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(C).buffer,done:!1})}cancel(C){if(!this._readableStream){this._error(C);return}this._readableStream.destroy(C)}_error(C){this._storedError=C,this._readCapability.resolve()}_setReadableStream(C){this._readableStream=C,C.on("readable",()=>{this._readCapability.resolve()}),C.on("end",()=>{C.destroy(),this._done=!0,this._readCapability.resolve()}),C.on("error",b=>{this._error(b)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new n.AbortException("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class v{constructor(C){this._url=C.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=(0,n.createPromiseCapability)();let b=C.source;this._isStreamingSupported=!b.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let C=this._readableStream.read();return C===null?(this._readCapability=(0,n.createPromiseCapability)(),this.read()):(this._loaded+=C.length,this.onProgress&&this.onProgress({loaded:this._loaded}),{value:new Uint8Array(C).buffer,done:!1})}cancel(C){if(!this._readableStream){this._error(C);return}this._readableStream.destroy(C)}_error(C){this._storedError=C,this._readCapability.resolve()}_setReadableStream(C){this._readableStream=C,C.on("readable",()=>{this._readCapability.resolve()}),C.on("end",()=>{C.destroy(),this._done=!0,this._readCapability.resolve()}),C.on("error",b=>{this._error(b)}),this._storedError&&this._readableStream.destroy(this._storedError)}}function g(A,C){return{protocol:A.protocol,auth:A.auth,host:A.hostname,port:A.port,path:A.path,method:"GET",headers:C}}class h extends _{constructor(C){super(C);let b=E=>{if(E.statusCode===404){let D=new n.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=D,this._headersCapability.reject(D);return}this._headersCapability.resolve(),this._setReadableStream(E);let k=D=>this._readableStream.headers[D.toLowerCase()],{allowRangeRequests:P,suggestedLength:N}=(0,i.validateRangeRequestCapabilities)({getResponseHeader:k,isHttp:C.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=P,this._contentLength=N||this._contentLength,this._filename=(0,i.extractFilenameFromHeader)(k)};this._request=null,this._url.protocol==="http:"?this._request=s.request(g(this._url,C.httpHeaders),b):this._request=c.request(g(this._url,C.httpHeaders),b),this._request.on("error",E=>{this._storedError=E,this._headersCapability.reject(E)}),this._request.end()}}class l extends v{constructor(C,b,E){super(C),this._httpHeaders={};for(let P in C.httpHeaders){let N=C.httpHeaders[P];typeof N>"u"||(this._httpHeaders[P]=N)}this._httpHeaders.Range=`bytes=${b}-${E-1}`;let k=P=>{if(P.statusCode===404){let N=new n.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=N;return}this._setReadableStream(P)};this._request=null,this._url.protocol==="http:"?this._request=s.request(g(this._url,this._httpHeaders),k):this._request=c.request(g(this._url,this._httpHeaders),k),this._request.on("error",P=>{this._storedError=P}),this._request.end()}}class p extends _{constructor(C){super(C);let b=decodeURIComponent(this._url.path);u.test(this._url.href)&&(b=b.replace(/^\//,"")),o.lstat(b,(E,k)=>{if(E){E.code==="ENOENT"&&(E=new n.MissingPDFException(`Missing PDF "${b}".`)),this._storedError=E,this._headersCapability.reject(E);return}this._contentLength=k.size,this._setReadableStream(o.createReadStream(b)),this._headersCapability.resolve()})}}class w extends v{constructor(C,b,E){super(C);let k=decodeURIComponent(this._url.path);u.test(this._url.href)&&(k=k.replace(/^\//,"")),this._setReadableStream(o.createReadStream(k,{start:b,end:E-1}))}}},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createResponseStatusError=f,e.extractFilenameFromHeader=c,e.validateRangeRequestCapabilities=s,e.validateResponseStatus=u;var n=t(1),i=t(27),o=t(5);function s({getResponseHeader:y,isHttp:m,rangeChunkSize:_,disableRange:v}){let g={allowRangeRequests:!1,suggestedLength:void 0},h=parseInt(y("Content-Length"),10);return!Number.isInteger(h)||(g.suggestedLength=h,h<=2*_)||v||!m||y("Accept-Ranges")!=="bytes"||(y("Content-Encoding")||"identity")!=="identity"||(g.allowRangeRequests=!0),g}function c(y){let m=y("Content-Disposition");if(m){let _=(0,i.getFilenameFromContentDispositionHeader)(m);if(_.includes("%"))try{_=decodeURIComponent(_)}catch{}if((0,o.isPdfFile)(_))return _}return null}function f(y,m){return y===404||y===0&&m.startsWith("file:")?new n.MissingPDFException('Missing PDF "'+m+'".'):new n.UnexpectedResponseException(`Unexpected server response (${y}) while retrieving PDF "${m}".`,y)}function u(y){return y===200||y===206}},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getFilenameFromContentDispositionHeader=i;var n=t(1);function i(o){let s=!0,c=f("filename\\*","i").exec(o);if(c){c=c[1];let h=_(c);return h=unescape(h),h=v(h),h=g(h),y(h)}if(c=m(o),c){let h=g(c);return y(h)}if(c=f("filename","i").exec(o),c){c=c[1];let h=_(c);return h=g(h),y(h)}function f(h,l){return new RegExp("(?:^|;)\\s*"+h+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',l)}function u(h,l){if(h){if(!/^[\x00-\xFF]+$/.test(l))return l;try{let p=new TextDecoder(h,{fatal:!0}),w=(0,n.stringToBytes)(l);l=p.decode(w),s=!1}catch{}}return l}function y(h){return s&&/[\x80-\xff]/.test(h)&&(h=u("utf-8",h),s&&(h=u("iso-8859-1",h))),h}function m(h){let l=[],p,w=f("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(p=w.exec(h))!==null;){let[,C,b,E]=p;if(C=parseInt(C,10),C in l){if(C===0)break;continue}l[C]=[b,E]}let A=[];for(let C=0;C<l.length&&C in l;++C){let[b,E]=l[C];E=_(E),b&&(E=unescape(E),C===0&&(E=v(E))),A.push(E)}return A.join("")}function _(h){if(h.startsWith('"')){let l=h.slice(1).split('\\"');for(let p=0;p<l.length;++p){let w=l[p].indexOf('"');w!==-1&&(l[p]=l[p].slice(0,w),l.length=p+1),l[p]=l[p].replace(/\\(.)/g,"$1")}h=l.join('"')}return h}function v(h){let l=h.indexOf("'");if(l===-1)return h;let p=h.slice(0,l),A=h.slice(l+1).replace(/^[^']*'/,"");return u(p,A)}function g(h){return!h.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(h)?h:h.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(l,p,w,A){if(w==="q"||w==="Q")return A=A.replace(/_/g," "),A=A.replace(/=([0-9a-fA-F]{2})/g,function(C,b){return String.fromCharCode(parseInt(b,16))}),u(p,A);try{A=atob(A)}catch{}return u(p,A)})}return""}},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PDFNetworkStream=void 0;var n=t(1),i=t(26);let o=200,s=206;function c(_){let v=_.response;return typeof v!="string"?v:(0,n.stringToBytes)(v).buffer}class f{constructor(v,g={}){this.url=v,this.isHttp=/^https?:/i.test(v),this.httpHeaders=this.isHttp&&g.httpHeaders||Object.create(null),this.withCredentials=g.withCredentials||!1,this.getXhr=g.getXhr||function(){return new XMLHttpRequest},this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(v,g,h){let l={begin:v,end:g};for(let p in h)l[p]=h[p];return this.request(l)}requestFull(v){return this.request(v)}request(v){let g=this.getXhr(),h=this.currXhrId++,l=this.pendingRequests[h]={xhr:g};g.open("GET",this.url),g.withCredentials=this.withCredentials;for(let p in this.httpHeaders){let w=this.httpHeaders[p];typeof w>"u"||g.setRequestHeader(p,w)}return this.isHttp&&"begin"in v&&"end"in v?(g.setRequestHeader("Range",`bytes=${v.begin}-${v.end-1}`),l.expectedStatus=s):l.expectedStatus=o,g.responseType="arraybuffer",v.onError&&(g.onerror=function(p){v.onError(g.status)}),g.onreadystatechange=this.onStateChange.bind(this,h),g.onprogress=this.onProgress.bind(this,h),l.onHeadersReceived=v.onHeadersReceived,l.onDone=v.onDone,l.onError=v.onError,l.onProgress=v.onProgress,g.send(null),h}onProgress(v,g){var l;let h=this.pendingRequests[v];h&&((l=h.onProgress)==null||l.call(h,g))}onStateChange(v,g){var C,b,E;let h=this.pendingRequests[v];if(!h)return;let l=h.xhr;if(l.readyState>=2&&h.onHeadersReceived&&(h.onHeadersReceived(),delete h.onHeadersReceived),l.readyState!==4||!(v in this.pendingRequests))return;if(delete this.pendingRequests[v],l.status===0&&this.isHttp){(C=h.onError)==null||C.call(h,l.status);return}let p=l.status||o;if(!(p===o&&h.expectedStatus===s)&&p!==h.expectedStatus){(b=h.onError)==null||b.call(h,l.status);return}let A=c(l);if(p===s){let k=l.getResponseHeader("Content-Range"),P=/bytes (\d+)-(\d+)\/(\d+)/.exec(k);h.onDone({begin:parseInt(P[1],10),chunk:A})}else A?h.onDone({begin:0,chunk:A}):(E=h.onError)==null||E.call(h,l.status)}getRequestXhr(v){return this.pendingRequests[v].xhr}isPendingRequest(v){return v in this.pendingRequests}abortRequest(v){let g=this.pendingRequests[v].xhr;delete this.pendingRequests[v],g.abort()}}class u{constructor(v){this._source=v,this._manager=new f(v.url,{httpHeaders:v.httpHeaders,withCredentials:v.withCredentials}),this._rangeChunkSize=v.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(v){let g=this._rangeRequestReaders.indexOf(v);g>=0&&this._rangeRequestReaders.splice(g,1)}getFullReader(){return(0,n.assert)(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new y(this._manager,this._source),this._fullRequestReader}getRangeReader(v,g){let h=new m(this._manager,v,g);return h.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(h),h}cancelAllRequests(v){var g;(g=this._fullRequestReader)==null||g.cancel(v);for(let h of this._rangeRequestReaders.slice(0))h.cancel(v)}}e.PDFNetworkStream=u;class y{constructor(v,g){this._manager=v;let h={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=g.url,this._fullRequestId=v.requestFull(h),this._headersReceivedCapability=(0,n.createPromiseCapability)(),this._disableRange=g.disableRange||!1,this._contentLength=g.length,this._rangeChunkSize=g.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){let v=this._fullRequestId,g=this._manager.getRequestXhr(v),h=w=>g.getResponseHeader(w),{allowRangeRequests:l,suggestedLength:p}=(0,i.validateRangeRequestCapabilities)({getResponseHeader:h,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});l&&(this._isRangeSupported=!0),this._contentLength=p||this._contentLength,this._filename=(0,i.extractFilenameFromHeader)(h),this._isRangeSupported&&this._manager.abortRequest(v),this._headersReceivedCapability.resolve()}_onDone(v){if(v&&(this._requests.length>0?this._requests.shift().resolve({value:v.chunk,done:!1}):this._cachedChunks.push(v.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(let g of this._requests)g.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(v){this._storedError=(0,i.createResponseStatusError)(v,this._url),this._headersReceivedCapability.reject(this._storedError);for(let g of this._requests)g.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(v){var g;(g=this.onProgress)==null||g.call(this,{loaded:v.loaded,total:v.lengthComputable?v.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersReceivedCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let v=(0,n.createPromiseCapability)();return this._requests.push(v),v.promise}cancel(v){this._done=!0,this._headersReceivedCapability.reject(v);for(let g of this._requests)g.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class m{constructor(v,g,h){this._manager=v;let l={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=v.url,this._requestId=v.requestRange(g,h,l),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){var v;(v=this.onClosed)==null||v.call(this,this)}_onDone(v){let g=v.chunk;this._requests.length>0?this._requests.shift().resolve({value:g,done:!1}):this._queuedChunk=g,this._done=!0;for(let h of this._requests)h.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(v){this._storedError=(0,i.createResponseStatusError)(v,this._url);for(let g of this._requests)g.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(v){var g;this.isStreamingSupported||(g=this.onProgress)==null||g.call(this,{loaded:v.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){let g=this._queuedChunk;return this._queuedChunk=null,{value:g,done:!1}}if(this._done)return{value:void 0,done:!0};let v=(0,n.createPromiseCapability)();return this._requests.push(v),v.promise}cancel(v){this._done=!0;for(let g of this._requests)g.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PDFFetchStream=void 0;var n=t(1),i=t(26);function o(y,m,_){return{method:"GET",headers:y,signal:_==null?void 0:_.signal,mode:"cors",credentials:m?"include":"same-origin",redirect:"follow"}}function s(y){let m=new Headers;for(let _ in y){let v=y[_];typeof v>"u"||m.append(_,v)}return m}class c{constructor(m){this.source=m,this.isHttp=/^https?:/i.test(m.url),this.httpHeaders=this.isHttp&&m.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){var m;return((m=this._fullRequestReader)==null?void 0:m._loaded)??0}getFullReader(){return(0,n.assert)(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new f(this),this._fullRequestReader}getRangeReader(m,_){if(_<=this._progressiveDataLength)return null;let v=new u(this,m,_);return this._rangeRequestReaders.push(v),v}cancelAllRequests(m){this._fullRequestReader&&this._fullRequestReader.cancel(m);for(let _ of this._rangeRequestReaders.slice(0))_.cancel(m)}}e.PDFFetchStream=c;class f{constructor(m){this._stream=m,this._reader=null,this._loaded=0,this._filename=null;let _=m.source;this._withCredentials=_.withCredentials||!1,this._contentLength=_.length,this._headersCapability=(0,n.createPromiseCapability)(),this._disableRange=_.disableRange||!1,this._rangeChunkSize=_.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),typeof AbortController<"u"&&(this._abortController=new AbortController),this._isStreamingSupported=!_.disableStream,this._isRangeSupported=!_.disableRange,this._headers=s(this._stream.httpHeaders);let v=_.url;fetch(v,o(this._headers,this._withCredentials,this._abortController)).then(g=>{if(!(0,i.validateResponseStatus)(g.status))throw(0,i.createResponseStatusError)(g.status,v);this._reader=g.body.getReader(),this._headersCapability.resolve();let h=w=>g.headers.get(w),{allowRangeRequests:l,suggestedLength:p}=(0,i.validateRangeRequestCapabilities)({getResponseHeader:h,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=l,this._contentLength=p||this._contentLength,this._filename=(0,i.extractFilenameFromHeader)(h),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new n.AbortException("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;let{value:m,done:_}=await this._reader.read();return _?{value:m,done:_}:(this._loaded+=m.byteLength,this.onProgress&&this.onProgress({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(m).buffer,done:!1})}cancel(m){this._reader&&this._reader.cancel(m),this._abortController&&this._abortController.abort()}}class u{constructor(m,_,v){this._stream=m,this._reader=null,this._loaded=0;let g=m.source;this._withCredentials=g.withCredentials||!1,this._readCapability=(0,n.createPromiseCapability)(),this._isStreamingSupported=!g.disableStream,typeof AbortController<"u"&&(this._abortController=new AbortController),this._headers=s(this._stream.httpHeaders),this._headers.append("Range",`bytes=${_}-${v-1}`);let h=g.url;fetch(h,o(this._headers,this._withCredentials,this._abortController)).then(l=>{if(!(0,i.validateResponseStatus)(l.status))throw(0,i.createResponseStatusError)(l.status,h);this._readCapability.resolve(),this._reader=l.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;let{value:m,done:_}=await this._reader.read();return _?{value:m,done:_}:(this._loaded+=m.byteLength,this.onProgress&&this.onProgress({loaded:this._loaded}),{value:new Uint8Array(m).buffer,done:!1})}cancel(m){this._reader&&this._reader.cancel(m),this._abortController&&this._abortController.abort()}}}],__webpack_module_cache__={};function __w_pdfjs_require__(r){var e=__webpack_module_cache__[r];if(e!==void 0)return e.exports;var t=__webpack_module_cache__[r]={exports:{}};return __webpack_modules__[r](t,t.exports,__w_pdfjs_require__),t.exports}var __webpack_exports__={};return(()=>{var r=__webpack_exports__;Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"AnnotationLayer",{enumerable:!0,get:function(){return i.AnnotationLayer}}),Object.defineProperty(r,"AnnotationMode",{enumerable:!0,get:function(){return e.AnnotationMode}}),Object.defineProperty(r,"CMapCompressionType",{enumerable:!0,get:function(){return e.CMapCompressionType}}),Object.defineProperty(r,"GlobalWorkerOptions",{enumerable:!0,get:function(){return o.GlobalWorkerOptions}}),Object.defineProperty(r,"InvalidPDFException",{enumerable:!0,get:function(){return e.InvalidPDFException}}),Object.defineProperty(r,"LoopbackPort",{enumerable:!0,get:function(){return t.LoopbackPort}}),Object.defineProperty(r,"MissingPDFException",{enumerable:!0,get:function(){return e.MissingPDFException}}),Object.defineProperty(r,"OPS",{enumerable:!0,get:function(){return e.OPS}}),Object.defineProperty(r,"PDFDataRangeTransport",{enumerable:!0,get:function(){return t.PDFDataRangeTransport}}),Object.defineProperty(r,"PDFDateString",{enumerable:!0,get:function(){return n.PDFDateString}}),Object.defineProperty(r,"PDFWorker",{enumerable:!0,get:function(){return t.PDFWorker}}),Object.defineProperty(r,"PasswordResponses",{enumerable:!0,get:function(){return e.PasswordResponses}}),Object.defineProperty(r,"PermissionFlag",{enumerable:!0,get:function(){return e.PermissionFlag}}),Object.defineProperty(r,"PixelsPerInch",{enumerable:!0,get:function(){return n.PixelsPerInch}}),Object.defineProperty(r,"RenderingCancelledException",{enumerable:!0,get:function(){return n.RenderingCancelledException}}),Object.defineProperty(r,"SVGGraphics",{enumerable:!0,get:function(){return f.SVGGraphics}}),Object.defineProperty(r,"UNSUPPORTED_FEATURES",{enumerable:!0,get:function(){return e.UNSUPPORTED_FEATURES}}),Object.defineProperty(r,"UnexpectedResponseException",{enumerable:!0,get:function(){return e.UnexpectedResponseException}}),Object.defineProperty(r,"Util",{enumerable:!0,get:function(){return e.Util}}),Object.defineProperty(r,"VerbosityLevel",{enumerable:!0,get:function(){return e.VerbosityLevel}}),Object.defineProperty(r,"XfaLayer",{enumerable:!0,get:function(){return u.XfaLayer}}),Object.defineProperty(r,"build",{enumerable:!0,get:function(){return t.build}}),Object.defineProperty(r,"createPromiseCapability",{enumerable:!0,get:function(){return e.createPromiseCapability}}),Object.defineProperty(r,"createValidAbsoluteUrl",{enumerable:!0,get:function(){return e.createValidAbsoluteUrl}}),Object.defineProperty(r,"getDocument",{enumerable:!0,get:function(){return t.getDocument}}),Object.defineProperty(r,"getFilenameFromUrl",{enumerable:!0,get:function(){return n.getFilenameFromUrl}}),Object.defineProperty(r,"getPdfFilenameFromUrl",{enumerable:!0,get:function(){return n.getPdfFilenameFromUrl}}),Object.defineProperty(r,"getXfaPageViewport",{enumerable:!0,get:function(){return n.getXfaPageViewport}}),Object.defineProperty(r,"isPdfFile",{enumerable:!0,get:function(){return n.isPdfFile}}),Object.defineProperty(r,"loadScript",{enumerable:!0,get:function(){return n.loadScript}}),Object.defineProperty(r,"renderTextLayer",{enumerable:!0,get:function(){return c.renderTextLayer}}),Object.defineProperty(r,"shadow",{enumerable:!0,get:function(){return e.shadow}}),Object.defineProperty(r,"version",{enumerable:!0,get:function(){return t.version}});var e=__w_pdfjs_require__(1),t=__w_pdfjs_require__(4),n=__w_pdfjs_require__(5),i=__w_pdfjs_require__(20),o=__w_pdfjs_require__(13),s=__w_pdfjs_require__(3),c=__w_pdfjs_require__(23),f=__w_pdfjs_require__(24),u=__w_pdfjs_require__(22);let y="2.14.305",m="eaaa8b4ad";if(s.isNodeJS){let{PDFNodeStream:_}=__w_pdfjs_require__(25);(0,t.setPDFNetworkStreamFactory)(v=>new _(v))}else{let{PDFNetworkStream:_}=__w_pdfjs_require__(28),{PDFFetchStream:v}=__w_pdfjs_require__(29);(0,t.setPDFNetworkStreamFactory)(g=>(0,n.isValidFetchUrl)(g.url)?new v(g):new _(g))}})(),__webpack_exports__})())});var YU={};F0(YU,{Link:()=>au,default:()=>JU,load:()=>KU});L();L();L();var r4=rt(e4()),n4=rt(Tr());L();var t4=rt(Tr());function ba(r,e){return t4.TaJson.deserialize(r,e)}var uo=class extends r4.Publication{static async fromUrl(e,t){let i=await(await fetch(e.href,t)).json(),o=ba(i,uo);return o.manifestUrl=e,o}get readingOrder(){return this.Spine??[]}get resources(){return this.Resources??[]}get tableOfContents(){var e,t;return(e=this.sample)!=null&&e.isSampleRead&&((t=this.positions)==null?void 0:t.length)>0?this.limitedTOC():this.TOC||[]}limitedTOC(){var n;function e(i){for(let o=0;o<i.Children.length;o++){let s=i.Children[o];s.Href=void 0,s.Children&&e(s)}}return((n=this.TOC)==null?void 0:n.map(i=>{var o,s;if(i.Href){let c=this.positionsByHref(this.getRelativeHref(i.Href));if((c==null?void 0:c.length)>0){let f=c[0],u=Math.round((f.locations.totalProgression?f.locations.totalProgression:0)*100);(o=this.sample)!=null&&o.limit&&(u<=((s=this.sample)==null?void 0:s.limit)||(i.Href=void 0,i.Children&&e(i)))}}return i}))||[]}get landmarks(){return this.Landmarks}get pageList(){return this.PageList}get isFixedLayout(){var e;return((e=this.Metadata.Rendition)==null?void 0:e.Layout)==="fixed"}get isReflowable(){return!this.isFixedLayout}get layout(){return this.isFixedLayout?"fixed":"reflowable"}get hasMediaOverlays(){return this.readingOrder?this.readingOrder.filter(e=>{var t;return(t=e.Properties)==null?void 0:t.MediaOverlay}).length>0:!1}getStartLink(){if(this.readingOrder!==void 0&&this.readingOrder.length>0)return this.readingOrder[0]}getPreviousSpineItem(e){let t=this.getSpineIndex(e);if(t!==void 0&&this.readingOrder!==void 0&&t>0)return this.readingOrder[t-1]}getNextSpineItem(e){let t=this.getSpineIndex(e);if(t!==void 0&&this.readingOrder!==void 0&&t<this.readingOrder.length-1)return this.readingOrder[t+1]}getSpineItem(e){let t=this.getSpineIndex(e);if(t!==void 0&&this.readingOrder!==void 0)return this.readingOrder[t]}getSpineIndex(e){var t;return(t=this.readingOrder)==null?void 0:t.findIndex(n=>n.Href&&this.getAbsoluteHref(n.Href)===e)}getAbsoluteHref(e){return new URL(e,this.manifestUrl.href).href}getRelativeHref(e){let t=this.manifestUrl.href.replace("/manifest.json",""),n=e.replace(t,"");return n.indexOf("#")>0&&(n=n.slice(0,n.indexOf("#"))),n.charAt(0)==="/"&&(n=n.substring(1)),n}getTOCItemAbsolute(e){let t=this.getAbsoluteHref(e),n=(o,s)=>{for(let c=0;c<s.length;c++){let f=s[c];if(f.Href){let u=f.Href.indexOf("#")!==-1?f.Href.slice(0,f.Href.indexOf("#")):f.Href;if(this.getAbsoluteHref(u)===o)return f}if(f.Children){let u=n(o,f.Children);if(u!==void 0)return u}}},i=n(t,this.tableOfContents);return i===void 0&&this.readingOrder!==void 0&&(i=n(t,this.readingOrder)),i}getTOCItem(e){let t=(i,o)=>{for(let s=0;s<o.length;s++){let c=o[s];if(c.Href&&this.getAbsoluteHref(c.Href)===i)return c;if(c.Children){let f=t(i,c.Children);if(f!==void 0)return f}}},n=t(e,this.tableOfContents);if(n===void 0&&this.readingOrder!==void 0&&(n=t(e,this.readingOrder)),n===void 0&&e.indexOf("#")!==-1){let i=e.slice(0,e.indexOf("#"));n=t(i,this.tableOfContents),n===void 0&&this.readingOrder!==void 0&&(n=t(i,this.readingOrder))}return n}positionsByHref(e){var n;let t=decodeURI(e)??"";return(n=this.positions)==null?void 0:n.filter(i=>t.includes(i.href))}async autoGeneratePositions(e,t=QR){let n=0,i=0,o=[];if(this.readingOrder!==void 0)for(let c of this.readingOrder)if(this.isFixedLayout){let f={href:c.Href,locations:{progression:0,position:n+1},type:c.TypeLink};o.push(f),n=n+1}else{let f=this.getAbsoluteHref(c.Href),u=await t(f,e);c.contentLength=u,i+=u;let m=Math.max(1,Math.ceil(u/1024));for(let _=0;_<m;_++){let v={href:c.Href,locations:{progression:_/m,position:n+(_+1)},type:c.TypeLink};o.push(v)}n=n+m}var s=0;if(this.isReflowable&&this.readingOrder!==void 0)for(let c of this.readingOrder){if(!c.contentLength){console.error("Link is missing contentLength",c);return}c.contentWeight=100/i*c.contentLength,s=s+c.contentWeight}for(let c of o){let f=o.filter(y=>y.href===decodeURI(c.href)),u=Math.ceil((c.locations.progression?c.locations.progression:0)*(f.length-1));c.locations.position&&(c.locations.totalProgression=(c.locations.position-1)/o.length),c.locations.remainingPositions=Math.abs(u-(f.length-1)),c.locations.position&&(c.locations.totalRemainingPositions=Math.abs(c.locations.position-1-(o.length-1)))}this.positions=o}async fetchPositionsFromService(e,t){let i=await(await fetch(e,t)).json();this.positions=i.positions}async fetchWeightsFromService(e,t){if(this.isFixedLayout){console.warn("Not fetching weights from service for fixed layout publication.");return}let i=await(await fetch(e,t)).json();this.readingOrder!==void 0&&this.readingOrder.forEach(o=>{o.contentWeight=i[o.Href]})}};uo=Lc([(0,n4.JsonObject)()],uo);var QR=async(r,e)=>(await(await fetch(r,e)).blob()).size;L();L();var Ss=class{json(){return JSON.stringify(this)}},Up=class extends Ss{constructor(e,t,n){super(),this.value=e,this.ref=t,this.name=n}toString(){return this.value}},jp=class extends Ss{constructor(e,t,n){super(),this.value=e,this.ref=t,this.name=n}toString(){return this.value}toJson(){return JSON.parse(this.value)}},qp=class extends Ss{constructor(e,t,n,i){super(),this.value=e,this.values=t,this.ref=n,this.name=i}toString(){return this.values[this.value]}},Gp=class extends Ss{constructor(t,n,i,o,s,c,f){super();this.countDecimals=function(t){return t%1!==0?t.toString().split(".")[1].length:1};this.value=t,this.min=n,this.max=i,this.step=o,this.suffix=s,this.ref=c,this.name=f}toString(){return this.value.toString()+this.suffix}increment(){let t=this.countDecimals(this.max);parseFloat(this.value.toFixed(t))<this.max&&(this.value=parseFloat(this.value.toFixed(t))+this.step)}decrement(){let t=this.countDecimals(this.min);parseFloat(this.value.toFixed(t))>this.min&&(this.value=parseFloat(this.value.toFixed(t))-this.step)}},va=class extends Ss{constructor(e,t,n,i,o){super(),this.value=n,this.onValue=e,this.offValue=t,this.ref=i,this.name=o}toString(){return this.value?this.onValue:this.offValue}switch(){this.value=!this.value}},ki=class{constructor(){this.properties=[]}addIncremental(e,t,n,i,o,s,c){this.properties.push(new Gp(e,t,n,i,o,s,c))}addStringable(e,t,n){this.properties.push(new Up(e,t,n))}addJSONable(e,t,n){this.properties.push(new jp(e,t,n))}addSwitchable(e,t,n,i,o){this.properties.push(new va(e,t,n,i,o))}addEnumerable(e,t,n,i){this.properties.push(new qp(e,t,n,i))}getByRef(e){let t=this.properties.filter(n=>n.ref===e);return t.length>0?t[0]:null}getByKey(e){let t=this.properties.filter(n=>n.key===e);return t.length>0?t[0]:null}};L();var xt=class xt{};xt.FONT_SIZE_REF="fontSize",xt.FONT_FAMILY_REF="fontFamily",xt.FONT_OVERRIDE_REF="fontOverride",xt.APPEARANCE_REF="appearance",xt.SCROLL_REF="scroll",xt.TEXT_ALIGNMENT_REF="textAlign",xt.COLUMN_COUNT_REF="colCount",xt.WORD_SPACING_REF="wordSpacing",xt.LETTER_SPACING_REF="letterSpacing",xt.PAGE_MARGINS_REF="pageMargins",xt.LINE_HEIGHT_REF="lineHeight",xt.FONT_SIZE_KEY="--USER__"+xt.FONT_SIZE_REF,xt.FONT_FAMILY_KEY="--USER__"+xt.FONT_FAMILY_REF,xt.FONT_OVERRIDE_KEY="--USER__"+xt.FONT_OVERRIDE_REF,xt.APPEARANCE_KEY="--USER__"+xt.APPEARANCE_REF,xt.SCROLL_KEY="--USER__"+xt.SCROLL_REF,xt.TEXT_ALIGNMENT_KEY="--USER__"+xt.TEXT_ALIGNMENT_REF,xt.COLUMN_COUNT_KEY="--USER__"+xt.COLUMN_COUNT_REF,xt.WORD_SPACING_KEY="--USER__"+xt.WORD_SPACING_REF,xt.LETTER_SPACING_KEY="--USER__"+xt.LETTER_SPACING_REF,xt.PAGE_MARGINS_KEY="--USER__"+xt.PAGE_MARGINS_REF,xt.LINE_HEIGHT_KEY="--USER__"+xt.LINE_HEIGHT_REF;var Se=xt;L();function Ne(r,e){return r.querySelector(e)}function ft(r,e){let t=Ne(r,e);if(t&&t instanceof HTMLElement)return t;throw new Error("required element "+e+" not found")}function cr(r,e){if(r===null)throw new Error("parent element is null");return r.querySelector(e)}function lo(r,e){let t=cr(r,e);if(t)return t;throw new Error("required element "+e+" not found in iframe")}function Lr(r,e,t){r.setAttribute(e,t)}L();L();var Q6=rt(Hg());var Ia=class{constructor(e){this.getScrollingElement=e=>e.scrollingElement?e.scrollingElement:e.body;this.navigator=e}async handleFootnote(e,t){var i,o;let n=e.getAttribute("href");if(n&&n.indexOf("#")>0){let c=function(u){let y=document.location.href;return new URL(u,y).href},s=n.substring(n.indexOf("#")+1),f=c(n);f&&(f=f.substring(0,f.indexOf("#")),t.preventDefault(),t.stopPropagation(),(i=this.navigator.api)!=null&&i.getContent?await((o=this.navigator.api)==null?void 0:o.getContent(n).then(u=>{let _=new DOMParser().parseFromString(u,"text/html").querySelector("#"+s);_&&(t.preventDefault(),t.stopPropagation(),this.showPopup(_,t))})):await fetch(f,this.navigator.requestConfig).then(u=>u.text()).then(async u=>{let _=new DOMParser().parseFromString(u,"text/html").querySelector("#"+s);_&&(t.preventDefault(),t.stopPropagation(),this.showPopup(_,t))}))}}async hidePopover(){var n,i;let e=(n=this.navigator.iframes[0].contentDocument)==null?void 0:n.getElementById("d2-popover");e&&((i=e.parentElement)==null||i.removeChild(e));let t=ft(document,"#iframe-wrapper");t.style.overflow="auto"}async showPopover(e,t){var s,c,f,u,y,m;let n=e.getAttribute("href"),i=e.getAttribute("src");function o(_){let v=document.location.href;return new URL(_,v).href}if(n){let _=o(n);if(_){t.preventDefault(),t.stopPropagation();let v=(s=this.navigator.iframes[0].contentDocument)==null?void 0:s.getElementById("d2-popover");v&&((c=v.parentElement)==null||c.removeChild(v));let g=document.createElement("div");g.id="d2-popover",g.className="d2-popover is-active";let h=ft(document,"#iframe-wrapper");h.style.overflow="hidden",g.style.top=h.scrollTop+"px",g.style.height=h.clientHeight*.9+"px";let l=document.createElement("div");l.className="d2-popover-wrapper",g.appendChild(l);let p=document.createElement("div");p.className="d2-popover-content",l.appendChild(p),(f=this.navigator.api)!=null&&f.getContent?await((u=this.navigator.api)==null?void 0:u.getContent(n).then(C=>{p.innerHTML=C;let b=this.navigator.iframes[0].contentDocument;b&&b.body.appendChild(g)})):await fetch(_,this.navigator.requestConfig).then(C=>C.text()).then(async C=>{p.innerHTML=C;let b=this.navigator.iframes[0].contentDocument;b&&b.body.appendChild(g)});let w=this.navigator.iframes[0].contentWindow;if(!w)return;let A=this;w.onclick=function(C){t.target!==C.target&&g.parentElement&&(A.hidePopover(),w&&(w.onclick=null))}}}else if(i&&o(i)){t.preventDefault(),t.stopPropagation();let v=(y=this.navigator.iframes[0].contentDocument)==null?void 0:y.getElementById("d2-popover");v&&((m=v.parentElement)==null||m.removeChild(v));let g=document.createElement("div");g.id="d2-popover",g.className="d2-popover is-active";let h=ft(document,"#iframe-wrapper");h.style.overflow="hidden",g.style.top=h.scrollTop+"px",g.style.height=h.clientHeight*.9+"px";let l=document.createElement("div");l.className="d2-popover-wrapper",g.appendChild(l);let p=document.createElement("img");p.className="d2-popover-content",l.appendChild(p),p.src=i;let w=this.navigator.iframes[0].contentDocument;w&&w.body.appendChild(g);let A=this.navigator.iframes[0].contentWindow;if(!A)return;let C=this;A.onclick=function(b){t.target!==b.target&&g.parentElement&&(C.hidePopover(),A&&(A.onclick=null))}}}showPopup(e,t){var l,p,w;let n=(l=this.navigator.iframes[0].contentDocument)==null?void 0:l.getElementById("d2-popup");n&&((p=n.parentElement)==null||p.removeChild(n));let i=document.createElement("aside");i.id="d2-popup",i.className="d2-popup is-active";let o=document.createElement("div");o.className="d2-popup-wrapper",i.appendChild(o);let s=document.createElement("div");s.className="d2-popup-content",o.appendChild(s);let c=document.createElement("p");s.appendChild(c),typeof e=="string"?c.innerHTML=e:c.innerHTML=(0,Q6.default)(e.innerHTML,{allowedTags:[],allowedAttributes:{}});let f=(w=this.navigator.view)==null?void 0:w.isPaginated(),u=this.navigator.iframes[0].contentDocument;if(!u)return;let y=this.getScrollingElement(u),m=f?y.scrollLeft:0,_=f?y.scrollTop:0,v=t.x+m,g=t.y+_;i.style.top=g+"px",f&&(i.style.left=v+"px"),u.body.appendChild(i);let h=this.navigator.iframes[0].contentWindow;h&&(h.onclick=function(A){t.target!==A.target&&i.parentElement&&(i.style.display="none",i.parentElement.removeChild(i),h&&(h.onclick=null))})}};var Pf=rt($t());function _e(r,e,t){r&&r.addEventListener(e,t,!0)}function Ue(r,e,t){r&&r.removeEventListener(e,t,!0)}var yl=class{constructor(e){this.onInternalLink=()=>{};this.onClickThrough=()=>{};this.checkForLink=e=>{let t=e.target;for(;t&&t.tagName.toLowerCase()!=="body";){if(t.tagName.toLowerCase()==="a"&&t.href)return t;t=t.parentElement}return null};this.linkInPublication=(e,t)=>e.some(n=>{var i;return!((i=n.Rel)!=null&&i.includes("external"))&&this.navigator.publication.getRelativeHref(t).includes(n.Href)});this.isReadingOrderInternal=e=>(Pf.default.log("clickedLink: ",e),this.linkInPublication(this.navigator.publication.readingOrder,e.href));this.isResourceInternal=e=>(Pf.default.log("clickedLink: ",e),this.linkInPublication(this.navigator.publication.resources,e.href));this.handleLinks=async e=>{Pf.default.log("R2 Click Handler");let t=this.checkForLink(e);if(t){let n=window.location.protocol===t.protocol&&window.location.port===t.port&&window.location.hostname===t.hostname,i=this.isReadingOrderInternal(t),o=this.isResourceInternal(t);o||await this.popup.hidePopover();let s=t.href.indexOf("#");if(!i&&!o)window.open(t.href,t.target??"_blank"),e.preventDefault(),e.stopPropagation();else if(e.target.href=t.href,(n||i)&&s!==-1){let c=e.target;c?c.getAttribute("epub:type")==="noteref"?await this.popup.handleFootnote(c,e):o&&!i?await this.popup.showPopover(c,e):this.onInternalLink(e):this.onInternalLink(e)}else(n||i)&&s===-1&&this.onInternalLink(e)}else this.onClickThrough(e)};this.navigator=e,this.popup=new Ia(this.navigator)}setupEvents(e){if(e!==null)e.addEventListener("dblclick",async t=>{let n=t.target;t.target&&n.tagName.toLowerCase()==="img"&&await this.popup.showPopover(n,t)},!0),e.addEventListener("click",this.handleLinks.bind(this));else throw"cannot setup events for null"}};L();L();function ew(){return ft(document,"#iframe-wrapper").clientWidth}function hi(){return ft(document,"#iframe-wrapper").clientHeight}var rw=rt(Vo()),bl=class{constructor(e){this.layout="reflowable";this.USERSETTINGS="userSetting";this.sideMargin=20;this.height=0;this.attributes={margin:0};this.hasFixedScrollWidth=!1;this.store=e,this.scrollMode?(this.name="readium-scroll-on",this.label="Scrolling"):(this.name="readium-scroll-off",this.label="Paginated")}setMode(e){var t;if(this.scrollMode=e,e){this.name="readium-scroll-on",this.label="Scrolling";let n=this.iframe.contentDocument;if(n){let i=cr(n,"head");if(i){let s=Ne(i,"meta[name=viewport]");s&&s.remove()}let o=cr(n,"html");o&&o.style.setProperty("--USER__scroll","readium-scroll-on")}this.setSize(),this.setIframeHeight(this.iframe)}else{this.height=hi()-40-this.attributes.margin,this.name="readium-scroll-off",this.label="Paginated",this.checkForFixedScrollWidth();let n=this.iframe.contentDocument;if(n){let i=cr(n,"html");i&&i.style.setProperty("--USER__scroll","readium-scroll-off")}this.setSize()}this.navigator.rights.enableContentProtection&&((t=this.navigator.contentProtectionModule)==null||t.recalculate())}start(){if(this.scrollMode){let e=this.iframe.contentDocument;if(e){let t=cr(e,"head");if(t){let n=Ne(t,"meta[name=viewport]");n&&n.remove()}}this.setSize(),this.setIframeHeight(this.iframe)}else{this.iframe.height="0",this.iframe.width="0",this.setSize();let e=document.createElement("meta");e.name="viewport",e.content="width=device-width, initial-scale=1, maximum-scale=1",this.checkForFixedScrollWidth()}}stop(){if(this.iframe.height="0",this.iframe.width="0",this.iframe.contentDocument){let t=cr(this.iframe.contentDocument,"body"),n=Array.prototype.slice.call(t.querySelectorAll("img"));for(let i of n)i.style.maxWidth=""}}getCurrentPosition(){let e=ft(document,"#iframe-wrapper");if(this.scrollMode)return e.scrollTop/this.scrollingElement.scrollHeight;{let t=this.getColumnWidth(),n=this.getLeftColumnsWidth(),i=this.getRightColumnsWidth(),o=n+t+i;return n/o}}goToProgression(e){let t=ft(document,"#iframe-wrapper");if(this.scrollMode)t.scrollTop=this.scrollingElement.scrollHeight*e;else{let n=this.getColumnWidth(),i=this.getLeftColumnsWidth(),o=this.getRightColumnsWidth(),s=i+n+o,c=e*s,f=Math.round(c/n)*n;f>=s&&(f=f-n),this.setLeftColumnsWidth(f)}}goToCssSelector(e,t){let n=this.iframe.contentDocument;if(n){let i=n.querySelector(e);this.goToElement(i,t)}}goToFragment(e,t){let n=this.iframe.contentDocument;if(n){let i=n.getElementById(e);this.goToElement(i,t)}}snap(e,t){var n;if(e&&!this.scrollMode){let i=e.style.height;e.style.height="0";let o=this.getColumnWidth(),s=this.getLeftColumnsWidth()+e.getBoundingClientRect().left,c=Math.floor(s/o)*o;e.style.height=i,this.setLeftColumnsWidth(c),this.navigator.rights.enableContentProtection&&((n=this.navigator.contentProtectionModule)==null||n.recalculate(0))}}goToElement(e,t){var n;if(this.scrollMode)e&&e.scrollIntoView({block:"center"});else if(e){let i=e.style.height;e.style.height="0";let o=e.getBoundingClientRect().left,s=this.getColumnWidth(),c=this.scrollingElement.scrollLeft-s,f=Math.ceil(o/s)*s+c;if(t){let u=this.getLeftColumnsWidth();f=Math.ceil(o/s)*s+u}e.style.height=i,this.setLeftColumnsWidth(f),this.navigator.rights.enableContentProtection&&((n=this.navigator.contentProtectionModule)==null||n.recalculate(200))}}atStart(){return this.scrollMode?ft(document,"#iframe-wrapper").scrollTop===0:this.getLeftColumnsWidth()<=0}atEnd(){if(this.scrollMode){let e=ft(document,"#iframe-wrapper");return Math.ceil(this.scrollingElement.scrollHeight-e.scrollTop)-1<=hi()}else return Math.floor(this.getRightColumnsWidth())<=0||Math.ceil(this.getCurrentPage())===this.getPageCount()}goToPreviousPage(){var t;let e=ft(document,"#iframe-wrapper");if(this.scrollMode){let n=e.scrollTop,i=this.getScreenHeight()-40,o=n-i;o>=0?e.scrollTop=o:e.scrollTop=0}else{let n=this.getLeftColumnsWidth(),i=this.getColumnWidth(),o=n-i;o>=0?this.setLeftColumnsWidth(o):this.setLeftColumnsWidth(0),this.navigator.checkResourcePosition()}this.navigator.rights.enableContentProtection&&((t=this.navigator.contentProtectionModule)==null||t.recalculate())}goToNextPage(){var t;let e=ft(document,"#iframe-wrapper");if(this.scrollMode){let n=e.scrollTop,i=this.getScreenHeight()-40,o=this.scrollingElement.scrollHeight,s=n+i;s<o?e.scrollTop=s:e.scrollTop=o}else{let n=this.getLeftColumnsWidth(),i=this.getColumnWidth(),o=this.scrollWidth,s=n+i;s<o?this.setLeftColumnsWidth(s):this.setLeftColumnsWidth(o),this.navigator.checkResourcePosition()}this.navigator.rights.enableContentProtection&&((t=this.navigator.contentProtectionModule)==null||t.recalculate())}getCurrentPage(){return this.scrollMode?0:this.getCurrentPosition()*this.getPageCount()+1}getPageCount(){if(this.scrollMode)return 0;{let e=this.getColumnWidth();return this.scrollWidth/e}}isPaginated(){if(this.iframe){let e=this.iframe.contentDocument;if(e){let t=cr(e,"html");if(t)return!(t.style.getPropertyValue("--USER__scroll")==="readium-scroll-on")}}return!this.scrollMode}isScrollMode(){if(this.iframe){let e=this.iframe.contentDocument;if(e){let t=cr(e,"html");if(t)return t.style.getPropertyValue("--USER__scroll")==="readium-scroll-on"}}return this.scrollMode}async getProperty(e){let t=await this.store.get(this.USERSETTINGS);if(t){let n=JSON.parse(t);return n=n.filter(i=>i.name===e),n.length===0?null:n[0]}return null}getScreenHeight(){return ft(document,"#iframe-wrapper").clientHeight}setIframeHeight(e){(0,rw.default)(n=>{if(n){let i=n.contentWindow.document.body,o=n.contentWindow.document.documentElement,s=Math.max(i==null?void 0:i.scrollHeight,i==null?void 0:i.offsetHeight,o==null?void 0:o.clientHeight,o==null?void 0:o.scrollHeight,o==null?void 0:o.offsetHeight);if(s){let c=hi()-this.attributes.margin;n.height=Math.max(c,s)+"px"}}},200)(e)}checkForFixedScrollWidth(){let e=this.iframe.contentDocument;if(e){let t=cr(e,"body"),n=t==null?void 0:t.scrollWidth;this.hasFixedScrollWidth=(t==null?void 0:t.scrollWidth)===n}}setSize(){var e,t;if(this.iframe.width=ew()+"px",this.scrollMode){let n=(t=(e=this.iframe.contentWindow)==null?void 0:e.document)==null?void 0:t.documentElement;this.iframe.height=(n==null?void 0:n.offsetHeight)+"px"}else{let n=this.iframe.contentDocument;n&&n.documentElement&&(n.documentElement.style.height=this.height+"px"),this.iframe.height=this.height+"px"}}getLeftColumnsWidth(){return Math.ceil(this.scrollingElement.scrollLeft)}getRightColumnsWidth(){let e=this.getColumnWidth(),t=this.scrollWidth-e;if(this.hasFixedScrollWidth){let n=this.getLeftColumnsWidth();t=Math.max(0,t-n)}return t}getColumnWidth(){return this.scrollingElement.clientWidth}setLeftColumnsWidth(e){this.scrollingElement.scrollLeft=e}get scrollingElement(){var e,t,n,i;return(e=this.iframe.contentDocument)!=null&&e.scrollingElement?(t=this.iframe.contentDocument)==null?void 0:t.scrollingElement:(n=this.iframe.contentDocument)!=null&&n.body?(i=this.iframe.contentDocument)==null?void 0:i.body:document.createElement("body")}get scrollWidth(){var i;let e=(i=this.scrollingElement)==null?void 0:i.scrollWidth,t=this.getColumnWidth();return Math.ceil(e/t)*t}};L();var vl=class{constructor(){this.layout="fixed";this.sideMargin=20;this.height=0;this.attributes={margin:0}}start(){}stop(){}getCurrentPosition(){return 0}getScreenHeight(){return ft(document,"#iframe-wrapper").clientHeight}goToProgression(e){}goToCssSelector(e,t){}goToFragment(e,t){}snap(e,t){}getCurrentPage(){return 0}getPageCount(){return 1}setSize(){}isPaginated(){return!0}isScrollMode(){return!1}atEnd(){return!0}atStart(){return!0}};var Ln=rt($t()),At=class At{constructor(e,t,n,i,o){this.USERSETTINGS="userSetting";this.fontSize=100;this.fontOverride=!1;this.fontFamily=0;this.appearance=0;this.verticalScroll=!0;this.textAlignment=0;this.columnCount=0;this.wordSpacing=0;this.letterSpacing=0;this.pageMargins=2;this.lineHeight=1;this.settingsChangeCallback=()=>{};this.settingsColumnsChangeCallback=()=>{};this.viewChangeCallback=()=>{};var s;this.store=e,this.view=o==="fixed"?new vl:new bl(this.store),this.headerMenu=t,this.api=n,this.injectables=i,(s=this.injectables)==null||s.forEach(c=>{c.type==="style"&&(c.fontFamily&&this.addFont(c.fontFamily),c.appearance&&this.addAppearance(c.appearance))})}async isPaginated(){return!await this.getPropertyAndFallback("verticalScroll",Se.SCROLL_KEY)}async isScrollMode(){return!await this.isPaginated()}static async create(e){let t=new this(e.store,e.headerMenu,e.api,e.injectables,e.layout);if(await t.initialise(),e.initialUserSettings){t.userProperties||(t.userProperties=t.getUserSettings());let n=e.initialUserSettings;if(n.verticalScroll!==void 0){t.verticalScroll=this.parseScrollSetting(n.verticalScroll);let i=t.userProperties.getByRef(Se.SCROLL_REF);i&&(i.value=t.verticalScroll,await t.saveProperty(i)),Ln.default.log(t.verticalScroll)}if(n.appearance){t.appearance=At.parseAppearanceSetting(n.appearance);let i=t.userProperties.getByRef(Se.APPEARANCE_REF);i&&(i.value=t.appearance,await t.saveProperty(i)),Ln.default.log(t.appearance)}if(n.fontSize){t.fontSize=n.fontSize;let i=t.userProperties.getByRef(Se.FONT_SIZE_REF);i&&(i.value=t.fontSize,await t.saveProperty(i)),Ln.default.log(t.fontSize)}if(n.fontFamily){t.fontFamily=At.fontFamilyValues.findIndex(o=>o===n.fontFamily);let i=t.userProperties.getByRef(Se.FONT_FAMILY_REF);i&&(i.value=t.fontFamily,await t.saveProperty(i)),Ln.default.log(t.fontFamily),t.fontFamily!==0&&(t.fontOverride=!0)}if(n.textAlignment){t.textAlignment=At.textAlignmentValues.findIndex(o=>o===n.textAlignment);let i=t.userProperties.getByRef(Se.TEXT_ALIGNMENT_REF);i&&(i.value=t.textAlignment,await t.saveProperty(i)),Ln.default.log(t.textAlignment)}if(n.columnCount){t.columnCount=At.columnCountValues.findIndex(o=>o===n.columnCount);let i=t.userProperties.getByRef(Se.COLUMN_COUNT_REF);i&&(i.value=t.columnCount,await t.saveProperty(i)),Ln.default.log(t.columnCount)}if(n.wordSpacing){t.wordSpacing=n.wordSpacing;let i=t.userProperties.getByRef(Se.WORD_SPACING_REF);i&&(i.value=t.wordSpacing,await t.saveProperty(i)),Ln.default.log(t.wordSpacing)}if(n.letterSpacing){t.letterSpacing=n.letterSpacing;let i=t.userProperties.getByRef(Se.LETTER_SPACING_REF);i&&(i.value=t.letterSpacing,await t.saveProperty(i)),Ln.default.log(t.letterSpacing)}if(n.pageMargins){t.pageMargins=n.pageMargins;let i=t.userProperties.getByRef(Se.PAGE_MARGINS_REF);i&&(i.value=t.pageMargins,await t.saveProperty(i)),Ln.default.log(t.pageMargins)}if(n.lineHeight){t.lineHeight=n.lineHeight;let i=t.userProperties.getByRef(Se.LINE_HEIGHT_REF);i&&(i.value=t.lineHeight,await t.saveProperty(i)),Ln.default.log(t.lineHeight)}t.userProperties=t.getUserSettings(),await t.initialise()}return await t.initializeSelections(),new Promise(n=>n(t))}stop(){Ln.default.log("book settings stop")}async initialise(){this.appearance=await this.getPropertyAndFallback("appearance",Se.APPEARANCE_KEY),this.verticalScroll=await this.getPropertyAndFallback("verticalScroll",Se.SCROLL_KEY),this.fontFamily=await this.getPropertyAndFallback("fontFamily",Se.FONT_FAMILY_KEY),this.fontFamily!==0&&(this.fontOverride=!0),this.textAlignment=await this.getPropertyAndFallback("textAlignment",Se.TEXT_ALIGNMENT_KEY),this.columnCount=await this.getPropertyAndFallback("columnCount",Se.COLUMN_COUNT_KEY),this.fontSize=await this.getPropertyAndFallback("fontSize",Se.FONT_SIZE_KEY),this.wordSpacing=await this.getPropertyAndFallback("wordSpacing",Se.WORD_SPACING_KEY),this.letterSpacing=await this.getPropertyAndFallback("letterSpacing",Se.LETTER_SPACING_KEY),this.pageMargins=await this.getPropertyAndFallback("pageMargins",Se.PAGE_MARGINS_KEY),this.lineHeight=await this.getPropertyAndFallback("lineHeight",Se.LINE_HEIGHT_KEY),this.userProperties=this.getUserSettings()}async reset(){this.appearance=0,this.verticalScroll=!0,this.fontSize=100,this.fontOverride=!1,this.fontFamily=0,this.textAlignment=0,this.columnCount=0,this.wordSpacing=0,this.letterSpacing=0,this.pageMargins=2,this.lineHeight=1,this.userProperties=this.getUserSettings();let e=this.iframe.contentDocument;if(e){let t=cr(e,"html");if(t){let n=document.documentElement,i=ft(n,"body");t.style.removeProperty(Se.FONT_SIZE_KEY),t.style.removeProperty(Se.WORD_SPACING_KEY),t.style.removeProperty(Se.LETTER_SPACING_KEY),t.style.removeProperty(Se.COLUMN_COUNT_KEY),t.style.removeProperty(Se.TEXT_ALIGNMENT_KEY),t.style.removeProperty(Se.LINE_HEIGHT_KEY),t.style.removeProperty(Se.PAGE_MARGINS_KEY),t.style.removeProperty(Se.APPEARANCE_KEY),Lr(n,"data-viewer-theme","day"),Lr(i,"data-viewer-theme","day"),t.style.removeProperty(Se.FONT_FAMILY_KEY),Lr(t,"data-viewer-font","publisher"),t.style.setProperty(Se.FONT_OVERRIDE_KEY,"readium-font-off")}}}async initializeSelections(){this.headerMenu&&(this.settingsView=Ne(this.headerMenu,"#container-view-settings"))}async applyProperties(){var t,n,i,o,s,c,f,u,y,m,_,v,g,h,l,p,w,A,C,b,E,k;this.userProperties=this.getUserSettings();let e=this.iframe.contentDocument;if(e){let P=cr(e,"html");if(P){let N=document.documentElement,D=ft(N,"body");if((t=this.view)!=null&&t.navigator.publication.isReflowable&&(await this.getProperty(Se.FONT_SIZE_KEY)&&P.style.setProperty(Se.FONT_SIZE_KEY,((n=this.userProperties.getByRef(Se.FONT_SIZE_REF))==null?void 0:n.toString())??null),await this.getProperty(Se.WORD_SPACING_KEY)&&P.style.setProperty(Se.WORD_SPACING_KEY,((i=this.userProperties.getByRef(Se.WORD_SPACING_REF))==null?void 0:i.toString())??null),await this.getProperty(Se.LETTER_SPACING_KEY)&&P.style.setProperty(Se.LETTER_SPACING_KEY,((o=this.userProperties.getByRef(Se.LETTER_SPACING_REF))==null?void 0:o.toString())??null)),await this.getProperty(Se.COLUMN_COUNT_KEY)&&P.style.setProperty(Se.COLUMN_COUNT_KEY,((s=this.userProperties.getByRef(Se.COLUMN_COUNT_REF))==null?void 0:s.toString())??null),(c=this.view)!=null&&c.navigator.publication.isReflowable&&(await this.getProperty(Se.TEXT_ALIGNMENT_KEY)&&(((f=this.userProperties.getByRef(Se.TEXT_ALIGNMENT_REF))==null?void 0:f.toString())==="auto"?P.style.removeProperty(Se.TEXT_ALIGNMENT_KEY):P.style.setProperty(Se.TEXT_ALIGNMENT_KEY,((u=this.userProperties.getByRef(Se.TEXT_ALIGNMENT_REF))==null?void 0:u.toString())??null)),await this.getProperty(Se.LINE_HEIGHT_KEY)&&P.style.setProperty(Se.LINE_HEIGHT_KEY,((y=this.userProperties.getByRef(Se.LINE_HEIGHT_REF))==null?void 0:y.toString())??null),await this.getProperty(Se.PAGE_MARGINS_KEY)&&P.style.setProperty(Se.PAGE_MARGINS_KEY,((m=this.userProperties.getByRef(Se.PAGE_MARGINS_REF))==null?void 0:m.toString())??null)),await this.getProperty(Se.APPEARANCE_KEY)?(P.style.setProperty(Se.APPEARANCE_KEY,((_=this.userProperties.getByRef(Se.APPEARANCE_REF))==null?void 0:_.toString())??null),((v=this.userProperties.getByRef(Se.APPEARANCE_REF))==null?void 0:v.value)===0?(Lr(N,"data-viewer-theme","day"),Lr(D,"data-viewer-theme","day")):((g=this.userProperties.getByRef(Se.APPEARANCE_REF))==null?void 0:g.value)===1?(Lr(N,"data-viewer-theme","sepia"),Lr(D,"data-viewer-theme","sepia")):((h=this.userProperties.getByRef(Se.APPEARANCE_REF))==null?void 0:h.value)===2&&(Lr(N,"data-viewer-theme","night"),Lr(D,"data-viewer-theme","night"))):(P.style.setProperty(Se.APPEARANCE_KEY,((l=this.userProperties.getByRef(Se.APPEARANCE_REF))==null?void 0:l.toString())??null),Lr(N,"data-viewer-theme","day"),Lr(D,"data-viewer-theme","day")),(p=this.view)!=null&&p.navigator.publication.isReflowable){if(await this.getProperty(Se.FONT_FAMILY_KEY))if(P.style.setProperty(Se.FONT_FAMILY_KEY,((w=this.userProperties.getByRef(Se.FONT_FAMILY_REF))==null?void 0:w.toString())??null),((A=this.userProperties.getByRef(Se.FONT_FAMILY_REF))==null?void 0:A.value)===0)Lr(P,"data-viewer-font","publisher"),P.style.setProperty(Se.FONT_OVERRIDE_KEY,"readium-font-off");else if(((C=this.userProperties.getByRef(Se.FONT_FAMILY_REF))==null?void 0:C.value)===1)Lr(P,"data-viewer-font","serif"),P.style.setProperty(Se.FONT_OVERRIDE_KEY,"readium-font-on");else if(((b=this.userProperties.getByRef(Se.FONT_FAMILY_REF))==null?void 0:b.value)===2)Lr(P,"data-viewer-font","sans"),P.style.setProperty(Se.FONT_OVERRIDE_KEY,"readium-font-on");else{let F=this.userProperties.getByRef(Se.FONT_FAMILY_REF);F&&Lr(P,"data-viewer-font",F.toString()),P.style.setProperty(Se.FONT_OVERRIDE_KEY,"readium-font-on")}else P.style.setProperty(Se.FONT_FAMILY_KEY,((E=this.userProperties.getByRef(Se.FONT_FAMILY_REF))==null?void 0:E.toString())??null),Lr(P,"data-viewer-font","publisher"),P.style.setProperty(Se.FONT_OVERRIDE_KEY,"readium-font-off");await this.getProperty(Se.SCROLL_KEY)?((k=this.userProperties.getByRef(Se.SCROLL_REF))==null?void 0:k.value)===!0?P.style.setProperty("--USER__scroll","readium-scroll-on"):P.style.setProperty("--USER__scroll","readium-scroll-off"):P.style.setProperty("--USER__scroll","readium-scroll-on"),P.style.setProperty("--USER__advancedSettings","readium-advanced-on"),this.isScrollMode().then(F=>{var B,V;(V=(B=this.view)==null?void 0:B.setMode)==null||V.call(B,F)})}}}}setIframe(e){this.iframe=e,this.view&&(this.view.iframe=e),this.settingsView&&At.renderControls(this.settingsView)}static renderControls(e){_e(Ne(e,"ul"),"click",t=>{t.stopPropagation()})}onSettingsChange(e){this.settingsChangeCallback=e}onColumnSettingsChange(e){this.settingsColumnsChangeCallback=e}onViewChange(e){this.viewChangeCallback=e}async storeProperty(e){await this.updateUserSettings(),await this.saveProperty(e)}addAppearance(e){At.appearanceValues.includes(e)||At.appearanceValues.push(e)}initAddedAppearance(){this.applyProperties()}addFont(e){At.fontFamilyValues.includes(e)||At.fontFamilyValues.push(e)}initAddedFont(){this.applyProperties()}async updateUserSettings(){var t,n,i,o,s,c,f,u,y,m,_,v,g,h,l,p,w,A;let e={fontFamily:At.fontFamilyValues[await((n=(t=this.userProperties)==null?void 0:t.getByRef(Se.FONT_FAMILY_REF))==null?void 0:n.value)],fontSize:(o=(i=this.userProperties)==null?void 0:i.getByRef(Se.FONT_SIZE_REF))==null?void 0:o.value,appearance:At.appearanceValues[await((c=(s=this.userProperties)==null?void 0:s.getByRef(Se.APPEARANCE_REF))==null?void 0:c.value)],textAlignment:At.textAlignmentValues[await((u=(f=this.userProperties)==null?void 0:f.getByRef(Se.TEXT_ALIGNMENT_REF))==null?void 0:u.value)],columnCount:At.columnCountValues[await((m=(y=this.userProperties)==null?void 0:y.getByRef(Se.COLUMN_COUNT_REF))==null?void 0:m.value)],wordSpacing:(v=(_=this.userProperties)==null?void 0:_.getByRef(Se.WORD_SPACING_REF))==null?void 0:v.value,letterSpacing:(h=(g=this.userProperties)==null?void 0:g.getByRef(Se.LETTER_SPACING_REF))==null?void 0:h.value,verticalScroll:(p=(l=this.userProperties)==null?void 0:l.getByRef(Se.SCROLL_REF))==null?void 0:p.value};(w=this.api)!=null&&w.updateSettings&&((A=this.api)==null||A.updateSettings(e).then(C=>{Ln.default.log("api updated user settings",JSON.stringify(e))}))}getUserSettings(){let e=new ki;return e.addSwitchable("readium-font-on","readium-font-off",this.fontOverride,Se.FONT_OVERRIDE_REF,Se.FONT_OVERRIDE_KEY),e.addEnumerable(this.columnCount,At.columnCountValues,Se.COLUMN_COUNT_REF,Se.COLUMN_COUNT_KEY),e.addEnumerable(this.appearance,At.appearanceValues,Se.APPEARANCE_REF,Se.APPEARANCE_KEY),e.addIncremental(this.pageMargins,.5,4,.25,"",Se.PAGE_MARGINS_REF,Se.PAGE_MARGINS_KEY),e.addEnumerable(this.textAlignment,At.textAlignmentValues,Se.TEXT_ALIGNMENT_REF,Se.TEXT_ALIGNMENT_KEY),e.addEnumerable(this.fontFamily,At.fontFamilyValues,Se.FONT_FAMILY_REF,Se.FONT_FAMILY_KEY),e.addIncremental(this.fontSize,100,300,25,"%",Se.FONT_SIZE_REF,Se.FONT_SIZE_KEY),e.addIncremental(this.lineHeight,1,2,.25,"em",Se.LINE_HEIGHT_REF,Se.LINE_HEIGHT_KEY),e.addIncremental(this.wordSpacing,0,1,.25,"rem",Se.WORD_SPACING_REF,Se.WORD_SPACING_KEY),e.addIncremental(this.letterSpacing,0,.5,.0625,"em",Se.LETTER_SPACING_REF,Se.LETTER_SPACING_KEY),e.addSwitchable("readium-scroll-on","readium-scroll-off",this.verticalScroll,Se.SCROLL_REF,Se.SCROLL_KEY),e}async saveProperty(e){let t=await this.store.get(this.USERSETTINGS);if(t){let n=JSON.parse(t);n=n.filter(i=>i.name!==e.name),e.value!==void 0&&n.push(e),await this.store.set(this.USERSETTINGS,JSON.stringify(n))}else{let n=[];n.push(e),await this.store.set(this.USERSETTINGS,JSON.stringify(n))}return new Promise(n=>n(e))}async getProperty(e){let t=await this.store.get(this.USERSETTINGS);if(t){let n=JSON.parse(t);return n=n.filter(i=>i.name===e),n.length===0?null:n[0]}return null}async getPropertyAndFallback(e,t){var n;return((n=await this.getProperty(t))==null?void 0:n.value)??this[e]}async resetUserSettings(){await this.store.remove(this.USERSETTINGS),await this.reset(),this.settingsChangeCallback()}get currentSettings(){var e,t,n,i,o,s,c,f;return{appearance:At.appearanceValues[(t=(e=this.userProperties)==null?void 0:e.getByRef(Se.APPEARANCE_REF))==null?void 0:t.value],fontFamily:At.fontFamilyValues[(i=(n=this.userProperties)==null?void 0:n.getByRef(Se.FONT_FAMILY_REF))==null?void 0:i.value],textAlignment:At.textAlignmentValues[(s=(o=this.userProperties)==null?void 0:o.getByRef(Se.TEXT_ALIGNMENT_REF))==null?void 0:s.value],columnCount:At.columnCountValues[(f=(c=this.userProperties)==null?void 0:c.getByRef(Se.COLUMN_COUNT_REF))==null?void 0:f.value],verticalScroll:this.verticalScroll,fontSize:this.fontSize,wordSpacing:this.wordSpacing,letterSpacing:this.letterSpacing,pageMargins:this.pageMargins,lineHeight:this.lineHeight}}async applyUserSettings(e){var t,n,i,o,s,c,f,u,y,m,_,v,g,h;if(e.appearance){this.appearance=At.parseAppearanceSetting(e.appearance);let l=(t=this.userProperties)==null?void 0:t.getByRef(Se.APPEARANCE_REF);l&&(l.value=this.appearance,await this.storeProperty(l))}if(e.fontSize){this.fontSize=e.fontSize;let l=(n=this.userProperties)==null?void 0:n.getByRef(Se.FONT_SIZE_REF);l&&(l.value=this.fontSize,await this.storeProperty(l))}if(e.fontFamily){this.fontFamily=At.fontFamilyValues.findIndex(p=>p===e.fontFamily);let l=(i=this.userProperties)==null?void 0:i.getByRef(Se.FONT_FAMILY_REF);l&&(l.value=this.fontFamily,await this.storeProperty(l))}if(e.letterSpacing){this.letterSpacing=e.letterSpacing;let l=(o=this.userProperties)==null?void 0:o.getByRef(Se.LETTER_SPACING_REF);l&&(l.value=this.letterSpacing,await this.storeProperty(l))}if(e.wordSpacing){this.wordSpacing=e.wordSpacing;let l=(s=this.userProperties)==null?void 0:s.getByRef(Se.WORD_SPACING_REF);l&&(l.value=this.wordSpacing,await this.storeProperty(l))}if(e.columnCount){this.columnCount=At.columnCountValues.findIndex(p=>p===e.columnCount);let l=(c=this.userProperties)==null?void 0:c.getByRef(Se.COLUMN_COUNT_REF);l&&(l.value=this.columnCount,await this.storeProperty(l)),this.settingsColumnsChangeCallback()}if(e.textAlignment){this.textAlignment=At.textAlignmentValues.findIndex(p=>p===e.textAlignment);let l=(f=this.userProperties)==null?void 0:f.getByRef(Se.TEXT_ALIGNMENT_REF);l&&(l.value=this.textAlignment,await this.storeProperty(l))}if(e.lineHeight){this.lineHeight=e.lineHeight;let l=(u=this.userProperties)==null?void 0:u.getByRef(Se.LINE_HEIGHT_REF);l&&(l.value=this.lineHeight,await this.storeProperty(l))}if(e.pageMargins){this.pageMargins=e.pageMargins;let l=(y=this.userProperties)==null?void 0:y.getByRef(Se.PAGE_MARGINS_REF);l&&(l.value=this.pageMargins,await this.storeProperty(l))}if(e.verticalScroll!==void 0){let l=(m=this.view)==null?void 0:m.getCurrentPosition();this.verticalScroll=At.parseScrollSetting(e.verticalScroll);let p=(_=this.userProperties)==null?void 0:_.getByRef(Se.SCROLL_REF);p&&(p.value=this.verticalScroll,await this.saveProperty(p)),(g=(v=this.view)==null?void 0:v.setMode)==null||g.call(v,this.verticalScroll),l&&((h=this.view)==null||h.goToProgression(l)),this.viewChangeCallback()}await this.applyProperties(),this.settingsChangeCallback()}static parseScrollSetting(e){switch(e){case!0:case"scroll":case"readium-scroll-on":return!0;case!1:case"paginated":case"readium-scroll-off":return!1;default:return!1}}static parseAppearanceSetting(e){let t;return e==="day"||e==="readium-default-on"?t=At.appearanceValues[0]:e==="sepia"||e==="readium-sepia-on"?t=At.appearanceValues[1]:e==="night"||e==="readium-night-on"?t=At.appearanceValues[2]:t=e,At.appearanceValues.findIndex(n=>n===t)}async scroll(e){var i,o,s,c,f;let t=(i=this.view)==null?void 0:i.getCurrentPosition();this.verticalScroll=e;let n=(o=this.userProperties)==null?void 0:o.getByRef(Se.SCROLL_REF);n&&(n.value=this.verticalScroll,await this.saveProperty(n)),await this.applyProperties(),(c=(s=this.view)==null?void 0:s.setMode)==null||c.call(s,this.verticalScroll),t&&((f=this.view)==null||f.goToProgression(t)),this.viewChangeCallback()}async increase(e){var t,n,i,o,s,c,f,u,y,m,_,v,g,h,l,p;if(e==="fontSize"){((t=this.userProperties)==null?void 0:t.getByRef(Se.FONT_SIZE_REF)).increment(),this.fontSize=(i=(n=this.userProperties)==null?void 0:n.getByRef(Se.FONT_SIZE_REF))==null?void 0:i.value;let w=(o=this.userProperties)==null?void 0:o.getByRef(Se.FONT_SIZE_REF);w&&await this.storeProperty(w)}else if(e==="letterSpacing"){((s=this.userProperties)==null?void 0:s.getByRef(Se.LETTER_SPACING_REF)).increment(),this.letterSpacing=(f=(c=this.userProperties)==null?void 0:c.getByRef(Se.LETTER_SPACING_REF))==null?void 0:f.value;let w=(u=this.userProperties)==null?void 0:u.getByRef(Se.LETTER_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="wordSpacing"){((y=this.userProperties)==null?void 0:y.getByRef(Se.WORD_SPACING_REF)).increment(),this.wordSpacing=(_=(m=this.userProperties)==null?void 0:m.getByRef(Se.WORD_SPACING_REF))==null?void 0:_.value;let w=(v=this.userProperties)==null?void 0:v.getByRef(Se.WORD_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="lineHeight"){((g=this.userProperties)==null?void 0:g.getByRef(Se.LINE_HEIGHT_REF)).increment(),this.lineHeight=(l=(h=this.userProperties)==null?void 0:h.getByRef(Se.LINE_HEIGHT_REF))==null?void 0:l.value;let w=(p=this.userProperties)==null?void 0:p.getByRef(Se.LINE_HEIGHT_REF);w&&await this.storeProperty(w)}await this.applyProperties(),this.settingsChangeCallback()}async decrease(e){var t,n,i,o,s,c,f,u,y,m,_,v,g,h,l,p;if(e==="fontSize"){((t=this.userProperties)==null?void 0:t.getByRef(Se.FONT_SIZE_REF)).decrement(),this.fontSize=(i=(n=this.userProperties)==null?void 0:n.getByRef(Se.FONT_SIZE_REF))==null?void 0:i.value;let w=(o=this.userProperties)==null?void 0:o.getByRef(Se.FONT_SIZE_REF);w&&await this.storeProperty(w)}else if(e==="letterSpacing"){((s=this.userProperties)==null?void 0:s.getByRef(Se.LETTER_SPACING_REF)).decrement(),this.letterSpacing=(f=(c=this.userProperties)==null?void 0:c.getByRef(Se.LETTER_SPACING_REF))==null?void 0:f.value;let w=(u=this.userProperties)==null?void 0:u.getByRef(Se.LETTER_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="wordSpacing"){((y=this.userProperties)==null?void 0:y.getByRef(Se.WORD_SPACING_REF)).decrement(),this.wordSpacing=(_=(m=this.userProperties)==null?void 0:m.getByRef(Se.WORD_SPACING_REF))==null?void 0:_.value;let w=(v=this.userProperties)==null?void 0:v.getByRef(Se.WORD_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="lineHeight"){((g=this.userProperties)==null?void 0:g.getByRef(Se.LINE_HEIGHT_REF)).decrement(),this.wordSpacing=(l=(h=this.userProperties)==null?void 0:h.getByRef(Se.LINE_HEIGHT_REF))==null?void 0:l.value;let w=(p=this.userProperties)==null?void 0:p.getByRef(Se.LINE_HEIGHT_REF);w&&await this.storeProperty(w)}await this.applyProperties(),this.settingsChangeCallback()}};At.appearanceValues=["readium-default-on","readium-sepia-on","readium-night-on"],At.fontFamilyValues=["Original","serif","sans-serif"],At.textAlignmentValues=["auto","justify","start"],At.columnCountValues=["auto","1","2"];var _l=At;L();L();L();L();L();L();L();L();var nw={stringify(r){let e=r.nSigBytes,t=r.words,n=[];for(let i=0;i<e;i++){let o=t[i>>>2]>>>24-i%4*8&255;n.push((o>>>4).toString(16)),n.push((o&15).toString(16))}return n.join("")},parse(r){let e=r.length;if(e%2!==0)throw new Error("Hex string count must be even");if(!/^[a-fA-F0-9]+$/.test(r))throw new Error(`Invalid Hex string: ${r}`);let t=[];for(let n=0;n<e;n+=2)t[n>>>3]|=parseInt(r.substr(n,2),16)<<24-n%8*4;return new In(t,e/2)}};L();L();var iw=typeof navigator<"u"&&navigator.userAgent?navigator.userAgent.toLowerCase():"",Os=(()=>{let r=parseInt((/msie (\d+)/.exec(iw)||[])[1],10);return isNaN(r)?(r=parseInt((/trident\/.*; rv:(\d+)/.exec(iw)||[])[1],10),isNaN(r)?!1:r):r})();function ow(r,e){return Os===!1?!1:e?r==="<"?Os<e:r==="<="?Os<=e:r===">"?Os>e:r===">="?Os>=e:Os===e:!0}function TB(){if(typeof window<"u"){let r=window.crypto||window.msCrypto;if(!r){if(ow("<",11))return console.warn("IE <= 10 uses insecure random generator. Please consider to use IE11 or another modern browser"),function(){return Math.floor(Math.random()*512)%256};throw new Error("Crypto module not found")}return function(){return r.getRandomValues(new Uint32Array(1))[0]}}else{if(typeof globalThis<"u"&&globalThis.crypto)return function(){return globalThis.crypto.randomBytes(4).readInt32LE()};if(typeof Eu=="function")return function(){return __non_webpack_require__("crypto").randomBytes(4).readInt32LE()}}throw new Error("Unable to find crypto module")}var sw=TB();var In=class r{constructor(e,t){if(Array.isArray(e)||!e){this._words=Array.isArray(e)?e:[],this._nSignificantBytes=typeof t=="number"?t:this._words.length*4;return}else if(e instanceof r){this._words=e.words.slice(),this._nSignificantBytes=e.nSigBytes;return}let n;try{e instanceof ArrayBuffer?n=new Uint8Array(e):(e instanceof Uint8Array||e instanceof Int8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array)&&(n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}catch{throw new Error("Invalid argument")}if(!n)throw new Error("Invalid argument");let i=n.byteLength,o=[];for(let s=0;s<i;s++)o[s>>>2]|=n[s]<<24-s%4*8;this._words=o,this._nSignificantBytes=i}get nSigBytes(){return this._nSignificantBytes}set nSigBytes(e){this._nSignificantBytes=e}get words(){return this._words}toString(e){return e?e.stringify(this):nw.stringify(this)}toUint8Array(){let e=this._words,t=this._nSignificantBytes,n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=e[i>>>2]>>>24-i%4*8&255;return n}concat(e){let t=e.words.slice(),n=e.nSigBytes;if(this.clamp(),this._nSignificantBytes%4)for(let i=0;i<n;i++){let o=t[i>>>2]>>>24-i%4*8&255;this._words[this._nSignificantBytes+i>>>2]|=o<<24-(this._nSignificantBytes+i)%4*8}else for(let i=0;i<n;i+=4)this._words[this._nSignificantBytes+i>>>2]=t[i>>>2];return this._nSignificantBytes+=n,this}clamp(){let e=this._nSignificantBytes;this._words[e>>>2]&=4294967295<<32-e%4*8,this._words.length=Math.ceil(e/4)}clone(){return new r(this._words.slice(),this._nSignificantBytes)}static random(e){let t=[];for(let n=0;n<e;n+=4)t.push(sw());return new r(t,e)}};L();L();var qg={stringify(r){let e=r.nSigBytes,t=r.words,n=[];for(let i=0;i<e;i++){let o=t[i>>>2]>>>24-i%4*8&255;n.push(String.fromCharCode(o))}return n.join("")},parse(r){let e=r.length,t=[];for(let n=0;n<e;n++)t[n>>>2]|=(r.charCodeAt(n)&255)<<24-n%4*8;return new In(t,e)}};var aw={stringify(r){try{return decodeURIComponent(escape(qg.stringify(r)))}catch{throw new Error("Malformed UTF-8 data")}},parse(r){return qg.parse(unescape(encodeURIComponent(r)))}};var Of=class{constructor(e){this._minBufferSize=0,this._blockSize=0,this._props=e,this._data=e&&typeof e.data<"u"?e.data.clone():new In,this._nBytes=e&&typeof e.nBytes=="number"?e.nBytes:0}get blockSize(){return this._blockSize}reset(e,t){this._data=typeof e<"u"?e.clone():new In,this._nBytes=typeof t=="number"?t:0}_append(e){let t=typeof e=="string"?aw.parse(e):e;this._data.concat(t),this._nBytes+=t.nSigBytes}_process(e){let t,n=this._data.words,i=this._data.nSigBytes,o=this._blockSize,s=this._blockSize*4,c=i/s;e?c=Math.ceil(c):c=Math.max((c|0)-this._minBufferSize,0);let f=c*o,u=Math.min(f*4,i);if(f){for(let y=0;y<f;y+=o)this._doProcessBlock(n,y);t=n.splice(0,f),this._data.nSigBytes-=u}return new In(t,u)}_doProcessBlock(e,t){throw new Error("Not implemented")}};var Mf=class extends Of{constructor(e){super(e),this._blockSize=512/32,this._props=e,e&&typeof e.blockSize=="number"&&(this._blockSize=e.blockSize),this.reset(e?e.data:void 0,e?e.nBytes:void 0)}get blockSize(){return this._blockSize}reset(e,t){super.reset.call(this,e,t),this._doReset()}update(e){return this._append(e),this._process(),this}finalize(e){return e&&this._append(e),this._doFinalize()}_doReset(){throw new Error("Not implemented")}_doFinalize(){throw new Error("Not implemented")}};var Gg=[],lw=[];function PB(r){let e=Math.sqrt(r);for(let t=2;t<=e;t++)if(!(r%t))return!1;return!0}function uw(r){return(r-(r|0))*4294967296|0}(function(){let e=2,t=0;for(;t<64;)PB(e)&&(t<8&&(Gg[t]=uw(Math.pow(e,1/2))),lw[t]=uw(Math.pow(e,1/3)),t++),e++})();var Ms=[],Fi=class r extends Mf{constructor(e){super(e),this._hash=new In(Gg.slice(0)),this._props=e,e&&typeof e.hash<"u"&&(this._hash=e.hash.clone())}_doReset(){this._hash=new In(Gg.slice(0))}_doProcessBlock(e,t){let n=this._hash.words,i=n[0],o=n[1],s=n[2],c=n[3],f=n[4],u=n[5],y=n[6],m=n[7];for(let _=0;_<64;_++){if(_<16)Ms[_]=e[t+_]|0;else{let A=Ms[_-15],C=(A<<25|A>>>7)^(A<<14|A>>>18)^A>>>3,b=Ms[_-2],E=(b<<15|b>>>17)^(b<<13|b>>>19)^b>>>10;Ms[_]=C+Ms[_-7]+E+Ms[_-16]}let v=f&u^~f&y,g=i&o^i&s^o&s,h=(i<<30|i>>>2)^(i<<19|i>>>13)^(i<<10|i>>>22),l=(f<<26|f>>>6)^(f<<21|f>>>11)^(f<<7|f>>>25),p=m+l+v+lw[_]+Ms[_],w=h+g;m=y,y=u,u=f,f=c+p|0,c=s,s=o,o=i,i=p+w|0}n[0]=n[0]+i|0,n[1]=n[1]+o|0,n[2]=n[2]+s|0,n[3]=n[3]+c|0,n[4]=n[4]+f|0,n[5]=n[5]+u|0,n[6]=n[6]+y|0,n[7]=n[7]+m|0}_doFinalize(){let e=this._data.words,t=this._nBytes*8,n=this._data.nSigBytes*8;return e[n>>>5]|=128<<24-n%32,e[(n+64>>>9<<4)+14]=Math.floor(t/4294967296),e[(n+64>>>9<<4)+15]=t,this._data.nSigBytes=e.length*4,this._process(),this._hash}clone(){let e={hash:this._hash,blockSize:this._blockSize,data:this._data,nBytes:this._nBytes};return new r(e)}static hash(e,t){return new r(t).finalize(e)}};var Al=rt(Vo());L();L();var Hr=rt($t());function Rf(r,e){let t=r.getClientRects();return Wg(t,e)}function Wg(r,e){let n=[];for(let f of r)n.push({bottom:f.bottom,height:f.height,left:f.left,right:f.right,top:f.top,width:f.width});let i=dw(n,1,e),o=IB(i,1),s=fw(o),c=2*2;for(let f=s.length-1;f>=0;f--){let u=s[f];if(!(u.width*u.height>c))if(s.length>1)Hr.default.log("CLIENT RECT: remove small"),s.splice(f,1);else{Hr.default.log("CLIENT RECT: remove small, but keep otherwise empty!");break}}return hw(s),Hr.default.log(`CLIENT RECT: reduced ${n.length} --> ${s.length}`),s}function Zn(r,e,t){return Math.abs(r-e)<=t}function OB(r,e){let t=Math.max(r.left,e.left),n=Math.min(r.right,e.right),i=Math.max(r.top,e.top),o=Math.min(r.bottom,e.bottom);return{bottom:o,height:Math.max(0,o-i),left:t,right:n,top:i,width:Math.max(0,n-t)}}function cw(r,e){let t=OB(e,r);if(t.height===0||t.width===0)return[r];let n=[];{let i={bottom:r.bottom,height:0,left:r.left,right:t.left,top:r.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}{let i={bottom:t.top,height:0,left:t.left,right:t.right,top:r.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}{let i={bottom:r.bottom,height:0,left:t.left,right:t.right,top:t.bottom,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}{let i={bottom:r.bottom,height:0,left:t.right,right:r.right,top:r.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}return n}function kf(r,e,t,n){return(r.left<e||Zn(r.left,e,n))&&(r.right>e||Zn(r.right,e,n))&&(r.top<t||Zn(r.top,t,n))&&(r.bottom>t||Zn(r.bottom,t,n))}function MB(r,e,t){return kf(r,e.left,e.top,t)&&kf(r,e.right,e.top,t)&&kf(r,e.left,e.bottom,t)&&kf(r,e.right,e.bottom,t)}function kB(r,e){let t=Math.min(r.left,e.left),n=Math.max(r.right,e.right),i=Math.min(r.top,e.top),o=Math.max(r.bottom,e.bottom);return{bottom:o,height:o-i,left:t,right:n,top:i,width:n-t}}function zg(r,e,t){return(r.left<e.right||t>=0&&Zn(r.left,e.right,t))&&(e.left<r.right||t>=0&&Zn(e.left,r.right,t))&&(r.top<e.bottom||t>=0&&Zn(r.top,e.bottom,t))&&(e.top<r.bottom||t>=0&&Zn(e.top,r.bottom,t))}function dw(r,e,t){for(let n=0;n<r.length;n++)for(let i=n+1;i<r.length;i++){let o=r[n],s=r[i];if(o===s){Hr.default.log("mergeTouchingRects rect1 === rect2 ??!");continue}let c=Zn(o.top,s.top,e)&&Zn(o.bottom,s.bottom,e),f=Zn(o.left,s.left,e)&&Zn(o.right,s.right,e);if((f&&!t||c&&!f)&&zg(o,s,e)){Hr.default.log(`CLIENT RECT: merging two into one, VERTICAL: ${c} HORIZONTAL: ${f} (${t})`);let _=r.filter(g=>g!==o&&g!==s),v=kB(o,s);return _.push(v),dw(_,e,t)}}return r}function fw(r){for(let e=0;e<r.length;e++)for(let t=e+1;t<r.length;t++){let n=r[e],i=r[t];if(n===i){Hr.default.log("replaceOverlappingRects rect1 === rect2 ??!");continue}if(zg(n,i,-1)){let o=[],s,c,f=cw(n,i);if(f.length===1)o=f,s=n,c=i;else{let m=cw(i,n);f.length<m.length?(o=f,s=n,c=i):(o=m,s=i,c=n)}let u=[];u.push(c),Array.prototype.push.apply(u,o),hw(u),Hr.default.log(`CLIENT RECT: overlap, cut one rect into ${o.length}`);let y=r.filter(m=>m!==s);return Array.prototype.push.apply(y,o),fw(y)}}return r}function RB(r,e){return Math.max(0,Math.min(r.right,e.right)-Math.max(r.left,e.left))}function LB(r,e){return Math.max(0,Math.min(r.bottom,e.bottom)-Math.max(r.top,e.top))}function IB(r,e){let t=new Set(r);for(let n of r){if(!(n.width>1&&n.height>1)){Hr.default.log("CLIENT RECT: remove tiny"),t.delete(n);continue}for(let o of r)if(n!==o&&t.has(o)&&MB(o,n,e)){Hr.default.log("CLIENT RECT: remove contained"),t.delete(n);break}}return Array.from(t)}function hw(r){let e=[];for(let t of r)for(let n of r){if(t===n)continue;let i=e.indexOf(t)>=0,o=e.indexOf(n)>=0;if((!i||!o)&&zg(t,n,-1)){i||e.push(t),o||e.push(n),Hr.default.log("CLIENT RECT: overlap ---"),Hr.default.log(`#1 TOP:${t.top} BOTTOM:${t.bottom} LEFT:${t.left} RIGHT:${t.right} WIDTH:${t.width} HEIGHT:${t.height}`),Hr.default.log(`#2 TOP:${n.top} BOTTOM:${n.bottom} LEFT:${n.left} RIGHT:${n.right} WIDTH:${n.width} HEIGHT:${n.height}`);let s=RB(t,n);Hr.default.log(`xOverlap: ${s}`);let c=LB(t,n);Hr.default.log(`yOverlap: ${c}`)}}e.length&&Hr.default.log(`CLIENT RECT: overlaps ${e.length}`)}L();var Ft=rt($t());function Hi(r,e){let t=r?r.getSelection():null;if(!t)return;if(t.isCollapsed){Ft.default.log("^^^ SELECTION COLLAPSED.");return}let n=t.toString(),i=n.trim().replace(/\n/g," ").replace(/\s\s+/g," ");if(i.length===0){Ft.default.log("^^^ SELECTION TEXT EMPTY.");return}if(!t.anchorNode||!t.focusNode)return;let o=t.rangeCount===1?t.getRangeAt(0):mw(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset);if(!o||o.collapsed){Ft.default.log("$$$$$$$$$$$$$$$$$ CANNOT GET NON-COLLAPSED SELECTION RANGE?!");return}let s=BB(o);s.startContainer!==o.startContainer&&(Ft.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startContainer"),Ft.default.log(s.startContainer),Ft.default.log(o.startContainer)),s.startOffset!==o.startOffset&&(Ft.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startOffset"),Ft.default.log(`${s.startOffset} !== ${o.startOffset}`)),s.endContainer!==o.endContainer&&(Ft.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endContainer"),Ft.default.log(s.endContainer),Ft.default.log(o.endContainer)),s.endOffset!==o.endOffset&&(Ft.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endOffset"),Ft.default.log(`${s.endOffset} !== ${o.endOffset}`));let c=go(s,e);if(!c){Ft.default.log("^^^ SELECTION RANGE INFO FAIL?!");return}return{rangeInfo:c,cleanText:i,rawText:n,range:s}}function mw(r,e,t,n){try{let i=new Range;if(i.setStart(r,e),i.setEnd(t,n),!i.collapsed)return Ft.default.log(">>> createOrderedRange RANGE OK"),i;Ft.default.log(">>> createOrderedRange COLLAPSED ... RANGE REVERSE?");let o=new Range;if(o.setStart(t,n),o.setEnd(r,e),!o.collapsed)return Ft.default.log(">>> createOrderedRange RANGE REVERSE OK."),i;Ft.default.log(">>> createOrderedRange RANGE REVERSE ALSO COLLAPSED?!");return}catch(i){console.warn(i.message);return}}function go(r,e){let t=r.startContainer.nodeType===Node.ELEMENT_NODE,n=t?r.startContainer:r.startContainer.parentNode&&r.startContainer.parentNode.nodeType===Node.ELEMENT_NODE?r.startContainer.parentNode:void 0;if(!n)return;let i=t?-1:Array.from(n.childNodes).indexOf(r.startContainer);if(i<-1)return;let o=e(n),s=r.endContainer.nodeType===Node.ELEMENT_NODE,c=s?r.endContainer:r.endContainer.parentNode&&r.endContainer.parentNode.nodeType===Node.ELEMENT_NODE?r.endContainer.parentNode:void 0;if(!c)return;let f=s?-1:Array.from(c.childNodes).indexOf(r.endContainer);if(f<-1)return;let u=e(c),y=NB(r.startContainer,r.endContainer);if(!y){Ft.default.log("^^^ NO RANGE COMMON ANCESTOR?!");return}if(r.commonAncestorContainer){let m=r.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?r.commonAncestorContainer:r.commonAncestorContainer.parentNode;m&&m.nodeType===Node.ELEMENT_NODE&&y!==m&&(Ft.default.log(">>>>>> COMMON ANCESTOR CONTAINER DIFF??!"),Ft.default.log(e(y)),Ft.default.log(e(m)))}if(u&&o)return{endContainerChildTextNodeIndex:f,endContainerElementCssSelector:u,endOffset:r.endOffset,startContainerChildTextNodeIndex:i,startContainerElementCssSelector:o,startOffset:r.startOffset}}function Lf(r,e){let t=r.querySelector(e.startContainerElementCssSelector);if(!t){Ft.default.log("^^^ convertRangeInfo NO START ELEMENT CSS SELECTOR?!");return}let n=t;if(e.startContainerChildTextNodeIndex>=0){if(e.startContainerChildTextNodeIndex>=t.childNodes.length){Ft.default.log("^^^ convertRangeInfo rangeInfo.startContainerChildTextNodeIndex >= startElement.childNodes.length?!");return}if(n=t.childNodes[e.startContainerChildTextNodeIndex],n.nodeType!==Node.TEXT_NODE){Ft.default.log("^^^ convertRangeInfo startContainer.nodeType !== Node.TEXT_NODE?!");return}}let i=r.querySelector(e.endContainerElementCssSelector);if(!i){Ft.default.log("^^^ convertRangeInfo NO END ELEMENT CSS SELECTOR?!");return}let o=i;if(e.endContainerChildTextNodeIndex>=0){if(e.endContainerChildTextNodeIndex>=i.childNodes.length){Ft.default.log("^^^ convertRangeInfo rangeInfo.endContainerChildTextNodeIndex >= endElement.childNodes.length?!");return}if(o=i.childNodes[e.endContainerChildTextNodeIndex],o.nodeType!==Node.TEXT_NODE){Ft.default.log("^^^ convertRangeInfo endContainer.nodeType !== Node.TEXT_NODE?!");return}}return mw(n,e.startOffset,o,e.endOffset)}function NB(r,e){if(r.nodeType===Node.ELEMENT_NODE&&r===e||r.nodeType===Node.ELEMENT_NODE&&r.contains(e))return r;if(e.nodeType===Node.ELEMENT_NODE&&e.contains(r))return e;let t=[],n=r.parentNode;for(;n&&n.nodeType===Node.ELEMENT_NODE;)t.push(n),n=n.parentNode;let i=[];for(n=e.parentNode;n&&n.nodeType===Node.ELEMENT_NODE;)i.push(n),n=n.parentNode;let o=t.find(s=>i.indexOf(s)>=0);return o||(o=i.find(s=>t.indexOf(s)>=0)),o}function BB(r){let e=r.cloneRange(),t=e.startContainer,n=e.startOffset,i=e.endContainer,o=e.endOffset;t.childNodes.length&&n>0&&(t=gw(t.childNodes[n-1]),n=t.length||0),o<i.childNodes.length&&(i=pw(i.childNodes[o]),o=0);let s=pw(t),c=gw(i);function f(u){if(u.childNodes.length)return!1;let y=u.length||0;return u===t&&n===y?!1:!(u===i&&o===0)}for(;s&&!f(s)&&s!==c;)s=DB(s);for(s===t?e.setStart(t,n):s!==null&&(s.nodeType===3?e.setStart(s,0):e.setStartBefore(s));c&&!f(c)&&c!==s;)c=FB(c);return c===i?e.setEnd(i,o):c!==null&&(c.nodeType===3?e.setEnd(c,c.length):e.setEndAfter(c)),e}function DB(r){if(r.firstChild)return r.firstChild;let e=r;for(;!e.nextSibling;)if(e=e.parentNode,!e)return null;return e.nextSibling}function FB(r){if(r.lastChild)return r.lastChild;let e=r;for(;!e.previousSibling;)if(e=e.parentNode,!e)return null;return e.previousSibling}function pw(r){for(;r.firstChild;)r=r.firstChild;return r}function gw(r){for(;r.lastChild;)r=r.lastChild;return r}L();var Xg=rt(bw());var mo,Qg;function Ar(r,e,t){if(r.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if(r.tagName.toLowerCase()==="html")return r.tagName.toLowerCase();let n={className:o=>!0,idName:o=>!0,optimizedMinLength:2,root:e.body,seedMinLength:1,tagName:o=>!0,threshold:1e3};mo={...n,...t},Qg=zB(mo.root,n);let i=$g(r,0,()=>$g(r,1,()=>$g(r,2)));if(i){let o=Aw(Cw(i,r));return o.length>0&&(i=o[0]),If(i)}else throw new Error("Selector was not found.")}function zB(r,e){return r.nodeType===Node.DOCUMENT_NODE?r:r===e.root?r.ownerDocument:r}function $g(r,e,t){let n=null,i=[],o=r,s=0;for(;o&&o!==mo.root.parentElement;){let c=Yg(VB(o))||Yg(...$B(o))||Yg(JB(o))||[KB()],f=YB(o);if(e===0)f&&(c=c.concat(c.filter(Kg).map(u=>Jg(u,f))));else if(e===1)c=c.slice(0,1),f&&(c=c.concat(c.filter(Kg).map(u=>Jg(u,f))));else if(e===2){let[u]=c=c.slice(0,1);f&&Kg(u)&&(c=[Jg(u,f)])}for(let u of c)u.level=s;if(i.push(c),i.length>=mo.seedMinLength&&(n=vw(i,t),n))break;o=o.parentElement,s++}return n||(n=vw(i,t)),n}function vw(r,e){let t=Aw(Sw(r));if(t.length>mo.threshold)return e?e():null;for(let n of t)if(ww(n))return n;return null}function If(r){let e=r[0],t=e.name;for(let n=1;n<r.length;n++){let i=r[n].level||0;e.level===i-1?t=`${r[n].name} > ${t}`:t=`${r[n].name} ${t}`,e=r[n]}return t}function _w(r){return r.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function ww(r){switch(Qg.querySelectorAll(If(r)).length){case 0:throw new Error(`Can't select any node with this selector: ${If(r)}`);case 1:return!0;default:return!1}}function VB(r){let e=r.getAttribute("id");return e&&mo.idName(e)?{name:"#"+(0,Xg.default)(e,{isIdentifier:!0}),penalty:0}:null}function $B(r){return Array.from(r.classList).filter(mo.className).map(t=>({name:"."+(0,Xg.default)(t,{isIdentifier:!0}),penalty:1}))}function JB(r){let e=r.tagName.toLowerCase();return mo.tagName(e)?{name:e,penalty:2}:null}function KB(){return{name:"*",penalty:3}}function YB(r){let e=r.parentNode;if(!e)return null;let t=e.firstChild;if(!t)return null;let n=0;for(;t&&(t.nodeType===Node.ELEMENT_NODE&&n++,t!==r);)t=t.nextSibling;return n}function Jg(r,e){return{name:r.name+`:nth-child(${e})`,penalty:r.penalty+1}}function Kg(r){return r.name!=="html"&&!r.name.startsWith("#")}function Yg(...r){let e=r.filter(XB);return e.length>0?e:null}function XB(r){return r!=null}function*Sw(r,e=[]){if(r.length>0)for(let t of r[0])yield*Sw(r.slice(1,r.length),e.concat(t));else yield e}function Aw(r){return Array.from(r).sort((e,t)=>_w(e)-_w(t))}function*Cw(r,e){if(r.length>2&&r.length>mo.optimizedMinLength)for(let t=1;t<r.length-1;t++){let n=[...r];n.splice(t,1),ww(n)&&QB(n,e)&&(yield n,yield*Cw(n,e))}}function QB(r,e){return Qg.querySelector(If(r))===e}L();L();var Ew="0 0 24 24",dn=(r,e,t,n="icon")=>`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="${Ew}" preserveAspectRatio="xMidYMid meet" role="img" class="${n}" aria-labelledBy="${r}">
|
|
73
|
+
`}setFont(b){let E=this.current,k=this.commonObjs.get(b[0]),P=b[1];E.font=k,this.embedFonts&&!k.missingFile&&!this.embeddedFonts[k.loadedName]&&(this.addFontStyle(k),this.embeddedFonts[k.loadedName]=k),E.fontMatrix=k.fontMatrix||n.FONT_IDENTITY_MATRIX;let N="normal";k.black?N="900":k.bold&&(N="bold");let D=k.italic?"italic":"normal";P<0?(P=-P,E.fontDirection=-1):E.fontDirection=1,E.fontSize=P,E.fontFamily=k.loadedName,E.fontWeight=N,E.fontStyle=D,E.tspan=this.svgFactory.createElement("svg:tspan"),E.tspan.setAttributeNS(null,"y",l(-E.y)),E.xcoords=[],E.ycoords=[]}endText(){var E;let b=this.current;b.textRenderingMode&n.TextRenderingMode.ADD_TO_PATH_FLAG&&((E=b.txtElement)!=null&&E.hasChildNodes())&&(b.element=b.txtElement,this.clip("nonzero"),this.endPath())}setLineWidth(b){b>0&&(this.current.lineWidth=b)}setLineCap(b){this.current.lineCap=y[b]}setLineJoin(b){this.current.lineJoin=m[b]}setMiterLimit(b){this.current.miterLimit=b}setStrokeAlpha(b){this.current.strokeAlpha=b}setStrokeRGBColor(b,E,k){this.current.strokeColor=n.Util.makeHexColor(b,E,k)}setFillAlpha(b){this.current.fillAlpha=b}setFillRGBColor(b,E,k){this.current.fillColor=n.Util.makeHexColor(b,E,k),this.current.tspan=this.svgFactory.createElement("svg:tspan"),this.current.xcoords=[],this.current.ycoords=[]}setStrokeColorN(b){this.current.strokeColor=this._makeColorN_Pattern(b)}setFillColorN(b){this.current.fillColor=this._makeColorN_Pattern(b)}shadingFill(b){let E=this.viewport.width,k=this.viewport.height,P=n.Util.inverseTransform(this.transformMatrix),N=n.Util.applyTransform([0,0],P),D=n.Util.applyTransform([0,k],P),F=n.Util.applyTransform([E,0],P),B=n.Util.applyTransform([E,k],P),V=Math.min(N[0],D[0],F[0],B[0]),q=Math.min(N[1],D[1],F[1],B[1]),G=Math.max(N[0],D[0],F[0],B[0]),Y=Math.max(N[1],D[1],F[1],B[1]),X=this.svgFactory.createElement("svg:rect");X.setAttributeNS(null,"x",V),X.setAttributeNS(null,"y",q),X.setAttributeNS(null,"width",G-V),X.setAttributeNS(null,"height",Y-q),X.setAttributeNS(null,"fill",this._makeShadingPattern(b)),this.current.fillAlpha<1&&X.setAttributeNS(null,"fill-opacity",this.current.fillAlpha),this._ensureTransformGroup().appendChild(X)}_makeColorN_Pattern(b){return b[0]==="TilingPattern"?this._makeTilingPattern(b):this._makeShadingPattern(b)}_makeTilingPattern(b){let E=b[1],k=b[2],P=b[3]||n.IDENTITY_MATRIX,[N,D,F,B]=b[4],V=b[5],q=b[6],G=b[7],Y=`shading${C++}`,[X,Q,le,ve]=n.Util.normalizeRect([...n.Util.applyTransform([N,D],P),...n.Util.applyTransform([F,B],P)]),[ce,W]=n.Util.singularValueDecompose2dScale(P),H=V*ce,R=q*W,x=this.svgFactory.createElement("svg:pattern");x.setAttributeNS(null,"id",Y),x.setAttributeNS(null,"patternUnits","userSpaceOnUse"),x.setAttributeNS(null,"width",H),x.setAttributeNS(null,"height",R),x.setAttributeNS(null,"x",`${X}`),x.setAttributeNS(null,"y",`${Q}`);let T=this.svg,O=this.transformMatrix,I=this.current.fillColor,U=this.current.strokeColor,z=this.svgFactory.create(le-X,ve-Q);if(this.svg=z,this.transformMatrix=P,G===2){let Z=n.Util.makeHexColor(...E);this.current.fillColor=Z,this.current.strokeColor=Z}return this.executeOpTree(this.convertOpList(k)),this.svg=T,this.transformMatrix=O,this.current.fillColor=I,this.current.strokeColor=U,x.appendChild(z.childNodes[0]),this.defs.appendChild(x),`url(#${Y})`}_makeShadingPattern(b){switch(typeof b=="string"&&(b=this.objs.get(b)),b[0]){case"RadialAxial":let E=`shading${C++}`,k=b[3],P;switch(b[1]){case"axial":let N=b[4],D=b[5];P=this.svgFactory.createElement("svg:linearGradient"),P.setAttributeNS(null,"id",E),P.setAttributeNS(null,"gradientUnits","userSpaceOnUse"),P.setAttributeNS(null,"x1",N[0]),P.setAttributeNS(null,"y1",N[1]),P.setAttributeNS(null,"x2",D[0]),P.setAttributeNS(null,"y2",D[1]);break;case"radial":let F=b[4],B=b[5],V=b[6],q=b[7];P=this.svgFactory.createElement("svg:radialGradient"),P.setAttributeNS(null,"id",E),P.setAttributeNS(null,"gradientUnits","userSpaceOnUse"),P.setAttributeNS(null,"cx",B[0]),P.setAttributeNS(null,"cy",B[1]),P.setAttributeNS(null,"r",q),P.setAttributeNS(null,"fx",F[0]),P.setAttributeNS(null,"fy",F[1]),P.setAttributeNS(null,"fr",V);break;default:throw new Error(`Unknown RadialAxial type: ${b[1]}`)}for(let N of k){let D=this.svgFactory.createElement("svg:stop");D.setAttributeNS(null,"offset",N[0]),D.setAttributeNS(null,"stop-color",N[1]),P.appendChild(D)}return this.defs.appendChild(P),`url(#${E})`;case"Mesh":return(0,n.warn)("Unimplemented pattern Mesh"),null;case"Dummy":return"hotpink";default:throw new Error(`Unknown IR type: ${b[0]}`)}}setDash(b,E){this.current.dashArray=b,this.current.dashPhase=E}constructPath(b,E){let k=this.current,P=k.x,N=k.y,D=[],F=0;for(let B of b)switch(B|0){case n.OPS.rectangle:P=E[F++],N=E[F++];let V=E[F++],q=E[F++],G=P+V,Y=N+q;D.push("M",l(P),l(N),"L",l(G),l(N),"L",l(G),l(Y),"L",l(P),l(Y),"Z");break;case n.OPS.moveTo:P=E[F++],N=E[F++],D.push("M",l(P),l(N));break;case n.OPS.lineTo:P=E[F++],N=E[F++],D.push("L",l(P),l(N));break;case n.OPS.curveTo:P=E[F+4],N=E[F+5],D.push("C",l(E[F]),l(E[F+1]),l(E[F+2]),l(E[F+3]),l(P),l(N)),F+=6;break;case n.OPS.curveTo2:D.push("C",l(P),l(N),l(E[F]),l(E[F+1]),l(E[F+2]),l(E[F+3])),P=E[F+2],N=E[F+3],F+=4;break;case n.OPS.curveTo3:P=E[F+2],N=E[F+3],D.push("C",l(E[F]),l(E[F+1]),l(P),l(N),l(P),l(N)),F+=4;break;case n.OPS.closePath:D.push("Z");break}D=D.join(" "),k.path&&b.length>0&&b[0]!==n.OPS.rectangle&&b[0]!==n.OPS.moveTo?D=k.path.getAttributeNS(null,"d")+D:(k.path=this.svgFactory.createElement("svg:path"),this._ensureTransformGroup().appendChild(k.path)),k.path.setAttributeNS(null,"d",D),k.path.setAttributeNS(null,"fill","none"),k.element=k.path,k.setCurrentPoint(P,N)}endPath(){let b=this.current;if(b.path=null,!this.pendingClip)return;if(!b.element){this.pendingClip=null;return}let E=`clippath${w++}`,k=this.svgFactory.createElement("svg:clipPath");k.setAttributeNS(null,"id",E),k.setAttributeNS(null,"transform",p(this.transformMatrix));let P=b.element.cloneNode(!0);if(this.pendingClip==="evenodd"?P.setAttributeNS(null,"clip-rule","evenodd"):P.setAttributeNS(null,"clip-rule","nonzero"),this.pendingClip=null,k.appendChild(P),this.defs.appendChild(k),b.activeClipUrl){b.clipGroup=null;for(let N of this.extraStack)N.clipGroup=null;k.setAttributeNS(null,"clip-path",b.activeClipUrl)}b.activeClipUrl=`url(#${E})`,this.tgrp=null}clip(b){this.pendingClip=b}closePath(){let b=this.current;if(b.path){let E=`${b.path.getAttributeNS(null,"d")}Z`;b.path.setAttributeNS(null,"d",E)}}setLeading(b){this.current.leading=-b}setTextRise(b){this.current.textRise=b}setTextRenderingMode(b){this.current.textRenderingMode=b}setHScale(b){this.current.textHScale=b/100}setRenderingIntent(b){}setFlatness(b){}setGState(b){for(let[E,k]of b)switch(E){case"LW":this.setLineWidth(k);break;case"LC":this.setLineCap(k);break;case"LJ":this.setLineJoin(k);break;case"ML":this.setMiterLimit(k);break;case"D":this.setDash(k[0],k[1]);break;case"RI":this.setRenderingIntent(k);break;case"FL":this.setFlatness(k);break;case"Font":this.setFont(k);break;case"CA":this.setStrokeAlpha(k);break;case"ca":this.setFillAlpha(k);break;default:(0,n.warn)(`Unimplemented graphic state operator ${E}`);break}}fill(){let b=this.current;b.element&&(b.element.setAttributeNS(null,"fill",b.fillColor),b.element.setAttributeNS(null,"fill-opacity",b.fillAlpha),this.endPath())}stroke(){let b=this.current;b.element&&(this._setStrokeAttributes(b.element),b.element.setAttributeNS(null,"fill","none"),this.endPath())}_setStrokeAttributes(b,E=1){let k=this.current,P=k.dashArray;E!==1&&P.length>0&&(P=P.map(function(N){return E*N})),b.setAttributeNS(null,"stroke",k.strokeColor),b.setAttributeNS(null,"stroke-opacity",k.strokeAlpha),b.setAttributeNS(null,"stroke-miterlimit",l(k.miterLimit)),b.setAttributeNS(null,"stroke-linecap",k.lineCap),b.setAttributeNS(null,"stroke-linejoin",k.lineJoin),b.setAttributeNS(null,"stroke-width",l(E*k.lineWidth)+"px"),b.setAttributeNS(null,"stroke-dasharray",P.map(l).join(" ")),b.setAttributeNS(null,"stroke-dashoffset",l(E*k.dashPhase)+"px")}eoFill(){this.current.element&&this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fill()}fillStroke(){this.stroke(),this.fill()}eoFillStroke(){this.current.element&&this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fillStroke()}closeStroke(){this.closePath(),this.stroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.closePath(),this.eoFillStroke()}paintSolidColorImageMask(){let b=this.svgFactory.createElement("svg:rect");b.setAttributeNS(null,"x","0"),b.setAttributeNS(null,"y","0"),b.setAttributeNS(null,"width","1px"),b.setAttributeNS(null,"height","1px"),b.setAttributeNS(null,"fill",this.current.fillColor),this._ensureTransformGroup().appendChild(b)}paintImageXObject(b){let E=b.startsWith("g_")?this.commonObjs.get(b):this.objs.get(b);if(!E){(0,n.warn)(`Dependent image with object ID ${b} is not ready yet`);return}this.paintInlineImageXObject(E)}paintInlineImageXObject(b,E){let k=b.width,P=b.height,N=v(b,this.forceDataSchema,!!E),D=this.svgFactory.createElement("svg:rect");D.setAttributeNS(null,"x","0"),D.setAttributeNS(null,"y","0"),D.setAttributeNS(null,"width",l(k)),D.setAttributeNS(null,"height",l(P)),this.current.element=D,this.clip("nonzero");let F=this.svgFactory.createElement("svg:image");F.setAttributeNS(u,"xlink:href",N),F.setAttributeNS(null,"x","0"),F.setAttributeNS(null,"y",l(-P)),F.setAttributeNS(null,"width",l(k)+"px"),F.setAttributeNS(null,"height",l(P)+"px"),F.setAttributeNS(null,"transform",`scale(${l(1/k)} ${l(-1/P)})`),E?E.appendChild(F):this._ensureTransformGroup().appendChild(F)}paintImageMaskXObject(b){let E=this.current,k=b.width,P=b.height,N=E.fillColor;E.maskId=`mask${A++}`;let D=this.svgFactory.createElement("svg:mask");D.setAttributeNS(null,"id",E.maskId);let F=this.svgFactory.createElement("svg:rect");F.setAttributeNS(null,"x","0"),F.setAttributeNS(null,"y","0"),F.setAttributeNS(null,"width",l(k)),F.setAttributeNS(null,"height",l(P)),F.setAttributeNS(null,"fill",N),F.setAttributeNS(null,"mask",`url(#${E.maskId})`),this.defs.appendChild(D),this._ensureTransformGroup().appendChild(F),this.paintInlineImageXObject(b,D)}paintFormXObjectBegin(b,E){if(Array.isArray(b)&&b.length===6&&this.transform(b[0],b[1],b[2],b[3],b[4],b[5]),E){let k=E[2]-E[0],P=E[3]-E[1],N=this.svgFactory.createElement("svg:rect");N.setAttributeNS(null,"x",E[0]),N.setAttributeNS(null,"y",E[1]),N.setAttributeNS(null,"width",l(k)),N.setAttributeNS(null,"height",l(P)),this.current.element=N,this.clip("nonzero"),this.endPath()}}paintFormXObjectEnd(){}_initialize(b){let E=this.svgFactory.create(b.width,b.height),k=this.svgFactory.createElement("svg:defs");E.appendChild(k),this.defs=k;let P=this.svgFactory.createElement("svg:g");return P.setAttributeNS(null,"transform",p(b.transform)),E.appendChild(P),this.svg=P,E}_ensureClipGroup(){if(!this.current.clipGroup){let b=this.svgFactory.createElement("svg:g");b.setAttributeNS(null,"clip-path",this.current.activeClipUrl),this.svg.appendChild(b),this.current.clipGroup=b}return this.current.clipGroup}_ensureTransformGroup(){return this.tgrp||(this.tgrp=this.svgFactory.createElement("svg:g"),this.tgrp.setAttributeNS(null,"transform",p(this.transformMatrix)),this.current.activeClipUrl?this._ensureClipGroup().appendChild(this.tgrp):this.svg.appendChild(this.tgrp)),this.tgrp}}}},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PDFNodeStream=void 0;var n=t(1),i=t(26);let o=gf(),s=FC(),c=HC(),f=pf(),u=/^file:\/\/\/[a-zA-Z]:\//;function y(A){let C=f.parse(A);return C.protocol==="file:"||C.host?C:/^[a-z]:[/\\]/i.test(A)?f.parse(`file:///${A}`):(C.host||(C.protocol="file:"),C)}class m{constructor(C){this.source=C,this.url=y(C.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=this.isHttp&&C.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){var C;return((C=this._fullRequestReader)==null?void 0:C._loaded)??0}getFullReader(){return(0,n.assert)(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new p(this):new h(this),this._fullRequestReader}getRangeReader(C,b){if(b<=this._progressiveDataLength)return null;let E=this.isFsUrl?new w(this,C,b):new l(this,C,b);return this._rangeRequestReaders.push(E),E}cancelAllRequests(C){this._fullRequestReader&&this._fullRequestReader.cancel(C);for(let b of this._rangeRequestReaders.slice(0))b.cancel(C)}}e.PDFNodeStream=m;class _{constructor(C){this._url=C.url,this._done=!1,this._storedError=null,this.onProgress=null;let b=C.source;this._contentLength=b.length,this._loaded=0,this._filename=null,this._disableRange=b.disableRange||!1,this._rangeChunkSize=b.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!b.disableStream,this._isRangeSupported=!b.disableRange,this._readableStream=null,this._readCapability=(0,n.createPromiseCapability)(),this._headersCapability=(0,n.createPromiseCapability)()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let C=this._readableStream.read();return C===null?(this._readCapability=(0,n.createPromiseCapability)(),this.read()):(this._loaded+=C.length,this.onProgress&&this.onProgress({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(C).buffer,done:!1})}cancel(C){if(!this._readableStream){this._error(C);return}this._readableStream.destroy(C)}_error(C){this._storedError=C,this._readCapability.resolve()}_setReadableStream(C){this._readableStream=C,C.on("readable",()=>{this._readCapability.resolve()}),C.on("end",()=>{C.destroy(),this._done=!0,this._readCapability.resolve()}),C.on("error",b=>{this._error(b)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new n.AbortException("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class v{constructor(C){this._url=C.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=(0,n.createPromiseCapability)();let b=C.source;this._isStreamingSupported=!b.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let C=this._readableStream.read();return C===null?(this._readCapability=(0,n.createPromiseCapability)(),this.read()):(this._loaded+=C.length,this.onProgress&&this.onProgress({loaded:this._loaded}),{value:new Uint8Array(C).buffer,done:!1})}cancel(C){if(!this._readableStream){this._error(C);return}this._readableStream.destroy(C)}_error(C){this._storedError=C,this._readCapability.resolve()}_setReadableStream(C){this._readableStream=C,C.on("readable",()=>{this._readCapability.resolve()}),C.on("end",()=>{C.destroy(),this._done=!0,this._readCapability.resolve()}),C.on("error",b=>{this._error(b)}),this._storedError&&this._readableStream.destroy(this._storedError)}}function g(A,C){return{protocol:A.protocol,auth:A.auth,host:A.hostname,port:A.port,path:A.path,method:"GET",headers:C}}class h extends _{constructor(C){super(C);let b=E=>{if(E.statusCode===404){let D=new n.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=D,this._headersCapability.reject(D);return}this._headersCapability.resolve(),this._setReadableStream(E);let k=D=>this._readableStream.headers[D.toLowerCase()],{allowRangeRequests:P,suggestedLength:N}=(0,i.validateRangeRequestCapabilities)({getResponseHeader:k,isHttp:C.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=P,this._contentLength=N||this._contentLength,this._filename=(0,i.extractFilenameFromHeader)(k)};this._request=null,this._url.protocol==="http:"?this._request=s.request(g(this._url,C.httpHeaders),b):this._request=c.request(g(this._url,C.httpHeaders),b),this._request.on("error",E=>{this._storedError=E,this._headersCapability.reject(E)}),this._request.end()}}class l extends v{constructor(C,b,E){super(C),this._httpHeaders={};for(let P in C.httpHeaders){let N=C.httpHeaders[P];typeof N>"u"||(this._httpHeaders[P]=N)}this._httpHeaders.Range=`bytes=${b}-${E-1}`;let k=P=>{if(P.statusCode===404){let N=new n.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=N;return}this._setReadableStream(P)};this._request=null,this._url.protocol==="http:"?this._request=s.request(g(this._url,this._httpHeaders),k):this._request=c.request(g(this._url,this._httpHeaders),k),this._request.on("error",P=>{this._storedError=P}),this._request.end()}}class p extends _{constructor(C){super(C);let b=decodeURIComponent(this._url.path);u.test(this._url.href)&&(b=b.replace(/^\//,"")),o.lstat(b,(E,k)=>{if(E){E.code==="ENOENT"&&(E=new n.MissingPDFException(`Missing PDF "${b}".`)),this._storedError=E,this._headersCapability.reject(E);return}this._contentLength=k.size,this._setReadableStream(o.createReadStream(b)),this._headersCapability.resolve()})}}class w extends v{constructor(C,b,E){super(C);let k=decodeURIComponent(this._url.path);u.test(this._url.href)&&(k=k.replace(/^\//,"")),this._setReadableStream(o.createReadStream(k,{start:b,end:E-1}))}}},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createResponseStatusError=f,e.extractFilenameFromHeader=c,e.validateRangeRequestCapabilities=s,e.validateResponseStatus=u;var n=t(1),i=t(27),o=t(5);function s({getResponseHeader:y,isHttp:m,rangeChunkSize:_,disableRange:v}){let g={allowRangeRequests:!1,suggestedLength:void 0},h=parseInt(y("Content-Length"),10);return!Number.isInteger(h)||(g.suggestedLength=h,h<=2*_)||v||!m||y("Accept-Ranges")!=="bytes"||(y("Content-Encoding")||"identity")!=="identity"||(g.allowRangeRequests=!0),g}function c(y){let m=y("Content-Disposition");if(m){let _=(0,i.getFilenameFromContentDispositionHeader)(m);if(_.includes("%"))try{_=decodeURIComponent(_)}catch{}if((0,o.isPdfFile)(_))return _}return null}function f(y,m){return y===404||y===0&&m.startsWith("file:")?new n.MissingPDFException('Missing PDF "'+m+'".'):new n.UnexpectedResponseException(`Unexpected server response (${y}) while retrieving PDF "${m}".`,y)}function u(y){return y===200||y===206}},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getFilenameFromContentDispositionHeader=i;var n=t(1);function i(o){let s=!0,c=f("filename\\*","i").exec(o);if(c){c=c[1];let h=_(c);return h=unescape(h),h=v(h),h=g(h),y(h)}if(c=m(o),c){let h=g(c);return y(h)}if(c=f("filename","i").exec(o),c){c=c[1];let h=_(c);return h=g(h),y(h)}function f(h,l){return new RegExp("(?:^|;)\\s*"+h+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',l)}function u(h,l){if(h){if(!/^[\x00-\xFF]+$/.test(l))return l;try{let p=new TextDecoder(h,{fatal:!0}),w=(0,n.stringToBytes)(l);l=p.decode(w),s=!1}catch{}}return l}function y(h){return s&&/[\x80-\xff]/.test(h)&&(h=u("utf-8",h),s&&(h=u("iso-8859-1",h))),h}function m(h){let l=[],p,w=f("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(p=w.exec(h))!==null;){let[,C,b,E]=p;if(C=parseInt(C,10),C in l){if(C===0)break;continue}l[C]=[b,E]}let A=[];for(let C=0;C<l.length&&C in l;++C){let[b,E]=l[C];E=_(E),b&&(E=unescape(E),C===0&&(E=v(E))),A.push(E)}return A.join("")}function _(h){if(h.startsWith('"')){let l=h.slice(1).split('\\"');for(let p=0;p<l.length;++p){let w=l[p].indexOf('"');w!==-1&&(l[p]=l[p].slice(0,w),l.length=p+1),l[p]=l[p].replace(/\\(.)/g,"$1")}h=l.join('"')}return h}function v(h){let l=h.indexOf("'");if(l===-1)return h;let p=h.slice(0,l),A=h.slice(l+1).replace(/^[^']*'/,"");return u(p,A)}function g(h){return!h.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(h)?h:h.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(l,p,w,A){if(w==="q"||w==="Q")return A=A.replace(/_/g," "),A=A.replace(/=([0-9a-fA-F]{2})/g,function(C,b){return String.fromCharCode(parseInt(b,16))}),u(p,A);try{A=atob(A)}catch{}return u(p,A)})}return""}},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PDFNetworkStream=void 0;var n=t(1),i=t(26);let o=200,s=206;function c(_){let v=_.response;return typeof v!="string"?v:(0,n.stringToBytes)(v).buffer}class f{constructor(v,g={}){this.url=v,this.isHttp=/^https?:/i.test(v),this.httpHeaders=this.isHttp&&g.httpHeaders||Object.create(null),this.withCredentials=g.withCredentials||!1,this.getXhr=g.getXhr||function(){return new XMLHttpRequest},this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(v,g,h){let l={begin:v,end:g};for(let p in h)l[p]=h[p];return this.request(l)}requestFull(v){return this.request(v)}request(v){let g=this.getXhr(),h=this.currXhrId++,l=this.pendingRequests[h]={xhr:g};g.open("GET",this.url),g.withCredentials=this.withCredentials;for(let p in this.httpHeaders){let w=this.httpHeaders[p];typeof w>"u"||g.setRequestHeader(p,w)}return this.isHttp&&"begin"in v&&"end"in v?(g.setRequestHeader("Range",`bytes=${v.begin}-${v.end-1}`),l.expectedStatus=s):l.expectedStatus=o,g.responseType="arraybuffer",v.onError&&(g.onerror=function(p){v.onError(g.status)}),g.onreadystatechange=this.onStateChange.bind(this,h),g.onprogress=this.onProgress.bind(this,h),l.onHeadersReceived=v.onHeadersReceived,l.onDone=v.onDone,l.onError=v.onError,l.onProgress=v.onProgress,g.send(null),h}onProgress(v,g){var l;let h=this.pendingRequests[v];h&&((l=h.onProgress)==null||l.call(h,g))}onStateChange(v,g){var C,b,E;let h=this.pendingRequests[v];if(!h)return;let l=h.xhr;if(l.readyState>=2&&h.onHeadersReceived&&(h.onHeadersReceived(),delete h.onHeadersReceived),l.readyState!==4||!(v in this.pendingRequests))return;if(delete this.pendingRequests[v],l.status===0&&this.isHttp){(C=h.onError)==null||C.call(h,l.status);return}let p=l.status||o;if(!(p===o&&h.expectedStatus===s)&&p!==h.expectedStatus){(b=h.onError)==null||b.call(h,l.status);return}let A=c(l);if(p===s){let k=l.getResponseHeader("Content-Range"),P=/bytes (\d+)-(\d+)\/(\d+)/.exec(k);h.onDone({begin:parseInt(P[1],10),chunk:A})}else A?h.onDone({begin:0,chunk:A}):(E=h.onError)==null||E.call(h,l.status)}getRequestXhr(v){return this.pendingRequests[v].xhr}isPendingRequest(v){return v in this.pendingRequests}abortRequest(v){let g=this.pendingRequests[v].xhr;delete this.pendingRequests[v],g.abort()}}class u{constructor(v){this._source=v,this._manager=new f(v.url,{httpHeaders:v.httpHeaders,withCredentials:v.withCredentials}),this._rangeChunkSize=v.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(v){let g=this._rangeRequestReaders.indexOf(v);g>=0&&this._rangeRequestReaders.splice(g,1)}getFullReader(){return(0,n.assert)(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new y(this._manager,this._source),this._fullRequestReader}getRangeReader(v,g){let h=new m(this._manager,v,g);return h.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(h),h}cancelAllRequests(v){var g;(g=this._fullRequestReader)==null||g.cancel(v);for(let h of this._rangeRequestReaders.slice(0))h.cancel(v)}}e.PDFNetworkStream=u;class y{constructor(v,g){this._manager=v;let h={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=g.url,this._fullRequestId=v.requestFull(h),this._headersReceivedCapability=(0,n.createPromiseCapability)(),this._disableRange=g.disableRange||!1,this._contentLength=g.length,this._rangeChunkSize=g.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){let v=this._fullRequestId,g=this._manager.getRequestXhr(v),h=w=>g.getResponseHeader(w),{allowRangeRequests:l,suggestedLength:p}=(0,i.validateRangeRequestCapabilities)({getResponseHeader:h,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});l&&(this._isRangeSupported=!0),this._contentLength=p||this._contentLength,this._filename=(0,i.extractFilenameFromHeader)(h),this._isRangeSupported&&this._manager.abortRequest(v),this._headersReceivedCapability.resolve()}_onDone(v){if(v&&(this._requests.length>0?this._requests.shift().resolve({value:v.chunk,done:!1}):this._cachedChunks.push(v.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(let g of this._requests)g.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(v){this._storedError=(0,i.createResponseStatusError)(v,this._url),this._headersReceivedCapability.reject(this._storedError);for(let g of this._requests)g.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(v){var g;(g=this.onProgress)==null||g.call(this,{loaded:v.loaded,total:v.lengthComputable?v.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersReceivedCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let v=(0,n.createPromiseCapability)();return this._requests.push(v),v.promise}cancel(v){this._done=!0,this._headersReceivedCapability.reject(v);for(let g of this._requests)g.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class m{constructor(v,g,h){this._manager=v;let l={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=v.url,this._requestId=v.requestRange(g,h,l),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){var v;(v=this.onClosed)==null||v.call(this,this)}_onDone(v){let g=v.chunk;this._requests.length>0?this._requests.shift().resolve({value:g,done:!1}):this._queuedChunk=g,this._done=!0;for(let h of this._requests)h.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(v){this._storedError=(0,i.createResponseStatusError)(v,this._url);for(let g of this._requests)g.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(v){var g;this.isStreamingSupported||(g=this.onProgress)==null||g.call(this,{loaded:v.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){let g=this._queuedChunk;return this._queuedChunk=null,{value:g,done:!1}}if(this._done)return{value:void 0,done:!0};let v=(0,n.createPromiseCapability)();return this._requests.push(v),v.promise}cancel(v){this._done=!0;for(let g of this._requests)g.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}},(r,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PDFFetchStream=void 0;var n=t(1),i=t(26);function o(y,m,_){return{method:"GET",headers:y,signal:_==null?void 0:_.signal,mode:"cors",credentials:m?"include":"same-origin",redirect:"follow"}}function s(y){let m=new Headers;for(let _ in y){let v=y[_];typeof v>"u"||m.append(_,v)}return m}class c{constructor(m){this.source=m,this.isHttp=/^https?:/i.test(m.url),this.httpHeaders=this.isHttp&&m.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){var m;return((m=this._fullRequestReader)==null?void 0:m._loaded)??0}getFullReader(){return(0,n.assert)(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new f(this),this._fullRequestReader}getRangeReader(m,_){if(_<=this._progressiveDataLength)return null;let v=new u(this,m,_);return this._rangeRequestReaders.push(v),v}cancelAllRequests(m){this._fullRequestReader&&this._fullRequestReader.cancel(m);for(let _ of this._rangeRequestReaders.slice(0))_.cancel(m)}}e.PDFFetchStream=c;class f{constructor(m){this._stream=m,this._reader=null,this._loaded=0,this._filename=null;let _=m.source;this._withCredentials=_.withCredentials||!1,this._contentLength=_.length,this._headersCapability=(0,n.createPromiseCapability)(),this._disableRange=_.disableRange||!1,this._rangeChunkSize=_.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),typeof AbortController<"u"&&(this._abortController=new AbortController),this._isStreamingSupported=!_.disableStream,this._isRangeSupported=!_.disableRange,this._headers=s(this._stream.httpHeaders);let v=_.url;fetch(v,o(this._headers,this._withCredentials,this._abortController)).then(g=>{if(!(0,i.validateResponseStatus)(g.status))throw(0,i.createResponseStatusError)(g.status,v);this._reader=g.body.getReader(),this._headersCapability.resolve();let h=w=>g.headers.get(w),{allowRangeRequests:l,suggestedLength:p}=(0,i.validateRangeRequestCapabilities)({getResponseHeader:h,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=l,this._contentLength=p||this._contentLength,this._filename=(0,i.extractFilenameFromHeader)(h),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new n.AbortException("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;let{value:m,done:_}=await this._reader.read();return _?{value:m,done:_}:(this._loaded+=m.byteLength,this.onProgress&&this.onProgress({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(m).buffer,done:!1})}cancel(m){this._reader&&this._reader.cancel(m),this._abortController&&this._abortController.abort()}}class u{constructor(m,_,v){this._stream=m,this._reader=null,this._loaded=0;let g=m.source;this._withCredentials=g.withCredentials||!1,this._readCapability=(0,n.createPromiseCapability)(),this._isStreamingSupported=!g.disableStream,typeof AbortController<"u"&&(this._abortController=new AbortController),this._headers=s(this._stream.httpHeaders),this._headers.append("Range",`bytes=${_}-${v-1}`);let h=g.url;fetch(h,o(this._headers,this._withCredentials,this._abortController)).then(l=>{if(!(0,i.validateResponseStatus)(l.status))throw(0,i.createResponseStatusError)(l.status,h);this._readCapability.resolve(),this._reader=l.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;let{value:m,done:_}=await this._reader.read();return _?{value:m,done:_}:(this._loaded+=m.byteLength,this.onProgress&&this.onProgress({loaded:this._loaded}),{value:new Uint8Array(m).buffer,done:!1})}cancel(m){this._reader&&this._reader.cancel(m),this._abortController&&this._abortController.abort()}}}],__webpack_module_cache__={};function __w_pdfjs_require__(r){var e=__webpack_module_cache__[r];if(e!==void 0)return e.exports;var t=__webpack_module_cache__[r]={exports:{}};return __webpack_modules__[r](t,t.exports,__w_pdfjs_require__),t.exports}var __webpack_exports__={};return(()=>{var r=__webpack_exports__;Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"AnnotationLayer",{enumerable:!0,get:function(){return i.AnnotationLayer}}),Object.defineProperty(r,"AnnotationMode",{enumerable:!0,get:function(){return e.AnnotationMode}}),Object.defineProperty(r,"CMapCompressionType",{enumerable:!0,get:function(){return e.CMapCompressionType}}),Object.defineProperty(r,"GlobalWorkerOptions",{enumerable:!0,get:function(){return o.GlobalWorkerOptions}}),Object.defineProperty(r,"InvalidPDFException",{enumerable:!0,get:function(){return e.InvalidPDFException}}),Object.defineProperty(r,"LoopbackPort",{enumerable:!0,get:function(){return t.LoopbackPort}}),Object.defineProperty(r,"MissingPDFException",{enumerable:!0,get:function(){return e.MissingPDFException}}),Object.defineProperty(r,"OPS",{enumerable:!0,get:function(){return e.OPS}}),Object.defineProperty(r,"PDFDataRangeTransport",{enumerable:!0,get:function(){return t.PDFDataRangeTransport}}),Object.defineProperty(r,"PDFDateString",{enumerable:!0,get:function(){return n.PDFDateString}}),Object.defineProperty(r,"PDFWorker",{enumerable:!0,get:function(){return t.PDFWorker}}),Object.defineProperty(r,"PasswordResponses",{enumerable:!0,get:function(){return e.PasswordResponses}}),Object.defineProperty(r,"PermissionFlag",{enumerable:!0,get:function(){return e.PermissionFlag}}),Object.defineProperty(r,"PixelsPerInch",{enumerable:!0,get:function(){return n.PixelsPerInch}}),Object.defineProperty(r,"RenderingCancelledException",{enumerable:!0,get:function(){return n.RenderingCancelledException}}),Object.defineProperty(r,"SVGGraphics",{enumerable:!0,get:function(){return f.SVGGraphics}}),Object.defineProperty(r,"UNSUPPORTED_FEATURES",{enumerable:!0,get:function(){return e.UNSUPPORTED_FEATURES}}),Object.defineProperty(r,"UnexpectedResponseException",{enumerable:!0,get:function(){return e.UnexpectedResponseException}}),Object.defineProperty(r,"Util",{enumerable:!0,get:function(){return e.Util}}),Object.defineProperty(r,"VerbosityLevel",{enumerable:!0,get:function(){return e.VerbosityLevel}}),Object.defineProperty(r,"XfaLayer",{enumerable:!0,get:function(){return u.XfaLayer}}),Object.defineProperty(r,"build",{enumerable:!0,get:function(){return t.build}}),Object.defineProperty(r,"createPromiseCapability",{enumerable:!0,get:function(){return e.createPromiseCapability}}),Object.defineProperty(r,"createValidAbsoluteUrl",{enumerable:!0,get:function(){return e.createValidAbsoluteUrl}}),Object.defineProperty(r,"getDocument",{enumerable:!0,get:function(){return t.getDocument}}),Object.defineProperty(r,"getFilenameFromUrl",{enumerable:!0,get:function(){return n.getFilenameFromUrl}}),Object.defineProperty(r,"getPdfFilenameFromUrl",{enumerable:!0,get:function(){return n.getPdfFilenameFromUrl}}),Object.defineProperty(r,"getXfaPageViewport",{enumerable:!0,get:function(){return n.getXfaPageViewport}}),Object.defineProperty(r,"isPdfFile",{enumerable:!0,get:function(){return n.isPdfFile}}),Object.defineProperty(r,"loadScript",{enumerable:!0,get:function(){return n.loadScript}}),Object.defineProperty(r,"renderTextLayer",{enumerable:!0,get:function(){return c.renderTextLayer}}),Object.defineProperty(r,"shadow",{enumerable:!0,get:function(){return e.shadow}}),Object.defineProperty(r,"version",{enumerable:!0,get:function(){return t.version}});var e=__w_pdfjs_require__(1),t=__w_pdfjs_require__(4),n=__w_pdfjs_require__(5),i=__w_pdfjs_require__(20),o=__w_pdfjs_require__(13),s=__w_pdfjs_require__(3),c=__w_pdfjs_require__(23),f=__w_pdfjs_require__(24),u=__w_pdfjs_require__(22);let y="2.14.305",m="eaaa8b4ad";if(s.isNodeJS){let{PDFNodeStream:_}=__w_pdfjs_require__(25);(0,t.setPDFNetworkStreamFactory)(v=>new _(v))}else{let{PDFNetworkStream:_}=__w_pdfjs_require__(28),{PDFFetchStream:v}=__w_pdfjs_require__(29);(0,t.setPDFNetworkStreamFactory)(g=>(0,n.isValidFetchUrl)(g.url)?new v(g):new _(g))}})(),__webpack_exports__})())});var YU={};F0(YU,{Link:()=>au,default:()=>JU,load:()=>KU});L();L();L();var r4=rt(e4()),n4=rt(Tr());L();var t4=rt(Tr());function ba(r,e){return t4.TaJson.deserialize(r,e)}var uo=class extends r4.Publication{static async fromUrl(e,t){let i=await(await fetch(e.href,t)).json(),o=ba(i,uo);return o.manifestUrl=e,o}get readingOrder(){return this.Spine??[]}get resources(){return this.Resources??[]}get tableOfContents(){var e,t;return(e=this.sample)!=null&&e.isSampleRead&&((t=this.positions)==null?void 0:t.length)>0?this.limitedTOC():this.TOC||[]}limitedTOC(){var n;function e(i){for(let o=0;o<i.Children.length;o++){let s=i.Children[o];s.Href=void 0,s.Children&&e(s)}}return((n=this.TOC)==null?void 0:n.map(i=>{var o,s;if(i.Href){let c=this.positionsByHref(this.getRelativeHref(i.Href));if((c==null?void 0:c.length)>0){let f=c[0],u=Math.round((f.locations.totalProgression?f.locations.totalProgression:0)*100);(o=this.sample)!=null&&o.limit&&(u<=((s=this.sample)==null?void 0:s.limit)||(i.Href=void 0,i.Children&&e(i)))}}return i}))||[]}get landmarks(){return this.Landmarks}get pageList(){return this.PageList}get isFixedLayout(){var e;return((e=this.Metadata.Rendition)==null?void 0:e.Layout)==="fixed"}get isReflowable(){return!this.isFixedLayout}get layout(){return this.isFixedLayout?"fixed":"reflowable"}get hasMediaOverlays(){return this.readingOrder?this.readingOrder.filter(e=>{var t;return(t=e.Properties)==null?void 0:t.MediaOverlay}).length>0:!1}getStartLink(){if(this.readingOrder!==void 0&&this.readingOrder.length>0)return this.readingOrder[0]}getPreviousSpineItem(e){let t=this.getSpineIndex(e);if(t!==void 0&&this.readingOrder!==void 0&&t>0)return this.readingOrder[t-1]}getNextSpineItem(e){let t=this.getSpineIndex(e);if(t!==void 0&&this.readingOrder!==void 0&&t<this.readingOrder.length-1)return this.readingOrder[t+1]}getSpineItem(e){let t=this.getSpineIndex(e);if(t!==void 0&&this.readingOrder!==void 0)return this.readingOrder[t]}getSpineIndex(e){var t;return(t=this.readingOrder)==null?void 0:t.findIndex(n=>n.Href&&this.getAbsoluteHref(n.Href)===e)}getAbsoluteHref(e){return new URL(e,this.manifestUrl.href).href}getRelativeHref(e){let t=this.manifestUrl.href.replace("/manifest.json",""),n=e.replace(t,"");return n.indexOf("#")>0&&(n=n.slice(0,n.indexOf("#"))),n.charAt(0)==="/"&&(n=n.substring(1)),n}getTOCItemAbsolute(e){let t=this.getAbsoluteHref(e),n=(o,s)=>{for(let c=0;c<s.length;c++){let f=s[c];if(f.Href){let u=f.Href.indexOf("#")!==-1?f.Href.slice(0,f.Href.indexOf("#")):f.Href;if(this.getAbsoluteHref(u)===o)return f}if(f.Children){let u=n(o,f.Children);if(u!==void 0)return u}}},i=n(t,this.tableOfContents);return i===void 0&&this.readingOrder!==void 0&&(i=n(t,this.readingOrder)),i}getTOCItem(e){let t=(i,o)=>{for(let s=0;s<o.length;s++){let c=o[s];if(c.Href&&this.getAbsoluteHref(c.Href)===i)return c;if(c.Children){let f=t(i,c.Children);if(f!==void 0)return f}}},n=t(e,this.tableOfContents);if(n===void 0&&this.readingOrder!==void 0&&(n=t(e,this.readingOrder)),n===void 0&&e.indexOf("#")!==-1){let i=e.slice(0,e.indexOf("#"));n=t(i,this.tableOfContents),n===void 0&&this.readingOrder!==void 0&&(n=t(i,this.readingOrder))}return n}positionsByHref(e){var n;let t=decodeURI(e)??"";return(n=this.positions)==null?void 0:n.filter(i=>t.includes(i.href))}async autoGeneratePositions(e,t=QR){let n=0,i=0,o=[];if(this.readingOrder!==void 0)for(let c of this.readingOrder)if(this.isFixedLayout){let f={href:c.Href,locations:{progression:0,position:n+1},type:c.TypeLink};o.push(f),n=n+1}else{let f=this.getAbsoluteHref(c.Href),u=await t(f,e);c.contentLength=u,i+=u;let m=Math.max(1,Math.ceil(u/1024));for(let _=0;_<m;_++){let v={href:c.Href,locations:{progression:_/m,position:n+(_+1)},type:c.TypeLink};o.push(v)}n=n+m}var s=0;if(this.isReflowable&&this.readingOrder!==void 0)for(let c of this.readingOrder){if(!c.contentLength){console.error("Link is missing contentLength",c);return}c.contentWeight=100/i*c.contentLength,s=s+c.contentWeight}for(let c of o){let f=o.filter(y=>y.href===decodeURI(c.href)),u=Math.ceil((c.locations.progression?c.locations.progression:0)*(f.length-1));c.locations.position&&(c.locations.totalProgression=(c.locations.position-1)/o.length),c.locations.remainingPositions=Math.abs(u-(f.length-1)),c.locations.position&&(c.locations.totalRemainingPositions=Math.abs(c.locations.position-1-(o.length-1)))}this.positions=o}async fetchPositionsFromService(e,t){let i=await(await fetch(e,t)).json();this.positions=i.positions}async fetchWeightsFromService(e,t){if(this.isFixedLayout){console.warn("Not fetching weights from service for fixed layout publication.");return}let i=await(await fetch(e,t)).json();this.readingOrder!==void 0&&this.readingOrder.forEach(o=>{o.contentWeight=i[o.Href]})}};uo=Lc([(0,n4.JsonObject)()],uo);var QR=async(r,e)=>(await(await fetch(r,e)).blob()).size;L();L();var Ss=class{json(){return JSON.stringify(this)}},Up=class extends Ss{constructor(e,t,n){super(),this.value=e,this.ref=t,this.name=n}toString(){return this.value}},jp=class extends Ss{constructor(e,t,n){super(),this.value=e,this.ref=t,this.name=n}toString(){return this.value}toJson(){return JSON.parse(this.value)}},qp=class extends Ss{constructor(e,t,n,i){super(),this.value=e,this.values=t,this.ref=n,this.name=i}toString(){return this.values[this.value]}},Gp=class extends Ss{constructor(t,n,i,o,s,c,f){super();this.countDecimals=function(t){return t%1!==0?t.toString().split(".")[1].length:1};this.value=t,this.min=n,this.max=i,this.step=o,this.suffix=s,this.ref=c,this.name=f}toString(){return this.value.toString()+this.suffix}increment(){let t=this.countDecimals(this.max);parseFloat(this.value.toFixed(t))<this.max&&(this.value=parseFloat(this.value.toFixed(t))+this.step)}decrement(){let t=this.countDecimals(this.min);parseFloat(this.value.toFixed(t))>this.min&&(this.value=parseFloat(this.value.toFixed(t))-this.step)}},va=class extends Ss{constructor(e,t,n,i,o){super(),this.value=n,this.onValue=e,this.offValue=t,this.ref=i,this.name=o}toString(){return this.value?this.onValue:this.offValue}switch(){this.value=!this.value}},ki=class{constructor(){this.properties=[]}addIncremental(e,t,n,i,o,s,c){this.properties.push(new Gp(e,t,n,i,o,s,c))}addStringable(e,t,n){this.properties.push(new Up(e,t,n))}addJSONable(e,t,n){this.properties.push(new jp(e,t,n))}addSwitchable(e,t,n,i,o){this.properties.push(new va(e,t,n,i,o))}addEnumerable(e,t,n,i){this.properties.push(new qp(e,t,n,i))}getByRef(e){let t=this.properties.filter(n=>n.ref===e);return t.length>0?t[0]:null}getByKey(e){let t=this.properties.filter(n=>n.key===e);return t.length>0?t[0]:null}};L();var xt=class xt{};xt.FONT_SIZE_REF="fontSize",xt.FONT_FAMILY_REF="fontFamily",xt.FONT_OVERRIDE_REF="fontOverride",xt.APPEARANCE_REF="appearance",xt.SCROLL_REF="scroll",xt.TEXT_ALIGNMENT_REF="textAlign",xt.COLUMN_COUNT_REF="colCount",xt.WORD_SPACING_REF="wordSpacing",xt.LETTER_SPACING_REF="letterSpacing",xt.PAGE_MARGINS_REF="pageMargins",xt.LINE_HEIGHT_REF="lineHeight",xt.FONT_SIZE_KEY="--USER__"+xt.FONT_SIZE_REF,xt.FONT_FAMILY_KEY="--USER__"+xt.FONT_FAMILY_REF,xt.FONT_OVERRIDE_KEY="--USER__"+xt.FONT_OVERRIDE_REF,xt.APPEARANCE_KEY="--USER__"+xt.APPEARANCE_REF,xt.SCROLL_KEY="--USER__"+xt.SCROLL_REF,xt.TEXT_ALIGNMENT_KEY="--USER__"+xt.TEXT_ALIGNMENT_REF,xt.COLUMN_COUNT_KEY="--USER__"+xt.COLUMN_COUNT_REF,xt.WORD_SPACING_KEY="--USER__"+xt.WORD_SPACING_REF,xt.LETTER_SPACING_KEY="--USER__"+xt.LETTER_SPACING_REF,xt.PAGE_MARGINS_KEY="--USER__"+xt.PAGE_MARGINS_REF,xt.LINE_HEIGHT_KEY="--USER__"+xt.LINE_HEIGHT_REF;var Se=xt;L();function Ne(r,e){return r.querySelector(e)}function ft(r,e){let t=Ne(r,e);if(t&&t instanceof HTMLElement)return t;throw new Error("required element "+e+" not found")}function cr(r,e){if(r===null)throw new Error("parent element is null");return r.querySelector(e)}function lo(r,e){let t=cr(r,e);if(t)return t;throw new Error("required element "+e+" not found in iframe")}function Lr(r,e,t){r.setAttribute(e,t)}L();L();var Q6=rt(Hg());var Ia=class{constructor(e){this.getScrollingElement=e=>e.scrollingElement?e.scrollingElement:e.body;this.navigator=e}async handleFootnote(e,t){var i,o;let n=e.getAttribute("href");if(n&&n.indexOf("#")>0){let c=function(u){let y=document.location.href;return new URL(u,y).href},s=n.substring(n.indexOf("#")+1),f=c(n);f&&(f=f.substring(0,f.indexOf("#")),t.preventDefault(),t.stopPropagation(),(i=this.navigator.api)!=null&&i.getContent?await((o=this.navigator.api)==null?void 0:o.getContent(n).then(u=>{let _=new DOMParser().parseFromString(u,"text/html").querySelector("#"+s);_&&(t.preventDefault(),t.stopPropagation(),this.showPopup(_,t))})):await fetch(f,this.navigator.requestConfig).then(u=>u.text()).then(async u=>{let _=new DOMParser().parseFromString(u,"text/html").querySelector("#"+s);_&&(t.preventDefault(),t.stopPropagation(),this.showPopup(_,t))}))}}async hidePopover(){var n,i;let e=(n=this.navigator.iframes[0].contentDocument)==null?void 0:n.getElementById("d2-popover");e&&((i=e.parentElement)==null||i.removeChild(e));let t=ft(document,"#iframe-wrapper");t.style.overflow="auto"}async showPopover(e,t){var s,c,f,u,y,m;let n=e.getAttribute("href"),i=e.getAttribute("src");function o(_){let v=document.location.href;return new URL(_,v).href}if(n){let _=o(n);if(_){t.preventDefault(),t.stopPropagation();let v=(s=this.navigator.iframes[0].contentDocument)==null?void 0:s.getElementById("d2-popover");v&&((c=v.parentElement)==null||c.removeChild(v));let g=document.createElement("div");g.id="d2-popover",g.className="d2-popover is-active";let h=ft(document,"#iframe-wrapper");h.style.overflow="hidden",g.style.top=h.scrollTop+"px",g.style.height=h.clientHeight*.9+"px";let l=document.createElement("div");l.className="d2-popover-wrapper",g.appendChild(l);let p=document.createElement("div");p.className="d2-popover-content",l.appendChild(p),(f=this.navigator.api)!=null&&f.getContent?await((u=this.navigator.api)==null?void 0:u.getContent(n).then(C=>{p.innerHTML=C;let b=this.navigator.iframes[0].contentDocument;b&&b.body.appendChild(g)})):await fetch(_,this.navigator.requestConfig).then(C=>C.text()).then(async C=>{p.innerHTML=C;let b=this.navigator.iframes[0].contentDocument;b&&b.body.appendChild(g)});let w=this.navigator.iframes[0].contentWindow;if(!w)return;let A=this;w.onclick=function(C){t.target!==C.target&&g.parentElement&&(A.hidePopover(),w&&(w.onclick=null))}}}else if(i&&o(i)){t.preventDefault(),t.stopPropagation();let v=(y=this.navigator.iframes[0].contentDocument)==null?void 0:y.getElementById("d2-popover");v&&((m=v.parentElement)==null||m.removeChild(v));let g=document.createElement("div");g.id="d2-popover",g.className="d2-popover is-active";let h=ft(document,"#iframe-wrapper");h.style.overflow="hidden",g.style.top=h.scrollTop+"px",g.style.height=h.clientHeight*.9+"px";let l=document.createElement("div");l.className="d2-popover-wrapper",g.appendChild(l);let p=document.createElement("img");p.className="d2-popover-content",l.appendChild(p),p.src=i;let w=this.navigator.iframes[0].contentDocument;w&&w.body.appendChild(g);let A=this.navigator.iframes[0].contentWindow;if(!A)return;let C=this;A.onclick=function(b){t.target!==b.target&&g.parentElement&&(C.hidePopover(),A&&(A.onclick=null))}}}showPopup(e,t){var l,p,w;let n=(l=this.navigator.iframes[0].contentDocument)==null?void 0:l.getElementById("d2-popup");n&&((p=n.parentElement)==null||p.removeChild(n));let i=document.createElement("aside");i.id="d2-popup",i.className="d2-popup is-active";let o=document.createElement("div");o.className="d2-popup-wrapper",i.appendChild(o);let s=document.createElement("div");s.className="d2-popup-content",o.appendChild(s);let c=document.createElement("p");s.appendChild(c),typeof e=="string"?c.innerHTML=e:c.innerHTML=(0,Q6.default)(e.innerHTML,{allowedTags:[],allowedAttributes:{}});let f=(w=this.navigator.view)==null?void 0:w.isPaginated(),u=this.navigator.iframes[0].contentDocument;if(!u)return;let y=this.getScrollingElement(u),m=f?y.scrollLeft:0,_=f?y.scrollTop:0,v=t.x+m,g=t.y+_;i.style.top=g+"px",f&&(i.style.left=v+"px"),u.body.appendChild(i);let h=this.navigator.iframes[0].contentWindow;h&&(h.onclick=function(A){t.target!==A.target&&i.parentElement&&(i.style.display="none",i.parentElement.removeChild(i),h&&(h.onclick=null))})}};var Pf=rt($t());function _e(r,e,t){r&&r.addEventListener(e,t,!0)}function Ue(r,e,t){r&&r.removeEventListener(e,t,!0)}var yl=class{constructor(e){this.onInternalLink=()=>{};this.onClickThrough=()=>{};this.checkForLink=e=>{let t=e.target;for(;t&&t.tagName.toLowerCase()!=="body";){if(t.tagName.toLowerCase()==="a"&&t.href)return t;t=t.parentElement}return null};this.linkInPublication=(e,t)=>e.some(n=>{var i;return!((i=n.Rel)!=null&&i.includes("external"))&&this.navigator.publication.getRelativeHref(t).includes(n.Href)});this.isReadingOrderInternal=e=>(Pf.default.log("clickedLink: ",e),this.linkInPublication(this.navigator.publication.readingOrder,e.href));this.isResourceInternal=e=>(Pf.default.log("clickedLink: ",e),this.linkInPublication(this.navigator.publication.resources,e.href));this.handleLinks=async e=>{Pf.default.log("R2 Click Handler");let t=this.checkForLink(e);if(t){let n=window.location.protocol===t.protocol&&window.location.port===t.port&&window.location.hostname===t.hostname,i=this.isReadingOrderInternal(t),o=this.isResourceInternal(t);o||await this.popup.hidePopover();let s=t.href.indexOf("#");if(!i&&!o)window.open(t.href,t.target??"_blank"),e.preventDefault(),e.stopPropagation();else if(e.target.href=t.href,(n||i)&&s!==-1){let c=e.target;c?c.getAttribute("epub:type")==="noteref"?await this.popup.handleFootnote(c,e):o&&!i?await this.popup.showPopover(c,e):this.onInternalLink(e):this.onInternalLink(e)}else(n||i)&&s===-1&&this.onInternalLink(e)}else this.onClickThrough(e)};this.navigator=e,this.popup=new Ia(this.navigator)}setupEvents(e){if(e!==null)e.addEventListener("dblclick",async t=>{let n=t.target;t.target&&n.tagName.toLowerCase()==="img"&&await this.popup.showPopover(n,t)},!0),e.addEventListener("click",this.handleLinks.bind(this));else throw"cannot setup events for null"}};L();L();function ew(){return ft(document,"#iframe-wrapper").clientWidth}function hi(){return ft(document,"#iframe-wrapper").clientHeight}var rw=rt(Vo()),bl=class{constructor(e){this.layout="reflowable";this.USERSETTINGS="userSetting";this.sideMargin=20;this.height=0;this.attributes={margin:0};this.hasFixedScrollWidth=!1;this.store=e,this.scrollMode?(this.name="readium-scroll-on",this.label="Scrolling"):(this.name="readium-scroll-off",this.label="Paginated")}setMode(e){var t;if(this.scrollMode=e,e){this.name="readium-scroll-on",this.label="Scrolling";let n=this.iframe.contentDocument;if(n){let i=cr(n,"head");if(i){let s=Ne(i,"meta[name=viewport]");s&&s.remove()}let o=cr(n,"html");o&&o.style.setProperty("--USER__scroll","readium-scroll-on")}this.setSize(),this.setIframeHeight(this.iframe)}else{this.height=hi()-40-this.attributes.margin,this.name="readium-scroll-off",this.label="Paginated",this.checkForFixedScrollWidth();let n=this.iframe.contentDocument;if(n){let i=cr(n,"html");i&&i.style.setProperty("--USER__scroll","readium-scroll-off")}this.setSize()}this.navigator.rights.enableContentProtection&&((t=this.navigator.contentProtectionModule)==null||t.recalculate())}start(){if(this.scrollMode){let e=this.iframe.contentDocument;if(e){let t=cr(e,"head");if(t){let n=Ne(t,"meta[name=viewport]");n&&n.remove()}}this.setSize(),this.setIframeHeight(this.iframe)}else{this.iframe.height="0",this.iframe.width="0",this.setSize();let e=document.createElement("meta");e.name="viewport",e.content="width=device-width, initial-scale=1, maximum-scale=1",this.checkForFixedScrollWidth()}}stop(){if(this.iframe.height="0",this.iframe.width="0",this.iframe.contentDocument){let t=cr(this.iframe.contentDocument,"body"),n=Array.prototype.slice.call(t.querySelectorAll("img"));for(let i of n)i.style.maxWidth=""}}getCurrentPosition(){let e=ft(document,"#iframe-wrapper");if(this.scrollMode)return e.scrollTop/this.scrollingElement.scrollHeight;{let t=this.getColumnWidth(),n=this.getLeftColumnsWidth(),i=this.getRightColumnsWidth(),o=n+t+i;return n/o}}goToProgression(e){let t=ft(document,"#iframe-wrapper");if(this.scrollMode)t.scrollTop=this.scrollingElement.scrollHeight*e;else{let n=this.getColumnWidth(),i=this.getLeftColumnsWidth(),o=this.getRightColumnsWidth(),s=i+n+o,c=e*s,f=Math.round(c/n)*n;f>=s&&(f=f-n),this.setLeftColumnsWidth(f)}}goToCssSelector(e,t){let n=this.iframe.contentDocument;if(n){let i=n.querySelector(e);this.goToElement(i,t)}}goToFragment(e,t){let n=this.iframe.contentDocument;if(n){let i=n.getElementById(e);this.goToElement(i,t)}}snap(e,t){var n;if(e&&!this.scrollMode){let i=e.style.height;e.style.height="0";let o=this.getColumnWidth(),s=this.getLeftColumnsWidth()+e.getBoundingClientRect().left,c=Math.floor(s/o)*o;e.style.height=i,this.setLeftColumnsWidth(c),this.navigator.rights.enableContentProtection&&((n=this.navigator.contentProtectionModule)==null||n.recalculate(0))}}goToElement(e,t){var n;if(this.scrollMode)e&&e.scrollIntoView({block:"center"});else if(e){let i=e.style.height;e.style.height="0";let o=e.getBoundingClientRect().left,s=this.getColumnWidth(),c=this.scrollingElement.scrollLeft-s,f=Math.ceil(o/s)*s+c;if(t){let u=this.getLeftColumnsWidth();f=Math.ceil(o/s)*s+u}e.style.height=i,this.setLeftColumnsWidth(f),this.navigator.rights.enableContentProtection&&((n=this.navigator.contentProtectionModule)==null||n.recalculate(200))}}atStart(){return this.scrollMode?ft(document,"#iframe-wrapper").scrollTop===0:this.getLeftColumnsWidth()<=0}atEnd(){if(this.scrollMode){let e=ft(document,"#iframe-wrapper");return Math.ceil(this.scrollingElement.scrollHeight-e.scrollTop)-1<=hi()}else return Math.floor(this.getRightColumnsWidth())<=0||Math.ceil(this.getCurrentPage())===this.getPageCount()}goToPreviousPage(){var t;let e=ft(document,"#iframe-wrapper");if(this.scrollMode){let n=e.scrollTop,i=this.getScreenHeight()-40,o=n-i;o>=0?e.scrollTop=o:e.scrollTop=0}else{let n=this.getLeftColumnsWidth(),i=this.getColumnWidth(),o=n-i;o>=0?this.setLeftColumnsWidth(o):this.setLeftColumnsWidth(0),this.navigator.checkResourcePosition()}this.navigator.rights.enableContentProtection&&((t=this.navigator.contentProtectionModule)==null||t.recalculate())}goToNextPage(){var t;let e=ft(document,"#iframe-wrapper");if(this.scrollMode){let n=e.scrollTop,i=this.getScreenHeight()-40,o=this.scrollingElement.scrollHeight,s=n+i;s<o?e.scrollTop=s:e.scrollTop=o}else{let n=this.getLeftColumnsWidth(),i=this.getColumnWidth(),o=this.scrollWidth,s=n+i;s<o?this.setLeftColumnsWidth(s):this.setLeftColumnsWidth(o),this.navigator.checkResourcePosition()}this.navigator.rights.enableContentProtection&&((t=this.navigator.contentProtectionModule)==null||t.recalculate())}getCurrentPage(){return this.scrollMode?0:this.getCurrentPosition()*this.getPageCount()+1}getPageCount(){if(this.scrollMode)return 0;{let e=this.getColumnWidth();return this.scrollWidth/e}}isPaginated(){if(this.iframe){let e=this.iframe.contentDocument;if(e){let t=cr(e,"html");if(t)return!(t.style.getPropertyValue("--USER__scroll")==="readium-scroll-on")}}return!this.scrollMode}isScrollMode(){if(this.iframe){let e=this.iframe.contentDocument;if(e){let t=cr(e,"html");if(t)return t.style.getPropertyValue("--USER__scroll")==="readium-scroll-on"}}return this.scrollMode}async getProperty(e){let t=await this.store.get(this.USERSETTINGS);if(t){let n=JSON.parse(t);return n=n.filter(i=>i.name===e),n.length===0?null:n[0]}return null}getScreenHeight(){return ft(document,"#iframe-wrapper").clientHeight}setIframeHeight(e){(0,rw.default)(n=>{if(n){let i=n.contentWindow.document.body,o=n.contentWindow.document.documentElement,s=Math.max(i==null?void 0:i.scrollHeight,i==null?void 0:i.offsetHeight,o==null?void 0:o.clientHeight,o==null?void 0:o.scrollHeight,o==null?void 0:o.offsetHeight);if(s){let c=hi()-this.attributes.margin;n.height=Math.max(c,s)+"px"}}},200)(e)}checkForFixedScrollWidth(){let e=this.iframe.contentDocument;if(e){let t=cr(e,"body"),n=t==null?void 0:t.scrollWidth;this.hasFixedScrollWidth=(t==null?void 0:t.scrollWidth)===n}}setSize(){var e,t;if(this.iframe.width=ew()+"px",this.scrollMode){let n=(t=(e=this.iframe.contentWindow)==null?void 0:e.document)==null?void 0:t.documentElement;this.iframe.height=(n==null?void 0:n.offsetHeight)+"px"}else{let n=this.iframe.contentDocument;n&&n.documentElement&&(n.documentElement.style.height=this.height+"px"),this.iframe.height=this.height+"px"}}getLeftColumnsWidth(){return Math.ceil(this.scrollingElement.scrollLeft)}getRightColumnsWidth(){let e=this.getColumnWidth(),t=this.scrollWidth-e;if(this.hasFixedScrollWidth){let n=this.getLeftColumnsWidth();t=Math.max(0,t-n)}return t}getColumnWidth(){return this.scrollingElement.clientWidth}setLeftColumnsWidth(e){this.scrollingElement.scrollLeft=e}get scrollingElement(){var e,t,n,i;return(e=this.iframe.contentDocument)!=null&&e.scrollingElement?(t=this.iframe.contentDocument)==null?void 0:t.scrollingElement:(n=this.iframe.contentDocument)!=null&&n.body?(i=this.iframe.contentDocument)==null?void 0:i.body:document.createElement("body")}get scrollWidth(){var i;let e=(i=this.scrollingElement)==null?void 0:i.scrollWidth,t=this.getColumnWidth();return Math.ceil(e/t)*t}};L();var vl=class{constructor(){this.layout="fixed";this.sideMargin=20;this.height=0;this.attributes={margin:0}}start(){}stop(){}getCurrentPosition(){return 0}getScreenHeight(){return ft(document,"#iframe-wrapper").clientHeight}goToProgression(e){}goToCssSelector(e,t){}goToFragment(e,t){}snap(e,t){}getCurrentPage(){return 0}getPageCount(){return 1}setSize(){}isPaginated(){return!0}isScrollMode(){return!1}atEnd(){return!0}atStart(){return!0}};var Ln=rt($t()),At=class At{constructor(e,t,n,i,o){this.USERSETTINGS="userSetting";this.fontSize=100;this.fontOverride=!1;this.fontFamily=0;this.appearance=0;this.verticalScroll=!0;this.textAlignment=0;this.columnCount=0;this.wordSpacing=0;this.letterSpacing=0;this.pageMargins=2;this.lineHeight=1;this.settingsChangeCallback=()=>{};this.settingsColumnsChangeCallback=()=>{};this.viewChangeCallback=()=>{};var s;this.store=e,this.view=o==="fixed"?new vl:new bl(this.store),this.headerMenu=t,this.api=n,this.injectables=i,(s=this.injectables)==null||s.forEach(c=>{c.type==="style"&&(c.fontFamily&&this.addFont(c.fontFamily),c.appearance&&this.addAppearance(c.appearance))})}async isPaginated(){return!await this.getPropertyAndFallback("verticalScroll",Se.SCROLL_KEY)}async isScrollMode(){return!await this.isPaginated()}static async create(e){let t=new this(e.store,e.headerMenu,e.api,e.injectables,e.layout);if(await t.initialise(),e.initialUserSettings){t.userProperties||(t.userProperties=t.getUserSettings());let n=e.initialUserSettings;if(n.verticalScroll!==void 0){t.verticalScroll=this.parseScrollSetting(n.verticalScroll);let i=t.userProperties.getByRef(Se.SCROLL_REF);i&&(i.value=t.verticalScroll,await t.saveProperty(i)),Ln.default.log(t.verticalScroll)}if(n.appearance){t.appearance=At.parseAppearanceSetting(n.appearance);let i=t.userProperties.getByRef(Se.APPEARANCE_REF);i&&(i.value=t.appearance,await t.saveProperty(i)),Ln.default.log(t.appearance)}if(n.fontSize){t.fontSize=n.fontSize;let i=t.userProperties.getByRef(Se.FONT_SIZE_REF);i&&(i.value=t.fontSize,await t.saveProperty(i)),Ln.default.log(t.fontSize)}if(n.fontFamily){t.fontFamily=At.fontFamilyValues.findIndex(o=>o===n.fontFamily);let i=t.userProperties.getByRef(Se.FONT_FAMILY_REF);i&&(i.value=t.fontFamily,await t.saveProperty(i)),Ln.default.log(t.fontFamily),t.fontFamily!==0&&(t.fontOverride=!0)}if(n.textAlignment){t.textAlignment=At.textAlignmentValues.findIndex(o=>o===n.textAlignment);let i=t.userProperties.getByRef(Se.TEXT_ALIGNMENT_REF);i&&(i.value=t.textAlignment,await t.saveProperty(i)),Ln.default.log(t.textAlignment)}if(n.columnCount){t.columnCount=At.columnCountValues.findIndex(o=>o===n.columnCount);let i=t.userProperties.getByRef(Se.COLUMN_COUNT_REF);i&&(i.value=t.columnCount,await t.saveProperty(i)),Ln.default.log(t.columnCount)}if(n.wordSpacing){t.wordSpacing=n.wordSpacing;let i=t.userProperties.getByRef(Se.WORD_SPACING_REF);i&&(i.value=t.wordSpacing,await t.saveProperty(i)),Ln.default.log(t.wordSpacing)}if(n.letterSpacing){t.letterSpacing=n.letterSpacing;let i=t.userProperties.getByRef(Se.LETTER_SPACING_REF);i&&(i.value=t.letterSpacing,await t.saveProperty(i)),Ln.default.log(t.letterSpacing)}if(n.pageMargins){t.pageMargins=n.pageMargins;let i=t.userProperties.getByRef(Se.PAGE_MARGINS_REF);i&&(i.value=t.pageMargins,await t.saveProperty(i)),Ln.default.log(t.pageMargins)}if(n.lineHeight){t.lineHeight=n.lineHeight;let i=t.userProperties.getByRef(Se.LINE_HEIGHT_REF);i&&(i.value=t.lineHeight,await t.saveProperty(i)),Ln.default.log(t.lineHeight)}t.userProperties=t.getUserSettings(),await t.initialise()}return await t.initializeSelections(),new Promise(n=>n(t))}stop(){Ln.default.log("book settings stop")}async initialise(){this.appearance=await this.getPropertyAndFallback("appearance",Se.APPEARANCE_KEY),this.verticalScroll=await this.getPropertyAndFallback("verticalScroll",Se.SCROLL_KEY),this.fontFamily=await this.getPropertyAndFallback("fontFamily",Se.FONT_FAMILY_KEY),this.fontFamily!==0&&(this.fontOverride=!0),this.textAlignment=await this.getPropertyAndFallback("textAlignment",Se.TEXT_ALIGNMENT_KEY),this.columnCount=await this.getPropertyAndFallback("columnCount",Se.COLUMN_COUNT_KEY),this.fontSize=await this.getPropertyAndFallback("fontSize",Se.FONT_SIZE_KEY),this.wordSpacing=await this.getPropertyAndFallback("wordSpacing",Se.WORD_SPACING_KEY),this.letterSpacing=await this.getPropertyAndFallback("letterSpacing",Se.LETTER_SPACING_KEY),this.pageMargins=await this.getPropertyAndFallback("pageMargins",Se.PAGE_MARGINS_KEY),this.lineHeight=await this.getPropertyAndFallback("lineHeight",Se.LINE_HEIGHT_KEY),this.userProperties=this.getUserSettings()}async reset(){this.appearance=0,this.verticalScroll=!0,this.fontSize=100,this.fontOverride=!1,this.fontFamily=0,this.textAlignment=0,this.columnCount=0,this.wordSpacing=0,this.letterSpacing=0,this.pageMargins=2,this.lineHeight=1,this.userProperties=this.getUserSettings();let e=this.iframe.contentDocument;if(e){let t=cr(e,"html");if(t){let n=document.documentElement,i=ft(n,"body");t.style.removeProperty(Se.FONT_SIZE_KEY),t.style.removeProperty(Se.WORD_SPACING_KEY),t.style.removeProperty(Se.LETTER_SPACING_KEY),t.style.removeProperty(Se.COLUMN_COUNT_KEY),t.style.removeProperty(Se.TEXT_ALIGNMENT_KEY),t.style.removeProperty(Se.LINE_HEIGHT_KEY),t.style.removeProperty(Se.PAGE_MARGINS_KEY),t.style.removeProperty(Se.APPEARANCE_KEY),Lr(n,"data-viewer-theme","day"),Lr(i,"data-viewer-theme","day"),t.style.removeProperty(Se.FONT_FAMILY_KEY),Lr(t,"data-viewer-font","publisher"),t.style.setProperty(Se.FONT_OVERRIDE_KEY,"readium-font-off")}}}async initializeSelections(){this.headerMenu&&(this.settingsView=Ne(this.headerMenu,"#container-view-settings"))}async applyProperties(){var t,n,i,o,s,c,f,u,y,m,_,v,g,h,l,p,w,A,C,b,E,k;this.userProperties=this.getUserSettings();let e=this.iframe.contentDocument;if(e){let P=cr(e,"html");if(P){let N=document.documentElement,D=ft(N,"body");if((t=this.view)!=null&&t.navigator.publication.isReflowable&&(await this.getProperty(Se.FONT_SIZE_KEY)&&P.style.setProperty(Se.FONT_SIZE_KEY,((n=this.userProperties.getByRef(Se.FONT_SIZE_REF))==null?void 0:n.toString())??null),await this.getProperty(Se.WORD_SPACING_KEY)&&P.style.setProperty(Se.WORD_SPACING_KEY,((i=this.userProperties.getByRef(Se.WORD_SPACING_REF))==null?void 0:i.toString())??null),await this.getProperty(Se.LETTER_SPACING_KEY)&&P.style.setProperty(Se.LETTER_SPACING_KEY,((o=this.userProperties.getByRef(Se.LETTER_SPACING_REF))==null?void 0:o.toString())??null)),await this.getProperty(Se.COLUMN_COUNT_KEY)&&P.style.setProperty(Se.COLUMN_COUNT_KEY,((s=this.userProperties.getByRef(Se.COLUMN_COUNT_REF))==null?void 0:s.toString())??null),(c=this.view)!=null&&c.navigator.publication.isReflowable&&(await this.getProperty(Se.TEXT_ALIGNMENT_KEY)&&(((f=this.userProperties.getByRef(Se.TEXT_ALIGNMENT_REF))==null?void 0:f.toString())==="auto"?P.style.removeProperty(Se.TEXT_ALIGNMENT_KEY):P.style.setProperty(Se.TEXT_ALIGNMENT_KEY,((u=this.userProperties.getByRef(Se.TEXT_ALIGNMENT_REF))==null?void 0:u.toString())??null)),await this.getProperty(Se.LINE_HEIGHT_KEY)&&P.style.setProperty(Se.LINE_HEIGHT_KEY,((y=this.userProperties.getByRef(Se.LINE_HEIGHT_REF))==null?void 0:y.toString())??null),await this.getProperty(Se.PAGE_MARGINS_KEY)&&P.style.setProperty(Se.PAGE_MARGINS_KEY,((m=this.userProperties.getByRef(Se.PAGE_MARGINS_REF))==null?void 0:m.toString())??null)),await this.getProperty(Se.APPEARANCE_KEY)?(P.style.setProperty(Se.APPEARANCE_KEY,((_=this.userProperties.getByRef(Se.APPEARANCE_REF))==null?void 0:_.toString())??null),((v=this.userProperties.getByRef(Se.APPEARANCE_REF))==null?void 0:v.value)===0?(Lr(N,"data-viewer-theme","day"),Lr(D,"data-viewer-theme","day")):((g=this.userProperties.getByRef(Se.APPEARANCE_REF))==null?void 0:g.value)===1?(Lr(N,"data-viewer-theme","sepia"),Lr(D,"data-viewer-theme","sepia")):((h=this.userProperties.getByRef(Se.APPEARANCE_REF))==null?void 0:h.value)===2&&(Lr(N,"data-viewer-theme","night"),Lr(D,"data-viewer-theme","night"))):(P.style.setProperty(Se.APPEARANCE_KEY,((l=this.userProperties.getByRef(Se.APPEARANCE_REF))==null?void 0:l.toString())??null),Lr(N,"data-viewer-theme","day"),Lr(D,"data-viewer-theme","day")),(p=this.view)!=null&&p.navigator.publication.isReflowable){if(await this.getProperty(Se.FONT_FAMILY_KEY))if(P.style.setProperty(Se.FONT_FAMILY_KEY,((w=this.userProperties.getByRef(Se.FONT_FAMILY_REF))==null?void 0:w.toString())??null),((A=this.userProperties.getByRef(Se.FONT_FAMILY_REF))==null?void 0:A.value)===0)Lr(P,"data-viewer-font","publisher"),P.style.setProperty(Se.FONT_OVERRIDE_KEY,"readium-font-off");else if(((C=this.userProperties.getByRef(Se.FONT_FAMILY_REF))==null?void 0:C.value)===1)Lr(P,"data-viewer-font","serif"),P.style.setProperty(Se.FONT_OVERRIDE_KEY,"readium-font-on");else if(((b=this.userProperties.getByRef(Se.FONT_FAMILY_REF))==null?void 0:b.value)===2)Lr(P,"data-viewer-font","sans"),P.style.setProperty(Se.FONT_OVERRIDE_KEY,"readium-font-on");else{let F=this.userProperties.getByRef(Se.FONT_FAMILY_REF);F&&Lr(P,"data-viewer-font",F.toString()),P.style.setProperty(Se.FONT_OVERRIDE_KEY,"readium-font-on")}else P.style.setProperty(Se.FONT_FAMILY_KEY,((E=this.userProperties.getByRef(Se.FONT_FAMILY_REF))==null?void 0:E.toString())??null),Lr(P,"data-viewer-font","publisher"),P.style.setProperty(Se.FONT_OVERRIDE_KEY,"readium-font-off");await this.getProperty(Se.SCROLL_KEY)?((k=this.userProperties.getByRef(Se.SCROLL_REF))==null?void 0:k.value)===!0?P.style.setProperty("--USER__scroll","readium-scroll-on"):P.style.setProperty("--USER__scroll","readium-scroll-off"):P.style.setProperty("--USER__scroll","readium-scroll-on"),P.style.setProperty("--USER__advancedSettings","readium-advanced-on"),this.isScrollMode().then(F=>{var B,V;(V=(B=this.view)==null?void 0:B.setMode)==null||V.call(B,F)})}}}}setIframe(e){this.iframe=e,this.view&&(this.view.iframe=e),this.settingsView&&At.renderControls(this.settingsView)}static renderControls(e){_e(Ne(e,"ul"),"click",t=>{t.stopPropagation()})}onSettingsChange(e){this.settingsChangeCallback=e}onColumnSettingsChange(e){this.settingsColumnsChangeCallback=e}onViewChange(e){this.viewChangeCallback=e}async storeProperty(e){await this.updateUserSettings(),await this.saveProperty(e)}addAppearance(e){At.appearanceValues.includes(e)||At.appearanceValues.push(e)}initAddedAppearance(){this.applyProperties()}addFont(e){At.fontFamilyValues.includes(e)||At.fontFamilyValues.push(e)}initAddedFont(){this.applyProperties()}async updateUserSettings(){var t,n,i,o,s,c,f,u,y,m,_,v,g,h,l,p,w,A;let e={fontFamily:At.fontFamilyValues[await((n=(t=this.userProperties)==null?void 0:t.getByRef(Se.FONT_FAMILY_REF))==null?void 0:n.value)],fontSize:(o=(i=this.userProperties)==null?void 0:i.getByRef(Se.FONT_SIZE_REF))==null?void 0:o.value,appearance:At.appearanceValues[await((c=(s=this.userProperties)==null?void 0:s.getByRef(Se.APPEARANCE_REF))==null?void 0:c.value)],textAlignment:At.textAlignmentValues[await((u=(f=this.userProperties)==null?void 0:f.getByRef(Se.TEXT_ALIGNMENT_REF))==null?void 0:u.value)],columnCount:At.columnCountValues[await((m=(y=this.userProperties)==null?void 0:y.getByRef(Se.COLUMN_COUNT_REF))==null?void 0:m.value)],wordSpacing:(v=(_=this.userProperties)==null?void 0:_.getByRef(Se.WORD_SPACING_REF))==null?void 0:v.value,letterSpacing:(h=(g=this.userProperties)==null?void 0:g.getByRef(Se.LETTER_SPACING_REF))==null?void 0:h.value,verticalScroll:(p=(l=this.userProperties)==null?void 0:l.getByRef(Se.SCROLL_REF))==null?void 0:p.value};(w=this.api)!=null&&w.updateSettings&&((A=this.api)==null||A.updateSettings(e).then(C=>{Ln.default.log("api updated user settings",JSON.stringify(e))}))}getUserSettings(){let e=new ki;return e.addSwitchable("readium-font-on","readium-font-off",this.fontOverride,Se.FONT_OVERRIDE_REF,Se.FONT_OVERRIDE_KEY),e.addEnumerable(this.columnCount,At.columnCountValues,Se.COLUMN_COUNT_REF,Se.COLUMN_COUNT_KEY),e.addEnumerable(this.appearance,At.appearanceValues,Se.APPEARANCE_REF,Se.APPEARANCE_KEY),e.addIncremental(this.pageMargins,.5,4,.25,"",Se.PAGE_MARGINS_REF,Se.PAGE_MARGINS_KEY),e.addEnumerable(this.textAlignment,At.textAlignmentValues,Se.TEXT_ALIGNMENT_REF,Se.TEXT_ALIGNMENT_KEY),e.addEnumerable(this.fontFamily,At.fontFamilyValues,Se.FONT_FAMILY_REF,Se.FONT_FAMILY_KEY),e.addIncremental(this.fontSize,100,300,25,"%",Se.FONT_SIZE_REF,Se.FONT_SIZE_KEY),e.addIncremental(this.lineHeight,1,2,.25,"em",Se.LINE_HEIGHT_REF,Se.LINE_HEIGHT_KEY),e.addIncremental(this.wordSpacing,0,1,.25,"rem",Se.WORD_SPACING_REF,Se.WORD_SPACING_KEY),e.addIncremental(this.letterSpacing,0,.5,.0625,"em",Se.LETTER_SPACING_REF,Se.LETTER_SPACING_KEY),e.addSwitchable("readium-scroll-on","readium-scroll-off",this.verticalScroll,Se.SCROLL_REF,Se.SCROLL_KEY),e}async saveProperty(e){let t=await this.store.get(this.USERSETTINGS);if(t){let n=JSON.parse(t);n=n.filter(i=>i.name!==e.name),e.value!==void 0&&n.push(e),await this.store.set(this.USERSETTINGS,JSON.stringify(n))}else{let n=[];n.push(e),await this.store.set(this.USERSETTINGS,JSON.stringify(n))}return new Promise(n=>n(e))}async getProperty(e){let t=await this.store.get(this.USERSETTINGS);if(t){let n=JSON.parse(t);return n=n.filter(i=>i.name===e),n.length===0?null:n[0]}return null}async getPropertyAndFallback(e,t){var n;return((n=await this.getProperty(t))==null?void 0:n.value)??this[e]}async resetUserSettings(){this.store.remove(this.USERSETTINGS),await this.reset(),this.viewChangeCallback(),this.settingsChangeCallback()}get currentSettings(){var e,t,n,i,o,s,c,f;return{appearance:At.appearanceValues[(t=(e=this.userProperties)==null?void 0:e.getByRef(Se.APPEARANCE_REF))==null?void 0:t.value],fontFamily:At.fontFamilyValues[(i=(n=this.userProperties)==null?void 0:n.getByRef(Se.FONT_FAMILY_REF))==null?void 0:i.value],textAlignment:At.textAlignmentValues[(s=(o=this.userProperties)==null?void 0:o.getByRef(Se.TEXT_ALIGNMENT_REF))==null?void 0:s.value],columnCount:At.columnCountValues[(f=(c=this.userProperties)==null?void 0:c.getByRef(Se.COLUMN_COUNT_REF))==null?void 0:f.value],verticalScroll:this.verticalScroll,fontSize:this.fontSize,wordSpacing:this.wordSpacing,letterSpacing:this.letterSpacing,pageMargins:this.pageMargins,lineHeight:this.lineHeight}}async applyUserSettings(e){var t,n,i,o,s,c,f,u,y,m,_,v,g,h;if(e.appearance){this.appearance=At.parseAppearanceSetting(e.appearance);let l=(t=this.userProperties)==null?void 0:t.getByRef(Se.APPEARANCE_REF);l&&(l.value=this.appearance,await this.storeProperty(l))}if(e.fontSize){this.fontSize=e.fontSize;let l=(n=this.userProperties)==null?void 0:n.getByRef(Se.FONT_SIZE_REF);l&&(l.value=this.fontSize,await this.storeProperty(l))}if(e.fontFamily){this.fontFamily=At.fontFamilyValues.findIndex(p=>p===e.fontFamily);let l=(i=this.userProperties)==null?void 0:i.getByRef(Se.FONT_FAMILY_REF);l&&(l.value=this.fontFamily,await this.storeProperty(l))}if(e.letterSpacing){this.letterSpacing=e.letterSpacing;let l=(o=this.userProperties)==null?void 0:o.getByRef(Se.LETTER_SPACING_REF);l&&(l.value=this.letterSpacing,await this.storeProperty(l))}if(e.wordSpacing){this.wordSpacing=e.wordSpacing;let l=(s=this.userProperties)==null?void 0:s.getByRef(Se.WORD_SPACING_REF);l&&(l.value=this.wordSpacing,await this.storeProperty(l))}if(e.columnCount){this.columnCount=At.columnCountValues.findIndex(p=>p===e.columnCount);let l=(c=this.userProperties)==null?void 0:c.getByRef(Se.COLUMN_COUNT_REF);l&&(l.value=this.columnCount,await this.storeProperty(l)),this.settingsColumnsChangeCallback()}if(e.textAlignment){this.textAlignment=At.textAlignmentValues.findIndex(p=>p===e.textAlignment);let l=(f=this.userProperties)==null?void 0:f.getByRef(Se.TEXT_ALIGNMENT_REF);l&&(l.value=this.textAlignment,await this.storeProperty(l))}if(e.lineHeight){this.lineHeight=e.lineHeight;let l=(u=this.userProperties)==null?void 0:u.getByRef(Se.LINE_HEIGHT_REF);l&&(l.value=this.lineHeight,await this.storeProperty(l))}if(e.pageMargins){this.pageMargins=e.pageMargins;let l=(y=this.userProperties)==null?void 0:y.getByRef(Se.PAGE_MARGINS_REF);l&&(l.value=this.pageMargins,await this.storeProperty(l))}if(e.verticalScroll!==void 0){let l=(m=this.view)==null?void 0:m.getCurrentPosition();this.verticalScroll=At.parseScrollSetting(e.verticalScroll);let p=(_=this.userProperties)==null?void 0:_.getByRef(Se.SCROLL_REF);p&&(p.value=this.verticalScroll,await this.saveProperty(p)),(g=(v=this.view)==null?void 0:v.setMode)==null||g.call(v,this.verticalScroll),l&&((h=this.view)==null||h.goToProgression(l)),this.viewChangeCallback()}await this.applyProperties(),this.settingsChangeCallback()}static parseScrollSetting(e){switch(e){case!0:case"scroll":case"readium-scroll-on":return!0;case!1:case"paginated":case"readium-scroll-off":return!1;default:return!1}}static parseAppearanceSetting(e){let t;return e==="day"||e==="readium-default-on"?t=At.appearanceValues[0]:e==="sepia"||e==="readium-sepia-on"?t=At.appearanceValues[1]:e==="night"||e==="readium-night-on"?t=At.appearanceValues[2]:t=e,At.appearanceValues.findIndex(n=>n===t)}async scroll(e){var i,o,s,c,f;let t=(i=this.view)==null?void 0:i.getCurrentPosition();this.verticalScroll=e;let n=(o=this.userProperties)==null?void 0:o.getByRef(Se.SCROLL_REF);n&&(n.value=this.verticalScroll,await this.saveProperty(n)),await this.applyProperties(),(c=(s=this.view)==null?void 0:s.setMode)==null||c.call(s,this.verticalScroll),t&&((f=this.view)==null||f.goToProgression(t)),this.viewChangeCallback()}async increase(e){var t,n,i,o,s,c,f,u,y,m,_,v,g,h,l,p;if(e==="fontSize"){((t=this.userProperties)==null?void 0:t.getByRef(Se.FONT_SIZE_REF)).increment(),this.fontSize=(i=(n=this.userProperties)==null?void 0:n.getByRef(Se.FONT_SIZE_REF))==null?void 0:i.value;let w=(o=this.userProperties)==null?void 0:o.getByRef(Se.FONT_SIZE_REF);w&&await this.storeProperty(w)}else if(e==="letterSpacing"){((s=this.userProperties)==null?void 0:s.getByRef(Se.LETTER_SPACING_REF)).increment(),this.letterSpacing=(f=(c=this.userProperties)==null?void 0:c.getByRef(Se.LETTER_SPACING_REF))==null?void 0:f.value;let w=(u=this.userProperties)==null?void 0:u.getByRef(Se.LETTER_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="wordSpacing"){((y=this.userProperties)==null?void 0:y.getByRef(Se.WORD_SPACING_REF)).increment(),this.wordSpacing=(_=(m=this.userProperties)==null?void 0:m.getByRef(Se.WORD_SPACING_REF))==null?void 0:_.value;let w=(v=this.userProperties)==null?void 0:v.getByRef(Se.WORD_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="lineHeight"){((g=this.userProperties)==null?void 0:g.getByRef(Se.LINE_HEIGHT_REF)).increment(),this.lineHeight=(l=(h=this.userProperties)==null?void 0:h.getByRef(Se.LINE_HEIGHT_REF))==null?void 0:l.value;let w=(p=this.userProperties)==null?void 0:p.getByRef(Se.LINE_HEIGHT_REF);w&&await this.storeProperty(w)}await this.applyProperties(),this.settingsChangeCallback()}async decrease(e){var t,n,i,o,s,c,f,u,y,m,_,v,g,h,l,p;if(e==="fontSize"){((t=this.userProperties)==null?void 0:t.getByRef(Se.FONT_SIZE_REF)).decrement(),this.fontSize=(i=(n=this.userProperties)==null?void 0:n.getByRef(Se.FONT_SIZE_REF))==null?void 0:i.value;let w=(o=this.userProperties)==null?void 0:o.getByRef(Se.FONT_SIZE_REF);w&&await this.storeProperty(w)}else if(e==="letterSpacing"){((s=this.userProperties)==null?void 0:s.getByRef(Se.LETTER_SPACING_REF)).decrement(),this.letterSpacing=(f=(c=this.userProperties)==null?void 0:c.getByRef(Se.LETTER_SPACING_REF))==null?void 0:f.value;let w=(u=this.userProperties)==null?void 0:u.getByRef(Se.LETTER_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="wordSpacing"){((y=this.userProperties)==null?void 0:y.getByRef(Se.WORD_SPACING_REF)).decrement(),this.wordSpacing=(_=(m=this.userProperties)==null?void 0:m.getByRef(Se.WORD_SPACING_REF))==null?void 0:_.value;let w=(v=this.userProperties)==null?void 0:v.getByRef(Se.WORD_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="lineHeight"){((g=this.userProperties)==null?void 0:g.getByRef(Se.LINE_HEIGHT_REF)).decrement(),this.wordSpacing=(l=(h=this.userProperties)==null?void 0:h.getByRef(Se.LINE_HEIGHT_REF))==null?void 0:l.value;let w=(p=this.userProperties)==null?void 0:p.getByRef(Se.LINE_HEIGHT_REF);w&&await this.storeProperty(w)}await this.applyProperties(),this.settingsChangeCallback()}};At.appearanceValues=["readium-default-on","readium-sepia-on","readium-night-on"],At.fontFamilyValues=["Original","serif","sans-serif"],At.textAlignmentValues=["auto","justify","start"],At.columnCountValues=["auto","1","2"];var _l=At;L();L();L();L();L();L();L();L();var nw={stringify(r){let e=r.nSigBytes,t=r.words,n=[];for(let i=0;i<e;i++){let o=t[i>>>2]>>>24-i%4*8&255;n.push((o>>>4).toString(16)),n.push((o&15).toString(16))}return n.join("")},parse(r){let e=r.length;if(e%2!==0)throw new Error("Hex string count must be even");if(!/^[a-fA-F0-9]+$/.test(r))throw new Error(`Invalid Hex string: ${r}`);let t=[];for(let n=0;n<e;n+=2)t[n>>>3]|=parseInt(r.substr(n,2),16)<<24-n%8*4;return new In(t,e/2)}};L();L();var iw=typeof navigator<"u"&&navigator.userAgent?navigator.userAgent.toLowerCase():"",Os=(()=>{let r=parseInt((/msie (\d+)/.exec(iw)||[])[1],10);return isNaN(r)?(r=parseInt((/trident\/.*; rv:(\d+)/.exec(iw)||[])[1],10),isNaN(r)?!1:r):r})();function ow(r,e){return Os===!1?!1:e?r==="<"?Os<e:r==="<="?Os<=e:r===">"?Os>e:r===">="?Os>=e:Os===e:!0}function TB(){if(typeof window<"u"){let r=window.crypto||window.msCrypto;if(!r){if(ow("<",11))return console.warn("IE <= 10 uses insecure random generator. Please consider to use IE11 or another modern browser"),function(){return Math.floor(Math.random()*512)%256};throw new Error("Crypto module not found")}return function(){return r.getRandomValues(new Uint32Array(1))[0]}}else{if(typeof globalThis<"u"&&globalThis.crypto)return function(){return globalThis.crypto.randomBytes(4).readInt32LE()};if(typeof Eu=="function")return function(){return __non_webpack_require__("crypto").randomBytes(4).readInt32LE()}}throw new Error("Unable to find crypto module")}var sw=TB();var In=class r{constructor(e,t){if(Array.isArray(e)||!e){this._words=Array.isArray(e)?e:[],this._nSignificantBytes=typeof t=="number"?t:this._words.length*4;return}else if(e instanceof r){this._words=e.words.slice(),this._nSignificantBytes=e.nSigBytes;return}let n;try{e instanceof ArrayBuffer?n=new Uint8Array(e):(e instanceof Uint8Array||e instanceof Int8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array)&&(n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}catch{throw new Error("Invalid argument")}if(!n)throw new Error("Invalid argument");let i=n.byteLength,o=[];for(let s=0;s<i;s++)o[s>>>2]|=n[s]<<24-s%4*8;this._words=o,this._nSignificantBytes=i}get nSigBytes(){return this._nSignificantBytes}set nSigBytes(e){this._nSignificantBytes=e}get words(){return this._words}toString(e){return e?e.stringify(this):nw.stringify(this)}toUint8Array(){let e=this._words,t=this._nSignificantBytes,n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=e[i>>>2]>>>24-i%4*8&255;return n}concat(e){let t=e.words.slice(),n=e.nSigBytes;if(this.clamp(),this._nSignificantBytes%4)for(let i=0;i<n;i++){let o=t[i>>>2]>>>24-i%4*8&255;this._words[this._nSignificantBytes+i>>>2]|=o<<24-(this._nSignificantBytes+i)%4*8}else for(let i=0;i<n;i+=4)this._words[this._nSignificantBytes+i>>>2]=t[i>>>2];return this._nSignificantBytes+=n,this}clamp(){let e=this._nSignificantBytes;this._words[e>>>2]&=4294967295<<32-e%4*8,this._words.length=Math.ceil(e/4)}clone(){return new r(this._words.slice(),this._nSignificantBytes)}static random(e){let t=[];for(let n=0;n<e;n+=4)t.push(sw());return new r(t,e)}};L();L();var qg={stringify(r){let e=r.nSigBytes,t=r.words,n=[];for(let i=0;i<e;i++){let o=t[i>>>2]>>>24-i%4*8&255;n.push(String.fromCharCode(o))}return n.join("")},parse(r){let e=r.length,t=[];for(let n=0;n<e;n++)t[n>>>2]|=(r.charCodeAt(n)&255)<<24-n%4*8;return new In(t,e)}};var aw={stringify(r){try{return decodeURIComponent(escape(qg.stringify(r)))}catch{throw new Error("Malformed UTF-8 data")}},parse(r){return qg.parse(unescape(encodeURIComponent(r)))}};var Of=class{constructor(e){this._minBufferSize=0,this._blockSize=0,this._props=e,this._data=e&&typeof e.data<"u"?e.data.clone():new In,this._nBytes=e&&typeof e.nBytes=="number"?e.nBytes:0}get blockSize(){return this._blockSize}reset(e,t){this._data=typeof e<"u"?e.clone():new In,this._nBytes=typeof t=="number"?t:0}_append(e){let t=typeof e=="string"?aw.parse(e):e;this._data.concat(t),this._nBytes+=t.nSigBytes}_process(e){let t,n=this._data.words,i=this._data.nSigBytes,o=this._blockSize,s=this._blockSize*4,c=i/s;e?c=Math.ceil(c):c=Math.max((c|0)-this._minBufferSize,0);let f=c*o,u=Math.min(f*4,i);if(f){for(let y=0;y<f;y+=o)this._doProcessBlock(n,y);t=n.splice(0,f),this._data.nSigBytes-=u}return new In(t,u)}_doProcessBlock(e,t){throw new Error("Not implemented")}};var Mf=class extends Of{constructor(e){super(e),this._blockSize=512/32,this._props=e,e&&typeof e.blockSize=="number"&&(this._blockSize=e.blockSize),this.reset(e?e.data:void 0,e?e.nBytes:void 0)}get blockSize(){return this._blockSize}reset(e,t){super.reset.call(this,e,t),this._doReset()}update(e){return this._append(e),this._process(),this}finalize(e){return e&&this._append(e),this._doFinalize()}_doReset(){throw new Error("Not implemented")}_doFinalize(){throw new Error("Not implemented")}};var Gg=[],lw=[];function PB(r){let e=Math.sqrt(r);for(let t=2;t<=e;t++)if(!(r%t))return!1;return!0}function uw(r){return(r-(r|0))*4294967296|0}(function(){let e=2,t=0;for(;t<64;)PB(e)&&(t<8&&(Gg[t]=uw(Math.pow(e,1/2))),lw[t]=uw(Math.pow(e,1/3)),t++),e++})();var Ms=[],Fi=class r extends Mf{constructor(e){super(e),this._hash=new In(Gg.slice(0)),this._props=e,e&&typeof e.hash<"u"&&(this._hash=e.hash.clone())}_doReset(){this._hash=new In(Gg.slice(0))}_doProcessBlock(e,t){let n=this._hash.words,i=n[0],o=n[1],s=n[2],c=n[3],f=n[4],u=n[5],y=n[6],m=n[7];for(let _=0;_<64;_++){if(_<16)Ms[_]=e[t+_]|0;else{let A=Ms[_-15],C=(A<<25|A>>>7)^(A<<14|A>>>18)^A>>>3,b=Ms[_-2],E=(b<<15|b>>>17)^(b<<13|b>>>19)^b>>>10;Ms[_]=C+Ms[_-7]+E+Ms[_-16]}let v=f&u^~f&y,g=i&o^i&s^o&s,h=(i<<30|i>>>2)^(i<<19|i>>>13)^(i<<10|i>>>22),l=(f<<26|f>>>6)^(f<<21|f>>>11)^(f<<7|f>>>25),p=m+l+v+lw[_]+Ms[_],w=h+g;m=y,y=u,u=f,f=c+p|0,c=s,s=o,o=i,i=p+w|0}n[0]=n[0]+i|0,n[1]=n[1]+o|0,n[2]=n[2]+s|0,n[3]=n[3]+c|0,n[4]=n[4]+f|0,n[5]=n[5]+u|0,n[6]=n[6]+y|0,n[7]=n[7]+m|0}_doFinalize(){let e=this._data.words,t=this._nBytes*8,n=this._data.nSigBytes*8;return e[n>>>5]|=128<<24-n%32,e[(n+64>>>9<<4)+14]=Math.floor(t/4294967296),e[(n+64>>>9<<4)+15]=t,this._data.nSigBytes=e.length*4,this._process(),this._hash}clone(){let e={hash:this._hash,blockSize:this._blockSize,data:this._data,nBytes:this._nBytes};return new r(e)}static hash(e,t){return new r(t).finalize(e)}};var Al=rt(Vo());L();L();var Hr=rt($t());function Rf(r,e){let t=r.getClientRects();return Wg(t,e)}function Wg(r,e){let n=[];for(let f of r)n.push({bottom:f.bottom,height:f.height,left:f.left,right:f.right,top:f.top,width:f.width});let i=dw(n,1,e),o=IB(i,1),s=fw(o),c=2*2;for(let f=s.length-1;f>=0;f--){let u=s[f];if(!(u.width*u.height>c))if(s.length>1)Hr.default.log("CLIENT RECT: remove small"),s.splice(f,1);else{Hr.default.log("CLIENT RECT: remove small, but keep otherwise empty!");break}}return hw(s),Hr.default.log(`CLIENT RECT: reduced ${n.length} --> ${s.length}`),s}function Zn(r,e,t){return Math.abs(r-e)<=t}function OB(r,e){let t=Math.max(r.left,e.left),n=Math.min(r.right,e.right),i=Math.max(r.top,e.top),o=Math.min(r.bottom,e.bottom);return{bottom:o,height:Math.max(0,o-i),left:t,right:n,top:i,width:Math.max(0,n-t)}}function cw(r,e){let t=OB(e,r);if(t.height===0||t.width===0)return[r];let n=[];{let i={bottom:r.bottom,height:0,left:r.left,right:t.left,top:r.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}{let i={bottom:t.top,height:0,left:t.left,right:t.right,top:r.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}{let i={bottom:r.bottom,height:0,left:t.left,right:t.right,top:t.bottom,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}{let i={bottom:r.bottom,height:0,left:t.right,right:r.right,top:r.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&n.push(i)}return n}function kf(r,e,t,n){return(r.left<e||Zn(r.left,e,n))&&(r.right>e||Zn(r.right,e,n))&&(r.top<t||Zn(r.top,t,n))&&(r.bottom>t||Zn(r.bottom,t,n))}function MB(r,e,t){return kf(r,e.left,e.top,t)&&kf(r,e.right,e.top,t)&&kf(r,e.left,e.bottom,t)&&kf(r,e.right,e.bottom,t)}function kB(r,e){let t=Math.min(r.left,e.left),n=Math.max(r.right,e.right),i=Math.min(r.top,e.top),o=Math.max(r.bottom,e.bottom);return{bottom:o,height:o-i,left:t,right:n,top:i,width:n-t}}function zg(r,e,t){return(r.left<e.right||t>=0&&Zn(r.left,e.right,t))&&(e.left<r.right||t>=0&&Zn(e.left,r.right,t))&&(r.top<e.bottom||t>=0&&Zn(r.top,e.bottom,t))&&(e.top<r.bottom||t>=0&&Zn(e.top,r.bottom,t))}function dw(r,e,t){for(let n=0;n<r.length;n++)for(let i=n+1;i<r.length;i++){let o=r[n],s=r[i];if(o===s){Hr.default.log("mergeTouchingRects rect1 === rect2 ??!");continue}let c=Zn(o.top,s.top,e)&&Zn(o.bottom,s.bottom,e),f=Zn(o.left,s.left,e)&&Zn(o.right,s.right,e);if((f&&!t||c&&!f)&&zg(o,s,e)){Hr.default.log(`CLIENT RECT: merging two into one, VERTICAL: ${c} HORIZONTAL: ${f} (${t})`);let _=r.filter(g=>g!==o&&g!==s),v=kB(o,s);return _.push(v),dw(_,e,t)}}return r}function fw(r){for(let e=0;e<r.length;e++)for(let t=e+1;t<r.length;t++){let n=r[e],i=r[t];if(n===i){Hr.default.log("replaceOverlappingRects rect1 === rect2 ??!");continue}if(zg(n,i,-1)){let o=[],s,c,f=cw(n,i);if(f.length===1)o=f,s=n,c=i;else{let m=cw(i,n);f.length<m.length?(o=f,s=n,c=i):(o=m,s=i,c=n)}let u=[];u.push(c),Array.prototype.push.apply(u,o),hw(u),Hr.default.log(`CLIENT RECT: overlap, cut one rect into ${o.length}`);let y=r.filter(m=>m!==s);return Array.prototype.push.apply(y,o),fw(y)}}return r}function RB(r,e){return Math.max(0,Math.min(r.right,e.right)-Math.max(r.left,e.left))}function LB(r,e){return Math.max(0,Math.min(r.bottom,e.bottom)-Math.max(r.top,e.top))}function IB(r,e){let t=new Set(r);for(let n of r){if(!(n.width>1&&n.height>1)){Hr.default.log("CLIENT RECT: remove tiny"),t.delete(n);continue}for(let o of r)if(n!==o&&t.has(o)&&MB(o,n,e)){Hr.default.log("CLIENT RECT: remove contained"),t.delete(n);break}}return Array.from(t)}function hw(r){let e=[];for(let t of r)for(let n of r){if(t===n)continue;let i=e.indexOf(t)>=0,o=e.indexOf(n)>=0;if((!i||!o)&&zg(t,n,-1)){i||e.push(t),o||e.push(n),Hr.default.log("CLIENT RECT: overlap ---"),Hr.default.log(`#1 TOP:${t.top} BOTTOM:${t.bottom} LEFT:${t.left} RIGHT:${t.right} WIDTH:${t.width} HEIGHT:${t.height}`),Hr.default.log(`#2 TOP:${n.top} BOTTOM:${n.bottom} LEFT:${n.left} RIGHT:${n.right} WIDTH:${n.width} HEIGHT:${n.height}`);let s=RB(t,n);Hr.default.log(`xOverlap: ${s}`);let c=LB(t,n);Hr.default.log(`yOverlap: ${c}`)}}e.length&&Hr.default.log(`CLIENT RECT: overlaps ${e.length}`)}L();var Ft=rt($t());function Hi(r,e){let t=r?r.getSelection():null;if(!t)return;if(t.isCollapsed){Ft.default.log("^^^ SELECTION COLLAPSED.");return}let n=t.toString(),i=n.trim().replace(/\n/g," ").replace(/\s\s+/g," ");if(i.length===0){Ft.default.log("^^^ SELECTION TEXT EMPTY.");return}if(!t.anchorNode||!t.focusNode)return;let o=t.rangeCount===1?t.getRangeAt(0):mw(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset);if(!o||o.collapsed){Ft.default.log("$$$$$$$$$$$$$$$$$ CANNOT GET NON-COLLAPSED SELECTION RANGE?!");return}let s=BB(o);s.startContainer!==o.startContainer&&(Ft.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startContainer"),Ft.default.log(s.startContainer),Ft.default.log(o.startContainer)),s.startOffset!==o.startOffset&&(Ft.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startOffset"),Ft.default.log(`${s.startOffset} !== ${o.startOffset}`)),s.endContainer!==o.endContainer&&(Ft.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endContainer"),Ft.default.log(s.endContainer),Ft.default.log(o.endContainer)),s.endOffset!==o.endOffset&&(Ft.default.log(">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endOffset"),Ft.default.log(`${s.endOffset} !== ${o.endOffset}`));let c=go(s,e);if(!c){Ft.default.log("^^^ SELECTION RANGE INFO FAIL?!");return}return{rangeInfo:c,cleanText:i,rawText:n,range:s}}function mw(r,e,t,n){try{let i=new Range;if(i.setStart(r,e),i.setEnd(t,n),!i.collapsed)return Ft.default.log(">>> createOrderedRange RANGE OK"),i;Ft.default.log(">>> createOrderedRange COLLAPSED ... RANGE REVERSE?");let o=new Range;if(o.setStart(t,n),o.setEnd(r,e),!o.collapsed)return Ft.default.log(">>> createOrderedRange RANGE REVERSE OK."),i;Ft.default.log(">>> createOrderedRange RANGE REVERSE ALSO COLLAPSED?!");return}catch(i){console.warn(i.message);return}}function go(r,e){let t=r.startContainer.nodeType===Node.ELEMENT_NODE,n=t?r.startContainer:r.startContainer.parentNode&&r.startContainer.parentNode.nodeType===Node.ELEMENT_NODE?r.startContainer.parentNode:void 0;if(!n)return;let i=t?-1:Array.from(n.childNodes).indexOf(r.startContainer);if(i<-1)return;let o=e(n),s=r.endContainer.nodeType===Node.ELEMENT_NODE,c=s?r.endContainer:r.endContainer.parentNode&&r.endContainer.parentNode.nodeType===Node.ELEMENT_NODE?r.endContainer.parentNode:void 0;if(!c)return;let f=s?-1:Array.from(c.childNodes).indexOf(r.endContainer);if(f<-1)return;let u=e(c),y=NB(r.startContainer,r.endContainer);if(!y){Ft.default.log("^^^ NO RANGE COMMON ANCESTOR?!");return}if(r.commonAncestorContainer){let m=r.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?r.commonAncestorContainer:r.commonAncestorContainer.parentNode;m&&m.nodeType===Node.ELEMENT_NODE&&y!==m&&(Ft.default.log(">>>>>> COMMON ANCESTOR CONTAINER DIFF??!"),Ft.default.log(e(y)),Ft.default.log(e(m)))}if(u&&o)return{endContainerChildTextNodeIndex:f,endContainerElementCssSelector:u,endOffset:r.endOffset,startContainerChildTextNodeIndex:i,startContainerElementCssSelector:o,startOffset:r.startOffset}}function Lf(r,e){let t=r.querySelector(e.startContainerElementCssSelector);if(!t){Ft.default.log("^^^ convertRangeInfo NO START ELEMENT CSS SELECTOR?!");return}let n=t;if(e.startContainerChildTextNodeIndex>=0){if(e.startContainerChildTextNodeIndex>=t.childNodes.length){Ft.default.log("^^^ convertRangeInfo rangeInfo.startContainerChildTextNodeIndex >= startElement.childNodes.length?!");return}if(n=t.childNodes[e.startContainerChildTextNodeIndex],n.nodeType!==Node.TEXT_NODE){Ft.default.log("^^^ convertRangeInfo startContainer.nodeType !== Node.TEXT_NODE?!");return}}let i=r.querySelector(e.endContainerElementCssSelector);if(!i){Ft.default.log("^^^ convertRangeInfo NO END ELEMENT CSS SELECTOR?!");return}let o=i;if(e.endContainerChildTextNodeIndex>=0){if(e.endContainerChildTextNodeIndex>=i.childNodes.length){Ft.default.log("^^^ convertRangeInfo rangeInfo.endContainerChildTextNodeIndex >= endElement.childNodes.length?!");return}if(o=i.childNodes[e.endContainerChildTextNodeIndex],o.nodeType!==Node.TEXT_NODE){Ft.default.log("^^^ convertRangeInfo endContainer.nodeType !== Node.TEXT_NODE?!");return}}return mw(n,e.startOffset,o,e.endOffset)}function NB(r,e){if(r.nodeType===Node.ELEMENT_NODE&&r===e||r.nodeType===Node.ELEMENT_NODE&&r.contains(e))return r;if(e.nodeType===Node.ELEMENT_NODE&&e.contains(r))return e;let t=[],n=r.parentNode;for(;n&&n.nodeType===Node.ELEMENT_NODE;)t.push(n),n=n.parentNode;let i=[];for(n=e.parentNode;n&&n.nodeType===Node.ELEMENT_NODE;)i.push(n),n=n.parentNode;let o=t.find(s=>i.indexOf(s)>=0);return o||(o=i.find(s=>t.indexOf(s)>=0)),o}function BB(r){let e=r.cloneRange(),t=e.startContainer,n=e.startOffset,i=e.endContainer,o=e.endOffset;t.childNodes.length&&n>0&&(t=gw(t.childNodes[n-1]),n=t.length||0),o<i.childNodes.length&&(i=pw(i.childNodes[o]),o=0);let s=pw(t),c=gw(i);function f(u){if(u.childNodes.length)return!1;let y=u.length||0;return u===t&&n===y?!1:!(u===i&&o===0)}for(;s&&!f(s)&&s!==c;)s=DB(s);for(s===t?e.setStart(t,n):s!==null&&(s.nodeType===3?e.setStart(s,0):e.setStartBefore(s));c&&!f(c)&&c!==s;)c=FB(c);return c===i?e.setEnd(i,o):c!==null&&(c.nodeType===3?e.setEnd(c,c.length):e.setEndAfter(c)),e}function DB(r){if(r.firstChild)return r.firstChild;let e=r;for(;!e.nextSibling;)if(e=e.parentNode,!e)return null;return e.nextSibling}function FB(r){if(r.lastChild)return r.lastChild;let e=r;for(;!e.previousSibling;)if(e=e.parentNode,!e)return null;return e.previousSibling}function pw(r){for(;r.firstChild;)r=r.firstChild;return r}function gw(r){for(;r.lastChild;)r=r.lastChild;return r}L();var Xg=rt(bw());var mo,Qg;function Ar(r,e,t){if(r.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if(r.tagName.toLowerCase()==="html")return r.tagName.toLowerCase();let n={className:o=>!0,idName:o=>!0,optimizedMinLength:2,root:e.body,seedMinLength:1,tagName:o=>!0,threshold:1e3};mo={...n,...t},Qg=zB(mo.root,n);let i=$g(r,0,()=>$g(r,1,()=>$g(r,2)));if(i){let o=Aw(Cw(i,r));return o.length>0&&(i=o[0]),If(i)}else throw new Error("Selector was not found.")}function zB(r,e){return r.nodeType===Node.DOCUMENT_NODE?r:r===e.root?r.ownerDocument:r}function $g(r,e,t){let n=null,i=[],o=r,s=0;for(;o&&o!==mo.root.parentElement;){let c=Yg(VB(o))||Yg(...$B(o))||Yg(JB(o))||[KB()],f=YB(o);if(e===0)f&&(c=c.concat(c.filter(Kg).map(u=>Jg(u,f))));else if(e===1)c=c.slice(0,1),f&&(c=c.concat(c.filter(Kg).map(u=>Jg(u,f))));else if(e===2){let[u]=c=c.slice(0,1);f&&Kg(u)&&(c=[Jg(u,f)])}for(let u of c)u.level=s;if(i.push(c),i.length>=mo.seedMinLength&&(n=vw(i,t),n))break;o=o.parentElement,s++}return n||(n=vw(i,t)),n}function vw(r,e){let t=Aw(Sw(r));if(t.length>mo.threshold)return e?e():null;for(let n of t)if(ww(n))return n;return null}function If(r){let e=r[0],t=e.name;for(let n=1;n<r.length;n++){let i=r[n].level||0;e.level===i-1?t=`${r[n].name} > ${t}`:t=`${r[n].name} ${t}`,e=r[n]}return t}function _w(r){return r.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function ww(r){switch(Qg.querySelectorAll(If(r)).length){case 0:throw new Error(`Can't select any node with this selector: ${If(r)}`);case 1:return!0;default:return!1}}function VB(r){let e=r.getAttribute("id");return e&&mo.idName(e)?{name:"#"+(0,Xg.default)(e,{isIdentifier:!0}),penalty:0}:null}function $B(r){return Array.from(r.classList).filter(mo.className).map(t=>({name:"."+(0,Xg.default)(t,{isIdentifier:!0}),penalty:1}))}function JB(r){let e=r.tagName.toLowerCase();return mo.tagName(e)?{name:e,penalty:2}:null}function KB(){return{name:"*",penalty:3}}function YB(r){let e=r.parentNode;if(!e)return null;let t=e.firstChild;if(!t)return null;let n=0;for(;t&&(t.nodeType===Node.ELEMENT_NODE&&n++,t!==r);)t=t.nextSibling;return n}function Jg(r,e){return{name:r.name+`:nth-child(${e})`,penalty:r.penalty+1}}function Kg(r){return r.name!=="html"&&!r.name.startsWith("#")}function Yg(...r){let e=r.filter(XB);return e.length>0?e:null}function XB(r){return r!=null}function*Sw(r,e=[]){if(r.length>0)for(let t of r[0])yield*Sw(r.slice(1,r.length),e.concat(t));else yield e}function Aw(r){return Array.from(r).sort((e,t)=>_w(e)-_w(t))}function*Cw(r,e){if(r.length>2&&r.length>mo.optimizedMinLength)for(let t=1;t<r.length-1;t++){let n=[...r];n.splice(t,1),ww(n)&&QB(n,e)&&(yield n,yield*Cw(n,e))}}function QB(r,e){return Qg.querySelector(If(r))===e}L();L();var Ew="0 0 24 24",dn=(r,e,t,n="icon")=>`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="${Ew}" preserveAspectRatio="xMidYMid meet" role="img" class="${n}" aria-labelledBy="${r}">
|
|
74
74
|
<title id="${r}">${e}</title>
|
|
75
75
|
${t}
|
|
76
76
|
</svg>`,ZB=(r,e,t,n,i="icon")=>`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="${n}" preserveAspectRatio="xMidYMid meet" role="img" class="${i}" aria-labelledBy="${r}">
|
|
@@ -79,7 +79,7 @@ function print() { __p += __j.call(arguments, '') }
|
|
|
79
79
|
</svg>`,Na=(r,e,t,n="icon",i,o)=>`<svg xmlns="http://www.w3.org/2000/svg" width="${i}" height="${i}" viewBox="${Ew}" style="fill:${o}" preserveAspectRatio="xMidYMid meet" role="img" class="${n}" aria-labelledBy="${r}">
|
|
80
80
|
<title id="${r}">${e}</title>
|
|
81
81
|
${t}
|
|
82
|
-
</svg>`,pi={error:dn("error-icon","Warning",'<path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>'),home:'<path d="M12 5.69l5 4.5V18h-2v-6H9v6H7v-7.81l5-4.5M12 3L2 12h3v8h6v-6h2v6h6v-8h3L12 3z"/>',expand:dn("expand-icon","Enter fullscreen",'<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>',"icon active-icon"),loading:ZB("loading-icon","Loading",'<path fill="#BBBBBB" d="M145,241.6c-53.3,0-96.6-43.2-96.6-96.6c0-53.3,43.2-96.6,96.6-96.6c53.3,0,96.6,43.2,96.6,96.6 c0,26.7-10.8,50.9-28.3,68.3l7.6,7.6c19.4-19.4,31.5-46.3,31.5-75.9c0-59.3-48-107.3-107.3-107.3S37.7,85.7,37.7,145 c0,59.3,48,107.3,107.3,107.3V241.6z"/>',"0 0 290 290"),next:dn("next-icon","Next Chapter",'<path d="M6.49 20.13l1.77 1.77 9.9-9.9-9.9-9.9-1.77 1.77L14.62 12l-8.13 8.13z"/>'),previous:dn("previous-icon","Previous Chapter",'<path d="M17.51 3.87L15.73 2.1 5.84 12l9.9 9.9 1.77-1.77L9.38 12l8.13-8.13z"/>'),settings:dn("settings-icon","Settings",'<path d="M19.43 12.98c.04-.32.07-.64.07-.98 0-.34-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.09-.16-.26-.25-.44-.25-.06 0-.12.01-.17.03l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.06-.02-.12-.03-.18-.03-.17 0-.34.09-.43.25l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98 0 .33.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.09.16.26.25.44.25.06 0 .12-.01.17-.03l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.06.02.12.03.18.03.17 0 .34-.09.43-.25l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zm-1.98-1.71c.04.31.05.52.05.73 0 .21-.02.43-.05.73l-.14 1.13.89.7 1.08.84-.7 1.21-1.27-.51-1.04-.42-.9.68c-.43.32-.84.56-1.25.73l-1.06.43-.16 1.13-.2 1.35h-1.4l-.19-1.35-.16-1.13-1.06-.43c-.43-.18-.83-.41-1.23-.71l-.91-.7-1.06.43-1.27.51-.7-1.21 1.08-.84.89-.7-.14-1.13c-.03-.31-.05-.54-.05-.74s.02-.43.05-.73l.14-1.13-.89-.7-1.08-.84.7-1.21 1.27.51 1.04.42.9-.68c.43-.32.84-.56 1.25-.73l1.06-.43.16-1.13.2-1.35h1.39l.19 1.35.16 1.13 1.06.43c.43.18.83.41 1.23.71l.91.7 1.06-.43 1.27-.51.7 1.21-1.07.85-.89.7.14 1.13zM12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>',"icon open"),toc:dn("toc-icon","Table of Contents",'<path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/>',"icon open"),bookmarks:dn("toc-icon","Bookmarks",'<path d="M4,6H2v16h16v-2H4V6z"/><path d="M22,2H6v16h16V2z M20,12l-2.5-1.5L15,12V4h5V12z"/>',"icon open"),bookmark:dn("toc-icon","Bookmark",'<path d="M19,3H5v18l7-3l7,3V3z"/>',"icon open"),delete:dn("delete-icon","Delete",'<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>',"icon open"),close:dn("close-icon","Close",'<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>',"icon open"),text:dn("text-icon","Text",'<path d="M5 4v3h5.5v12h3V7H19V4z"/>',"icon open"),speak:dn("speak-icon","Speak",'<circle cx="9" cy="9" r="4"/><path d="M9 15c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4zm7.76-9.64l-1.68 1.69c.84 1.18.84 2.71 0 3.89l1.68 1.69c2.02-2.02 2.02-5.07 0-7.27zM20.07 2l-1.63 1.63c2.77 3.02 2.77 7.56 0 10.74L20.07 16c3.9-3.89 3.91-9.95 0-14z"/><path d="M0 0h24v24H0z" fill="none"/>',"icon open"),note:dn("note-icon","Note",'<polygon points="17.71 24.66 22.3 20.07 17.71 20.07 17.71 24.66" fill="none"/><path d="M22.42.07H5.58A3.28,3.28,0,0,0,2.29,3.35V24.79a3.28,3.28,0,0,0,3.29,3.28H16.71a1,1,0,0,0,.71-.29l8-8a1,1,0,0,0,.29-.71V3.35A3.28,3.28,0,0,0,22.42.07Zm-8.17,15h-7v-2h7Zm-7-6v-2h13v2ZM16.5,25.86v-6a1,1,0,0,1,1-1h6Z" />',"icon open"),highlight:dn("highlight-icon","Highlight",'<path d="M27.71,7.78,21.12,1.19a1,1,0,0,0-1.38,0L4.32,15A1,1,0,0,0,4,15.7a1,1,0,0,0,.3.73c1.22,1.22,1.2,2.37,0,3.62a1,1,0,0,0,0,1.41l3.2,3.2a1,1,0,0,0,1.41,0c1.28-1.28,2.36-1.29,3.62,0a1,1,0,0,0,1.45,0L27.74,9.16A1,1,0,0,0,27.71,7.78Z" /><path d="M3.09,22.59l-2.8,2.8a1,1,0,0,0-.21,1.09A1,1,0,0,0,1,27.1H4.6a1,1,0,0,0,.71-.29l1-1Z" />',"icon open")};var t1=rt(Nf());var Yr=rt($t()),ks=(f=>(f.R2_ID_HIGHLIGHTS_CONTAINER="R2_ID_HIGHLIGHTS_CONTAINER",f.R2_ID_BOOKMAKRS_CONTAINER="R2_ID_BOOKMAKRS_CONTAINER",f.R2_ID_READALOUD_CONTAINER="R2_ID_READALOUD_CONTAINER",f.R2_ID_PAGEBREAK_CONTAINER="R2_ID_PAGEBREAK_CONTAINER",f.R2_ID_SEARCH_CONTAINER="R2_ID_SEARCH_CONTAINER",f.R2_ID_DEFINITIONS_CONTAINER="R2_ID_DEFINITIONS_CONTAINER",f.R2_ID_LINEFOCUS_CONTAINER="R2_ID_LINEFOCUS_CONTAINER",f.R2_ID_GUTTER_RIGHT_CONTAINER="R2_ID_GUTTER_RIGHT_CONTAINER",f))(ks||{}),Tw="R2_CLASS_HIGHLIGHT_CONTAINER",Cl="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",Ur="R2_CLASS_HIGHLIGHT_AREA",Sl="R2_CLASS_HIGHLIGHT_ICON",Ui=.5,xw=.75,Rs={blue:100,green:50,red:230},er=[],tD="data-highlighted",rD="data-timestamp",Da={ELEMENT_NODE:1,TEXT_NODE:3};var Nn=["R2_ID_HIGHLIGHTS_CONTAINER","R2_ID_PAGEBREAK_CONTAINER","R2_ID_SEARCH_CONTAINER","R2_ID_READALOUD_CONTAINER","R2_ID_BOOKMAKRS_CONTAINER","R2_ID_DEFINITIONS_CONTAINER","R2_ID_LINEFOCUS_CONTAINER","R2_ID_GUTTER_RIGHT_CONTAINER",Tw,Ur,Cl],Zg=-1,e1=-1,Jt=class r{constructor(e,t,n,i,o){this.lastSelectedHighlight=void 0;this.activeAnnotationMarkerId=void 0;this.showTool=(0,Al.default)(e=>{this.isAndroid()||this.snapSelectionToWord(e),this.toolboxShow()},navigator.userAgent.toLowerCase().indexOf("firefox")>-1?200:100);this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,Al.default)(()=>{var e,t;this.isSelectionMenuOpen||(this.isSelectionMenuOpen=!0,(e=this.api)!=null&&e.selectionMenuOpen&&((t=this.api)==null||t.selectionMenuOpen()),this.navigator.emit("toolbox.opened","opened"))},100);this.selectionMenuClosed=(0,Al.default)(()=>{var e,t;this.isSelectionMenuOpen&&(this.isSelectionMenuOpen=!1,(e=this.api)!=null&&e.selectionMenuClose&&((t=this.api)==null||t.selectionMenuClose()),this.navigator.emit("toolbox.closed","closed"))},100);this.selection=(0,Al.default)((e,t)=>{var n,i;(n=this.api)!=null&&n.selection&&((i=this.api)==null||i.selection(e,t))},100);this.getScrollingElement=e=>e!=null&&e.scrollingElement?e==null?void 0:e.scrollingElement:e!=null&&e.body?e==null?void 0:e.body:document.createElement("body");this.layerSettings=e,this.properties=t,this.properties.menuPosition===void 0&&(this.properties.menuPosition="inline"),this.api=o,this.hasEventListener=n,this.options=this.defaults(i,{color:"#fce300",highlightedClass:"highlighted",contextClass:"highlighter-context",onBeforeHighlight:function(){return!0},onAfterHighlight:function(){}})}static async create(e){let t=new this(e.layerSettings,e,!1,{},e.api);return new Promise(n=>n(t))}async initialize(){var i;let e=this.navigator.iframes[0].contentDocument;e&&this.dom(e.body).addClass(this.options.contextClass),this.bindEvents((i=this.navigator.iframes[0].contentDocument)==null?void 0:i.body,this,this.hasEventListener),this.initializeToolbox(),Zg=-1,e1=-1;let t=this;async function n(){t.lastSelectedHighlight===void 0||(t.lastSelectedHighlight=void 0)}setTimeout(async()=>{var s;let o=this.navigator.iframes[0].contentDocument;o&&await((s=o.body)==null?void 0:s.addEventListener("click",n))},100)}haveSameColor(e,t){return this.dom(e).color()===this.dom(t).color()}defaults(e,t){e=e||{};for(let n in t)t.hasOwnProperty(n)&&e[n]===void 0&&(e[n]=t[n]);return e}unique(e){return e.filter(function(t,n,i){return i.indexOf(t)===n})}refineRangeBoundaries(e){let t=e.startContainer,n=e.endContainer,i=e.commonAncestorContainer,o=!0;if(e.endOffset===0){for(;!n.previousSibling&&n.parentNode!==i;)n=n.parentNode;n=n.previousSibling}else n.nodeType===Da.TEXT_NODE?e.endOffset<n.nodeValue.length&&n.splitText(e.endOffset):e.endOffset>0&&(n=n.childNodes.item(e.endOffset-1));return t.nodeType===Da.TEXT_NODE?e.startOffset===t.nodeValue.length?o=!1:e.startOffset>0&&(t=t.splitText(e.startOffset),n===t.previousSibling&&(n=t)):e.startOffset<t.childNodes.length?t=t.childNodes.item(e.startOffset):t=t.nextSibling,{startContainer:t,endContainer:n,goDeeper:o}}sortByDepth(e,t){let n=this;e.sort(function(i,o){return n.dom(t?o:i).parents().length-n.dom(t?i:o).parents().length})}groupHighlights(e){let t=[],n={},i=[];return e.forEach(function(o){let s=o.getAttribute(rD);typeof n[s]>"u"&&(n[s]=[],t.push(s)),n[s].push(o)}),t.forEach(function(o){let s=n[o];i.push({chunks:s,timestamp:o,toString:function(){return s.map(function(c){return c.textContent}).join("")}})}),i}dom(e){let t=this;return{addClass:function(n){e.classList?e.classList.add(n):e.className+=" "+n},removeClass:function(n){e.classList?e.classList.remove(n):e.className=e.className.replace(new RegExp("(^|\\b)"+n+"(\\b|$)","gi")," ")},prepend:function(n){let i=Array.prototype.slice.call(n),o=i.length;for(;o--;)e.insertBefore(i[o],e.firstChild)},append:function(n){let i=Array.prototype.slice.call(n);for(let o=0,s=i.length;o<s;++o)e.appendChild(i[o])},insertAfter:function(n){var i;return(i=n.parentNode)==null?void 0:i.insertBefore(e,n.nextSibling)},insertBefore:function(n){var i;return(i=n.parentNode)==null?void 0:i.insertBefore(e,n)},remove:function(){e.parentNode.removeChild(e),e=null},contains:function(n){return e!==n&&e.contains(n)},wrap:function(n){return e.parentNode&&e.parentNode.insertBefore(n,e),n.appendChild(e),n},unwrap:function(){let n=Array.prototype.slice.call(e.childNodes),i;return n.forEach(function(o){i=o.parentNode,t.dom(o).insertBefore(o.parentNode),t.dom(i).remove()}),n},parents:function(){let n,i=[];for(;n=e.parentNode;)i.push(n),e=n;return i},normalizeTextNodes:function(){if(e){if(e.nodeType===Da.TEXT_NODE)for(;e.nextSibling&&e.nextSibling.nodeType===Da.TEXT_NODE;)e.nodeValue+=e.nextSibling.nodeValue,e.parentNode.removeChild(e.nextSibling);else t.dom(e.firstChild).normalizeTextNodes();t.dom(e.nextSibling).normalizeTextNodes()}},color:function(){return e.style.backgroundColor},fromHTML:function(n){let i=document.createElement("div");return i.innerHTML=n,i.childNodes},getRange:function(){var o;let n=(o=t.dom(e))==null?void 0:o.getSelection(),i;return(n==null?void 0:n.rangeCount)>0&&(i=n==null?void 0:n.getRangeAt(0)),i},removeAllRanges:function(){var i;let n=(i=t.dom(e))==null?void 0:i.getSelection();n==null||n.removeAllRanges(),t.toolboxHide()},getSelection:function(){var n;return(n=t.dom(e).getWindow())==null?void 0:n.getSelection()},getWindow:function(){var n;return(n=t.dom(e).getDocument())==null?void 0:n.defaultView},getDocument:function(){return(e==null?void 0:e.ownerDocument)||e}}}disableContext(e){return e.preventDefault(),e.stopPropagation(),!1}bindEvents(e,t,n){let i=e.ownerDocument;e.addEventListener("mouseup",this.toolboxShowDelayed.bind(this)),e.addEventListener("touchend",this.toolboxShowDelayed.bind(this)),i.addEventListener("mouseup",this.toolboxShowDelayed.bind(this)),i.addEventListener("touchend",this.toolboxShowDelayed.bind(this)),n||window.addEventListener("resize",this.toolboxPlacement.bind(this)),i.addEventListener("selectionchange",this.toolboxPlacement.bind(this)),this.isIOS()||i.addEventListener("selectionchange",this.toolboxShowDelayed.bind(this)),e.addEventListener("mousedown",this.toolboxHide.bind(this)),e.addEventListener("touchstart",this.toolboxHide.bind(this)),this.isAndroid()&&e.addEventListener("contextmenu",this.disableContext),e.addEventListener("mousedown",this.mousedown.bind(this)),e.addEventListener("mouseup",this.mouseup.bind(this)),e.addEventListener("touchstart",this.mousedown.bind(this)),e.addEventListener("touchend",this.mouseup.bind(this)),this.hasEventListener=!0}async mousedown(e){var t;if(Zg=e.clientX,e1=e.clientY,(t=this.properties)!=null&&t.preventScrollOnSelection){let n=ft(document,"#iframe-wrapper");n.style.overflow="hidden"}}async mouseup(e){Math.abs(Zg-e.clientX)<3&&Math.abs(e1-e.clientY)<3&&await this.processMouseEvent(e)}async mousemove(e){await this.processMouseEvent(e)}unbindEvents(e,t){let n=e.ownerDocument;e.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),e.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),n.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),n.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),window.removeEventListener("resize",this.toolboxPlacement.bind(this)),n.removeEventListener("selectionchange",this.toolboxPlacement.bind(this)),e.removeEventListener("mousedown",this.toolboxHide.bind(this)),e.removeEventListener("touchstart",this.toolboxHide.bind(this)),this.isAndroid()&&e.removeEventListener("contextmenu",this.disableContext),e.removeEventListener("mousedown",this.mousedown.bind(this)),e.removeEventListener("mouseup",this.mouseup.bind(this)),e.removeEventListener("mousemove",this.mousemove.bind(this)),e.removeEventListener("touchstart",this.mousedown.bind(this)),e.removeEventListener("touchend",this.mouseup.bind(this)),e.removeEventListener("touchmove",this.mousemove.bind(this)),this.hasEventListener=!1}destroy(){this.toolboxHide();let e=this.navigator.iframes[0].contentDocument;e&&(this.unbindEvents(e.body,this),this.dom(e.body).removeClass(this.options.contextClass))}initializeToolbox(){let e=document.getElementById("highlight-toolbox-mode-colors"),t=document.getElementById("highlight-toolbox-mode-add"),n=["#fce300","#48e200","#00bae5","#157cf9","#6a39b7","#ea426a","#ff8500"],i=document.getElementById("colorIcon"),o=document.getElementById("actionIcon"),s=document.getElementById("dismissIcon"),c=document.getElementById("collapseIcon"),f=document.getElementById("highlightIcon"),u=this;if(s&&(s.innerHTML=pi.close,s.addEventListener("click",function(){u.toolboxMode("add")})),c&&(c.innerHTML=pi.close,c.addEventListener("click",function(){u.toolboxMode("add")})),i){i.style.position="relative",i.style.zIndex="20",n.forEach(_=>{let v=document.getElementById(_),g=document.getElementById(`c${_}`);v&&(e!=null&&e.contains(v))&&e.removeChild(v),t&&g&&t.contains(g)&&t.removeChild(g)});let y=[],m=[];if(i.addEventListener("click",function(){u.toolboxMode("colors")}),this.navigator.rights.enableAnnotations){let _=10;n.forEach(v=>{_--;let g=i==null?void 0:i.cloneNode(!0),h=g.lastChild,l=r.hexToRgbChannels(v);h.style.backgroundColor="rgba("+[l.red,l.green,l.blue].join(",")+",.5)",g.id=`c${v}`,g.style.display="unset",g.style.position="relative",g.style.zIndex=`${_}`,g.style.marginLeft="-30px",m.push(g),t==null||t.insertBefore(g,f)})}n.forEach(_=>{let v=i==null?void 0:i.cloneNode(!0),g=v.lastChild;g.style.backgroundColor=_,v.id=_,v.style.position="relative",v.style.display="unset",y.push(v),i&&v.addEventListener("click",function(){var A,C,b;u.setColor(_);let h=i==null?void 0:i.lastChild;h&&(h.style.backgroundColor=_);let l=document.getElementById("highlightIcon"),p=document.getElementById("underlineIcon"),w=document.getElementById("noteIcon");(((A=l==null?void 0:l.getElementsByTagName)==null?void 0:A.call(l,"span").length)??0)>0&&((l==null?void 0:l.getElementsByTagName("span")[0]).style.background=u.getColor()),(((C=p==null?void 0:p.getElementsByTagName)==null?void 0:C.call(p,"span").length)??0)>0&&((p==null?void 0:p.getElementsByTagName("span")[0]).style.borderBottomColor=u.getColor()),(((b=w==null?void 0:w.getElementsByTagName)==null?void 0:b.call(w,"span").length)??0)>0&&((w==null?void 0:w.getElementsByTagName("span")[0]).style.borderBottomColor=u.getColor()),u.toolboxMode("add")}),e==null||e.insertBefore(v,s)})}o&&o.addEventListener("click",function(){u.toolboxMode("action")}),u.toolboxMode("add")}toolboxMode(e){let t=document.getElementById("highlight-toolbox-mode-colors"),n=document.getElementById("highlight-toolbox-mode-add"),i=document.getElementById("highlight-toolbox-mode-edit"),o=document.getElementById("highlight-toolbox-mode-action");switch(e){case"colors":t&&(t.style.display="unset"),n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none");break;case"edit":t&&(t.style.display="none"),n&&(n.style.display="none"),i&&(i.style.display="unset"),o&&(o.style.display="none");break;case"action":t&&(t.style.display="none"),n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="unset");break;default:t&&(t.style.display="none"),n&&(n.style.display="unset"),i&&(i.style.display="none"),o&&(o.style.display="none");break}}toolboxHide(){var t;let e=document.getElementById("highlight-toolbox");if(e&&(e.style.display="none"),this.selectionMenuClosed(),(t=this.properties)!=null&&t.preventScrollOnSelection){let n=ft(document,"#iframe-wrapper");n.style.overflow="auto"}}toolboxShowDelayed(e){this.showTool(e.detail===1)}snapSelectionToWord(e=!1){var o;let t=this,n=this.navigator.iframes[0].contentDocument;if(n){let s=(o=t.dom(n.body))==null?void 0:o.getSelection();if(t.dom(n.body)&&s&&!(s!=null&&s.isCollapsed)){let y=function(p){let w=p.match(new RegExp("[^a-zA-Z0-9]+$"));return!w||!w.index?p:p.slice(0,w.index)},c=s.toString(),f=c.length-c.trimStart().length,u=c.length-c.trimEnd().length,m=c.length;var i=/[-!$%^&*()_+|~=`{}[\]:/;<>?,.@#]/;c=c.replace(i,""),f=m-c.trimStart().length,c=y(c),u=m-c.trimEnd().length;let _=document.createRange();e?(_.setStart(s.anchorNode,s.anchorOffset+f),_.setEnd(s.focusNode,s.focusOffset-u)):(_.setStart(s.anchorNode,s.anchorOffset),_.setEnd(s.focusNode,s.focusOffset));let v=_.collapsed;_.detach();let g=s.focusNode,h;e?(h=s.focusOffset-u,s.collapse(s.anchorNode,s.anchorOffset+f)):(h=s.focusOffset,s.collapse(s.anchorNode,s.anchorOffset));let l=["forward","backward"];v&&(l=["backward","forward"]),e?(s.modify("move",l[0],"character"),s.modify("move",l[1],"word"),s.extend(g,h),s.modify("extend",l[1],"character"),s.modify("extend",l[0],"word")):s.extend(g,h),this.selection(s.toString(),s)}return s}}toolboxShow(){var e;if(this.activeAnnotationMarkerId===void 0){let t=this,n=document.getElementById("highlight-toolbox-mode-add"),i=this.dom((e=this.navigator.iframes[0].contentDocument)==null?void 0:e.body).getRange();if((!i||i.collapsed)&&n){getComputedStyle(n).display!=="none"&&t.toolboxHide();return}this.isIOS()&&setTimeout(function(){let o=t.navigator.iframes[0].contentDocument;if(o){let s=t.dom(o.body).getSelection();s.removeAllRanges(),setTimeout(function(){var y,m;s.addRange(i);function c(_){let v={className:h=>Nn.indexOf(h)<0,idName:h=>Nn.indexOf(h)<0},g=t.navigator.iframes[0].contentDocument;if(g)return Ar(_,g,v)}let f=t.navigator.iframes[0].contentWindow,u=Hi(f,c);(m=(y=t.navigator.annotationModule)==null?void 0:y.annotator)==null||m.saveTemporarySelectionInfo(u)},5)}},100),this.toolboxPlacement(),this.toolboxHandler()}}toolboxPlacement(){var i,o,s,c,f;let e=this.dom((i=this.navigator.iframes[0].contentDocument)==null?void 0:i.body).getRange();if(!e||e.collapsed)return;let t=e.getBoundingClientRect(),n=document.getElementById("highlight-toolbox");n&&(((o=this.properties)==null?void 0:o.menuPosition)==="top"?(n.style.left="0px",n.style.transform="revert",n.style.width="100%",n.style.textAlign="center",n.style.position="absolute",n.style.setProperty("--content","revert")):((s=this.properties)==null?void 0:s.menuPosition)==="bottom"?(n.style.bottom="0px",n.style.left="0px",n.style.transform="revert",n.style.width="100%",n.style.textAlign="center",n.style.position="absolute",n.style.setProperty("--content","revert")):(((c=this.navigator.view)==null?void 0:c.isPaginated())?n.style.top=t.top+(((f=this.navigator.attributes)==null?void 0:f.navHeight)??0)+"px":n.style.top=t.top+"px",n.style.left=(t.right-t.left)/2+t.left+"px"))}toolboxHandler(){var t,n,i,o,s,c,f;let e=document.getElementById("highlight-toolbox");if(e&&getComputedStyle(e).display==="none"){e.style.display="block",((t=this.navigator.view)==null?void 0:t.isPaginated())?e.style.position="absolute":e.style.position="relative",this.selectionMenuOpened();let y=this;y.toolboxMode("add");let m=document.getElementById("highlightIcon"),_=document.getElementById("collapseIcon"),v=document.getElementById("underlineIcon"),g=document.getElementById("noteIcon"),h=document.getElementById("colorIcon"),l=document.getElementById("speakIcon");if(this.navigator.rights.enableAnnotations){if(m&&(m.style.display="unset",h&&m.getElementsByTagName("span").length>0&&(m.getElementsByTagName("span")[0].style.background=this.getColor())),v&&(v.style.display="unset",h&&v.getElementsByTagName("span").length>0&&(v.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),g&&(g.style.display="unset",h&&g.getElementsByTagName("span").length>0&&(g.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),h){h.style.display="unset";let p=h.lastChild;p.style.backgroundColor=this.getColor()}if(m){let p=function(){y.doHighlight(!1,0),y.toolboxHide(),m==null||m.removeEventListener("click",p)},w=m.cloneNode(!0);(n=m==null?void 0:m.parentNode)==null||n.replaceChild(w,m),m=document.getElementById("highlightIcon"),m==null||m.addEventListener("click",p)}if(v){let p=function(){y.doHighlight(!1,1),y.toolboxHide(),v==null||v.removeEventListener("click",p)},w=v.cloneNode(!0);(i=v==null?void 0:v.parentNode)==null||i.replaceChild(w,v),v=document.getElementById("underlineIcon"),v==null||v.addEventListener("click",p)}if(g){let p=function(){y.doHighlight(!1,4),y.toolboxHide(),g==null||g.removeEventListener("click",p)},w=g.cloneNode(!0);(o=g==null?void 0:g.parentNode)==null||o.replaceChild(w,g),g=document.getElementById("noteIcon"),g==null||g.addEventListener("click",p)}}else m&&m.style.setProperty("display","none"),v&&v.style.setProperty("display","none"),g&&g.style.setProperty("display","none"),h&&h.style.setProperty("display","none"),_&&_.style.setProperty("display","none");if(this.navigator.rights.enableTTS){if(l){let p=function(){l==null||l.removeEventListener("click",p),y.speak()},w=l.cloneNode(!0);(s=l==null?void 0:l.parentNode)==null||s.replaceChild(w,l),l=document.getElementById("speakIcon"),l==null||l.addEventListener("click",p)}}else l&&l.style.setProperty("display","none");(((c=this.properties)==null?void 0:c.selectionMenuItems)??[])&&(((f=this.properties)==null?void 0:f.selectionMenuItems)??[]).forEach(p=>{var b;p.icon&&(p.icon.id=p.id);let w=document.getElementById(p.id),A=this;function C(){var P,N,D,F,B,V,q;w==null||w.removeEventListener("click",C);function E(G){let Y={className:Q=>Nn.indexOf(Q)<0,idName:Q=>Nn.indexOf(Q)<0},X=A.navigator.iframes[0].contentDocument;if(X)return Ar(G,X,Y)}let k=A.navigator.iframes[0].contentWindow;if(k){let G=Hi(k,E);if(G===void 0){let Y=A.navigator.iframes[0].contentDocument;G=(N=(P=A.navigator.annotationModule)==null?void 0:P.annotator)==null?void 0:N.getTemporarySelectionInfo(Y)}if(G!==void 0)if(p.callback)p.callback(G.cleanText,(D=G.range)==null?void 0:D.startContainer.parentElement);else{let Y=(F=p.highlight)==null?void 0:F.style,X=p.marker?p.marker:3;if(X===3&&A.navigator.rights.enableAnnotations||X===2&&A.navigator.rights.enableBookmarks){let Q=A.navigator.iframes[0].contentDocument;if(Q){let le=A.createHighlight(A.dom(Q.body).getWindow(),G,(B=p.highlight)==null?void 0:B.color,!0,X,p.icon,p.popup,Y);A.options.onAfterHighlight(le,X),A.navigator.rights.enableAnnotations?(V=A.navigator.annotationModule)==null||V.saveAnnotation(le[0]).then(ve=>{var ce,W;p!=null&&p.note&&ve.highlight&&((W=(ce=A.navigator.annotationModule)==null?void 0:ce.api)==null||W.addCommentToAnnotation(ve).then(H=>{var R;(R=A.navigator.annotationModule)==null||R.updateAnnotation(H).then(async()=>{Yr.default.log("update highlight "+H.id)})}))}):A.navigator.rights.enableBookmarks&&((q=A.navigator.bookmarkModule)==null||q.saveAnnotation(le[0]))}}}}A.callbackComplete()}if(w){let E=w.cloneNode(!0);(b=w==null?void 0:w.parentNode)==null||b.replaceChild(E,w),w=document.getElementById(p.id),w==null||w.addEventListener("click",C)}})}}doHighlight(e,t){var s,c,f,u,y,m;let n=this;function i(_){let v={className:h=>Nn.indexOf(h)<0,idName:h=>Nn.indexOf(h)<0},g=n.navigator.iframes[0].contentDocument;if(g)return Ar(_,g,v)}let o=n.navigator.iframes[0].contentWindow;if(o){let _=Hi(o,i);if(_===void 0){let v=n.navigator.iframes[0].contentDocument;_=(c=(s=this.navigator.annotationModule)==null?void 0:s.annotator)==null?void 0:c.getTemporarySelectionInfo(v)}if(_){if(this.options.onBeforeHighlight(_)===!0){let v;v=this.getColor(),r.isHexColor(v)&&(v=r.hexToRgbChannels(v));let g=n.navigator.iframes[0].contentDocument;if(g){let h=this.createHighlight(n.dom(g.body).getWindow(),_,v,!0,t??0);this.options.onAfterHighlight(h,t),this.navigator.rights.enableAnnotations&&t!==2?(f=this.navigator.annotationModule)==null||f.saveAnnotation(h[0]):this.navigator.rights.enableBookmarks&&t===2&&((u=this.navigator.bookmarkModule)==null||u.saveAnnotation(h[0]))}}e||this.dom((y=this.navigator.iframes[0].contentDocument)==null?void 0:y.body).removeAllRanges()}else e||this.dom((m=this.navigator.iframes[0].contentDocument)==null?void 0:m.body).removeAllRanges()}}speak(){var e,t;if(this.navigator.rights.enableTTS){let i=function(f){let u={className:m=>Nn.indexOf(m)<0,idName:m=>Nn.indexOf(m)<0},y=n.navigator.iframes[0].contentDocument;if(y)return Ar(f,y,u)},n=this,o=n.navigator.iframes[0].contentWindow;if(o){let f=Hi(o,i);if(f===void 0){let u=n.navigator.iframes[0].contentDocument;f=(t=(e=n.navigator.annotationModule)==null?void 0:e.annotator)==null?void 0:t.getTemporarySelectionInfo(u)}f!==void 0&&this.navigator.ttsModule.speak(f,!0,()=>{})}let s=n.navigator.iframes[0].contentDocument;s&&n.dom(s.body).getSelection().removeAllRanges();let c=document.getElementById("highlight-toolbox");c&&(c.style.display="none"),this.selectionMenuClosed()}}stopReadAloud(){this.navigator.rights.enableTTS&&this.doneSpeaking()}callbackComplete(){this.toolboxHide();let e=this.navigator.iframes[0].contentDocument;e&&this.dom(e.body).removeAllRanges()}isOutsideViewport(e){let t=ft(document,"#iframe-wrapper"),n=t.scrollLeft,i=n+t.clientWidth,o=e.left+e.width,s=e.top+e.height,c=t.scrollTop,f=c+t.clientHeight,u=s<c,y=e.top>f,m=o<n,_=e.left>i;return u||y||m||_}isInsideViewport(e){let t=ft(document,"#iframe-wrapper"),n=t.scrollTop,i=n+t.clientHeight,o=e.top+20>=n,s=e.top<=i,c=t.scrollLeft,f=c+t.clientWidth,u=e.left+e.width,y=e.left>c,m=u<f;return o&&s&&y&&m}get visibleTextRects(){let e=this.navigator.iframes[0].contentDocument;if(e){let n=function(c,f=[]){var y;let u=c.firstChild;for(;u;)u.nodeType===1&&n(u,f),u.nodeType===3&&(y=u.textContent)!=null&&y.trim()&&f.push(u),u=u.nextSibling;return f},i=function(c){return n(c).map(u=>{let{top:y,height:m,left:_,width:v}=o(u);return{top:y,height:m,width:v,left:_,node:u,textContent:u.textContent??""}})},o=function(c){try{let f=document.createRange();f.selectNode(c);let u=f.getBoundingClientRect();return f.detach(),u}catch(f){Yr.default.log("measureTextNode "+f),Yr.default.log("measureTextNode "+c),Yr.default.log(`${c.textContent}`)}},t=lo(e,"body");return i(t).filter(c=>this.isInsideViewport(c))}return[]}doneSpeaking(e=!1){if(this.navigator.rights.enableTTS){this.toolboxHide();let t=this.navigator.iframes[0].contentDocument;t&&this.dom(t.body).removeAllRanges(),this.navigator.ttsModule.cancel(),e&&this.navigator.reload()}}normalizeHighlights(e){var t;return t=e.filter(function(n){return n.parentElement?n:null}),t=this.unique(t),t.sort(function(n,i){return n.offsetTop-i.offsetTop||n.offsetLeft-i.offsetLeft}),t}flattenNestedHighlights(e){let t,n=this;n.sortByDepth(e,!0);function i(){let o=!1;return e.forEach(function(s,c){let f=s.parentElement,u=f.previousSibling,y=f.nextSibling;n.isHighlight(f)&&(n.haveSameColor(f,s)?(f.replaceChild(s.firstChild,s),e[c]=f,o=!0):(s.nextSibling||(n.dom(s).insertBefore(y||f),o=!0),s.previousSibling||(n.dom(s).insertAfter(u||f),o=!0),f.hasChildNodes()||n.dom(f).remove()))}),o}do t=i();while(t)}mergeSiblingHighlights(e){let t=this;function n(i,o){return o&&o.nodeType===Da.ELEMENT_NODE&&t.haveSameColor(i,o)&&t.isHighlight(o)}e.forEach(function(i){let o=i.previousSibling,s=i.nextSibling;n(i,o)&&(t.dom(i).prepend(o.childNodes),t.dom(o).remove()),n(i,s)&&(t.dom(i).append(s.childNodes),t.dom(s).remove()),t.dom(i).normalizeTextNodes()})}setColor(e){this.options.color=e}getColor(){return this.options.color}isHighlight(e){return e&&e.nodeType===Da.ELEMENT_NODE&&e.hasAttribute(tD)}createWrapper(){let e=document.createElement("mark");return e.style.background="linear-gradient("+r.hexToRgbA(this.options.color)+", "+r.hexToRgbA(this.options.color)+")",e.className=this.options.highlightedClass,e}static isHexColor(e){return/^#([A-Fa-f0-9]{3}){1,2}$/.test(e)}static hexToRgbString(e){let t;return t=e.substring(1).split(""),t.length===3&&(t=[t[0],t[0],t[1],t[1],t[2],t[2]]),t="0x"+t.join(""),t}static hexToRgbChannels(e){let t;if(this.isHexColor(e))return t=this.hexToRgbString(e),{red:t>>16&255,green:t>>8&255,blue:t&255};throw new Error("Bad Hex")}static hexToRgbA(e){let t;if(this.isHexColor(e))return t=this.hexToRgbChannels(e),"rgba("+[t.red,t.green,t.blue].join(",")+",.5)";if(typeof e=="object"){let n=e;return"rgba("+[n.red,n.green,n.blue].join(",")+",.5)"}throw new Error("Bad Hex")}static hexToRgbAWithOpacity(e,t){let n;if(this.isHexColor(e))return n=this.hexToRgbChannels(e),"rgba("+[n.red,n.green,n.blue].join(",")+","+t+")";if(typeof e=="object"){let i=e;return"rgba("+[i.red,i.green,i.blue].join(",")+","+t+")"}throw new Error("Bad Hex")}resetHighlightBoundingStyle(e){e.style.outline="none",e.style.setProperty("background-color","transparent","important")}resetHighlightAreaStyle(e,t){var o,s,c,f,u,y,m,_,v,g,h,l,p,w,A;let n=(o=this.navigator.iframes[0].contentWindow)==null?void 0:o.document,i=e.parentNode&&e.parentNode.nodeType===Node.ELEMENT_NODE&&e.parentNode.getAttribute?e.parentNode.getAttribute("id"):void 0;if(i){let C=er.find(b=>b.id===i);if(C){if(C.marker===3||C.marker===2)if((s=C.style)!=null&&s.hover){if((c=C.style)!=null&&c.hover)for(let k=0;k<((u=(f=C.style)==null?void 0:f.hover)==null?void 0:u.length);k++){let P=(y=C.style)==null?void 0:y.hover[k];e.style.removeProperty(P.property)}let E="";if((m=C.style)!=null&&m.default)for(let k=0;k<((v=(_=C.style)==null?void 0:_.default)==null?void 0:v.length);k++){let P=(g=C.style)==null?void 0:g.default[k];e.style.removeProperty(P.property),E+=`${P.property}: ${P.value} !${P.priority};`}e.setAttribute("style",`${e.getAttribute("style")}; ${E}`)}else if((h=C.style)!=null&&h.hoverClass){(l=C.style)!=null&&l.hoverClass&&e.classList.remove((p=C.style)==null?void 0:p.hoverClass);let E="";(w=C.style)!=null&&w.defaultClass&&e.classList.add((A=C.style)==null?void 0:A.defaultClass),e.setAttribute("style",`${e.getAttribute("style")}; ${E}`)}else if(r.isHexColor(C.color)){let E=r.hexToRgbChannels(C.color);e.style.setProperty("background-color",`rgba(${E.red}, ${E.green}, ${E.blue}, 0)`,"important")}else e.classList.remove("hover");else if(C.marker===1||C.marker===4)if(typeof C.color=="object"){let E=C.color;e.style.setProperty("background-color",`rgba(${E.red}, ${E.green}, ${E.blue}, 0)`,"important"),e.style.setProperty("border-bottom",`2px solid rgba(${E.red}, ${E.green}, ${E.blue}, 1)`,"important")}else if(r.isHexColor(C.color)){let E=r.hexToRgbChannels(C.color);e.style.setProperty("background-color",`rgba(${E.red}, ${E.green}, ${E.blue}, 0)`,"important"),e.style.setProperty("border-bottom",`2px solid rgba(${E.red}, ${E.green}, ${E.blue}, 1)`,"important")}else e.classList.remove("hover");else if(typeof C.color=="object"){let E=C.color;e.style.setProperty("background-color",`rgba(${E.red}, ${E.green}, ${E.blue}, ${Ui})`,"important")}else if(r.isHexColor(C.color)){let E=r.hexToRgbChannels(C.color);e.style.setProperty("background-color",`rgba(${E.red}, ${E.green}, ${E.blue}, ${Ui})`,"important")}else e.classList.remove("hover");let b;if(n){let E=n.getElementById(t);E&&(b=E.querySelector(`#${C.id}`))}if(b){let E=b.getElementsByClassName(Sl);if(E.length>0){let k=E.item(0).getElementsByClassName("icon-tooltip");k.length>0&&k.item(0).style.removeProperty("display")}}}}}setHighlightAreaStyle(e,t,n){var i,o,s,c,f,u,y,m,_,v,g,h;for(let l of t){if(n.marker===3||n.marker===2)if((i=n.style)!=null&&i.hover){if((o=n.style)!=null&&o.default)for(let w=0;w<((c=(s=n.style)==null?void 0:s.default)==null?void 0:c.length);w++){let A=(f=n.style)==null?void 0:f.default[w];l.style.removeProperty(A.property)}let p="";for(let w=0;w<((y=(u=n.style)==null?void 0:u.hover)==null?void 0:y.length);w++){let A=(m=n.style)==null?void 0:m.hover[w];l.style.removeProperty(A.property),p+=`${A.property}: ${A.value} !${A.priority};`}l.setAttribute("style",`${l.getAttribute("style")}; ${p}`)}else if((_=n.style)!=null&&_.hoverClass){(v=n.style)!=null&&v.defaultClass&&l.classList.remove((g=n.style)==null?void 0:g.defaultClass);let p="";l.classList.add((h=n.style)==null?void 0:h.hoverClass),l.setAttribute("style",`${l.getAttribute("style")}; ${p}`)}else if(r.isHexColor(n.color)){let p=r.hexToRgbChannels(n.color);l.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${.1})`,"important")}else l.classList.add("hover");else if(n.marker===1||n.marker===4)if(typeof n.color=="object"){let p=n.color;l.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${.1})`,"important"),l.style.setProperty("border-bottom",`2px solid rgba(${p.red}, ${p.green}, ${p.blue}, 1)`,"important")}else if(r.isHexColor(n.color)){let p=r.hexToRgbChannels(n.color);l.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${.1})`,"important"),l.style.setProperty("border-bottom",`2px solid rgba(${p.red}, ${p.green}, ${p.blue}, 1)`,"important")}else l.classList.add("hover");else if(typeof n.color=="object"){let p=n.color;l.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${xw})`,"important")}else if(r.isHexColor(n.color)){let p=r.hexToRgbChannels(n.color);l.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${xw})`,"important")}else l.classList.add("hover");if(n.type!==4){let w=e.getElementById("R2_ID_HIGHLIGHTS_CONTAINER").querySelector(`#${n.id}`).getElementsByClassName(Sl);if(w.length>0){let A=w.item(0).getElementsByClassName("icon-tooltip");A.length>0&&A.item(0).style.setProperty("display","block")}}}}setAndResetSearchHighlight(e,t){var o;let n=(o=this.navigator.iframes[0].contentWindow)==null?void 0:o.document,i=Array.from(n.getElementById("R2_ID_SEARCH_CONTAINER").querySelectorAll(`.${Ur}`));for(let s of i){let c=s,f=c.parentNode&&c.parentNode.nodeType===Node.ELEMENT_NODE&&c.parentNode.getAttribute?c.parentNode.getAttribute("id"):void 0;if(t.forEach(u=>{if(f===u.id&&u){if(typeof u.color=="object"){let _=u.color;c.style.setProperty("background-color",`rgba(${_.red}, ${_.green}, ${_.blue}, ${Ui})`,"important")}else if(r.isHexColor(u.color)){let _=r.hexToRgbChannels(u.color);c.style.setProperty("background-color",`rgba(${_.red}, ${_.green}, ${_.blue}, ${Ui})`,"important")}else c.classList.remove("hover");let m=n.getElementById("R2_ID_SEARCH_CONTAINER").querySelector(`#${u.id}`).getElementsByClassName(Sl);if(m.length>0){let _=m.item(0).getElementsByClassName("icon-tooltip");_.length>0&&_.item(0).style.removeProperty("display")}}}),f===e.id&&e){if(typeof e.color=="object"){let m=e.color;c.style.setProperty("background-color",`rgba(${m.red}, ${m.green}, ${m.blue}, ${Ui})`,"important")}else if(r.isHexColor(e.color)){let m=r.hexToRgbChannels(e.color);c.style.setProperty("background-color",`rgba(${m.red}, ${m.green}, ${m.blue}, ${Ui})`,"important")}else c.classList.remove("hover");let y=n.getElementById("R2_ID_SEARCH_CONTAINER").querySelector(`#${e.id}`).getElementsByClassName(Sl);if(y.length>0){let m=y.item(0).getElementsByClassName("icon-tooltip");m.length>0&&m.item(0).style.removeProperty("display")}}}}isIOS(){return navigator.userAgent.match(/iPhone|iPad|iPod/i)!=null||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}isAndroid(){return navigator.userAgent.match(/Android/i)!=null}async processMouseEvent(e){var o,s,c,f,u,y,m,_,v,g,h,l,p;let t=(o=this.navigator.iframes[0].contentWindow)==null?void 0:o.document;if(!t||!(e.type==="mouseup"||e.type==="click"||e.type==="touchup")||!t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER")&&!t.getElementById("R2_ID_SEARCH_CONTAINER")&&!t.getElementById("R2_ID_PAGEBREAK_CONTAINER")&&!t.getElementById("R2_ID_READALOUD_CONTAINER")&&!t.getElementById("R2_ID_DEFINITIONS_CONTAINER"))return;let n=e.target,i=er.find(w=>{var A;return w.id===((A=e.target.parentElement)==null?void 0:A.id)});if(!i||!n){for(let w in ks){let A=t.getElementById(w);if(A){let C=A.querySelectorAll(`.${Cl}`);for(let E of C)this.resetHighlightBoundingStyle(E);let b=Array.from(A.querySelectorAll(`.${Ur}`));for(let E of b)this.resetHighlightAreaStyle(E,w)}}return}if(n.getAttribute("data-click")&&(e.type==="mouseup"||e.type==="click"||e.type==="touchup")&&((s=n.parentElement)==null?void 0:s.style.display)!=="none"){let w={highlight:i};Yr.default.log(JSON.stringify(w));let A=this,C;if(A.navigator.rights.enableAnnotations?C=await((c=this.navigator.annotationModule)==null?void 0:c.getAnnotation(w.highlight)):A.navigator.rights.enableBookmarks&&(C=await((f=this.navigator.bookmarkModule)==null?void 0:f.getAnnotation(w.highlight))),w.highlight.type===0&&((y=(u=this.navigator.annotationModule)==null?void 0:u.api)==null||y.selectedAnnotation(C).then(async()=>{})),C!=null&&C.id){Yr.default.log("selected highlight "+C.id),A.lastSelectedHighlight=C.id;let b=document.getElementById("highlight-toolbox");if(b)if(b.style.top=e.clientY+(((m=this.navigator.attributes)==null?void 0:m.navHeight)??0)+"px",b.style.left=e.clientX+"px",getComputedStyle(b).display==="none"){let P=function(){var q,G;(G=(q=A.navigator.annotationModule)==null?void 0:q.api)==null||G.addCommentToAnnotation(C).then(Y=>{var X;(X=A.navigator.annotationModule)==null||X.updateAnnotation(Y).then(async()=>{Yr.default.log("update highlight "+Y.id),b&&(b.style.display="none"),A.selectionMenuClosed()}),b&&(b.style.display="none"),A.selectionMenuClosed(),N==null||N.removeEventListener("click",P,!1)})},F=function(){var q,G;A.navigator.rights.enableAnnotations?(q=A.navigator.annotationModule)==null||q.deleteSelectedHighlight(C).then(async()=>{Yr.default.log("delete highlight "+C.id),b&&(b.style.display="none"),A.selectionMenuClosed()}):A.navigator.rights.enableBookmarks&&((G=A.navigator.bookmarkModule)==null||G.deleteSelectedHighlight(C).then(async()=>{Yr.default.log("delete highlight "+C.id),b&&(b.style.display="none"),A.selectionMenuClosed()}))};b.style.display="block",this.toolboxMode("edit");let E=document.getElementById("colorIcon"),k=document.getElementById("highlightIcon");E&&(E.style.display="none"),k&&(k.style.display="none");let N=document.getElementById("commentIcon"),D=document.getElementById("cloneCommentIcon");if(D){let q=D.parentElement;q&&q.removeChild(D)}if(N){N.style.display="none";let q=N.cloneNode(!0),G=N.parentElement;q.style.display="unset",q.id="cloneCommentIcon",q.addEventListener("click",P,!1),G&&G.append(q)}let B=document.getElementById("deleteIcon"),V=document.getElementById("cloneDeleteIcon");if(V){let q=V.parentElement;q&&q.removeChild(V)}if(B){B.style.display="none";let q=B.cloneNode(!0),G=B.parentElement;q.style.display="unset",q.id="cloneDeleteIcon",q.addEventListener("click",F,!1),G&&G.append(q)}}else b.style.display="none",this.selectionMenuClosed(),b.offsetWidth,b.style.display="block"}else{n.dataset.definition&&new Ia(this.navigator).showPopup(n.dataset.definition,e);let b=(g=(v=(_=this.navigator.definitionsModule)==null?void 0:_.properties)==null?void 0:v.definitions)==null?void 0:g.filter(E=>E.order===Number(n==null?void 0:n.dataset.order))[0];Yr.default.log(b),(l=(h=this.navigator.definitionsModule)==null?void 0:h.api)!=null&&l.click&&((p=this.navigator.definitionsModule.api)==null||p.click(t1.omit(b,"callbacks"),t1.omit(i,"definition")),this.navigator.emit("definition.click",b,i))}}}async prepareContainers(e){for(let t in ks)await this.ensureHighlightsContainer(e,t)}async ensureHighlightsContainer(e,t){var i,o;let n=e.document;if(!n.getElementById(t)){let s=n.createElement("div");s.setAttribute("id",t),t!=="R2_ID_GUTTER_RIGHT_CONTAINER"&&s.style.setProperty("pointer-events","none"),((i=this.navigator.view)==null?void 0:i.layout)==="fixed"&&(s.style.setProperty("position","absolute"),s.style.setProperty("top","0"),s.style.setProperty("left","0")),n.body&&n.body.append(s),((o=await this.layerSettings.getProperty(t))==null?void 0:o.value)===!1&&(s.style.display="none")}return n.getElementById(t)}hideAllhighlights(e){this.removeAllChildNodes(e.getElementById("R2_ID_HIGHLIGHTS_CONTAINER")),this.removeAllChildNodes(e.getElementById("R2_ID_SEARCH_CONTAINER")),this.removeAllChildNodes(e.getElementById("R2_ID_READALOUD_CONTAINER")),this.removeAllChildNodes(e.getElementById("R2_ID_PAGEBREAK_CONTAINER")),this.removeAllChildNodes(e.getElementById("R2_ID_DEFINITIONS_CONTAINER"))}destroyAllhighlights(e){this.hideAllhighlights(e),er.splice(0,er.length)}removeAllChildNodes(e){for(;e.firstChild;)e.removeChild(e.firstChild)}destroyHighlights(e){var n;let t=(n=this.navigator.iframes[0].contentWindow)==null?void 0:n.document;if(t){let i;switch(e){case 2:i=t.getElementById("R2_ID_READALOUD_CONTAINER"),i&&this.removeAllChildNodes(i);break;case 1:i=t.getElementById("R2_ID_SEARCH_CONTAINER"),i&&this.removeAllChildNodes(i);break;case 3:i=t.getElementById("R2_ID_PAGEBREAK_CONTAINER"),i&&this.removeAllChildNodes(i);break;case 4:i=t.getElementById("R2_ID_DEFINITIONS_CONTAINER"),i&&this.removeAllChildNodes(i);break;case 5:i=t.getElementById("R2_ID_LINEFOCUS_CONTAINER"),i&&this.removeAllChildNodes(i);break;case 6:i=t.getElementById("R2_ID_GUTTER_RIGHT_CONTAINER"),i&&this.removeAllChildNodes(i);break;default:i=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),i&&this.removeAllChildNodes(i),er.splice(0,er.length);break}}}destroyHighlight(e,t){if(!e)return;let n=-1;er.find((s,c)=>(n=c,s.id===t))&&n>=0&&n<er.length&&er.splice(n,1);let o=e.getElementById(t);o&&this.removeAllChildNodes(o)}createHighlight(e,t,n,i,o,s,c,f,u,y){try{let m=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,_=Fi.hash(m),v=(y||"R2_HIGHLIGHT_")+_;this.destroyHighlight(e.document,v);let g=`rgb(${Rs.red}, ${Rs.green}, ${Rs.blue})`,h={color:n||g,id:v,pointerInteraction:i,selectionInfo:t,marker:o,icon:s,popup:c,style:f,type:u||0};(u===0||u===4||u===void 0)&&er.push(h);let l=this.createHighlightDom(e,h);return h.position=parseInt((l!=null&&l.hasChildNodes()?l.childNodes[0]:l).style.top.replace("px","")),[h,l]}catch(m){throw"Can't create highlight: "+m}}createHighlightDom(e,t){var B,V,q,G,Y,X,Q,le,ve,ce,W,H,R,x,T,O,I,U,z,Z,re,ne,se,fe,he,Te,Ie,we,ye,oe,Ce,xe;let n=e.document,i=Lf(n,t.selectionInfo.rangeInfo);if(!i)return;for(let K in ks)this.ensureHighlightsContainer(e,K);let o=n.createElement("div");o.setAttribute("id",t.id),o.setAttribute("class",Tw),o.style.setProperty("pointer-events","none"),t.pointerInteraction&&(o.setAttribute("data-click","1"),o.addEventListener("mouseover",K=>{var ie;if(K.target.classList.contains("R2_CLASS_HIGHLIGHT_AREA")){let be=K.currentTarget,Ee=er.find(Re=>Re.id===K.currentTarget.id);if(K.type==="mouseover"&&((ie=be.parentElement)==null?void 0:ie.style.display)!=="none"&&Ee){let Re=Array.from(be.querySelectorAll(`.${Ur}`));this.setHighlightAreaStyle(n,Re,Ee)}}}),o.addEventListener("mouseleave",K=>{let ie=K.currentTarget,be=Array.from(ie.querySelectorAll(`.${Ur}`));for(let Ke of be)this.resetHighlightAreaStyle(Ke,ie.id);let Ee=ie.querySelector(`.${Cl}`),Re=ie.querySelectorAll(`.${Cl}`);for(let Ke of Re)(!Ee||Ke!==Ee)&&this.resetHighlightBoundingStyle(Ke)}));let s=(B=this.navigator.view)==null?void 0:B.isPaginated();s?n.body.style.position="revert":n.body.style.position="relative";let c=n.body.getBoundingClientRect(),f=this.getScrollingElement(n),u=s?-f.scrollLeft:c.left,y=s?-f.scrollTop:c.top,m=1,_=!1,v=!1,h=_||v||!1;Yr.default.debug(h),h=!0;let l=Rf(i,h),p=3,w=2,A=3,C=0,b=24,E,k;for(let K of l){let ie=n.createElement("div");ie.setAttribute("class",Ur),ie.dataset.marker=""+t.marker;let be="";if(_&&t.marker!==3&&t.marker!==2&&t.marker!==4){let Be=t.color;r.isHexColor(Be)&&(Be=r.hexToRgbChannels(Be)),be+=`border-bottom: ${w*m}px solid rgba(${Be.red}, ${Be.green}, ${Be.blue}, ${Ui}) !important`}if(t.marker===3||t.marker===2)if((V=t.style)!=null&&V.default){for(let Be=0;Be<((G=(q=t.style)==null?void 0:q.default)==null?void 0:G.length);Be++){let ut=(Y=t.style)==null?void 0:Y.default[Be];be+=`${ut.property}: ${ut.value} !${ut.priority};`}ie.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${p}px !important; ${be}`)}else(X=t.style)!=null&&X.defaultClass&&(ie.classList.add((Q=t.style)==null?void 0:Q.defaultClass),ie.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${p}px !important; ${be}`));else if(t.marker===1||t.marker===4)if(typeof t.color=="object"){let Be=t.color;ie.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${p}px !important; background-color: rgba(${Be.red}, ${Be.green}, ${Be.blue}, 0) !important; ${be}`),ie.style.setProperty("border-bottom",`2px solid rgba(${Be.red}, ${Be.green}, ${Be.blue}, 1)`,"important")}else if(r.isHexColor(t.color)){let Be=r.hexToRgbChannels(t.color);ie.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${p}px !important; background-color: rgba(${Be.red}, ${Be.green}, ${Be.blue}, 0) !important; ${be}`),ie.style.setProperty("border-bottom",`2px solid rgba(${Be.red}, ${Be.green}, ${Be.blue}, 1)`,"important")}else ie.setAttribute("style",`border-radius: ${p}px !important; ${be}`);else if(typeof t.color=="object"){let Be=t.color;ie.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${p}px !important; background-color: rgba(${Be.red}, ${Be.green}, ${Be.blue}, ${Ui}) !important; ${be}`)}else if(r.isHexColor(t.color)){let Be=r.hexToRgbChannels(t.color);ie.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${p}px !important; background-color: rgba(${Be.red}, ${Be.green}, ${Be.blue}, ${Ui}) !important; ${be}`)}else ie.setAttribute("style",`border-radius: ${p}px !important; ${be}`);t.type===1||t.type===2||t.type===5||t.type===3?ie.style.setProperty("pointer-events","none"):(ie.style.setProperty("pointer-events","all"),ie.style.setProperty("cursor","hand")),ie.style.position="absolute",ie.scale=m,ie.rect={height:K.height,left:K.left-u,top:K.top-y,width:K.width},t.pointerInteraction&&(ie.setAttribute("data-click","1"),ie.tabIndex=0),ie.style.width=`${ie.rect.width*m}px`,ie.style.height=`${ie.rect.height*m}px`,ie.style.left=`${ie.rect.left*m}px`,ie.style.top=`${ie.rect.top*m}px`,o.append(ie);let Ee=parseInt(ie.style.top.replace("px",""));if((Ee<C||C===0)&&(C=Ee),b=parseInt(ie.style.height.replace("px","")),v){let Be=n.createElement("div");Be.setAttribute("class",Ur);let ut=t.color;r.isHexColor(ut)&&(ut=r.hexToRgbChannels(ut)),Be.setAttribute("style",`background-color: rgba(${ut.red}, ${ut.green}, ${ut.blue}, ${Ui}) !important;`),t.type===1||t.type===2||t.type===5||t.type===3?Be.style.setProperty("pointer-events","none"):(Be.style.setProperty("pointer-events","all"),Be.style.setProperty("cursor","hand")),Be.style.position="absolute",Be.scale=m,Be.rect={height:K.height,left:K.left-u,top:K.top-y,width:K.width},Be.style.width=`${Be.rect.width*m}px`,Be.style.height=`${A*m}px`,Be.style.left=`${Be.rect.left*m}px`,Be.style.top=`${(Be.rect.top+Be.rect.height/2-A/2)*m}px`,o.append(Be)}let Re=(le=this.navigator.iframes[0].contentWindow)==null?void 0:le.innerWidth,Ke=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-count")),ze=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-width")),Ve=parseInt(getComputedStyle(n.body).getPropertyValue("padding-left")),qe=Re/(Ke||1);qe<ze&&(qe=Re),s||(qe=parseInt(getComputedStyle(n.body).width.replace("px","")));let pe=this.navigator.settings.fontSize/100,ee=20*pe;pe<=1&&(ee=-60);let de=0*pe;pe<=1&&(de=-60),E=Math.floor(K.left/qe)*qe+qe-(b<40?40:b)+de,k=Math.floor(K.left/qe)*qe+(b<40?40:b)-ee;let je=parseInt(this.navigator.iframes[0].contentDocument.documentElement.style.getPropertyValue("--USER__pageMargins"));je>=2&&(k=k+Ve/Ke,E=E-Ve/Ke),s||(E=parseInt(getComputedStyle((ve=this.navigator.iframes[0].contentDocument)==null?void 0:ve.body).width.replace("px","")),k=parseInt(getComputedStyle((ce=this.navigator.iframes[0].contentDocument)==null?void 0:ce.body).width.replace("px",""))-qe,je>=2&&(k=k+Ve/2,E=E-Ve/2))}let P=i.getBoundingClientRect(),N=n.createElement("div");N.setAttribute("class",Cl),N.style.setProperty("pointer-events","none"),N.style.position="absolute",N.scale=m,N.rect={height:P.height,left:P.left-u,top:P.top-y,width:P.width},N.style.width=`${N.rect.width*m}px`,N.style.height=`${N.rect.height*m}px`,N.style.left=`${N.rect.left*m}px`,N.style.top=`${N.rect.top*m}px`,o.append(N);let D=n.createElement("div");if(D.setAttribute("class",Sl),((W=t.icon)==null?void 0:W.position)==="left")D.setAttribute("style",`position: absolute;top:${C}px;left:${k+((R=(H=this.navigator.iframes[0].contentDocument)==null?void 0:H.scrollingElement)==null?void 0:R.scrollLeft)}px;height:${b}px; width:${b}px;`);else if(((x=t.icon)==null?void 0:x.position)==="inline")D.setAttribute("style",`position: absolute;top:${C-b/2}px;left:${parseInt(N.style.left.replace("px",""))+parseInt(N.style.width.replace("px",""))-b/2}px;height:${b}px; width:${b}px;`);else if(((T=t.icon)==null?void 0:T.position)==="center"){let ie=b/3*2;D.setAttribute("style",`position: absolute;top:${C}px;left:${parseInt(N.style.left.replace("px",""))+parseInt(N.style.width.replace("px",""))-ie}px;height:${b}px; width:${b}px;`)}else t.note&&t.marker!==3&&t.marker!==2&&t.marker!==4&&t.marker!==0&&t.marker!==1?D.setAttribute("style",`position: absolute;top:${C-b/2}px;left:${parseInt(N.style.left.replace("px",""))+parseInt(N.style.width.replace("px",""))-b/2}px;height:${b}px; width:${b}px;`):t.note&&t.marker===4||t.marker===0||t.marker===1?D.setAttribute("style",`position: absolute;top:${C}px;left:${E+((I=(O=this.navigator.iframes[0].contentDocument)==null?void 0:O.scrollingElement)==null?void 0:I.scrollLeft)}px;height:${b}px; width:${b}px;`):D.setAttribute("style",`position: absolute;top:${C}px;left:${E+((z=(U=this.navigator.iframes[0].contentDocument)==null?void 0:U.scrollingElement)==null?void 0:z.scrollLeft)}px;height:${b}px; width:${b}px;`);if(t.marker===3||t.marker===2)(Z=t.icon)!=null&&Z.class?(D.classList.add((re=t.icon)==null?void 0:re.class),D.id=(ne=t.icon)==null?void 0:ne.id):(se=t.icon)!=null&&se.svgPath?D.innerHTML=Na(`${(fe=t.icon)==null?void 0:fe.id}`,`${(he=t.icon)==null?void 0:he.title}`,`${(Te=t.icon)==null?void 0:Te.svgPath}`,"icon open",b,`${(Ie=t.icon)==null?void 0:Ie.color} !important`):(we=t.icon)!=null&&we.title&&(D.innerHTML=(ye=t.icon)==null?void 0:ye.title);else if(t.note){let K=t.color;r.isHexColor(K)&&(K=r.hexToRgbChannels(K)),t.marker===4||t.marker===0||t.marker===1?D.innerHTML=Na("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="14"/>',"icon open",b/2,`rgba(${K.red}, ${K.green}, ${K.blue}, 1) !important`):D.innerHTML=Na("note-icon","Note",'<rect fill="none" height="24" width="24"/><path d="M19,5v9l-5,0l0,5H5V5H19 M19,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h10l6-6V5C21,3.9,20.1,3,19,3z M12,14H7v-2h5V14z M17,10H7V8h10V10z"/>',"icon open",b,`rgba(${K.red}, ${K.green}, ${K.blue}, 1) !important`)}t.type===1||t.type===2||t.type===5||t.type===3?D.style.setProperty("pointer-events","none"):(D.style.setProperty("pointer-events","all"),D.style.setProperty("cursor","hand"));let F=this;if(t.type!==3&&t.type!==4&&D.addEventListener("click",async function(K){var Re,Ke,ze,Ve,qe;let ie;F.navigator.rights.enableAnnotations?(ie=await((Re=F.navigator.annotationModule)==null?void 0:Re.getAnnotationByID(t.id)),(ze=(Ke=F.navigator.annotationModule)==null?void 0:Ke.api)==null||ze.selectedAnnotation(ie).then(async()=>{})):F.navigator.rights.enableBookmarks&&(ie=await((Ve=F.navigator.bookmarkModule)==null?void 0:Ve.getAnnotationByID(t.id))),Yr.default.log("selected highlight "+ie.id),F.lastSelectedHighlight=ie.id;let be=document.getElementById("highlight-toolbox");if(be)if(be.style.top=K.clientY+(((qe=F.navigator.attributes)==null?void 0:qe.navHeight)??0)+"px",be.style.left=K.clientX+"px",getComputedStyle(be).display==="none"){let Be=function(){var Ht,Br;F.navigator.rights.enableAnnotations?(Ht=F.navigator.annotationModule)==null||Ht.deleteSelectedHighlight(ie).then(async()=>{Yr.default.log("delete highlight "+ie.id),be.style.display="none",F.selectionMenuClosed()}):F.navigator.rights.enableBookmarks&&((Br=F.navigator.bookmarkModule)==null||Br.deleteSelectedHighlight(ie).then(async()=>{Yr.default.log("delete highlight "+ie.id),be.style.display="none",F.selectionMenuClosed()}))};be.style.display="block",F.toolboxMode("edit");let pe=document.getElementById("colorIcon"),ee=document.getElementById("highlightIcon");pe&&(pe.style.display="none"),ee&&(ee.style.display="none");let de=document.getElementById("commentIcon"),je=document.getElementById("cloneCommentIcon");if(je){let Ht=je.parentElement;Ht&&Ht.removeChild(je)}de&&(de.style.display="none");let ut=document.getElementById("deleteIcon"),Ct=document.getElementById("cloneDeleteIcon");if(Ct){let Ht=Ct.parentElement;Ht&&Ht.removeChild(Ct)}if(ut){ut.style.display="none";let Ht=ut.cloneNode(!0),Br=ut.parentElement;Ht.style.display="unset",Ht.id="cloneDeleteIcon",Ht.addEventListener("click",Be,!1),Br&&Br.append(Ht)}}else be.style.display="none",F.selectionMenuClosed(),be.offsetWidth,be.style.display="block";let Ee=Array.from(o.querySelectorAll(`.${Ur}`));F.setHighlightAreaStyle(n,Ee,t)}),t.note){let K=document.createElement("span");K.innerHTML=t.note,K.className="icon-tooltip",t.marker===3||t.marker===2?((oe=t.popup)!=null&&oe.background&&K.style.setProperty("background",t.popup.background),(Ce=t.popup)!=null&&Ce.textColor&&K.style.setProperty("color",t.popup.textColor),(xe=t.popup)!=null&&xe.class&&K.classList.add(t.popup.class)):(K.style.setProperty("background","lightyellow"),K.style.setProperty("color","black"))}switch((t.note||t.marker===3||t.marker===2)&&o.append(D),t.type){case 1:n.getElementById("R2_ID_SEARCH_CONTAINER").append(o);break;case 2:n.getElementById("R2_ID_READALOUD_CONTAINER").append(o);break;case 3:n.getElementById("R2_ID_PAGEBREAK_CONTAINER").append(o);break;case 4:n.getElementById("R2_ID_DEFINITIONS_CONTAINER").append(o);break;default:n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER").append(o);break}return o}addSelectionMenuItem(e){var t,n;(((t=this.properties)==null?void 0:t.selectionMenuItems)??[])&&(((n=this.properties)==null?void 0:n.selectionMenuItems)??[]).push(e)}};var Uw=rt(d1());L();var dD=rt($t());var Jo={className:r=>!0,idName:r=>!0,tagName:r=>!0};var jw=rt(Nf()),ei=rt($t());L();var Fw=rt($t());var Ha=class{constructor(e,t,n){this.currSeconds=0;this.publication=e,this.properties=t,this.api=n}static async create(e){let t=new this(e.publication,e,e.api);return await t.start(),t}async start(){this.startResearchSession()}async stop(){Fw.default.log("Consumption module stop"),this.endResearchSession()}initialize(){let e=this.navigator.iframes[0].contentWindow;if(e){let t=this;e.onload=function(){t.resetTimer()},e.onmousemove=function(){t.resetTimer()},e.onmousedown=function(){t.resetTimer()},e.ontouchstart=function(){t.resetTimer()},e.onclick=function(){t.resetTimer()},e.onkeypress=function(){t.resetTimer()}}}trackAction(e,t){var n;(n=this.api)==null||n.actionTracked(e,t)}startReadingSession(e){if(this.firstReadingLocator&&this.lastReadingLocator){let t=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,n=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:n,progress:Math.round(t*100)})}this.firstReadingLocator=e,this.startReadingTimer=new Date}continueReadingSession(e){this.properties.enableTrackingSession&&(this.startResearchTimer===void 0&&this.startResearchSession(),(this.lastReadingLocator===void 0||this.lastReadingLocator.locations.totalProgression<e.locations.totalProgression)&&(this.lastReadingLocator=e),this.firstReadingLocator===void 0&&(this.firstReadingLocator=e),this.startReadingTimer===void 0&&(this.startReadingTimer=new Date))}startResearchSession(){var e;if(this.properties.enableTrackingSession){this.startResearchTimer=new Date,this.readingSessions=[],clearInterval(this.readingSessionsInterval);let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.researchSessionId=(e=this.api)==null?void 0:e.startResearchSession(this.readingSessions,Math.round(t));let n=this;this.readingSessionsInterval=setInterval(function(){n.updateResearchSession()},this.properties.updateSessionInterval*1e3)}}updateResearchSession(){var e;if(this.properties.enableTrackingSession){let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;(e=this.api)==null||e.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(t))}}endResearchSession(){var e,t;if(this.properties.enableTrackingSession){if(this.firstReadingLocator&&this.lastReadingLocator){let i=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,o=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:o,progress:Math.round(i*100)})}let n=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;(e=this.api)==null||e.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(n)),(t=this.api)==null||t.endResearchSession(this.researchSessionId,this.readingSessions,Math.round(n)),this.researchSessionId=void 0,this.readingSessions=[],this.startResearchTimer=void 0,clearInterval(this.readingSessionsInterval),clearInterval(this.timer)}}startIdleTimer(){var e;this.currSeconds++,this.currSeconds===this.properties.idleTimeout&&((e=this.api)==null||e.idleSince(this.currSeconds),this.startResearchTimer!==void 0?this.updateResearchSession():this.startResearchSession()),this.currSeconds===this.properties.idleTimeout+this.properties.responseTimeout&&this.endResearchSession()}resetTimer(){clearInterval(this.timer),this.currSeconds=0;let e=this;this.timer=setInterval(function(){e.startIdleTimer()},1e3)}};var Ua=class r{constructor(e,t,n,i,o,s,c,f){this.hide=Ne(document,"#menu-button-hide");this.show=Ne(document,"#menu-button-show");this.annotator=e,this.rights=t,this.publication=n,this.headerMenu=f,this.initialAnnotations=i,this.highlighter=s,this.properties=o,this.api=c}static async create(e){let t=new this(e.annotator,e.rights||{enableAnnotations:!1,enableTTS:!1},e.publication,e.initialAnnotations||null,e,e.highlighter,e.api,e.headerMenu);return await t.start(),t}async stop(){ei.default.log("Annotation module stop")}async start(){var t;if(this.headerMenu&&(this.highlightsView=Ne(this.headerMenu,"#container-view-highlights")),this.initialAnnotations){var e=this.initialAnnotations.highlights||null;e&&((t=this.annotator)==null||t.initAnnotations(e))}setTimeout(()=>{var n;(n=this.properties)!=null&&n.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)}hideAnnotationLayer(){let e=this.navigator.iframes[0].contentDocument;if(e){let t=Ne(e,"#R2_ID_HIGHLIGHTS_CONTAINER");t&&(t.style.display="none")}this.show&&this.hide&&(this.show.style.display="block",this.hide.style.display="none")}showAnnotationLayer(){let e=this.navigator.iframes[0].contentDocument;if(e){let t=Ne(e,"#R2_ID_HIGHLIGHTS_CONTAINER");t&&(t.style.display="block")}this.show&&this.hide&&(this.show.style.display="none",this.hide.style.display="block")}async handleResize(){setTimeout(async()=>{await this.drawHighlights(),await this.showHighlights()},200)}initialize(){return new Promise(async e=>{await document.fonts.ready,this.rights.enableAnnotations&&setTimeout(()=>{var t;this.drawHighlights(),this.showHighlights(),_e((t=this.navigator.iframes[0].contentDocument)==null?void 0:t.body,"click",this.click.bind(this))},300),e(null)})}click(e){var t,n,i,o,s,c,f;if(this.activeAnnotationMarkerId){let u=(i=(n=(t=this.highlighter)==null?void 0:t.properties)==null?void 0:n.selectionMenuItems)==null?void 0:i.filter(y=>y.id===this.activeAnnotationMarkerId);if(u&&(u==null?void 0:u.length)>0){let y=jw.cloneDeep(u[0]);y.marker=3,this.activeAnnotationMarkerPosition&&(y.icon.position=this.activeAnnotationMarkerPosition),y.highlight.style.default=null,y.highlight.style.hover=null;let m=this.navigator.iframes[0].contentDocument;if(m){let l=function(w){try{let A=h.navigator.iframes[0].contentDocument;return A?Ar(w,A,Jo):""}catch(A){return ei.default.log("uniqueCssSelector:"),ei.default.error(A),""}},_=(o=this.highlighter)==null?void 0:o.dom(m.body).getSelection(),v=_.getRangeAt(0),g=_.anchorNode;v.setStart(g,v.startOffset),v.setEnd(g,v.endOffset+1),_.removeAllRanges(),_.addRange(v);let h=this,p=go(v,l);if(_.removeAllRanges(),p){let w={rangeInfo:p},A=(c=this.navigator.highlighter)==null?void 0:c.createHighlight((s=this.navigator.highlighter)==null?void 0:s.dom(m.body).getWindow(),w,y.highlight.color,!0,2,y.icon,y.popup,y.highlight.style);A&&this.saveAnnotation(A[0]).then(C=>{ei.default.log("saved bookmark "+C.id)})}(f=m.getSelection())==null||f.removeAllRanges()}}}}async scrollToHighlight(e){var n;ei.default.log("still need to scroll to "+e);var t=await((n=this.annotator)==null?void 0:n.getAnnotationElement(e,this.navigator.iframes[0].contentWindow));t.scrollIntoView({block:"center",behavior:"smooth"})}async updateLocalHighlight(e){if(this.annotator){let t=await this.annotator.deleteAnnotation(e.id),n=await this.addAnnotation(e);return ei.default.log("Highlight deleted "+JSON.stringify(t)),ei.default.log("Highlight added "+JSON.stringify(n)),await this.showHighlights(),await this.drawHighlights(),n}else return new Promise(t=>t(null))}async deleteLocalHighlight(e){if(this.annotator){var t=await this.annotator.deleteAnnotation(e);return ei.default.log("Highlight deleted "+JSON.stringify(t)),await this.showHighlights(),await this.drawHighlights(),t}else return new Promise(n=>n(null))}async deleteAnnotation(e){await this.deleteLocalHighlight(e.id)}async addAnnotation(e){var t;await((t=this.annotator)==null?void 0:t.saveAnnotation(e)),await this.showHighlights(),await this.drawHighlights()}async deleteHighlight(e){var t,n;(t=this.api)!=null&&t.deleteAnnotation?(n=this.api)==null||n.deleteAnnotation(e).then(async()=>{this.deleteLocalHighlight(e.id)}):this.deleteLocalHighlight(e.id)}async deleteSelectedHighlight(e){var t;(t=this.api)!=null&&t.deleteAnnotation?this.api.deleteAnnotation(e).then(async()=>{this.deleteLocalHighlight(e.id)}):this.deleteLocalHighlight(e.id)}async updateAnnotation(e){var t;(t=this.api)!=null&&t.updateAnnotation?this.api.updateAnnotation(e).then(async()=>{this.updateLocalHighlight(e)}):this.updateLocalHighlight(e)}async saveAnnotation(e){var n,i,o;if(this.annotator){var t=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let s=(n=this.navigator.view)==null?void 0:n.getCurrentPosition(),c=this.navigator.iframes[0].contentDocument;if(c){let f=lo(c,"body"),u=e.position?e.position/f.scrollHeight:s,y=(0,Uw.v4)(),m;if(t){let _=t.Href;if(_.indexOf("#")>0&&(_=_.slice(0,_.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let v=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),g=Math.ceil((u??0)*(v.length-1));m={...v[g],id:y,href:_,created:new Date,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}else m={id:y,href:_,locations:{progression:u},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}if(m)if((i=this.navigator.consumptionModule)==null||i.trackAction(m,"HighlightCreated"),(o=this.api)!=null&&o.addAnnotation)try{let _=await this.api.addAnnotation(m),v=await this.annotator.saveAnnotation(_);return await this.showHighlights(),await this.drawHighlights(),new Promise(g=>g(v))}catch{await this.showHighlights(),await this.drawHighlights()}else{let _=await this.annotator.saveAnnotation(m);return await this.showHighlights(),await this.drawHighlights(),new Promise(v=>v(_))}}}return new Promise(s=>s(null))}getAnnotations(){let e=[];return this.annotator&&(e=this.annotator.getAnnotations()),e}showHighlights(){let e=[];this.annotator&&(e=this.annotator.getAnnotations(),e&&(e=e.filter(t=>t.highlight.marker!==2),e.forEach(t=>{er.push(t.highlight)}))),this.highlightsView&&this.createTree(1,e,this.highlightsView)}async drawHighlights(){var t,n,i,o;if(this.rights.enableAnnotations&&this.highlighter){if(this.api){let s=[];if(this.annotator&&(s=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&s&&((t=this.navigator.iframes[0].contentDocument)==null?void 0:t.readyState)==="complete"){await this.highlighter.destroyHighlights(0);for(let c of s){er.push(c.highlight);let f=c,u=this.navigator.currentChapterLink.href;var e=this.publication.getTOCItem(u);if(this.navigator.currentTocUrl!==void 0&&(e=this.publication.getTOCItem(this.navigator.currentTocUrl)),e===null&&(e=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),e){let y=e.Href;y.indexOf("#")>0&&(y=y.slice(0,y.indexOf("#"))),f.href===y&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,c.highlight),setTimeout(async()=>{var m,_;if(((m=f.highlight)==null?void 0:m.marker)===1){let g='<div class="comment" style="top: '+await((_=this.annotator)==null?void 0:_.getAnnotationPosition(c.id,this.navigator.iframes[0].contentWindow))+'px;width:20px"></div>',h=document.createElement("div");h.innerHTML=g;let l=h.childNodes[0],p=document.createElement("i");p.innerHTML="sticky_note_2",p.className="material-icons",p.style.color=f.highlight.color,l.appendChild(p),_e(h,"click",w=>{w.preventDefault(),w.stopPropagation(),this.scrollToHighlight(f.id)})}},100))}}}}else{let s=[];if(this.annotator&&(s=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&s&&((n=this.navigator.iframes[0].contentDocument)==null?void 0:n.readyState)==="complete"){await this.highlighter.destroyHighlights(0);for(let c of s){er.push(c.highlight);let f=c,u=this.navigator.currentChapterLink.href,y=this.publication.getTOCItem(u);if(this.navigator.currentTocUrl&&(y=this.publication.getTOCItem(this.navigator.currentTocUrl)),y===null&&(y=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),y){let m=y.Href;m.indexOf("#")>0&&(m=m.slice(0,m.indexOf("#"))),f.href===m&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,c.highlight),setTimeout(async()=>{var _,v,g;if(((_=f.highlight)==null?void 0:_.marker)===1){let l='<div class="comment" style="top: '+await((v=this.annotator)==null?void 0:v.getAnnotationPosition(c.id,this.navigator.iframes[0].contentWindow))+"px;background: "+((g=f.highlight)==null?void 0:g.color)+';width:20px"></div>',p=document.createElement("div");p.innerHTML=l,p.childNodes[0].innerHTML=pi.note,_e(p,"click",w=>{w.preventDefault(),w.stopPropagation(),this.scrollToHighlight(f.id)})}},100))}}}}(i=this.properties)!=null&&i.initialAnnotationColor&&this.highlighter.setColor((o=this.properties)==null?void 0:o.initialAnnotationColor),this.repositionGutters()}}repositionGutters(){var t,n,i,o,s,c;let e=this.navigator.iframes[0].contentDocument;if(e&&(this.commentGutter=e.getElementById("R2_ID_GUTTER_RIGHT_CONTAINER"),(t=this.navigator.view)!=null&&t.isScrollMode()&&((n=this.properties)!=null&&n.enableComments)?(i=this.commentGutter)==null||i.style.removeProperty("display"):(o=this.commentGutter)==null||o.style.setProperty("display","none"),this.commentGutter&&((s=this.navigator.view)!=null&&s.isScrollMode())&&((c=this.properties)!=null&&c.enableComments))){this.commentGutter.innerHTML="";let f=[];this.annotator&&(f=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href),f&&(f=f.filter(u=>{var y,m;return((m=(y=u.highlight)==null?void 0:y.note)==null?void 0:m.length)>0}),f=this.syncPosition(f),f=this.reposition(f),f.forEach(u=>{var b,E;let y=document.createElement("i");y.innerHTML="sticky_note_2",y.className="material-icons",y.style.color=u.highlight.color;let m=e.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),_,v;m&&(_=m.querySelector(`#${u.highlight.id}`)),v=_.getElementsByClassName(Ur)[0];let h=parseInt(v.style.height.replace("px","")),l=u.highlight.position,p=e.createElement("div");p.setAttribute("style",`position: absolute;top:${l}px;display: flex;max-width: 250px !important;height:${h}px;width: 200px;align-items: center;`);let w=e.createElement("div");p.appendChild(w);let A=u.highlight.color;Jt.isHexColor(A)&&(A=Jt.hexToRgbChannels(A)),p.innerHTML=Na("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="8"/>',"icon open",10,`rgba(${A.red}, ${A.green}, ${A.blue}, 1) !important`);let C=e.createElement("div");C.innerHTML=(b=u.highlight)==null?void 0:b.note,C.setAttribute("style",`height:${h}px;overflow: hidden;padding-left: 5px;`),p.appendChild(C),_e(p,"click",k=>{k.preventDefault(),k.stopPropagation(),this.scrollToHighlight(u.highlight.id)}),(E=this.commentGutter)==null||E.appendChild(p)})))}}createTree(e,t,n){if(t){let i=this,o=this.publication.readingOrder;if(o.length){let s=(c,f)=>{let u=document.createElement("ul");u.className="sidenav-annotations";for(let y of f){let m=document.createElement("li"),_=document.createElement("a"),v=document.createElement("span");if(_.tabIndex=-1,_.className="chapter-link",y.Href){let h=this.publication.getAbsoluteHref(y.Href),l=this.publication.getTOCItemAbsolute(h);_.href=h,_.innerHTML=(l==null?void 0:l.Title)||"",m.appendChild(_)}else v.innerHTML=y.Title||"",v.className="chapter-title",m.appendChild(v);_e(_,"click",h=>{h.preventDefault(),h.stopPropagation();let l={href:_.href,locations:{progression:0},type:y.TypeLink,title:_.title};this.navigator.stopReadAloud(),this.navigator.navigate(l)});let g=document.createElement("ol");t.forEach(function(h){var p,w,A,C,b,E,k;let l=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&h.href.endsWith(l)){let P=document.createElement("li");P.className="annotation-item";let N=document.createElement("a");if(N.setAttribute("href",h.href),e===1){N.className="highlight-link";let F=document.createElement("span"),B=document.createElement("span");if(F.className="title",B.innerHTML=h.highlight.selectionInfo.cleanText,((p=h.highlight)==null?void 0:p.marker)===1)if(typeof((w=h.highlight)==null?void 0:w.color)=="object"){let G=(A=h.highlight)==null?void 0:A.color;G&&B.style.setProperty("border-bottom",`2px solid ${Jt.hexToRgbA(G)}`,"important")}else B.style.setProperty("border-bottom",`2px solid ${(C=h.highlight)==null?void 0:C.color}`,"important");else if(typeof((b=h.highlight)==null?void 0:b.color)=="object"){let G=(E=h.highlight)==null?void 0:E.color;G&&(B.style.backgroundColor=Jt.hexToRgbA(G))}else{let G=(k=h.highlight)==null?void 0:k.color;G&&(B.style.backgroundColor=G)}F.appendChild(B),N.appendChild(F);let V=document.createElement("span"),q=Math.round((h.locations.progression??0)*100)+"% through resource";V.className="subtitle",V.innerHTML=q,N.appendChild(V)}let D=document.createElement("span");if(D.className="timestamp",D.innerHTML=r.readableTimestamp(h.created),N.appendChild(D),_e(N,"click",F=>{F.preventDefault(),F.stopPropagation(),i.handleAnnotationLinkClick(F,h)}),P.appendChild(N),i.navigator.sideNavExpanded){let F=document.createElement("button");F.className="delete",F.innerHTML=pi.delete,_e(F,"click",B=>{B.preventDefault(),B.stopPropagation(),i.handleAnnotationLinkDeleteClick(e,B,h)}),P.appendChild(F)}g.appendChild(P)}}),g.children.length>0&&(u.appendChild(m),u.appendChild(g)),u.children.length>0&&c.appendChild(u),y.Children&&y.Children.length>0&&s(c,y.Children)}};n.innerHTML="",s(n,o)}}}handleAnnotationLinkClick(e,t){t?(t.href=this.publication.getAbsoluteHref(t.href),this.navigator.stopReadAloud(),this.navigator.navigate(t)):ei.default.log("annotation data missing: ",e)}handleAnnotationLinkDeleteClick(e,t,n){ei.default.log("annotation data locator: ",n),n?e===1&&this.deleteHighlight(n):ei.default.log("annotation data missing: ",t)}static readableTimestamp(e){let t=new Date(e);return t.toDateString()+" "+t.toLocaleTimeString()}async getAnnotation(e){var t;return(t=this.annotator)==null?void 0:t.getAnnotation(e)}async getAnnotationByID(e){var t;return(t=this.annotator)==null?void 0:t.getAnnotationByID(e)}syncPosition(e){let t=this.navigator.iframes[0].contentDocument,n=(i,o)=>{let s=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),c,f;s&&(c=s.querySelector(`#${o.highlight.id}`)),f=c.getElementsByClassName(Ur)[0];let y=parseInt(f.style.top.replace("px","")),m={...o,highlight:{...o.highlight,position:y}};return[...i,m]};return e.reduce(n,[])}reposition(e){let t=this.navigator.iframes[0].contentDocument,n=(i,o,s)=>{let c=e[0],f=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),u,y;f&&(u=f.querySelector(`#${c.highlight.id}`)),y=u.getElementsByClassName(Ur)[0];let _=parseInt(y.style.height.replace("px","")),v=o.highlight.position,g=i[s-1]&&i[s-1].highlight.position,l=s===0?0:g+_+0,p=l>v?l:v,w={...o,highlight:{...o.highlight,position:p}};return[...i,w]};return e.sort(function(i,o){return i.highlight.position-o.highlight.position}).reduce(n,[])}};L();var f1=rt(d1());var ti=rt($t());var ja=class r{static async create(e){let t=new this(e.annotator,e.rights||{enableBookmarks:!1},e.publication,e,e.initialAnnotations,e.api,e.headerMenu);return await t.start(),new Promise(n=>n(t))}constructor(e,t,n,i,o,s,c){this.annotator=e,this.rights=t,this.publication=n,this.headerMenu=c,this.initialAnnotations=o,this.properties=i,this.api=s}stop(){ti.default.log("Bookmark module stop")}async start(){var e,t;if(this.headerMenu&&(this.bookmarksView=Ne(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=Ne(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){let n=Ne(this.headerMenu,"#menu-button-bookmark");n&&((e=n.parentElement)==null||e.style.removeProperty("display")),n&&_e(n,"click",this.saveBookmark.bind(this))}if(this.initialAnnotations){let n=this.initialAnnotations.bookmarks||null;n&&((t=this.annotator)==null||t.initBookmarks(n))}}async handleResize(){setTimeout(async()=>{await this.drawBookmarks(),await this.showBookmarks(),setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)},100)}initialize(){return new Promise(async e=>{await document.fonts.ready,this.rights.enableBookmarks&&setTimeout(()=>{this.drawBookmarks(),this.showBookmarks()},300),e(null)})}async deleteBookmark(e){var t,n;if(this.annotator)if((t=this.api)!=null&&t.deleteBookmark){await((n=this.api)==null?void 0:n.deleteBookmark(e));let i=await this.annotator.deleteBookmark(e);return ti.default.log("Bookmark deleted "+JSON.stringify(i)),await this.showBookmarks(),await this.drawBookmarks(),i}else{let i=await this.annotator.deleteBookmark(e);return ti.default.log("Bookmark deleted "+JSON.stringify(i)),await this.showBookmarks(),await this.drawBookmarks(),i}else return new Promise(i=>i(null))}async saveBookmarkPlus(){await this.addBookmarkPlus()}async saveBookmark(){var t,n,i;if(this.annotator){var e=this.publication.getTOCItem(this.navigator.currentChapterLink.href);if(this.navigator.currentTocUrl&&(e=this.publication.getTOCItem(this.navigator.currentTocUrl)),e===void 0&&(e=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),e){let o=e.Href;o.indexOf("#")>0&&(o=o.slice(0,o.indexOf("#")));let s=(t=this.navigator.view)==null?void 0:t.getCurrentPosition(),c=(0,f1.v4)(),f;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let u=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),y=Math.ceil((s??0)*(u.length-1));f={...u[y],id:c,href:o,created:new Date,title:this.navigator.currentChapterLink.title}}else f={id:c,href:o,locations:{progression:s},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title};if(!this.annotator.locatorExists(f,0))if((n=this.navigator.consumptionModule)==null||n.trackAction(f,"BookmarkCreated"),(i=this.api)!=null&&i.addBookmark){let u=await this.api.addBookmark(f);u&&(f=u),ti.default.log(f);let y=this.annotator.saveBookmark(f);return ti.default.log("Bookmark added "+JSON.stringify(y)),this.showBookmarks(),await this.drawBookmarks(),y}else{let u=this.annotator.saveBookmark(f);return ti.default.log("Bookmark added "+JSON.stringify(u)),this.showBookmarks(),await this.drawBookmarks(),u}}}}async addBookmarkPlus(){var c,f,u,y,m,_,v,g,h,l,p,w,A;let e=this,t=(c=this.navigator.highlighter)==null?void 0:c.visibleTextRects[0],n=this.navigator.iframes[0].contentDocument;if(n){let C=(f=this.navigator.highlighter)==null?void 0:f.dom(n.body).getWindow().document.createRange(),b=(y=this.navigator.highlighter)==null?void 0:y.dom((u=this.navigator.iframes[0].contentDocument)==null?void 0:u.body).getSelection();b.removeAllRanges(),t&&C.selectNodeContents(t.node),b.addRange(C);let E=Rf(C,!1),k=0;for(let P of E){if(!((m=this.navigator.highlighter)!=null&&m.isOutsideViewport(P))){let N=b.focusNode,D=b.focusOffset;b.collapse(b.anchorNode,b.anchorOffset);for(let q=0;q<k;q++)b.modify("move","forward","line");b.extend(N,D);let F=b.focusNode,B=b.focusNode.length;b.collapse(b.anchorNode,b.anchorOffset);let V=B;b.anchorOffset>B?V=B:V=b.anchorOffset+1,b.modify("move","forward","character"),b.modify("move","backward","word"),b.extend(F,V),b.modify("extend","backward","character"),b.modify("extend","forward","word");break}k++}}function i(C){var k;let b={},E=e.navigator.iframes[0].contentDocument;if(E)return Ar(C,(k=e.navigator.highlighter)==null?void 0:k.dom(E.body).getDocument(),b)}let o=this.navigator.iframes[0].contentWindow,s={id:"bookmarkIcon",marker:2,icon:{id:"bookmarkIcon",title:"Bookmark",svgPath:'<path d="M0 0h24v24H0V0z" fill="none"/><path d="M17 3H7c-1.1 0-2 .9-2 2v16l7-3 7 3V5c0-1.1-.9-2-2-2z"/>',color:"#000000",position:"left"},popup:{background:"#000000",textColor:"#ffffff"},highlight:{color:"#000000",style:{default:[{property:"border-bottom",value:"0px dashed #000000",priority:"important"}]}}};if(o!==null){let C=Hi(o,i);if(C===void 0){let E=e.navigator.iframes[0].contentDocument;C=(v=(_=this.navigator.annotationModule)==null?void 0:_.annotator)==null?void 0:v.getTemporarySelectionInfo(E)}let b=e.navigator.iframes[0].contentDocument;if(C&&b){let E=(p=this.navigator.highlighter)==null?void 0:p.createHighlight((g=this.navigator.highlighter)==null?void 0:g.dom(b.body).getWindow(),C,(h=s.highlight)==null?void 0:h.color,!0,2,s.icon,s.popup,(l=s.highlight)==null?void 0:l.style);if((A=(w=this.navigator.iframes[0].contentDocument)==null?void 0:w.getSelection())==null||A.removeAllRanges(),E)return this.saveAnnotation(E[0]).then(k=>{ti.default.log("saved bookmark "+(k==null?void 0:k.id))})}}}async saveAnnotation(e){var n,i,o;if(this.annotator){var t=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===null&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let s=(n=this.navigator.view)==null?void 0:n.getCurrentPosition(),c=this.navigator.iframes[0].contentDocument;if(c){let f=lo(c,"body"),u=e.position?e.position/f.scrollHeight:s,y=(0,f1.v4)(),m;if(t){let _=t.Href;if(_.indexOf("#")>0&&(_=_.slice(0,_.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let v=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),g=Math.ceil((u??0)*(v.length-1));m={...v[g],id:y,href:_,created:new Date,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}else m={id:y,href:_,locations:{progression:u},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}if(m)if((i=this.navigator.consumptionModule)==null||i.trackAction(m,"BookmarkCreated"),(o=this.api)!=null&&o.addBookmark){let _=await this.api.addBookmark(m),v=await this.annotator.saveAnnotation(_);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(g=>g(v))}else{let _=await this.annotator.saveAnnotation(m);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(v=>v(_))}}}return new Promise(s=>s(void 0))}getBookmarks(){let e=[];return this.annotator&&(e=this.annotator.getBookmarks()),e}showBookmarks(){let e=[];this.annotator&&(e=this.annotator.getBookmarks());let t=[];this.annotator&&(t=this.annotator.getAnnotations(),t&&(t=t.filter(n=>n.highlight.marker===2),e?e.push.apply(e,t):e=t)),this.bookmarksView&&this.createTree(0,e,this.bookmarksView)}async drawBookmarks(){var t,n;if(this.rights.enableBookmarks&&this.navigator.highlighter)if(this.api){let i=[];if(this.annotator&&(i=await this.annotator.getAnnotations()),this.navigator.highlighter&&i&&((t=this.navigator.iframes[0].contentDocument)==null?void 0:t.readyState)==="complete"){await this.navigator.highlighter.destroyHighlights(0);for(let o of i){er.push(o.highlight);let s=o,c=this.navigator.currentChapterLink.href;var e=this.publication.getTOCItem(c);if(this.navigator.currentTocUrl&&(e=this.publication.getTOCItem(this.navigator.currentTocUrl)),e===void 0&&(e=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),e){let f=e.Href;f.indexOf("#")>0&&(f=f.slice(0,f.indexOf("#"))),s.href===f&&await this.navigator.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,o.highlight)}}}}else{let i=[];if(this.annotator&&(i=await this.annotator.getAnnotations()),this.navigator.highlighter&&i&&((n=this.navigator.iframes[0].contentDocument)==null?void 0:n.readyState)==="complete"){await this.navigator.highlighter.destroyHighlights(0);for(let o of i){er.push(o.highlight);let s=o,c=this.navigator.currentChapterLink.href,f=this.publication.getTOCItem(c);if(this.navigator.currentTocUrl&&(f=this.publication.getTOCItem(this.navigator.currentTocUrl)),f===void 0&&(f=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),f){let u=f.Href;u.indexOf("#")>0&&(u=u.slice(0,u.indexOf("#"))),s.href===u&&await this.navigator.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,o.highlight)}}}}}async deleteSelectedHighlight(e){var t;(t=this.api)!=null&&t.deleteBookmark?this.api.deleteBookmark(e).then(async()=>{this.deleteLocalHighlight(e.id)}):this.deleteLocalHighlight(e.id)}async deleteLocalHighlight(e){if(this.annotator){var t=await this.annotator.deleteAnnotation(e);return ti.default.log("Highlight deleted "+JSON.stringify(t)),await this.showBookmarks(),await this.drawBookmarks(),t}else return new Promise(n=>n(null))}createTree(e,t,n){if(t){let i=this,o=this.publication.readingOrder;if(o.length){let s=(c,f)=>{let u=document.createElement("ul");u.className="sidenav-annotations";for(let y of f){let m=document.createElement("li"),_=document.createElement("a"),v=document.createElement("span");if(_.tabIndex=-1,_.className="chapter-link",y.Href){let h=this.publication.getAbsoluteHref(y.Href),l=this.publication.getTOCItemAbsolute(h);_.href=h,_.innerHTML=(l==null?void 0:l.Title)||"",m.appendChild(_)}else v.innerHTML=y.Title||"",v.className="chapter-title",m.appendChild(v);_e(_,"click",h=>{h.preventDefault(),h.stopPropagation();let l={href:_.href,locations:{progression:0},type:y.TypeLink,title:_.title};this.navigator.stopReadAloud(),this.navigator.navigate(l)});let g=document.createElement("ol");t.forEach(function(h){let l=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&h.href.endsWith(l)){let p=document.createElement("li");p.className="annotation-item";let w=document.createElement("a");if(w.setAttribute("href",h.href),e===0){w.className="bookmark-link";let C=document.createElement("span"),b=Math.round((h.locations.progression??0)*100)+"% through resource";C.className="title",C.innerHTML=b,w.appendChild(C)}let A=document.createElement("span");if(A.className="timestamp",A.innerHTML=r.readableTimestamp(h.created),w.appendChild(A),_e(w,"click",C=>{C.preventDefault(),C.stopPropagation(),i.handleAnnotationLinkClick(C,h)}),p.appendChild(w),i.navigator.sideNavExpanded){let C=document.createElement("button");C.className="delete",C.innerHTML=pi.delete,_e(C,"click",b=>{b.preventDefault(),b.stopPropagation(),i.handleAnnotationLinkDeleteClick(e,b,h)}),p.appendChild(C)}g.appendChild(p)}}),g.children.length>0&&(u.appendChild(m),u.appendChild(g)),u.children.length>0&&c.appendChild(u),y.Children&&y.Children.length>0&&s(c,y.Children)}};n.innerHTML="",s(n,o)}}}handleAnnotationLinkClick(e,t){t?(t.href=this.publication.getAbsoluteHref(t.href),this.navigator.stopReadAloud(),this.navigator.navigate(t)):ti.default.log("bookmark data missing: ",e)}handleAnnotationLinkDeleteClick(e,t,n){ti.default.log("bookmark data locator: ",n),n?e===0&&this.deleteBookmark(n):ti.default.log("bookmark data missing: ",t)}static readableTimestamp(e){let t=new Date(e);return t.toDateString()+" "+t.toLocaleTimeString()}async getAnnotation(e){var t;return(t=this.annotator)==null?void 0:t.getAnnotation(e)}async getAnnotationByID(e){var t;return(t=this.annotator)==null?void 0:t.getAnnotationByID(e)}};L();var Gw=rt(qw());L();var fn=rt($t()),p1="r2-mo-active",Ir=class Ir{};Ir.COLOR_REF="color",Ir.AUTO_SCROLL_REF="autoscroll",Ir.AUTO_TURN_REF="autoturn",Ir.VOLUME_REF="volume",Ir.RATE_REF="rate",Ir.COLOR_KEY="mediaoverlay-"+Ir.COLOR_REF,Ir.AUTO_SCROLL_KEY="mediaoverlay-"+Ir.AUTO_SCROLL_REF,Ir.AUTO_TURN_KEY="mediaoverlay-"+Ir.AUTO_TURN_REF,Ir.VOLUME_KEY="mediaoverlay-"+Ir.VOLUME_REF,Ir.RATE_KEY="mediaoverlay-"+Ir.RATE_REF;var ot=Ir,Bf=class{constructor(e,t,n){this.MEDIAOVERLAYSETTINGS="mediaOverlaySetting";this.color="r2-mo-active";this.autoScroll=!0;this.autoTurn=!0;this.volume=1;this.rate=1;this.playing=!1;this.resourceReady=!1;this.wait=1;this.settingsChangeCallback=()=>{};this.store=e,this.api=t,this.headerMenu=n,this.initialise(),fn.default.log(this.api)}static create(e){let t=new this(e.store,e.api,e.headerMenu);if(e.initialMediaOverlaySettings){let n=e.initialMediaOverlaySettings;n!=null&&n.color&&(t.color=n.color,fn.default.log(t.color)),n!=null&&n.autoScroll&&(t.autoScroll=n.autoScroll,fn.default.log(t.autoScroll)),n!=null&&n.autoTurn&&(t.autoTurn=n.autoTurn,fn.default.log(t.autoScroll)),n!=null&&n.volume&&(t.volume=n.volume,fn.default.log(t.volume)),n!=null&&n.rate&&(t.rate=n.rate,fn.default.log(t.rate)),n!=null&&n.wait&&(t.wait=n.wait,fn.default.log(t.wait))}return t.initializeSelections(),t}stop(){fn.default.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(ot.AUTO_SCROLL_KEY)!=null?this.getProperty(ot.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(ot.AUTO_TURN_KEY)!=null?this.getProperty(ot.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(ot.COLOR_KEY)!=null?this.getProperty(ot.COLOR_KEY).value:this.color,this.volume=this.getProperty(ot.VOLUME_KEY)!=null?this.getProperty(ot.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(ot.RATE_KEY)!=null?this.getProperty(ot.RATE_KEY).value:this.rate,this.userProperties=this.getMediaOverlaySettings()}reset(){this.color="redtext",this.autoScroll=!0,this.autoTurn=!0,this.volume=1,this.rate=1,this.wait=1,this.userProperties=this.getMediaOverlaySettings()}initializeSelections(){this.headerMenu&&(this.settingsView=Ne(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(e){this.headerMenu&&(this.speechAutoTurn=Ne(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=Ne(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=Ne(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=Ne(this.headerMenu,"#mediaOverlayRate")),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),this.speechAutoTurn&&(this.speechAutoTurn.checked=this.autoTurn),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechRate&&(this.speechRate.value=this.volume.toString()),_e(Ne(e,"ul"),"click",t=>{t.stopPropagation()})}onSettingsChange(e){this.settingsChangeCallback=e}storeProperty(e){this.updateUserSettings(),this.saveProperty(e)}updateUserSettings(){var t,n,i,o,s,c,f;let e={color:(t=this.userProperties.getByRef(ot.COLOR_REF))==null?void 0:t.value,autoScroll:(n=this.userProperties.getByRef(ot.AUTO_SCROLL_REF))==null?void 0:n.value,autoTurn:(i=this.userProperties.getByRef(ot.AUTO_TURN_REF))==null?void 0:i.value,volume:(o=this.userProperties.getByRef(ot.VOLUME_REF))==null?void 0:o.value,rate:(s=this.userProperties.getByRef(ot.RATE_REF))==null?void 0:s.value};this.applyMediaOverlaySettings(e),(c=this.api)!=null&&c.updateSettings&&((f=this.api)==null||f.updateSettings(e).then(async u=>{fn.default.log("api updated sync settings",u)}))}getMediaOverlaySettings(){let e=new ki;return e.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,ot.AUTO_SCROLL_REF,ot.AUTO_SCROLL_KEY),e.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,ot.AUTO_TURN_REF,ot.AUTO_TURN_KEY),e.addStringable(this.color,ot.COLOR_REF,ot.COLOR_KEY),e.addIncremental(this.volume,.1,1,.1,"",ot.VOLUME_REF,ot.VOLUME_KEY),e.addIncremental(this.rate,.1,3,.1,"",ot.RATE_REF,ot.RATE_KEY),e}saveProperty(e){let t=this.store.get(this.MEDIAOVERLAYSETTINGS);if(t){let n=JSON.parse(t);n=n.filter(i=>i.name!==e.name),n.push(e),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(n))}else{let n=[];n.push(e),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(n))}return e}getProperty(e){let t=this.store.get(this.MEDIAOVERLAYSETTINGS);if(t){let n=JSON.parse(t);return n=n.filter(i=>i.name===e),n.length===0?null:n[0]}return null}resetMediaOverlaySettings(){this.store.remove(this.MEDIAOVERLAYSETTINGS),this.reset(),this.settingsChangeCallback()}applyMediaOverlaySettings(e){if(e.color){this.color=e.color;let t=this.userProperties.getByRef(ot.COLOR_REF);t&&(t.value=this.color,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoScroll!==void 0){fn.default.log("autoScroll "+this.autoScroll),this.autoScroll=e.autoScroll;let t=this.userProperties.getByRef(ot.AUTO_SCROLL_REF);t&&(t.value=this.autoScroll,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoTurn!==void 0){fn.default.log("autoTurn "+this.autoTurn),this.autoTurn=e.autoTurn;let t=this.userProperties.getByRef(ot.AUTO_TURN_REF);t&&(t.value=this.autoTurn,this.saveProperty(t)),this.settingsChangeCallback()}if(e.volume){fn.default.log("volume "+this.volume),this.volume=e.volume;let t=this.userProperties.getByRef(ot.VOLUME_REF);t&&(t.value=this.volume,this.saveProperty(t)),this.settingsChangeCallback()}if(e.rate){fn.default.log("rate "+this.rate),this.rate=e.rate;let t=this.userProperties.getByRef(ot.RATE_REF);t&&(t.value=this.rate,this.saveProperty(t)),this.settingsChangeCallback()}}applyMediaOverlaySetting(e,t){if(e===ot.COLOR_REF){this.color=t;let n=this.userProperties.getByRef(ot.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}else if(e===ot.AUTO_SCROLL_REF){this.autoScroll=t;let n=this.userProperties.getByRef(ot.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}else if(e===ot.AUTO_TURN_REF){this.autoTurn=t;let n=this.userProperties.getByRef(ot.AUTO_TURN_REF);n&&(n.value=this.autoTurn,this.saveProperty(n)),this.settingsChangeCallback()}}increase(e){var t,n;if(e==="mo_volume"){this.userProperties.getByRef(ot.VOLUME_REF).increment(),this.volume=(t=this.userProperties.getByRef(ot.VOLUME_REF))==null?void 0:t.value;let i=this.userProperties.getByRef(ot.VOLUME_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}else if(e==="mo_rate"){this.userProperties.getByRef(ot.RATE_REF).increment(),this.rate=(n=this.userProperties.getByRef(ot.RATE_REF))==null?void 0:n.value;let i=this.userProperties.getByRef(ot.RATE_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}}decrease(e){var t,n;if(e==="mo_volume"){this.userProperties.getByRef(ot.VOLUME_REF).decrement(),this.volume=(t=this.userProperties.getByRef(ot.VOLUME_REF))==null?void 0:t.value;let i=this.userProperties.getByRef(ot.VOLUME_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}else if(e==="mo_rate"){this.userProperties.getByRef(ot.RATE_REF).decrement(),this.rate=(n=this.userProperties.getByRef(ot.RATE_REF))==null?void 0:n.value;let i=this.userProperties.getByRef(ot.RATE_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}}};var Ze=rt($t()),Ga=class{constructor(e,t,n){this.play=Ne(document,"#menu-button-play");this.pause=Ne(document,"#menu-button-pause");this.currentLinkIndex=0;this.pid=void 0;this.__ontimeupdate=!1;this.ontimeupdate=async e=>{Ze.default.log("ontimeupdate"),this.trackCurrentTime()};this.ensureOnTimeUpdate=(e,t)=>{e?this.__ontimeupdate&&(this.__ontimeupdate=!1,this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),cancelAnimationFrame(this.myReq)):(!this.__ontimeupdate||t)&&(this.__ontimeupdate=!0,t&&(this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),this.audioElement.addEventListener("timeupdate",this.ontimeupdate)))};this.publication=e,this.settings=t,this.properties=n}static create(e){let t=new this(e.publication,e.settings,e);return t.start(),t}stop(){Ze.default.log("MediaOverlay module stop")}start(){Ze.default.log("MediaOverlay module start")}async initialize(){return new Promise(async e=>{await document.fonts.ready,this.settings.setControls(),this.settings.onSettingsChange(()=>{this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}),e()})}async initializeResource(e){this.currentLinks=e,this.currentLinkIndex=0,await this.playLink()}async playLink(){var t,n;let e=this.currentLinks[this.currentLinkIndex];if((t=e==null?void 0:e.Properties)!=null&&t.MediaOverlay){this.ensureOnTimeUpdate(!1,!1);let i=(n=e.Properties)==null?void 0:n.MediaOverlay,s=new URL(i,this.publication.manifestUrl).toString(),c;try{c=await fetch(s,this.navigator.requestConfig)}catch(m){console.error(m,s);return}c.ok||Ze.default.log("BAD RESPONSE?!");let f;try{f=await c.json()}catch(m){console.error(m)}if(!f){Ze.default.log("## moJson"+f);return}e.MediaOverlays=ba(f,Gw.MediaOverlayNode),e.MediaOverlays.initialized=!0;let u=e.HrefDecoded||e.Href,y=new URL("https://dita.digital/"+u);await this.playMediaOverlays(y.pathname.substr(1),e.MediaOverlays,void 0)}else this.audioElement&&await this.audioElement.pause(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement&&await this.audioElement.pause(),this.navigator.nextResource()):await this.stopReadAloud()}async startReadAloud(){var e;if(this.navigator.rights.enableMediaOverlays){if(this.settings.playing=!0,this.audioElement&&((e=this.currentLinks[this.currentLinkIndex])!=null&&e.Properties.MediaOverlay)){let t=this.currentAudioBegin?this.currentAudioBegin:0;this.audioElement.currentTime=t,await this.audioElement.play(),this.ensureOnTimeUpdate(!1,!0),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}else this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?this.navigator.nextResource():await this.stopReadAloud();this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display")}}async stopReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement&&this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}pauseReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}async resumeReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!0,await this.audioElement.play(),this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"))}findDepthFirstTextAudioPair(e,t,n){Ze.default.log("findDepthFirstTextAudioPair()");let i,o;if(t.Text){let f=new URL("https://dita.digital/"+t.Text);if(f.pathname.substr(1)===e){if(i=!0,f.hash&&n){o=!1;let u=f.hash.substr(1);for(let y of n)if(y===u){o=!0;break}}}else i=!1}if(Ze.default.log("isFragmentIDMatch: "+o),Ze.default.log("isTextUrlMatch: "+i),!t.Children||!t.Children.length){if(Ze.default.log("findDepthFirstTextAudioPair() - leaf text/audio pair"),!i){Ze.default.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch");return}return o||i&&!n?(Ze.default.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),t):void 0}let s=n,c=n;for(let f of t.Children){Ze.default.log("findDepthFirstTextAudioPair() - child"),Ze.default.log(JSON.stringify(f));let u=this.findDepthFirstTextAudioPair(e,f,c);if(u===null&&(Ze.default.log("findDepthFirstTextAudioPair() - child - match null (skip)"),c=void 0),u)return Ze.default.log("findDepthFirstTextAudioPair() - child - match"),Ze.default.log(JSON.stringify(u)),u}if(o){Ze.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch");let f=this.findDepthFirstTextAudioPair(e,t,void 0);return f&&(Ze.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch - match"),Ze.default.log(JSON.stringify(f)),f)}if(s&&!c)return null}trackCurrentTime(){if(cancelAnimationFrame(this.myReq),this.mediaOverlayTextAudioPair)try{this.currentAudioEnd&&this.audioElement.currentTime>=this.currentAudioEnd-.05&&(Ze.default.log("ontimeupdate - mediaOverlaysNext()"),this.mediaOverlaysNext());let e=this.mediaOverlayTextAudioPair.Text.lastIndexOf("#"),t=this.mediaOverlayTextAudioPair.Text.substr(e+1);this.mediaOverlayHighlight(t),this.myReq=requestAnimationFrame(this.trackCurrentTime.bind(this))}catch{}}mediaOverlaysNext(e){if(Ze.default.log("mediaOverlaysNext()"),this.mediaOverlayRoot&&this.mediaOverlayTextAudioPair){let t=this.findNextTextAudioPair(this.mediaOverlayRoot,this.mediaOverlayTextAudioPair,{prev:void 0},!!e);if(!t)Ze.default.log("mediaOverlaysNext() - navLeftOrRight()"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud());else{let n=!1;if(this.mediaOverlayTextAudioPair.Text&&t.Text){let i=new URL("https://dita.digital/"+this.mediaOverlayTextAudioPair.Text),o=new URL("https://dita.digital/"+t.Text);i.pathname!==o.pathname&&(Ze.default.log("mediaOverlaysNext() SWITCH! "+i.pathname+" != "+o.pathname),n=!0)}n?this.mediaOverlaysStop():(Ze.default.log("mediaOverlaysNext() - playMediaOverlaysAudio()"),setTimeout(async()=>{await this.playMediaOverlaysAudio(t,void 0,void 0)},0))}}else Ze.default.log("mediaOverlaysNext() - navLeftOrRight() 2"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud())}mediaOverlaysStop(){Ze.default.log("mediaOverlaysStop()"),this.mediaOverlaysPause(),this.mediaOverlayRoot=void 0,this.mediaOverlayTextAudioPair=void 0}mediaOverlaysPause(){Ze.default.log("mediaOverlaysPause()"),this.mediaOverlayHighlight(void 0),this.audioElement&&this.audioElement.pause()}findNextTextAudioPair(e,t,n,i){if(!e.Children||!e.Children.length){if((n==null?void 0:n.prev)===t)return Ze.default.log("findNextTextAudioPair() - prevMo === moToMatch"),e;Ze.default.log("findNextTextAudioPair() - set previous"),Ze.default.log(JSON.stringify(e)),n.prev=e;return}for(let o of e.Children){Ze.default.log("findNextTextAudioPair() - child"),Ze.default.log(JSON.stringify(o));let s=this.findNextTextAudioPair(o,t,n,i);if(s)return Ze.default.log("findNextTextAudioPair() - match"),Ze.default.log(JSON.stringify(s)),s}}async playMediaOverlaysAudio(e,t,n){if(Ze.default.log("playMediaOverlaysAudio()"),this.mediaOverlayTextAudioPair=e,!e.Audio)return;let i=new URL(e.Audio,this.publication.manifestUrl),o=i.toString(),s=new URL(o);s.hash="",s.search="";let c=s.toString(),f=typeof t<"u",u=typeof n<"u";if(this.previousAudioEnd=this.currentAudioEnd,this.currentAudioBegin=void 0,this.currentAudioEnd=void 0,!f&&!u){if(i.hash){let m=i.hash.match(/t=([0-9.]+)(,([0-9.]+))?/);if(m&&m.length>=1){let _=m[1];try{this.currentAudioBegin=parseFloat(_)}catch(v){Ze.default.error(v)}if(m.length>=3){let v=m[3];try{this.currentAudioEnd=parseFloat(v)}catch(g){Ze.default.error(g)}}}}}else this.currentAudioBegin=t,this.currentAudioEnd=n;Ze.default.log(`${o} => [${this.currentAudioBegin}-${this.currentAudioEnd}]`);let y=async m=>{if(!this.audioElement)return;let _=this.currentAudioBegin?this.currentAudioBegin:0;if(m||this.audioElement.paused)if(m&&!_||this.audioElement.currentTime===_){if(Ze.default.log("playMediaOverlaysAudio() - playClip() - _currentAudioElement.play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing){let g=function(){v.settings.resourceReady?setTimeout(async()=>{await v.audioElement.play(),v.ensureOnTimeUpdate(!1,!0)},v.settings.wait*1e3):setTimeout(g,200)},v=this;g()}}else{Ze.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked");let v=async g=>{if(this.audioElement.removeEventListener("timeupdate",v),Ze.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked - .play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement&&(this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing)){let l=function(){h.settings.resourceReady?setTimeout(async()=>{await h.audioElement.play(),h.ensureOnTimeUpdate(!1,!0)},h.settings.wait*1e3):setTimeout(l,200)},h=this;l()}};this.audioElement.addEventListener("timeupdate",v),this.audioElement.currentTime=_}else{let v=this.previousAudioUrl===this.currentAudioUrl&&typeof this.previousAudioEnd<"u"&&this.previousAudioEnd>_-.02&&this.previousAudioEnd<=_&&this.audioElement.currentTime>=_-.1;this.ensureOnTimeUpdate(!1,!1),v?Ze.default.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"):(Ze.default.log("playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo"),this.audioElement.currentTime=_)}};if(this.previousAudioUrl=this.currentAudioUrl,!this.currentAudioUrl||c!==this.currentAudioUrl){this.currentAudioUrl=c,Ze.default.log("playMediaOverlaysAudio() - RESET: "+this.previousAudioUrl+" => "+this.currentAudioUrl),this.audioElement=document.getElementById("AUDIO_MO_ID"),this.audioElement&&(this.audioElement.pause(),this.audioElement.setAttribute("src",""),this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement)),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("style","display: none"),this.audioElement.setAttribute("id","AUDIO_MO_ID"),this.audioElement.setAttribute("role","media-overlays"),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate,document.body.appendChild(this.audioElement),this.audioElement.addEventListener("error",v=>{Ze.default.log("-1) error: "+(this.currentAudioUrl!==v.currentTarget.src?this.currentAudioUrl+" -- ":"")+v.currentTarget.src.substr(v.currentTarget.src.lastIndexOf("/"))),this.audioElement&&this.audioElement.error&&(Ze.default.log(this.audioElement.error.code),Ze.default.log(this.audioElement.error.message))});let m=async v=>{v.currentTarget.removeEventListener("canplaythrough",m),Ze.default.log("oncanplaythrough"),await y(!0)};this.audioElement.addEventListener("canplaythrough",m);let _=async v=>{Ze.default.log("onended"),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud()};this.audioElement.addEventListener("ended",_),this.audioElement.playbackRate=this.settings.rate,this.audioElement.setAttribute("src",this.currentAudioUrl)}else Ze.default.log("playMediaOverlaysAudio() - playClip()"),await y(!1)}async playMediaOverlays(e,t,n){Ze.default.log("playMediaOverlays()");let i=n?n.filter(s=>s):void 0;i&&i.length===0&&(i=void 0);let o=this.findDepthFirstTextAudioPair(e,t,i);!o&&i&&(Ze.default.log("playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE "),Ze.default.log(JSON.stringify(i,null,4)),Ze.default.log(JSON.stringify(t,null,4)),o=this.findDepthFirstTextAudioPair(e,t,void 0)),o?o.Audio&&(Ze.default.log("playMediaOverlays() - playMediaOverlaysAudio()"),this.mediaOverlayRoot=t,await this.playMediaOverlaysAudio(o,void 0,void 0)):Ze.default.log("playMediaOverlays() - !moTextAudioPair "+e)}mediaOverlayHighlight(e){var c,f,u,y,m,_,v,g,h;Ze.default.log("moHighlight: ## "+e);let t=(f=(c=this.publication.Metadata)==null?void 0:c.MediaOverlay)==null?void 0:f.ActiveClass;t||(t=this.settings.color);let n=(u=this.navigator.iframes[0].contentDocument)==null?void 0:u.documentElement.getAttribute("style"),i=n?n.indexOf("readium-night-on")>0:!1,o=n?n.indexOf("readium-sepia-on")>0:!1;if((((y=this.publication.Metadata.Rendition)==null?void 0:y.Layout)??"unknown")!=="fixed"&&(t=i||o?p1:t||p1),this.pid){let l;this.currentLinkIndex===0?l=(m=this.navigator.iframes[0].contentDocument)==null?void 0:m.getElementById(this.pid):l=(_=this.navigator.iframes[1].contentDocument)==null?void 0:_.getElementById(this.pid),l&&l.classList.remove(t)}let s;e&&(this.currentLinkIndex===0?s=(v=this.navigator.iframes[0].contentDocument)==null?void 0:v.getElementById(e):s=(g=this.navigator.iframes[1].contentDocument)==null?void 0:g.getElementById(e),s&&s.classList.add(t),this.pid=e),s&&(((h=this.publication.Metadata.Rendition)==null?void 0:h.Layout)??"unknown")!=="fixed"&&s.scrollIntoView({block:"center",behavior:"smooth"})}};L();var g1=rt($t()),Wa=class{static async create(e){let t=new this(e.publication);return await t.start(),t}constructor(e){this.publication=e}async stop(){g1.default.log("Timeline module stop")}async start(){this.timelineContainer=Ne(document,"#container-view-timeline"),this.positionSlider=Ne(document,"#positionSlider"),this.publication.positions?this.positionSlider&&(this.positionSlider.style.display="block"):this.positionSlider&&(this.positionSlider.style.display="none")}async initialize(){return new Promise(async e=>{var n;await document.fonts.ready;let t=this.navigator.currentLocator();(this.navigator.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions)&&(this.positionSlider&&(this.positionSlider.value=(t.locations.position??0).toString()),this.positionSlider&&(this.positionSlider.max=((t.locations.totalRemainingPositions??0)+(t.locations.position??0)).toString())),this.timelineContainer&&(this.timelineContainer.innerHTML=""),(n=this.publication.readingOrder)==null||n.forEach(i=>{var _,v;let o=this.publication.getAbsoluteHref(i.Href),s=this.publication.getTOCItemAbsolute(o),c=(s==null?void 0:s.Href.indexOf("#"))!==-1?s==null?void 0:s.Href.slice(0,s==null?void 0:s.Href.indexOf("#")):s.Href,f=this.publication.getAbsoluteHref(c??"");var u;this.publication.positions&&((_=this.navigator.view)==null?void 0:_.layout)!=="fixed"?i.contentWeight?u=i.contentWeight:u=1:u=100/(((v=this.publication.readingOrder)==null?void 0:v.length)??0);var y=document.createElement("div");if(y.style.height=u+"%",y.style.width="100%",y.className="chapter",(s==null?void 0:s.Title)!==void 0){var m=document.createElement("span");m.innerHTML=s.Title,m.className="chapter-tooltip",y.appendChild(m)}_e(y,"click",g=>{g.preventDefault(),g.stopPropagation();var h;this.publication.positions||this.navigator.rights.autoGeneratePositions&&this.publication.positions?(h={...this.publication.positions.filter(l=>l.href===i.Href)[0]},h.href=this.publication.getAbsoluteHref(h.href)):h={href:f,locations:{progression:0},type:i.TypeLink,title:i.Title},g1.default.log(h),this.navigator.navigate(h)}),f===this.navigator.currentChapterLink.href?y.className+=" active":y.className=y.className.replace(" active",""),this.timelineContainer&&this.timelineContainer.appendChild(y)}),e()})}};L();var Z1=rt(Vo());L();var Ww=rt($t());function zw(r,e){return new Promise(function(t){setTimeout(t.bind(null,e),r)})}var gD=!1;Ww.default.setLevel(gD?"trace":"warn",!0);var hh=rt(Vw()),Nr=rt($t());L();var aC=rt(B8(),1),mi=rt(QA(),1);L();var ZA=[{regex:/IE (\d+)\.(\d+)/,family:"ie",maxVersion:[7,1/0,1/0]},{regex:/Trident\/4\.0/,family:"ie",version:[8,0,0]},{regex:/Trident\/5\.0/,family:"ie",version:[9,0,0]},{regex:/Trident\/6\.0/,family:"ie",version:[10,0,0]},{regex:/Trident\/[78]\.0/,family:"ie",version:[11,0,0]},{regex:/Edge?\/(\d+)\.(\d+)(\.(\d+)|)/,family:"edge"},{regex:/Firefox\/(\d+)\.(\d+)(\.(\d+)|)/,family:"firefox"},{regex:/Chrom(ium|e)\/(\d+)\.(\d+)(\.(\d+)|)/,family:"chrome"},{regex:/Chrom(ium|e)\/(\d+)\.(\d+)(\.(\d+)|)([\d.]+$|.*Safari\/(?![\d.]+ Edge\/[\d.]+$))/,family:"chrome",maxVersion:[70,1/0,1/0]},{regex:/(Maci|X11).+ Version\/(\d+)\.(\d+)([.,](\d+)|)( \(\w+\)|)( Mobile\/\w+|) Safari\//,family:"safari"},{regex:/Opera\/9\.80.+Version\/(\d+)\.(\d+)(\.(\d+)|)/,family:"opera",maxVersion:[12,15,0]},{regex:/Chrome.+OPR\/(\d+)\.(\d+)\.(\d+)/,family:"opera",minVersion:[15,0,0]},{regex:/(CPU[ +]OS|iPhone[ +]OS|CPU[ +]iPhone|CPU IPhone OS|CPU iPad OS)[ +]+(\d+)[_.](\d+)([_.](\d+)|)/,family:"ios_saf"},{regex:/[^e] (CPU[ +]OS|iPhone[ +]OS|CPU[ +]iPhone|CPU IPhone OS|CPU iPad OS)[ +]+(\d+)[_.](\d+)([_.](\d+)|)/,family:"ios_saf",version:[7,0,3]},{regex:/Opera Mini/,family:"op_mini"},{regex:/Android Donut/,family:"android",version:[1,2,0]},{regex:/Android Eclair/,family:"android",version:[2,1,0]},{regex:/Android Froyo/,family:"android",version:[2,2,0]},{regex:/Android Gingerbread/,family:"android",version:[2,3,0]},{regex:/Android Honeycomb/,family:"android",version:[3,0,0]},{regex:/Android:?[ /-](\d+)(\.(\d+)|)(\.(\d+)|)/,family:"android"},{regex:/Android:?[ /-](\d+)(\.(\d+)|)(\.(\d+)|);(?! ARM; Trident)/,family:"android",version:[4,0,0]},{regex:/PlayBook.+RIM Tablet OS (\d+)\.(\d+)\.(\d+)/,family:"bb"},{regex:/(Black[bB]erry|BB10).+Version\/(\d+)\.(\d+)\.(\d+)/,family:"bb"},{regex:/Opera\/.+Opera Mobi.+Version\/(\d+)\.(\d+)/,family:"op_mob",maxVersion:[12,16,0]},{regex:/Mobile Safari.+OPR\/(\d+)\.(\d+)\.(\d+)/,family:"op_mob",minVersion:[14,0,0]},{regex:/Android.+Firefox\/(\d+)\.(\d+)(\.(\d+)|)/,family:"and_ff"},{regex:/Android.+Chrom(ium|e)\/(\d+)\.(\d+)(\.(\d+)|)/,family:"and_chr"},{regex:/IEMobile[ /](\d+)\.(\d+)/,family:"ie_mob"},{regex:/Android.+(UC? ?Browser|UCWEB|U3)[ /]?(\d+)\.(\d+)\.(\d+)/,family:"and_uc"},{regex:/SamsungBrowser\/(\d+)\.(\d+)/,family:"samsung"},{regex:/Android.+MQQBrowser\/(\d+)(\.(\d+)|)(\.(\d+)|)/,family:"and_qq"},{regex:/baidubrowser[/\s](\d+)(\.(\d+)|)(\.(\d+)|)/,family:"baidu"},{regex:/K[Aa][Ii]OS\/(\d+)\.(\d+)(\.(\d+)|)/,family:"kaios"}];function J1(r){return typeof r=="number"?r:r.length===1?r[0]:[r[0],r[r.length-1]]}var fr;(function(r){r[r.Major=0]="Major",r[r.Minor=1]="Minor",r[r.Patch=2]="Patch"})(fr||(fr={}));function eC(r){let e=Array.isArray(r)?r:r.toString().split(".");if(e[0]==="all")return[1/0,0,0];let t=null,n=null,i=[0,0,0];for(let o=0;o<3;o++)if(t=e[o],!(typeof t>"u")){if(n=typeof t=="number"?t:parseInt(t,10),isNaN(n))return null;i[o]=n}return i}function iU(r,e){let t=0,n=[];for(let i=2;i>=0;i--)if(r[i]!==e[i]){t=i;break}for(let i=r[t],o=e[t];i<=o;i++)n.push(r.map((s,c)=>c===t?i:s));return n}function tC(r,e,t){let[n,i,o]=r,[s,c,f]=e,{ignoreMinor:u,ignorePatch:y,allowHigherVersions:m}=t;if(s===1/0)return!0;let _=!u,v=_&&!y;return m?v&&o<f||_&&i<c?!1:n>=s:v&&o!==f||_&&i!==c?!1:n===s}function oU(r,e){let{ignoreMinor:t,ignorePatch:n,allowZeroSubversions:i}=e,o=t?1:n?2:3;if(i)for(let s=o-1;s>0&&!(r[s]!==0||o===1);s--)o--;return o}function sU(r){return r.reduce((e,t)=>{let[n,i,o]=t.split(/ |-/),s=eC(i);return(s?o?iU(s,eC(o)):[s]:[]).reduce((f,u)=>(u&&f.push({family:n,version:u}),f),e)},[])}function aU(r={}){let{browsers:e,...t}=r,n=(0,aC.default)(e,t);return sU(n)}function uU(r,e,t=0){let n=r.length;for(let i=t;i<n;i++)if(r[i]!==e[i])return!1;return!0}function uC(r){if(r===null||typeof r!="object")return r;let e=Array.isArray(r)?[]:{},t;for(t in r)e[t]=uC(r[t]);return e}function dh(r){return[].concat(...r)}function lU(r){let e=new Map;return r.forEach(({family:t,version:n})=>{let i=e.get(t);if(i){let o=n.join(".");i.every(s=>s.join(".")!==o)&&i.push(n);return}e.set(t,[n])}),e.forEach(t=>{t.sort((n,i)=>{for(let o in n)if(n[o]!==i[o])return n[o]-i[o];return 0})}),e}function cU(r){if(r.length<2)return r;let e=r.length+1,t=[],n=null,i=r[0],o=[i[fr.Major]],s=[i[fr.Minor]],c=[i[fr.Patch]],f=null;for(let u=1;u<e;u++){n=r[u-1],i=r[u]||[];for(let y=fr.Major;y<=fr.Patch;y++){if((y===f||f===null)&&n[y]+1===i[y]&&uU(n,i,y+1)){f=y,y===fr.Major?o.push(i[fr.Major]):o=i[fr.Major],y===fr.Minor?s.push(i[fr.Minor]):s=i[fr.Minor],y===fr.Patch?c.push(i[fr.Patch]):c=i[fr.Patch];break}if(f===y||n[y]!==i[y]){t.push([J1(o),J1(s),J1(c)]),o=[i[fr.Major]],s=[i[fr.Minor]],c=[i[fr.Patch]],f=null;break}}}return t}function dU(r){return{type:"RegExp",body:r,flags:""}}function So(...r){let e=dh(r).filter(Boolean);return e.length===1?e[0]:{type:"Alternative",expressions:e}}function ri(r){return{type:"Char",kind:"simple",value:String(r),codePoint:NaN}}function fU(r){return{type:"Char",kind:"meta",value:r,codePoint:NaN}}function lC(r,e){return{type:"ClassRange",from:r,to:e}}function K1(...r){return{type:"CharacterClass",expressions:dh(r).filter(Boolean)}}function hU(r){return{type:"Quantifier",kind:r,greedy:!0}}function pU(r,e){return{type:"Quantifier",kind:"Range",from:r,to:e,greedy:!0}}function cC(r){return{type:"Group",capturing:!0,expression:r,number:null}}function gU(r,e){return{type:"Repetition",expression:r,quantifier:e}}function mU(...r){let e=dh(r).filter(Boolean);if(e.length===1)return e[0];let t={type:"Disjunction",left:null,right:e.pop()};return e.reduceRight((n,i,o)=>o===0?(n.left=i,n):(n.left={type:"Disjunction",left:null,right:i},n.left),t),t}function fh(...r){let e=mU(...r);return e.type==="Disjunction"?cC(e):e}function tu(){return fU("\\d")}function eu(r=hU("+")){return gU(tu(),r)}function rC(r){return So(Array.from(String(r),ri))}function ch(r){if(r.type==="Group"&&r.expression.type==="Repetition"){let{expression:e,quantifier:t}=r.expression;return e.type==="Char"&&e.value==="\\d"&&t.kind==="+"&&t.greedy}return!1}function Za(r,e){return r&&r.type==="Char"?typeof e>"u"||e instanceof RegExp&&e.test(r.value)||String(e)===r.value:!1}function nC(r){if(r.type==="CharacterClass"&&r.expressions.length===1){let[e]=r.expressions;return e.type==="ClassRange"&&Za(e.from,/\d/)&&Za(e.to,/\d/)}return!1}function iC(r){return r.type!=="RegExp"&&r.type!=="ClassRange"&&r.type!=="Quantifier"}function ru(r){return typeof r=="string"?mi.default.parse(r.replace(/^([^/])/,"/$1").replace(/([^/])$/,"$1/")):r instanceof RegExp?mi.default.parse(r):r}function yU(r){return typeof r=="string"?new RegExp(r):new RegExp(mi.default.generate(r.body),r.flags)}function bU(r){return typeof r=="string"?r:r instanceof RegExp?r.toString():mi.default.generate(r)}var vU=["RegExp","Disjunction","Alternative","Assertion","Char","CharacterClass","ClassRange","Backreference","Group","Repetition","Quantifier"];function Q1(r){let{every:e}=r;return e?typeof e=="function"?{"*":e,...r}:vU.reduce((t,n)=>{let i=r[n],o=i?"pre"in i?i.pre:i:null,s=i&&"post"in i?i.post:null;return t[n]={pre(c){return e.pre(c)!==!1&&o?o(c):!0},post(c){return e.post(c)!==!1&&s?s(c):!0}},t},{}):r}function _U(r){let e=mi.default.optimize(ru(bU(r))).getAST();return mi.default.traverse(e,{Group(t){let{parent:n,node:i}=t,{expression:o}=i;i.capturing=!0,(n.type==="RegExp"||o.type!=="Disjunction"&&n.type!=="Repetition"||o.type==="Disjunction"&&n.type==="Disjunction")&&t.replace(t.node.expression)}}),e}function wU(r,e){return Za(r)&&Za(e)&&r.value===e.value?e:Za(r,/\d/)&&nC(e)&&Number(e.expressions[0].from.value)-Number(r.value)===1?{...e,expressions:[{...e.expressions[0],from:r}]}:nC(r)&&Za(e,/\d/)&&Number(e.value)-Number(r.expressions[0].to.value)===1?{...r,expressions:[{...r.expressions[0],to:e}]}:null}function SU(r){return r.reduce((e,t)=>{let n=e[e.length-1];if(n&&t.type==="Alternative"&&n.type==="Alternative"&&t.expressions.length===n.expressions.length){let i=n.expressions.reduceRight((o,s,c)=>{if(!o)return o;let f=wU(s,t.expressions[c]);if(f)o.unshift(f);else return null;return o},[]);i&&(t.expressions=i,e.pop())}return e.push(t),e},[])}function Y1(r){return Array.from(r.toString(),Number)}function oC(r,e){let t=r+ +!e;return t===0?tu():t===9?ri("9"):t>9?null:K1(lC(ri(t),ri("9")))}function AU(r){if(r===0)return[eu()];let e=Y1(r),t=e.length,n=eu(pU(t+1)),i=t-1;if(r/Math.pow(10,i)===e[0])return[So(oC(e[0],!0),Array.from({length:i},tu)),n];let s=e.reduce((c,f,u)=>{let y=t-u-1,m=u===0,_=ri(""),v=e.reduce((g,h,l)=>{if(l<y)g.push(ri(h));else if(_)if(l>y)g.push(tu());else if(_=oC(h,m),_)g.push(_);else return[];return g},[]);return v.length&&c.push(v),c},[]).map(c=>So(c));return s.push(n),s}function Qa(r,e,t){if(e<r)return null;let n=ri(r),i=ri(e),o=typeof t=="number"&&t>0?Array.from({length:t},()=>ri(0)):[],s=o.length?c=>So(o,c):c=>c;return r===e?s(n):r===0&&e===9?s(tu()):e-r===1?s(K1(n,i)):s(K1(lC(n,i)))}function CU(r,e){let t=[],n=r,i=1;do i*=10,n<i&&(t.push([n,Math.min(i-1,e)]),n=i);while(i<=e);return t}function EU(r,e){let t=r.length;if(t!==e.length||r[0]!==e[0])return null;let n=r[0].toString(),i=0,o=0,s="",c="";for(let f=1;f<t;f++)i=r[f],o=e[f],i===o?n+=i:(s+=i,c+=o);return[n,parseInt(s,10),parseInt(c,10)]}function X1(r,e,t=0){let n=Y1(r),i=n.length;if(r<10&&e<10||r===e){let y=t-i;return[Qa(r,e,y)]}let o=Y1(e);if(i!==o.length){let y=CU(r,e);return dh(y.map(([_,v])=>X1(_,v,t)))}let s=EU(n,o);if(Array.isArray(s)){let[y,m,_]=s,v=i-y.length,g=X1(m,_,v);return[So(Array.from(y,ri),fh(g))]}let c=Array.from({length:i-1}),f=Qa(n[0]+1,o[0]-1),u=[...c.map((y,m)=>{let _=i-m-1,v=+(m>0);return So(n.map((g,h)=>h<_?ri(g):h>_?Qa(0,9):Qa(g+v,9)))}),...f?[So(f,Array.from({length:i-1},()=>tu()))]:[],...c.map((y,m)=>{let _=i-m-1,v=+(m>0);return So(o.map((g,h)=>h<_?ri(g):h>_?Qa(0,9):Qa(0,g-v)))})];return SU(u)}function sC(r,e=1/0){if(r===1/0)return eu();let t=e===1/0?AU(r):X1(r,e);return fh(t)}function xU(r,e,t,n){let i={...n,allowHigherVersions:!0},o=f=>tC(f,r,i),s=f=>tC(e,f,i),c=r&&e?f=>o(f)&&s(f):r?o:e?s:()=>!0;return t.filter(c)}function TU(r,e,t=ZA){let n=[],i="",o=!1;return t.forEach(s=>{let c=r.get(s.family);if(!c)return;let{version:f,minVersion:u,maxVersion:y}=s;f&&(u=f,y=f);let m=xU(u,y,c,e);m.length&&(i===s.family&&o&&(f=void 0,u=void 0,y=void 0,m=c,n.pop()),n.push({...s,version:f,minVersion:u,maxVersion:y,requestVersions:c,matchedVersions:m})),o=!f&&!u&&!y,i=s.family}),n}function PU(r){let e=r.map(({regexAst:n})=>cC(n.body)),t=_U(dU(fh(e)));return yU(t)}function OU(r){let e=ru(r),t=0;return mi.default.traverse(e,{Group(n){ch(n.node)&&t++}}),t}function MU(r,e,t){let n=ru(r),i=typeof t=="number"&&t<e.length?e.slice(0,t):e.slice();return mi.default.traverse(n,Q1({every(){return!!i.length},Group(o){return ch(o.node)&&i.length?(n===o.node?n=i.shift():o.replace(i.shift()),!1):!0}})),n}function dC(r,e){let t=ru(r),n=Math.min(OU(t),e||1/0),i=[],o=0,s=!1;return mi.default.traverse(t,Q1({every:{pre({node:c,parent:f}){return c===t?!0:iC(c)?(f===t&&(s=!1),o<n):!1},post({node:c,parent:f}){c!==t&&f===t&&iC(c)&&(s||o>0&&o<n)&&i.push(c)}},Group(c){return ch(c.node)&&o<n?(s=!0,o++,!1):!0}})),i.length===1&&!ch(i[0])?dC(i[0],n):i}function kU(r,e){let{ignoreMinor:t,ignorePatch:n,allowHigherVersions:i}=e,o=r[0]===1/0?0:t?1:n?2:3;if(i){let c=[],f=!0,u=0,y=0,m=_=>(v,g)=>g>=o?eu():(y=Array.isArray(v)?v[0]:v,g<_?rC(y):g>_?eu():sC(y+u));for(let _=o-1;_>=0;_--)f&&!r[_]||(f=!1,c.push(r.map(m(_))),u=1);return c}return[r.map((c,f)=>f>=o?eu():Array.isArray(c)?sC(c[0],c[1]):rC(c))]}function RU(r,e,t){let{allowHigherVersions:n}=t,i=ru(r),o=n&&e.length?[e[0]]:e,s=o.reduce((u,y)=>Math.max(u,oU(y,t)),1),c=dC(i,s),f=fh(...o.map(u=>kU(u,t).map(y=>MU(So(uC(c)),y,s))));return mi.default.traverse(i,Q1({every(u){return c.length?(u.node===c[0]&&(c.length===1?u.replace(f):u.remove(),c.shift()),!0):!1}})),i}function LU(r,e){return r.map(({regex:t,version:n,maxVersion:i,matchedVersions:o,...s})=>{let c=ru(t);return n||(c=RU(c,cU(o),{...e,allowHigherVersions:!i&&e.allowHigherVersions})),{regex:null,sourceRegex:t,regexAst:c,version:n,maxVersion:i,matchedVersions:o,...s}})}var IU={ignoreMinor:!1,ignorePatch:!0,allowZeroSubversions:!1,allowHigherVersions:!1};function NU(r={}){let e={...IU,...r},t=aU(e),n=lU(t),i=TU(n,e);return LU(i,e)}function fC(r={}){return PU(NU(r))}var Ns=class{constructor(e){this.hasEventListener=!1;this.isHacked=!1;this.properties=e}static async setupPreloadProtection(e){if(this.isCurrentBrowserSupported(e))e.detectInspect&&await this.startInspectorProtection(e);else throw new Error("Browser not supported")}static async create(e){let t=new this(e);return await t.start(),t}static async startInspectorProtection(e){(0,hh.addListener)(n=>{var i;n&&(e.clearOnInspect&&(console.clear(),window.localStorage.clear(),window.sessionStorage.clear(),window.location.replace(window.location.origin)),e.detectInspect&&typeof((i=e.api)==null?void 0:i.inspectDetected)=="function"&&e.api.inspectDetected())}),(0,hh.launch)(),await zw(e.detectInspectInitDelay??100)}static isCurrentBrowserSupported(e){if(!e.enforceSupportedBrowsers)return!0;let t=[];return(e.supportedBrowsers??[]).forEach(i=>{t.push("last 1 "+i+" version")}),fC({browsers:t,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){var t;if((t=this.properties)!=null&&t.enableObfuscation){this.wrapper=ft(document,"#iframe-wrapper"),this.securityContainer=Ne(document,"#container-view-security");var e=this;this.mutationObserver=new MutationObserver(function(n){n.forEach(function(i){Nr.default.log(i.type),e.isHacked=!0})})}}async stop(){var e,t,n,i,o,s,c,f;if(Nr.default.log("Protection module stop"),(e=this.properties)!=null&&e.enableObfuscation&&this.mutationObserver.disconnect(),(t=this.properties)!=null&&t.disableKeys){Ue(this.navigator.mainElement,"keydown",this.disableSave),Ue(this.navigator.headerMenu,"keydown",this.disableSave);for(let u of this.navigator.iframes)Ue(u.contentDocument,"keydown",this.disableSave),Ue(u.contentWindow,"keydown",this.disableSave);Ue(window,"keydown",this.disableSave),Ue(document,"keydown",this.disableSave)}if((n=this.properties)!=null&&n.disableCopy){Ue(this.navigator.mainElement,"copy",this.preventCopy),Ue(this.navigator.headerMenu,"copy",this.preventCopy);for(let u of this.navigator.iframes)Ue(u.contentDocument,"copy",this.preventCopy),Ue(u.contentWindow,"copy",this.preventCopy);Ue(window,"copy",this.preventCopy),Ue(document,"copy",this.preventCopy),Ue(this.navigator.mainElement,"cut",this.preventCopy),Ue(this.navigator.headerMenu,"cut",this.preventCopy);for(let u of this.navigator.iframes)Ue(u.contentDocument,"cut",this.preventCopy),Ue(u.contentWindow,"cut",this.preventCopy);Ue(window,"cut",this.preventCopy),Ue(document,"cut",this.preventCopy),Ue(this.navigator.mainElement,"keydown",this.preventCopyKey),Ue(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let u of this.navigator.iframes)Ue(u.contentDocument,"keydown",this.preventCopyKey),Ue(u.contentWindow,"keydown",this.preventCopyKey);Ue(window,"keydown",this.preventCopyKey),Ue(document,"keydown",this.preventCopyKey)}else if((i=this.properties)!=null&&i.canCopy){Ue(this.navigator.mainElement,"copy",this.restrictCopy),Ue(this.navigator.headerMenu,"copy",this.restrictCopy);for(let u of this.navigator.iframes)Ue(u.contentDocument,"copy",this.restrictCopy),Ue(u.contentWindow,"copy",this.restrictCopy);Ue(window,"copy",this.restrictCopy),Ue(document,"copy",this.restrictCopy),Ue(this.navigator.mainElement,"cut",this.restrictCopy),Ue(this.navigator.headerMenu,"cut",this.restrictCopy);for(let u of this.navigator.iframes)Ue(u.contentDocument,"cut",this.restrictCopy),Ue(u.contentWindow,"cut",this.restrictCopy);Ue(window,"cut",this.restrictCopy),Ue(document,"cut",this.restrictCopy),Ue(this.navigator.mainElement,"keydown",this.restrictCopyKey),Ue(this.navigator.headerMenu,"keydown",this.restrictCopyKey);for(let u of this.navigator.iframes)Ue(u.contentDocument,"keydown",this.restrictCopyKey),Ue(u.contentWindow,"keydown",this.restrictCopyKey);Ue(window,"keydown",this.restrictCopyKey),Ue(document,"keydown",this.restrictCopyKey)}if((o=this.properties)!=null&&o.disablePrint){Ue(this.navigator.mainElement,"beforeprint",this.beforePrint.bind(this)),Ue(this.navigator.headerMenu,"beforeprint",this.beforePrint.bind(this));for(let u of this.navigator.iframes)Ue(u.contentDocument,"beforeprint",this.beforePrint),Ue(u.contentWindow,"beforeprint",this.beforePrint);Ue(window,"beforeprint",this.beforePrint),Ue(document,"beforeprint",this.beforePrint),Ue(this.navigator.mainElement,"afterprint",this.afterPrint.bind(this)),Ue(this.navigator.headerMenu,"afterprint",this.afterPrint.bind(this));for(let u of this.navigator.iframes)Ue(u.contentDocument,"afterprint",this.afterPrint.bind(this)),Ue(u.contentWindow,"afterprint",this.afterPrint.bind(this));Ue(window,"afterprint",this.afterPrint.bind(this)),Ue(document,"afterprint",this.afterPrint.bind(this))}if((s=this.properties)!=null&&s.disableContextMenu){Ue(this.navigator.mainElement,"contextmenu",this.disableContext),Ue(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let u of this.navigator.iframes)Ue(u.contentDocument,"contextmenu",this.disableContext),Ue(u.contentWindow,"contextmenu",this.disableContext);Ue(window,"contextmenu",this.disableContext),Ue(document,"contextmenu",this.disableContext)}(c=this.properties)!=null&&c.hideTargetUrl&&this.hideTargetUrls(!1),(f=this.properties)!=null&&f.disableDrag&&this.preventDrag(!1),Ue(this.wrapper,"scroll",this.handleScroll.bind(this))}observe(){var t;if((t=this.properties)!=null&&t.enableObfuscation){this.securityContainer.hasAttribute("style")&&(this.isHacked=!0),this.mutationObserver.disconnect();var e={attributes:!0,childList:!0,characterData:!0};this.mutationObserver.observe(this.securityContainer,e)}}async deactivate(){var e;(e=this.properties)!=null&&e.enableObfuscation&&(this.observe(),this.rects.forEach(t=>this.deactivateRect(t,this.securityContainer,this.isHacked)))}async activate(){var e;if((e=this.properties)!=null&&e.enableObfuscation){this.observe();for(let t of this.navigator.iframes)if(t.contentDocument){let n=lo(t.contentDocument,"body");this.rects=this.findRects(n),this.rects.forEach(i=>this.toggleRect(i,this.securityContainer,this.isHacked))}}}setupEvents(){var e,t,n,i,o,s,c,f,u,y,m,_,v,g,h;if((e=this.properties)!=null&&e.disableKeys){_e(this.navigator.mainElement,"keydown",this.disableSave),_e(this.navigator.headerMenu,"keydown",this.disableSave);for(let l of this.navigator.iframes)_e(l,"keydown",this.disableSave),_e(l.ownerDocument,"keydown",this.disableSave),_e(l.contentDocument,"keydown",this.disableSave),_e(l.contentWindow,"keydown",this.disableSave),_e((t=l.contentWindow)==null?void 0:t.document,"keydown",this.disableSave);_e(window,"keydown",this.disableSave),_e(document,"keydown",this.disableSave)}if((n=this.properties)!=null&&n.disableCopy){_e(this.navigator.mainElement,"copy",this.preventCopy),_e(this.navigator.headerMenu,"copy",this.preventCopy);for(let l of this.navigator.iframes)_e(l,"copy",this.preventCopy),_e(l.ownerDocument,"copy",this.preventCopy),_e(l.contentDocument,"copy",this.preventCopy),_e(l.contentWindow,"copy",this.preventCopy),_e((i=l.contentWindow)==null?void 0:i.document,"copy",this.preventCopy);_e(window,"copy",this.preventCopy),_e(document,"copy",this.preventCopy),_e(this.navigator.mainElement,"cut",this.preventCopy),_e(this.navigator.headerMenu,"cut",this.preventCopy);for(let l of this.navigator.iframes)_e(l,"cut",this.preventCopy),_e(l.ownerDocument,"cut",this.preventCopy),_e(l.contentDocument,"cut",this.preventCopy),_e(l.contentWindow,"cut",this.preventCopy),_e((o=l.contentWindow)==null?void 0:o.document,"cut",this.preventCopy);_e(window,"cut",this.preventCopy),_e(document,"cut",this.preventCopy),_e(this.navigator.mainElement,"keydown",this.preventCopyKey),_e(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let l of this.navigator.iframes)_e(l,"keydown",this.preventCopyKey),_e(l.ownerDocument,"keydown",this.preventCopyKey),_e(l.contentDocument,"keydown",this.preventCopyKey),_e(l.contentWindow,"keydown",this.preventCopyKey),_e((s=l.contentWindow)==null?void 0:s.document,"keydown",this.preventCopyKey);_e(window,"keydown",this.preventCopyKey),_e(document,"keydown",this.preventCopyKey)}else if((c=this.properties)!=null&&c.canCopy){_e(this.navigator.mainElement,"copy",this.restrictCopy.bind(this)),_e(this.navigator.headerMenu,"copy",this.restrictCopy.bind(this));for(let l of this.navigator.iframes)_e(l,"copy",this.restrictCopy),_e(l.ownerDocument,"copy",this.restrictCopy.bind(this)),_e(l.contentDocument,"copy",this.restrictCopy.bind(this)),_e(l.contentWindow,"copy",this.restrictCopy.bind(this)),_e((f=l.contentWindow)==null?void 0:f.document,"copy",this.restrictCopy.bind(this));_e(window,"copy",this.restrictCopy.bind(this)),_e(document,"copy",this.restrictCopy.bind(this)),_e(this.navigator.mainElement,"cut",this.restrictCopy.bind(this)),_e(this.navigator.headerMenu,"cut",this.restrictCopy.bind(this));for(let l of this.navigator.iframes)_e(l,"cut",this.restrictCopy.bind(this)),_e(l.ownerDocument,"cut",this.restrictCopy.bind(this)),_e(l.contentDocument,"cut",this.restrictCopy.bind(this)),_e(l.contentWindow,"cut",this.restrictCopy.bind(this)),_e((u=l.contentWindow)==null?void 0:u.document,"cut",this.restrictCopy.bind(this));_e(window,"cut",this.restrictCopy.bind(this)),_e(document,"cut",this.restrictCopy.bind(this)),_e(this.navigator.mainElement,"keydown",this.restrictCopyKey.bind(this)),_e(this.navigator.headerMenu,"keydown",this.restrictCopyKey.bind(this));for(let l of this.navigator.iframes)_e(l,"keydown",this.restrictCopyKey.bind(this)),_e(l.ownerDocument,"keydown",this.restrictCopyKey.bind(this)),_e(l.contentDocument,"keydown",this.restrictCopyKey.bind(this)),_e(l.contentWindow,"keydown",this.restrictCopyKey.bind(this)),_e((y=l.contentWindow)==null?void 0:y.document,"keydown",this.restrictCopyKey.bind(this));_e(window,"keydown",this.restrictCopyKey.bind(this)),_e(document,"keydown",this.restrictCopyKey.bind(this))}if((m=this.properties)!=null&&m.disablePrint){_e(this.navigator.mainElement,"beforeprint",this.beforePrint),_e(this.navigator.headerMenu,"beforeprint",this.beforePrint);for(let l of this.navigator.iframes)_e(l,"beforeprint",this.beforePrint.bind(this)),_e(l.ownerDocument,"beforeprint",this.beforePrint.bind(this)),_e(l.contentDocument,"beforeprint",this.beforePrint.bind(this)),_e(l.contentWindow,"beforeprint",this.beforePrint.bind(this)),_e((_=l.contentWindow)==null?void 0:_.document,"beforeprint",this.beforePrint.bind(this));_e(window,"beforeprint",this.beforePrint.bind(this)),_e(document,"beforeprint",this.beforePrint.bind(this)),_e(this.navigator.mainElement,"afterprint",this.afterPrint),_e(this.navigator.headerMenu,"afterprint",this.afterPrint);for(let l of this.navigator.iframes)_e(l,"afterprint",this.afterPrint.bind(this)),_e(l.ownerDocument,"afterprint",this.afterPrint.bind(this)),_e(l.contentDocument,"afterprint",this.afterPrint.bind(this)),_e(l.contentWindow,"afterprint",this.afterPrint.bind(this)),_e((v=l.contentWindow)==null?void 0:v.document,"afterprint",this.afterPrint.bind(this));_e(window,"afterprint",this.afterPrint.bind(this)),_e(document,"afterprint",this.afterPrint.bind(this))}if((g=this.properties)!=null&&g.disableContextMenu){_e(this.navigator.mainElement,"contextmenu",this.disableContext),_e(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let l of this.navigator.iframes)_e(l,"contextmenu",this.disableContext),_e(l.ownerDocument,"contextmenu",this.disableContext),_e(l.contentDocument,"contextmenu",this.disableContext),_e(l.contentWindow,"contextmenu",this.disableContext),_e((h=l.contentWindow)==null?void 0:h.document,"contextmenu",this.disableContext);_e(window,"contextmenu",this.disableContext),_e(document,"contextmenu",this.disableContext)}}initializeResource(){var e,t;(e=this.properties)!=null&&e.hideTargetUrl&&this.hideTargetUrls(!0),(t=this.properties)!=null&&t.disableDrag&&this.preventDrag(!0)}async initialize(){var e;if((e=this.properties)!=null&&e.enableObfuscation)return new Promise(async t=>{await document.fonts.ready;for(let n of this.navigator.iframes)if(n.contentDocument){let i=lo(n.contentDocument,"body");this.observe(),setTimeout(()=>{this.rects=this.findRects(i),this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),this.setupEvents(),this.hasEventListener||(this.hasEventListener=!0,_e(this.wrapper,"scroll",this.handleScroll.bind(this))),t()},10)}})}handleScroll(){this.rects.forEach(e=>this.toggleRect(e,this.securityContainer,this.isHacked))}async handleResize(){var e;if((e=this.properties)!=null&&e.enableObfuscation){let t=(0,Z1.default)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(n=>this.toggleRect(n,this.securityContainer,this.isHacked))},50);this.rects&&(this.observe(),t())}}disableContext(e){return e.preventDefault(),e.stopPropagation(),!1}disableSave(e){return(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?e.metaKey:e.ctrlKey&&(e.key==="s"||e.keyCode===83))?(e.preventDefault(),e.stopPropagation(),!1):!0}preventCopy(e){return Nr.default.log("copy action initiated"),e.clipboardData.setData("text/plain","copy not allowed"),e.stopPropagation(),e.preventDefault(),!1}preventCopyKey(e){return(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?e.metaKey:e.ctrlKey&&(e.key==="c"||e.keyCode===67))?(e.preventDefault(),e.stopPropagation(),!1):!0}restrictCopy(e){var n,i,o,s;if(this.citation)return;Nr.default.log("copy action initiated");let t=this.navigator.iframes[0].contentWindow;if(t){let f=function(y){let m={className:v=>Nn.indexOf(v)<0,idName:v=>Nn.indexOf(v)<0},_=c.navigator.iframes[0].contentDocument;if(_)return Ar(y,_,m)},c=this,u=Hi(t,f);if(u===void 0){let y=this.navigator.iframes[0].contentDocument;u=(i=(n=this.navigator.annotationModule)==null?void 0:n.annotator)==null?void 0:i.getTemporarySelectionInfo(y)}e.clipboardData.setData("text/plain",(s=u==null?void 0:u.cleanText)==null?void 0:s.substring(0,((o=this.properties)==null?void 0:o.charactersToCopy)??0))}else e.clipboardData.setData("text/plain","");return e.stopPropagation(),e.preventDefault(),!1}restrictCopyKey(e){var t,n,i,o;if(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?e.metaKey:e.ctrlKey&&(e.key==="c"||e.keyCode===67)){let s=this.navigator.iframes[0].contentWindow;if(s){let f=function(y){let m={className:v=>Nn.indexOf(v)<0,idName:v=>Nn.indexOf(v)<0},_=c.navigator.iframes[0].contentDocument;if(_)return Ar(y,_,m)},c=this,u=Hi(s,f);if(u===void 0){let y=this.navigator.iframes[0].contentDocument;u=(n=(t=this.navigator.annotationModule)==null?void 0:t.annotator)==null?void 0:n.getTemporarySelectionInfo(y)}this.copyToClipboard((o=u==null?void 0:u.cleanText)==null?void 0:o.substring(0,((i=this.properties)==null?void 0:i.charactersToCopy)??0))}else this.copyToClipboard("");return e.stopPropagation(),e.preventDefault(),!1}return!0}copyToClipboard(e){var t;if(e=e==null?void 0:e.substring(0,((t=this.properties)==null?void 0:t.charactersToCopy)??0),window.clipboardData)window.clipboardData.setData("text/plain",e);else{let n=this.createElementForExecCommand(e);this.selectContent(n);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),document.execCommand("copy",!1)}catch{}document.body.removeChild(n)}}createElementForExecCommand(e){let t=document.createElement("div");return t.style.position="absolute",t.style.left="-10000px",t.style.top="-10000px",t.innerHTML=e,document.body.appendChild(t),t.contentEditable=!0,t}selectContent(e){let t=document.createRange();t.selectNodeContents(e);let n=window.getSelection();n==null||n.removeAllRanges(),n==null||n.addRange(t)}beforePrint(e){return Nr.default.log("before print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.display="none",this.navigator.mainElement.style.display="none"),e.stopPropagation(),e.preventDefault(),!1}afterPrint(e){return Nr.default.log("after print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.removeProperty("display"),this.navigator.mainElement.style.removeProperty("display")),e.stopPropagation(),e.preventDefault(),!1}hideTargetUrls(e){var n;function t(i){i.preventDefault();let o=i.currentTarget.getAttribute("data-href-resolved"),s=document.createElement("a");s.setAttribute("href",o),s.click()}for(let i of this.navigator.iframes){let o=(n=i.contentDocument)==null?void 0:n.querySelectorAll("a");o==null||o.forEach(s=>{let c=s.getAttribute("data-href"),f=s.getAttribute("href");!c&&f&&(s.setAttribute("data-href",f),s.setAttribute("data-href-resolved",s.href))}),e?o==null||o.forEach(s=>{s.setAttribute("href",""),s.addEventListener("click",t)}):o==null||o.forEach(s=>{let c=s.getAttribute("data-href");c&&s.setAttribute("href",c),s.removeEventListener("click",t)})}}preventDrag(e){var i,o,s,c,f;let t="-webkit-user-drag: none; -khtml-user-drag: none; -moz-user-drag: none; -ms-user-drag: none; user-drag: none; -webkit-pointer-events: none; -khtml-pointer-events: none; -moz-pointer-events: none; -ms-pointer-events: none; pointer-events: none;",n=u=>{u.preventDefault()};for(let u of this.navigator.iframes){let y=((i=u.contentDocument)==null?void 0:i.body.getAttribute("style"))||"";e?((o=u.contentDocument)==null||o.body.addEventListener("dragstart",n),(s=u.contentDocument)==null||s.body.setAttribute("style",y+t)):((c=u.contentDocument)==null||c.body.removeEventListener("dragstart",n),(f=u.contentDocument)==null||f.body.setAttribute("style",y.replace(t,"")))}}recalculate(e=0){return new Promise(t=>{var n;if((n=this.properties)!=null&&n.enableObfuscation){let i=(0,Z1.default)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),t(!0)},e);this.rects?(this.observe(),i()):t(!1)}else t(!1)})}calcRects(e){e!==void 0&&e.forEach(t=>{try{let{top:n,height:i,left:o,width:s}=this.measureTextNode(t.node);t.top=n,t.height=i,t.width=s,t.left=o}catch(n){Nr.default.log("error "+n),Nr.default.log(t),Nr.default.log(t.node),Nr.default.log("scrambledTextContent "+t.scrambledTextContent),Nr.default.log("textContent "+t.textContent),Nr.default.log("isObfuscated "+t.isObfuscated)}})}deactivateRect(e,t,n){this.isBeingHacked(t)||n?(e.node.textContent=e.scrambledTextContent,e.isObfuscated=!0):(e.node.textContent=e.textContent,e.isObfuscated=!1)}toggleRect(e,t,n){let i=this.isOutsideViewport(e),o=this.isBeingHacked(t);e.isObfuscated&&!i&&!o&&!n&&(e.node.textContent=e.textContent,e.isObfuscated=!1),!e.isObfuscated&&(i||o||n)&&(e.node.textContent=e.scrambledTextContent,e.isObfuscated=!0)}findRects(e){return this.findTextNodes(e).map(n=>{var y,m,_,v;let{top:i,height:o,left:s,width:c}=this.measureTextNode(n),f=n.parentElement&&((y=this.properties)!=null&&y.excludeNodes&&((m=this.properties)==null?void 0:m.excludeNodes.indexOf(n.parentElement.nodeName.toLowerCase()))>-1||((_=n.parentElement)==null?void 0:_.nodeName.toLowerCase())==="option"||((v=n.parentElement)==null?void 0:v.nodeName.toLowerCase())==="script")?n.textContent:this.obfuscateText(n.textContent??"");return{top:i,height:o,width:c,left:s,node:n,textContent:n.textContent??"",scrambledTextContent:f??"",isObfuscated:!1}})}obfuscateText(e){return this.scramble(e,!0)}measureTextNode(e){try{let t=document.createRange();t.selectNode(e);let n=t.getBoundingClientRect();return t.detach(),n}catch(t){Nr.default.log("measureTextNode "+t),Nr.default.log("measureTextNode "+e),Nr.default.log(e.textContent)}}isBeingHacked(e){return e.style.animation||e.style.transition||e.style.position||e.hasAttribute("style")?(Nr.default.log("content being hacked"),!0):!1}isOutsideViewport(e){let t=this.wrapper.scrollLeft,n=t+this.wrapper.clientWidth,i=e.left+e.width,o=e.top+e.height,s=this.wrapper.scrollTop,c=s+this.wrapper.clientHeight,f=o<s,u=e.top>c,y=i<t-window.innerWidth,m=e.left>n+window.innerWidth;return f||u||y||m}findTextNodes(e,t=[]){var i;let n=e.firstChild;for(;n;)n.nodeType===1&&this.findTextNodes(n,t),n.nodeType===3&&(i=n.textContent)!=null&&i.trim()&&t.push(n),n=n.nextSibling;return t}scramble(e,t=!1,n=!1){var i=e.split(" ");function o(s){for(var c=s.length,f,u;c>0;)u=Math.floor(Math.random()*c),c--,f=s[c],s[c]=s[u],s[u]=f;return s}return t&&(i=i.map(function(s){return s.includes("-")?s:o(s.split("")).join("")})),n?o(i).join(" "):i.join(" ")}};L();var bC=rt(pC());L();var ph=r=>r.replace(/\n/g," ").replace(/\s\s+/g," "),BU=r=>ph(r).trim(),mC=/[\\^$.*+?()[\]{}|]/g,DU=RegExp(mC.source);function gC(r){return r&&DU.test(r)?r.replace(mC,"\\$&"):r||""}var gh=0,FU=()=>()=>Number.isSafeInteger(++gh)?gh:gh=1,yC=()=>{gh=0},HU=FU(),UU=r=>e=>{try{return Ar(e,r,Jo)}catch(t){return console.error("uniqueCssSelector:",t),""}};async function es(r,e,t,n,i=!1){var v,g,h;if(!e)return[];let o=(v=e.body)==null?void 0:v.textContent;if(!o)return[];if(r=BU(r),!r.length)return[];let s=e.createNodeIterator(e.body,NodeFilter.SHOW_TEXT,{acceptNode:l=>NodeFilter.FILTER_ACCEPT}),c=new RegExp(gC(r).replace(/ /g,"\\s+"),"gim");i&&(c=new RegExp("\\b"+gC(r).replace(/ /g,"\\s+")+"\\b","gim"));let f=[],u=100,y=30,m=0,_;for(;_=c.exec(o);){let l=Math.max(0,_.index-u),p=Math.min(u,_.index),w=ph(o.substr(l,p));w=w.substr(w.length-y),l=c.lastIndex,p=Math.min(u,o.length-l);let A=ph(o.substr(l,p)).substr(0,y),C=new Range,b=_.index;for(;m<=b;){let P=s.nextNode();P&&P.nodeValue&&(m+=P.nodeValue.length)}let E=s.referenceNode.nodeValue?((g=s.referenceNode.nodeValue)==null?void 0:g.length)-(m-b):0;for(C.setStart(s.referenceNode,E),b=_.index+_[0].length;m<=b;){let P=s.nextNode(),N=P==null?void 0:P.nodeValue;N&&(m+=N.length)}E=s.referenceNode.nodeValue?((h=s.referenceNode.nodeValue)==null?void 0:h.length)-(m-b):0,C.setEnd(s.referenceNode,E),e.getCssSelector||(e.getCssSelector=UU(e));let k=go(C,e.getCssSelector);k&&f.push({textMatch:ph(_[0]),textBefore:w,textAfter:A,rangeInfo:k,href:t,title:n,uuid:HU().toString()})}return f}var vC=rt($t()),nu=class{constructor(e,t,n,i,o){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.headerMenu=o,this.publication=e,this.properties=t,this.api=i,this.highlighter=n}static async create(e){let t=new this(e.publication,e,e.highlighter,e.api,e.headerMenu);return await t.start(),t}async stop(){vC.default.log("Search module stop"),Ue(this.searchInput,"keypress",this.handleSearch.bind(this)),Ue(this.searchGo,"click",this.handleSearch.bind(this))}async start(){var t;if(this.headerMenu){this.searchInput=Ne(this.headerMenu,"#searchInput"),_e(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=Ne(this.headerMenu,"#searchGo"),_e(this.searchGo,"click",this.handleSearch.bind(this));var e=Ne(this.headerMenu,"#menu-button-search");e&&((t=e.parentElement)==null||t.style.removeProperty("display"))}setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("search"):this.navigator.showLayer("search")},10)}async handleSearch(e){(e.key==="Enter"||e.type==="click")&&(await this.handleSearchChapter(),await this.handleSearchBook())}async handleSearchChapter(e){var t=this,n=this.searchInput.value;let i=this.navigator.currentChapterLink.href,o=this.publication.getSpineItem(i);if(this.headerMenu)var s=Ne(document,"#searchResultChapter");t.currentChapterSearchResult=[],t.currentSearchHighlights=[];var c=[];await this.searchAndPaintChapter(n,e,async u=>{var y;c=u,f(1),this.navigator.rights.enableContentProtection&&((y=this.navigator.contentProtectionModule)==null||y.recalculate(200))});async function f(u){s.innerHTML="";var y;if(y=t.paginate(c,u,10),y.total===0){let m=document.createElement("a");m.className="collection-item",m.innerHTML="nothing found",s.appendChild(m)}else{for(let h=0;h<y.data.length;h++){let l=document.createElement("a"),p=y.data[h];l.className="collection-item",l.href=(o==null?void 0:o.Href)??"",l.innerHTML="..."+p.textBefore+"<mark>"+p.textMatch+"</mark>"+p.textAfter+"...",_e(l,"click",w=>{w.preventDefault(),w.stopPropagation(),t.jumpToMark(h+u*10-10)}),s.appendChild(l)}let m=document.createElement("div");m.style.textAlign="center",m.style.marginTop="10px";let _=document.createElement("ul");_.className="pagination";let v=document.createElement("li");if(v.className="disabled",v.innerHTML='<a href="#!"> < </a>',y.pre_page!==void 0){let h=y.pre_page;v.className="waves-effect",_e(v,"click",l=>{l.preventDefault(),l.stopPropagation(),f(h)})}_.appendChild(v);for(let h=1;h<=y.total_pages;h++){let l,p=document.createElement("li");p.className="waves-effect",h===y.page&&(p.className="active",l=p),p.innerHTML='<a href="#!">'+h+"</a>",_e(p,"click",w=>{w.preventDefault(),w.stopPropagation(),l&&(l.className="waves-effect"),p.className="active",l=p,f(h)}),_.appendChild(p)}let g=document.createElement("li");if(g.className="disabled",g.innerHTML='<a href="#!"> > </a>',y.next_page!==void 0){let h=y.next_page;g.className="waves-effect",_e(g,"click",l=>{l.preventDefault(),l.stopPropagation(),f(h)})}_.appendChild(g),m.appendChild(_),s.appendChild(m)}}}async searchAndPaintChapter(e,t=0,n){var f,u;this.navigator.rights.enableContentProtection&&((f=this.navigator.contentProtectionModule)==null||f.deactivate());let i=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),o=this.publication.getTOCItem(i);o===null&&(o=this.publication.readingOrder[this.navigator.currentResource()??0]);let s=[];(u=this.highlighter)==null||u.destroyHighlights(1),this.navigator.rights.enableSearch&&this.drawSearch();let c=0;if(o){let y=this.navigator.iframes[0].contentDocument;y&&o&&es(e,y,o.Href,o.Title).then(m=>{m.forEach(_=>{let v={rangeInfo:_.rangeInfo};setTimeout(()=>{var h,l;let g;c===t?(g=this.createSearchHighlight(v,(h=this.properties)==null?void 0:h.current),this.jumpToMark(t)):g=this.createSearchHighlight(v,(l=this.properties)==null?void 0:l.color),_.highlight=g,s.push(_),this.currentChapterSearchResult.push(_),this.currentSearchHighlights.push(g),c++},500)}),setTimeout(()=>{n(s)},500)})}}createSearchHighlight(e,t){var o;try{var n=t;Jt.isHexColor(n)&&(n=Jt.hexToRgbChannels(n));let s=`${e.rangeInfo.startContainerElementCssSelector}${e.rangeInfo.startContainerChildTextNodeIndex}${e.rangeInfo.startOffset}${e.rangeInfo.endContainerElementCssSelector}${e.rangeInfo.endContainerChildTextNodeIndex}${e.rangeInfo.endOffset}`,f="R2_SEARCH_"+bC.SHA256.hash(s);var i=!1;let u={color:n||Rs,id:f,pointerInteraction:i,selectionInfo:e,marker:0,type:1},y=(o=this.highlighter)==null?void 0:o.createHighlightDom(this.navigator.iframes[0].contentWindow,u);return u.position=parseInt((y!=null&&y.hasChildNodes()?y.childNodes[0]:y).style.top.replace("px","")),u}catch(s){throw"Can't create highlight: "+s}}clearSearch(){var e;this.currentChapterSearchResult=[],this.currentSearchHighlights=[],(e=this.highlighter)==null||e.destroyHighlights(1)}async search(e,t){return this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.bookSearchResult=[],yC(),await this.searchAndPaintChapter(e,0,async()=>{var n;this.navigator.rights.enableContentProtection&&((n=this.navigator.contentProtectionModule)==null||n.recalculate(200))}),t?(await this.searchBook(e),await this.searchChapter(e)):(await this.searchChapter(e),await this.searchBook(e))}async goToSearchID(e,t,n){var i=t,o;let s=this.navigator.currentChapterLink.href;var c=this.publication.getAbsoluteHref(e);let f=this.bookSearchResult.filter(u=>u.href===e);if(n?(o=this.currentChapterSearchResult.filter(u=>u.uuid===t)[0],i=this.currentChapterSearchResult.findIndex(u=>u.uuid===t)):(o=f.filter(u=>u.uuid===t)[0],i=f.findIndex(u=>u.uuid===t)),o!==void 0)if(s===c)this.jumpToMark(i);else{let y={href:c,locations:{progression:0},title:"title"};this.navigator.navigate(y),setTimeout(()=>{this.searchAndPaintChapter(o.textMatch,i,async()=>{var m;this.navigator.rights.enableContentProtection&&((m=this.navigator.contentProtectionModule)==null||m.recalculate(200))})},300)}}async goToSearchIndex(e,t,n){var i=t,o;let s=this.navigator.currentChapterLink.href;var c=this.publication.getAbsoluteHref(e);let f=this.bookSearchResult.filter(u=>u.href===e);if(n?o=this.currentChapterSearchResult[i]:o=f[i],o!==void 0)if(s===c)this.jumpToMark(i);else{let y={href:c,locations:{progression:0},title:"title"};this.navigator.navigate(y),setTimeout(()=>{this.searchAndPaintChapter(o.textMatch,i,async()=>{var m;this.navigator.rights.enableContentProtection&&((m=this.navigator.contentProtectionModule)==null||m.recalculate(200))})},300)}}async handleSearchBook(){var e=this,t=this.searchInput.value;if(e.headerMenu)var n=Ne(document,"#searchResultBook");i(1);async function i(s){n.innerHTML="";var c,f=await e.searchBook(t);if(c=e.paginate(f,s,10),c.total===0){let u=document.createElement("a");u.className="collection-item",u.innerHTML="nothing found",n.appendChild(u)}else{o(c.data,g=>g.href).forEach(g=>{let h=document.createElement("div");if(h.style.marginBottom="10px",g[0].title){let l=document.createElement("span");l.className="collection-item",l.style.display="block",l.innerHTML=g[0].title,h.appendChild(l)}n.appendChild(h),g.forEach(l=>{let p=document.createElement("a");p.className="collection-item";var w=e.publication.getAbsoluteHref(l.href);p.innerHTML="..."+l.textBefore+"<mark>"+l.textMatch+"</mark>"+l.textAfter+"...",_e(p,"click",A=>{A.preventDefault(),A.stopPropagation();let b=f.filter(k=>k.href===l.href).findIndex(k=>k===l);if(e.navigator.currentChapterLink.href===w)e.jumpToMark(b);else{let P={href:w,locations:{progression:0},title:"title"};e.navigator.navigate(P),setTimeout(()=>{e.handleSearchChapter(b)},300)}}),h.appendChild(p)})});let y=document.createElement("div");y.style.textAlign="center",y.style.marginTop="10px";let m=document.createElement("ul");m.className="pagination";let _=document.createElement("li");if(_.className="disabled",_.innerHTML='<a href="#!"> < </a>',c.pre_page!=null){let g=c.pre_page;_.className="waves-effect",_e(_,"click",h=>{h.preventDefault(),h.stopPropagation(),i(g)})}m.appendChild(_);for(let g=1;g<=c.total_pages;g++){let h,l=document.createElement("li");l.className="waves-effect",g===c.page&&(l.className="active",h=l),l.innerHTML='<a href="#!">'+g+"</a>",_e(l,"click",p=>{p.preventDefault(),p.stopPropagation(),h&&(h.className="waves-effect"),l.className="active",h=l,i(g)}),m.appendChild(l)}let v=document.createElement("li");if(v.className="disabled",v.innerHTML='<a href="#!"> > </a>',c.next_page!=null){let g=c.next_page;v.className="waves-effect",_e(v,"click",h=>{h.preventDefault(),h.stopPropagation(),i(g)})}m.appendChild(v),y.appendChild(m),n.appendChild(y)}}function o(s,c){let f=new Map;return s.forEach(u=>{let y=c(u),m=f.get(y);m?m.push(u):f.set(y,[u])}),Array.from(f.values())}}async searchBook(e){var n,i;this.bookSearchResult=[];let t=[];for(let o=0;o<this.publication.readingOrder.length;o++){let s=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[o].Href:""),c=this.publication.getTOCItem(s);if(c===void 0&&this.publication.readingOrder&&(c=this.publication.readingOrder[o]),c){let f=this.publication.getAbsoluteHref(c.Href);(n=this.navigator.api)!=null&&n.getContent?await((i=this.navigator.api)==null?void 0:i.getContent(f).then(u=>{let m=new DOMParser().parseFromString(u,"application/xhtml+xml");c&&es(e,m,c.Href,c.Title).then(_=>{_.forEach(v=>{t.push(v),this.bookSearchResult.push(v)})})})):await fetch(f,this.navigator.requestConfig).then(u=>u.text()).then(async u=>{var _;let m=new DOMParser().parseFromString((_=this.navigator.requestConfig)!=null&&_.encoded?this.decodeBase64(u):u,"application/xhtml+xml");c&&es(e,m,c.Href,c.Title).then(v=>{v.forEach(g=>{t.push(g),this.bookSearchResult.push(g)})})})}if(o===this.publication.readingOrder.length-1)return t}}decodeBase64(e){let t=atob(e),n=t.length,i=new Uint8Array(n);for(let s=0;s<n;s++)i[s]=t.charCodeAt(s);return new TextDecoder().decode(i)}async searchChapter(e){var o,s;let t=[],n=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),i=this.publication.getTOCItem(n);if(i===null&&(i=this.publication.readingOrder[this.navigator.currentResource()??0]),i){let c=this.publication.getAbsoluteHref(i.Href);(o=this.navigator.api)!=null&&o.getContent?await((s=this.navigator.api)==null?void 0:s.getContent(c).then(f=>{let y=new DOMParser().parseFromString(f,"application/xhtml+xml");i&&es(e,y,i.Href,i.Title).then(m=>{m.forEach(_=>{t.push(_)})})})):await fetch(c,this.navigator.requestConfig).then(f=>f.text()).then(async f=>{var m;let y=new DOMParser().parseFromString((m=this.navigator.requestConfig)!=null&&m.encoded?this.decodeBase64(f):f,"application/xhtml+xml");i&&es(e,y,i.Href,i.Title).then(_=>{_.forEach(v=>{t.push(v)})})})}return t}drawSearch(){setTimeout(()=>{this.currentSearchHighlights=[],this.currentChapterSearchResult.forEach(e=>{var n,i;let t={rangeInfo:e.rangeInfo};if((n=this.properties)!=null&&n.color){let o=this.createSearchHighlight(t,(i=this.properties)==null?void 0:i.color);e.highlight=o,this.currentSearchHighlights.push(o)}})},100)}async handleResize(){var e;await((e=this.highlighter)==null?void 0:e.destroyHighlights(1)),this.drawSearch()}jumpToMark(e){setTimeout(()=>{var i,o,s;if(this.currentChapterSearchResult.length){var t=this.currentChapterSearchResult[e];this.currentSearchHighlights.forEach(c=>{var u;var f=(u=this.properties)==null?void 0:u.color;Jt.isHexColor(f)&&(f=Jt.hexToRgbChannels(f)),c.color=f});var n=(i=this.properties)==null?void 0:i.current;Jt.isHexColor(n)&&(n=Jt.hexToRgbChannels(n)),t.highlight.color=n,(o=this.highlighter)==null||o.setAndResetSearchHighlight(t.highlight,this.currentSearchHighlights),(s=this.navigator.view)==null||s.goToCssSelector(t.rangeInfo.startContainerElementCssSelector),this.navigator.updatePositionInfo()}},200)}paginate(e,t,n){let i=t||1,o=n||10,s=(i-1)*o,c=e.slice(s).slice(0,o),f=Math.ceil(e.length/o);return{page:i,per_page:o,pre_page:i-1?i-1:void 0,next_page:f>i?i+1:void 0,total:e.length,total_pages:f,data:c}}};L();var gn=rt($t()),sr=class sr{};sr.COLOR_REF="color",sr.AUTO_SCROLL_REF="autoscroll",sr.RATE_REF="rate",sr.PITCH_REF="pitch",sr.VOLUME_REF="volume",sr.VOICE_REF="voice",sr.COLOR_KEY="tts-"+sr.COLOR_REF,sr.AUTO_SCROLL_KEY="tts-"+sr.AUTO_SCROLL_REF,sr.RATE_KEY="tts-"+sr.RATE_REF,sr.PITCH_KEY="tts-"+sr.PITCH_REF,sr.VOLUME_KEY="tts-"+sr.VOLUME_REF,sr.VOICE_KEY="tts-"+sr.VOICE_REF;var st=sr,mh=class{constructor(e,t,n){this.TTSSETTINGS="ttsSetting";this.color="orange";this.autoScroll=!0;this.rate=1;this.pitch=1;this.volume=1;this.voice={usePublication:!0};this.settingsChangeCallback=()=>{};this.restartCallback=()=>{};this.store=e,this.api=t,this.headerMenu=n,this.initialise()}static create(e){let t=new this(e.store,e.api,e.headerMenu);if(e.initialTTSSettings){let n=e.initialTTSSettings;n!=null&&n.rate&&(t.rate=n.rate,gn.default.log(t.rate)),n!=null&&n.pitch&&(t.pitch=n.pitch,gn.default.log(t.pitch)),n!=null&&n.volume&&(t.volume=n.volume,gn.default.log(t.volume)),n!=null&&n.color&&(t.color=n.color,gn.default.log(t.color)),n!=null&&n.autoScroll&&(t.autoScroll=n.autoScroll,gn.default.log(t.autoScroll)),n!=null&&n.voice&&(t.voice=n.voice,gn.default.log(t.voice))}return t.initializeSelections(),t}stop(){gn.default.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty(st.AUTO_SCROLL_KEY)!=null?this.getProperty(st.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty(st.RATE_KEY)!=null?this.getProperty(st.RATE_KEY).value:this.rate,this.pitch=this.getProperty(st.PITCH_KEY)!=null?this.getProperty(st.PITCH_KEY).value:this.pitch,this.volume=this.getProperty(st.VOLUME_KEY)!=null?this.getProperty(st.VOLUME_KEY).value:this.volume,this.color=this.getProperty(st.COLOR_KEY)!=null?this.getProperty(st.COLOR_KEY).value:this.color,this.voice=this.getProperty(st.VOICE_REF)!=null?this.getProperty(st.VOICE_REF).value:this.voice,this.userProperties=this.getTTSSettings()}reset(){this.color="orange",this.autoScroll=!0,this.rate=1,this.pitch=1,this.volume=1,this.voice={usePublication:!0},this.userProperties=this.getTTSSettings()}initializeSelections(){this.headerMenu&&(this.settingsView=Ne(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(e){this.headerMenu&&(this.speechRate=Ne(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=Ne(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=Ne(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=Ne(this.headerMenu,"#autoScroll")),this.speechRate&&(this.speechRate.value=this.rate.toString()),this.speechPitch&&(this.speechPitch.value=this.pitch.toString()),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),_e(Ne(e,"ul"),"click",t=>{t.stopPropagation()})}onSettingsChange(e){this.settingsChangeCallback=e}onRestart(e){this.restartCallback=e}storeProperty(e){this.updateUserSettings(),this.saveProperty(e)}updateUserSettings(){var t,n,i,o,s,c,f,u;var e={rate:(t=this.userProperties.getByRef(st.RATE_REF))==null?void 0:t.value,pitch:(n=this.userProperties.getByRef(st.PITCH_REF))==null?void 0:n.value,volume:(i=this.userProperties.getByRef(st.VOLUME_REF))==null?void 0:i.value,voice:(o=this.userProperties.getByRef(st.VOLUME_REF))==null?void 0:o.value,color:(s=this.userProperties.getByRef(st.COLOR_REF))==null?void 0:s.value,autoScroll:(c=this.userProperties.getByRef(st.AUTO_SCROLL_REF))==null?void 0:c.value};this.applyTTSSettings(e),(f=this.api)!=null&&f.updateSettings&&((u=this.api)==null||u.updateSettings(e).then(async y=>{gn.default.log("api updated tts settings",y)}))}getTTSSettings(){var e=new ki;return e.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,st.AUTO_SCROLL_REF,st.AUTO_SCROLL_KEY),e.addIncremental(this.rate,.1,10,.1,"",st.RATE_REF,st.RATE_KEY),e.addIncremental(this.pitch,.1,2,.1,"",st.PITCH_REF,st.PITCH_KEY),e.addIncremental(this.volume,.1,1,.1,"",st.VOLUME_REF,st.VOLUME_KEY),e.addStringable(this.color,st.COLOR_REF,st.COLOR_KEY),e.addJSONable(JSON.stringify(this.voice),st.VOICE_REF,st.VOICE_KEY),e}saveProperty(e){let t=this.store.get(this.TTSSETTINGS);if(t){let n=JSON.parse(t);n=n.filter(i=>i.name!==e.name),n.push(e),this.store.set(this.TTSSETTINGS,JSON.stringify(n))}else{let n=[];n.push(e),this.store.set(this.TTSSETTINGS,JSON.stringify(n))}return e}getProperty(e){let t=this.store.get(this.TTSSETTINGS);if(t){let n=JSON.parse(t);return n=n.filter(i=>i.name===e),n.length===0?void 0:n[0]}}resetTTSSettings(){this.store.remove(this.TTSSETTINGS),this.reset(),this.settingsChangeCallback(),this.restartCallback()}applyTTSSettings(e){if(e.rate){gn.default.log("rate "+this.rate),this.rate=e.rate;let t=this.userProperties.getByRef(st.RATE_REF);t&&(t.value=this.rate,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.pitch){gn.default.log("pitch "+this.pitch),this.pitch=e.pitch;let t=this.userProperties.getByRef(st.PITCH_REF);t&&(t.value=this.pitch,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.volume){gn.default.log("volume "+this.volume),this.volume=e.volume;let t=this.userProperties.getByRef(st.VOLUME_REF);t&&(t.value=this.volume,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.color){this.color=e.color;let t=this.userProperties.getByRef(st.COLOR_REF);t&&(t.value=this.color,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoScroll!==void 0){gn.default.log("autoScroll "+this.autoScroll),this.autoScroll=e.autoScroll;let t=this.userProperties.getByRef(st.AUTO_SCROLL_REF);t&&(t.value=this.autoScroll,this.saveProperty(t)),this.settingsChangeCallback()}if(e.voice){gn.default.log("voice "+this.voice),this.voice=e.voice;let t=this.userProperties.getByRef(st.VOICE_REF);t&&(t.value=this.voice,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}}applyPreferredVoice(e){var t=e.indexOf(":")!==-1?e.slice(0,e.indexOf(":")):void 0,n=e.indexOf(":")!==-1?e.slice(e.indexOf(":")+1):e;t!==void 0&&n!==void 0?this.applyTTSSettings({voice:{usePublication:!0,name:t,lang:n}}):n!==void 0&&t===void 0&&this.applyTTSSettings({voice:{usePublication:!0,lang:n}})}increase(e){if(e==="rate"){this.userProperties.getByRef(st.RATE_REF).increment();let t=this.userProperties.getByRef(st.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="pitch"){this.userProperties.getByRef(st.PITCH_REF).increment();let t=this.userProperties.getByRef(st.PITCH_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="volume"){this.userProperties.getByRef(st.VOLUME_REF).increment();let t=this.userProperties.getByRef(st.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}}decrease(e){if(e==="rate"){this.userProperties.getByRef(st.RATE_REF).decrement();let t=this.userProperties.getByRef(st.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="pitch"){this.userProperties.getByRef(st.PITCH_REF).decrement();let t=this.userProperties.getByRef(st.PITCH_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="volume"){this.userProperties.getByRef(st.VOLUME_REF).decrement();let t=this.userProperties.getByRef(st.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}}};L();L();var yh=`${pi.loading}`,_C=`
|
|
82
|
+
</svg>`,pi={error:dn("error-icon","Warning",'<path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>'),home:'<path d="M12 5.69l5 4.5V18h-2v-6H9v6H7v-7.81l5-4.5M12 3L2 12h3v8h6v-6h2v6h6v-8h3L12 3z"/>',expand:dn("expand-icon","Enter fullscreen",'<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>',"icon active-icon"),loading:ZB("loading-icon","Loading",'<path fill="#BBBBBB" d="M145,241.6c-53.3,0-96.6-43.2-96.6-96.6c0-53.3,43.2-96.6,96.6-96.6c53.3,0,96.6,43.2,96.6,96.6 c0,26.7-10.8,50.9-28.3,68.3l7.6,7.6c19.4-19.4,31.5-46.3,31.5-75.9c0-59.3-48-107.3-107.3-107.3S37.7,85.7,37.7,145 c0,59.3,48,107.3,107.3,107.3V241.6z"/>',"0 0 290 290"),next:dn("next-icon","Next Chapter",'<path d="M6.49 20.13l1.77 1.77 9.9-9.9-9.9-9.9-1.77 1.77L14.62 12l-8.13 8.13z"/>'),previous:dn("previous-icon","Previous Chapter",'<path d="M17.51 3.87L15.73 2.1 5.84 12l9.9 9.9 1.77-1.77L9.38 12l8.13-8.13z"/>'),settings:dn("settings-icon","Settings",'<path d="M19.43 12.98c.04-.32.07-.64.07-.98 0-.34-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.09-.16-.26-.25-.44-.25-.06 0-.12.01-.17.03l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.06-.02-.12-.03-.18-.03-.17 0-.34.09-.43.25l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98 0 .33.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.09.16.26.25.44.25.06 0 .12-.01.17-.03l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.06.02.12.03.18.03.17 0 .34-.09.43-.25l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zm-1.98-1.71c.04.31.05.52.05.73 0 .21-.02.43-.05.73l-.14 1.13.89.7 1.08.84-.7 1.21-1.27-.51-1.04-.42-.9.68c-.43.32-.84.56-1.25.73l-1.06.43-.16 1.13-.2 1.35h-1.4l-.19-1.35-.16-1.13-1.06-.43c-.43-.18-.83-.41-1.23-.71l-.91-.7-1.06.43-1.27.51-.7-1.21 1.08-.84.89-.7-.14-1.13c-.03-.31-.05-.54-.05-.74s.02-.43.05-.73l.14-1.13-.89-.7-1.08-.84.7-1.21 1.27.51 1.04.42.9-.68c.43-.32.84-.56 1.25-.73l1.06-.43.16-1.13.2-1.35h1.39l.19 1.35.16 1.13 1.06.43c.43.18.83.41 1.23.71l.91.7 1.06-.43 1.27-.51.7 1.21-1.07.85-.89.7.14 1.13zM12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>',"icon open"),toc:dn("toc-icon","Table of Contents",'<path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/>',"icon open"),bookmarks:dn("toc-icon","Bookmarks",'<path d="M4,6H2v16h16v-2H4V6z"/><path d="M22,2H6v16h16V2z M20,12l-2.5-1.5L15,12V4h5V12z"/>',"icon open"),bookmark:dn("toc-icon","Bookmark",'<path d="M19,3H5v18l7-3l7,3V3z"/>',"icon open"),delete:dn("delete-icon","Delete",'<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>',"icon open"),close:dn("close-icon","Close",'<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>',"icon open"),text:dn("text-icon","Text",'<path d="M5 4v3h5.5v12h3V7H19V4z"/>',"icon open"),speak:dn("speak-icon","Speak",'<circle cx="9" cy="9" r="4"/><path d="M9 15c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4zm7.76-9.64l-1.68 1.69c.84 1.18.84 2.71 0 3.89l1.68 1.69c2.02-2.02 2.02-5.07 0-7.27zM20.07 2l-1.63 1.63c2.77 3.02 2.77 7.56 0 10.74L20.07 16c3.9-3.89 3.91-9.95 0-14z"/><path d="M0 0h24v24H0z" fill="none"/>',"icon open"),note:dn("note-icon","Note",'<polygon points="17.71 24.66 22.3 20.07 17.71 20.07 17.71 24.66" fill="none"/><path d="M22.42.07H5.58A3.28,3.28,0,0,0,2.29,3.35V24.79a3.28,3.28,0,0,0,3.29,3.28H16.71a1,1,0,0,0,.71-.29l8-8a1,1,0,0,0,.29-.71V3.35A3.28,3.28,0,0,0,22.42.07Zm-8.17,15h-7v-2h7Zm-7-6v-2h13v2ZM16.5,25.86v-6a1,1,0,0,1,1-1h6Z" />',"icon open"),highlight:dn("highlight-icon","Highlight",'<path d="M27.71,7.78,21.12,1.19a1,1,0,0,0-1.38,0L4.32,15A1,1,0,0,0,4,15.7a1,1,0,0,0,.3.73c1.22,1.22,1.2,2.37,0,3.62a1,1,0,0,0,0,1.41l3.2,3.2a1,1,0,0,0,1.41,0c1.28-1.28,2.36-1.29,3.62,0a1,1,0,0,0,1.45,0L27.74,9.16A1,1,0,0,0,27.71,7.78Z" /><path d="M3.09,22.59l-2.8,2.8a1,1,0,0,0-.21,1.09A1,1,0,0,0,1,27.1H4.6a1,1,0,0,0,.71-.29l1-1Z" />',"icon open")};var t1=rt(Nf());var Yr=rt($t()),ks=(f=>(f.R2_ID_HIGHLIGHTS_CONTAINER="R2_ID_HIGHLIGHTS_CONTAINER",f.R2_ID_BOOKMAKRS_CONTAINER="R2_ID_BOOKMAKRS_CONTAINER",f.R2_ID_READALOUD_CONTAINER="R2_ID_READALOUD_CONTAINER",f.R2_ID_PAGEBREAK_CONTAINER="R2_ID_PAGEBREAK_CONTAINER",f.R2_ID_SEARCH_CONTAINER="R2_ID_SEARCH_CONTAINER",f.R2_ID_DEFINITIONS_CONTAINER="R2_ID_DEFINITIONS_CONTAINER",f.R2_ID_LINEFOCUS_CONTAINER="R2_ID_LINEFOCUS_CONTAINER",f.R2_ID_GUTTER_RIGHT_CONTAINER="R2_ID_GUTTER_RIGHT_CONTAINER",f))(ks||{}),Tw="R2_CLASS_HIGHLIGHT_CONTAINER",Cl="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",Ur="R2_CLASS_HIGHLIGHT_AREA",Sl="R2_CLASS_HIGHLIGHT_ICON",Ui=.5,xw=.75,Rs={blue:100,green:50,red:230},er=[],tD="data-highlighted",rD="data-timestamp",Da={ELEMENT_NODE:1,TEXT_NODE:3};var Nn=["R2_ID_HIGHLIGHTS_CONTAINER","R2_ID_PAGEBREAK_CONTAINER","R2_ID_SEARCH_CONTAINER","R2_ID_READALOUD_CONTAINER","R2_ID_BOOKMAKRS_CONTAINER","R2_ID_DEFINITIONS_CONTAINER","R2_ID_LINEFOCUS_CONTAINER","R2_ID_GUTTER_RIGHT_CONTAINER",Tw,Ur,Cl],Zg=-1,e1=-1,Jt=class r{constructor(e,t,n,i,o){this.lastSelectedHighlight=void 0;this.activeAnnotationMarkerId=void 0;this.showTool=(0,Al.default)(e=>{this.isAndroid()||this.snapSelectionToWord(e),this.toolboxShow()},navigator.userAgent.toLowerCase().indexOf("firefox")>-1?200:100);this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,Al.default)(()=>{var e,t;this.isSelectionMenuOpen||(this.isSelectionMenuOpen=!0,(e=this.api)!=null&&e.selectionMenuOpen&&((t=this.api)==null||t.selectionMenuOpen()),this.navigator.emit("toolbox.opened","opened"))},100);this.selectionMenuClosed=(0,Al.default)(()=>{var e,t;this.isSelectionMenuOpen&&(this.isSelectionMenuOpen=!1,(e=this.api)!=null&&e.selectionMenuClose&&((t=this.api)==null||t.selectionMenuClose()),this.navigator.emit("toolbox.closed","closed"))},100);this.selection=(0,Al.default)((e,t)=>{var n,i;(n=this.api)!=null&&n.selection&&((i=this.api)==null||i.selection(e,t))},100);this.getScrollingElement=e=>e!=null&&e.scrollingElement?e==null?void 0:e.scrollingElement:e!=null&&e.body?e==null?void 0:e.body:document.createElement("body");this.layerSettings=e,this.properties=t,this.properties.menuPosition===void 0&&(this.properties.menuPosition="inline"),this.api=o,this.hasEventListener=n,this.options=this.defaults(i,{color:"#fce300",highlightedClass:"highlighted",contextClass:"highlighter-context",onBeforeHighlight:function(){return!0},onAfterHighlight:function(){}})}static async create(e){let t=new this(e.layerSettings,e,!1,{},e.api);return new Promise(n=>n(t))}async initialize(){var i;let e=this.navigator.iframes[0].contentDocument;e&&this.dom(e.body).addClass(this.options.contextClass),this.bindEvents((i=this.navigator.iframes[0].contentDocument)==null?void 0:i.body,this,this.hasEventListener),this.initializeToolbox(),Zg=-1,e1=-1;let t=this;async function n(){t.lastSelectedHighlight===void 0||(t.lastSelectedHighlight=void 0)}setTimeout(async()=>{var s;let o=this.navigator.iframes[0].contentDocument;o&&await((s=o.body)==null?void 0:s.addEventListener("click",n))},100)}haveSameColor(e,t){return this.dom(e).color()===this.dom(t).color()}defaults(e,t){e=e||{};for(let n in t)t.hasOwnProperty(n)&&e[n]===void 0&&(e[n]=t[n]);return e}unique(e){return e.filter(function(t,n,i){return i.indexOf(t)===n})}refineRangeBoundaries(e){let t=e.startContainer,n=e.endContainer,i=e.commonAncestorContainer,o=!0;if(e.endOffset===0){for(;!n.previousSibling&&n.parentNode!==i;)n=n.parentNode;n=n.previousSibling}else n.nodeType===Da.TEXT_NODE?e.endOffset<n.nodeValue.length&&n.splitText(e.endOffset):e.endOffset>0&&(n=n.childNodes.item(e.endOffset-1));return t.nodeType===Da.TEXT_NODE?e.startOffset===t.nodeValue.length?o=!1:e.startOffset>0&&(t=t.splitText(e.startOffset),n===t.previousSibling&&(n=t)):e.startOffset<t.childNodes.length?t=t.childNodes.item(e.startOffset):t=t.nextSibling,{startContainer:t,endContainer:n,goDeeper:o}}sortByDepth(e,t){let n=this;e.sort(function(i,o){return n.dom(t?o:i).parents().length-n.dom(t?i:o).parents().length})}groupHighlights(e){let t=[],n={},i=[];return e.forEach(function(o){let s=o.getAttribute(rD);typeof n[s]>"u"&&(n[s]=[],t.push(s)),n[s].push(o)}),t.forEach(function(o){let s=n[o];i.push({chunks:s,timestamp:o,toString:function(){return s.map(function(c){return c.textContent}).join("")}})}),i}dom(e){let t=this;return{addClass:function(n){e.classList?e.classList.add(n):e.className+=" "+n},removeClass:function(n){e.classList?e.classList.remove(n):e.className=e.className.replace(new RegExp("(^|\\b)"+n+"(\\b|$)","gi")," ")},prepend:function(n){let i=Array.prototype.slice.call(n),o=i.length;for(;o--;)e.insertBefore(i[o],e.firstChild)},append:function(n){let i=Array.prototype.slice.call(n);for(let o=0,s=i.length;o<s;++o)e.appendChild(i[o])},insertAfter:function(n){var i;return(i=n.parentNode)==null?void 0:i.insertBefore(e,n.nextSibling)},insertBefore:function(n){var i;return(i=n.parentNode)==null?void 0:i.insertBefore(e,n)},remove:function(){e.parentNode.removeChild(e),e=null},contains:function(n){return e!==n&&e.contains(n)},wrap:function(n){return e.parentNode&&e.parentNode.insertBefore(n,e),n.appendChild(e),n},unwrap:function(){let n=Array.prototype.slice.call(e.childNodes),i;return n.forEach(function(o){i=o.parentNode,t.dom(o).insertBefore(o.parentNode),t.dom(i).remove()}),n},parents:function(){let n,i=[];for(;n=e.parentNode;)i.push(n),e=n;return i},normalizeTextNodes:function(){if(e){if(e.nodeType===Da.TEXT_NODE)for(;e.nextSibling&&e.nextSibling.nodeType===Da.TEXT_NODE;)e.nodeValue+=e.nextSibling.nodeValue,e.parentNode.removeChild(e.nextSibling);else t.dom(e.firstChild).normalizeTextNodes();t.dom(e.nextSibling).normalizeTextNodes()}},color:function(){return e.style.backgroundColor},fromHTML:function(n){let i=document.createElement("div");return i.innerHTML=n,i.childNodes},getRange:function(){var o;let n=(o=t.dom(e))==null?void 0:o.getSelection(),i;return(n==null?void 0:n.rangeCount)>0&&(i=n==null?void 0:n.getRangeAt(0)),i},removeAllRanges:function(){var i;let n=(i=t.dom(e))==null?void 0:i.getSelection();n==null||n.removeAllRanges(),t.toolboxHide()},getSelection:function(){var n;return(n=t.dom(e).getWindow())==null?void 0:n.getSelection()},getWindow:function(){var n;return(n=t.dom(e).getDocument())==null?void 0:n.defaultView},getDocument:function(){return(e==null?void 0:e.ownerDocument)||e}}}disableContext(e){return e.preventDefault(),e.stopPropagation(),!1}bindEvents(e,t,n){let i=e.ownerDocument;e.addEventListener("mouseup",this.toolboxShowDelayed.bind(this)),e.addEventListener("touchend",this.toolboxShowDelayed.bind(this)),i.addEventListener("mouseup",this.toolboxShowDelayed.bind(this)),i.addEventListener("touchend",this.toolboxShowDelayed.bind(this)),n||window.addEventListener("resize",this.toolboxPlacement.bind(this)),i.addEventListener("selectionchange",this.toolboxPlacement.bind(this)),this.isIOS()||i.addEventListener("selectionchange",this.toolboxShowDelayed.bind(this)),e.addEventListener("mousedown",this.toolboxHide.bind(this)),e.addEventListener("touchstart",this.toolboxHide.bind(this)),this.isAndroid()&&e.addEventListener("contextmenu",this.disableContext),e.addEventListener("mousedown",this.mousedown.bind(this)),e.addEventListener("mouseup",this.mouseup.bind(this)),e.addEventListener("touchstart",this.mousedown.bind(this)),e.addEventListener("touchend",this.mouseup.bind(this)),this.hasEventListener=!0}async mousedown(e){var t;if(Zg=e.clientX,e1=e.clientY,(t=this.properties)!=null&&t.preventScrollOnSelection){let n=ft(document,"#iframe-wrapper");n.style.overflow="hidden"}}async mouseup(e){Math.abs(Zg-e.clientX)<3&&Math.abs(e1-e.clientY)<3&&await this.processMouseEvent(e)}async mousemove(e){await this.processMouseEvent(e)}unbindEvents(e,t){let n=e.ownerDocument;e.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),e.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),n.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),n.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),window.removeEventListener("resize",this.toolboxPlacement.bind(this)),n.removeEventListener("selectionchange",this.toolboxPlacement.bind(this)),e.removeEventListener("mousedown",this.toolboxHide.bind(this)),e.removeEventListener("touchstart",this.toolboxHide.bind(this)),this.isAndroid()&&e.removeEventListener("contextmenu",this.disableContext),e.removeEventListener("mousedown",this.mousedown.bind(this)),e.removeEventListener("mouseup",this.mouseup.bind(this)),e.removeEventListener("mousemove",this.mousemove.bind(this)),e.removeEventListener("touchstart",this.mousedown.bind(this)),e.removeEventListener("touchend",this.mouseup.bind(this)),e.removeEventListener("touchmove",this.mousemove.bind(this)),this.hasEventListener=!1}destroy(){this.toolboxHide();let e=this.navigator.iframes[0].contentDocument;e&&(this.unbindEvents(e.body,this),this.dom(e.body).removeClass(this.options.contextClass))}initializeToolbox(){let e=document.getElementById("highlight-toolbox-mode-colors"),t=document.getElementById("highlight-toolbox-mode-add"),n=["#fce300","#48e200","#00bae5","#157cf9","#6a39b7","#ea426a","#ff8500"],i=document.getElementById("colorIcon"),o=document.getElementById("actionIcon"),s=document.getElementById("dismissIcon"),c=document.getElementById("collapseIcon"),f=document.getElementById("highlightIcon"),u=this;if(s&&(s.innerHTML=pi.close,s.addEventListener("click",function(){u.toolboxMode("add")})),c&&(c.innerHTML=pi.close,c.addEventListener("click",function(){u.toolboxMode("add")})),i){i.style.position="relative",i.style.zIndex="20",n.forEach(_=>{let v=document.getElementById(_),g=document.getElementById(`c${_}`);v&&(e!=null&&e.contains(v))&&e.removeChild(v),t&&g&&t.contains(g)&&t.removeChild(g)});let y=[],m=[];if(i.addEventListener("click",function(){u.toolboxMode("colors")}),this.navigator.rights.enableAnnotations){let _=10;n.forEach(v=>{_--;let g=i==null?void 0:i.cloneNode(!0),h=g.lastChild,l=r.hexToRgbChannels(v);h.style.backgroundColor="rgba("+[l.red,l.green,l.blue].join(",")+",.5)",g.id=`c${v}`,g.style.display="unset",g.style.position="relative",g.style.zIndex=`${_}`,g.style.marginLeft="-30px",m.push(g),t==null||t.insertBefore(g,f)})}n.forEach(_=>{let v=i==null?void 0:i.cloneNode(!0),g=v.lastChild;g.style.backgroundColor=_,v.id=_,v.style.position="relative",v.style.display="unset",y.push(v),i&&v.addEventListener("click",function(){var A,C,b;u.setColor(_);let h=i==null?void 0:i.lastChild;h&&(h.style.backgroundColor=_);let l=document.getElementById("highlightIcon"),p=document.getElementById("underlineIcon"),w=document.getElementById("noteIcon");(((A=l==null?void 0:l.getElementsByTagName)==null?void 0:A.call(l,"span").length)??0)>0&&((l==null?void 0:l.getElementsByTagName("span")[0]).style.background=u.getColor()),(((C=p==null?void 0:p.getElementsByTagName)==null?void 0:C.call(p,"span").length)??0)>0&&((p==null?void 0:p.getElementsByTagName("span")[0]).style.borderBottomColor=u.getColor()),(((b=w==null?void 0:w.getElementsByTagName)==null?void 0:b.call(w,"span").length)??0)>0&&((w==null?void 0:w.getElementsByTagName("span")[0]).style.borderBottomColor=u.getColor()),u.toolboxMode("add")}),e==null||e.insertBefore(v,s)})}o&&o.addEventListener("click",function(){u.toolboxMode("action")}),u.toolboxMode("add")}toolboxMode(e){let t=document.getElementById("highlight-toolbox-mode-colors"),n=document.getElementById("highlight-toolbox-mode-add"),i=document.getElementById("highlight-toolbox-mode-edit"),o=document.getElementById("highlight-toolbox-mode-action");switch(e){case"colors":t&&(t.style.display="unset"),n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none");break;case"edit":t&&(t.style.display="none"),n&&(n.style.display="none"),i&&(i.style.display="unset"),o&&(o.style.display="none");break;case"action":t&&(t.style.display="none"),n&&(n.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="unset");break;default:t&&(t.style.display="none"),n&&(n.style.display="unset"),i&&(i.style.display="none"),o&&(o.style.display="none");break}}toolboxHide(){var t;let e=document.getElementById("highlight-toolbox");if(e&&(e.style.display="none"),this.selectionMenuClosed(),(t=this.properties)!=null&&t.preventScrollOnSelection){let n=ft(document,"#iframe-wrapper");n.style.overflow="auto"}}toolboxShowDelayed(e){this.showTool(e.detail===1)}snapSelectionToWord(e=!1){var o;let t=this,n=this.navigator.iframes[0].contentDocument;if(n){let s=(o=t.dom(n.body))==null?void 0:o.getSelection();if(t.dom(n.body)&&s&&!(s!=null&&s.isCollapsed)){let y=function(p){let w=p.match(new RegExp("[^a-zA-Z0-9]+$"));return!w||!w.index?p:p.slice(0,w.index)},c=s.toString(),f=c.length-c.trimStart().length,u=c.length-c.trimEnd().length,m=c.length;var i=/[-!$%^&*()_+|~=`{}[\]:/;<>?,.@#]/;c=c.replace(i,""),f=m-c.trimStart().length,c=y(c),u=m-c.trimEnd().length;let _=document.createRange();e?(_.setStart(s.anchorNode,s.anchorOffset+f),_.setEnd(s.focusNode,s.focusOffset-u)):(_.setStart(s.anchorNode,s.anchorOffset),_.setEnd(s.focusNode,s.focusOffset));let v=_.collapsed;_.detach();let g=s.focusNode,h;e?(h=s.focusOffset-u,s.collapse(s.anchorNode,s.anchorOffset+f)):(h=s.focusOffset,s.collapse(s.anchorNode,s.anchorOffset));let l=["forward","backward"];v&&(l=["backward","forward"]),e?(s.modify("move",l[0],"character"),s.modify("move",l[1],"word"),s.extend(g,h),s.modify("extend",l[1],"character"),s.modify("extend",l[0],"word")):s.extend(g,h),this.selection(s.toString(),s)}return s}}toolboxShow(){var e;if(this.activeAnnotationMarkerId===void 0){let t=this,n=document.getElementById("highlight-toolbox-mode-add"),i=this.dom((e=this.navigator.iframes[0].contentDocument)==null?void 0:e.body).getRange();if((!i||i.collapsed)&&n){getComputedStyle(n).display!=="none"&&t.toolboxHide();return}this.isIOS()&&setTimeout(function(){let o=t.navigator.iframes[0].contentDocument;if(o){let s=t.dom(o.body).getSelection();s.removeAllRanges(),setTimeout(function(){var y,m;s.addRange(i);function c(_){let v={className:h=>Nn.indexOf(h)<0,idName:h=>Nn.indexOf(h)<0},g=t.navigator.iframes[0].contentDocument;if(g)return Ar(_,g,v)}let f=t.navigator.iframes[0].contentWindow,u=Hi(f,c);(m=(y=t.navigator.annotationModule)==null?void 0:y.annotator)==null||m.saveTemporarySelectionInfo(u)},5)}},100),this.toolboxPlacement(),this.toolboxHandler()}}toolboxPlacement(){var i,o,s,c,f;let e=this.dom((i=this.navigator.iframes[0].contentDocument)==null?void 0:i.body).getRange();if(!e||e.collapsed)return;let t=e.getBoundingClientRect(),n=document.getElementById("highlight-toolbox");n&&(((o=this.properties)==null?void 0:o.menuPosition)==="top"?(n.style.left="0px",n.style.transform="revert",n.style.width="100%",n.style.textAlign="center",n.style.position="absolute",n.style.setProperty("--content","revert")):((s=this.properties)==null?void 0:s.menuPosition)==="bottom"?(n.style.bottom="0px",n.style.left="0px",n.style.transform="revert",n.style.width="100%",n.style.textAlign="center",n.style.position="absolute",n.style.setProperty("--content","revert")):(((c=this.navigator.view)==null?void 0:c.isPaginated())?n.style.top=t.top+(((f=this.navigator.attributes)==null?void 0:f.navHeight)??0)+"px":n.style.top=t.top+"px",n.style.left=(t.right-t.left)/2+t.left+"px"))}toolboxHandler(){var t,n,i,o,s,c,f;let e=document.getElementById("highlight-toolbox");if(e&&getComputedStyle(e).display==="none"){e.style.display="block",((t=this.navigator.view)==null?void 0:t.isPaginated())?e.style.position="absolute":e.style.position="relative",this.selectionMenuOpened();let y=this;y.toolboxMode("add");let m=document.getElementById("highlightIcon"),_=document.getElementById("collapseIcon"),v=document.getElementById("underlineIcon"),g=document.getElementById("noteIcon"),h=document.getElementById("colorIcon"),l=document.getElementById("speakIcon");if(this.navigator.rights.enableAnnotations){if(m&&(m.style.display="unset",h&&m.getElementsByTagName("span").length>0&&(m.getElementsByTagName("span")[0].style.background=this.getColor())),v&&(v.style.display="unset",h&&v.getElementsByTagName("span").length>0&&(v.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),g&&(g.style.display="unset",h&&g.getElementsByTagName("span").length>0&&(g.getElementsByTagName("span")[0].style.borderBottomColor=this.getColor())),h){h.style.display="unset";let p=h.lastChild;p.style.backgroundColor=this.getColor()}if(m){let p=function(){y.doHighlight(!1,0),y.toolboxHide(),m==null||m.removeEventListener("click",p)},w=m.cloneNode(!0);(n=m==null?void 0:m.parentNode)==null||n.replaceChild(w,m),m=document.getElementById("highlightIcon"),m==null||m.addEventListener("click",p)}if(v){let p=function(){y.doHighlight(!1,1),y.toolboxHide(),v==null||v.removeEventListener("click",p)},w=v.cloneNode(!0);(i=v==null?void 0:v.parentNode)==null||i.replaceChild(w,v),v=document.getElementById("underlineIcon"),v==null||v.addEventListener("click",p)}if(g){let p=function(){y.doHighlight(!1,4),y.toolboxHide(),g==null||g.removeEventListener("click",p)},w=g.cloneNode(!0);(o=g==null?void 0:g.parentNode)==null||o.replaceChild(w,g),g=document.getElementById("noteIcon"),g==null||g.addEventListener("click",p)}}else m&&m.style.setProperty("display","none"),v&&v.style.setProperty("display","none"),g&&g.style.setProperty("display","none"),h&&h.style.setProperty("display","none"),_&&_.style.setProperty("display","none");if(this.navigator.rights.enableTTS){if(l){let p=function(){l==null||l.removeEventListener("click",p),y.speak()},w=l.cloneNode(!0);(s=l==null?void 0:l.parentNode)==null||s.replaceChild(w,l),l=document.getElementById("speakIcon"),l==null||l.addEventListener("click",p)}}else l&&l.style.setProperty("display","none");(((c=this.properties)==null?void 0:c.selectionMenuItems)??[])&&(((f=this.properties)==null?void 0:f.selectionMenuItems)??[]).forEach(p=>{var b;p.icon&&(p.icon.id=p.id);let w=document.getElementById(p.id),A=this;function C(){var P,N,D,F,B,V,q;w==null||w.removeEventListener("click",C);function E(G){let Y={className:Q=>Nn.indexOf(Q)<0,idName:Q=>Nn.indexOf(Q)<0},X=A.navigator.iframes[0].contentDocument;if(X)return Ar(G,X,Y)}let k=A.navigator.iframes[0].contentWindow;if(k){let G=Hi(k,E);if(G===void 0){let Y=A.navigator.iframes[0].contentDocument;G=(N=(P=A.navigator.annotationModule)==null?void 0:P.annotator)==null?void 0:N.getTemporarySelectionInfo(Y)}if(G!==void 0)if(p.callback)p.callback(G.cleanText,(D=G.range)==null?void 0:D.startContainer.parentElement);else{let Y=(F=p.highlight)==null?void 0:F.style,X=p.marker?p.marker:3;if(X===3&&A.navigator.rights.enableAnnotations||X===2&&A.navigator.rights.enableBookmarks){let Q=A.navigator.iframes[0].contentDocument;if(Q){let le=A.createHighlight(A.dom(Q.body).getWindow(),G,(B=p.highlight)==null?void 0:B.color,!0,X,p.icon,p.popup,Y);A.options.onAfterHighlight(le,X),A.navigator.rights.enableAnnotations?(V=A.navigator.annotationModule)==null||V.saveAnnotation(le[0]).then(ve=>{var ce,W;p!=null&&p.note&&ve.highlight&&((W=(ce=A.navigator.annotationModule)==null?void 0:ce.api)==null||W.addCommentToAnnotation(ve).then(H=>{var R;(R=A.navigator.annotationModule)==null||R.updateAnnotation(H).then(async()=>{Yr.default.log("update highlight "+H.id)})}))}):A.navigator.rights.enableBookmarks&&((q=A.navigator.bookmarkModule)==null||q.saveAnnotation(le[0]))}}}}A.callbackComplete()}if(w){let E=w.cloneNode(!0);(b=w==null?void 0:w.parentNode)==null||b.replaceChild(E,w),w=document.getElementById(p.id),w==null||w.addEventListener("click",C)}})}}doHighlight(e,t){var s,c,f,u,y,m;let n=this;function i(_){let v={className:h=>Nn.indexOf(h)<0,idName:h=>Nn.indexOf(h)<0},g=n.navigator.iframes[0].contentDocument;if(g)return Ar(_,g,v)}let o=n.navigator.iframes[0].contentWindow;if(o){let _=Hi(o,i);if(_===void 0){let v=n.navigator.iframes[0].contentDocument;_=(c=(s=this.navigator.annotationModule)==null?void 0:s.annotator)==null?void 0:c.getTemporarySelectionInfo(v)}if(_){if(this.options.onBeforeHighlight(_)===!0){let v;v=this.getColor(),r.isHexColor(v)&&(v=r.hexToRgbChannels(v));let g=n.navigator.iframes[0].contentDocument;if(g){let h=this.createHighlight(n.dom(g.body).getWindow(),_,v,!0,t??0);this.options.onAfterHighlight(h,t),this.navigator.rights.enableAnnotations&&t!==2?(f=this.navigator.annotationModule)==null||f.saveAnnotation(h[0]):this.navigator.rights.enableBookmarks&&t===2&&((u=this.navigator.bookmarkModule)==null||u.saveAnnotation(h[0]))}}e||this.dom((y=this.navigator.iframes[0].contentDocument)==null?void 0:y.body).removeAllRanges()}else e||this.dom((m=this.navigator.iframes[0].contentDocument)==null?void 0:m.body).removeAllRanges()}}speak(){var e,t;if(this.navigator.rights.enableTTS){let i=function(f){let u={className:m=>Nn.indexOf(m)<0,idName:m=>Nn.indexOf(m)<0},y=n.navigator.iframes[0].contentDocument;if(y)return Ar(f,y,u)},n=this,o=n.navigator.iframes[0].contentWindow;if(o){let f=Hi(o,i);if(f===void 0){let u=n.navigator.iframes[0].contentDocument;f=(t=(e=n.navigator.annotationModule)==null?void 0:e.annotator)==null?void 0:t.getTemporarySelectionInfo(u)}f!==void 0&&this.navigator.ttsModule.speak(f,!0,()=>{})}let s=n.navigator.iframes[0].contentDocument;s&&n.dom(s.body).getSelection().removeAllRanges();let c=document.getElementById("highlight-toolbox");c&&(c.style.display="none"),this.selectionMenuClosed()}}stopReadAloud(){this.navigator.rights.enableTTS&&this.doneSpeaking()}callbackComplete(){this.toolboxHide();let e=this.navigator.iframes[0].contentDocument;e&&this.dom(e.body).removeAllRanges()}isOutsideViewport(e){let t=ft(document,"#iframe-wrapper"),n=t.scrollLeft,i=n+t.clientWidth,o=e.left+e.width,s=e.top+e.height,c=t.scrollTop,f=c+t.clientHeight,u=s<c,y=e.top>f,m=o<n,_=e.left>i;return u||y||m||_}isInsideViewport(e){let t=ft(document,"#iframe-wrapper"),n=t.scrollTop,i=n+t.clientHeight,o=e.top+20>=n,s=e.top<=i,c=t.scrollLeft,f=c+t.clientWidth,u=e.left+e.width,y=e.left>c,m=u<f;return o&&s&&y&&m}get visibleTextRects(){let e=this.navigator.iframes[0].contentDocument;if(e){let n=function(c,f=[]){var y;let u=c.firstChild;for(;u;)u.nodeType===1&&n(u,f),u.nodeType===3&&(y=u.textContent)!=null&&y.trim()&&f.push(u),u=u.nextSibling;return f},i=function(c){return n(c).map(u=>{let{top:y,height:m,left:_,width:v}=o(u);return{top:y,height:m,width:v,left:_,node:u,textContent:u.textContent??""}})},o=function(c){try{let f=document.createRange();f.selectNode(c);let u=f.getBoundingClientRect();return f.detach(),u}catch(f){Yr.default.log("measureTextNode "+f),Yr.default.log("measureTextNode "+c),Yr.default.log(`${c.textContent}`)}},t=lo(e,"body");return i(t).filter(c=>this.isInsideViewport(c))}return[]}doneSpeaking(e=!1){if(this.navigator.rights.enableTTS){this.toolboxHide();let t=this.navigator.iframes[0].contentDocument;t&&this.dom(t.body).removeAllRanges(),this.navigator.ttsModule.cancel(),e&&this.navigator.reload()}}normalizeHighlights(e){var t;return t=e.filter(function(n){return n.parentElement?n:null}),t=this.unique(t),t.sort(function(n,i){return n.offsetTop-i.offsetTop||n.offsetLeft-i.offsetLeft}),t}flattenNestedHighlights(e){let t,n=this;n.sortByDepth(e,!0);function i(){let o=!1;return e.forEach(function(s,c){let f=s.parentElement,u=f.previousSibling,y=f.nextSibling;n.isHighlight(f)&&(n.haveSameColor(f,s)?(f.replaceChild(s.firstChild,s),e[c]=f,o=!0):(s.nextSibling||(n.dom(s).insertBefore(y||f),o=!0),s.previousSibling||(n.dom(s).insertAfter(u||f),o=!0),f.hasChildNodes()||n.dom(f).remove()))}),o}do t=i();while(t)}mergeSiblingHighlights(e){let t=this;function n(i,o){return o&&o.nodeType===Da.ELEMENT_NODE&&t.haveSameColor(i,o)&&t.isHighlight(o)}e.forEach(function(i){let o=i.previousSibling,s=i.nextSibling;n(i,o)&&(t.dom(i).prepend(o.childNodes),t.dom(o).remove()),n(i,s)&&(t.dom(i).append(s.childNodes),t.dom(s).remove()),t.dom(i).normalizeTextNodes()})}setColor(e){this.options.color=e}getColor(){return this.options.color}isHighlight(e){return e&&e.nodeType===Da.ELEMENT_NODE&&e.hasAttribute(tD)}createWrapper(){let e=document.createElement("mark");return e.style.background="linear-gradient("+r.hexToRgbA(this.options.color)+", "+r.hexToRgbA(this.options.color)+")",e.className=this.options.highlightedClass,e}static isHexColor(e){return/^#([A-Fa-f0-9]{3}){1,2}$/.test(e)}static hexToRgbString(e){let t;return t=e.substring(1).split(""),t.length===3&&(t=[t[0],t[0],t[1],t[1],t[2],t[2]]),t="0x"+t.join(""),t}static hexToRgbChannels(e){let t;if(this.isHexColor(e))return t=this.hexToRgbString(e),{red:t>>16&255,green:t>>8&255,blue:t&255};throw new Error("Bad Hex")}static hexToRgbA(e){let t;if(this.isHexColor(e))return t=this.hexToRgbChannels(e),"rgba("+[t.red,t.green,t.blue].join(",")+",.5)";if(typeof e=="object"){let n=e;return"rgba("+[n.red,n.green,n.blue].join(",")+",.5)"}throw new Error("Bad Hex")}static hexToRgbAWithOpacity(e,t){let n;if(this.isHexColor(e))return n=this.hexToRgbChannels(e),"rgba("+[n.red,n.green,n.blue].join(",")+","+t+")";if(typeof e=="object"){let i=e;return"rgba("+[i.red,i.green,i.blue].join(",")+","+t+")"}throw new Error("Bad Hex")}resetHighlightBoundingStyle(e){e.style.outline="none",e.style.setProperty("background-color","transparent","important")}resetHighlightAreaStyle(e,t){var o,s,c,f,u,y,m,_,v,g,h,l,p,w,A;let n=(o=this.navigator.iframes[0].contentWindow)==null?void 0:o.document,i=e.parentNode&&e.parentNode.nodeType===Node.ELEMENT_NODE&&e.parentNode.getAttribute?e.parentNode.getAttribute("id"):void 0;if(i){let C=er.find(b=>b.id===i);if(C){if(C.marker===3||C.marker===2)if((s=C.style)!=null&&s.hover){if((c=C.style)!=null&&c.hover)for(let k=0;k<((u=(f=C.style)==null?void 0:f.hover)==null?void 0:u.length);k++){let P=(y=C.style)==null?void 0:y.hover[k];e.style.removeProperty(P.property)}let E="";if((m=C.style)!=null&&m.default)for(let k=0;k<((v=(_=C.style)==null?void 0:_.default)==null?void 0:v.length);k++){let P=(g=C.style)==null?void 0:g.default[k];e.style.removeProperty(P.property),E+=`${P.property}: ${P.value} !${P.priority};`}e.setAttribute("style",`${e.getAttribute("style")}; ${E}`)}else if((h=C.style)!=null&&h.hoverClass){(l=C.style)!=null&&l.hoverClass&&e.classList.remove((p=C.style)==null?void 0:p.hoverClass);let E="";(w=C.style)!=null&&w.defaultClass&&e.classList.add((A=C.style)==null?void 0:A.defaultClass),e.setAttribute("style",`${e.getAttribute("style")}; ${E}`)}else if(r.isHexColor(C.color)){let E=r.hexToRgbChannels(C.color);e.style.setProperty("background-color",`rgba(${E.red}, ${E.green}, ${E.blue}, 0)`,"important")}else e.classList.remove("hover");else if(C.marker===1||C.marker===4)if(typeof C.color=="object"){let E=C.color;e.style.setProperty("background-color",`rgba(${E.red}, ${E.green}, ${E.blue}, 0)`,"important"),e.style.setProperty("border-bottom",`2px solid rgba(${E.red}, ${E.green}, ${E.blue}, 1)`,"important")}else if(r.isHexColor(C.color)){let E=r.hexToRgbChannels(C.color);e.style.setProperty("background-color",`rgba(${E.red}, ${E.green}, ${E.blue}, 0)`,"important"),e.style.setProperty("border-bottom",`2px solid rgba(${E.red}, ${E.green}, ${E.blue}, 1)`,"important")}else e.classList.remove("hover");else if(typeof C.color=="object"){let E=C.color;e.style.setProperty("background-color",`rgba(${E.red}, ${E.green}, ${E.blue}, ${Ui})`,"important")}else if(r.isHexColor(C.color)){let E=r.hexToRgbChannels(C.color);e.style.setProperty("background-color",`rgba(${E.red}, ${E.green}, ${E.blue}, ${Ui})`,"important")}else e.classList.remove("hover");let b;if(n){let E=n.getElementById(t);E&&(b=E.querySelector(`#${C.id}`))}if(b){let E=b.getElementsByClassName(Sl);if(E.length>0){let k=E.item(0).getElementsByClassName("icon-tooltip");k.length>0&&k.item(0).style.removeProperty("display")}}}}}setHighlightAreaStyle(e,t,n){var i,o,s,c,f,u,y,m,_,v,g,h;for(let l of t){if(n.marker===3||n.marker===2)if((i=n.style)!=null&&i.hover){if((o=n.style)!=null&&o.default)for(let w=0;w<((c=(s=n.style)==null?void 0:s.default)==null?void 0:c.length);w++){let A=(f=n.style)==null?void 0:f.default[w];l.style.removeProperty(A.property)}let p="";for(let w=0;w<((y=(u=n.style)==null?void 0:u.hover)==null?void 0:y.length);w++){let A=(m=n.style)==null?void 0:m.hover[w];l.style.removeProperty(A.property),p+=`${A.property}: ${A.value} !${A.priority};`}l.setAttribute("style",`${l.getAttribute("style")}; ${p}`)}else if((_=n.style)!=null&&_.hoverClass){(v=n.style)!=null&&v.defaultClass&&l.classList.remove((g=n.style)==null?void 0:g.defaultClass);let p="";l.classList.add((h=n.style)==null?void 0:h.hoverClass),l.setAttribute("style",`${l.getAttribute("style")}; ${p}`)}else if(r.isHexColor(n.color)){let p=r.hexToRgbChannels(n.color);l.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${.1})`,"important")}else l.classList.add("hover");else if(n.marker===1||n.marker===4)if(typeof n.color=="object"){let p=n.color;l.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${.1})`,"important"),l.style.setProperty("border-bottom",`2px solid rgba(${p.red}, ${p.green}, ${p.blue}, 1)`,"important")}else if(r.isHexColor(n.color)){let p=r.hexToRgbChannels(n.color);l.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${.1})`,"important"),l.style.setProperty("border-bottom",`2px solid rgba(${p.red}, ${p.green}, ${p.blue}, 1)`,"important")}else l.classList.add("hover");else if(typeof n.color=="object"){let p=n.color;l.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${xw})`,"important")}else if(r.isHexColor(n.color)){let p=r.hexToRgbChannels(n.color);l.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${xw})`,"important")}else l.classList.add("hover");if(n.type!==4){let w=e.getElementById("R2_ID_HIGHLIGHTS_CONTAINER").querySelector(`#${n.id}`).getElementsByClassName(Sl);if(w.length>0){let A=w.item(0).getElementsByClassName("icon-tooltip");A.length>0&&A.item(0).style.setProperty("display","block")}}}}setAndResetSearchHighlight(e,t){var o;let n=(o=this.navigator.iframes[0].contentWindow)==null?void 0:o.document,i=Array.from(n.getElementById("R2_ID_SEARCH_CONTAINER").querySelectorAll(`.${Ur}`));for(let s of i){let c=s,f=c.parentNode&&c.parentNode.nodeType===Node.ELEMENT_NODE&&c.parentNode.getAttribute?c.parentNode.getAttribute("id"):void 0;if(t.forEach(u=>{if(f===u.id&&u){if(typeof u.color=="object"){let _=u.color;c.style.setProperty("background-color",`rgba(${_.red}, ${_.green}, ${_.blue}, ${Ui})`,"important")}else if(r.isHexColor(u.color)){let _=r.hexToRgbChannels(u.color);c.style.setProperty("background-color",`rgba(${_.red}, ${_.green}, ${_.blue}, ${Ui})`,"important")}else c.classList.remove("hover");let m=n.getElementById("R2_ID_SEARCH_CONTAINER").querySelector(`#${u.id}`).getElementsByClassName(Sl);if(m.length>0){let _=m.item(0).getElementsByClassName("icon-tooltip");_.length>0&&_.item(0).style.removeProperty("display")}}}),f===e.id&&e){if(typeof e.color=="object"){let m=e.color;c.style.setProperty("background-color",`rgba(${m.red}, ${m.green}, ${m.blue}, ${Ui})`,"important")}else if(r.isHexColor(e.color)){let m=r.hexToRgbChannels(e.color);c.style.setProperty("background-color",`rgba(${m.red}, ${m.green}, ${m.blue}, ${Ui})`,"important")}else c.classList.remove("hover");let y=n.getElementById("R2_ID_SEARCH_CONTAINER").querySelector(`#${e.id}`).getElementsByClassName(Sl);if(y.length>0){let m=y.item(0).getElementsByClassName("icon-tooltip");m.length>0&&m.item(0).style.removeProperty("display")}}}}isIOS(){return navigator.userAgent.match(/iPhone|iPad|iPod/i)!=null||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}isAndroid(){return navigator.userAgent.match(/Android/i)!=null}async processMouseEvent(e){var o,s,c,f,u,y,m,_,v,g,h,l,p;let t=(o=this.navigator.iframes[0].contentWindow)==null?void 0:o.document;if(!t||!(e.type==="mouseup"||e.type==="click"||e.type==="touchup")||!t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER")&&!t.getElementById("R2_ID_SEARCH_CONTAINER")&&!t.getElementById("R2_ID_PAGEBREAK_CONTAINER")&&!t.getElementById("R2_ID_READALOUD_CONTAINER")&&!t.getElementById("R2_ID_DEFINITIONS_CONTAINER"))return;let n=e.target,i=er.find(w=>{var A;return w.id===((A=e.target.parentElement)==null?void 0:A.id)});if(!i||!n){for(let w in ks){let A=t.getElementById(w);if(A){let C=A.querySelectorAll(`.${Cl}`);for(let E of C)this.resetHighlightBoundingStyle(E);let b=Array.from(A.querySelectorAll(`.${Ur}`));for(let E of b)this.resetHighlightAreaStyle(E,w)}}return}if(n.getAttribute("data-click")&&(e.type==="mouseup"||e.type==="click"||e.type==="touchup")&&((s=n.parentElement)==null?void 0:s.style.display)!=="none"){let w={highlight:i};Yr.default.log(JSON.stringify(w));let A=this,C;if(A.navigator.rights.enableAnnotations?C=await((c=this.navigator.annotationModule)==null?void 0:c.getAnnotation(w.highlight)):A.navigator.rights.enableBookmarks&&(C=await((f=this.navigator.bookmarkModule)==null?void 0:f.getAnnotation(w.highlight))),w.highlight.type===0&&((y=(u=this.navigator.annotationModule)==null?void 0:u.api)==null||y.selectedAnnotation(C).then(async()=>{})),C!=null&&C.id){Yr.default.log("selected highlight "+C.id),A.lastSelectedHighlight=C.id;let b=document.getElementById("highlight-toolbox");if(b)if(b.style.top=e.clientY+(((m=this.navigator.attributes)==null?void 0:m.navHeight)??0)+"px",b.style.left=e.clientX+"px",getComputedStyle(b).display==="none"){let P=function(){var q,G;(G=(q=A.navigator.annotationModule)==null?void 0:q.api)==null||G.addCommentToAnnotation(C).then(Y=>{var X;(X=A.navigator.annotationModule)==null||X.updateAnnotation(Y).then(async()=>{Yr.default.log("update highlight "+Y.id),b&&(b.style.display="none"),A.selectionMenuClosed()}),b&&(b.style.display="none"),A.selectionMenuClosed(),N==null||N.removeEventListener("click",P,!1)})},F=function(){var q,G;A.navigator.rights.enableAnnotations?(q=A.navigator.annotationModule)==null||q.deleteSelectedHighlight(C).then(async()=>{Yr.default.log("delete highlight "+C.id),b&&(b.style.display="none"),A.selectionMenuClosed()}):A.navigator.rights.enableBookmarks&&((G=A.navigator.bookmarkModule)==null||G.deleteSelectedHighlight(C).then(async()=>{Yr.default.log("delete highlight "+C.id),b&&(b.style.display="none"),A.selectionMenuClosed()}))};b.style.display="block",this.toolboxMode("edit");let E=document.getElementById("colorIcon"),k=document.getElementById("highlightIcon");E&&(E.style.display="none"),k&&(k.style.display="none");let N=document.getElementById("commentIcon"),D=document.getElementById("cloneCommentIcon");if(D){let q=D.parentElement;q&&q.removeChild(D)}if(N){N.style.display="none";let q=N.cloneNode(!0),G=N.parentElement;q.style.display="unset",q.id="cloneCommentIcon",q.addEventListener("click",P,!1),G&&G.append(q)}let B=document.getElementById("deleteIcon"),V=document.getElementById("cloneDeleteIcon");if(V){let q=V.parentElement;q&&q.removeChild(V)}if(B){B.style.display="none";let q=B.cloneNode(!0),G=B.parentElement;q.style.display="unset",q.id="cloneDeleteIcon",q.addEventListener("click",F,!1),G&&G.append(q)}}else b.style.display="none",this.selectionMenuClosed(),b.offsetWidth,b.style.display="block"}else{n.dataset.definition&&new Ia(this.navigator).showPopup(n.dataset.definition,e);let b=(g=(v=(_=this.navigator.definitionsModule)==null?void 0:_.properties)==null?void 0:v.definitions)==null?void 0:g.filter(E=>E.order===Number(n==null?void 0:n.dataset.order))[0];Yr.default.log(b),(l=(h=this.navigator.definitionsModule)==null?void 0:h.api)!=null&&l.click&&((p=this.navigator.definitionsModule.api)==null||p.click(t1.omit(b,"callbacks"),t1.omit(i,"definition")),this.navigator.emit("definition.click",b,i))}}}async prepareContainers(e){for(let t in ks)await this.ensureHighlightsContainer(e,t)}async ensureHighlightsContainer(e,t){var i,o;let n=e.document;if(!n.getElementById(t)){let s=n.createElement("div");s.setAttribute("id",t),t!=="R2_ID_GUTTER_RIGHT_CONTAINER"&&s.style.setProperty("pointer-events","none"),((i=this.navigator.view)==null?void 0:i.layout)==="fixed"&&(s.style.setProperty("position","absolute"),s.style.setProperty("top","0"),s.style.setProperty("left","0")),n.body&&n.body.append(s),((o=await this.layerSettings.getProperty(t))==null?void 0:o.value)===!1&&(s.style.display="none")}return n.getElementById(t)}hideAllhighlights(e){this.removeAllChildNodes(e.getElementById("R2_ID_HIGHLIGHTS_CONTAINER")),this.removeAllChildNodes(e.getElementById("R2_ID_SEARCH_CONTAINER")),this.removeAllChildNodes(e.getElementById("R2_ID_READALOUD_CONTAINER")),this.removeAllChildNodes(e.getElementById("R2_ID_PAGEBREAK_CONTAINER")),this.removeAllChildNodes(e.getElementById("R2_ID_DEFINITIONS_CONTAINER"))}destroyAllhighlights(e){this.hideAllhighlights(e),er.splice(0,er.length)}removeAllChildNodes(e){for(;e.firstChild;)e.removeChild(e.firstChild)}destroyHighlights(e){var n;let t=(n=this.navigator.iframes[0].contentWindow)==null?void 0:n.document;if(t){let i;switch(e){case 2:i=t.getElementById("R2_ID_READALOUD_CONTAINER"),i&&this.removeAllChildNodes(i);break;case 1:i=t.getElementById("R2_ID_SEARCH_CONTAINER"),i&&this.removeAllChildNodes(i);break;case 3:i=t.getElementById("R2_ID_PAGEBREAK_CONTAINER"),i&&this.removeAllChildNodes(i);break;case 4:i=t.getElementById("R2_ID_DEFINITIONS_CONTAINER"),i&&this.removeAllChildNodes(i);break;case 5:i=t.getElementById("R2_ID_LINEFOCUS_CONTAINER"),i&&this.removeAllChildNodes(i);break;case 6:i=t.getElementById("R2_ID_GUTTER_RIGHT_CONTAINER"),i&&this.removeAllChildNodes(i);break;default:i=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),i&&this.removeAllChildNodes(i),er.splice(0,er.length);break}}}destroyHighlight(e,t){if(!e)return;let n=-1;er.find((s,c)=>(n=c,s.id===t))&&n>=0&&n<er.length&&er.splice(n,1);let o=e.getElementById(t);o&&this.removeAllChildNodes(o)}createHighlight(e,t,n,i,o,s,c,f,u,y){try{let m=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,_=Fi.hash(m),v=(y||"R2_HIGHLIGHT_")+_;this.destroyHighlight(e.document,v);let g=`rgb(${Rs.red}, ${Rs.green}, ${Rs.blue})`,h={color:n||g,id:v,pointerInteraction:i,selectionInfo:t,marker:o,icon:s,popup:c,style:f,type:u||0};(u===0||u===4||u===void 0)&&er.push(h);let l=this.createHighlightDom(e,h);return h.position=parseInt((l!=null&&l.hasChildNodes()?l.childNodes[0]:l).style.top.replace("px","")),[h,l]}catch(m){throw"Can't create highlight: "+m}}createHighlightDom(e,t){var B,V,q,G,Y,X,Q,le,ve,ce,W,H,R,x,T,O,I,U,z,Z,re,ne,se,fe,he,Te,Ie,we,ye,oe,Ce,xe;let n=e.document,i=Lf(n,t.selectionInfo.rangeInfo);if(!i)return;for(let K in ks)this.ensureHighlightsContainer(e,K);let o=n.createElement("div");o.setAttribute("id",t.id),o.setAttribute("class",Tw),o.style.setProperty("pointer-events","none"),t.pointerInteraction&&(o.setAttribute("data-click","1"),o.addEventListener("mouseover",K=>{var ie;if(K.target.classList.contains("R2_CLASS_HIGHLIGHT_AREA")){let be=K.currentTarget,Ee=er.find(Re=>Re.id===K.currentTarget.id);if(K.type==="mouseover"&&((ie=be.parentElement)==null?void 0:ie.style.display)!=="none"&&Ee){let Re=Array.from(be.querySelectorAll(`.${Ur}`));this.setHighlightAreaStyle(n,Re,Ee)}}}),o.addEventListener("mouseleave",K=>{let ie=K.currentTarget,be=Array.from(ie.querySelectorAll(`.${Ur}`));for(let Ke of be)this.resetHighlightAreaStyle(Ke,ie.id);let Ee=ie.querySelector(`.${Cl}`),Re=ie.querySelectorAll(`.${Cl}`);for(let Ke of Re)(!Ee||Ke!==Ee)&&this.resetHighlightBoundingStyle(Ke)}));let s=(B=this.navigator.view)==null?void 0:B.isPaginated();s?n.body.style.position="revert":n.body.style.position="relative";let c=n.body.getBoundingClientRect(),f=this.getScrollingElement(n),u=s?-f.scrollLeft:c.left,y=s?-f.scrollTop:c.top,m=1,_=!1,v=!1,h=_||v||!1;Yr.default.debug(h),h=!0;let l=Rf(i,h),p=3,w=2,A=3,C=0,b=24,E,k;for(let K of l){let ie=n.createElement("div");ie.setAttribute("class",Ur),ie.dataset.marker=""+t.marker;let be="";if(_&&t.marker!==3&&t.marker!==2&&t.marker!==4){let Be=t.color;r.isHexColor(Be)&&(Be=r.hexToRgbChannels(Be)),be+=`border-bottom: ${w*m}px solid rgba(${Be.red}, ${Be.green}, ${Be.blue}, ${Ui}) !important`}if(t.marker===3||t.marker===2)if((V=t.style)!=null&&V.default){for(let Be=0;Be<((G=(q=t.style)==null?void 0:q.default)==null?void 0:G.length);Be++){let ut=(Y=t.style)==null?void 0:Y.default[Be];be+=`${ut.property}: ${ut.value} !${ut.priority};`}ie.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${p}px !important; ${be}`)}else(X=t.style)!=null&&X.defaultClass&&(ie.classList.add((Q=t.style)==null?void 0:Q.defaultClass),ie.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${p}px !important; ${be}`));else if(t.marker===1||t.marker===4)if(typeof t.color=="object"){let Be=t.color;ie.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${p}px !important; background-color: rgba(${Be.red}, ${Be.green}, ${Be.blue}, 0) !important; ${be}`),ie.style.setProperty("border-bottom",`2px solid rgba(${Be.red}, ${Be.green}, ${Be.blue}, 1)`,"important")}else if(r.isHexColor(t.color)){let Be=r.hexToRgbChannels(t.color);ie.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${p}px !important; background-color: rgba(${Be.red}, ${Be.green}, ${Be.blue}, 0) !important; ${be}`),ie.style.setProperty("border-bottom",`2px solid rgba(${Be.red}, ${Be.green}, ${Be.blue}, 1)`,"important")}else ie.setAttribute("style",`border-radius: ${p}px !important; ${be}`);else if(typeof t.color=="object"){let Be=t.color;ie.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${p}px !important; background-color: rgba(${Be.red}, ${Be.green}, ${Be.blue}, ${Ui}) !important; ${be}`)}else if(r.isHexColor(t.color)){let Be=r.hexToRgbChannels(t.color);ie.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${p}px !important; background-color: rgba(${Be.red}, ${Be.green}, ${Be.blue}, ${Ui}) !important; ${be}`)}else ie.setAttribute("style",`border-radius: ${p}px !important; ${be}`);t.type===1||t.type===2||t.type===5||t.type===3?ie.style.setProperty("pointer-events","none"):(ie.style.setProperty("pointer-events","all"),ie.style.setProperty("cursor","hand")),ie.style.position="absolute",ie.scale=m,ie.rect={height:K.height,left:K.left-u,top:K.top-y,width:K.width},t.pointerInteraction&&(ie.setAttribute("data-click","1"),ie.tabIndex=0),ie.style.width=`${ie.rect.width*m}px`,ie.style.height=`${ie.rect.height*m}px`,ie.style.left=`${ie.rect.left*m}px`,ie.style.top=`${ie.rect.top*m}px`,o.append(ie);let Ee=parseInt(ie.style.top.replace("px",""));if((Ee<C||C===0)&&(C=Ee),b=parseInt(ie.style.height.replace("px","")),v){let Be=n.createElement("div");Be.setAttribute("class",Ur);let ut=t.color;r.isHexColor(ut)&&(ut=r.hexToRgbChannels(ut)),Be.setAttribute("style",`background-color: rgba(${ut.red}, ${ut.green}, ${ut.blue}, ${Ui}) !important;`),t.type===1||t.type===2||t.type===5||t.type===3?Be.style.setProperty("pointer-events","none"):(Be.style.setProperty("pointer-events","all"),Be.style.setProperty("cursor","hand")),Be.style.position="absolute",Be.scale=m,Be.rect={height:K.height,left:K.left-u,top:K.top-y,width:K.width},Be.style.width=`${Be.rect.width*m}px`,Be.style.height=`${A*m}px`,Be.style.left=`${Be.rect.left*m}px`,Be.style.top=`${(Be.rect.top+Be.rect.height/2-A/2)*m}px`,o.append(Be)}let Re=(le=this.navigator.iframes[0].contentWindow)==null?void 0:le.innerWidth,Ke=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-count")),ze=parseInt(getComputedStyle(n.documentElement).getPropertyValue("column-width")),Ve=parseInt(getComputedStyle(n.body).getPropertyValue("padding-left")),qe=Re/(Ke||1);qe<ze&&(qe=Re),s||(qe=parseInt(getComputedStyle(n.body).width.replace("px","")));let pe=this.navigator.settings.fontSize/100,ee=20*pe;pe<=1&&(ee=-60);let de=0*pe;pe<=1&&(de=-60),E=Math.floor(K.left/qe)*qe+qe-(b<40?40:b)+de,k=Math.floor(K.left/qe)*qe+(b<40?40:b)-ee;let je=parseInt(this.navigator.iframes[0].contentDocument.documentElement.style.getPropertyValue("--USER__pageMargins"));je>=2&&(k=k+Ve/Ke,E=E-Ve/Ke),s||(E=parseInt(getComputedStyle((ve=this.navigator.iframes[0].contentDocument)==null?void 0:ve.body).width.replace("px","")),k=parseInt(getComputedStyle((ce=this.navigator.iframes[0].contentDocument)==null?void 0:ce.body).width.replace("px",""))-qe,je>=2&&(k=k+Ve/2,E=E-Ve/2))}let P=i.getBoundingClientRect(),N=n.createElement("div");N.setAttribute("class",Cl),N.style.setProperty("pointer-events","none"),N.style.position="absolute",N.scale=m,N.rect={height:P.height,left:P.left-u,top:P.top-y,width:P.width},N.style.width=`${N.rect.width*m}px`,N.style.height=`${N.rect.height*m}px`,N.style.left=`${N.rect.left*m}px`,N.style.top=`${N.rect.top*m}px`,o.append(N);let D=n.createElement("div");if(D.setAttribute("class",Sl),((W=t.icon)==null?void 0:W.position)==="left")D.setAttribute("style",`position: absolute;top:${C}px;left:${k+((R=(H=this.navigator.iframes[0].contentDocument)==null?void 0:H.scrollingElement)==null?void 0:R.scrollLeft)}px;height:${b}px; width:${b}px;`);else if(((x=t.icon)==null?void 0:x.position)==="inline")D.setAttribute("style",`position: absolute;top:${C-b/2}px;left:${parseInt(N.style.left.replace("px",""))+parseInt(N.style.width.replace("px",""))-b/2}px;height:${b}px; width:${b}px;`);else if(((T=t.icon)==null?void 0:T.position)==="center"){let ie=b/3*2;D.setAttribute("style",`position: absolute;top:${C}px;left:${parseInt(N.style.left.replace("px",""))+parseInt(N.style.width.replace("px",""))-ie}px;height:${b}px; width:${b}px;`)}else t.note&&t.marker!==3&&t.marker!==2&&t.marker!==4&&t.marker!==0&&t.marker!==1?D.setAttribute("style",`position: absolute;top:${C-b/2}px;left:${parseInt(N.style.left.replace("px",""))+parseInt(N.style.width.replace("px",""))-b/2}px;height:${b}px; width:${b}px;`):t.note&&t.marker===4||t.marker===0||t.marker===1?D.setAttribute("style",`position: absolute;top:${C}px;left:${E+((I=(O=this.navigator.iframes[0].contentDocument)==null?void 0:O.scrollingElement)==null?void 0:I.scrollLeft)}px;height:${b}px; width:${b}px;`):D.setAttribute("style",`position: absolute;top:${C}px;left:${E+((z=(U=this.navigator.iframes[0].contentDocument)==null?void 0:U.scrollingElement)==null?void 0:z.scrollLeft)}px;height:${b}px; width:${b}px;`);if(t.marker===3||t.marker===2)(Z=t.icon)!=null&&Z.class?(D.classList.add((re=t.icon)==null?void 0:re.class),D.id=(ne=t.icon)==null?void 0:ne.id):(se=t.icon)!=null&&se.svgPath?D.innerHTML=Na(`${(fe=t.icon)==null?void 0:fe.id}`,`${(he=t.icon)==null?void 0:he.title}`,`${(Te=t.icon)==null?void 0:Te.svgPath}`,"icon open",b,`${(Ie=t.icon)==null?void 0:Ie.color} !important`):(we=t.icon)!=null&&we.title&&(D.innerHTML=(ye=t.icon)==null?void 0:ye.title);else if(t.note){let K=t.color;r.isHexColor(K)&&(K=r.hexToRgbChannels(K)),t.marker===4||t.marker===0||t.marker===1?D.innerHTML=Na("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="14"/>',"icon open",b/2,`rgba(${K.red}, ${K.green}, ${K.blue}, 1) !important`):D.innerHTML=Na("note-icon","Note",'<rect fill="none" height="24" width="24"/><path d="M19,5v9l-5,0l0,5H5V5H19 M19,3H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h10l6-6V5C21,3.9,20.1,3,19,3z M12,14H7v-2h5V14z M17,10H7V8h10V10z"/>',"icon open",b,`rgba(${K.red}, ${K.green}, ${K.blue}, 1) !important`)}t.type===1||t.type===2||t.type===5||t.type===3?D.style.setProperty("pointer-events","none"):(D.style.setProperty("pointer-events","all"),D.style.setProperty("cursor","hand"));let F=this;if(t.type!==3&&t.type!==4&&D.addEventListener("click",async function(K){var Re,Ke,ze,Ve,qe;let ie;F.navigator.rights.enableAnnotations?(ie=await((Re=F.navigator.annotationModule)==null?void 0:Re.getAnnotationByID(t.id)),(ze=(Ke=F.navigator.annotationModule)==null?void 0:Ke.api)==null||ze.selectedAnnotation(ie).then(async()=>{})):F.navigator.rights.enableBookmarks&&(ie=await((Ve=F.navigator.bookmarkModule)==null?void 0:Ve.getAnnotationByID(t.id))),Yr.default.log("selected highlight "+ie.id),F.lastSelectedHighlight=ie.id;let be=document.getElementById("highlight-toolbox");if(be)if(be.style.top=K.clientY+(((qe=F.navigator.attributes)==null?void 0:qe.navHeight)??0)+"px",be.style.left=K.clientX+"px",getComputedStyle(be).display==="none"){let Be=function(){var Ht,Br;F.navigator.rights.enableAnnotations?(Ht=F.navigator.annotationModule)==null||Ht.deleteSelectedHighlight(ie).then(async()=>{Yr.default.log("delete highlight "+ie.id),be.style.display="none",F.selectionMenuClosed()}):F.navigator.rights.enableBookmarks&&((Br=F.navigator.bookmarkModule)==null||Br.deleteSelectedHighlight(ie).then(async()=>{Yr.default.log("delete highlight "+ie.id),be.style.display="none",F.selectionMenuClosed()}))};be.style.display="block",F.toolboxMode("edit");let pe=document.getElementById("colorIcon"),ee=document.getElementById("highlightIcon");pe&&(pe.style.display="none"),ee&&(ee.style.display="none");let de=document.getElementById("commentIcon"),je=document.getElementById("cloneCommentIcon");if(je){let Ht=je.parentElement;Ht&&Ht.removeChild(je)}de&&(de.style.display="none");let ut=document.getElementById("deleteIcon"),Ct=document.getElementById("cloneDeleteIcon");if(Ct){let Ht=Ct.parentElement;Ht&&Ht.removeChild(Ct)}if(ut){ut.style.display="none";let Ht=ut.cloneNode(!0),Br=ut.parentElement;Ht.style.display="unset",Ht.id="cloneDeleteIcon",Ht.addEventListener("click",Be,!1),Br&&Br.append(Ht)}}else be.style.display="none",F.selectionMenuClosed(),be.offsetWidth,be.style.display="block";let Ee=Array.from(o.querySelectorAll(`.${Ur}`));F.setHighlightAreaStyle(n,Ee,t)}),t.note){let K=document.createElement("span");K.innerHTML=t.note,K.className="icon-tooltip",t.marker===3||t.marker===2?((oe=t.popup)!=null&&oe.background&&K.style.setProperty("background",t.popup.background),(Ce=t.popup)!=null&&Ce.textColor&&K.style.setProperty("color",t.popup.textColor),(xe=t.popup)!=null&&xe.class&&K.classList.add(t.popup.class)):(K.style.setProperty("background","lightyellow"),K.style.setProperty("color","black"))}switch((t.note||t.marker===3||t.marker===2)&&o.append(D),t.type){case 1:n.getElementById("R2_ID_SEARCH_CONTAINER").append(o);break;case 2:n.getElementById("R2_ID_READALOUD_CONTAINER").append(o);break;case 3:n.getElementById("R2_ID_PAGEBREAK_CONTAINER").append(o);break;case 4:n.getElementById("R2_ID_DEFINITIONS_CONTAINER").append(o);break;default:n.getElementById("R2_ID_HIGHLIGHTS_CONTAINER").append(o);break}return o}addSelectionMenuItem(e){var t,n;(((t=this.properties)==null?void 0:t.selectionMenuItems)??[])&&(((n=this.properties)==null?void 0:n.selectionMenuItems)??[]).push(e)}};var Uw=rt(d1());L();var dD=rt($t());var Jo={className:r=>!0,idName:r=>!0,tagName:r=>!0};var jw=rt(Nf()),ei=rt($t());L();var Fw=rt($t());var Ha=class{constructor(e,t,n){this.currSeconds=0;this.publication=e,this.properties=t,this.api=n}static async create(e){let t=new this(e.publication,e,e.api);return await t.start(),t}async start(){this.startResearchSession()}async stop(){Fw.default.log("Consumption module stop"),this.endResearchSession()}initialize(){let e=this.navigator.iframes[0].contentWindow;if(e){let t=this;e.onload=function(){t.resetTimer()},e.onmousemove=function(){t.resetTimer()},e.onmousedown=function(){t.resetTimer()},e.ontouchstart=function(){t.resetTimer()},e.onclick=function(){t.resetTimer()},e.onkeypress=function(){t.resetTimer()}}}trackAction(e,t){var n;(n=this.api)==null||n.actionTracked(e,t)}startReadingSession(e){if(this.firstReadingLocator&&this.lastReadingLocator){let t=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,n=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:n,progress:Math.round(t*100)})}this.firstReadingLocator=e,this.startReadingTimer=new Date}continueReadingSession(e){this.properties.enableTrackingSession&&(this.startResearchTimer===void 0&&this.startResearchSession(),(this.lastReadingLocator===void 0||this.lastReadingLocator.locations.totalProgression<e.locations.totalProgression)&&(this.lastReadingLocator=e),this.firstReadingLocator===void 0&&(this.firstReadingLocator=e),this.startReadingTimer===void 0&&(this.startReadingTimer=new Date))}startResearchSession(){var e;if(this.properties.enableTrackingSession){this.startResearchTimer=new Date,this.readingSessions=[],clearInterval(this.readingSessionsInterval);let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;this.researchSessionId=(e=this.api)==null?void 0:e.startResearchSession(this.readingSessions,Math.round(t));let n=this;this.readingSessionsInterval=setInterval(function(){n.updateResearchSession()},this.properties.updateSessionInterval*1e3)}}updateResearchSession(){var e;if(this.properties.enableTrackingSession){let t=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;(e=this.api)==null||e.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(t))}}endResearchSession(){var e,t;if(this.properties.enableTrackingSession){if(this.firstReadingLocator&&this.lastReadingLocator){let i=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,o=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:o,progress:Math.round(i*100)})}let n=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;(e=this.api)==null||e.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(n)),(t=this.api)==null||t.endResearchSession(this.researchSessionId,this.readingSessions,Math.round(n)),this.researchSessionId=void 0,this.readingSessions=[],this.startResearchTimer=void 0,clearInterval(this.readingSessionsInterval),clearInterval(this.timer)}}startIdleTimer(){var e;this.currSeconds++,this.currSeconds===this.properties.idleTimeout&&((e=this.api)==null||e.idleSince(this.currSeconds),this.startResearchTimer!==void 0?this.updateResearchSession():this.startResearchSession()),this.currSeconds===this.properties.idleTimeout+this.properties.responseTimeout&&this.endResearchSession()}resetTimer(){clearInterval(this.timer),this.currSeconds=0;let e=this;this.timer=setInterval(function(){e.startIdleTimer()},1e3)}};var Ua=class r{constructor(e,t,n,i,o,s,c,f){this.hide=Ne(document,"#menu-button-hide");this.show=Ne(document,"#menu-button-show");this.annotator=e,this.rights=t,this.publication=n,this.headerMenu=f,this.initialAnnotations=i,this.highlighter=s,this.properties=o,this.api=c}static async create(e){let t=new this(e.annotator,e.rights||{enableAnnotations:!1,enableTTS:!1},e.publication,e.initialAnnotations||null,e,e.highlighter,e.api,e.headerMenu);return await t.start(),t}async stop(){ei.default.log("Annotation module stop")}async start(){var t;if(this.headerMenu&&(this.highlightsView=Ne(this.headerMenu,"#container-view-highlights")),this.initialAnnotations){var e=this.initialAnnotations.highlights||null;e&&((t=this.annotator)==null||t.initAnnotations(e))}setTimeout(()=>{var n;(n=this.properties)!=null&&n.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)}hideAnnotationLayer(){let e=this.navigator.iframes[0].contentDocument;if(e){let t=Ne(e,"#R2_ID_HIGHLIGHTS_CONTAINER");t&&(t.style.display="none")}this.show&&this.hide&&(this.show.style.display="block",this.hide.style.display="none")}showAnnotationLayer(){let e=this.navigator.iframes[0].contentDocument;if(e){let t=Ne(e,"#R2_ID_HIGHLIGHTS_CONTAINER");t&&(t.style.display="block")}this.show&&this.hide&&(this.show.style.display="none",this.hide.style.display="block")}async handleResize(){setTimeout(async()=>{await this.drawHighlights(),await this.showHighlights()},200)}initialize(){return new Promise(async e=>{await document.fonts.ready,this.rights.enableAnnotations&&setTimeout(()=>{var t;this.drawHighlights(),this.showHighlights(),_e((t=this.navigator.iframes[0].contentDocument)==null?void 0:t.body,"click",this.click.bind(this))},300),e(null)})}click(e){var t,n,i,o,s,c,f;if(this.activeAnnotationMarkerId){let u=(i=(n=(t=this.highlighter)==null?void 0:t.properties)==null?void 0:n.selectionMenuItems)==null?void 0:i.filter(y=>y.id===this.activeAnnotationMarkerId);if(u&&(u==null?void 0:u.length)>0){let y=jw.cloneDeep(u[0]);y.marker=3,this.activeAnnotationMarkerPosition&&(y.icon.position=this.activeAnnotationMarkerPosition),y.highlight.style.default=null,y.highlight.style.hover=null;let m=this.navigator.iframes[0].contentDocument;if(m){let l=function(w){try{let A=h.navigator.iframes[0].contentDocument;return A?Ar(w,A,Jo):""}catch(A){return ei.default.log("uniqueCssSelector:"),ei.default.error(A),""}},_=(o=this.highlighter)==null?void 0:o.dom(m.body).getSelection(),v=_.getRangeAt(0),g=_.anchorNode;v.setStart(g,v.startOffset),v.setEnd(g,v.endOffset+1),_.removeAllRanges(),_.addRange(v);let h=this,p=go(v,l);if(_.removeAllRanges(),p){let w={rangeInfo:p},A=(c=this.navigator.highlighter)==null?void 0:c.createHighlight((s=this.navigator.highlighter)==null?void 0:s.dom(m.body).getWindow(),w,y.highlight.color,!0,2,y.icon,y.popup,y.highlight.style);A&&this.saveAnnotation(A[0]).then(C=>{ei.default.log("saved bookmark "+C.id)})}(f=m.getSelection())==null||f.removeAllRanges()}}}}async scrollToHighlight(e){var n;ei.default.log("still need to scroll to "+e);var t=await((n=this.annotator)==null?void 0:n.getAnnotationElement(e,this.navigator.iframes[0].contentWindow));t.scrollIntoView({block:"center",behavior:"smooth"})}async updateLocalHighlight(e){if(this.annotator){let t=await this.annotator.deleteAnnotation(e.id),n=await this.addAnnotation(e);return ei.default.log("Highlight deleted "+JSON.stringify(t)),ei.default.log("Highlight added "+JSON.stringify(n)),await this.showHighlights(),await this.drawHighlights(),n}else return new Promise(t=>t(null))}async deleteLocalHighlight(e){if(this.annotator){var t=await this.annotator.deleteAnnotation(e);return ei.default.log("Highlight deleted "+JSON.stringify(t)),await this.showHighlights(),await this.drawHighlights(),t}else return new Promise(n=>n(null))}async deleteAnnotation(e){await this.deleteLocalHighlight(e.id)}async addAnnotation(e){var t;await((t=this.annotator)==null?void 0:t.saveAnnotation(e)),await this.showHighlights(),await this.drawHighlights()}async deleteHighlight(e){var t,n;(t=this.api)!=null&&t.deleteAnnotation?(n=this.api)==null||n.deleteAnnotation(e).then(async()=>{this.deleteLocalHighlight(e.id)}):this.deleteLocalHighlight(e.id)}async deleteSelectedHighlight(e){var t;(t=this.api)!=null&&t.deleteAnnotation?this.api.deleteAnnotation(e).then(async()=>{this.deleteLocalHighlight(e.id)}):this.deleteLocalHighlight(e.id)}async updateAnnotation(e){var t;(t=this.api)!=null&&t.updateAnnotation?this.api.updateAnnotation(e).then(async()=>{this.updateLocalHighlight(e)}):this.updateLocalHighlight(e)}async saveAnnotation(e){var n,i,o;if(this.annotator){var t=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let s=(n=this.navigator.view)==null?void 0:n.getCurrentPosition(),c=this.navigator.iframes[0].contentDocument;if(c){let f=lo(c,"body"),u=e.position?e.position/f.scrollHeight:s,y=(0,Uw.v4)(),m;if(t){let _=t.Href;if(_.indexOf("#")>0&&(_=_.slice(0,_.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let v=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),g=Math.ceil((u??0)*(v.length-1));m={...v[g],id:y,href:_,created:new Date,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}else m={id:y,href:_,locations:{progression:u},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}if(m)if((i=this.navigator.consumptionModule)==null||i.trackAction(m,"HighlightCreated"),(o=this.api)!=null&&o.addAnnotation)try{let _=await this.api.addAnnotation(m),v=await this.annotator.saveAnnotation(_);return await this.showHighlights(),await this.drawHighlights(),new Promise(g=>g(v))}catch{await this.showHighlights(),await this.drawHighlights()}else{let _=await this.annotator.saveAnnotation(m);return await this.showHighlights(),await this.drawHighlights(),new Promise(v=>v(_))}}}return new Promise(s=>s(null))}getAnnotations(){let e=[];return this.annotator&&(e=this.annotator.getAnnotations()),e}showHighlights(){let e=[];this.annotator&&(e=this.annotator.getAnnotations(),e&&(e=e.filter(t=>t.highlight.marker!==2),e.forEach(t=>{er.push(t.highlight)}))),this.highlightsView&&this.createTree(1,e,this.highlightsView)}async drawHighlights(){var t,n,i,o;if(this.rights.enableAnnotations&&this.highlighter){if(this.api){let s=[];if(this.annotator&&(s=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&s&&((t=this.navigator.iframes[0].contentDocument)==null?void 0:t.readyState)==="complete"){await this.highlighter.destroyHighlights(0);for(let c of s){er.push(c.highlight);let f=c,u=this.navigator.currentChapterLink.href;var e=this.publication.getTOCItem(u);if(this.navigator.currentTocUrl!==void 0&&(e=this.publication.getTOCItem(this.navigator.currentTocUrl)),e===null&&(e=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),e){let y=e.Href;y.indexOf("#")>0&&(y=y.slice(0,y.indexOf("#"))),f.href===y&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,c.highlight),setTimeout(async()=>{var m,_;if(((m=f.highlight)==null?void 0:m.marker)===1){let g='<div class="comment" style="top: '+await((_=this.annotator)==null?void 0:_.getAnnotationPosition(c.id,this.navigator.iframes[0].contentWindow))+'px;width:20px"></div>',h=document.createElement("div");h.innerHTML=g;let l=h.childNodes[0],p=document.createElement("i");p.innerHTML="sticky_note_2",p.className="material-icons",p.style.color=f.highlight.color,l.appendChild(p),_e(h,"click",w=>{w.preventDefault(),w.stopPropagation(),this.scrollToHighlight(f.id)})}},100))}}}}else{let s=[];if(this.annotator&&(s=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href)),this.highlighter&&s&&((n=this.navigator.iframes[0].contentDocument)==null?void 0:n.readyState)==="complete"){await this.highlighter.destroyHighlights(0);for(let c of s){er.push(c.highlight);let f=c,u=this.navigator.currentChapterLink.href,y=this.publication.getTOCItem(u);if(this.navigator.currentTocUrl&&(y=this.publication.getTOCItem(this.navigator.currentTocUrl)),y===null&&(y=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),y){let m=y.Href;m.indexOf("#")>0&&(m=m.slice(0,m.indexOf("#"))),f.href===m&&(await this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,c.highlight),setTimeout(async()=>{var _,v,g;if(((_=f.highlight)==null?void 0:_.marker)===1){let l='<div class="comment" style="top: '+await((v=this.annotator)==null?void 0:v.getAnnotationPosition(c.id,this.navigator.iframes[0].contentWindow))+"px;background: "+((g=f.highlight)==null?void 0:g.color)+';width:20px"></div>',p=document.createElement("div");p.innerHTML=l,p.childNodes[0].innerHTML=pi.note,_e(p,"click",w=>{w.preventDefault(),w.stopPropagation(),this.scrollToHighlight(f.id)})}},100))}}}}(i=this.properties)!=null&&i.initialAnnotationColor&&this.highlighter.setColor((o=this.properties)==null?void 0:o.initialAnnotationColor),this.repositionGutters()}}repositionGutters(){var t,n,i,o,s,c;let e=this.navigator.iframes[0].contentDocument;if(e&&(this.commentGutter=e.getElementById("R2_ID_GUTTER_RIGHT_CONTAINER"),(t=this.navigator.view)!=null&&t.isScrollMode()&&((n=this.properties)!=null&&n.enableComments)?(i=this.commentGutter)==null||i.style.removeProperty("display"):(o=this.commentGutter)==null||o.style.setProperty("display","none"),this.commentGutter&&((s=this.navigator.view)!=null&&s.isScrollMode())&&((c=this.properties)!=null&&c.enableComments))){this.commentGutter.innerHTML="";let f=[];this.annotator&&(f=this.annotator.getAnnotationsByChapter(this.navigator.currentLocator().href),f&&(f=f.filter(u=>{var y,m;return((m=(y=u.highlight)==null?void 0:y.note)==null?void 0:m.length)>0}),f=this.syncPosition(f),f=this.reposition(f),f.forEach(u=>{var b,E;let y=document.createElement("i");y.innerHTML="sticky_note_2",y.className="material-icons",y.style.color=u.highlight.color;let m=e.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),_,v;m&&(_=m.querySelector(`#${u.highlight.id}`)),v=_.getElementsByClassName(Ur)[0];let h=parseInt(v.style.height.replace("px","")),l=u.highlight.position,p=e.createElement("div");p.setAttribute("style",`position: absolute;top:${l}px;display: flex;max-width: 250px !important;height:${h}px;width: 200px;align-items: center;`);let w=e.createElement("div");p.appendChild(w);let A=u.highlight.color;Jt.isHexColor(A)&&(A=Jt.hexToRgbChannels(A)),p.innerHTML=Na("","",'<path d="M24 24H0V0h24v24z" fill="none"/><circle cx="12" cy="12" r="8"/>',"icon open",10,`rgba(${A.red}, ${A.green}, ${A.blue}, 1) !important`);let C=e.createElement("div");C.innerHTML=(b=u.highlight)==null?void 0:b.note,C.setAttribute("style",`height:${h}px;overflow: hidden;padding-left: 5px;`),p.appendChild(C),_e(p,"click",k=>{k.preventDefault(),k.stopPropagation(),this.scrollToHighlight(u.highlight.id)}),(E=this.commentGutter)==null||E.appendChild(p)})))}}createTree(e,t,n){if(t){let i=this,o=this.publication.readingOrder;if(o.length){let s=(c,f)=>{let u=document.createElement("ul");u.className="sidenav-annotations";for(let y of f){let m=document.createElement("li"),_=document.createElement("a"),v=document.createElement("span");if(_.tabIndex=-1,_.className="chapter-link",y.Href){let h=this.publication.getAbsoluteHref(y.Href),l=this.publication.getTOCItemAbsolute(h);_.href=h,_.innerHTML=(l==null?void 0:l.Title)||"",m.appendChild(_)}else v.innerHTML=y.Title||"",v.className="chapter-title",m.appendChild(v);_e(_,"click",h=>{h.preventDefault(),h.stopPropagation();let l={href:_.href,locations:{progression:0},type:y.TypeLink,title:_.title};this.navigator.stopReadAloud(),this.navigator.navigate(l)});let g=document.createElement("ol");t.forEach(function(h){var p,w,A,C,b,E,k;let l=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&h.href.endsWith(l)){let P=document.createElement("li");P.className="annotation-item";let N=document.createElement("a");if(N.setAttribute("href",h.href),e===1){N.className="highlight-link";let F=document.createElement("span"),B=document.createElement("span");if(F.className="title",B.innerHTML=h.highlight.selectionInfo.cleanText,((p=h.highlight)==null?void 0:p.marker)===1)if(typeof((w=h.highlight)==null?void 0:w.color)=="object"){let G=(A=h.highlight)==null?void 0:A.color;G&&B.style.setProperty("border-bottom",`2px solid ${Jt.hexToRgbA(G)}`,"important")}else B.style.setProperty("border-bottom",`2px solid ${(C=h.highlight)==null?void 0:C.color}`,"important");else if(typeof((b=h.highlight)==null?void 0:b.color)=="object"){let G=(E=h.highlight)==null?void 0:E.color;G&&(B.style.backgroundColor=Jt.hexToRgbA(G))}else{let G=(k=h.highlight)==null?void 0:k.color;G&&(B.style.backgroundColor=G)}F.appendChild(B),N.appendChild(F);let V=document.createElement("span"),q=Math.round((h.locations.progression??0)*100)+"% through resource";V.className="subtitle",V.innerHTML=q,N.appendChild(V)}let D=document.createElement("span");if(D.className="timestamp",D.innerHTML=r.readableTimestamp(h.created),N.appendChild(D),_e(N,"click",F=>{F.preventDefault(),F.stopPropagation(),i.handleAnnotationLinkClick(F,h)}),P.appendChild(N),i.navigator.sideNavExpanded){let F=document.createElement("button");F.className="delete",F.innerHTML=pi.delete,_e(F,"click",B=>{B.preventDefault(),B.stopPropagation(),i.handleAnnotationLinkDeleteClick(e,B,h)}),P.appendChild(F)}g.appendChild(P)}}),g.children.length>0&&(u.appendChild(m),u.appendChild(g)),u.children.length>0&&c.appendChild(u),y.Children&&y.Children.length>0&&s(c,y.Children)}};n.innerHTML="",s(n,o)}}}handleAnnotationLinkClick(e,t){t?(t.href=this.publication.getAbsoluteHref(t.href),this.navigator.stopReadAloud(),this.navigator.navigate(t)):ei.default.log("annotation data missing: ",e)}handleAnnotationLinkDeleteClick(e,t,n){ei.default.log("annotation data locator: ",n),n?e===1&&this.deleteHighlight(n):ei.default.log("annotation data missing: ",t)}static readableTimestamp(e){let t=new Date(e);return t.toDateString()+" "+t.toLocaleTimeString()}async getAnnotation(e){var t;return(t=this.annotator)==null?void 0:t.getAnnotation(e)}async getAnnotationByID(e){var t;return(t=this.annotator)==null?void 0:t.getAnnotationByID(e)}syncPosition(e){let t=this.navigator.iframes[0].contentDocument,n=(i,o)=>{let s=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),c,f;s&&(c=s.querySelector(`#${o.highlight.id}`)),f=c.getElementsByClassName(Ur)[0];let y=parseInt(f.style.top.replace("px","")),m={...o,highlight:{...o.highlight,position:y}};return[...i,m]};return e.reduce(n,[])}reposition(e){let t=this.navigator.iframes[0].contentDocument,n=(i,o,s)=>{let c=e[0],f=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),u,y;f&&(u=f.querySelector(`#${c.highlight.id}`)),y=u.getElementsByClassName(Ur)[0];let _=parseInt(y.style.height.replace("px","")),v=o.highlight.position,g=i[s-1]&&i[s-1].highlight.position,l=s===0?0:g+_+0,p=l>v?l:v,w={...o,highlight:{...o.highlight,position:p}};return[...i,w]};return e.sort(function(i,o){return i.highlight.position-o.highlight.position}).reduce(n,[])}};L();var f1=rt(d1());var ti=rt($t());var ja=class r{static async create(e){let t=new this(e.annotator,e.rights||{enableBookmarks:!1},e.publication,e,e.initialAnnotations,e.api,e.headerMenu);return await t.start(),new Promise(n=>n(t))}constructor(e,t,n,i,o,s,c){this.annotator=e,this.rights=t,this.publication=n,this.headerMenu=c,this.initialAnnotations=o,this.properties=i,this.api=s}stop(){ti.default.log("Bookmark module stop")}async start(){var e,t;if(this.headerMenu&&(this.bookmarksView=Ne(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=Ne(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){let n=Ne(this.headerMenu,"#menu-button-bookmark");n&&((e=n.parentElement)==null||e.style.removeProperty("display")),n&&_e(n,"click",this.saveBookmark.bind(this))}if(this.initialAnnotations){let n=this.initialAnnotations.bookmarks||null;n&&((t=this.annotator)==null||t.initBookmarks(n))}}async handleResize(){setTimeout(async()=>{await this.drawBookmarks(),await this.showBookmarks(),setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)},100)}initialize(){return new Promise(async e=>{await document.fonts.ready,this.rights.enableBookmarks&&setTimeout(()=>{this.drawBookmarks(),this.showBookmarks()},300),e(null)})}async deleteBookmark(e){var t,n;if(this.annotator)if((t=this.api)!=null&&t.deleteBookmark){await((n=this.api)==null?void 0:n.deleteBookmark(e));let i=await this.annotator.deleteBookmark(e);return ti.default.log("Bookmark deleted "+JSON.stringify(i)),await this.showBookmarks(),await this.drawBookmarks(),i}else{let i=await this.annotator.deleteBookmark(e);return ti.default.log("Bookmark deleted "+JSON.stringify(i)),await this.showBookmarks(),await this.drawBookmarks(),i}else return new Promise(i=>i(null))}async saveBookmarkPlus(){await this.addBookmarkPlus()}async saveBookmark(){var t,n,i;if(this.annotator){var e=this.publication.getTOCItem(this.navigator.currentChapterLink.href);if(this.navigator.currentTocUrl&&(e=this.publication.getTOCItem(this.navigator.currentTocUrl)),e===void 0&&(e=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),e){let o=e.Href;o.indexOf("#")>0&&(o=o.slice(0,o.indexOf("#")));let s=(t=this.navigator.view)==null?void 0:t.getCurrentPosition(),c=(0,f1.v4)(),f;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let u=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),y=Math.ceil((s??0)*(u.length-1));f={...u[y],id:c,href:o,created:new Date,title:this.navigator.currentChapterLink.title}}else f={id:c,href:o,locations:{progression:s},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title};if(!this.annotator.locatorExists(f,0))if((n=this.navigator.consumptionModule)==null||n.trackAction(f,"BookmarkCreated"),(i=this.api)!=null&&i.addBookmark){let u=await this.api.addBookmark(f);u&&(f=u),ti.default.log(f);let y=this.annotator.saveBookmark(f);return ti.default.log("Bookmark added "+JSON.stringify(y)),this.showBookmarks(),await this.drawBookmarks(),y}else{let u=this.annotator.saveBookmark(f);return ti.default.log("Bookmark added "+JSON.stringify(u)),this.showBookmarks(),await this.drawBookmarks(),u}}}}async addBookmarkPlus(){var c,f,u,y,m,_,v,g,h,l,p,w,A;let e=this,t=(c=this.navigator.highlighter)==null?void 0:c.visibleTextRects[0],n=this.navigator.iframes[0].contentDocument;if(n){let C=(f=this.navigator.highlighter)==null?void 0:f.dom(n.body).getWindow().document.createRange(),b=(y=this.navigator.highlighter)==null?void 0:y.dom((u=this.navigator.iframes[0].contentDocument)==null?void 0:u.body).getSelection();b.removeAllRanges(),t&&C.selectNodeContents(t.node),b.addRange(C);let E=Rf(C,!1),k=0;for(let P of E){if(!((m=this.navigator.highlighter)!=null&&m.isOutsideViewport(P))){let N=b.focusNode,D=b.focusOffset;b.collapse(b.anchorNode,b.anchorOffset);for(let q=0;q<k;q++)b.modify("move","forward","line");b.extend(N,D);let F=b.focusNode,B=b.focusNode.length;b.collapse(b.anchorNode,b.anchorOffset);let V=B;b.anchorOffset>B?V=B:V=b.anchorOffset+1,b.modify("move","forward","character"),b.modify("move","backward","word"),b.extend(F,V),b.modify("extend","backward","character"),b.modify("extend","forward","word");break}k++}}function i(C){var k;let b={},E=e.navigator.iframes[0].contentDocument;if(E)return Ar(C,(k=e.navigator.highlighter)==null?void 0:k.dom(E.body).getDocument(),b)}let o=this.navigator.iframes[0].contentWindow,s={id:"bookmarkIcon",marker:2,icon:{id:"bookmarkIcon",title:"Bookmark",svgPath:'<path d="M0 0h24v24H0V0z" fill="none"/><path d="M17 3H7c-1.1 0-2 .9-2 2v16l7-3 7 3V5c0-1.1-.9-2-2-2z"/>',color:"#000000",position:"left"},popup:{background:"#000000",textColor:"#ffffff"},highlight:{color:"#000000",style:{default:[{property:"border-bottom",value:"0px dashed #000000",priority:"important"}]}}};if(o!==null){let C=Hi(o,i);if(C===void 0){let E=e.navigator.iframes[0].contentDocument;C=(v=(_=this.navigator.annotationModule)==null?void 0:_.annotator)==null?void 0:v.getTemporarySelectionInfo(E)}let b=e.navigator.iframes[0].contentDocument;if(C&&b){let E=(p=this.navigator.highlighter)==null?void 0:p.createHighlight((g=this.navigator.highlighter)==null?void 0:g.dom(b.body).getWindow(),C,(h=s.highlight)==null?void 0:h.color,!0,2,s.icon,s.popup,(l=s.highlight)==null?void 0:l.style);if((A=(w=this.navigator.iframes[0].contentDocument)==null?void 0:w.getSelection())==null||A.removeAllRanges(),E)return this.saveAnnotation(E[0]).then(k=>{ti.default.log("saved bookmark "+(k==null?void 0:k.id))})}}}async saveAnnotation(e){var n,i,o;if(this.annotator){var t=this.publication.getTOCItem(this.navigator.currentChapterLink.href);this.navigator.currentTocUrl&&(t=this.publication.getTOCItem(this.navigator.currentTocUrl)),t===null&&(t=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href));let s=(n=this.navigator.view)==null?void 0:n.getCurrentPosition(),c=this.navigator.iframes[0].contentDocument;if(c){let f=lo(c,"body"),u=e.position?e.position/f.scrollHeight:s,y=(0,f1.v4)(),m;if(t){let _=t.Href;if(_.indexOf("#")>0&&(_=_.slice(0,_.indexOf("#"))),this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let v=this.publication.positionsByHref(this.publication.getRelativeHref(this.navigator.currentChapterLink.href)),g=Math.ceil((u??0)*(v.length-1));m={...v[g],id:y,href:_,created:new Date,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}else m={id:y,href:_,locations:{progression:u},created:new Date,type:this.navigator.currentChapterLink.type,title:this.navigator.currentChapterLink.title,highlight:e,text:{highlight:e.selectionInfo.cleanText}}}if(m)if((i=this.navigator.consumptionModule)==null||i.trackAction(m,"BookmarkCreated"),(o=this.api)!=null&&o.addBookmark){let _=await this.api.addBookmark(m),v=await this.annotator.saveAnnotation(_);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(g=>g(v))}else{let _=await this.annotator.saveAnnotation(m);return await this.showBookmarks(),await this.drawBookmarks(),new Promise(v=>v(_))}}}return new Promise(s=>s(void 0))}getBookmarks(){let e=[];return this.annotator&&(e=this.annotator.getBookmarks()),e}showBookmarks(){let e=[];this.annotator&&(e=this.annotator.getBookmarks());let t=[];this.annotator&&(t=this.annotator.getAnnotations(),t&&(t=t.filter(n=>n.highlight.marker===2),e?e.push.apply(e,t):e=t)),this.bookmarksView&&this.createTree(0,e,this.bookmarksView)}async drawBookmarks(){var t,n;if(this.rights.enableBookmarks&&this.navigator.highlighter)if(this.api){let i=[];if(this.annotator&&(i=await this.annotator.getAnnotations()),this.navigator.highlighter&&i&&((t=this.navigator.iframes[0].contentDocument)==null?void 0:t.readyState)==="complete"){await this.navigator.highlighter.destroyHighlights(0);for(let o of i){er.push(o.highlight);let s=o,c=this.navigator.currentChapterLink.href;var e=this.publication.getTOCItem(c);if(this.navigator.currentTocUrl&&(e=this.publication.getTOCItem(this.navigator.currentTocUrl)),e===void 0&&(e=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),e){let f=e.Href;f.indexOf("#")>0&&(f=f.slice(0,f.indexOf("#"))),s.href===f&&await this.navigator.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,o.highlight)}}}}else{let i=[];if(this.annotator&&(i=await this.annotator.getAnnotations()),this.navigator.highlighter&&i&&((n=this.navigator.iframes[0].contentDocument)==null?void 0:n.readyState)==="complete"){await this.navigator.highlighter.destroyHighlights(0);for(let o of i){er.push(o.highlight);let s=o,c=this.navigator.currentChapterLink.href,f=this.publication.getTOCItem(c);if(this.navigator.currentTocUrl&&(f=this.publication.getTOCItem(this.navigator.currentTocUrl)),f===void 0&&(f=this.publication.getTOCItemAbsolute(this.navigator.currentChapterLink.href)),f){let u=f.Href;u.indexOf("#")>0&&(u=u.slice(0,u.indexOf("#"))),s.href===u&&await this.navigator.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,o.highlight)}}}}}async deleteSelectedHighlight(e){var t;(t=this.api)!=null&&t.deleteBookmark?this.api.deleteBookmark(e).then(async()=>{this.deleteLocalHighlight(e.id)}):this.deleteLocalHighlight(e.id)}async deleteLocalHighlight(e){if(this.annotator){var t=await this.annotator.deleteAnnotation(e);return ti.default.log("Highlight deleted "+JSON.stringify(t)),await this.showBookmarks(),await this.drawBookmarks(),t}else return new Promise(n=>n(null))}createTree(e,t,n){if(t){let i=this,o=this.publication.readingOrder;if(o.length){let s=(c,f)=>{let u=document.createElement("ul");u.className="sidenav-annotations";for(let y of f){let m=document.createElement("li"),_=document.createElement("a"),v=document.createElement("span");if(_.tabIndex=-1,_.className="chapter-link",y.Href){let h=this.publication.getAbsoluteHref(y.Href),l=this.publication.getTOCItemAbsolute(h);_.href=h,_.innerHTML=(l==null?void 0:l.Title)||"",m.appendChild(_)}else v.innerHTML=y.Title||"",v.className="chapter-title",m.appendChild(v);_e(_,"click",h=>{h.preventDefault(),h.stopPropagation();let l={href:_.href,locations:{progression:0},type:y.TypeLink,title:_.title};this.navigator.stopReadAloud(),this.navigator.navigate(l)});let g=document.createElement("ol");t.forEach(function(h){let l=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&h.href.endsWith(l)){let p=document.createElement("li");p.className="annotation-item";let w=document.createElement("a");if(w.setAttribute("href",h.href),e===0){w.className="bookmark-link";let C=document.createElement("span"),b=Math.round((h.locations.progression??0)*100)+"% through resource";C.className="title",C.innerHTML=b,w.appendChild(C)}let A=document.createElement("span");if(A.className="timestamp",A.innerHTML=r.readableTimestamp(h.created),w.appendChild(A),_e(w,"click",C=>{C.preventDefault(),C.stopPropagation(),i.handleAnnotationLinkClick(C,h)}),p.appendChild(w),i.navigator.sideNavExpanded){let C=document.createElement("button");C.className="delete",C.innerHTML=pi.delete,_e(C,"click",b=>{b.preventDefault(),b.stopPropagation(),i.handleAnnotationLinkDeleteClick(e,b,h)}),p.appendChild(C)}g.appendChild(p)}}),g.children.length>0&&(u.appendChild(m),u.appendChild(g)),u.children.length>0&&c.appendChild(u),y.Children&&y.Children.length>0&&s(c,y.Children)}};n.innerHTML="",s(n,o)}}}handleAnnotationLinkClick(e,t){t?(t.href=this.publication.getAbsoluteHref(t.href),this.navigator.stopReadAloud(),this.navigator.navigate(t)):ti.default.log("bookmark data missing: ",e)}handleAnnotationLinkDeleteClick(e,t,n){ti.default.log("bookmark data locator: ",n),n?e===0&&this.deleteBookmark(n):ti.default.log("bookmark data missing: ",t)}static readableTimestamp(e){let t=new Date(e);return t.toDateString()+" "+t.toLocaleTimeString()}async getAnnotation(e){var t;return(t=this.annotator)==null?void 0:t.getAnnotation(e)}async getAnnotationByID(e){var t;return(t=this.annotator)==null?void 0:t.getAnnotationByID(e)}};L();var Gw=rt(qw());L();var fn=rt($t()),p1="r2-mo-active",Ir=class Ir{};Ir.COLOR_REF="color",Ir.AUTO_SCROLL_REF="autoscroll",Ir.AUTO_TURN_REF="autoturn",Ir.VOLUME_REF="volume",Ir.RATE_REF="rate",Ir.COLOR_KEY="mediaoverlay-"+Ir.COLOR_REF,Ir.AUTO_SCROLL_KEY="mediaoverlay-"+Ir.AUTO_SCROLL_REF,Ir.AUTO_TURN_KEY="mediaoverlay-"+Ir.AUTO_TURN_REF,Ir.VOLUME_KEY="mediaoverlay-"+Ir.VOLUME_REF,Ir.RATE_KEY="mediaoverlay-"+Ir.RATE_REF;var ot=Ir,Bf=class{constructor(e,t,n){this.MEDIAOVERLAYSETTINGS="mediaOverlaySetting";this.color="r2-mo-active";this.autoScroll=!0;this.autoTurn=!0;this.volume=1;this.rate=1;this.playing=!1;this.resourceReady=!1;this.wait=1;this.settingsChangeCallback=()=>{};this.store=e,this.api=t,this.headerMenu=n,this.initialise(),fn.default.log(this.api)}static create(e){let t=new this(e.store,e.api,e.headerMenu);if(e.initialMediaOverlaySettings){let n=e.initialMediaOverlaySettings;n!=null&&n.color&&(t.color=n.color,fn.default.log(t.color)),n!=null&&n.autoScroll&&(t.autoScroll=n.autoScroll,fn.default.log(t.autoScroll)),n!=null&&n.autoTurn&&(t.autoTurn=n.autoTurn,fn.default.log(t.autoScroll)),n!=null&&n.volume&&(t.volume=n.volume,fn.default.log(t.volume)),n!=null&&n.rate&&(t.rate=n.rate,fn.default.log(t.rate)),n!=null&&n.wait&&(t.wait=n.wait,fn.default.log(t.wait))}return t.initializeSelections(),t}stop(){fn.default.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(ot.AUTO_SCROLL_KEY)!=null?this.getProperty(ot.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(ot.AUTO_TURN_KEY)!=null?this.getProperty(ot.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(ot.COLOR_KEY)!=null?this.getProperty(ot.COLOR_KEY).value:this.color,this.volume=this.getProperty(ot.VOLUME_KEY)!=null?this.getProperty(ot.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(ot.RATE_KEY)!=null?this.getProperty(ot.RATE_KEY).value:this.rate,this.userProperties=this.getMediaOverlaySettings()}reset(){this.color="redtext",this.autoScroll=!0,this.autoTurn=!0,this.volume=1,this.rate=1,this.wait=1,this.userProperties=this.getMediaOverlaySettings()}initializeSelections(){this.headerMenu&&(this.settingsView=Ne(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(e){this.headerMenu&&(this.speechAutoTurn=Ne(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=Ne(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=Ne(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=Ne(this.headerMenu,"#mediaOverlayRate")),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),this.speechAutoTurn&&(this.speechAutoTurn.checked=this.autoTurn),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechRate&&(this.speechRate.value=this.volume.toString()),_e(Ne(e,"ul"),"click",t=>{t.stopPropagation()})}onSettingsChange(e){this.settingsChangeCallback=e}storeProperty(e){this.updateUserSettings(),this.saveProperty(e)}updateUserSettings(){var t,n,i,o,s,c,f;let e={color:(t=this.userProperties.getByRef(ot.COLOR_REF))==null?void 0:t.value,autoScroll:(n=this.userProperties.getByRef(ot.AUTO_SCROLL_REF))==null?void 0:n.value,autoTurn:(i=this.userProperties.getByRef(ot.AUTO_TURN_REF))==null?void 0:i.value,volume:(o=this.userProperties.getByRef(ot.VOLUME_REF))==null?void 0:o.value,rate:(s=this.userProperties.getByRef(ot.RATE_REF))==null?void 0:s.value};this.applyMediaOverlaySettings(e),(c=this.api)!=null&&c.updateSettings&&((f=this.api)==null||f.updateSettings(e).then(async u=>{fn.default.log("api updated sync settings",u)}))}getMediaOverlaySettings(){let e=new ki;return e.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,ot.AUTO_SCROLL_REF,ot.AUTO_SCROLL_KEY),e.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,ot.AUTO_TURN_REF,ot.AUTO_TURN_KEY),e.addStringable(this.color,ot.COLOR_REF,ot.COLOR_KEY),e.addIncremental(this.volume,.1,1,.1,"",ot.VOLUME_REF,ot.VOLUME_KEY),e.addIncremental(this.rate,.1,3,.1,"",ot.RATE_REF,ot.RATE_KEY),e}saveProperty(e){let t=this.store.get(this.MEDIAOVERLAYSETTINGS);if(t){let n=JSON.parse(t);n=n.filter(i=>i.name!==e.name),n.push(e),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(n))}else{let n=[];n.push(e),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(n))}return e}getProperty(e){let t=this.store.get(this.MEDIAOVERLAYSETTINGS);if(t){let n=JSON.parse(t);return n=n.filter(i=>i.name===e),n.length===0?null:n[0]}return null}resetMediaOverlaySettings(){this.store.remove(this.MEDIAOVERLAYSETTINGS),this.reset(),this.settingsChangeCallback()}applyMediaOverlaySettings(e){if(e.color){this.color=e.color;let t=this.userProperties.getByRef(ot.COLOR_REF);t&&(t.value=this.color,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoScroll!==void 0){fn.default.log("autoScroll "+this.autoScroll),this.autoScroll=e.autoScroll;let t=this.userProperties.getByRef(ot.AUTO_SCROLL_REF);t&&(t.value=this.autoScroll,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoTurn!==void 0){fn.default.log("autoTurn "+this.autoTurn),this.autoTurn=e.autoTurn;let t=this.userProperties.getByRef(ot.AUTO_TURN_REF);t&&(t.value=this.autoTurn,this.saveProperty(t)),this.settingsChangeCallback()}if(e.volume){fn.default.log("volume "+this.volume),this.volume=e.volume;let t=this.userProperties.getByRef(ot.VOLUME_REF);t&&(t.value=this.volume,this.saveProperty(t)),this.settingsChangeCallback()}if(e.rate){fn.default.log("rate "+this.rate),this.rate=e.rate;let t=this.userProperties.getByRef(ot.RATE_REF);t&&(t.value=this.rate,this.saveProperty(t)),this.settingsChangeCallback()}}applyMediaOverlaySetting(e,t){if(e===ot.COLOR_REF){this.color=t;let n=this.userProperties.getByRef(ot.COLOR_REF);n&&(n.value=this.color,this.saveProperty(n)),this.settingsChangeCallback()}else if(e===ot.AUTO_SCROLL_REF){this.autoScroll=t;let n=this.userProperties.getByRef(ot.AUTO_SCROLL_REF);n&&(n.value=this.autoScroll,this.saveProperty(n)),this.settingsChangeCallback()}else if(e===ot.AUTO_TURN_REF){this.autoTurn=t;let n=this.userProperties.getByRef(ot.AUTO_TURN_REF);n&&(n.value=this.autoTurn,this.saveProperty(n)),this.settingsChangeCallback()}}increase(e){var t,n;if(e==="mo_volume"){this.userProperties.getByRef(ot.VOLUME_REF).increment(),this.volume=(t=this.userProperties.getByRef(ot.VOLUME_REF))==null?void 0:t.value;let i=this.userProperties.getByRef(ot.VOLUME_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}else if(e==="mo_rate"){this.userProperties.getByRef(ot.RATE_REF).increment(),this.rate=(n=this.userProperties.getByRef(ot.RATE_REF))==null?void 0:n.value;let i=this.userProperties.getByRef(ot.RATE_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}}decrease(e){var t,n;if(e==="mo_volume"){this.userProperties.getByRef(ot.VOLUME_REF).decrement(),this.volume=(t=this.userProperties.getByRef(ot.VOLUME_REF))==null?void 0:t.value;let i=this.userProperties.getByRef(ot.VOLUME_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}else if(e==="mo_rate"){this.userProperties.getByRef(ot.RATE_REF).decrement(),this.rate=(n=this.userProperties.getByRef(ot.RATE_REF))==null?void 0:n.value;let i=this.userProperties.getByRef(ot.RATE_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}}};var Ze=rt($t()),Ga=class{constructor(e,t,n){this.play=Ne(document,"#menu-button-play");this.pause=Ne(document,"#menu-button-pause");this.currentLinkIndex=0;this.pid=void 0;this.__ontimeupdate=!1;this.ontimeupdate=async e=>{Ze.default.log("ontimeupdate"),this.trackCurrentTime()};this.ensureOnTimeUpdate=(e,t)=>{e?this.__ontimeupdate&&(this.__ontimeupdate=!1,this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),cancelAnimationFrame(this.myReq)):(!this.__ontimeupdate||t)&&(this.__ontimeupdate=!0,t&&(this.audioElement&&this.audioElement.removeEventListener("timeupdate",this.ontimeupdate),this.audioElement.addEventListener("timeupdate",this.ontimeupdate)))};this.publication=e,this.settings=t,this.properties=n}static create(e){let t=new this(e.publication,e.settings,e);return t.start(),t}stop(){Ze.default.log("MediaOverlay module stop")}start(){Ze.default.log("MediaOverlay module start")}async initialize(){return new Promise(async e=>{await document.fonts.ready,this.settings.setControls(),this.settings.onSettingsChange(()=>{this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}),e()})}async initializeResource(e){this.currentLinks=e,this.currentLinkIndex=0,await this.playLink()}async playLink(){var t,n;let e=this.currentLinks[this.currentLinkIndex];if((t=e==null?void 0:e.Properties)!=null&&t.MediaOverlay){this.ensureOnTimeUpdate(!1,!1);let i=(n=e.Properties)==null?void 0:n.MediaOverlay,s=new URL(i,this.publication.manifestUrl).toString(),c;try{c=await fetch(s,this.navigator.requestConfig)}catch(m){console.error(m,s);return}c.ok||Ze.default.log("BAD RESPONSE?!");let f;try{f=await c.json()}catch(m){console.error(m)}if(!f){Ze.default.log("## moJson"+f);return}e.MediaOverlays=ba(f,Gw.MediaOverlayNode),e.MediaOverlays.initialized=!0;let u=e.HrefDecoded||e.Href,y=new URL("https://dita.digital/"+u);await this.playMediaOverlays(y.pathname.substr(1),e.MediaOverlays,void 0)}else this.audioElement&&await this.audioElement.pause(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement&&await this.audioElement.pause(),this.navigator.nextResource()):await this.stopReadAloud()}async startReadAloud(){var e;if(this.navigator.rights.enableMediaOverlays){if(this.settings.playing=!0,this.audioElement&&((e=this.currentLinks[this.currentLinkIndex])!=null&&e.Properties.MediaOverlay)){let t=this.currentAudioBegin?this.currentAudioBegin:0;this.audioElement.currentTime=t,await this.audioElement.play(),this.ensureOnTimeUpdate(!1,!0),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate}else this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?this.navigator.nextResource():await this.stopReadAloud();this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display")}}async stopReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement&&this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}pauseReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!1,this.audioElement.pause(),this.play&&this.play.style.removeProperty("display"),this.pause&&(this.pause.style.display="none"))}async resumeReadAloud(){this.navigator.rights.enableMediaOverlays&&(this.settings.playing=!0,await this.audioElement.play(),this.play&&(this.play.style.display="none"),this.pause&&this.pause.style.removeProperty("display"))}findDepthFirstTextAudioPair(e,t,n){Ze.default.log("findDepthFirstTextAudioPair()");let i,o;if(t.Text){let f=new URL("https://dita.digital/"+t.Text);if(f.pathname.substr(1)===e){if(i=!0,f.hash&&n){o=!1;let u=f.hash.substr(1);for(let y of n)if(y===u){o=!0;break}}}else i=!1}if(Ze.default.log("isFragmentIDMatch: "+o),Ze.default.log("isTextUrlMatch: "+i),!t.Children||!t.Children.length){if(Ze.default.log("findDepthFirstTextAudioPair() - leaf text/audio pair"),!i){Ze.default.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch");return}return o||i&&!n?(Ze.default.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),t):void 0}let s=n,c=n;for(let f of t.Children){Ze.default.log("findDepthFirstTextAudioPair() - child"),Ze.default.log(JSON.stringify(f));let u=this.findDepthFirstTextAudioPair(e,f,c);if(u===null&&(Ze.default.log("findDepthFirstTextAudioPair() - child - match null (skip)"),c=void 0),u)return Ze.default.log("findDepthFirstTextAudioPair() - child - match"),Ze.default.log(JSON.stringify(u)),u}if(o){Ze.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch");let f=this.findDepthFirstTextAudioPair(e,t,void 0);return f&&(Ze.default.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch - match"),Ze.default.log(JSON.stringify(f)),f)}if(s&&!c)return null}trackCurrentTime(){if(cancelAnimationFrame(this.myReq),this.mediaOverlayTextAudioPair)try{this.currentAudioEnd&&this.audioElement.currentTime>=this.currentAudioEnd-.05&&(Ze.default.log("ontimeupdate - mediaOverlaysNext()"),this.mediaOverlaysNext());let e=this.mediaOverlayTextAudioPair.Text.lastIndexOf("#"),t=this.mediaOverlayTextAudioPair.Text.substr(e+1);this.mediaOverlayHighlight(t),this.myReq=requestAnimationFrame(this.trackCurrentTime.bind(this))}catch{}}mediaOverlaysNext(e){if(Ze.default.log("mediaOverlaysNext()"),this.mediaOverlayRoot&&this.mediaOverlayTextAudioPair){let t=this.findNextTextAudioPair(this.mediaOverlayRoot,this.mediaOverlayTextAudioPair,{prev:void 0},!!e);if(!t)Ze.default.log("mediaOverlaysNext() - navLeftOrRight()"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud());else{let n=!1;if(this.mediaOverlayTextAudioPair.Text&&t.Text){let i=new URL("https://dita.digital/"+this.mediaOverlayTextAudioPair.Text),o=new URL("https://dita.digital/"+t.Text);i.pathname!==o.pathname&&(Ze.default.log("mediaOverlaysNext() SWITCH! "+i.pathname+" != "+o.pathname),n=!0)}n?this.mediaOverlaysStop():(Ze.default.log("mediaOverlaysNext() - playMediaOverlaysAudio()"),setTimeout(async()=>{await this.playMediaOverlaysAudio(t,void 0,void 0)},0))}}else Ze.default.log("mediaOverlaysNext() - navLeftOrRight() 2"),this.mediaOverlaysStop(),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,this.playLink()):(this.audioElement.pause(),this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud())}mediaOverlaysStop(){Ze.default.log("mediaOverlaysStop()"),this.mediaOverlaysPause(),this.mediaOverlayRoot=void 0,this.mediaOverlayTextAudioPair=void 0}mediaOverlaysPause(){Ze.default.log("mediaOverlaysPause()"),this.mediaOverlayHighlight(void 0),this.audioElement&&this.audioElement.pause()}findNextTextAudioPair(e,t,n,i){if(!e.Children||!e.Children.length){if((n==null?void 0:n.prev)===t)return Ze.default.log("findNextTextAudioPair() - prevMo === moToMatch"),e;Ze.default.log("findNextTextAudioPair() - set previous"),Ze.default.log(JSON.stringify(e)),n.prev=e;return}for(let o of e.Children){Ze.default.log("findNextTextAudioPair() - child"),Ze.default.log(JSON.stringify(o));let s=this.findNextTextAudioPair(o,t,n,i);if(s)return Ze.default.log("findNextTextAudioPair() - match"),Ze.default.log(JSON.stringify(s)),s}}async playMediaOverlaysAudio(e,t,n){if(Ze.default.log("playMediaOverlaysAudio()"),this.mediaOverlayTextAudioPair=e,!e.Audio)return;let i=new URL(e.Audio,this.publication.manifestUrl),o=i.toString(),s=new URL(o);s.hash="",s.search="";let c=s.toString(),f=typeof t<"u",u=typeof n<"u";if(this.previousAudioEnd=this.currentAudioEnd,this.currentAudioBegin=void 0,this.currentAudioEnd=void 0,!f&&!u){if(i.hash){let m=i.hash.match(/t=([0-9.]+)(,([0-9.]+))?/);if(m&&m.length>=1){let _=m[1];try{this.currentAudioBegin=parseFloat(_)}catch(v){Ze.default.error(v)}if(m.length>=3){let v=m[3];try{this.currentAudioEnd=parseFloat(v)}catch(g){Ze.default.error(g)}}}}}else this.currentAudioBegin=t,this.currentAudioEnd=n;Ze.default.log(`${o} => [${this.currentAudioBegin}-${this.currentAudioEnd}]`);let y=async m=>{if(!this.audioElement)return;let _=this.currentAudioBegin?this.currentAudioBegin:0;if(m||this.audioElement.paused)if(m&&!_||this.audioElement.currentTime===_){if(Ze.default.log("playMediaOverlaysAudio() - playClip() - _currentAudioElement.play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing){let g=function(){v.settings.resourceReady?setTimeout(async()=>{await v.audioElement.play(),v.ensureOnTimeUpdate(!1,!0)},v.settings.wait*1e3):setTimeout(g,200)},v=this;g()}}else{Ze.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked");let v=async g=>{if(this.audioElement.removeEventListener("timeupdate",v),Ze.default.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked - .play()"),this.ensureOnTimeUpdate(!1,!1),this.audioElement&&(this.audioElement.playbackRate=this.settings.rate,this.audioElement.volume=this.settings.volume,this.settings.playing)){let l=function(){h.settings.resourceReady?setTimeout(async()=>{await h.audioElement.play(),h.ensureOnTimeUpdate(!1,!0)},h.settings.wait*1e3):setTimeout(l,200)},h=this;l()}};this.audioElement.addEventListener("timeupdate",v),this.audioElement.currentTime=_}else{let v=this.previousAudioUrl===this.currentAudioUrl&&typeof this.previousAudioEnd<"u"&&this.previousAudioEnd>_-.02&&this.previousAudioEnd<=_&&this.audioElement.currentTime>=_-.1;this.ensureOnTimeUpdate(!1,!1),v?Ze.default.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"):(Ze.default.log("playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo"),this.audioElement.currentTime=_)}};if(this.previousAudioUrl=this.currentAudioUrl,!this.currentAudioUrl||c!==this.currentAudioUrl){this.currentAudioUrl=c,Ze.default.log("playMediaOverlaysAudio() - RESET: "+this.previousAudioUrl+" => "+this.currentAudioUrl),this.audioElement=document.getElementById("AUDIO_MO_ID"),this.audioElement&&(this.audioElement.pause(),this.audioElement.setAttribute("src",""),this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement)),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("style","display: none"),this.audioElement.setAttribute("id","AUDIO_MO_ID"),this.audioElement.setAttribute("role","media-overlays"),this.audioElement.volume=this.settings.volume,this.audioElement.playbackRate=this.settings.rate,document.body.appendChild(this.audioElement),this.audioElement.addEventListener("error",v=>{Ze.default.log("-1) error: "+(this.currentAudioUrl!==v.currentTarget.src?this.currentAudioUrl+" -- ":"")+v.currentTarget.src.substr(v.currentTarget.src.lastIndexOf("/"))),this.audioElement&&this.audioElement.error&&(Ze.default.log(this.audioElement.error.code),Ze.default.log(this.audioElement.error.message))});let m=async v=>{v.currentTarget.removeEventListener("canplaythrough",m),Ze.default.log("oncanplaythrough"),await y(!0)};this.audioElement.addEventListener("canplaythrough",m);let _=async v=>{Ze.default.log("onended"),this.currentLinks.length>1&&this.currentLinkIndex===0?(this.currentLinkIndex++,await this.playLink()):this.settings.autoTurn&&this.settings.playing?(this.audioElement.pause(),this.navigator.nextResource()):this.stopReadAloud()};this.audioElement.addEventListener("ended",_),this.audioElement.playbackRate=this.settings.rate,this.audioElement.setAttribute("src",this.currentAudioUrl)}else Ze.default.log("playMediaOverlaysAudio() - playClip()"),await y(!1)}async playMediaOverlays(e,t,n){Ze.default.log("playMediaOverlays()");let i=n?n.filter(s=>s):void 0;i&&i.length===0&&(i=void 0);let o=this.findDepthFirstTextAudioPair(e,t,i);!o&&i&&(Ze.default.log("playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE "),Ze.default.log(JSON.stringify(i,null,4)),Ze.default.log(JSON.stringify(t,null,4)),o=this.findDepthFirstTextAudioPair(e,t,void 0)),o?o.Audio&&(Ze.default.log("playMediaOverlays() - playMediaOverlaysAudio()"),this.mediaOverlayRoot=t,await this.playMediaOverlaysAudio(o,void 0,void 0)):Ze.default.log("playMediaOverlays() - !moTextAudioPair "+e)}mediaOverlayHighlight(e){var c,f,u,y,m,_,v,g,h;Ze.default.log("moHighlight: ## "+e);let t=(f=(c=this.publication.Metadata)==null?void 0:c.MediaOverlay)==null?void 0:f.ActiveClass;t||(t=this.settings.color);let n=(u=this.navigator.iframes[0].contentDocument)==null?void 0:u.documentElement.getAttribute("style"),i=n?n.indexOf("readium-night-on")>0:!1,o=n?n.indexOf("readium-sepia-on")>0:!1;if((((y=this.publication.Metadata.Rendition)==null?void 0:y.Layout)??"unknown")!=="fixed"&&(t=i||o?p1:t||p1),this.pid){let l;this.currentLinkIndex===0?l=(m=this.navigator.iframes[0].contentDocument)==null?void 0:m.getElementById(this.pid):l=(_=this.navigator.iframes[1].contentDocument)==null?void 0:_.getElementById(this.pid),l&&l.classList.remove(t)}let s;e&&(this.currentLinkIndex===0?s=(v=this.navigator.iframes[0].contentDocument)==null?void 0:v.getElementById(e):s=(g=this.navigator.iframes[1].contentDocument)==null?void 0:g.getElementById(e),s&&s.classList.add(t),this.pid=e),s&&(((h=this.publication.Metadata.Rendition)==null?void 0:h.Layout)??"unknown")!=="fixed"&&s.scrollIntoView({block:"center",behavior:"smooth"})}};L();var g1=rt($t()),Wa=class{static async create(e){let t=new this(e.publication);return await t.start(),t}constructor(e){this.publication=e}async stop(){g1.default.log("Timeline module stop")}async start(){this.timelineContainer=Ne(document,"#container-view-timeline"),this.positionSlider=Ne(document,"#positionSlider"),this.publication.positions?this.positionSlider&&(this.positionSlider.style.display="block"):this.positionSlider&&(this.positionSlider.style.display="none")}async initialize(){return new Promise(async e=>{var n;await document.fonts.ready;let t=this.navigator.currentLocator();(this.navigator.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions)&&(this.positionSlider&&(this.positionSlider.value=(t.locations.position??0).toString()),this.positionSlider&&(this.positionSlider.max=((t.locations.totalRemainingPositions??0)+(t.locations.position??0)).toString())),this.timelineContainer&&(this.timelineContainer.innerHTML=""),(n=this.publication.readingOrder)==null||n.forEach(i=>{var _,v;let o=this.publication.getAbsoluteHref(i.Href),s=this.publication.getTOCItemAbsolute(o),c=(s==null?void 0:s.Href.indexOf("#"))!==-1?s==null?void 0:s.Href.slice(0,s==null?void 0:s.Href.indexOf("#")):s.Href,f=this.publication.getAbsoluteHref(c??"");var u;this.publication.positions&&((_=this.navigator.view)==null?void 0:_.layout)!=="fixed"?i.contentWeight?u=i.contentWeight:u=1:u=100/(((v=this.publication.readingOrder)==null?void 0:v.length)??0);var y=document.createElement("div");if(y.style.height=u+"%",y.style.width="100%",y.className="chapter",(s==null?void 0:s.Title)!==void 0){var m=document.createElement("span");m.innerHTML=s.Title,m.className="chapter-tooltip",y.appendChild(m)}_e(y,"click",g=>{g.preventDefault(),g.stopPropagation();var h;this.publication.positions||this.navigator.rights.autoGeneratePositions&&this.publication.positions?(h={...this.publication.positions.filter(l=>l.href===i.Href)[0]},h.href=this.publication.getAbsoluteHref(h.href)):h={href:f,locations:{progression:0},type:i.TypeLink,title:i.Title},g1.default.log(h),this.navigator.navigate(h)}),f===this.navigator.currentChapterLink.href?y.className+=" active":y.className=y.className.replace(" active",""),this.timelineContainer&&this.timelineContainer.appendChild(y)}),e()})}};L();var Z1=rt(Vo());L();var Ww=rt($t());function zw(r,e){return new Promise(function(t){setTimeout(t.bind(null,e),r)})}var gD=!1;Ww.default.setLevel(gD?"trace":"warn",!0);var hh=rt(Vw()),Nr=rt($t());L();var aC=rt(B8(),1),mi=rt(QA(),1);L();var ZA=[{regex:/IE (\d+)\.(\d+)/,family:"ie",maxVersion:[7,1/0,1/0]},{regex:/Trident\/4\.0/,family:"ie",version:[8,0,0]},{regex:/Trident\/5\.0/,family:"ie",version:[9,0,0]},{regex:/Trident\/6\.0/,family:"ie",version:[10,0,0]},{regex:/Trident\/[78]\.0/,family:"ie",version:[11,0,0]},{regex:/Edge?\/(\d+)\.(\d+)(\.(\d+)|)/,family:"edge"},{regex:/Firefox\/(\d+)\.(\d+)(\.(\d+)|)/,family:"firefox"},{regex:/Chrom(ium|e)\/(\d+)\.(\d+)(\.(\d+)|)/,family:"chrome"},{regex:/Chrom(ium|e)\/(\d+)\.(\d+)(\.(\d+)|)([\d.]+$|.*Safari\/(?![\d.]+ Edge\/[\d.]+$))/,family:"chrome",maxVersion:[70,1/0,1/0]},{regex:/(Maci|X11).+ Version\/(\d+)\.(\d+)([.,](\d+)|)( \(\w+\)|)( Mobile\/\w+|) Safari\//,family:"safari"},{regex:/Opera\/9\.80.+Version\/(\d+)\.(\d+)(\.(\d+)|)/,family:"opera",maxVersion:[12,15,0]},{regex:/Chrome.+OPR\/(\d+)\.(\d+)\.(\d+)/,family:"opera",minVersion:[15,0,0]},{regex:/(CPU[ +]OS|iPhone[ +]OS|CPU[ +]iPhone|CPU IPhone OS|CPU iPad OS)[ +]+(\d+)[_.](\d+)([_.](\d+)|)/,family:"ios_saf"},{regex:/[^e] (CPU[ +]OS|iPhone[ +]OS|CPU[ +]iPhone|CPU IPhone OS|CPU iPad OS)[ +]+(\d+)[_.](\d+)([_.](\d+)|)/,family:"ios_saf",version:[7,0,3]},{regex:/Opera Mini/,family:"op_mini"},{regex:/Android Donut/,family:"android",version:[1,2,0]},{regex:/Android Eclair/,family:"android",version:[2,1,0]},{regex:/Android Froyo/,family:"android",version:[2,2,0]},{regex:/Android Gingerbread/,family:"android",version:[2,3,0]},{regex:/Android Honeycomb/,family:"android",version:[3,0,0]},{regex:/Android:?[ /-](\d+)(\.(\d+)|)(\.(\d+)|)/,family:"android"},{regex:/Android:?[ /-](\d+)(\.(\d+)|)(\.(\d+)|);(?! ARM; Trident)/,family:"android",version:[4,0,0]},{regex:/PlayBook.+RIM Tablet OS (\d+)\.(\d+)\.(\d+)/,family:"bb"},{regex:/(Black[bB]erry|BB10).+Version\/(\d+)\.(\d+)\.(\d+)/,family:"bb"},{regex:/Opera\/.+Opera Mobi.+Version\/(\d+)\.(\d+)/,family:"op_mob",maxVersion:[12,16,0]},{regex:/Mobile Safari.+OPR\/(\d+)\.(\d+)\.(\d+)/,family:"op_mob",minVersion:[14,0,0]},{regex:/Android.+Firefox\/(\d+)\.(\d+)(\.(\d+)|)/,family:"and_ff"},{regex:/Android.+Chrom(ium|e)\/(\d+)\.(\d+)(\.(\d+)|)/,family:"and_chr"},{regex:/IEMobile[ /](\d+)\.(\d+)/,family:"ie_mob"},{regex:/Android.+(UC? ?Browser|UCWEB|U3)[ /]?(\d+)\.(\d+)\.(\d+)/,family:"and_uc"},{regex:/SamsungBrowser\/(\d+)\.(\d+)/,family:"samsung"},{regex:/Android.+MQQBrowser\/(\d+)(\.(\d+)|)(\.(\d+)|)/,family:"and_qq"},{regex:/baidubrowser[/\s](\d+)(\.(\d+)|)(\.(\d+)|)/,family:"baidu"},{regex:/K[Aa][Ii]OS\/(\d+)\.(\d+)(\.(\d+)|)/,family:"kaios"}];function J1(r){return typeof r=="number"?r:r.length===1?r[0]:[r[0],r[r.length-1]]}var fr;(function(r){r[r.Major=0]="Major",r[r.Minor=1]="Minor",r[r.Patch=2]="Patch"})(fr||(fr={}));function eC(r){let e=Array.isArray(r)?r:r.toString().split(".");if(e[0]==="all")return[1/0,0,0];let t=null,n=null,i=[0,0,0];for(let o=0;o<3;o++)if(t=e[o],!(typeof t>"u")){if(n=typeof t=="number"?t:parseInt(t,10),isNaN(n))return null;i[o]=n}return i}function iU(r,e){let t=0,n=[];for(let i=2;i>=0;i--)if(r[i]!==e[i]){t=i;break}for(let i=r[t],o=e[t];i<=o;i++)n.push(r.map((s,c)=>c===t?i:s));return n}function tC(r,e,t){let[n,i,o]=r,[s,c,f]=e,{ignoreMinor:u,ignorePatch:y,allowHigherVersions:m}=t;if(s===1/0)return!0;let _=!u,v=_&&!y;return m?v&&o<f||_&&i<c?!1:n>=s:v&&o!==f||_&&i!==c?!1:n===s}function oU(r,e){let{ignoreMinor:t,ignorePatch:n,allowZeroSubversions:i}=e,o=t?1:n?2:3;if(i)for(let s=o-1;s>0&&!(r[s]!==0||o===1);s--)o--;return o}function sU(r){return r.reduce((e,t)=>{let[n,i,o]=t.split(/ |-/),s=eC(i);return(s?o?iU(s,eC(o)):[s]:[]).reduce((f,u)=>(u&&f.push({family:n,version:u}),f),e)},[])}function aU(r={}){let{browsers:e,...t}=r,n=(0,aC.default)(e,t);return sU(n)}function uU(r,e,t=0){let n=r.length;for(let i=t;i<n;i++)if(r[i]!==e[i])return!1;return!0}function uC(r){if(r===null||typeof r!="object")return r;let e=Array.isArray(r)?[]:{},t;for(t in r)e[t]=uC(r[t]);return e}function dh(r){return[].concat(...r)}function lU(r){let e=new Map;return r.forEach(({family:t,version:n})=>{let i=e.get(t);if(i){let o=n.join(".");i.every(s=>s.join(".")!==o)&&i.push(n);return}e.set(t,[n])}),e.forEach(t=>{t.sort((n,i)=>{for(let o in n)if(n[o]!==i[o])return n[o]-i[o];return 0})}),e}function cU(r){if(r.length<2)return r;let e=r.length+1,t=[],n=null,i=r[0],o=[i[fr.Major]],s=[i[fr.Minor]],c=[i[fr.Patch]],f=null;for(let u=1;u<e;u++){n=r[u-1],i=r[u]||[];for(let y=fr.Major;y<=fr.Patch;y++){if((y===f||f===null)&&n[y]+1===i[y]&&uU(n,i,y+1)){f=y,y===fr.Major?o.push(i[fr.Major]):o=i[fr.Major],y===fr.Minor?s.push(i[fr.Minor]):s=i[fr.Minor],y===fr.Patch?c.push(i[fr.Patch]):c=i[fr.Patch];break}if(f===y||n[y]!==i[y]){t.push([J1(o),J1(s),J1(c)]),o=[i[fr.Major]],s=[i[fr.Minor]],c=[i[fr.Patch]],f=null;break}}}return t}function dU(r){return{type:"RegExp",body:r,flags:""}}function So(...r){let e=dh(r).filter(Boolean);return e.length===1?e[0]:{type:"Alternative",expressions:e}}function ri(r){return{type:"Char",kind:"simple",value:String(r),codePoint:NaN}}function fU(r){return{type:"Char",kind:"meta",value:r,codePoint:NaN}}function lC(r,e){return{type:"ClassRange",from:r,to:e}}function K1(...r){return{type:"CharacterClass",expressions:dh(r).filter(Boolean)}}function hU(r){return{type:"Quantifier",kind:r,greedy:!0}}function pU(r,e){return{type:"Quantifier",kind:"Range",from:r,to:e,greedy:!0}}function cC(r){return{type:"Group",capturing:!0,expression:r,number:null}}function gU(r,e){return{type:"Repetition",expression:r,quantifier:e}}function mU(...r){let e=dh(r).filter(Boolean);if(e.length===1)return e[0];let t={type:"Disjunction",left:null,right:e.pop()};return e.reduceRight((n,i,o)=>o===0?(n.left=i,n):(n.left={type:"Disjunction",left:null,right:i},n.left),t),t}function fh(...r){let e=mU(...r);return e.type==="Disjunction"?cC(e):e}function tu(){return fU("\\d")}function eu(r=hU("+")){return gU(tu(),r)}function rC(r){return So(Array.from(String(r),ri))}function ch(r){if(r.type==="Group"&&r.expression.type==="Repetition"){let{expression:e,quantifier:t}=r.expression;return e.type==="Char"&&e.value==="\\d"&&t.kind==="+"&&t.greedy}return!1}function Za(r,e){return r&&r.type==="Char"?typeof e>"u"||e instanceof RegExp&&e.test(r.value)||String(e)===r.value:!1}function nC(r){if(r.type==="CharacterClass"&&r.expressions.length===1){let[e]=r.expressions;return e.type==="ClassRange"&&Za(e.from,/\d/)&&Za(e.to,/\d/)}return!1}function iC(r){return r.type!=="RegExp"&&r.type!=="ClassRange"&&r.type!=="Quantifier"}function ru(r){return typeof r=="string"?mi.default.parse(r.replace(/^([^/])/,"/$1").replace(/([^/])$/,"$1/")):r instanceof RegExp?mi.default.parse(r):r}function yU(r){return typeof r=="string"?new RegExp(r):new RegExp(mi.default.generate(r.body),r.flags)}function bU(r){return typeof r=="string"?r:r instanceof RegExp?r.toString():mi.default.generate(r)}var vU=["RegExp","Disjunction","Alternative","Assertion","Char","CharacterClass","ClassRange","Backreference","Group","Repetition","Quantifier"];function Q1(r){let{every:e}=r;return e?typeof e=="function"?{"*":e,...r}:vU.reduce((t,n)=>{let i=r[n],o=i?"pre"in i?i.pre:i:null,s=i&&"post"in i?i.post:null;return t[n]={pre(c){return e.pre(c)!==!1&&o?o(c):!0},post(c){return e.post(c)!==!1&&s?s(c):!0}},t},{}):r}function _U(r){let e=mi.default.optimize(ru(bU(r))).getAST();return mi.default.traverse(e,{Group(t){let{parent:n,node:i}=t,{expression:o}=i;i.capturing=!0,(n.type==="RegExp"||o.type!=="Disjunction"&&n.type!=="Repetition"||o.type==="Disjunction"&&n.type==="Disjunction")&&t.replace(t.node.expression)}}),e}function wU(r,e){return Za(r)&&Za(e)&&r.value===e.value?e:Za(r,/\d/)&&nC(e)&&Number(e.expressions[0].from.value)-Number(r.value)===1?{...e,expressions:[{...e.expressions[0],from:r}]}:nC(r)&&Za(e,/\d/)&&Number(e.value)-Number(r.expressions[0].to.value)===1?{...r,expressions:[{...r.expressions[0],to:e}]}:null}function SU(r){return r.reduce((e,t)=>{let n=e[e.length-1];if(n&&t.type==="Alternative"&&n.type==="Alternative"&&t.expressions.length===n.expressions.length){let i=n.expressions.reduceRight((o,s,c)=>{if(!o)return o;let f=wU(s,t.expressions[c]);if(f)o.unshift(f);else return null;return o},[]);i&&(t.expressions=i,e.pop())}return e.push(t),e},[])}function Y1(r){return Array.from(r.toString(),Number)}function oC(r,e){let t=r+ +!e;return t===0?tu():t===9?ri("9"):t>9?null:K1(lC(ri(t),ri("9")))}function AU(r){if(r===0)return[eu()];let e=Y1(r),t=e.length,n=eu(pU(t+1)),i=t-1;if(r/Math.pow(10,i)===e[0])return[So(oC(e[0],!0),Array.from({length:i},tu)),n];let s=e.reduce((c,f,u)=>{let y=t-u-1,m=u===0,_=ri(""),v=e.reduce((g,h,l)=>{if(l<y)g.push(ri(h));else if(_)if(l>y)g.push(tu());else if(_=oC(h,m),_)g.push(_);else return[];return g},[]);return v.length&&c.push(v),c},[]).map(c=>So(c));return s.push(n),s}function Qa(r,e,t){if(e<r)return null;let n=ri(r),i=ri(e),o=typeof t=="number"&&t>0?Array.from({length:t},()=>ri(0)):[],s=o.length?c=>So(o,c):c=>c;return r===e?s(n):r===0&&e===9?s(tu()):e-r===1?s(K1(n,i)):s(K1(lC(n,i)))}function CU(r,e){let t=[],n=r,i=1;do i*=10,n<i&&(t.push([n,Math.min(i-1,e)]),n=i);while(i<=e);return t}function EU(r,e){let t=r.length;if(t!==e.length||r[0]!==e[0])return null;let n=r[0].toString(),i=0,o=0,s="",c="";for(let f=1;f<t;f++)i=r[f],o=e[f],i===o?n+=i:(s+=i,c+=o);return[n,parseInt(s,10),parseInt(c,10)]}function X1(r,e,t=0){let n=Y1(r),i=n.length;if(r<10&&e<10||r===e){let y=t-i;return[Qa(r,e,y)]}let o=Y1(e);if(i!==o.length){let y=CU(r,e);return dh(y.map(([_,v])=>X1(_,v,t)))}let s=EU(n,o);if(Array.isArray(s)){let[y,m,_]=s,v=i-y.length,g=X1(m,_,v);return[So(Array.from(y,ri),fh(g))]}let c=Array.from({length:i-1}),f=Qa(n[0]+1,o[0]-1),u=[...c.map((y,m)=>{let _=i-m-1,v=+(m>0);return So(n.map((g,h)=>h<_?ri(g):h>_?Qa(0,9):Qa(g+v,9)))}),...f?[So(f,Array.from({length:i-1},()=>tu()))]:[],...c.map((y,m)=>{let _=i-m-1,v=+(m>0);return So(o.map((g,h)=>h<_?ri(g):h>_?Qa(0,9):Qa(0,g-v)))})];return SU(u)}function sC(r,e=1/0){if(r===1/0)return eu();let t=e===1/0?AU(r):X1(r,e);return fh(t)}function xU(r,e,t,n){let i={...n,allowHigherVersions:!0},o=f=>tC(f,r,i),s=f=>tC(e,f,i),c=r&&e?f=>o(f)&&s(f):r?o:e?s:()=>!0;return t.filter(c)}function TU(r,e,t=ZA){let n=[],i="",o=!1;return t.forEach(s=>{let c=r.get(s.family);if(!c)return;let{version:f,minVersion:u,maxVersion:y}=s;f&&(u=f,y=f);let m=xU(u,y,c,e);m.length&&(i===s.family&&o&&(f=void 0,u=void 0,y=void 0,m=c,n.pop()),n.push({...s,version:f,minVersion:u,maxVersion:y,requestVersions:c,matchedVersions:m})),o=!f&&!u&&!y,i=s.family}),n}function PU(r){let e=r.map(({regexAst:n})=>cC(n.body)),t=_U(dU(fh(e)));return yU(t)}function OU(r){let e=ru(r),t=0;return mi.default.traverse(e,{Group(n){ch(n.node)&&t++}}),t}function MU(r,e,t){let n=ru(r),i=typeof t=="number"&&t<e.length?e.slice(0,t):e.slice();return mi.default.traverse(n,Q1({every(){return!!i.length},Group(o){return ch(o.node)&&i.length?(n===o.node?n=i.shift():o.replace(i.shift()),!1):!0}})),n}function dC(r,e){let t=ru(r),n=Math.min(OU(t),e||1/0),i=[],o=0,s=!1;return mi.default.traverse(t,Q1({every:{pre({node:c,parent:f}){return c===t?!0:iC(c)?(f===t&&(s=!1),o<n):!1},post({node:c,parent:f}){c!==t&&f===t&&iC(c)&&(s||o>0&&o<n)&&i.push(c)}},Group(c){return ch(c.node)&&o<n?(s=!0,o++,!1):!0}})),i.length===1&&!ch(i[0])?dC(i[0],n):i}function kU(r,e){let{ignoreMinor:t,ignorePatch:n,allowHigherVersions:i}=e,o=r[0]===1/0?0:t?1:n?2:3;if(i){let c=[],f=!0,u=0,y=0,m=_=>(v,g)=>g>=o?eu():(y=Array.isArray(v)?v[0]:v,g<_?rC(y):g>_?eu():sC(y+u));for(let _=o-1;_>=0;_--)f&&!r[_]||(f=!1,c.push(r.map(m(_))),u=1);return c}return[r.map((c,f)=>f>=o?eu():Array.isArray(c)?sC(c[0],c[1]):rC(c))]}function RU(r,e,t){let{allowHigherVersions:n}=t,i=ru(r),o=n&&e.length?[e[0]]:e,s=o.reduce((u,y)=>Math.max(u,oU(y,t)),1),c=dC(i,s),f=fh(...o.map(u=>kU(u,t).map(y=>MU(So(uC(c)),y,s))));return mi.default.traverse(i,Q1({every(u){return c.length?(u.node===c[0]&&(c.length===1?u.replace(f):u.remove(),c.shift()),!0):!1}})),i}function LU(r,e){return r.map(({regex:t,version:n,maxVersion:i,matchedVersions:o,...s})=>{let c=ru(t);return n||(c=RU(c,cU(o),{...e,allowHigherVersions:!i&&e.allowHigherVersions})),{regex:null,sourceRegex:t,regexAst:c,version:n,maxVersion:i,matchedVersions:o,...s}})}var IU={ignoreMinor:!1,ignorePatch:!0,allowZeroSubversions:!1,allowHigherVersions:!1};function NU(r={}){let e={...IU,...r},t=aU(e),n=lU(t),i=TU(n,e);return LU(i,e)}function fC(r={}){return PU(NU(r))}var Ns=class{constructor(e){this.hasEventListener=!1;this.isHacked=!1;this.properties=e}static async setupPreloadProtection(e){if(this.isCurrentBrowserSupported(e))e.detectInspect&&await this.startInspectorProtection(e);else throw new Error("Browser not supported")}static async create(e){let t=new this(e);return await t.start(),t}static async startInspectorProtection(e){(0,hh.addListener)(n=>{var i;n&&(e.clearOnInspect&&(console.clear(),window.localStorage.clear(),window.sessionStorage.clear(),window.location.replace(window.location.origin)),e.detectInspect&&typeof((i=e.api)==null?void 0:i.inspectDetected)=="function"&&e.api.inspectDetected())}),(0,hh.launch)(),await zw(e.detectInspectInitDelay??100)}static isCurrentBrowserSupported(e){if(!e.enforceSupportedBrowsers)return!0;let t=[];return(e.supportedBrowsers??[]).forEach(i=>{t.push("last 1 "+i+" version")}),fC({browsers:t,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){var t;if((t=this.properties)!=null&&t.enableObfuscation){this.wrapper=ft(document,"#iframe-wrapper"),this.securityContainer=Ne(document,"#container-view-security");var e=this;this.mutationObserver=new MutationObserver(function(n){n.forEach(function(i){Nr.default.log(i.type),e.isHacked=!0})})}}async stop(){var e,t,n,i,o,s,c,f;if(Nr.default.log("Protection module stop"),(e=this.properties)!=null&&e.enableObfuscation&&this.mutationObserver.disconnect(),(t=this.properties)!=null&&t.disableKeys){Ue(this.navigator.mainElement,"keydown",this.disableSave),Ue(this.navigator.headerMenu,"keydown",this.disableSave);for(let u of this.navigator.iframes)Ue(u.contentDocument,"keydown",this.disableSave),Ue(u.contentWindow,"keydown",this.disableSave);Ue(window,"keydown",this.disableSave),Ue(document,"keydown",this.disableSave)}if((n=this.properties)!=null&&n.disableCopy){Ue(this.navigator.mainElement,"copy",this.preventCopy),Ue(this.navigator.headerMenu,"copy",this.preventCopy);for(let u of this.navigator.iframes)Ue(u.contentDocument,"copy",this.preventCopy),Ue(u.contentWindow,"copy",this.preventCopy);Ue(window,"copy",this.preventCopy),Ue(document,"copy",this.preventCopy),Ue(this.navigator.mainElement,"cut",this.preventCopy),Ue(this.navigator.headerMenu,"cut",this.preventCopy);for(let u of this.navigator.iframes)Ue(u.contentDocument,"cut",this.preventCopy),Ue(u.contentWindow,"cut",this.preventCopy);Ue(window,"cut",this.preventCopy),Ue(document,"cut",this.preventCopy),Ue(this.navigator.mainElement,"keydown",this.preventCopyKey),Ue(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let u of this.navigator.iframes)Ue(u.contentDocument,"keydown",this.preventCopyKey),Ue(u.contentWindow,"keydown",this.preventCopyKey);Ue(window,"keydown",this.preventCopyKey),Ue(document,"keydown",this.preventCopyKey)}else if((i=this.properties)!=null&&i.canCopy){Ue(this.navigator.mainElement,"copy",this.restrictCopy),Ue(this.navigator.headerMenu,"copy",this.restrictCopy);for(let u of this.navigator.iframes)Ue(u.contentDocument,"copy",this.restrictCopy),Ue(u.contentWindow,"copy",this.restrictCopy);Ue(window,"copy",this.restrictCopy),Ue(document,"copy",this.restrictCopy),Ue(this.navigator.mainElement,"cut",this.restrictCopy),Ue(this.navigator.headerMenu,"cut",this.restrictCopy);for(let u of this.navigator.iframes)Ue(u.contentDocument,"cut",this.restrictCopy),Ue(u.contentWindow,"cut",this.restrictCopy);Ue(window,"cut",this.restrictCopy),Ue(document,"cut",this.restrictCopy),Ue(this.navigator.mainElement,"keydown",this.restrictCopyKey),Ue(this.navigator.headerMenu,"keydown",this.restrictCopyKey);for(let u of this.navigator.iframes)Ue(u.contentDocument,"keydown",this.restrictCopyKey),Ue(u.contentWindow,"keydown",this.restrictCopyKey);Ue(window,"keydown",this.restrictCopyKey),Ue(document,"keydown",this.restrictCopyKey)}if((o=this.properties)!=null&&o.disablePrint){Ue(this.navigator.mainElement,"beforeprint",this.beforePrint.bind(this)),Ue(this.navigator.headerMenu,"beforeprint",this.beforePrint.bind(this));for(let u of this.navigator.iframes)Ue(u.contentDocument,"beforeprint",this.beforePrint),Ue(u.contentWindow,"beforeprint",this.beforePrint);Ue(window,"beforeprint",this.beforePrint),Ue(document,"beforeprint",this.beforePrint),Ue(this.navigator.mainElement,"afterprint",this.afterPrint.bind(this)),Ue(this.navigator.headerMenu,"afterprint",this.afterPrint.bind(this));for(let u of this.navigator.iframes)Ue(u.contentDocument,"afterprint",this.afterPrint.bind(this)),Ue(u.contentWindow,"afterprint",this.afterPrint.bind(this));Ue(window,"afterprint",this.afterPrint.bind(this)),Ue(document,"afterprint",this.afterPrint.bind(this))}if((s=this.properties)!=null&&s.disableContextMenu){Ue(this.navigator.mainElement,"contextmenu",this.disableContext),Ue(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let u of this.navigator.iframes)Ue(u.contentDocument,"contextmenu",this.disableContext),Ue(u.contentWindow,"contextmenu",this.disableContext);Ue(window,"contextmenu",this.disableContext),Ue(document,"contextmenu",this.disableContext)}(c=this.properties)!=null&&c.hideTargetUrl&&this.hideTargetUrls(!1),(f=this.properties)!=null&&f.disableDrag&&this.preventDrag(!1),Ue(this.wrapper,"scroll",this.handleScroll.bind(this))}observe(){var t;if((t=this.properties)!=null&&t.enableObfuscation){this.securityContainer.hasAttribute("style")&&(this.isHacked=!0),this.mutationObserver.disconnect();var e={attributes:!0,childList:!0,characterData:!0};this.mutationObserver.observe(this.securityContainer,e)}}async deactivate(){var e;(e=this.properties)!=null&&e.enableObfuscation&&(this.observe(),this.rects.forEach(t=>this.deactivateRect(t,this.securityContainer,this.isHacked)))}async activate(){var e;if((e=this.properties)!=null&&e.enableObfuscation){this.observe();for(let t of this.navigator.iframes)if(t.contentDocument){let n=lo(t.contentDocument,"body");this.rects=this.findRects(n),this.rects.forEach(i=>this.toggleRect(i,this.securityContainer,this.isHacked))}}}setupEvents(){var e,t,n,i,o,s,c,f,u,y,m,_,v,g,h;if((e=this.properties)!=null&&e.disableKeys){_e(this.navigator.mainElement,"keydown",this.disableSave),_e(this.navigator.headerMenu,"keydown",this.disableSave);for(let l of this.navigator.iframes)_e(l,"keydown",this.disableSave),_e(l.ownerDocument,"keydown",this.disableSave),_e(l.contentDocument,"keydown",this.disableSave),_e(l.contentWindow,"keydown",this.disableSave),_e((t=l.contentWindow)==null?void 0:t.document,"keydown",this.disableSave);_e(window,"keydown",this.disableSave),_e(document,"keydown",this.disableSave)}if((n=this.properties)!=null&&n.disableCopy){_e(this.navigator.mainElement,"copy",this.preventCopy),_e(this.navigator.headerMenu,"copy",this.preventCopy);for(let l of this.navigator.iframes)_e(l,"copy",this.preventCopy),_e(l.ownerDocument,"copy",this.preventCopy),_e(l.contentDocument,"copy",this.preventCopy),_e(l.contentWindow,"copy",this.preventCopy),_e((i=l.contentWindow)==null?void 0:i.document,"copy",this.preventCopy);_e(window,"copy",this.preventCopy),_e(document,"copy",this.preventCopy),_e(this.navigator.mainElement,"cut",this.preventCopy),_e(this.navigator.headerMenu,"cut",this.preventCopy);for(let l of this.navigator.iframes)_e(l,"cut",this.preventCopy),_e(l.ownerDocument,"cut",this.preventCopy),_e(l.contentDocument,"cut",this.preventCopy),_e(l.contentWindow,"cut",this.preventCopy),_e((o=l.contentWindow)==null?void 0:o.document,"cut",this.preventCopy);_e(window,"cut",this.preventCopy),_e(document,"cut",this.preventCopy),_e(this.navigator.mainElement,"keydown",this.preventCopyKey),_e(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let l of this.navigator.iframes)_e(l,"keydown",this.preventCopyKey),_e(l.ownerDocument,"keydown",this.preventCopyKey),_e(l.contentDocument,"keydown",this.preventCopyKey),_e(l.contentWindow,"keydown",this.preventCopyKey),_e((s=l.contentWindow)==null?void 0:s.document,"keydown",this.preventCopyKey);_e(window,"keydown",this.preventCopyKey),_e(document,"keydown",this.preventCopyKey)}else if((c=this.properties)!=null&&c.canCopy){_e(this.navigator.mainElement,"copy",this.restrictCopy.bind(this)),_e(this.navigator.headerMenu,"copy",this.restrictCopy.bind(this));for(let l of this.navigator.iframes)_e(l,"copy",this.restrictCopy),_e(l.ownerDocument,"copy",this.restrictCopy.bind(this)),_e(l.contentDocument,"copy",this.restrictCopy.bind(this)),_e(l.contentWindow,"copy",this.restrictCopy.bind(this)),_e((f=l.contentWindow)==null?void 0:f.document,"copy",this.restrictCopy.bind(this));_e(window,"copy",this.restrictCopy.bind(this)),_e(document,"copy",this.restrictCopy.bind(this)),_e(this.navigator.mainElement,"cut",this.restrictCopy.bind(this)),_e(this.navigator.headerMenu,"cut",this.restrictCopy.bind(this));for(let l of this.navigator.iframes)_e(l,"cut",this.restrictCopy.bind(this)),_e(l.ownerDocument,"cut",this.restrictCopy.bind(this)),_e(l.contentDocument,"cut",this.restrictCopy.bind(this)),_e(l.contentWindow,"cut",this.restrictCopy.bind(this)),_e((u=l.contentWindow)==null?void 0:u.document,"cut",this.restrictCopy.bind(this));_e(window,"cut",this.restrictCopy.bind(this)),_e(document,"cut",this.restrictCopy.bind(this)),_e(this.navigator.mainElement,"keydown",this.restrictCopyKey.bind(this)),_e(this.navigator.headerMenu,"keydown",this.restrictCopyKey.bind(this));for(let l of this.navigator.iframes)_e(l,"keydown",this.restrictCopyKey.bind(this)),_e(l.ownerDocument,"keydown",this.restrictCopyKey.bind(this)),_e(l.contentDocument,"keydown",this.restrictCopyKey.bind(this)),_e(l.contentWindow,"keydown",this.restrictCopyKey.bind(this)),_e((y=l.contentWindow)==null?void 0:y.document,"keydown",this.restrictCopyKey.bind(this));_e(window,"keydown",this.restrictCopyKey.bind(this)),_e(document,"keydown",this.restrictCopyKey.bind(this))}if((m=this.properties)!=null&&m.disablePrint){_e(this.navigator.mainElement,"beforeprint",this.beforePrint),_e(this.navigator.headerMenu,"beforeprint",this.beforePrint);for(let l of this.navigator.iframes)_e(l,"beforeprint",this.beforePrint.bind(this)),_e(l.ownerDocument,"beforeprint",this.beforePrint.bind(this)),_e(l.contentDocument,"beforeprint",this.beforePrint.bind(this)),_e(l.contentWindow,"beforeprint",this.beforePrint.bind(this)),_e((_=l.contentWindow)==null?void 0:_.document,"beforeprint",this.beforePrint.bind(this));_e(window,"beforeprint",this.beforePrint.bind(this)),_e(document,"beforeprint",this.beforePrint.bind(this)),_e(this.navigator.mainElement,"afterprint",this.afterPrint),_e(this.navigator.headerMenu,"afterprint",this.afterPrint);for(let l of this.navigator.iframes)_e(l,"afterprint",this.afterPrint.bind(this)),_e(l.ownerDocument,"afterprint",this.afterPrint.bind(this)),_e(l.contentDocument,"afterprint",this.afterPrint.bind(this)),_e(l.contentWindow,"afterprint",this.afterPrint.bind(this)),_e((v=l.contentWindow)==null?void 0:v.document,"afterprint",this.afterPrint.bind(this));_e(window,"afterprint",this.afterPrint.bind(this)),_e(document,"afterprint",this.afterPrint.bind(this))}if((g=this.properties)!=null&&g.disableContextMenu){_e(this.navigator.mainElement,"contextmenu",this.disableContext),_e(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let l of this.navigator.iframes)_e(l,"contextmenu",this.disableContext),_e(l.ownerDocument,"contextmenu",this.disableContext),_e(l.contentDocument,"contextmenu",this.disableContext),_e(l.contentWindow,"contextmenu",this.disableContext),_e((h=l.contentWindow)==null?void 0:h.document,"contextmenu",this.disableContext);_e(window,"contextmenu",this.disableContext),_e(document,"contextmenu",this.disableContext)}}initializeResource(){var e,t;(e=this.properties)!=null&&e.hideTargetUrl&&this.hideTargetUrls(!0),(t=this.properties)!=null&&t.disableDrag&&this.preventDrag(!0)}async initialize(){var e;if((e=this.properties)!=null&&e.enableObfuscation)return new Promise(async t=>{await document.fonts.ready;for(let n of this.navigator.iframes)if(n.contentDocument){let i=lo(n.contentDocument,"body");this.observe(),setTimeout(()=>{this.rects=this.findRects(i),this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),this.setupEvents(),this.hasEventListener||(this.hasEventListener=!0,_e(this.wrapper,"scroll",this.handleScroll.bind(this))),t()},10)}})}handleScroll(){this.rects.forEach(e=>this.toggleRect(e,this.securityContainer,this.isHacked))}async handleResize(){var e;if((e=this.properties)!=null&&e.enableObfuscation){let t=(0,Z1.default)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(n=>this.toggleRect(n,this.securityContainer,this.isHacked))},50);this.rects&&(this.observe(),t())}}disableContext(e){return e.preventDefault(),e.stopPropagation(),!1}disableSave(e){return(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?e.metaKey:e.ctrlKey&&(e.key==="s"||e.keyCode===83))?(e.preventDefault(),e.stopPropagation(),!1):!0}preventCopy(e){return Nr.default.log("copy action initiated"),e.clipboardData.setData("text/plain","copy not allowed"),e.stopPropagation(),e.preventDefault(),!1}preventCopyKey(e){return(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?e.metaKey:e.ctrlKey&&(e.key==="c"||e.keyCode===67))?(e.preventDefault(),e.stopPropagation(),!1):!0}restrictCopy(e){var n,i,o,s;if(this.citation)return;Nr.default.log("copy action initiated");let t=this.navigator.iframes[0].contentWindow;if(t){let f=function(y){let m={className:v=>Nn.indexOf(v)<0,idName:v=>Nn.indexOf(v)<0},_=c.navigator.iframes[0].contentDocument;if(_)return Ar(y,_,m)},c=this,u=Hi(t,f);if(u===void 0){let y=this.navigator.iframes[0].contentDocument;u=(i=(n=this.navigator.annotationModule)==null?void 0:n.annotator)==null?void 0:i.getTemporarySelectionInfo(y)}e.clipboardData.setData("text/plain",(s=u==null?void 0:u.cleanText)==null?void 0:s.substring(0,((o=this.properties)==null?void 0:o.charactersToCopy)??0))}else e.clipboardData.setData("text/plain","");return e.stopPropagation(),e.preventDefault(),!1}restrictCopyKey(e){var t,n,i,o;if(navigator.platform==="MacIntel"||navigator.platform.match("Mac")?e.metaKey:e.ctrlKey&&(e.key==="c"||e.keyCode===67)){let s=this.navigator.iframes[0].contentWindow;if(s){let f=function(y){let m={className:v=>Nn.indexOf(v)<0,idName:v=>Nn.indexOf(v)<0},_=c.navigator.iframes[0].contentDocument;if(_)return Ar(y,_,m)},c=this,u=Hi(s,f);if(u===void 0){let y=this.navigator.iframes[0].contentDocument;u=(n=(t=this.navigator.annotationModule)==null?void 0:t.annotator)==null?void 0:n.getTemporarySelectionInfo(y)}this.copyToClipboard((o=u==null?void 0:u.cleanText)==null?void 0:o.substring(0,((i=this.properties)==null?void 0:i.charactersToCopy)??0))}else this.copyToClipboard("");return e.stopPropagation(),e.preventDefault(),!1}return!0}copyToClipboard(e){var t;if(e=e==null?void 0:e.substring(0,((t=this.properties)==null?void 0:t.charactersToCopy)??0),window.clipboardData)window.clipboardData.setData("text/plain",e);else{let n=this.createElementForExecCommand(e);this.selectContent(n);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),document.execCommand("copy",!1)}catch{}document.body.removeChild(n)}}createElementForExecCommand(e){let t=document.createElement("div");return t.style.position="absolute",t.style.left="-10000px",t.style.top="-10000px",t.innerHTML=e,document.body.appendChild(t),t.contentEditable=!0,t}selectContent(e){let t=document.createRange();t.selectNodeContents(e);let n=window.getSelection();n==null||n.removeAllRanges(),n==null||n.addRange(t)}beforePrint(e){return Nr.default.log("before print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.display="none",this.navigator.mainElement.style.display="none"),e.stopPropagation(),e.preventDefault(),!1}afterPrint(e){return Nr.default.log("after print"),this.navigator&&this.navigator.headerMenu&&(this.navigator.headerMenu.style.removeProperty("display"),this.navigator.mainElement.style.removeProperty("display")),e.stopPropagation(),e.preventDefault(),!1}hideTargetUrls(e){var n;function t(i){i.preventDefault();let o=i.currentTarget.getAttribute("data-href-resolved"),s=document.createElement("a");s.setAttribute("href",o),s.click()}for(let i of this.navigator.iframes){let o=(n=i.contentDocument)==null?void 0:n.querySelectorAll("a");o==null||o.forEach(s=>{let c=s.getAttribute("data-href"),f=s.getAttribute("href");!c&&f&&(s.setAttribute("data-href",f),s.setAttribute("data-href-resolved",s.href))}),e?o==null||o.forEach(s=>{s.setAttribute("href",""),s.addEventListener("click",t)}):o==null||o.forEach(s=>{let c=s.getAttribute("data-href");c&&s.setAttribute("href",c),s.removeEventListener("click",t)})}}preventDrag(e){var i,o,s,c,f;let t="-webkit-user-drag: none; -khtml-user-drag: none; -moz-user-drag: none; -ms-user-drag: none; user-drag: none; -webkit-pointer-events: none; -khtml-pointer-events: none; -moz-pointer-events: none; -ms-pointer-events: none; pointer-events: none;",n=u=>{u.preventDefault()};for(let u of this.navigator.iframes){let y=((i=u.contentDocument)==null?void 0:i.body.getAttribute("style"))||"";e?((o=u.contentDocument)==null||o.body.addEventListener("dragstart",n),(s=u.contentDocument)==null||s.body.setAttribute("style",y+t)):((c=u.contentDocument)==null||c.body.removeEventListener("dragstart",n),(f=u.contentDocument)==null||f.body.setAttribute("style",y.replace(t,"")))}}recalculate(e=0){return new Promise(t=>{var n;if((n=this.properties)!=null&&n.enableObfuscation){let i=(0,Z1.default)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(o=>this.toggleRect(o,this.securityContainer,this.isHacked)),t(!0)},e);this.rects?(this.observe(),i()):t(!1)}else t(!1)})}calcRects(e){e!==void 0&&e.forEach(t=>{try{let{top:n,height:i,left:o,width:s}=this.measureTextNode(t.node);t.top=n,t.height=i,t.width=s,t.left=o}catch(n){Nr.default.log("error "+n),Nr.default.log(t),Nr.default.log(t.node),Nr.default.log("scrambledTextContent "+t.scrambledTextContent),Nr.default.log("textContent "+t.textContent),Nr.default.log("isObfuscated "+t.isObfuscated)}})}deactivateRect(e,t,n){this.isBeingHacked(t)||n?(e.node.textContent=e.scrambledTextContent,e.isObfuscated=!0):(e.node.textContent=e.textContent,e.isObfuscated=!1)}toggleRect(e,t,n){let i=this.isOutsideViewport(e),o=this.isBeingHacked(t);e.isObfuscated&&!i&&!o&&!n&&(e.node.textContent=e.textContent,e.isObfuscated=!1),!e.isObfuscated&&(i||o||n)&&(e.node.textContent=e.scrambledTextContent,e.isObfuscated=!0)}findRects(e){return this.findTextNodes(e).map(n=>{var y,m,_,v;let{top:i,height:o,left:s,width:c}=this.measureTextNode(n),f=n.parentElement&&((y=this.properties)!=null&&y.excludeNodes&&((m=this.properties)==null?void 0:m.excludeNodes.indexOf(n.parentElement.nodeName.toLowerCase()))>-1||((_=n.parentElement)==null?void 0:_.nodeName.toLowerCase())==="option"||((v=n.parentElement)==null?void 0:v.nodeName.toLowerCase())==="script")?n.textContent:this.obfuscateText(n.textContent??"");return{top:i,height:o,width:c,left:s,node:n,textContent:n.textContent??"",scrambledTextContent:f??"",isObfuscated:!1}})}obfuscateText(e){return this.scramble(e,!0)}measureTextNode(e){try{let t=document.createRange();t.selectNode(e);let n=t.getBoundingClientRect();return t.detach(),n}catch(t){Nr.default.log("measureTextNode "+t),Nr.default.log("measureTextNode "+e),Nr.default.log(e.textContent)}}isBeingHacked(e){return e.style.animation||e.style.transition||e.style.position||e.hasAttribute("style")?(Nr.default.log("content being hacked"),!0):!1}isOutsideViewport(e){let t=this.wrapper.scrollLeft,n=t+this.wrapper.clientWidth,i=e.left+e.width,o=e.top+e.height,s=this.wrapper.scrollTop-(e.node.parentElement?parseInt(getComputedStyle(e.node.parentElement).lineHeight.replace("px","")):10),c=s+this.wrapper.clientHeight+(e.node.parentElement?parseInt(getComputedStyle(e.node.parentElement).lineHeight.replace("px","")):10),f=o<s,u=e.top>c,y=i<t-window.innerWidth,m=e.left>n+window.innerWidth;return f||u||y||m}findTextNodes(e,t=[]){var i;let n=e.firstChild;for(;n;)n.nodeType===1&&this.findTextNodes(n,t),n.nodeType===3&&(i=n.textContent)!=null&&i.trim()&&t.push(n),n=n.nextSibling;return t}scramble(e,t=!1,n=!1){var i=e.split(" ");function o(s){for(var c=s.length,f,u;c>0;)u=Math.floor(Math.random()*c),c--,f=s[c],s[c]=s[u],s[u]=f;return s}return t&&(i=i.map(function(s){return s.includes("-")?s:o(s.split("")).join("")})),n?o(i).join(" "):i.join(" ")}};L();var bC=rt(pC());L();var ph=r=>r.replace(/\n/g," ").replace(/\s\s+/g," "),BU=r=>ph(r).trim(),mC=/[\\^$.*+?()[\]{}|]/g,DU=RegExp(mC.source);function gC(r){return r&&DU.test(r)?r.replace(mC,"\\$&"):r||""}var gh=0,FU=()=>()=>Number.isSafeInteger(++gh)?gh:gh=1,yC=()=>{gh=0},HU=FU(),UU=r=>e=>{try{return Ar(e,r,Jo)}catch(t){return console.error("uniqueCssSelector:",t),""}};async function es(r,e,t,n,i=!1){var v,g,h;if(!e)return[];let o=(v=e.body)==null?void 0:v.textContent;if(!o)return[];if(r=BU(r),!r.length)return[];let s=e.createNodeIterator(e.body,NodeFilter.SHOW_TEXT,{acceptNode:l=>NodeFilter.FILTER_ACCEPT}),c=new RegExp(gC(r).replace(/ /g,"\\s+"),"gim");i&&(c=new RegExp("\\b"+gC(r).replace(/ /g,"\\s+")+"\\b","gim"));let f=[],u=100,y=30,m=0,_;for(;_=c.exec(o);){let l=Math.max(0,_.index-u),p=Math.min(u,_.index),w=ph(o.substr(l,p));w=w.substr(w.length-y),l=c.lastIndex,p=Math.min(u,o.length-l);let A=ph(o.substr(l,p)).substr(0,y),C=new Range,b=_.index;for(;m<=b;){let P=s.nextNode();P&&P.nodeValue&&(m+=P.nodeValue.length)}let E=s.referenceNode.nodeValue?((g=s.referenceNode.nodeValue)==null?void 0:g.length)-(m-b):0;for(C.setStart(s.referenceNode,E),b=_.index+_[0].length;m<=b;){let P=s.nextNode(),N=P==null?void 0:P.nodeValue;N&&(m+=N.length)}E=s.referenceNode.nodeValue?((h=s.referenceNode.nodeValue)==null?void 0:h.length)-(m-b):0,C.setEnd(s.referenceNode,E),e.getCssSelector||(e.getCssSelector=UU(e));let k=go(C,e.getCssSelector);k&&f.push({textMatch:ph(_[0]),textBefore:w,textAfter:A,rangeInfo:k,href:t,title:n,uuid:HU().toString()})}return f}var vC=rt($t()),nu=class{constructor(e,t,n,i,o){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.headerMenu=o,this.publication=e,this.properties=t,this.api=i,this.highlighter=n}static async create(e){let t=new this(e.publication,e,e.highlighter,e.api,e.headerMenu);return await t.start(),t}async stop(){vC.default.log("Search module stop"),Ue(this.searchInput,"keypress",this.handleSearch.bind(this)),Ue(this.searchGo,"click",this.handleSearch.bind(this))}async start(){var t;if(this.headerMenu){this.searchInput=Ne(this.headerMenu,"#searchInput"),_e(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=Ne(this.headerMenu,"#searchGo"),_e(this.searchGo,"click",this.handleSearch.bind(this));var e=Ne(this.headerMenu,"#menu-button-search");e&&((t=e.parentElement)==null||t.style.removeProperty("display"))}setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("search"):this.navigator.showLayer("search")},10)}async handleSearch(e){(e.key==="Enter"||e.type==="click")&&(await this.handleSearchChapter(),await this.handleSearchBook())}async handleSearchChapter(e){var t=this,n=this.searchInput.value;let i=this.navigator.currentChapterLink.href,o=this.publication.getSpineItem(i);if(this.headerMenu)var s=Ne(document,"#searchResultChapter");t.currentChapterSearchResult=[],t.currentSearchHighlights=[];var c=[];await this.searchAndPaintChapter(n,e,async u=>{var y;c=u,f(1),this.navigator.rights.enableContentProtection&&((y=this.navigator.contentProtectionModule)==null||y.recalculate(200))});async function f(u){s.innerHTML="";var y;if(y=t.paginate(c,u,10),y.total===0){let m=document.createElement("a");m.className="collection-item",m.innerHTML="nothing found",s.appendChild(m)}else{for(let h=0;h<y.data.length;h++){let l=document.createElement("a"),p=y.data[h];l.className="collection-item",l.href=(o==null?void 0:o.Href)??"",l.innerHTML="..."+p.textBefore+"<mark>"+p.textMatch+"</mark>"+p.textAfter+"...",_e(l,"click",w=>{w.preventDefault(),w.stopPropagation(),t.jumpToMark(h+u*10-10)}),s.appendChild(l)}let m=document.createElement("div");m.style.textAlign="center",m.style.marginTop="10px";let _=document.createElement("ul");_.className="pagination";let v=document.createElement("li");if(v.className="disabled",v.innerHTML='<a href="#!"> < </a>',y.pre_page!==void 0){let h=y.pre_page;v.className="waves-effect",_e(v,"click",l=>{l.preventDefault(),l.stopPropagation(),f(h)})}_.appendChild(v);for(let h=1;h<=y.total_pages;h++){let l,p=document.createElement("li");p.className="waves-effect",h===y.page&&(p.className="active",l=p),p.innerHTML='<a href="#!">'+h+"</a>",_e(p,"click",w=>{w.preventDefault(),w.stopPropagation(),l&&(l.className="waves-effect"),p.className="active",l=p,f(h)}),_.appendChild(p)}let g=document.createElement("li");if(g.className="disabled",g.innerHTML='<a href="#!"> > </a>',y.next_page!==void 0){let h=y.next_page;g.className="waves-effect",_e(g,"click",l=>{l.preventDefault(),l.stopPropagation(),f(h)})}_.appendChild(g),m.appendChild(_),s.appendChild(m)}}}async searchAndPaintChapter(e,t=0,n){var f,u;this.navigator.rights.enableContentProtection&&((f=this.navigator.contentProtectionModule)==null||f.deactivate());let i=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),o=this.publication.getTOCItem(i);o===null&&(o=this.publication.readingOrder[this.navigator.currentResource()??0]);let s=[];(u=this.highlighter)==null||u.destroyHighlights(1),this.navigator.rights.enableSearch&&this.drawSearch();let c=0;if(o){let y=this.navigator.iframes[0].contentDocument;y&&o&&es(e,y,o.Href,o.Title).then(m=>{m.forEach(_=>{let v={rangeInfo:_.rangeInfo};setTimeout(()=>{var h,l;let g;c===t?(g=this.createSearchHighlight(v,(h=this.properties)==null?void 0:h.current),this.jumpToMark(t)):g=this.createSearchHighlight(v,(l=this.properties)==null?void 0:l.color),_.highlight=g,s.push(_),this.currentChapterSearchResult.push(_),this.currentSearchHighlights.push(g),c++},500)}),setTimeout(()=>{n(s)},500)})}}createSearchHighlight(e,t){var o;try{var n=t;Jt.isHexColor(n)&&(n=Jt.hexToRgbChannels(n));let s=`${e.rangeInfo.startContainerElementCssSelector}${e.rangeInfo.startContainerChildTextNodeIndex}${e.rangeInfo.startOffset}${e.rangeInfo.endContainerElementCssSelector}${e.rangeInfo.endContainerChildTextNodeIndex}${e.rangeInfo.endOffset}`,f="R2_SEARCH_"+bC.SHA256.hash(s);var i=!1;let u={color:n||Rs,id:f,pointerInteraction:i,selectionInfo:e,marker:0,type:1},y=(o=this.highlighter)==null?void 0:o.createHighlightDom(this.navigator.iframes[0].contentWindow,u);return u.position=parseInt((y!=null&&y.hasChildNodes()?y.childNodes[0]:y).style.top.replace("px","")),u}catch(s){throw"Can't create highlight: "+s}}clearSearch(){var e;this.currentChapterSearchResult=[],this.currentSearchHighlights=[],(e=this.highlighter)==null||e.destroyHighlights(1)}async search(e,t){return this.currentChapterSearchResult=[],this.currentSearchHighlights=[],this.bookSearchResult=[],yC(),await this.searchAndPaintChapter(e,0,async()=>{var n;this.navigator.rights.enableContentProtection&&((n=this.navigator.contentProtectionModule)==null||n.recalculate(200))}),t?(await this.searchBook(e),await this.searchChapter(e)):(await this.searchChapter(e),await this.searchBook(e))}async goToSearchID(e,t,n){var i=t,o;let s=this.navigator.currentChapterLink.href;var c=this.publication.getAbsoluteHref(e);let f=this.bookSearchResult.filter(u=>u.href===e);if(n?(o=this.currentChapterSearchResult.filter(u=>u.uuid===t)[0],i=this.currentChapterSearchResult.findIndex(u=>u.uuid===t)):(o=f.filter(u=>u.uuid===t)[0],i=f.findIndex(u=>u.uuid===t)),o!==void 0)if(s===c)this.jumpToMark(i);else{let y={href:c,locations:{progression:0},title:"title"};this.navigator.navigate(y),setTimeout(()=>{this.searchAndPaintChapter(o.textMatch,i,async()=>{var m;this.navigator.rights.enableContentProtection&&((m=this.navigator.contentProtectionModule)==null||m.recalculate(200))})},300)}}async goToSearchIndex(e,t,n){var i=t,o;let s=this.navigator.currentChapterLink.href;var c=this.publication.getAbsoluteHref(e);let f=this.bookSearchResult.filter(u=>u.href===e);if(n?o=this.currentChapterSearchResult[i]:o=f[i],o!==void 0)if(s===c)this.jumpToMark(i);else{let y={href:c,locations:{progression:0},title:"title"};this.navigator.navigate(y),setTimeout(()=>{this.searchAndPaintChapter(o.textMatch,i,async()=>{var m;this.navigator.rights.enableContentProtection&&((m=this.navigator.contentProtectionModule)==null||m.recalculate(200))})},300)}}async handleSearchBook(){var e=this,t=this.searchInput.value;if(e.headerMenu)var n=Ne(document,"#searchResultBook");i(1);async function i(s){n.innerHTML="";var c,f=await e.searchBook(t);if(c=e.paginate(f,s,10),c.total===0){let u=document.createElement("a");u.className="collection-item",u.innerHTML="nothing found",n.appendChild(u)}else{o(c.data,g=>g.href).forEach(g=>{let h=document.createElement("div");if(h.style.marginBottom="10px",g[0].title){let l=document.createElement("span");l.className="collection-item",l.style.display="block",l.innerHTML=g[0].title,h.appendChild(l)}n.appendChild(h),g.forEach(l=>{let p=document.createElement("a");p.className="collection-item";var w=e.publication.getAbsoluteHref(l.href);p.innerHTML="..."+l.textBefore+"<mark>"+l.textMatch+"</mark>"+l.textAfter+"...",_e(p,"click",A=>{A.preventDefault(),A.stopPropagation();let b=f.filter(k=>k.href===l.href).findIndex(k=>k===l);if(e.navigator.currentChapterLink.href===w)e.jumpToMark(b);else{let P={href:w,locations:{progression:0},title:"title"};e.navigator.navigate(P),setTimeout(()=>{e.handleSearchChapter(b)},300)}}),h.appendChild(p)})});let y=document.createElement("div");y.style.textAlign="center",y.style.marginTop="10px";let m=document.createElement("ul");m.className="pagination";let _=document.createElement("li");if(_.className="disabled",_.innerHTML='<a href="#!"> < </a>',c.pre_page!=null){let g=c.pre_page;_.className="waves-effect",_e(_,"click",h=>{h.preventDefault(),h.stopPropagation(),i(g)})}m.appendChild(_);for(let g=1;g<=c.total_pages;g++){let h,l=document.createElement("li");l.className="waves-effect",g===c.page&&(l.className="active",h=l),l.innerHTML='<a href="#!">'+g+"</a>",_e(l,"click",p=>{p.preventDefault(),p.stopPropagation(),h&&(h.className="waves-effect"),l.className="active",h=l,i(g)}),m.appendChild(l)}let v=document.createElement("li");if(v.className="disabled",v.innerHTML='<a href="#!"> > </a>',c.next_page!=null){let g=c.next_page;v.className="waves-effect",_e(v,"click",h=>{h.preventDefault(),h.stopPropagation(),i(g)})}m.appendChild(v),y.appendChild(m),n.appendChild(y)}}function o(s,c){let f=new Map;return s.forEach(u=>{let y=c(u),m=f.get(y);m?m.push(u):f.set(y,[u])}),Array.from(f.values())}}async searchBook(e){var n,i;this.bookSearchResult=[];let t=[];for(let o=0;o<this.publication.readingOrder.length;o++){let s=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[o].Href:""),c=this.publication.getTOCItem(s);if(c===void 0&&this.publication.readingOrder&&(c=this.publication.readingOrder[o]),c){let f=this.publication.getAbsoluteHref(c.Href);(n=this.navigator.api)!=null&&n.getContent?await((i=this.navigator.api)==null?void 0:i.getContent(f).then(u=>{let m=new DOMParser().parseFromString(u,"application/xhtml+xml");c&&es(e,m,c.Href,c.Title).then(_=>{_.forEach(v=>{t.push(v),this.bookSearchResult.push(v)})})})):await fetch(f,this.navigator.requestConfig).then(u=>u.text()).then(async u=>{var _;let m=new DOMParser().parseFromString((_=this.navigator.requestConfig)!=null&&_.encoded?this.decodeBase64(u):u,"application/xhtml+xml");c&&es(e,m,c.Href,c.Title).then(v=>{v.forEach(g=>{t.push(g),this.bookSearchResult.push(g)})})})}if(o===this.publication.readingOrder.length-1)return t}}decodeBase64(e){let t=atob(e),n=t.length,i=new Uint8Array(n);for(let s=0;s<n;s++)i[s]=t.charCodeAt(s);return new TextDecoder().decode(i)}async searchChapter(e){var o,s;let t=[],n=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),i=this.publication.getTOCItem(n);if(i===null&&(i=this.publication.readingOrder[this.navigator.currentResource()??0]),i){let c=this.publication.getAbsoluteHref(i.Href);(o=this.navigator.api)!=null&&o.getContent?await((s=this.navigator.api)==null?void 0:s.getContent(c).then(f=>{let y=new DOMParser().parseFromString(f,"application/xhtml+xml");i&&es(e,y,i.Href,i.Title).then(m=>{m.forEach(_=>{t.push(_)})})})):await fetch(c,this.navigator.requestConfig).then(f=>f.text()).then(async f=>{var m;let y=new DOMParser().parseFromString((m=this.navigator.requestConfig)!=null&&m.encoded?this.decodeBase64(f):f,"application/xhtml+xml");i&&es(e,y,i.Href,i.Title).then(_=>{_.forEach(v=>{t.push(v)})})})}return t}drawSearch(){setTimeout(()=>{this.currentSearchHighlights=[],this.currentChapterSearchResult.forEach(e=>{var n,i;let t={rangeInfo:e.rangeInfo};if((n=this.properties)!=null&&n.color){let o=this.createSearchHighlight(t,(i=this.properties)==null?void 0:i.color);e.highlight=o,this.currentSearchHighlights.push(o)}})},100)}async handleResize(){var e;await((e=this.highlighter)==null?void 0:e.destroyHighlights(1)),this.drawSearch()}jumpToMark(e){setTimeout(()=>{var i,o,s;if(this.currentChapterSearchResult.length){var t=this.currentChapterSearchResult[e];this.currentSearchHighlights.forEach(c=>{var u;var f=(u=this.properties)==null?void 0:u.color;Jt.isHexColor(f)&&(f=Jt.hexToRgbChannels(f)),c.color=f});var n=(i=this.properties)==null?void 0:i.current;Jt.isHexColor(n)&&(n=Jt.hexToRgbChannels(n)),t.highlight.color=n,(o=this.highlighter)==null||o.setAndResetSearchHighlight(t.highlight,this.currentSearchHighlights),(s=this.navigator.view)==null||s.goToCssSelector(t.rangeInfo.startContainerElementCssSelector),this.navigator.updatePositionInfo()}},200)}paginate(e,t,n){let i=t||1,o=n||10,s=(i-1)*o,c=e.slice(s).slice(0,o),f=Math.ceil(e.length/o);return{page:i,per_page:o,pre_page:i-1?i-1:void 0,next_page:f>i?i+1:void 0,total:e.length,total_pages:f,data:c}}};L();var gn=rt($t()),sr=class sr{};sr.COLOR_REF="color",sr.AUTO_SCROLL_REF="autoscroll",sr.RATE_REF="rate",sr.PITCH_REF="pitch",sr.VOLUME_REF="volume",sr.VOICE_REF="voice",sr.COLOR_KEY="tts-"+sr.COLOR_REF,sr.AUTO_SCROLL_KEY="tts-"+sr.AUTO_SCROLL_REF,sr.RATE_KEY="tts-"+sr.RATE_REF,sr.PITCH_KEY="tts-"+sr.PITCH_REF,sr.VOLUME_KEY="tts-"+sr.VOLUME_REF,sr.VOICE_KEY="tts-"+sr.VOICE_REF;var st=sr,mh=class{constructor(e,t,n){this.TTSSETTINGS="ttsSetting";this.color="orange";this.autoScroll=!0;this.rate=1;this.pitch=1;this.volume=1;this.voice={usePublication:!0};this.settingsChangeCallback=()=>{};this.restartCallback=()=>{};this.store=e,this.api=t,this.headerMenu=n,this.initialise()}static create(e){let t=new this(e.store,e.api,e.headerMenu);if(e.initialTTSSettings){let n=e.initialTTSSettings;n!=null&&n.rate&&(t.rate=n.rate,gn.default.log(t.rate)),n!=null&&n.pitch&&(t.pitch=n.pitch,gn.default.log(t.pitch)),n!=null&&n.volume&&(t.volume=n.volume,gn.default.log(t.volume)),n!=null&&n.color&&(t.color=n.color,gn.default.log(t.color)),n!=null&&n.autoScroll&&(t.autoScroll=n.autoScroll,gn.default.log(t.autoScroll)),n!=null&&n.voice&&(t.voice=n.voice,gn.default.log(t.voice))}return t.initializeSelections(),t}stop(){gn.default.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty(st.AUTO_SCROLL_KEY)!=null?this.getProperty(st.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty(st.RATE_KEY)!=null?this.getProperty(st.RATE_KEY).value:this.rate,this.pitch=this.getProperty(st.PITCH_KEY)!=null?this.getProperty(st.PITCH_KEY).value:this.pitch,this.volume=this.getProperty(st.VOLUME_KEY)!=null?this.getProperty(st.VOLUME_KEY).value:this.volume,this.color=this.getProperty(st.COLOR_KEY)!=null?this.getProperty(st.COLOR_KEY).value:this.color,this.voice=this.getProperty(st.VOICE_REF)!=null?this.getProperty(st.VOICE_REF).value:this.voice,this.userProperties=this.getTTSSettings()}reset(){this.color="orange",this.autoScroll=!0,this.rate=1,this.pitch=1,this.volume=1,this.voice={usePublication:!0},this.userProperties=this.getTTSSettings()}initializeSelections(){this.headerMenu&&(this.settingsView=Ne(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(e){this.headerMenu&&(this.speechRate=Ne(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=Ne(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=Ne(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=Ne(this.headerMenu,"#autoScroll")),this.speechRate&&(this.speechRate.value=this.rate.toString()),this.speechPitch&&(this.speechPitch.value=this.pitch.toString()),this.speechVolume&&(this.speechVolume.value=this.volume.toString()),this.speechAutoScroll&&(this.speechAutoScroll.checked=this.autoScroll),_e(Ne(e,"ul"),"click",t=>{t.stopPropagation()})}onSettingsChange(e){this.settingsChangeCallback=e}onRestart(e){this.restartCallback=e}storeProperty(e){this.updateUserSettings(),this.saveProperty(e)}updateUserSettings(){var t,n,i,o,s,c,f,u;var e={rate:(t=this.userProperties.getByRef(st.RATE_REF))==null?void 0:t.value,pitch:(n=this.userProperties.getByRef(st.PITCH_REF))==null?void 0:n.value,volume:(i=this.userProperties.getByRef(st.VOLUME_REF))==null?void 0:i.value,voice:(o=this.userProperties.getByRef(st.VOLUME_REF))==null?void 0:o.value,color:(s=this.userProperties.getByRef(st.COLOR_REF))==null?void 0:s.value,autoScroll:(c=this.userProperties.getByRef(st.AUTO_SCROLL_REF))==null?void 0:c.value};this.applyTTSSettings(e),(f=this.api)!=null&&f.updateSettings&&((u=this.api)==null||u.updateSettings(e).then(async y=>{gn.default.log("api updated tts settings",y)}))}getTTSSettings(){var e=new ki;return e.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,st.AUTO_SCROLL_REF,st.AUTO_SCROLL_KEY),e.addIncremental(this.rate,.1,10,.1,"",st.RATE_REF,st.RATE_KEY),e.addIncremental(this.pitch,.1,2,.1,"",st.PITCH_REF,st.PITCH_KEY),e.addIncremental(this.volume,.1,1,.1,"",st.VOLUME_REF,st.VOLUME_KEY),e.addStringable(this.color,st.COLOR_REF,st.COLOR_KEY),e.addJSONable(JSON.stringify(this.voice),st.VOICE_REF,st.VOICE_KEY),e}saveProperty(e){let t=this.store.get(this.TTSSETTINGS);if(t){let n=JSON.parse(t);n=n.filter(i=>i.name!==e.name),n.push(e),this.store.set(this.TTSSETTINGS,JSON.stringify(n))}else{let n=[];n.push(e),this.store.set(this.TTSSETTINGS,JSON.stringify(n))}return e}getProperty(e){let t=this.store.get(this.TTSSETTINGS);if(t){let n=JSON.parse(t);return n=n.filter(i=>i.name===e),n.length===0?void 0:n[0]}}resetTTSSettings(){this.store.remove(this.TTSSETTINGS),this.reset(),this.settingsChangeCallback(),this.restartCallback()}applyTTSSettings(e){if(e.rate){gn.default.log("rate "+this.rate),this.rate=e.rate;let t=this.userProperties.getByRef(st.RATE_REF);t&&(t.value=this.rate,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.pitch){gn.default.log("pitch "+this.pitch),this.pitch=e.pitch;let t=this.userProperties.getByRef(st.PITCH_REF);t&&(t.value=this.pitch,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.volume){gn.default.log("volume "+this.volume),this.volume=e.volume;let t=this.userProperties.getByRef(st.VOLUME_REF);t&&(t.value=this.volume,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.color){this.color=e.color;let t=this.userProperties.getByRef(st.COLOR_REF);t&&(t.value=this.color,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoScroll!==void 0){gn.default.log("autoScroll "+this.autoScroll),this.autoScroll=e.autoScroll;let t=this.userProperties.getByRef(st.AUTO_SCROLL_REF);t&&(t.value=this.autoScroll,this.saveProperty(t)),this.settingsChangeCallback()}if(e.voice){gn.default.log("voice "+this.voice),this.voice=e.voice;let t=this.userProperties.getByRef(st.VOICE_REF);t&&(t.value=this.voice,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}}applyPreferredVoice(e){var t=e.indexOf(":")!==-1?e.slice(0,e.indexOf(":")):void 0,n=e.indexOf(":")!==-1?e.slice(e.indexOf(":")+1):e;t!==void 0&&n!==void 0?this.applyTTSSettings({voice:{usePublication:!0,name:t,lang:n}}):n!==void 0&&t===void 0&&this.applyTTSSettings({voice:{usePublication:!0,lang:n}})}increase(e){if(e==="rate"){this.userProperties.getByRef(st.RATE_REF).increment();let t=this.userProperties.getByRef(st.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="pitch"){this.userProperties.getByRef(st.PITCH_REF).increment();let t=this.userProperties.getByRef(st.PITCH_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="volume"){this.userProperties.getByRef(st.VOLUME_REF).increment();let t=this.userProperties.getByRef(st.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}}decrease(e){if(e==="rate"){this.userProperties.getByRef(st.RATE_REF).decrement();let t=this.userProperties.getByRef(st.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="pitch"){this.userProperties.getByRef(st.PITCH_REF).decrement();let t=this.userProperties.getByRef(st.PITCH_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="volume"){this.userProperties.getByRef(st.VOLUME_REF).decrement();let t=this.userProperties.getByRef(st.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}}};L();L();var yh=`${pi.loading}`,_C=`
|
|
83
83
|
<span>
|
|
84
84
|
${pi.error}
|
|
85
85
|
</span>
|