@d-i-t-a/reader 2.4.8 → 2.4.9
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 +54 -34
- package/dist/esm/index.js.map +2 -2
- package/dist/reader.js +2 -2
- package/dist/reader.js.map +2 -2
- package/dist/types/utils/EventHandler.d.ts +3 -0
- 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 Ce(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}},(n,e,t)=>{var r=t(3)},(n,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 n,t,r,i,o,s,l,f,u,em,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 c=Object.create(null),p=null,w=null;for(let E in h){let b=h[E];switch(E){case"url":if(typeof window<"u")try{c[E]=new URL(b,window.location).href;continue}catch(C){(0,_util.warn)(`Cannot create valid URL: "${C}".`)}else if(typeof b=="string"||b instanceof URL){c[E]=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)c[E]=new Uint8Array(b);else{if(b instanceof Uint8Array)break;if(typeof b=="string")c[E]=(0,_util.stringToBytes)(b);else if(typeof b=="object"&&b!==null&&!isNaN(b.length))c[E]=new Uint8Array(b);else if((0,_util.isArrayBuffer)(b))c[E]=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}c[E]=b}if(c.CMapReaderFactory=c.CMapReaderFactory||DefaultCMapReaderFactory,c.StandardFontDataFactory=c.StandardFontDataFactory||DefaultStandardFontDataFactory,c.ignoreErrors=c.stopAtErrors!==!0,c.fontExtraProperties=c.fontExtraProperties===!0,c.pdfBug=c.pdfBug===!0,c.enableXfa=c.enableXfa===!0,(!Number.isInteger(c.rangeChunkSize)||c.rangeChunkSize<1)&&(c.rangeChunkSize=DEFAULT_RANGE_CHUNK_SIZE),(typeof c.docBaseUrl!="string"||(0,_display_utils.isDataScheme)(c.docBaseUrl))&&(c.docBaseUrl=null),(!Number.isInteger(c.maxImageSize)||c.maxImageSize<-1)&&(c.maxImageSize=-1),typeof c.cMapUrl!="string"&&(c.cMapUrl=null),typeof c.standardFontDataUrl!="string"&&(c.standardFontDataUrl=null),typeof c.useWorkerFetch!="boolean"&&(c.useWorkerFetch=c.CMapReaderFactory===_display_utils.DOMCMapReaderFactory&&c.StandardFontDataFactory===_display_utils.DOMStandardFontDataFactory),typeof c.isEvalSupported!="boolean"&&(c.isEvalSupported=!0),typeof c.disableFontFace!="boolean"&&(c.disableFontFace=_is_node.isNodeJS),typeof c.useSystemFonts!="boolean"&&(c.useSystemFonts=!_is_node.isNodeJS&&!c.disableFontFace),(typeof c.ownerDocument!="object"||c.ownerDocument===null)&&(c.ownerDocument=globalThis.document),typeof c.disableRange!="boolean"&&(c.disableRange=!1),typeof c.disableStream!="boolean"&&(c.disableStream=!1),typeof c.disableAutoFetch!="boolean"&&(c.disableAutoFetch=!1),(0,_util.setVerbosityLevel)(c.verbosity),!w){let E={verbosity:c.verbosity,port:_worker_options.GlobalWorkerOptions.workerPort};w=E.port?PDFWorker.fromPort(E):new PDFWorker(E),g._worker=w}let A=g.docId;return w.promise.then(function(){if(g.destroyed)throw new Error("Loading aborted");let E=_fetchDocument(w,c,p,A),b=new Promise(function(C){let k;p?k=new _transport_stream.PDFDataTransportStream({length:c.length,initialData:c.initialData,progressiveDone:c.progressiveDone,contentDispositionFilename:c.contentDispositionFilename,disableRange:c.disableRange,disableStream:c.disableStream},p):c.data||(k=createPDFNetworkStream({url:c.url,length:c.length,httpHeaders:c.httpHeaders,withCredentials:c.withCredentials,rangeChunkSize:c.rangeChunkSize,disableRange:c.disableRange,disableStream:c.disableStream})),C(k)});return Promise.all([E,b]).then(function([C,k]){if(g.destroyed)throw new Error("Loading aborted");let R=new _message_handler.MessageHandler(A,C,w.port),B=new WorkerTransport(R,g,k,c);g._transport=B,R.send("Ready",null)})}).catch(g._capability.reject),g}async function _fetchDocument(v,g,h,c){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:c,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${Mb(e,n)._++}`,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)}};n=new WeakMap,Tr(e,n,0);let PDFDocumentLoadingTask=e;exports.PDFDocumentLoadingTask=PDFDocumentLoadingTask;class PDFDataRangeTransport{constructor(g,h,c=!1,p=null){this.length=g,this.initialData=h,this.progressiveDone=c,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 c of this._rangeListeners)c(g,h)}onDataProgress(g,h){this._readyCapability.promise.then(()=>{for(let c of this._progressListeners)c(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,c,p,w=!1){this._pageIndex=g,this._pageInfo=h,this._ownerDocument=p,this._transport=c,this._stats=w?new _display_utils.StatTimer:null,this._pdfBug=w,this.commonObjs=c.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:c=0,offsetY:p=0,dontFlip:w=!1}={}){return new _display_utils.PageViewport({viewBox:this.view,scale:g,rotation:h,offsetX:c,offsetY:p,dontFlip:w})}getAnnotations({intent:g="display"}={}){let h=this._transport.getRenderingIntent(g),c=this._annotationPromises.get(h.cacheKey);return c||(c=this._transport.getAnnotations(this._pageIndex,h.renderingIntent),this._annotationPromises.set(h.cacheKey,c),c=c.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})),c}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:c="display",annotationMode:p=_util.AnnotationMode.ENABLE,transform:w=null,imageLayer:A=null,canvasFactory:E=null,background:b=null,optionalContentConfigPromise:C=null,annotationCanvasMap:k=null,pageColors:R=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 B=this._transport.getRenderingIntent(c,p);this.pendingCleanup=!1,C||(C=this._transport.getOptionalContentConfig());let I=this._intentStates.get(B.cacheKey);I||(I=Object.create(null),this._intentStates.set(B.cacheKey,I)),I.streamReaderCancelTimeout&&(clearTimeout(I.streamReaderCancelTimeout),I.streamReaderCancelTimeout=null);let D=E||new DefaultCanvasFactory({ownerDocument:this._ownerDocument}),F=!!(B.renderingIntent&_util.RenderingIntentFlag.PRINT);I.displayReadyCapability||(I.displayReadyCapability=(0,_util.createPromiseCapability)(),I.operatorList={fnArray:[],argsArray:[],lastChunk:!1},this._stats&&this._stats.time("Page Request"),this._pumpOperatorList(B));let z=Q=>{I.renderTasks.delete(q),(this.cleanupAfterRender||F)&&(this.pendingCleanup=!0),this._tryCleanup(),Q?(q.capability.reject(Q),this._abortOperatorList({intentState:I,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:z,params:{canvasContext:g,viewport:h,transform:w,imageLayer:A,background:b},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:k,operatorList:I.operatorList,pageIndex:this._pageIndex,canvasFactory:D,useRequestAnimationFrame:!F,pdfBug:this._pdfBug,pageColors:R});(I.renderTasks||=new Set).add(q);let G=q.task;return Promise.all([I.displayReadyCapability.promise,C]).then(([Q,se])=>{if(this.pendingCleanup){z();return}this._stats&&this._stats.time("Rendering"),q.initializeGraphics({transparency:Q,optionalContentConfig:se}),q.operatorListChanged()}).catch(z),G}getOperatorList({intent:g="display",annotationMode:h=_util.AnnotationMode.ENABLE}={}){function c(){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=c,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(c=>_xfa_text.XfaText.textContent(c));let h=this.streamTextContent(g);return new Promise(function(c,p){function w(){A.read().then(function({value:b,done:C}){if(C){c(E);return}Object.assign(E.styles,b.styles),E.items.push(...b.items),w()},p)}let A=h.getReader(),E={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 c of h.renderTasks)g.push(c.completed),c.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:c}of this._intentStates.values())if(h.size>0||!c.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 c=this._intentStates.get(h);c&&(this._stats&&this._stats.timeEnd("Page Request"),c.displayReadyCapability&&c.displayReadyCapability.resolve(g))}_renderPageChunk(g,h){for(let c=0,p=g.length;c<p;c++)h.operatorList.fnArray.push(g.fnArray[c]),h.operatorList.argsArray.push(g.argsArray[c]);h.operatorList.lastChunk=g.lastChunk;for(let c of h.renderTasks)c.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:E,done:b})=>{if(b){w.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(E,w),A())},E=>{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(E);else if(w.opListReadCapability)w.opListReadCapability.reject(E);else throw E}})};A()}_abortOperatorList({intentState:g,reason:h,force:c=!1}){if(g.streamReader){if(!c){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 c={data:structuredClone(g,h)};this._deferred.then(()=>{for(let p of this._listeners)p.call(this,c)})}addEventListener(g,h){this._listeners.push(h)}removeEventListener(g,h){let c=this._listeners.indexOf(h);this._listeners.splice(c,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 Tu=="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 c=new URL(g,h);return h.origin===c.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,r).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,r).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),c=()=>{g.removeEventListener("error",p),h.destroy(),g.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},p=()=>{this._webWorker||c()};g.addEventListener("error",p),h.on("test",A=>{if(g.removeEventListener("error",p),this.destroyed){c();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){c();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++}`,c=new _message_handler.MessageHandler(h+"_worker",h,g);v.setup(c,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,r).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,r).has(v.port)?Lt(this,r).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 Tu=="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())}};r=new WeakMap,Tr(_PDFWorker,r,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,c,p){Tr(this,i,null);Tr(this,o,new Map);Tr(this,s,new Map);Tr(this,l,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=c,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,c=!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 c&&(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 c of Lt(this,o).values())g.push(c._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(),to(this,l,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",(c,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",c=>{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=E=>{var b;(b=h.onProgress)==null||b.call(h,{loaded:E.loaded,total:E.total})}),p.resolve({isStreamingSupported:w.isStreamingSupported,isRangeSupported:w.isRangeSupported,contentLength:w.contentLength})},p.reject),p.promise}),g.on("GetRangeReader",(c,p)=>{(0,_util.assert)(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");let w=this._networkStream.getRangeReader(c.begin,c.end);if(!w){p.close();return}p.onPull=()=>{w.read().then(function({value:A,done:E}){if(E){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(E=>{if(!this.destroyed)throw E})}}),g.on("GetDoc",({pdfInfo:c})=>{this._numPages=c.numPages,this._htmlForXfa=c.htmlForXfa,delete c.htmlForXfa,h._capability.resolve(new PDFDocumentProxy(c,this))}),g.on("DocException",function(c){let p;switch(c.name){case"PasswordException":p=new _util.PasswordException(c.message,c.code);break;case"InvalidPDFException":p=new _util.InvalidPDFException(c.message);break;case"MissingPDFException":p=new _util.MissingPDFException(c.message);break;case"UnexpectedResponseException":p=new _util.UnexpectedResponseException(c.message,c.status);break;case"UnknownErrorException":p=new _util.UnknownErrorException(c.message,c.details);break;default:(0,_util.unreachable)("DocException - expected a valid Error.")}h._capability.reject(p)}),g.on("PasswordRequest",c=>{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,c.code)}catch(w){this._passwordCapability.reject(w)}}else this._passwordCapability.reject(new _util.PasswordException(c.message,c.code));return this._passwordCapability.promise}),g.on("DataLoaded",c=>{var p;(p=h.onProgress)==null||p.call(h,{loaded:c.length,total:c.length}),this.downloadInfoCapability.resolve(c)}),g.on("StartRenderPage",c=>{if(this.destroyed)return;Lt(this,o).get(c.pageIndex)._startRenderPage(c.transparency,c.cacheKey)}),g.on("commonobj",([c,p,w])=>{var A;if(!this.destroyed&&!this.commonObjs.has(c))switch(p){case"Font":let E=this._params;if("error"in w){let k=w.error;(0,_util.warn)(`Error during font loading: ${k}`),this.commonObjs.resolve(c,k);break}let b=null;E.pdfBug&&((A=globalThis.FontInspector)!=null&&A.enabled)&&(b={registerFont(k,R){globalThis.FontInspector.fontAdded(k,R)}});let C=new _font_loader.FontFaceObject(w,{isEvalSupported:E.isEvalSupported,disableFontFace:E.disableFontFace,ignoreErrors:E.ignoreErrors,onUnsupportedFeature:this._onUnsupportedFeature.bind(this),fontRegistry:b});this.fontLoader.bind(C).catch(k=>g.sendWithPromise("FontFallback",{id:c})).finally(()=>{!E.fontExtraProperties&&C.data&&(C.data=null),this.commonObjs.resolve(c,C)});break;case"FontPath":case"Image":this.commonObjs.resolve(c,w);break;default:throw new Error(`Got unknown common object type ${p}`)}}),g.on("obj",([c,p,w,A])=>{var b;if(this.destroyed)return;let E=Lt(this,o).get(p);if(!E.objs.has(c))switch(w){case"Image":E.objs.resolve(c,A);let C=8e6;if(A){let k;if(A.bitmap){let{bitmap:R,width:B,height:I}=A;k=B*I*4,E._bitmaps.add(R)}else k=((b=A.data)==null?void 0:b.length)||0;k>C&&(E.cleanupAfterRender=!0)}break;case"Pattern":E.objs.resolve(c,A);break;default:throw new Error(`Got unknown object type ${w}`)}}),g.on("DocProgress",c=>{var p;this.destroyed||(p=h.onProgress)==null||p.call(h,{loaded:c.loaded,total:c.total})}),g.on("DocStats",c=>{this.destroyed||to(this,i,Object.freeze({streamTypes:Object.freeze(c.streamTypes),fontTypes:Object.freeze(c.fontTypes)}))}),g.on("UnsupportedFeature",this._onUnsupportedFeature.bind(this)),g.on("FetchBuiltInCMap",c=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.CMapReaderFactory?this.CMapReaderFactory.fetch(c):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."))),g.on("FetchStandardFontData",c=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.StandardFontDataFactory?this.StandardFontDataFactory.fetch(c):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.")))}_onUnsupportedFeature({featureId:g}){var h,c;this.destroyed||(c=(h=this.loadingTask).onUnsupportedFeature)==null||c.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,c=Lt(this,s).get(h);if(c)return c;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,l)||to(this,l,this.messageHandler.sendWithPromise("GetMetadata",null).then(g=>{var h,c;return{info:g[0],metadata:g[1]?new _metadata.Metadata(g[1]):null,contentDispositionFilename:((h=this._fullReader)==null?void 0:h.filename)??null,contentLength:((c=this._fullReader)==null?void 0:c.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(),to(this,l,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,l=new WeakMap;class PDFObjects{constructor(){Tr(this,u);Tr(this,f,Object.create(null))}get(g,h=null){if(h){let p=ro(this,u,em).call(this,g);return p.capability.promise.then(()=>h(p.data)),null}let c=Lt(this,f)[g];if(!(c!=null&&c.capability.settled))throw new Error(`Requesting object that isn't resolved yet ${g}.`);return c.data}has(g){let h=Lt(this,f)[g];return(h==null?void 0:h.capability.settled)||!1}resolve(g,h=null){let c=ro(this,u,em).call(this,g);c.data=h,c.capability.resolve()}clear(){to(this,f,Object.create(null))}}f=new WeakMap,u=new WeakSet,em=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:c,commonObjs:p,annotationCanvasMap:w,operatorList:A,pageIndex:E,canvasFactory:b,useRequestAnimationFrame:C=!1,pdfBug:k=!1,pageColors:R=null}){this.callback=g,this.params=h,this.objs=c,this.commonObjs=p,this.annotationCanvasMap=w,this.operatorListIdx=null,this.operatorList=A,this._pageIndex=E,this.canvasFactory=b,this._pdfBug=k,this.pageColors=R,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=C===!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:c,viewport:p,transform:w,imageLayer:A,background:E}=this.params;this.gfx=new _canvas.CanvasGraphics(c,this.commonObjs,this.objs,this.canvasFactory,A,h,this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:w,viewport:p,transparency:g,background:E}),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,Tr(_,m,new WeakSet);let InternalRenderTask=_,version="2.14.305";exports.version=version;let build="eaaa8b4ad";exports.build=build},(n,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=c,e.getPdfFilenameFromUrl=p,e.getXfaPageViewport=R,e.isDataScheme=g,e.isPdfFile=h,e.isValidFetchUrl=A,e.loadScript=E;var r=t(6),i=t(1);let o="http://www.w3.org/2000/svg",B=class B{};Bc(B,"CSS",96),Bc(B,"PDF",72),Bc(B,"PDF_TO_CSS_UNITS",B.CSS/B.PDF);let s=B;e.PixelsPerInch=s;class l extends r.BaseCanvasFactory{constructor({ownerDocument:D=globalThis.document}={}){super(),this._document=D}_createCanvas(D,F){let z=this._document.createElement("canvas");return z.width=D,z.height=F,z}}e.DOMCanvasFactory=l;async function f(I,D=!1){if(A(I,document.baseURI)){let F=await fetch(I);if(!F.ok)throw new Error(F.statusText);return D?new Uint8Array(await F.arrayBuffer()):(0,i.stringToBytes)(await F.text())}return new Promise((F,z)=>{let q=new XMLHttpRequest;q.open("GET",I,!0),D&&(q.responseType="arraybuffer"),q.onreadystatechange=()=>{if(q.readyState===XMLHttpRequest.DONE){if(q.status===200||q.status===0){let G;if(D&&q.response?G=new Uint8Array(q.response):!D&&q.responseText&&(G=(0,i.stringToBytes)(q.responseText)),G){F(G);return}}z(new Error(q.statusText))}},q.send(null)})}class u extends r.BaseCMapReaderFactory{_fetchData(D,F){return f(D,this.isCompressed).then(z=>({cMapData:z,compressionType:F}))}}e.DOMCMapReaderFactory=u;class y extends r.BaseStandardFontDataFactory{_fetchData(D){return f(D,!0)}}e.DOMStandardFontDataFactory=y;class m extends r.BaseSVGFactory{_createSVG(D){return document.createElementNS(o,D)}}e.DOMSVGFactory=m;class _{constructor({viewBox:D,scale:F,rotation:z,offsetX:q=0,offsetY:G=0,dontFlip:Y=!1}){this.viewBox=D,this.scale=F,this.rotation=z,this.offsetX=q,this.offsetY=G;let X=(D[2]+D[0])/2,Q=(D[3]+D[1])/2,se,ve,ce,W;switch(z%=360,z<0&&(z+=360),z){case 180:se=-1,ve=0,ce=0,W=1;break;case 90:se=0,ve=1,ce=1,W=0;break;case 270:se=0,ve=-1,ce=-1,W=0;break;case 0:se=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,M,x,T;se===0?(H=Math.abs(Q-D[1])*F+q,M=Math.abs(X-D[0])*F+G,x=Math.abs(D[3]-D[1])*F,T=Math.abs(D[2]-D[0])*F):(H=Math.abs(X-D[0])*F+q,M=Math.abs(Q-D[1])*F+G,x=Math.abs(D[2]-D[0])*F,T=Math.abs(D[3]-D[1])*F),this.transform=[se*F,ve*F,ce*F,W*F,H-se*F*X-ce*F*Q,M-ve*F*X-W*F*Q],this.width=x,this.height=T}clone({scale:D=this.scale,rotation:F=this.rotation,offsetX:z=this.offsetX,offsetY:q=this.offsetY,dontFlip:G=!1}={}){return new _({viewBox:this.viewBox.slice(),scale:D,rotation:F,offsetX:z,offsetY:q,dontFlip:G})}convertToViewportPoint(D,F){return i.Util.applyTransform([D,F],this.transform)}convertToViewportRectangle(D){let F=i.Util.applyTransform([D[0],D[1]],this.transform),z=i.Util.applyTransform([D[2],D[3]],this.transform);return[F[0],F[1],z[0],z[1]]}convertToPdfPoint(D,F){return i.Util.applyInverseTransform([D,F],this.transform)}}e.PageViewport=_;class v extends i.BaseException{constructor(D,F){super(D,"RenderingCancelledException"),this.type=F}}e.RenderingCancelledException=v;function g(I){let D=I.length,F=0;for(;F<D&&I[F].trim()==="";)F++;return I.substring(F,F+5).toLowerCase()==="data:"}function h(I){return typeof I=="string"&&/\.pdf$/i.test(I)}function c(I){let D=I.indexOf("#"),F=I.indexOf("?"),z=Math.min(D>0?D:I.length,F>0?F:I.length);return I.substring(I.lastIndexOf("/",z)+1,z)}function p(I,D="document.pdf"){if(typeof I!="string")return D;if(g(I))return(0,i.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),D;let F=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,z=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,q=F.exec(I),G=z.exec(q[1])||z.exec(q[2])||z.exec(q[3]);if(G&&(G=G[0],G.includes("%")))try{G=z.exec(decodeURIComponent(G))[0]}catch{}return G||D}class w{constructor(){this.started=Object.create(null),this.times=[]}time(D){D in this.started&&(0,i.warn)(`Timer is already running for ${D}`),this.started[D]=Date.now()}timeEnd(D){D in this.started||(0,i.warn)(`Timer has not been started for ${D}`),this.times.push({name:D,start:this.started[D],end:Date.now()}),delete this.started[D]}toString(){let D=[],F=0;for(let z of this.times){let q=z.name;q.length>F&&(F=q.length)}for(let z of this.times){let q=z.end-z.start;D.push(`${z.name.padEnd(F)} ${q}ms
|
|
71
71
|
`)}return D.join("")}}e.StatTimer=w;function A(I,D){try{let{protocol:F}=D?new URL(I,D):new URL(I);return F==="http:"||F==="https:"}catch{return!1}}function E(I,D=!1){return new Promise((F,z)=>{let q=document.createElement("script");q.src=I,q.onload=function(G){D&&q.remove(),F(G)},q.onerror=function(){z(new Error(`Cannot load script at: ${q.src}`))},(document.head||document.documentElement).appendChild(q)})}function b(I){console.log("Deprecated API usage: "+I)}let C;class k{static toDateObject(D){if(!D||typeof D!="string")return null;C||(C=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"));let F=C.exec(D);if(!F)return null;let z=parseInt(F[1],10),q=parseInt(F[2],10);q=q>=1&&q<=12?q-1:0;let G=parseInt(F[3],10);G=G>=1&&G<=31?G:1;let Y=parseInt(F[4],10);Y=Y>=0&&Y<=23?Y:0;let X=parseInt(F[5],10);X=X>=0&&X<=59?X:0;let Q=parseInt(F[6],10);Q=Q>=0&&Q<=59?Q:0;let se=F[7]||"Z",ve=parseInt(F[8],10);ve=ve>=0&&ve<=23?ve:0;let ce=parseInt(F[9],10)||0;return ce=ce>=0&&ce<=59?ce:0,se==="-"?(Y+=ve,X+=ce):se==="+"&&(Y-=ve,X-=ce),new Date(Date.UTC(z,q,G,Y,X,Q))}}e.PDFDateString=k;function R(I,{scale:D=1,rotation:F=0}){let{width:z,height:q}=I.attributes.style,G=[0,0,parseInt(z),parseInt(q)];return new _({viewBox:G,scale:D,rotation:F})}},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BaseStandardFontDataFactory=e.BaseSVGFactory=e.BaseCanvasFactory=e.BaseCMapReaderFactory=void 0;var r=t(1);class i{constructor(){this.constructor===i&&(0,r.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,r.unreachable)("Abstract method `_createCanvas` called.")}}e.BaseCanvasFactory=i;class o{constructor({baseUrl:u=null,isCompressed:y=!1}){this.constructor===o&&(0,r.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?r.CMapCompressionType.BINARY:r.CMapCompressionType.NONE;return this._fetchData(y,m).catch(_=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${y}`)})}_fetchData(u,y){(0,r.unreachable)("Abstract method `_fetchData` called.")}}e.BaseCMapReaderFactory=o;class s{constructor({baseUrl:u=null}){this.constructor===s&&(0,r.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,r.unreachable)("Abstract method `_fetchData` called.")}}e.BaseStandardFontDataFactory=s;class l{constructor(){this.constructor===l&&(0,r.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,r.unreachable)("Abstract method `_createSVG` called.")}}e.BaseSVGFactory=l},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FontLoader=e.FontFaceObject=void 0;var r=t(1);class i{constructor({docId:f,onUnsupportedFeature:u,ownerDocument:y=globalThis.document,styleElement:m=null}){this.constructor===i&&(0,r.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:r.UNSUPPORTED_FEATURES.errorFontLoadNative}),(0,r.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,r.unreachable)("Abstract method `_queueLoadingCallback`.")}get isFontLoadingAPISupported(){var u;let f=!!((u=this._document)!=null&&u.fonts);return(0,r.shadow)(this,"isFontLoadingAPISupported",f)}get isSyncFontLoadingSupported(){(0,r.unreachable)("Abstract method `isSyncFontLoadingSupported`.")}get _loadTestFont(){(0,r.unreachable)("Abstract method `_loadTestFont`.")}_prepareFontLoadEvent(f,u,y){(0,r.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,r.shadow)(this,"isSyncFontLoadingSupported",f)}_queueLoadingCallback(f){function u(){for((0,r.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,r.shadow)(this,"_loadTestFont",f())}_prepareFontLoadEvent(f,u,y){function m(z,q){return z.charCodeAt(q)<<24|z.charCodeAt(q+1)<<16|z.charCodeAt(q+2)<<8|z.charCodeAt(q+3)&255}function _(z,q,G,Y){let X=z.substring(0,q),Q=z.substring(q+G);return X+Y+Q}let v,g,h=this._document.createElement("canvas");h.width=1,h.height=1;let c=h.getContext("2d"),p=0;function w(z,q){if(p++,p>30){(0,r.warn)("Load test font never loaded."),q();return}if(c.font="30px "+z,c.fillText(".",0,20),c.getImageData(0,0,1,1).data[3]>0){q();return}setTimeout(w.bind(null,z,q))}let A=`lt${Date.now()}${this.loadTestFontId++}`,E=this._loadTestFont;E=_(E,976,A.length,A);let C=16,k=1482184792,R=m(E,C);for(v=0,g=A.length-3;v<g;v+=4)R=R-k+m(A,v)|0;v<A.length&&(R=R-k+m(A+"XXX",v)|0),E=_(E,C,4,(0,r.string32)(R));let B=`url(data:font/opentype;base64,${btoa(E)});`,I=`@font-face {font-family:"${A}";src:${B}}`;this.insertRule(I);let D=[];for(let z of u)D.push(z.loadedName);D.push(A);let F=this._document.createElement("div");F.style.visibility="hidden",F.style.width=F.style.height="10px",F.style.position="absolute",F.style.top=F.style.left="0px";for(let z of D){let q=this._document.createElement("span");q.textContent="Hi",q.style.fontFamily=z,F.appendChild(q)}this._document.body.appendChild(F),w(A,()=>{F.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,r.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:r.UNSUPPORTED_FEATURES.errorFontGetPath}),(0,r.warn)(`getPathGenerator - ignoring character: "${m}".`),this.compiledGlyphs[u]=function(_,v){}}if(this.isEvalSupported&&r.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},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AnnotationStorage=void 0;var r=t(9),i=t(1);class o{constructor(){this._storage=new Map,this._modified=!1,this.onSetModified=null,this.onResetModified=null}getValue(l,f){let u=this._storage.get(l);return u===void 0?f:Object.assign(f,u)}getRawValue(l){return this._storage.get(l)}setValue(l,f){let u=this._storage.get(l),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(l,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 l=new r.MurmurHash3_64;for(let[f,u]of this._storage)l.update(`${f}:${JSON.stringify(u)}`);return l.hexdigest()}}e.AnnotationStorage=o},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MurmurHash3_64=void 0;var r=t(1);let i=3285377520,o=4294901760,s=65535;class l{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,R=u.length;k<R;k++){let B=u.charCodeAt(k);B<=255?y[m++]=B:(y[m++]=B>>>8,y[m++]=B&255)}}else if((0,r.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,c=0,p=this.h1,w=this.h2,A=3432918353,E=461845907,b=A&s,C=E&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*E&o|h*C&s,p^=h,p=p<<13|p>>>19,p=p*5+3864292196):(c=g[k],c=c*A&o|c*b&s,c=c<<15|c>>>17,c=c*E&o|c*C&s,w^=c,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*E&o|h*C&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=l},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CanvasGraphics=void 0;var r=t(1),i=t(11),o=t(12),s=t(3),l=t(5);let f=16,u=100,y=4096,m=15,_=10,v=!0,g=1e3,h=16,c=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,P,N,U,V){H.transform(x,T,P,N,U,V),this.__originalTransform(x,T,P,N,U,V)},W.setTransform=function(x,T,P,N,U,V){H.setTransform(x,T,P,N,U,V),this.__originalSetTransform(x,T,P,N,U,V)},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(M,x){H.moveTo(M,x),this.__originalMoveTo(M,x)},W.lineTo=function(M,x){H.lineTo(M,x),this.__originalLineTo(M,x)},W.bezierCurveTo=function(M,x,T,P,N,U){H.bezierCurveTo(M,x,T,P,N,U),this.__originalBezierCurveTo(M,x,T,P,N,U)},W.rect=function(M,x,T,P){H.rect(M,x,T,P),this.__originalRect(M,x,T,P)},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*c)},get:function(){return this._getLineWidth()}})}catch{}Object.defineProperty(W,"mozCurrentTransform",{get:function(){return this._transformMatrix}}),Object.defineProperty(W,"mozCurrentTransformInverse",{get:function(){let[M,x,T,P,N,U]=this._transformMatrix,V=M*P-x*T,Z=x*T-M*P;return[P/V,x/Z,T/Z,M/V,(P*N-T*U)/Z,(x*N-M*U)/V]}}),W.save=function(){let M=this._transformMatrix;this._transformStack.push(M),this._transformMatrix=M.slice(0,6),this._originalSave()},W.restore=function(){this._transformStack.length===0&&(0,r.warn)("Tried to restore a ctx when the stack was already empty.");let M=this._transformStack.pop();M&&(this._transformMatrix=M,this._originalRestore())},W.translate=function(M,x){let T=this._transformMatrix;T[4]=T[0]*M+T[2]*x+T[4],T[5]=T[1]*M+T[3]*x+T[5],this._originalTranslate(M,x)},W.scale=function(M,x){let T=this._transformMatrix;T[0]*=M,T[1]*=M,T[2]*=x,T[3]*=x,this._originalScale(M,x)},W.transform=function(M,x,T,P,N,U){let V=this._transformMatrix;this._transformMatrix=[V[0]*M+V[2]*x,V[1]*M+V[3]*x,V[0]*T+V[2]*P,V[1]*T+V[3]*P,V[0]*N+V[2]*U+V[4],V[1]*N+V[3]*U+V[5]],W._originalTransform(M,x,T,P,N,U)},W.setTransform=function(M,x,T,P,N,U){this._transformMatrix=[M,x,T,P,N,U],W._originalSetTransform(M,x,T,P,N,U)},W.resetTransform=function(){this._transformMatrix=[1,0,0,1,0,0],W._originalResetTransform()},W.rotate=function(M){let x=Math.cos(M),T=Math.sin(M),P=this._transformMatrix;this._transformMatrix=[P[0]*x+P[2]*T,P[1]*x+P[3]*T,P[0]*-T+P[2]*x,P[1]*-T+P[3]*x,P[4],P[5]],this._originalRotate(M)}}}class A{constructor(H){this.canvasFactory=H,this.cache=Object.create(null)}getCanvas(H,M,x,T){let P;return this.cache[H]!==void 0?(P=this.cache[H],this.canvasFactory.reset(P,M,x),P.context.setTransform(1,0,0,1,0,0)):(P=this.canvasFactory.create(M,x),this.cache[H]=P),T&&w(P.context),P}delete(H){delete this.cache[H]}clear(){for(let H in this.cache){let M=this.cache[H];this.canvasFactory.destroy(M),delete this.cache[H]}}}function E(W,H,M,x,T,P,N,U,V,Z){let[re,ne,ae,fe,he,Te]=W.mozCurrentTransform;if(ne===0&&ae===0){let ye=N*re+he,oe=Math.round(ye),Ee=U*fe+Te,xe=Math.round(Ee),K=(N+V)*re+he,ie=Math.abs(Math.round(K)-oe)||1,be=(U+Z)*fe+Te,Ce=Math.abs(Math.round(be)-xe)||1;return W.setTransform(Math.sign(re),0,0,Math.sign(fe),oe,xe),W.drawImage(H,M,x,T,P,0,0,ie,Ce),W.setTransform(re,ne,ae,fe,he,Te),[ie,Ce]}if(re===0&&fe===0){let ye=U*ae+he,oe=Math.round(ye),Ee=N*ne+Te,xe=Math.round(Ee),K=(U+Z)*ae+he,ie=Math.abs(Math.round(K)-oe)||1,be=(N+V)*ne+Te,Ce=Math.abs(Math.round(be)-xe)||1;return W.setTransform(0,Math.sign(ne),Math.sign(ae),0,oe,xe),W.drawImage(H,M,x,T,P,0,0,Ce,ie),W.setTransform(re,ne,ae,fe,he,Te),[Ce,ie]}W.drawImage(H,M,x,T,P,N,U,V,Z);let Ne=Math.hypot(re,ne),Se=Math.hypot(ae,fe);return[Ne*V,Se*Z]}function b(W){let{width:H,height:M}=W;if(!v||H>g||M>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]),P=H+1,N=new Uint8Array(P*(M+1)),U,V,Z,re=H+7&-8,ne=new Uint8Array(re*M),ae=0;for(let oe of W.data){let Ee=128;for(;Ee>0;)ne[ae++]=oe&Ee?0:255,Ee>>=1}let fe=0;for(ae=0,ne[ae]!==0&&(N[0]=1,++fe),V=1;V<H;V++)ne[ae]!==ne[ae+1]&&(N[V]=ne[ae]?2:1,++fe),ae++;for(ne[ae]!==0&&(N[V]=2,++fe),U=1;U<M;U++){ae=U*re,Z=U*P,ne[ae-re]!==ne[ae]&&(N[Z]=ne[ae]?1:8,++fe);let oe=(ne[ae]?4:0)+(ne[ae-re]?8:0);for(V=1;V<H;V++)oe=(oe>>2)+(ne[ae+1]?4:0)+(ne[ae-re+1]?8:0),T[oe]&&(N[Z+V]=T[oe],++fe),ae++;if(ne[ae-re]!==ne[ae]&&(N[Z+V]=ne[ae]?2:4,++fe),fe>x)return null}for(ae=re*(M-1),Z=U*P,ne[ae]!==0&&(N[Z]=8,++fe),V=1;V<H;V++)ne[ae]!==ne[ae+1]&&(N[Z+V]=ne[ae]?4:8,++fe),ae++;if(ne[ae]!==0&&(N[Z+V]=4,++fe),fe>x)return null;let he=new Int32Array([0,P,-1,0,-P,0,0,0,1]),Te,Ne,Se;for(s.isNodeJS?Ne=[]:Te=new Path2D,U=0;fe&&U<=M;U++){let oe=U*P,Ee=oe+H;for(;oe<Ee&&!N[oe];)oe++;if(oe===Ee)continue;Te?Te.moveTo(oe%P,U):Se=[oe%P,U];let xe=oe,K=N[oe];do{let ie=he[K];do oe+=ie;while(!N[oe]);let be=N[oe];be!==5&&be!==10?(K=be,N[oe]=0):(K=be&51*K>>4,N[oe]&=K>>2|K<<2),Te?Te.lineTo(oe%P,oe/P|0):Se.push(oe%P,oe/P|0),N[oe]||--fe}while(xe!==oe);Te||Ne.push(Se),--U}return ne=null,N=null,function(oe){if(oe.save(),oe.scale(1/H,-1/M),oe.translate(0,-M),Te)oe.fill(Te);else{oe.beginPath();for(let Ee of Ne){oe.moveTo(Ee[0],Ee[1]);for(let xe=2,K=Ee.length;xe<K;xe+=2)oe.lineTo(Ee[xe],Ee[xe+1])}oe.fill()}oe.beginPath(),oe.restore()}}class C{constructor(H,M){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=r.IDENTITY_MATRIX,this.textMatrixScale=1,this.fontMatrix=r.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=r.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,M])}clone(){let H=Object.create(this);return H.clipBox=this.clipBox.slice(),H}setCurrentPoint(H,M){this.x=H,this.y=M}updatePathMinMax(H,M,x){[M,x]=r.Util.applyTransform([M,x],H),this.minX=Math.min(this.minX,M),this.minY=Math.min(this.minY,x),this.maxX=Math.max(this.maxX,M),this.maxY=Math.max(this.maxY,x)}updateRectMinMax(H,M){let x=r.Util.applyTransform(M,H),T=r.Util.applyTransform(M.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,M){r.Util.scaleMinMax(H,M),this.minX=Math.min(this.minX,M[0]),this.maxX=Math.max(this.maxX,M[1]),this.minY=Math.min(this.minY,M[2]),this.maxY=Math.max(this.maxY,M[3])}updateCurvePathMinMax(H,M,x,T,P,N,U,V,Z,re){let ne=r.Util.bezierBoundingBox(M,x,T,P,N,U,V,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,M=null){let x=[this.minX,this.minY,this.maxX,this.maxY];if(H===i.PathType.STROKE){M||(0,r.unreachable)("Stroke bounding box must include transform.");let T=r.Util.singularValueDecompose2dScale(M),P=T[0]*this.lineWidth/2,N=T[1]*this.lineWidth/2;x[0]-=P,x[1]-=N,x[2]+=P,x[3]+=N}return x}updateClipFromPath(){let H=r.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,M=null){return r.Util.intersect(this.clipBox,this.getPathBoundingBox(H,M))}}function k(W,H,M=null){if(typeof ImageData<"u"&&H instanceof ImageData){W.putImageData(H,0,0);return}let x=H.height,T=H.width,P=x%h,N=(x-P)/h,U=P===0?N:N+1,V=W.createImageData(T,h),Z=0,re,ne=H.data,ae=V.data,fe,he,Te,Ne,Se,ye,oe,Ee;if(M)switch(M.length){case 1:Se=M[0],ye=M[0],oe=M[0],Ee=M[0];break;case 4:Se=M[0],ye=M[1],oe=M[2],Ee=M[3];break}if(H.kind===r.ImageKind.GRAYSCALE_1BPP){let xe=ne.byteLength,K=new Uint32Array(ae.buffer,0,ae.byteLength>>2),ie=K.length,be=T+7>>3,Ce=4294967295,Re=r.FeatureTest.isLittleEndian?4278190080:255;for(Ee&&Ee[0]===255&&Ee[255]===0&&([Ce,Re]=[Re,Ce]),fe=0;fe<U;fe++){for(Te=fe<N?h:P,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?Ce:Re,K[re++]=ee&64?Ce:Re,K[re++]=ee&32?Ce:Re,K[re++]=ee&16?Ce:Re,K[re++]=ee&8?Ce:Re,K[re++]=ee&4?Ce:Re,K[re++]=ee&2?Ce:Re,K[re++]=ee&1?Ce:Re;for(;ze<Ve;ze++)pe===0&&(ee=ne[Z++],pe=128),K[re++]=ee&pe?Ce:Re,pe>>=1}for(;re<ie;)K[re++]=0;W.putImageData(V,0,fe*h)}}else if(H.kind===r.ImageKind.RGBA_32BPP){let xe=!!(Se||ye||oe);for(he=0,Ne=T*h*4,fe=0;fe<N;fe++){if(ae.set(ne.subarray(Z,Z+Ne)),Z+=Ne,xe)for(let K=0;K<Ne;K+=4)Se&&(ae[K+0]=Se[ae[K+0]]),ye&&(ae[K+1]=ye[ae[K+1]]),oe&&(ae[K+2]=oe[ae[K+2]]);W.putImageData(V,0,he),he+=h}if(fe<U){if(Ne=T*P*4,ae.set(ne.subarray(Z,Z+Ne)),xe)for(let K=0;K<Ne;K+=4)Se&&(ae[K+0]=Se[ae[K+0]]),ye&&(ae[K+1]=ye[ae[K+1]]),oe&&(ae[K+2]=oe[ae[K+2]]);W.putImageData(V,0,he)}}else if(H.kind===r.ImageKind.RGB_24BPP){let xe=!!(Se||ye||oe);for(Te=h,Ne=T*Te,fe=0;fe<U;fe++){for(fe>=N&&(Te=P,Ne=T*Te),re=0,he=Ne;he--;)ae[re++]=ne[Z++],ae[re++]=ne[Z++],ae[re++]=ne[Z++],ae[re++]=255;if(xe)for(let K=0;K<re;K+=4)Se&&(ae[K+0]=Se[ae[K+0]]),ye&&(ae[K+1]=ye[ae[K+1]]),oe&&(ae[K+2]=oe[ae[K+2]]);W.putImageData(V,0,fe*h)}}else throw new Error(`bad image kind: ${H.kind}`)}function R(W,H){if(H.bitmap){W.drawImage(H.bitmap,0,0);return}let M=H.height,x=H.width,T=M%h,P=(M-T)/h,N=T===0?P:P+1,U=W.createImageData(x,h),V=0,Z=H.data,re=U.data;for(let ne=0;ne<N;ne++){let ae=ne<P?h:T;({srcPos:V}=(0,o.applyMaskImageData)({src:Z,srcPos:V,dest:re,width:x,height:ae})),W.putImageData(U,0,ne*h)}}function B(W,H){let M=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font"];for(let x=0,T=M.length;x<T;x++){let P=M[x];W[P]!==void 0&&(H[P]=W[P])}W.setLineDash!==void 0&&(H.setLineDash(W.getLineDash()),H.lineDashOffset=W.lineDashOffset)}function I(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 D(W,H,M,x){let T=W.length;for(let P=3;P<T;P+=4){let N=W[P];if(N===0)W[P-3]=H,W[P-2]=M,W[P-1]=x;else if(N<255){let U=255-N;W[P-3]=W[P-3]*N+H*U>>8,W[P-2]=W[P-2]*N+M*U>>8,W[P-1]=W[P-1]*N+x*U>>8}}}function F(W,H,M){let x=W.length,T=1/255;for(let P=3;P<x;P+=4){let N=M?M[W[P]]:W[P];H[P]=H[P]*N*T|0}}function z(W,H,M){let x=W.length;for(let T=3;T<x;T+=4){let P=W[T-3]*77+W[T-2]*152+W[T-1]*28;H[T]=M?H[T]*M[P>>8]>>8:H[T]*P>>16}}function q(W,H,M,x,T,P,N,U,V,Z,re){let ne=!!P,ae=ne?P[0]:0,fe=ne?P[1]:0,he=ne?P[2]:0,Te;T==="Luminosity"?Te=z:Te=F;let Se=Math.min(x,Math.ceil(1048576/M));for(let ye=0;ye<x;ye+=Se){let oe=Math.min(Se,x-ye),Ee=W.getImageData(U-Z,ye+(V-re),M,oe),xe=H.getImageData(U,ye+V,M,oe);ne&&D(Ee.data,ae,fe,he),Te(Ee.data,xe.data,N),H.putImageData(xe,U,ye+V)}}function G(W,H,M,x){let T=x[0],P=x[1],N=x[2]-T,U=x[3]-P;N===0||U===0||(q(H.context,M,N,U,H.subtype,H.backdrop,H.transferMap,T,P,H.offsetX,H.offsetY),W.save(),W.globalAlpha=1,W.globalCompositeOperation="source-over",W.setTransform(1,0,0,1,0,0),W.drawImage(M.canvas,0,0),W.restore())}function Y(W,H){let M=r.Util.singularValueDecompose2dScale(W);M[0]=Math.fround(M[0]),M[1]=Math.fround(M[1]);let x=Math.fround((globalThis.devicePixelRatio||1)*l.PixelsPerInch.PDF_TO_CSS_UNITS);return H!==void 0?H:M[0]<=x||M[1]<=x}let X=["butt","round","square"],Q=["miter","round","bevel"],se={},ve={};class ce{constructor(H,M,x,T,P,N,U,V){this.ctx=H,this.current=new C(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=M,this.objs=x,this.canvasFactory=T,this.imageLayer=P,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=N,this.cachedCanvases=new A(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=U,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.backgroundColor=(V==null?void 0:V.background)||null,this.foregroundColor=(V==null?void 0:V.foreground)||null,H&&w(H),this._cachedScaleForStroking=null,this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(H,M=null){return typeof H=="string"?H.startsWith("g_")?this.commonObjs.get(H):this.objs.get(H):M}beginDrawing({transform:H,viewport:M,transparency:x=!1,background:T=null}){let P=this.ctx.canvas.width,N=this.ctx.canvas.height,U=T||"#ffffff";if(this.ctx.save(),this.foregroundColor&&this.backgroundColor){this.ctx.fillStyle=this.foregroundColor;let V=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),V==="#000000"&&Z==="#ffffff"||V===Z||!re)this.foregroundColor=this.backgroundColor=null;else{let ae=parseInt(ne.slice(1),16),fe=(ae&&16711680)>>16,he=(ae&&65280)>>8,Te=ae&&255,Ne=ye=>(ye/=255,ye<=.03928?ye/12.92:((ye+.055)/1.055)**2.4),Se=Math.round(.2126*Ne(fe)+.7152*Ne(he)+.0722*Ne(Te));this.selectColor=(ye,oe,Ee)=>{let xe=.2126*Ne(ye)+.7152*Ne(oe)+.0722*Ne(Ee);return Math.round(xe)===Se?Z:V}}}if(this.ctx.fillStyle=this.backgroundColor||U,this.ctx.fillRect(0,0,P,N),this.ctx.restore(),x){let V=this.cachedCanvases.getCanvas("transparent",P,N,!0);this.compositeCtx=this.ctx,this.transparentCanvas=V.canvas,this.ctx=V.context,this.ctx.save(),this.ctx.transform.apply(this.ctx,this.compositeCtx.mozCurrentTransform)}this.ctx.save(),I(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,M.transform),this.viewportScale=M.scale,this.baseTransform=this.ctx.mozCurrentTransform.slice(),this.imageLayer&&this.imageLayer.beginLayout()}executeOperatorList(H,M,x,T){let P=H.argsArray,N=H.fnArray,U=M||0,V=P.length;if(V===U)return U;let Z=V-U>_&&typeof x=="function",re=Z?Date.now()+m:0,ne=0,ae=this.commonObjs,fe=this.objs,he;for(;;){if(T!==void 0&&U===T.nextBreakPoint)return T.breakIt(U,x),U;if(he=N[U],he!==r.OPS.dependency)this[he].apply(this,P[U]);else for(let Te of P[U]){let Ne=Te.startsWith("g_")?ae:fe;if(!Ne.has(Te))return Ne.get(Te,x),U}if(U++,U===V)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 M of H.values())typeof HTMLCanvasElement<"u"&&M instanceof HTMLCanvasElement&&(M.width=M.height=0);H.clear()}this._cachedBitmapsMap.clear(),this.imageLayer&&this.imageLayer.endLayout()}_scaleImage(H,M){let x=H.width,T=H.height,P=Math.max(Math.hypot(M[0],M[1]),1),N=Math.max(Math.hypot(M[2],M[3]),1),U=x,V=T,Z="prescale1",re,ne;for(;P>2&&U>1||N>2&&V>1;){let ae=U,fe=V;P>2&&U>1&&(ae=Math.ceil(U/2),P/=U/ae),N>2&&V>1&&(fe=Math.ceil(V/2),N/=V/fe),re=this.cachedCanvases.getCanvas(Z,ae,fe,!1),ne=re.context,ne.clearRect(0,0,ae,fe),ne.drawImage(H,0,0,U,V,0,0,ae,fe),H=re.canvas,U=ae,V=fe,Z=Z==="prescale1"?"prescale2":"prescale1"}return{img:H,paintWidth:U,paintHeight:V}}_createMaskCanvas(H){let M=this.ctx,{width:x,height:T}=H,P=this.current.fillColor,N=this.current.patternFill,U=M.mozCurrentTransform,V,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(N?be:[be,P]),V=this._cachedBitmapsMap.get(ie),V||(V=new Map,this._cachedBitmapsMap.set(ie,V));let Ce=V.get(Z);if(Ce&&!N){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:Ce,offsetX:Re,offsetY:Ke}}re=Ce}re||(ne=this.cachedCanvases.getCanvas("maskCanvas",x,T,!1),R(ne.context,H));let ae=r.Util.transform(U,[1/x,0,0,-1/T,0,0]);ae=r.Util.transform(ae,[1,0,0,1,0,-T]);let fe=r.Util.applyTransform([0,0],ae),he=r.Util.applyTransform([x,T],ae),Te=r.Util.normalizeRect([fe[0],fe[1],he[0],he[1]]),Ne=Math.round(Te[2]-Te[0])||1,Se=Math.round(Te[3]-Te[1])||1,ye=this.cachedCanvases.getCanvas("fillCanvas",Ne,Se,!0),oe=ye.context,Ee=Math.min(fe[0],he[0]),xe=Math.min(fe[1],he[1]);oe.translate(-Ee,-xe),oe.transform.apply(oe,ae),re||(re=this._scaleImage(ne.canvas,oe.mozCurrentTransformInverse),re=re.img,V&&N&&V.set(Z,re)),oe.imageSmoothingEnabled=Y(oe.mozCurrentTransform,H.interpolate),E(oe,re,0,0,re.width,re.height,0,0,x,T),oe.globalCompositeOperation="source-in";let K=r.Util.transform(oe.mozCurrentTransformInverse,[1,0,0,1,-Ee,-xe]);return oe.fillStyle=N?P.getPattern(M,this,K,i.PathType.FILL):P,oe.fillRect(0,0,x,T),V&&!N&&(this.cachedCanvases.delete("fillCanvas"),V.set(Z,ye.canvas)),{canvas:ye.canvas,offsetX:Math.round(Ee),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,M){let x=this.ctx;x.setLineDash!==void 0&&(x.setLineDash(H),x.lineDashOffset=M)}setRenderingIntent(H){}setFlatness(H){}setGState(H){for(let M=0,x=H.length;M<x;M++){let T=H[M],P=T[0],N=T[1];switch(P){case"LW":this.setLineWidth(N);break;case"LC":this.setLineCap(N);break;case"LJ":this.setLineJoin(N);break;case"ML":this.setMiterLimit(N);break;case"D":this.setDash(N[0],N[1]);break;case"RI":this.setRenderingIntent(N);break;case"FL":this.setFlatness(N);break;case"Font":this.setFont(N[0],N[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=N;break;case"SMask":this.current.activeSMask=N?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.current.transferMaps=N}}}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,M=this.ctx.canvas.height,x="smaskGroupAt"+this.groupLevel,T=this.cachedCanvases.getCanvas(x,H,M,!0);this.suspendedCtx=this.ctx,this.ctx=T.context;let P=this.ctx;P.setTransform.apply(P,this.suspendedCtx.mozCurrentTransform),B(this.suspendedCtx,P),p(P,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(),B(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 M=this.current.activeSMask,x=this.suspendedCtx;G(x,M,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?(B(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(),B(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking=null,this._cachedGetSinglePixelWidth=null)}transform(H,M,x,T,P,N){this.ctx.transform(H,M,x,T,P,N),this._cachedScaleForStroking=null,this._cachedGetSinglePixelWidth=null}constructPath(H,M,x){let T=this.ctx,P=this.current,N=P.x,U=P.y,V,Z,re=T.mozCurrentTransform,ne=re[0]===0&&re[3]===0||re[1]===0&&re[2]===0,ae=ne?x.slice(0):null;for(let fe=0,he=0,Te=H.length;fe<Te;fe++)switch(H[fe]|0){case r.OPS.rectangle:N=M[he++],U=M[he++];let Ne=M[he++],Se=M[he++],ye=N+Ne,oe=U+Se;T.moveTo(N,U),Ne===0||Se===0?T.lineTo(ye,oe):(T.lineTo(ye,U),T.lineTo(ye,oe),T.lineTo(N,oe)),ne||P.updateRectMinMax(re,[N,U,ye,oe]),T.closePath();break;case r.OPS.moveTo:N=M[he++],U=M[he++],T.moveTo(N,U),ne||P.updatePathMinMax(re,N,U);break;case r.OPS.lineTo:N=M[he++],U=M[he++],T.lineTo(N,U),ne||P.updatePathMinMax(re,N,U);break;case r.OPS.curveTo:V=N,Z=U,N=M[he+4],U=M[he+5],T.bezierCurveTo(M[he],M[he+1],M[he+2],M[he+3],N,U),P.updateCurvePathMinMax(re,V,Z,M[he],M[he+1],M[he+2],M[he+3],N,U,ae),he+=6;break;case r.OPS.curveTo2:V=N,Z=U,T.bezierCurveTo(N,U,M[he],M[he+1],M[he+2],M[he+3]),P.updateCurvePathMinMax(re,V,Z,N,U,M[he],M[he+1],M[he+2],M[he+3],ae),N=M[he+2],U=M[he+3],he+=4;break;case r.OPS.curveTo3:V=N,Z=U,N=M[he+2],U=M[he+3],T.bezierCurveTo(M[he],M[he+1],N,U,N,U),P.updateCurvePathMinMax(re,V,Z,M[he],M[he+1],N,U,N,U,ae),he+=4;break;case r.OPS.closePath:T.closePath();break}ne&&P.updateScalingPathMinMax(re,ae),P.setCurrentPoint(N,U)}closePath(){this.ctx.closePath()}stroke(H){H=typeof H<"u"?H:!0;let M=this.ctx,x=this.current.strokeColor;M.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof x=="object"&&(x!=null&&x.getPattern)?(M.save(),M.strokeStyle=x.getPattern(M,this,M.mozCurrentTransformInverse,i.PathType.STROKE),this.rescaleAndStroke(!1),M.restore()):this.rescaleAndStroke(!0)),H&&this.consumePath(this.current.getClippedPathBoundingBox()),M.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(H){H=typeof H<"u"?H:!0;let M=this.ctx,x=this.current.fillColor,T=this.current.patternFill,P=!1;T&&(M.save(),M.fillStyle=x.getPattern(M,this,M.mozCurrentTransformInverse,i.PathType.FILL),P=!0);let N=this.current.getClippedPathBoundingBox();this.contentVisible&&N!==null&&(this.pendingEOFill?(M.fill("evenodd"),this.pendingEOFill=!1):M.fill()),P&&M.restore(),H&&this.consumePath(N)}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=se}eoClip(){this.pendingClip=ve}beginText(){this.current.textMatrix=r.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,M=this.ctx;if(H===void 0){M.beginPath();return}M.save(),M.beginPath();for(let x=0;x<H.length;x++){let T=H[x];M.setTransform.apply(M,T.transform),M.translate(T.x,T.y),T.addToPath(M,T.fontSize)}M.restore(),M.clip(),M.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,M){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||r.FONT_IDENTITY_MATRIX,(T.fontMatrix[0]===0||T.fontMatrix[3]===0)&&(0,r.warn)("Invalid font matrix for font "+H),M<0?(M=-M,T.fontDirection=-1):T.fontDirection=1,this.current.font=x,this.current.fontSize=M,x.isType3Font)return;let P=x.loadedName||"sans-serif",N="normal";x.black?N="900":x.bold&&(N="bold");let U=x.italic?"italic":"normal",V=`"${P}", ${x.fallbackName}`,Z=M;M<f?Z=f:M>u&&(Z=u),this.current.fontSizeScale=M/Z,this.ctx.font=`${U} ${N} ${Z}px ${V}`}setTextRenderingMode(H){this.current.textRenderingMode=H}setTextRise(H){this.current.textRise=H}moveText(H,M){this.current.x=this.current.lineX+=H,this.current.y=this.current.lineY+=M}setLeadingMoveText(H,M){this.setLeading(-M),this.moveText(H,M)}setTextMatrix(H,M,x,T,P,N){this.current.textMatrix=[H,M,x,T,P,N],this.current.textMatrixScale=Math.hypot(H,M),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(H,M,x,T){let P=this.ctx,N=this.current,U=N.font,V=N.textRenderingMode,Z=N.fontSize/N.fontSizeScale,re=V&r.TextRenderingMode.FILL_STROKE_MASK,ne=!!(V&r.TextRenderingMode.ADD_TO_PATH_FLAG),ae=N.patternFill&&!U.missingFile,fe;(U.disableFontFace||ne||ae)&&(fe=U.getPathGenerator(this.commonObjs,H)),U.disableFontFace||ae?(P.save(),P.translate(M,x),P.beginPath(),fe(P,Z),T&&P.setTransform.apply(P,T),(re===r.TextRenderingMode.FILL||re===r.TextRenderingMode.FILL_STROKE)&&P.fill(),(re===r.TextRenderingMode.STROKE||re===r.TextRenderingMode.FILL_STROKE)&&P.stroke(),P.restore()):((re===r.TextRenderingMode.FILL||re===r.TextRenderingMode.FILL_STROKE)&&P.fillText(H,M,x),(re===r.TextRenderingMode.STROKE||re===r.TextRenderingMode.FILL_STROKE)&&P.strokeText(H,M,x)),ne&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:P.mozCurrentTransform,x:M,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 M=H.getImageData(0,0,10,10).data,x=!1;for(let T=3;T<M.length;T+=4)if(M[T]>0&&M[T]<255){x=!0;break}return(0,r.shadow)(this,"isFontSubpixelAAEnabled",x)}showText(H){let M=this.current,x=M.font;if(x.isType3Font)return this.showType3Text(H);let T=M.fontSize;if(T===0)return;let P=this.ctx,N=M.fontSizeScale,U=M.charSpacing,V=M.wordSpacing,Z=M.fontDirection,re=M.textHScale*Z,ne=H.length,ae=x.vertical,fe=ae?1:-1,he=x.defaultVMetrics,Te=T*M.fontMatrix[0],Ne=M.textRenderingMode===r.TextRenderingMode.FILL&&!x.disableFontFace&&!M.patternFill;P.save(),P.transform.apply(P,M.textMatrix),P.translate(M.x,M.y+M.textRise),Z>0?P.scale(re,-1):P.scale(re,1);let Se;if(M.patternFill){P.save();let K=M.fillColor.getPattern(P,this,P.mozCurrentTransformInverse,i.PathType.FILL);Se=P.mozCurrentTransform,P.restore(),P.fillStyle=K}let ye=M.lineWidth,oe=M.textMatrixScale;if(oe===0||ye===0){let K=M.textRenderingMode&r.TextRenderingMode.FILL_STROKE_MASK;(K===r.TextRenderingMode.STROKE||K===r.TextRenderingMode.FILL_STROKE)&&(ye=this.getSinglePixelWidth())}else ye/=oe;N!==1&&(P.scale(N,N),ye/=N),P.lineWidth=ye;let Ee=0,xe;for(xe=0;xe<ne;++xe){let K=H[xe];if(typeof K=="number"){Ee+=fe*K*T/1e3;continue}let ie=!1,be=(K.isSpace?V:0)+U,Ce=K.fontChar,Re=K.accent,Ke,ze,Ve=K.width;if(ae){let pe=K.vmetric||he,ee=-(K.vmetric?pe[1]:Ve*.5)*Te,de=pe[2]*Te;Ve=pe?-pe[0]:Ve,Ke=ee/N,ze=(Ee+de)/N}else Ke=Ee/N,ze=0;if(x.remeasure&&Ve>0){let pe=P.measureText(Ce).width*1e3/T*N;if(Ve<pe&&this.isFontSubpixelAAEnabled){let ee=Ve/pe;ie=!0,P.save(),P.scale(ee,1),Ke/=ee}else Ve!==pe&&(Ke+=(Ve-pe)/2e3*T/N)}if(this.contentVisible&&(K.isInFont||x.missingFile)){if(Ne&&!Re)P.fillText(Ce,Ke,ze);else if(this.paintChar(Ce,Ke,ze,Se),Re){let pe=Ke+T*Re.offset.x/N,ee=ze-T*Re.offset.y/N;this.paintChar(Re.fontChar,pe,ee,Se)}}let qe;ae?qe=Ve*Te-be*Z:qe=Ve*Te+be*Z,Ee+=qe,ie&&P.restore()}ae?M.y-=Ee:M.x+=Ee*re,P.restore(),this.compose()}showType3Text(H){let M=this.ctx,x=this.current,T=x.font,P=x.fontSize,N=x.fontDirection,U=T.vertical?1:-1,V=x.charSpacing,Z=x.wordSpacing,re=x.textHScale*N,ne=x.fontMatrix||r.FONT_IDENTITY_MATRIX,ae=H.length,fe=x.textRenderingMode===r.TextRenderingMode.INVISIBLE,he,Te,Ne,Se;if(!(fe||P===0)){for(this._cachedScaleForStroking=null,this._cachedGetSinglePixelWidth=null,M.save(),M.transform.apply(M,x.textMatrix),M.translate(x.x,x.y),M.scale(re,N),he=0;he<ae;++he){if(Te=H[he],typeof Te=="number"){Se=U*Te*P/1e3,this.ctx.translate(Se,0),x.x+=Se*re;continue}let ye=(Te.isSpace?Z:0)+V,oe=T.charProcOperatorList[Te.operatorListId];if(!oe){(0,r.warn)(`Type3 character "${Te.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=Te,this.save(),M.scale(P,P),M.transform.apply(M,ne),this.executeOperatorList(oe),this.restore()),Ne=r.Util.applyTransform([Te.width,0],ne)[0]*P+ye,M.translate(Ne,0),x.x+=Ne*re}M.restore(),this.processingType3=null}}setCharWidth(H,M){}setCharWidthAndBounds(H,M,x,T,P,N){this.ctx.rect(x,T,P-x,N-T),this.ctx.clip(),this.endPath()}getColorN_Pattern(H){let M;if(H[0]==="TilingPattern"){let x=H[1],T=this.baseTransform||this.ctx.mozCurrentTransform.slice(),P={createCanvasGraphics:N=>new ce(N,this.commonObjs,this.objs,this.canvasFactory)};M=new i.TilingPattern(H,x,this.ctx,P,T)}else M=this._getPattern(H[1],H[2]);return M}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(H,M,x){var P;let T=((P=this.selectColor)==null?void 0:P.call(this,H,M,x))||r.Util.makeHexColor(H,M,x);this.ctx.strokeStyle=T,this.current.strokeColor=T}setFillRGBColor(H,M,x){var P;let T=((P=this.selectColor)==null?void 0:P.call(this,H,M,x))||r.Util.makeHexColor(H,M,x);this.ctx.fillStyle=T,this.current.fillColor=T,this.current.patternFill=!1}_getPattern(H,M=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)),M&&(x.matrix=M),x}shadingFill(H){if(!this.contentVisible)return;let M=this.ctx;this.save();let x=this._getPattern(H);M.fillStyle=x.getPattern(M,this,M.mozCurrentTransformInverse,i.PathType.SHADING);let T=M.mozCurrentTransformInverse;if(T){let P=M.canvas,N=P.width,U=P.height,V=r.Util.applyTransform([0,0],T),Z=r.Util.applyTransform([0,U],T),re=r.Util.applyTransform([N,0],T),ne=r.Util.applyTransform([N,U],T),ae=Math.min(V[0],Z[0],re[0],ne[0]),fe=Math.min(V[1],Z[1],re[1],ne[1]),he=Math.max(V[0],Z[0],re[0],ne[0]),Te=Math.max(V[1],Z[1],re[1],ne[1]);this.ctx.fillRect(ae,fe,he-ae,Te-fe)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){(0,r.unreachable)("Should not call beginInlineImage")}beginImageData(){(0,r.unreachable)("Should not call beginImageData")}paintFormXObjectBegin(H,M){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,M)){let x=M[2]-M[0],T=M[3]-M[1];this.ctx.rect(M[0],M[1],x,T),this.current.updateRectMinMax(this.ctx.mozCurrentTransform,M),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 M=this.ctx;H.isolated||(0,r.info)("TODO: Support non-isolated groups."),H.knockout&&(0,r.warn)("Knockout groups not supported.");let x=M.mozCurrentTransform;if(H.matrix&&M.transform.apply(M,H.matrix),!H.bbox)throw new Error("Bounding box is required.");let T=r.Util.getAxialAlignedBoundingBox(H.bbox,M.mozCurrentTransform),P=[0,0,M.canvas.width,M.canvas.height];T=r.Util.intersect(T,P)||[0,0,0,0];let N=Math.floor(T[0]),U=Math.floor(T[1]),V=Math.max(Math.ceil(T[2])-N,1),Z=Math.max(Math.ceil(T[3])-U,1),re=1,ne=1;V>y&&(re=V/y,V=y),Z>y&&(ne=Z/y,Z=y),this.current.startNewPathAndClipBox([0,0,V,Z]);let ae="groupAt"+this.groupLevel;H.smask&&(ae+="_smask_"+this.smaskCounter++%2);let fe=this.cachedCanvases.getCanvas(ae,V,Z,!0),he=fe.context;he.scale(1/re,1/ne),he.translate(-N,-U),he.transform.apply(he,x),H.smask?this.smaskStack.push({canvas:fe.canvas,context:he,offsetX:N,offsetY:U,scaleX:re,scaleY:ne,subtype:H.smask.subtype,backdrop:H.smask.backdrop,transferMap:H.smask.transferMap||null,startTransformInverse:null}):(M.setTransform(1,0,0,1,0,0),M.translate(N,U),M.scale(re,ne),M.save()),B(M,he),this.ctx=he,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(M),this.groupLevel++}endGroup(H){if(!this.contentVisible)return;this.groupLevel--;let M=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 P=r.Util.getAxialAlignedBoundingBox([0,0,M.canvas.width,M.canvas.height],T);this.ctx.drawImage(M.canvas,0,0),this.ctx.restore(),this.compose(P)}}beginAnnotations(){this.save(),this.baseTransform&&this.ctx.setTransform.apply(this.ctx,this.baseTransform)}endAnnotations(){this.restore()}beginAnnotation(H,M,x,T,P){if(this.save(),Array.isArray(M)&&M.length===4){let N=M[2]-M[0],U=M[3]-M[1];if(P&&this.annotationCanvasMap){x=x.slice(),x[4]-=M[0],x[5]-=M[1],M=M.slice(),M[0]=M[1]=0,M[2]=N,M[3]=U;let[V,Z]=r.Util.singularValueDecompose2dScale(this.ctx.mozCurrentTransform),{viewportScale:re}=this,ne=Math.ceil(N*this.outputScaleX*re),ae=Math.ceil(U*this.outputScaleY*re);this.annotationCanvas=this.canvasFactory.create(ne,ae);let{canvas:fe,context:he}=this.annotationCanvas,Te=`var(--zoom-factor) * ${l.PixelsPerInch.PDF_TO_CSS_UNITS}`;fe.style.width=`calc(${N}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(V,0,0,-Z,0,U*Z),w(this.ctx),I(this.ctx,this.foregroundColor)}else I(this.ctx,this.foregroundColor),this.ctx.rect(M[0],M[1],N,U),this.ctx.clip(),this.endPath()}this.current=new C(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 M=H.count;H=this.getObject(H.data,H),H.count=M;let x=this.ctx,T=this.processingType3;if(T&&(T.compiled===void 0&&(T.compiled=b(H)),T.compiled)){T.compiled(x);return}let P=this._createMaskCanvas(H),N=P.canvas;x.save(),x.setTransform(1,0,0,1,0,0),x.drawImage(N,P.offsetX,P.offsetY),x.restore(),this.compose()}paintImageMaskXObjectRepeat(H,M,x=0,T=0,P,N){if(!this.contentVisible)return;H=this.getObject(H.data,H);let U=this.ctx;U.save();let V=U.mozCurrentTransform;U.transform(M,x,T,P,0,0);let Z=this._createMaskCanvas(H);U.setTransform(1,0,0,1,0,0);for(let re=0,ne=N.length;re<ne;re+=2){let ae=r.Util.transform(V,[M,x,T,P,N[re],N[re+1]]),[fe,he]=r.Util.applyTransform([0,0],ae);U.drawImage(Z.canvas,fe,he)}U.restore(),this.compose()}paintImageMaskXObjectGroup(H){if(!this.contentVisible)return;let M=this.ctx,x=this.current.fillColor,T=this.current.patternFill;for(let P=0,N=H.length;P<N;P++){let U=H[P],V=U.width,Z=U.height,re=this.cachedCanvases.getCanvas("maskCanvas",V,Z,!1),ne=re.context;ne.save(),R(ne,U),ne.globalCompositeOperation="source-in",ne.fillStyle=T?x.getPattern(ne,this,M.mozCurrentTransformInverse,i.PathType.FILL):x,ne.fillRect(0,0,V,Z),ne.restore(),M.save(),M.transform.apply(M,U.transform),M.scale(1,-1),E(M,re.canvas,0,0,V,Z,0,-1,1,1),M.restore()}this.compose()}paintImageXObject(H){if(!this.contentVisible)return;let M=this.getObject(H);if(!M){(0,r.warn)("Dependent image isn't ready yet");return}this.paintInlineImageXObject(M)}paintImageXObjectRepeat(H,M,x,T){if(!this.contentVisible)return;let P=this.getObject(H);if(!P){(0,r.warn)("Dependent image isn't ready yet");return}let N=P.width,U=P.height,V=[];for(let Z=0,re=T.length;Z<re;Z+=2)V.push({transform:[M,0,0,x,T[Z],T[Z+1]],x:0,y:0,w:N,h:U});this.paintInlineImageXObjectGroup(P,V)}paintInlineImageXObject(H){if(!this.contentVisible)return;let M=H.width,x=H.height,T=this.ctx;this.save(),T.scale(1/M,-1/x);let P;if(typeof HTMLElement=="function"&&H instanceof HTMLElement||!H.data)P=H;else{let Z=this.cachedCanvases.getCanvas("inlineImage",M,x,!1),re=Z.context;k(re,H,this.current.transferMaps),P=Z.canvas}let N=this._scaleImage(P,T.mozCurrentTransformInverse);T.imageSmoothingEnabled=Y(T.mozCurrentTransform,H.interpolate);let[U,V]=E(T,N.img,0,0,N.paintWidth,N.paintHeight,0,-x,M,x);if(this.imageLayer){let Z=this.getCanvasPosition(0,-x);this.imageLayer.appendImage({imgData:H,left:Z[0],top:Z[1],width:U,height:V})}this.compose(),this.restore()}paintInlineImageXObjectGroup(H,M){if(!this.contentVisible)return;let x=this.ctx,T=H.width,P=H.height,N=this.cachedCanvases.getCanvas("inlineImage",T,P,!1),U=N.context;k(U,H,this.current.transferMaps);for(let V=0,Z=M.length;V<Z;V++){let re=M[V];if(x.save(),x.transform.apply(x,re.transform),x.scale(1,-1),E(x,N.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:P})}x.restore()}this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(H){}markPointProps(H,M){}beginMarkedContent(H){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(H,M){H==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(M)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(H){let M=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(H);let x=this.ctx;this.pendingClip&&(M||(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 M=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)/M}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(!this._cachedScaleForStroking){let{lineWidth:H}=this.current,M=this.ctx.mozCurrentTransform,x,T;if(M[1]===0&&M[2]===0){let P=Math.abs(M[0]),N=Math.abs(M[3]);if(H===0)x=1/P,T=1/N;else{let U=P*H,V=N*H;x=U<1?1/U:1,T=V<1?1/V:1}}else{let P=Math.abs(M[0]*M[3]-M[2]*M[1]),N=Math.hypot(M[0],M[1]),U=Math.hypot(M[2],M[3]);if(H===0)x=U/P,T=N/P;else{let V=H*P;x=U>V?U/V:1,T=N>V?N/V:1}}this._cachedScaleForStroking=[x,T]}return this._cachedScaleForStroking}rescaleAndStroke(H){let{ctx:M}=this,{lineWidth:x}=this.current,[T,P]=this.getScaleForStroking();if(M.lineWidth=x||1,T===1&&P===1){M.stroke();return}let N,U,V;H&&(N=M.mozCurrentTransform.slice(),U=M.getLineDash().slice(),V=M.lineDashOffset),M.scale(T,P);let Z=Math.max(T,P);M.setLineDash(M.getLineDash().map(re=>re/Z)),M.lineDashOffset/=Z,M.stroke(),H&&(M.setTransform(...N),M.setLineDash(U),M.lineDashOffset=V)}getCanvasPosition(H,M){let x=this.ctx.mozCurrentTransform;return[x[0]*H+x[2]*M+x[4],x[1]*H+x[3]*M+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 r.OPS)ce.prototype[W]!==void 0&&(ce.prototype[r.OPS[W]]=ce.prototype[W])},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TilingPattern=e.PathType=void 0,e.getShadingPattern=v;var r=t(1),i=t(3);let o={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};e.PathType=o;function s(c,p){if(!p||i.isNodeJS)return;let w=p[2]-p[0],A=p[3]-p[1],E=new Path2D;E.rect(p[0],p[1],w,A),c.clip(E)}class l{constructor(){this.constructor===l&&(0,r.unreachable)("Cannot initialize BaseShadingPattern.")}getPattern(){(0,r.unreachable)("Abstract method `getPattern` called.")}}class f extends l{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,E){let b;if(E===o.STROKE||E===o.FILL){let C=w.current.getClippedPathBoundingBox(E,p.mozCurrentTransform)||[0,0,0,0],k=Math.ceil(C[2]-C[0])||1,R=Math.ceil(C[3]-C[1])||1,B=w.cachedCanvases.getCanvas("pattern",k,R,!0),I=B.context;I.clearRect(0,0,I.canvas.width,I.canvas.height),I.beginPath(),I.rect(0,0,I.canvas.width,I.canvas.height),I.translate(-C[0],-C[1]),A=r.Util.transform(A,[1,0,0,1,C[0],C[1]]),I.transform.apply(I,w.baseTransform),this.matrix&&I.transform.apply(I,this.matrix),s(I,this._bbox),I.fillStyle=this._createGradient(I),I.fill(),b=p.createPattern(B.canvas,"no-repeat");let D=new DOMMatrix(A);try{b.setTransform(D)}catch(F){(0,r.warn)(`RadialAxialShadingPattern.getPattern: "${F==null?void 0:F.message}".`)}}else s(p,this._bbox),b=this._createGradient(p);return b}}function u(c,p,w,A,E,b,C,k){let R=p.coords,B=p.colors,I=c.data,D=c.width*4,F;R[w+1]>R[A+1]&&(F=w,w=A,A=F,F=b,b=C,C=F),R[A+1]>R[E+1]&&(F=A,A=E,E=F,F=C,C=k,k=F),R[w+1]>R[A+1]&&(F=w,w=A,A=F,F=b,b=C,C=F);let z=(R[w]+p.offsetX)*p.scaleX,q=(R[w+1]+p.offsetY)*p.scaleY,G=(R[A]+p.offsetX)*p.scaleX,Y=(R[A+1]+p.offsetY)*p.scaleY,X=(R[E]+p.offsetX)*p.scaleX,Q=(R[E+1]+p.offsetY)*p.scaleY;if(q>=Q)return;let se=B[b],ve=B[b+1],ce=B[b+2],W=B[C],H=B[C+1],M=B[C+2],x=B[k],T=B[k+1],P=B[k+2],N=Math.round(q),U=Math.round(Q),V,Z,re,ne,ae,fe,he,Te;for(let Ne=N;Ne<=U;Ne++){if(Ne<Y){let xe;Ne<q?xe=0:xe=(q-Ne)/(q-Y),V=z-(z-G)*xe,Z=se-(se-W)*xe,re=ve-(ve-H)*xe,ne=ce-(ce-M)*xe}else{let xe;Ne>Q?xe=1:Y===Q?xe=0:xe=(Y-Ne)/(Y-Q),V=G-(G-X)*xe,Z=W-(W-x)*xe,re=H-(H-T)*xe,ne=M-(M-P)*xe}let Se;Ne<q?Se=0:Ne>Q?Se=1:Se=(q-Ne)/(q-Q),ae=z-(z-X)*Se,fe=se-(se-x)*Se,he=ve-(ve-T)*Se,Te=ce-(ce-P)*Se;let ye=Math.round(Math.min(V,ae)),oe=Math.round(Math.max(V,ae)),Ee=D*Ne+ye*4;for(let xe=ye;xe<=oe;xe++)Se=(V-xe)/(V-ae),Se<0?Se=0:Se>1&&(Se=1),I[Ee++]=Z-(Z-fe)*Se|0,I[Ee++]=re-(re-he)*Se|0,I[Ee++]=ne-(ne-Te)*Se|0,I[Ee++]=255}}function y(c,p,w){let A=p.coords,E=p.colors,b,C;switch(p.type){case"lattice":let k=p.verticesPerRow,R=Math.floor(A.length/k)-1,B=k-1;for(b=0;b<R;b++){let I=b*k;for(let D=0;D<B;D++,I++)u(c,w,A[I],A[I+1],A[I+k],E[I],E[I+1],E[I+k]),u(c,w,A[I+k+1],A[I+1],A[I+k],E[I+k+1],E[I+1],E[I+k])}break;case"triangles":for(b=0,C=A.length;b<C;b+=3)u(c,w,A[b],A[b+1],A[b+2],E[b],E[b+1],E[b+2]);break;default:throw new Error("illegal figure")}}class m extends l{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]),R=Math.floor(this._bounds[1]),B=Math.ceil(this._bounds[2])-k,I=Math.ceil(this._bounds[3])-R,D=Math.min(Math.ceil(Math.abs(B*p[0]*1.1)),3e3),F=Math.min(Math.ceil(Math.abs(I*p[1]*1.1)),3e3),z=B/D,q=I/F,G={coords:this._coords,colors:this._colors,offsetX:-k,offsetY:-R,scaleX:1/z,scaleY:1/q},Y=D+2*2,X=F+2*2,Q=A.getCanvas("mesh",Y,X,!1),se=Q.context,ve=se.createImageData(D,F);if(w){let W=ve.data;for(let H=0,M=W.length;H<M;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 se.putImageData(ve,2,2),{canvas:Q.canvas,offsetX:k-2*z,offsetY:R-2*q,scaleX:z,scaleY:q}}getPattern(p,w,A,E){s(p,this._bbox);let b;if(E===o.SHADING)b=r.Util.singularValueDecompose2dScale(p.mozCurrentTransform);else if(b=r.Util.singularValueDecompose2dScale(w.baseTransform),this.matrix){let k=r.Util.singularValueDecompose2dScale(this.matrix);b=[b[0]*k[0],b[1]*k[1]]}let C=this._createMeshCanvas(b,E===o.SHADING?null:this._background,w.cachedCanvases);return E!==o.SHADING&&(p.setTransform.apply(p,w.baseTransform),this.matrix&&p.transform.apply(p,this.matrix)),p.translate(C.offsetX,C.offsetY),p.scale(C.scaleX,C.scaleY),p.createPattern(C.canvas,"no-repeat")}}class _ extends l{getPattern(){return"hotpink"}}function v(c){switch(c[0]){case"RadialAxial":return new f(c);case"Mesh":return new m(c);case"Dummy":return new _}throw new Error(`Unknown IR type: ${c[0]}`)}let g={COLORED:1,UNCOLORED:2};class h{static get MAX_PATTERN_SIZE(){return(0,r.shadow)(this,"MAX_PATTERN_SIZE",3e3)}constructor(p,w,A,E,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=E,this.baseTransform=b}createPatternCanvas(p){let w=this.operatorList,A=this.bbox,E=this.xstep,b=this.ystep,C=this.paintType,k=this.tilingType,R=this.color,B=this.canvasGraphicsFactory;(0,r.info)("TilingType: "+k);let I=A[0],D=A[1],F=A[2],z=A[3],q=r.Util.singularValueDecompose2dScale(this.matrix),G=r.Util.singularValueDecompose2dScale(this.baseTransform),Y=[q[0]*G[0],q[1]*G[1]],X=this.getSizeAndScale(E,this.ctx.canvas.width,Y[0]),Q=this.getSizeAndScale(b,this.ctx.canvas.height,Y[1]),se=p.cachedCanvases.getCanvas("pattern",X.size,Q.size,!0),ve=se.context,ce=B.createCanvasGraphics(ve);ce.groupLevel=p.groupLevel,this.setFillAndStrokeStyleToContext(ce,C,R);let W=I,H=D,M=F,x=z;return I<0&&(W=0,M+=Math.abs(I)),D<0&&(H=0,x+=Math.abs(D)),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,M,x),ce.baseTransform=ce.ctx.mozCurrentTransform.slice(),ce.executeOperatorList(w),ce.endDrawing(),{canvas:se.canvas,scaleX:X.scale,scaleY:Q.scale,offsetX:W,offsetY:H}}getSizeAndScale(p,w,A){p=Math.abs(p);let E=Math.max(h.MAX_PATTERN_SIZE,w),b=Math.ceil(p*A);return b>=E?b=E:A=b/p,{scale:A,size:b}}clipBbox(p,w,A,E,b){let C=E-w,k=b-A;p.ctx.rect(w,A,C,k),p.current.updateRectMinMax(p.ctx.mozCurrentTransform,[w,A,E,b]),p.clip(),p.endPath()}setFillAndStrokeStyleToContext(p,w,A){let E=p.ctx,b=p.current;switch(w){case g.COLORED:let C=this.ctx;E.fillStyle=C.fillStyle,E.strokeStyle=C.strokeStyle,b.fillColor=C.fillStyle,b.strokeColor=C.strokeStyle;break;case g.UNCOLORED:let k=r.Util.makeHexColor(A[0],A[1],A[2]);E.fillStyle=k,E.strokeStyle=k,b.fillColor=k,b.strokeColor=k;break;default:throw new r.FormatError(`Unsupported paint type: ${w}`)}}getPattern(p,w,A,E){let b=A;E!==o.SHADING&&(b=r.Util.transform(b,w.baseTransform),this.matrix&&(b=r.Util.transform(b,this.matrix)));let C=this.createPatternCanvas(w),k=new DOMMatrix(b);k=k.translate(C.offsetX,C.offsetY),k=k.scale(1/C.scaleX,1/C.scaleY);let R=p.createPattern(C.canvas,"repeat");try{R.setTransform(k)}catch(B){(0,r.warn)(`TilingPattern.getPattern: "${B==null?void 0:B.message}".`)}return R}}e.TilingPattern=h},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.applyMaskImageData=i;var r=t(1);function i({src:o,srcPos:s=0,dest:l,destPos:f=0,width:u,height:y,inverseDecode:m=!1}){let _=r.FeatureTest.isLittleEndian?4278190080:255,[v,g]=m?[0,_]:[_,0],h=u>>3,c=u&7,p=o.length;l=new Uint32Array(l.buffer);for(let w=0;w<y;w++){for(let E=s+h;s<E;s++){let b=s<p?o[s]:255;l[f++]=b&128?g:v,l[f++]=b&64?g:v,l[f++]=b&32?g:v,l[f++]=b&16?g:v,l[f++]=b&8?g:v,l[f++]=b&4?g:v,l[f++]=b&2?g:v,l[f++]=b&1?g:v}if(c===0)continue;let A=s<p?o[s++]:255;for(let E=0;E<c;E++)l[f++]=A&1<<7-E?g:v}return{srcPos:s,destPos:f}}},(n,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},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MessageHandler=void 0;var r=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,r.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),f.name){case"AbortException":return new r.AbortException(f.message);case"MissingPDFException":return new r.MissingPDFException(f.message);case"PasswordException":return new r.PasswordException(f.message,f.code);case"UnexpectedResponseException":return new r.UnexpectedResponseException(f.message,f.status);case"UnknownErrorException":return new r.UnknownErrorException(f.message,f.details);default:return new r.UnknownErrorException(f.message,f.toString())}}class l{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,c=this.callbackCapabilities[h];if(!c)throw new Error(`Cannot resolve callback ${h}`);if(delete this.callbackCapabilities[h],v.callback===i.DATA)c.resolve(v.data);else if(v.callback===i.ERROR)c.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,c=v.sourceName;new Promise(function(p){p(g(v.data))}).then(function(p){m.postMessage({sourceName:h,targetName:c,callback:i.DATA,callbackId:v.callbackId,data:p})},function(p){m.postMessage({sourceName:h,targetName:c,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,r.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,c=this.comObj;return new ReadableStream({start:p=>{let w=(0,r.createPromiseCapability)();return this.streamControllers[v]={controller:p,startCall:w,pullCall:null,cancelCall:null,isClosed:!1},c.postMessage({sourceName:g,targetName:h,action:u,streamId:v,data:y,desiredSize:p.desiredSize},_),w.promise},pull:p=>{let w=(0,r.createPromiseCapability)();return this.streamControllers[v].pullCall=w,c.postMessage({sourceName:g,targetName:h,stream:o.PULL,streamId:v,desiredSize:p.desiredSize}),w.promise},cancel:p=>{(0,r.assert)(p instanceof Error,"cancel must have a valid reason");let w=(0,r.createPromiseCapability)();return this.streamControllers[v].cancelCall=w,this.streamControllers[v].isClosed=!0,c.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],c={enqueue(p,w=1,A){if(this.isCancelled)return;let E=this.desiredSize;this.desiredSize-=w,E>0&&this.desiredSize<=0&&(this.sinkCapability=(0,r.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,r.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,r.createPromiseCapability)(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:u.desiredSize,ready:null};c.sinkCapability.resolve(),c.ready=c.sinkCapability.promise,this.streamSinks[y]=c,new Promise(function(p){p(h(u.data,c))}).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(c){c(h.onPull&&h.onPull())}).then(function(){v.postMessage({sourceName:m,targetName:_,stream:o.PULL_COMPLETE,streamId:y,success:!0})},function(c){v.postMessage({sourceName:m,targetName:_,stream:o.PULL_COMPLETE,streamId:y,reason:s(c)})});break;case o.ENQUEUE:if((0,r.assert)(g,"enqueue should have stream controller"),g.isClosed)break;g.controller.enqueue(u.chunk);break;case o.CLOSE:if((0,r.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,r.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(c){c(h.onCancel&&h.onCancel(s(u.reason)))}).then(function(){v.postMessage({sourceName:m,targetName:_,stream:o.CANCEL_COMPLETE,streamId:y,success:!0})},function(c){v.postMessage({sourceName:m,targetName:_,stream:o.CANCEL_COMPLETE,streamId:y,reason:s(c)})}),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=l},(n,e,t)=>{var o,s;Object.defineProperty(e,"__esModule",{value:!0}),e.Metadata=void 0;var r=t(1);class i{constructor({parsedData:f,rawData:u}){Tr(this,o,void 0);Tr(this,s,void 0);to(this,o,f),to(this,s,u)}getRaw(){return Lt(this,s)}get(f){return Lt(this,o).get(f)??null}getAll(){return(0,r.objectFromMap)(Lt(this,o))}has(f){return Lt(this,o).has(f)}}o=new WeakMap,s=new WeakMap,e.Metadata=i},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OptionalContentConfig=void 0;var r=t(1);class i{constructor(l,f){this.visible=!0,this.name=l,this.intent=f}}class o{constructor(l){if(this.name=null,this.creator=null,this._order=null,this._groups=new Map,l!==null){this.name=l.name,this.creator=l.creator,this._order=l.order;for(let f of l.groups)this._groups.set(f.id,new i(f.name,f.intent));if(l.baseState==="OFF")for(let f of this._groups)f.visible=!1;for(let f of l.on)this._groups.get(f).visible=!0;for(let f of l.off)this._groups.get(f).visible=!1}}_evaluateVisibilityExpression(l){let f=l.length;if(f<2)return!0;let u=l[0];for(let y=1;y<f;y++){let m=l[y],_;if(Array.isArray(m))_=this._evaluateVisibilityExpression(m);else if(this._groups.has(m))_=this._groups.get(m).visible;else return(0,r.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(l){if(this._groups.size===0)return!0;if(!l)return(0,r.warn)("Optional content group not defined."),!0;if(l.type==="OCG")return this._groups.has(l.id)?this._groups.get(l.id).visible:((0,r.warn)(`Optional content group not found: ${l.id}`),!0);if(l.type==="OCMD"){if(l.expression)return this._evaluateVisibilityExpression(l.expression);if(!l.policy||l.policy==="AnyOn"){for(let f of l.ids){if(!this._groups.has(f))return(0,r.warn)(`Optional content group not found: ${f}`),!0;if(this._groups.get(f).visible)return!0}return!1}else if(l.policy==="AllOn"){for(let f of l.ids){if(!this._groups.has(f))return(0,r.warn)(`Optional content group not found: ${f}`),!0;if(!this._groups.get(f).visible)return!1}return!0}else if(l.policy==="AnyOff"){for(let f of l.ids){if(!this._groups.has(f))return(0,r.warn)(`Optional content group not found: ${f}`),!0;if(!this._groups.get(f).visible)return!0}return!1}else if(l.policy==="AllOff"){for(let f of l.ids){if(!this._groups.has(f))return(0,r.warn)(`Optional content group not found: ${f}`),!0;if(this._groups.get(f).visible)return!1}return!0}return(0,r.warn)(`Unknown optional content policy ${l.policy}.`),!0}return(0,r.warn)(`Unknown group type ${l.type}.`),!0}setVisibility(l,f=!0){if(!this._groups.has(l)){(0,r.warn)(`Optional content group not found: ${l}`);return}this._groups.get(l).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,r.objectFromMap)(this._groups):null}getGroup(l){return this._groups.get(l)||null}}e.OptionalContentConfig=o},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PDFDataTransportStream=void 0;var r=t(1),i=t(5);class o{constructor(u,y){(0,r.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,r.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,r.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 l(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,r.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 l{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,r.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)}}},(n,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 l(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)l(_)}return l(i),s}static shouldBuildText(i){return!(i==="textarea"||i==="input"||i==="option"||i==="select")}}e.XfaText=t},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NodeStandardFontDataFactory=e.NodeCanvasFactory=e.NodeCMapReaderFactory=void 0;var r=t(6);let i=function(f){return new Promise((u,y)=>{pf().readFile(f,(_,v)=>{if(_||!v){y(new Error(_));return}u(new Uint8Array(v))})})};class o extends r.BaseCanvasFactory{_createCanvas(u,y){return IE().createCanvas(u,y)}}e.NodeCanvasFactory=o;class s extends r.BaseCMapReaderFactory{_fetchData(u,y){return i(u).then(m=>({cMapData:m,compressionType:y}))}}e.NodeCMapReaderFactory=s;class l extends r.BaseStandardFontDataFactory{_fetchData(u){return i(u)}}e.NodeStandardFontDataFactory=l},(n,e,t)=>{var W,tm;Object.defineProperty(e,"__esModule",{value:!0}),e.AnnotationLayer=void 0;var r=t(1),i=t(5),o=t(8),s=t(21),l=t(22);let f=1e3,u=new WeakSet;function y(M){return{width:M[2]-M[0],height:M[3]-M[1]}}class m{static create(x){switch(x.data.annotationType){case r.AnnotationType.LINK:return new v(x);case r.AnnotationType.TEXT:return new g(x);case r.AnnotationType.WIDGET:switch(x.data.fieldType){case"Tx":return new c(x);case"Btn":return x.data.radioButton?new w(x):x.data.checkBox?new p(x):new A(x);case"Ch":return new E(x)}return new h(x);case r.AnnotationType.POPUP:return new b(x);case r.AnnotationType.FREETEXT:return new k(x);case r.AnnotationType.LINE:return new R(x);case r.AnnotationType.SQUARE:return new B(x);case r.AnnotationType.CIRCLE:return new I(x);case r.AnnotationType.POLYLINE:return new D(x);case r.AnnotationType.CARET:return new z(x);case r.AnnotationType.INK:return new q(x);case r.AnnotationType.POLYGON:return new F(x);case r.AnnotationType.HIGHLIGHT:return new G(x);case r.AnnotationType.UNDERLINE:return new Y(x);case r.AnnotationType.SQUIGGLY:return new X(x);case r.AnnotationType.STRIKEOUT:return new Q(x);case r.AnnotationType.STAMP:return new se(x);case r.AnnotationType.FILEATTACHMENT:return new ve(x);default:return new _(x)}}}class _{constructor(x,{isRenderable:T=!1,ignoreBorder:P=!1,createQuadrilaterals:N=!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(P)),N&&(this.quadrilaterals=this._createQuadrilaterals(P))}_createContainer(x=!1){let T=this.data,P=this.page,N=this.viewport,U=document.createElement("section"),{width:V,height:Z}=y(T.rect);U.setAttribute("data-annotation-id",T.id);let re=r.Util.normalizeRect([T.rect[0],P.view[3]-T.rect[1]+P.view[1],T.rect[2],P.view[3]-T.rect[3]+P.view[1]]);if(T.hasOwnCanvas){let ne=N.transform.slice(),[ae,fe]=r.Util.singularValueDecompose2dScale(ne);V=Math.ceil(V*ae),Z=Math.ceil(Z*fe),re[0]*=ae,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(${N.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!==r.AnnotationBorderStyleType.UNDERLINE&&(V-=2*T.borderStyle.width,Z-=2*T.borderStyle.width);let ne=T.borderStyle.horizontalCornerRadius,ae=T.borderStyle.verticalCornerRadius;if(ne>0||ae>0){let he=`${ne}px / ${ae}px`;U.style.borderRadius=he}switch(T.borderStyle.style){case r.AnnotationBorderStyleType.SOLID:U.style.borderStyle="solid";break;case r.AnnotationBorderStyleType.DASHED:U.style.borderStyle="dashed";break;case r.AnnotationBorderStyleType.BEVELED:(0,r.warn)("Unimplemented border style: beveled");break;case r.AnnotationBorderStyleType.INSET:(0,r.warn)("Unimplemented border style: inset");break;case r.AnnotationBorderStyleType.UNDERLINE:U.style.borderBottomStyle="solid";break;default:break}T.borderColor||T.color||null?U.style.borderColor=r.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=`${V}px`,U.style.height=`${Z}px`),U}get _commonActions(){let x=(T,P,N)=>{let U=N.detail[T];N.target.style[P]=s.ColorConverters[`${U[0]}_HTML`](U.slice(1))};return(0,r.shadow)(this,"_commonActions",{display:T=>{let P=T.detail.display%2===1;T.target.style.visibility=P?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{hidden:P,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 P=this._commonActions;for(let N of Object.keys(T.detail)){let U=x[N]||P[N];U&&U(T)}}_setDefaultPropertiesFromJS(x){if(!this.enableScripting)return;let T=this.annotationStorage.getRawValue(this.data.id);if(!T)return;let P=this._commonActions;for(let[N,U]of Object.entries(T)){let V=P[N];V&&(V({detail:U,target:x}),delete T[N])}}_createQuadrilaterals(x=!1){if(!this.data.quadPoints)return null;let T=[],P=this.data.rect;for(let N of this.data.quadPoints)this.data.rect=[N[2].x,N[2].y,N[1].x,N[1].y],T.push(this._createContainer(x));return this.data.rect=P,T}_createPopup(x,T){let P=this.container;this.quadrilaterals&&(x=x||this.quadrilaterals,P=this.quadrilaterals[0]),x||(x=document.createElement("div"),x.style.height=P.style.height,x.style.width=P.style.width,P.appendChild(x));let U=new C({container:P,trigger:x,color:T.color,titleObj:T.titleObj,modificationDate:T.modificationDate,contentsObj:T.contentsObj,richText:T.richText,hideWrapper:!0}).render();U.style.left=P.style.width,P.appendChild(U)}_renderQuadrilaterals(x){for(let T of this.quadrilaterals)T.className=x;return this.quadrilaterals}render(){(0,r.unreachable)("Abstract method `AnnotationElement.render` called")}_getElementsByName(x,T=null){let P=[];if(this._fieldObjects){let N=this._fieldObjects[x];if(N)for(let{page:U,id:V,exportValues:Z}of N){if(U===-1||V===T)continue;let re=typeof Z=="string"?Z:null,ne=document.getElementById(V);if(ne&&!u.has(ne)){(0,r.warn)(`_getElementsByName - element not allowed: ${V}`);continue}P.push({id:V,exportValue:re,domElement:ne})}return P}for(let N of document.getElementsByName(x)){let{id:U,exportValue:V}=N;U!==T&&u.has(N)&&P.push({id:U,exportValue:V,domElement:N})}return P}static get platform(){let x=typeof navigator<"u"?navigator.platform:"";return(0,r.shadow)(this,"platform",{isWin:x.includes("Win"),isMac:x.includes("Mac")})}}class v extends _{constructor(x,T=null){let P=!!(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:P,ignoreBorder:!!(T!=null&&T.ignoreBorder),createQuadrilaterals:!0})}render(){let{data:x,linkService:T}=this,P=document.createElement("a");if(x.url)T.addLinkAttributes(P,x.url,x.newWindow);else if(x.action)this._bindNamedAction(P,x.action);else if(x.dest)this._bindLink(P,x.dest);else{let N=!1;x.actions&&(x.actions.Action||x.actions["Mouse Up"]||x.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(N=!0,this._bindJSAction(P,x)),x.resetForm?this._bindResetFormAction(P,x.resetForm):N||this._bindLink(P,"")}return this.quadrilaterals?this._renderQuadrilaterals("linkAnnotation").map((N,U)=>{let V=U===0?P:P.cloneNode();return N.appendChild(V),N}):(this.container.className="linkAnnotation",this.container.appendChild(P),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 P=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(let N of Object.keys(T.actions)){let U=P.get(N);U&&(x[U]=()=>{var V;return(V=this.linkService.eventBus)==null||V.dispatch("dispatcheventinsandbox",{source:this,detail:{id:T.id,name:N}}),!1})}x.onclick||(x.onclick=()=>!1),x.className="internalLink"}_bindResetFormAction(x,T){let P=x.onclick;if(P||(x.href=this.linkService.getAnchorUrl("")),x.className="internalLink",!this._fieldObjects){(0,r.warn)('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),P||(x.onclick=()=>!1);return}x.onclick=()=>{var ae;P&&P();let{fields:N,refs:U,include:V}=T,Z=[];if(N.length!==0||U.length!==0){let fe=new Set(U);for(let he of N){let Te=this._fieldObjects[he]||[];for(let{id:Ne}of Te)fe.add(Ne)}for(let he of Object.values(this._fieldObjects))for(let Te of he)fe.has(Te.id)===V&&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 Ne=fe.defaultValue||"";re.setValue(he,{value:Ne});break}case"checkbox":case"radiobutton":{let Ne=fe.defaultValue===fe.exportValues;re.setValue(he,{value:Ne});break}case"combobox":case"listbox":{let Ne=fe.defaultValue||"";re.setValue(he,{value:Ne});break}default:continue}let Te=document.getElementById(he);!Te||!u.has(Te)||Te.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((ae=this.linkService.eventBus)==null||ae.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:ne,name:"ResetForm"}})),!1}}}class g extends _{constructor(x){var P,N,U;let T=!!(x.data.hasPopup||(P=x.data.titleObj)!=null&&P.str||(N=x.data.contentsObj)!=null&&N.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:P}=_.platform;return T&&x.ctrlKey||P&&x.metaKey}_setEventListener(x,T,P,N){T.includes("mouse")?x.addEventListener(T,U=>{var V;(V=this.linkService.eventBus)==null||V.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:P,value:N(U),shift:U.shiftKey,modifier:this._getKeyModifier(U)}})}):x.addEventListener(T,U=>{var V;(V=this.linkService.eventBus)==null||V.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:P,value:N(U)}})})}_setEventListeners(x,T,P){var N;for(let[U,V]of T)(V==="Action"||(N=this.data.actions)!=null&&N[V])&&this._setEventListener(x,U,V,P)}_setBackgroundColor(x){let T=this.data.backgroundColor||null;x.style.backgroundColor=T===null?"transparent":r.Util.makeHexColor(T[0],T[1],T[2])}}class c extends h{constructor(x){let T=x.renderForms||!x.data.hasAppearance&&!!x.data.fieldValue;super(x,{isRenderable:T})}setPropertyOnSiblings(x,T,P,N){let U=this.annotationStorage;for(let V of this._getElementsByName(x.name,x.id))V.domElement&&(V.domElement[T]=P),U.setValue(V.id,{[N]:P})}render(){var N;let x=this.annotationStorage,T=this.data.id;this.container.className="textWidgetAnnotation";let P=null;if(this.renderForms){let U=x.getValue(T,{value:this.data.fieldValue}),V=U.formattedValue||U.value||"",Z={userValue:null,formattedValue:null,valueOnFocus:""};this.data.multiLine?(P=document.createElement("textarea"),P.textContent=V):(P=document.createElement("input"),P.type="text",P.setAttribute("value",V)),u.add(P),P.disabled=this.data.readOnly,P.name=this.data.fieldName,P.tabIndex=f,Z.userValue=V,P.setAttribute("id",T),P.addEventListener("input",ne=>{x.setValue(T,{value:ne.target.value}),this.setPropertyOnSiblings(P,"value",ne.target.value,"value")}),P.addEventListener("resetform",ne=>{let ae=this.data.defaultFieldValue??"";P.value=Z.userValue=ae,Z.formattedValue=null});let re=ne=>{let{formattedValue:ae}=Z;ae!=null&&(ne.target.value=ae),ne.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){P.addEventListener("focus",ae=>{Z.userValue&&(ae.target.value=Z.userValue),Z.valueOnFocus=ae.target.value}),P.addEventListener("updatefromsandbox",ae=>{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,ae)}),P.addEventListener("keydown",ae=>{var Te;let fe=-1;if(ae.key==="Escape"?fe=0:ae.key==="Enter"?fe=2:ae.key==="Tab"&&(fe=3),fe===-1)return;let{value:he}=ae.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:ae.target.selectionStart,selEnd:ae.target.selectionEnd}}))});let ne=re;re=null,P.addEventListener("blur",ae=>{var he;let{value:fe}=ae.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:ae.target.selectionStart,selEnd:ae.target.selectionEnd}})),ne(ae)}),(N=this.data.actions)!=null&&N.Keystroke&&P.addEventListener("beforeinput",ae=>{var Ee;let{data:fe,target:he}=ae,{value:Te,selectionStart:Ne,selectionEnd:Se}=he,ye=Ne,oe=Se;switch(ae.inputType){case"deleteWordBackward":{let xe=Te.substring(0,Ne).match(/\w*[^\w]*$/);xe&&(ye-=xe[0].length);break}case"deleteWordForward":{let xe=Te.substring(Ne).match(/^[^\w]*\w*/);xe&&(oe+=xe[0].length);break}case"deleteContentBackward":Ne===Se&&(ye-=1);break;case"deleteContentForward":Ne===Se&&(oe+=1);break}ae.preventDefault(),(Ee=this.linkService.eventBus)==null||Ee.dispatch("dispatcheventinsandbox",{source:this,detail:{id:T,name:"Keystroke",value:Te,change:fe||"",willCommit:!1,selStart:ye,selEnd:oe}})}),this._setEventListeners(P,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],ae=>ae.target.value)}if(re&&P.addEventListener("blur",re),this.data.maxLen!==null&&(P.maxLength=this.data.maxLen),this.data.comb){let ae=(this.data.rect[2]-this.data.rect[0])/this.data.maxLen;P.classList.add("comb"),P.style.letterSpacing=`calc(${ae}px - 1ch)`}}else P=document.createElement("div"),P.textContent=this.data.fieldValue,P.style.verticalAlign="middle",P.style.display="table-cell";return this._setTextStyle(P),this._setBackgroundColor(P),this._setDefaultPropertiesFromJS(P),this.container.appendChild(P),this.container}_setTextStyle(x){let T=["left","center","right"],{fontSize:P,fontColor:N}=this.data.defaultAppearanceData,U=x.style;P&&(U.fontSize=`${P}px`),U.color=r.Util.makeHexColor(N[0],N[1],N[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,P=T.id,N=x.getValue(P,{value:T.exportValue===T.fieldValue}).value;typeof N=="string"&&(N=N!=="Off",x.setValue(P,{value:N})),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,N&&U.setAttribute("checked",!0),U.setAttribute("id",P),U.setAttribute("exportValue",T.exportValue),U.tabIndex=f,U.addEventListener("change",V=>{let{name:Z,checked:re}=V.target;for(let ne of this._getElementsByName(Z,P)){let ae=re&&ne.exportValue===T.exportValue;ne.domElement&&(ne.domElement.checked=ae),x.setValue(ne.id,{value:ae})}x.setValue(P,{value:re})}),U.addEventListener("resetform",V=>{let Z=T.defaultFieldValue||"Off";V.target.checked=Z===T.exportValue}),this.enableScripting&&this.hasJSActions&&(U.addEventListener("updatefromsandbox",V=>{let Z={value(re){re.target.checked=re.detail.value!=="Off",x.setValue(P,{value:re.target.checked})}};this._dispatchEventFromSandbox(Z,V)}),this._setEventListeners(U,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],V=>V.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,P=T.id,N=x.getValue(P,{value:T.fieldValue===T.buttonValue}).value;typeof N=="string"&&(N=N!==T.buttonValue,x.setValue(P,{value:N}));let U=document.createElement("input");if(u.add(U),U.disabled=T.readOnly,U.type="radio",U.name=T.fieldName,N&&U.setAttribute("checked",!0),U.setAttribute("id",P),U.tabIndex=f,U.addEventListener("change",V=>{let{name:Z,checked:re}=V.target;for(let ne of this._getElementsByName(Z,P))x.setValue(ne.id,{value:!1});x.setValue(P,{value:re})}),U.addEventListener("resetform",V=>{let Z=T.defaultFieldValue;V.target.checked=Z!=null&&Z===T.buttonValue}),this.enableScripting&&this.hasJSActions){let V=T.buttonValue;U.addEventListener("updatefromsandbox",Z=>{let re={value:ne=>{let ae=V===ne.detail.value;for(let fe of this._getElementsByName(ne.target.name)){let he=ae&&fe.id===P;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 E extends h{constructor(x){super(x,{isRenderable:x.renderForms})}render(){this.container.className="choiceWidgetAnnotation";let x=this.annotationStorage,T=this.data.id,P=x.getValue(T,{value:this.data.fieldValue}),{fontSize:N}=this.data.defaultAppearanceData;N||(N=9);let U=`calc(${N}px * var(--zoom-factor))`,V=document.createElement("select");u.add(V),V.disabled=this.data.readOnly,V.name=this.data.fieldName,V.setAttribute("id",T),V.tabIndex=f,V.style.fontSize=`${N}px`,this.data.combo||(V.size=this.data.options.length,this.data.multiSelect&&(V.multiple=!0)),V.addEventListener("resetform",ne=>{let ae=this.data.defaultFieldValue;for(let fe of V.options)fe.selected=fe.value===ae});for(let ne of this.data.options){let ae=document.createElement("option");ae.textContent=ne.displayValue,ae.value=ne.exportValue,this.data.combo&&(ae.style.fontSize=U),P.value.includes(ne.exportValue)&&ae.setAttribute("selected",!0),V.appendChild(ae)}let Z=(ne,ae)=>{let fe=ae?"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 ae=ne.target.options;return Array.prototype.map.call(ae,fe=>({displayValue:fe.textContent,exportValue:fe.value}))};return this.enableScripting&&this.hasJSActions?(V.addEventListener("updatefromsandbox",ne=>{let ae={value(fe){let he=fe.detail.value,Te=new Set(Array.isArray(he)?he:[he]);for(let Ne of V.options)Ne.selected=Te.has(Ne.value);x.setValue(T,{value:Z(fe,!0)})},multipleSelection(fe){V.multiple=!0},remove(fe){let he=V.options,Te=fe.detail.remove;he[Te].selected=!1,V.remove(Te),he.length>0&&Array.prototype.findIndex.call(he,Se=>Se.selected)===-1&&(he[0].selected=!0),x.setValue(T,{value:Z(fe,!0),items:re(fe)})},clear(fe){for(;V.length!==0;)V.remove(0);x.setValue(T,{value:null,items:[]})},insert(fe){let{index:he,displayValue:Te,exportValue:Ne}=fe.detail.insert,Se=document.createElement("option");Se.textContent=Te,Se.value=Ne,V.insertBefore(Se,V.children[he]),x.setValue(T,{value:Z(fe,!0),items:re(fe)})},items(fe){let{items:he}=fe.detail;for(;V.length!==0;)V.remove(0);for(let Te of he){let{displayValue:Ne,exportValue:Se}=Te,ye=document.createElement("option");ye.textContent=Ne,ye.value=Se,V.appendChild(ye)}V.options.length>0&&(V.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(ae,ne)}),V.addEventListener("input",ne=>{var he;let ae=Z(ne,!0),fe=Z(ne,!1);x.setValue(T,{value:ae}),(he=this.linkService.eventBus)==null||he.dispatch("dispatcheventinsandbox",{source:this,detail:{id:T,name:"Keystroke",value:fe,changeEx:ae,willCommit:!0,commitKey:1,keyDown:!1}})}),this._setEventListeners(V,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"]],ne=>ne.target.checked)):V.addEventListener("input",function(ne){x.setValue(T,{value:Z(ne,!0)})}),this._setBackgroundColor(V),this._setDefaultPropertiesFromJS(V),this.container.appendChild(V),this.container}}class b extends _{constructor(x){var P,N,U;let T=!!((P=x.data.titleObj)!=null&&P.str||(N=x.data.contentsObj)!=null&&N.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}"]`,P=this.layer.querySelectorAll(T);if(P.length===0)return this.container;let N=new C({container:this.container,trigger:Array.from(P),color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText}),U=this.page,V=r.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=V[0]+this.data.parentRect[2]-this.data.parentRect[0],re=V[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(N.render()),this.container}}class C{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 P=document.createElement("div");P.className="popup";let N=this.color;if(N){let ne=.7*(255-N[0])+N[0],ae=.7*(255-N[1])+N[1],fe=.7*(255-N[2])+N[2];P.style.backgroundColor=r.Util.makeHexColor(ne|0,ae|0,fe|0)}let U=document.createElement("h1");U.dir=this.titleObj.dir,U.textContent=this.titleObj.str,P.appendChild(U);let V=i.PDFDateString.toDateObject(this.modificationDate);if(V){let ne=document.createElement("span");ne.className="popupDate",ne.textContent="{{date}}, {{time}}",ne.dataset.l10nId="annotation_date_string",ne.dataset.l10nArgs=JSON.stringify({date:V.toLocaleDateString(),time:V.toLocaleTimeString()}),P.appendChild(ne)}if((Z=this.richText)!=null&&Z.str&&(!((re=this.contentsObj)!=null&&re.str)||this.contentsObj.str===this.richText.str))l.XfaLayer.render({xfaHtml:this.richText.html,intent:"richText",div:P}),P.lastChild.className="richText popupContent";else{let ne=this._formatContents(this.contentsObj);P.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 P.addEventListener("click",this._hide.bind(this,!0)),T.appendChild(P),T}_formatContents({str:x,dir:T}){let P=document.createElement("p");P.className="popupContent",P.dir=T;let N=x.split(/(?:\r\n?|\n)/);for(let U=0,V=N.length;U<V;++U){let Z=N[U];P.appendChild(document.createTextNode(Z)),U<V-1&&P.appendChild(document.createElement("br"))}return P}_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 P,N,U;let T=!!(x.data.hasPopup||(P=x.data.titleObj)!=null&&P.str||(N=x.data.contentsObj)!=null&&N.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 R extends _{constructor(x){var P,N,U;let T=!!(x.data.hasPopup||(P=x.data.titleObj)!=null&&P.str||(N=x.data.contentsObj)!=null&&N.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:P}=y(x.rect),N=this.svgFactory.create(T,P),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"),N.appendChild(U),this.container.append(N),this._createPopup(U,x),this.container}}class B extends _{constructor(x){var P,N,U;let T=!!(x.data.hasPopup||(P=x.data.titleObj)!=null&&P.str||(N=x.data.contentsObj)!=null&&N.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:P}=y(x.rect),N=this.svgFactory.create(T,P),U=x.borderStyle.width,V=this.svgFactory.createElement("svg:rect");return V.setAttribute("x",U/2),V.setAttribute("y",U/2),V.setAttribute("width",T-U),V.setAttribute("height",P-U),V.setAttribute("stroke-width",U||1),V.setAttribute("stroke","transparent"),V.setAttribute("fill","transparent"),N.appendChild(V),this.container.append(N),this._createPopup(V,x),this.container}}class I extends _{constructor(x){var P,N,U;let T=!!(x.data.hasPopup||(P=x.data.titleObj)!=null&&P.str||(N=x.data.contentsObj)!=null&&N.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:P}=y(x.rect),N=this.svgFactory.create(T,P),U=x.borderStyle.width,V=this.svgFactory.createElement("svg:ellipse");return V.setAttribute("cx",T/2),V.setAttribute("cy",P/2),V.setAttribute("rx",T/2-U/2),V.setAttribute("ry",P/2-U/2),V.setAttribute("stroke-width",U||1),V.setAttribute("stroke","transparent"),V.setAttribute("fill","transparent"),N.appendChild(V),this.container.append(N),this._createPopup(V,x),this.container}}class D extends _{constructor(x){var P,N,U;let T=!!(x.data.hasPopup||(P=x.data.titleObj)!=null&&P.str||(N=x.data.contentsObj)!=null&&N.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:P}=y(x.rect),N=this.svgFactory.create(T,P),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 V=this.svgFactory.createElement(this.svgElementName);return V.setAttribute("points",U),V.setAttribute("stroke-width",x.borderStyle.width||1),V.setAttribute("stroke","transparent"),V.setAttribute("fill","transparent"),N.appendChild(V),this.container.append(N),this._createPopup(V,x),this.container}}class F extends D{constructor(x){super(x),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class z extends _{constructor(x){var P,N,U;let T=!!(x.data.hasPopup||(P=x.data.titleObj)!=null&&P.str||(N=x.data.contentsObj)!=null&&N.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 P,N,U;let T=!!(x.data.hasPopup||(P=x.data.titleObj)!=null&&P.str||(N=x.data.contentsObj)!=null&&N.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:P}=y(x.rect),N=this.svgFactory.create(T,P);for(let U of x.inkLists){let V=[];for(let re of U){let ne=re.x-x.rect[0],ae=x.rect[3]-re.y;V.push(`${ne},${ae}`)}V=V.join(" ");let Z=this.svgFactory.createElement(this.svgElementName);Z.setAttribute("points",V),Z.setAttribute("stroke-width",x.borderStyle.width||1),Z.setAttribute("stroke","transparent"),Z.setAttribute("fill","transparent"),this._createPopup(Z,x),N.appendChild(Z)}return this.container.append(N),this.container}}class G extends _{constructor(x){var P,N,U;let T=!!(x.data.hasPopup||(P=x.data.titleObj)!=null&&P.str||(N=x.data.contentsObj)!=null&&N.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 P,N,U;let T=!!(x.data.hasPopup||(P=x.data.titleObj)!=null&&P.str||(N=x.data.contentsObj)!=null&&N.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 P,N,U;let T=!!(x.data.hasPopup||(P=x.data.titleObj)!=null&&P.str||(N=x.data.contentsObj)!=null&&N.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 P,N,U;let T=!!(x.data.hasPopup||(P=x.data.titleObj)!=null&&P.str||(N=x.data.contentsObj)!=null&&N.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 se extends _{constructor(x){var P,N,U;let T=!!(x.data.hasPopup||(P=x.data.titleObj)!=null&&P.str||(N=x.data.contentsObj)!=null&&N.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 N;super(x,{isRenderable:!0});let{filename:T,content:P}=this.data.file;this.filename=(0,i.getFilenameFromUrl)(T),this.content=P,(N=this.linkService.eventBus)==null||N.dispatch("fileattachmentannotation",{source:this,filename:T,content:P})}render(){var T,P;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||(P=this.data.contentsObj)!=null&&P.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=[],P=[];for(let U of x.annotations){if(!U)continue;let{width:V,height:Z}=y(U.rect);if(!(V<=0||Z<=0)){if(U.annotationType===r.AnnotationType.POPUP){P.push(U);continue}T.push(U)}}P.length&&T.push(...P);let N=x.div;for(let U of T){let V=m.create({data:U,layer:N,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(V.isRenderable){let Z=V.render();if(U.hidden&&(Z.style.visibility="hidden"),Array.isArray(Z))for(let re of Z)N.appendChild(re);else V instanceof b?N.prepend(Z):N.appendChild(Z)}}ro(this,W,tm).call(this,N,x.annotationCanvasMap)}static update(x){let{page:T,viewport:P,annotations:N,annotationCanvasMap:U,div:V}=x,Z=P.transform,re=`matrix(${Z.join(",")})`,ne,ae;for(let fe of N){let he=V.querySelectorAll(`[data-annotation-id="${fe.id}"]`);if(he)for(let Te of he)if(fe.hasOwnCanvas){let Ne=r.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(!ae){ne=Math.abs(Z[0]||Z[1]);let oe=Z.slice();for(let Ee=0;Ee<4;Ee++)oe[Ee]=Math.sign(oe[Ee]);ae=`matrix(${oe.join(",")})`}let Se=Ne[0]*ne,ye=Ne[1]*ne;Te.style.left=`${Se}px`,Te.style.top=`${ye}px`,Te.style.transformOrigin=`${-Se}px ${-ye}px`,Te.style.transform=ae}else Te.style.transform=re}ro(this,W,tm).call(this,V,U),V.hidden=!1}}W=new WeakSet,tm=function(x,T){if(T){for(let[P,N]of T){let U=x.querySelector(`[data-annotation-id="${P}"]`);if(!U)continue;let{firstChild:V}=U;V.nodeName==="CANVAS"?U.replaceChild(N,V):U.insertBefore(N,V)}T.clear()}},Tr(ce,W),e.AnnotationLayer=ce},(n,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 r{static CMYK_G([o,s,l,f]){return["G",1-Math.min(1,.3*o+.59*l+.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,l]){return["G",.3*o+.59*s+.11*l]}static RGB_HTML([o,s,l]){let f=t(o),u=t(s),y=t(l);return`#${f}${u}${y}`}static T_HTML(){return"#00000000"}static CMYK_RGB([o,s,l,f]){return["RGB",1-Math.min(1,o+f),1-Math.min(1,l+f),1-Math.min(1,s+f)]}static CMYK_HTML(o){return this.RGB_HTML(this.CMYK_RGB(o))}static RGB_CMYK([o,s,l]){let f=1-o,u=1-s,y=1-l,m=Math.min(f,u,y);return["CMYK",f,u,y,m]}}e.ColorConverters=r},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.XfaLayer=void 0;var r=t(18);class i{static setupStorage(s,l,f,u,y){let m=u.getValue(l,{value:null});switch(f.name){case"textarea":if(m.value!==null&&(s.textContent=m.value),y==="print")break;s.addEventListener("input",_=>{u.setValue(l,{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(l,{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(l,{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(l,{value:g})});break}}static setAttributes({html:s,element:l,storage:f=null,intent:u,linkService:y}){let{attributes:m}=l,_=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,l,f)}static render(s){var h;let l=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 c=`matrix(${s.viewport.transform.join(",")})`;v.style.transform=c}y!=="richText"&&v.setAttribute("class","xfaLayer xfaFont");let g=[];for(;_.length>0;){let[c,p,w]=_[_.length-1];if(p+1===c.children.length){_.pop();continue}let A=c.children[++_[_.length-1][1]];if(A===null)continue;let{name:E}=A;if(E==="#text"){let C=document.createTextNode(A.value);g.push(C),w.appendChild(C);continue}let b;if((h=A==null?void 0:A.attributes)!=null&&h.xmlns?b=document.createElementNS(A.attributes.xmlns,E):b=document.createElement(E),w.appendChild(b),A.attributes&&this.setAttributes({html:b,element:A,storage:l,intent:y,linkService:f}),A.children&&A.children.length>0)_.push([A,-1,b]);else if(A.value){let C=document.createTextNode(A.value);r.XfaText.shouldBuildText(E)&&g.push(C),b.appendChild(C)}}for(let c of v.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))c.setAttribute("readOnly",!0);return{textDivs:g}}static update(s){let l=`matrix(${s.viewport.transform.join(",")})`;s.div.style.transform=l,s.div.hidden=!1}}e.XfaLayer=i},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.renderTextLayer=p;var r=t(1);let i=1e5,o=30,s=.8,l=new Map,f=/^\s+$/g;function u(w,A){let E=l.get(w);if(E)return E;A.save(),A.font=`${o}px ${w}`;let b=A.measureText(""),C=b.fontBoundingBoxAscent,k=Math.abs(b.fontBoundingBoxDescent);if(C){A.restore();let B=C/(C+k);return l.set(w,B),B}A.strokeStyle="red",A.clearRect(0,0,o,o),A.strokeText("g",0,0);let R=A.getImageData(0,0,o,o).data;k=0;for(let B=R.length-1-3;B>=0;B-=4)if(R[B]>0){k=Math.ceil(B/4/o);break}A.clearRect(0,0,o,o),A.strokeText("A",0,o),R=A.getImageData(0,0,o,o).data,C=0;for(let B=0,I=R.length;B<I;B+=4)if(R[B]>0){C=o-Math.floor(B/4/o);break}if(A.restore(),C){let B=C/(C+k);return l.set(w,B),B}return l.set(w,s),s}function y(w,A,E,b){let C=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(C);let R=r.Util.transform(w._viewport.transform,A.transform),B=Math.atan2(R[1],R[0]),I=E[A.fontName];I.vertical&&(B+=Math.PI/2);let D=Math.hypot(R[2],R[3]),F=D*u(I.fontFamily,b),z,q;B===0?(z=R[4],q=R[5]-F):(z=R[4]+F*Math.sin(B),q=R[5]-F*Math.cos(B)),C.style.left=`${z}px`,C.style.top=`${q}px`,C.style.fontSize=`${D}px`,C.style.fontFamily=I.fontFamily,C.setAttribute("role","presentation"),C.textContent=A.str,C.dir=A.dir,w._fontInspectorEnabled&&(C.dataset.fontName=A.fontName),B!==0&&(k.angle=B*(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&&(I.vertical?k.canvasWidth=A.height*w._viewport.scale:k.canvasWidth=A.width*w._viewport.scale),w._textDivProperties.set(C,k),w._textContentStream&&w._layoutText(C),w._enhanceTextSelection&&k.hasText){let Y=1,X=0;B!==0&&(Y=Math.cos(B),X=Math.sin(B));let Q=(I.vertical?A.height:A.width)*w._viewport.scale,se=D,ve,ce;B!==0?(ve=[Y,X,-X,Y,z,q],ce=r.Util.getAxialAlignedBoundingBox([0,0,Q,se],ve)):ce=[z,q,z+Q,q+se],w._bounds.push({left:ce[0],top:ce[1],right:ce[2],bottom:ce[3],div:C,size:[Q,se],m:ve})}}function m(w){if(w._canceled)return;let A=w._textDivs,E=w._capability,b=A.length;if(b>i){w._renderingDone=!0,E.resolve();return}if(!w._textContentStream)for(let C=0;C<b;C++)w._layoutText(A[C]);w._renderingDone=!0,E.resolve()}function _(w,A,E){let b=0;for(let C=0;C<E;C++){let k=w[A++];k>0&&(b=b?Math.min(k,b):k)}return b}function v(w){let A=w._bounds,E=w._viewport,b=g(E.width,E.height,A);for(let C=0;C<b.length;C++){let k=A[C].div,R=w._textDivProperties.get(k);if(R.angle===0){R.paddingLeft=A[C].left-b[C].left,R.paddingTop=A[C].top-b[C].top,R.paddingRight=b[C].right-A[C].right,R.paddingBottom=b[C].bottom-A[C].bottom,w._textDivProperties.set(k,R);continue}let B=b[C],I=A[C],D=I.m,F=D[0],z=D[1],q=[[0,0],[0,I.size[1]],[I.size[0],0],I.size],G=new Float64Array(64);for(let X=0,Q=q.length;X<Q;X++){let se=r.Util.applyTransform(q[X],D);G[X+0]=F&&(B.left-se[0])/F,G[X+4]=z&&(B.top-se[1])/z,G[X+8]=F&&(B.right-se[0])/F,G[X+12]=z&&(B.bottom-se[1])/z,G[X+16]=z&&(B.left-se[0])/-z,G[X+20]=F&&(B.top-se[1])/F,G[X+24]=z&&(B.right-se[0])/-z,G[X+28]=F&&(B.bottom-se[1])/F,G[X+32]=F&&(B.left-se[0])/-F,G[X+36]=z&&(B.top-se[1])/-z,G[X+40]=F&&(B.right-se[0])/-F,G[X+44]=z&&(B.bottom-se[1])/-z,G[X+48]=z&&(B.left-se[0])/z,G[X+52]=F&&(B.top-se[1])/-F,G[X+56]=z&&(B.right-se[0])/z,G[X+60]=F&&(B.bottom-se[1])/-F}let Y=1+Math.min(Math.abs(F),Math.abs(z));R.paddingLeft=_(G,32,16)/Y,R.paddingTop=_(G,48,16)/Y,R.paddingRight=_(G,0,16)/Y,R.paddingBottom=_(G,16,16)/Y,w._textDivProperties.set(k,R)}}function g(w,A,E){let b=E.map(function(k,R){return{x1:k.left,y1:k.top,x2:k.right,y2:k.bottom,index:R,x1New:void 0,x2New:void 0}});h(w,b);let C=new Array(E.length);for(let k of b){let R=k.index;C[R]={left:k.x1New,top:0,right:k.x2New,bottom:0}}E.map(function(k,R){let B=C[R],I=b[R];I.x1=k.top,I.y1=w-B.right,I.x2=k.bottom,I.y2=w-B.left,I.index=R,I.x1New=void 0,I.x2New=void 0}),h(A,b);for(let k of b){let R=k.index;C[R].top=k.x1New,C[R].bottom=k.x2New}return C}function h(w,A){A.sort(function(C,k){return C.x1-k.x1||C.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 C of A){let k=0;for(;k<b.length&&b[k].end<=C.y1;)k++;let R=b.length-1;for(;R>=0&&b[R].start>=C.y2;)R--;let B,I,D,F,z=-1/0;for(D=k;D<=R;D++){B=b[D],I=B.boundary;let Y;I.x2>C.x1?Y=I.index>C.index?I.x1New:C.x1:I.x2New===void 0?Y=(I.x2+C.x1)/2:Y=I.x2New,Y>z&&(z=Y)}for(C.x1New=z,D=k;D<=R;D++)B=b[D],I=B.boundary,I.x2New===void 0?I.x2>C.x1?I.index>C.index&&(I.x2New=I.x2):I.x2New=z:I.x2New>z&&(I.x2New=Math.max(z,I.x2));let q=[],G=null;for(D=k;D<=R;D++){B=b[D],I=B.boundary;let Y=I.x2>C.x2?I:C;G===Y?q[q.length-1].end=B.end:(q.push({start:B.start,end:B.end,boundary:Y}),G=Y)}for(b[k].start<C.y1&&(q[0].start=C.y1,q.unshift({start:b[k].start,end:C.y1,boundary:b[k].boundary})),C.y2<b[R].end&&(q[q.length-1].end=C.y2,q.push({start:C.y2,end:b[R].end,boundary:b[R].boundary})),D=k;D<=R;D++){if(B=b[D],I=B.boundary,I.x2New!==void 0)continue;let Y=!1;for(F=k-1;!Y&&F>=0&&b[F].start>=I.y1;F--)Y=b[F].boundary===I;for(F=R+1;!Y&&F<b.length&&b[F].end<=I.y2;F++)Y=b[F].boundary===I;for(F=0;!Y&&F<q.length;F++)Y=q[F].boundary===I;Y||(I.x2New=z)}Array.prototype.splice.apply(b,[k,R-k+1].concat(q))}for(let C of b){let k=C.boundary;k.x2New===void 0&&(k.x2New=Math.max(w,k.x2))}}class c{constructor({textContent:A,textContentStream:E,container:b,viewport:C,textDivs:k,textContentItemsStr:R,enhanceTextSelection:B}){var I;this._textContent=A,this._textContentStream=E,this._container=b,this._document=b.ownerDocument,this._viewport=C,this._textDivs=k||[],this._textContentItemsStr=R||[],this._enhanceTextSelection=!!B,this._fontInspectorEnabled=!!((I=globalThis.FontInspector)!=null&&I.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,r.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 r.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,E){for(let b=0,C=A.length;b<C;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],E,this._layoutTextCtx)}}_layoutText(A){let E=this._textDivProperties.get(A),b="";if(E.canvasWidth!==0&&E.hasText){let{fontSize:C,fontFamily:k}=A.style;(C!==this._layoutTextLastFontSize||k!==this._layoutTextLastFontFamily)&&(this._layoutTextCtx.font=`${C} ${k}`,this._layoutTextLastFontSize=C,this._layoutTextLastFontFamily=k);let{width:R}=this._layoutTextCtx.measureText(A.textContent);if(R>0){let B=E.canvasWidth/R;this._enhanceTextSelection&&(E.scale=B),b=`scaleX(${B})`}}if(E.angle!==0&&(b=`rotate(${E.angle}deg) ${b}`),b.length>0&&(this._enhanceTextSelection&&(E.originalTransform=b),A.style.transform=b),E.hasText&&this._container.appendChild(A),E.hasEOL){let C=document.createElement("br");C.setAttribute("role","presentation"),this._container.appendChild(C)}}_render(A=0){let E=(0,r.createPromiseCapability)(),b=Object.create(null),C=this._document.createElement("canvas");if(C.height=C.width=o,this._layoutTextCtx=C.getContext("2d",{alpha:!1}),this._textContent){let k=this._textContent.items,R=this._textContent.styles;this._processItems(k,R),E.resolve()}else if(this._textContentStream){let k=()=>{this._reader.read().then(({value:R,done:B})=>{if(B){E.resolve();return}Object.assign(b,R.styles),this._processItems(R.items,b),k()},E.reject)};this._reader=this._textContentStream.getReader(),k()}else throw new Error('Neither "textContent" nor "textContentStream" parameters specified.');E.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 E=[],b=[];for(let C=0,k=this._textDivs.length;C<k;C++){let R=this._textDivs[C],B=this._textDivProperties.get(R);B.hasText&&(A?(E.length=0,b.length=0,B.originalTransform&&E.push(B.originalTransform),B.paddingTop>0?(b.push(`${B.paddingTop}px`),E.push(`translateY(${-B.paddingTop}px)`)):b.push(0),B.paddingRight>0?b.push(`${B.paddingRight/B.scale}px`):b.push(0),B.paddingBottom>0?b.push(`${B.paddingBottom}px`):b.push(0),B.paddingLeft>0?(b.push(`${B.paddingLeft/B.scale}px`),E.push(`translateX(${-B.paddingLeft/B.scale}px)`)):b.push(0),R.style.padding=b.join(" "),E.length&&(R.style.transform=E.join(" "))):(R.style.padding=null,R.style.transform=B.originalTransform))}}}function p(w){let A=new c({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}},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SVGGraphics=void 0;var r=t(1),i=t(5),o=t(3);let s=class{constructor(){(0,r.unreachable)("Not implemented: SVGGraphics")}};e.SVGGraphics=s;{let h=function(b){let C=[],k=[];for(let R of b){if(R.fn==="save"){C.push({fnId:92,fn:"group",items:[]}),k.push(C),C=C[C.length-1].items;continue}R.fn==="restore"?C=k.pop():C.push(R)}return C},c=function(b){if(Number.isInteger(b))return b.toString();let C=b.toFixed(10),k=C.length-1;if(C[k]!=="0")return C;do k--;while(C[k]==="0");return C.substring(0,C[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(${c(b[0])} ${c(b[3])})`;if(b[0]===b[3]&&b[1]===-b[2]){let C=Math.acos(b[0])*180/Math.PI;return`rotate(${c(C)})`}}else if(b[0]===1&&b[1]===0&&b[2]===0&&b[3]===1)return`translate(${c(b[4])} ${c(b[5])})`;return`matrix(${c(b[0])} ${c(b[1])} ${c(b[2])} ${c(b[3])} ${c(b[4])} ${c(b[5])})`},l={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,C="",k=!1){if(URL.createObjectURL&&typeof Blob<"u"&&!k)return URL.createObjectURL(new Blob([b],{type:C}));let R="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",B=`data:${C};base64,`;for(let I=0,D=b.length;I<D;I+=3){let F=b[I]&255,z=b[I+1]&255,q=b[I+2]&255,G=F>>2,Y=(F&3)<<4|z>>4,X=I+1<D?(z&15)<<2|q>>6:64,Q=I+2<D?q&63:64;B+=R[G]+R[Y]+R[X]+R[Q]}return B},v=function(){let b=new Uint8Array([137,80,78,71,13,10,26,10]),C=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 R(q,G,Y){let X=-1;for(let Q=G;Q<Y;Q++){let se=(X^q[Q])&255,ve=k[se];X=X>>>8^ve}return X^-1}function B(q,G,Y,X){let Q=X,se=G.length;Y[Q]=se>>24&255,Y[Q+1]=se>>16&255,Y[Q+2]=se>>8&255,Y[Q+3]=se&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=R(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 I(q,G,Y){let X=1,Q=0;for(let se=G;se<Y;++se)X=(X+(q[se]&255))%65521,Q=(Q+X)%65521;return Q<<16|X}function D(q){if(!o.isNodeJS)return F(q);try{let G;parseInt(process.versions.node)>=8?G=q:G=Buffer.from(q);let Y=NE().deflateSync(G,{level:9});return Y instanceof Uint8Array?Y:new Uint8Array(Y)}catch(G){(0,r.warn)("Not compressing PNG because zlib.deflateSync is unavailable: "+G)}return F(q)}function F(q){let G=q.length,Y=65535,X=Math.ceil(G/Y),Q=new Uint8Array(2+G+X*5+4),se=0;Q[se++]=120,Q[se++]=156;let ve=0;for(;G>Y;)Q[se++]=0,Q[se++]=255,Q[se++]=255,Q[se++]=0,Q[se++]=0,Q.set(q.subarray(ve,ve+Y),se),se+=Y,ve+=Y,G-=Y;Q[se++]=1,Q[se++]=G&255,Q[se++]=G>>8&255,Q[se++]=~G&65535&255,Q[se++]=(~G&65535)>>8&255,Q.set(q.subarray(ve),se),se+=q.length-ve;let ce=I(q,0,q.length);return Q[se++]=ce>>24&255,Q[se++]=ce>>16&255,Q[se++]=ce>>8&255,Q[se++]=ce&255,Q}function z(q,G,Y,X){let Q=q.width,se=q.height,ve,ce,W,H=q.data;switch(G){case r.ImageKind.GRAYSCALE_1BPP:ce=0,ve=1,W=Q+7>>3;break;case r.ImageKind.RGB_24BPP:ce=2,ve=8,W=Q*3;break;case r.ImageKind.RGBA_32BPP:ce=6,ve=8,W=Q*4;break;default:throw new Error("invalid format")}let M=new Uint8Array((1+W)*se),x=0,T=0;for(let re=0;re<se;++re)M[x++]=0,M.set(H.subarray(T,T+W),x),T+=W,x+=W;if(G===r.ImageKind.GRAYSCALE_1BPP&&X){x=0;for(let re=0;re<se;re++){x++;for(let ne=0;ne<W;ne++)M[x++]^=255}}let P=new Uint8Array([Q>>24&255,Q>>16&255,Q>>8&255,Q&255,se>>24&255,se>>16&255,se>>8&255,se&255,ve,ce,0,0,0]),N=D(M),U=b.length+C*3+P.length+N.length,V=new Uint8Array(U),Z=0;return V.set(b,Z),Z+=b.length,B("IHDR",P,V,Z),Z+=C+P.length,B("IDATA",N,V,Z),Z+=C+N.length,B("IEND",new Uint8Array(0),V,Z),_(V,"image/png",Y)}return function(G,Y,X){let Q=G.kind===void 0?r.ImageKind.GRAYSCALE_1BPP:G.kind;return z(G,Q,Y,X)}}();class g{constructor(){this.fontSizeScale=1,this.fontWeight=l.fontWeight,this.fontSize=0,this.textMatrix=r.IDENTITY_MATRIX,this.fontMatrix=r.FONT_IDENTITY_MATRIX,this.leading=0,this.textRenderingMode=r.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=l.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(C,k){this.x=C,this.y=k}}let w=0,A=0,E=0;e.SVGGraphics=s=class{constructor(b,C,k=!1){this.svgFactory=new i.DOMSVGFactory,this.current=new g,this.transformMatrix=r.IDENTITY_MATRIX,this.transformStack=[],this.extraStack=[],this.commonObjs=b,this.objs=C,this.pendingClip=null,this.pendingEOFill=!1,this.embedFonts=!1,this.embeddedFonts=Object.create(null),this.cssStyle=null,this.forceDataSchema=!!k,this._operatorIdMapping=[];for(let R in r.OPS)this._operatorIdMapping[r.OPS[R]]=R}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 C=b.fnArray,k=b.argsArray;for(let R=0,B=C.length;R<B;R++)if(C[R]===r.OPS.dependency)for(let I of k[R]){let D=I.startsWith("g_")?this.commonObjs:this.objs,F=new Promise(z=>{D.get(I,z)});this.current.dependencies.push(F)}return Promise.all(this.current.dependencies)}transform(b,C,k,R,B,I){let D=[b,C,k,R,B,I];this.transformMatrix=r.Util.transform(this.transformMatrix,D),this.tgrp=null}getSVG(b,C){this.viewport=C;let k=this._initialize(C);return this.loadDependencies(b).then(()=>(this.transformMatrix=r.IDENTITY_MATRIX,this.executeOpTree(this.convertOpList(b)),k))}convertOpList(b){let C=this._operatorIdMapping,k=b.argsArray,R=b.fnArray,B=[];for(let I=0,D=R.length;I<D;I++){let F=R[I];B.push({fnId:F,fn:C[F],args:k[I]})}return h(B)}executeOpTree(b){for(let C of b){let k=C.fn,R=C.fnId,B=C.args;switch(R|0){case r.OPS.beginText:this.beginText();break;case r.OPS.dependency:break;case r.OPS.setLeading:this.setLeading(B);break;case r.OPS.setLeadingMoveText:this.setLeadingMoveText(B[0],B[1]);break;case r.OPS.setFont:this.setFont(B);break;case r.OPS.showText:this.showText(B[0]);break;case r.OPS.showSpacedText:this.showText(B[0]);break;case r.OPS.endText:this.endText();break;case r.OPS.moveText:this.moveText(B[0],B[1]);break;case r.OPS.setCharSpacing:this.setCharSpacing(B[0]);break;case r.OPS.setWordSpacing:this.setWordSpacing(B[0]);break;case r.OPS.setHScale:this.setHScale(B[0]);break;case r.OPS.setTextMatrix:this.setTextMatrix(B[0],B[1],B[2],B[3],B[4],B[5]);break;case r.OPS.setTextRise:this.setTextRise(B[0]);break;case r.OPS.setTextRenderingMode:this.setTextRenderingMode(B[0]);break;case r.OPS.setLineWidth:this.setLineWidth(B[0]);break;case r.OPS.setLineJoin:this.setLineJoin(B[0]);break;case r.OPS.setLineCap:this.setLineCap(B[0]);break;case r.OPS.setMiterLimit:this.setMiterLimit(B[0]);break;case r.OPS.setFillRGBColor:this.setFillRGBColor(B[0],B[1],B[2]);break;case r.OPS.setStrokeRGBColor:this.setStrokeRGBColor(B[0],B[1],B[2]);break;case r.OPS.setStrokeColorN:this.setStrokeColorN(B);break;case r.OPS.setFillColorN:this.setFillColorN(B);break;case r.OPS.shadingFill:this.shadingFill(B[0]);break;case r.OPS.setDash:this.setDash(B[0],B[1]);break;case r.OPS.setRenderingIntent:this.setRenderingIntent(B[0]);break;case r.OPS.setFlatness:this.setFlatness(B[0]);break;case r.OPS.setGState:this.setGState(B[0]);break;case r.OPS.fill:this.fill();break;case r.OPS.eoFill:this.eoFill();break;case r.OPS.stroke:this.stroke();break;case r.OPS.fillStroke:this.fillStroke();break;case r.OPS.eoFillStroke:this.eoFillStroke();break;case r.OPS.clip:this.clip("nonzero");break;case r.OPS.eoClip:this.clip("evenodd");break;case r.OPS.paintSolidColorImageMask:this.paintSolidColorImageMask();break;case r.OPS.paintImageXObject:this.paintImageXObject(B[0]);break;case r.OPS.paintInlineImageXObject:this.paintInlineImageXObject(B[0]);break;case r.OPS.paintImageMaskXObject:this.paintImageMaskXObject(B[0]);break;case r.OPS.paintFormXObjectBegin:this.paintFormXObjectBegin(B[0],B[1]);break;case r.OPS.paintFormXObjectEnd:this.paintFormXObjectEnd();break;case r.OPS.closePath:this.closePath();break;case r.OPS.closeStroke:this.closeStroke();break;case r.OPS.closeFillStroke:this.closeFillStroke();break;case r.OPS.closeEOFillStroke:this.closeEOFillStroke();break;case r.OPS.nextLine:this.nextLine();break;case r.OPS.transform:this.transform(B[0],B[1],B[2],B[3],B[4],B[5]);break;case r.OPS.constructPath:this.constructPath(B[0],B[1]);break;case r.OPS.endPath:this.endPath();break;case 92:this.group(C.items);break;default:(0,r.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,C,k,R,B,I){let D=this.current;D.textMatrix=D.lineMatrix=[b,C,k,R,B,I],D.textMatrixScale=Math.hypot(b,C),D.x=D.lineX=0,D.y=D.lineY=0,D.xcoords=[],D.ycoords=[],D.tspan=this.svgFactory.createElement("svg:tspan"),D.tspan.setAttributeNS(null,"font-family",D.fontFamily),D.tspan.setAttributeNS(null,"font-size",`${c(D.fontSize)}px`),D.tspan.setAttributeNS(null,"y",c(-D.y)),D.txtElement=this.svgFactory.createElement("svg:text"),D.txtElement.appendChild(D.tspan)}beginText(){let b=this.current;b.x=b.lineX=0,b.y=b.lineY=0,b.textMatrix=r.IDENTITY_MATRIX,b.lineMatrix=r.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,C){let k=this.current;k.x=k.lineX+=b,k.y=k.lineY+=C,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",`${c(k.fontSize)}px`),k.tspan.setAttributeNS(null,"y",c(-k.y))}showText(b){let C=this.current,k=C.font,R=C.fontSize;if(R===0)return;let B=C.fontSizeScale,I=C.charSpacing,D=C.wordSpacing,F=C.fontDirection,z=C.textHScale*F,q=k.vertical,G=q?1:-1,Y=k.defaultVMetrics,X=R*C.fontMatrix[0],Q=0;for(let ce of b){if(ce===null){Q+=F*D;continue}else if(typeof ce=="number"){Q+=G*ce*R/1e3;continue}let W=(ce.isSpace?D:0)+I,H=ce.fontChar,M,x,T=ce.width;if(q){let N,U=ce.vmetric||Y;N=ce.vmetric?U[1]:T*.5,N=-N*X;let V=U[2]*X;T=U?-U[0]:T,M=N/B,x=(Q+V)/B}else M=Q/B,x=0;(ce.isInFont||k.missingFile)&&(C.xcoords.push(C.x+M),q&&C.ycoords.push(-C.y+x),C.tspan.textContent+=H);let P;q?P=T*X-W*F:P=T*X+W*F,Q+=P}C.tspan.setAttributeNS(null,"x",C.xcoords.map(c).join(" ")),q?C.tspan.setAttributeNS(null,"y",C.ycoords.map(c).join(" ")):C.tspan.setAttributeNS(null,"y",c(-C.y)),q?C.y-=Q:C.x+=Q*z,C.tspan.setAttributeNS(null,"font-family",C.fontFamily),C.tspan.setAttributeNS(null,"font-size",`${c(C.fontSize)}px`),C.fontStyle!==l.fontStyle&&C.tspan.setAttributeNS(null,"font-style",C.fontStyle),C.fontWeight!==l.fontWeight&&C.tspan.setAttributeNS(null,"font-weight",C.fontWeight);let se=C.textRenderingMode&r.TextRenderingMode.FILL_STROKE_MASK;if(se===r.TextRenderingMode.FILL||se===r.TextRenderingMode.FILL_STROKE?(C.fillColor!==l.fillColor&&C.tspan.setAttributeNS(null,"fill",C.fillColor),C.fillAlpha<1&&C.tspan.setAttributeNS(null,"fill-opacity",C.fillAlpha)):C.textRenderingMode===r.TextRenderingMode.ADD_TO_PATH?C.tspan.setAttributeNS(null,"fill","transparent"):C.tspan.setAttributeNS(null,"fill","none"),se===r.TextRenderingMode.STROKE||se===r.TextRenderingMode.FILL_STROKE){let ce=1/(C.textMatrixScale||1);this._setStrokeAttributes(C.tspan,ce)}let ve=C.textMatrix;C.textRise!==0&&(ve=ve.slice(),ve[5]+=C.textRise),C.txtElement.setAttributeNS(null,"transform",`${p(ve)} scale(${c(z)}, -1)`),C.txtElement.setAttributeNS(f,"xml:space","preserve"),C.txtElement.appendChild(C.tspan),C.txtgrp.appendChild(C.txtElement),this._ensureTransformGroup().appendChild(C.txtElement)}setLeadingMoveText(b,C){this.setLeading(-C),this.moveText(b,C)}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 C=_(b.data,b.mimetype,this.forceDataSchema);this.cssStyle.textContent+=`@font-face { font-family: "${b.loadedName}"; src: url(${C}); }
|
|
73
|
-
`}setFont(b){let C=this.current,k=this.commonObjs.get(b[0]),R=b[1];C.font=k,this.embedFonts&&!k.missingFile&&!this.embeddedFonts[k.loadedName]&&(this.addFontStyle(k),this.embeddedFonts[k.loadedName]=k),C.fontMatrix=k.fontMatrix||r.FONT_IDENTITY_MATRIX;let B="normal";k.black?B="900":k.bold&&(B="bold");let I=k.italic?"italic":"normal";R<0?(R=-R,C.fontDirection=-1):C.fontDirection=1,C.fontSize=R,C.fontFamily=k.loadedName,C.fontWeight=B,C.fontStyle=I,C.tspan=this.svgFactory.createElement("svg:tspan"),C.tspan.setAttributeNS(null,"y",c(-C.y)),C.xcoords=[],C.ycoords=[]}endText(){var C;let b=this.current;b.textRenderingMode&r.TextRenderingMode.ADD_TO_PATH_FLAG&&((C=b.txtElement)!=null&&C.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,C,k){this.current.strokeColor=r.Util.makeHexColor(b,C,k)}setFillAlpha(b){this.current.fillAlpha=b}setFillRGBColor(b,C,k){this.current.fillColor=r.Util.makeHexColor(b,C,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 C=this.viewport.width,k=this.viewport.height,R=r.Util.inverseTransform(this.transformMatrix),B=r.Util.applyTransform([0,0],R),I=r.Util.applyTransform([0,k],R),D=r.Util.applyTransform([C,0],R),F=r.Util.applyTransform([C,k],R),z=Math.min(B[0],I[0],D[0],F[0]),q=Math.min(B[1],I[1],D[1],F[1]),G=Math.max(B[0],I[0],D[0],F[0]),Y=Math.max(B[1],I[1],D[1],F[1]),X=this.svgFactory.createElement("svg:rect");X.setAttributeNS(null,"x",z),X.setAttributeNS(null,"y",q),X.setAttributeNS(null,"width",G-z),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 C=b[1],k=b[2],R=b[3]||r.IDENTITY_MATRIX,[B,I,D,F]=b[4],z=b[5],q=b[6],G=b[7],Y=`shading${E++}`,[X,Q,se,ve]=r.Util.normalizeRect([...r.Util.applyTransform([B,I],R),...r.Util.applyTransform([D,F],R)]),[ce,W]=r.Util.singularValueDecompose2dScale(R),H=z*ce,M=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",M),x.setAttributeNS(null,"x",`${X}`),x.setAttributeNS(null,"y",`${Q}`);let T=this.svg,P=this.transformMatrix,N=this.current.fillColor,U=this.current.strokeColor,V=this.svgFactory.create(se-X,ve-Q);if(this.svg=V,this.transformMatrix=R,G===2){let Z=r.Util.makeHexColor(...C);this.current.fillColor=Z,this.current.strokeColor=Z}return this.executeOpTree(this.convertOpList(k)),this.svg=T,this.transformMatrix=P,this.current.fillColor=N,this.current.strokeColor=U,x.appendChild(V.childNodes[0]),this.defs.appendChild(x),`url(#${Y})`}_makeShadingPattern(b){switch(typeof b=="string"&&(b=this.objs.get(b)),b[0]){case"RadialAxial":let C=`shading${E++}`,k=b[3],R;switch(b[1]){case"axial":let B=b[4],I=b[5];R=this.svgFactory.createElement("svg:linearGradient"),R.setAttributeNS(null,"id",C),R.setAttributeNS(null,"gradientUnits","userSpaceOnUse"),R.setAttributeNS(null,"x1",B[0]),R.setAttributeNS(null,"y1",B[1]),R.setAttributeNS(null,"x2",I[0]),R.setAttributeNS(null,"y2",I[1]);break;case"radial":let D=b[4],F=b[5],z=b[6],q=b[7];R=this.svgFactory.createElement("svg:radialGradient"),R.setAttributeNS(null,"id",C),R.setAttributeNS(null,"gradientUnits","userSpaceOnUse"),R.setAttributeNS(null,"cx",F[0]),R.setAttributeNS(null,"cy",F[1]),R.setAttributeNS(null,"r",q),R.setAttributeNS(null,"fx",D[0]),R.setAttributeNS(null,"fy",D[1]),R.setAttributeNS(null,"fr",z);break;default:throw new Error(`Unknown RadialAxial type: ${b[1]}`)}for(let B of k){let I=this.svgFactory.createElement("svg:stop");I.setAttributeNS(null,"offset",B[0]),I.setAttributeNS(null,"stop-color",B[1]),R.appendChild(I)}return this.defs.appendChild(R),`url(#${C})`;case"Mesh":return(0,r.warn)("Unimplemented pattern Mesh"),null;case"Dummy":return"hotpink";default:throw new Error(`Unknown IR type: ${b[0]}`)}}setDash(b,C){this.current.dashArray=b,this.current.dashPhase=C}constructPath(b,C){let k=this.current,R=k.x,B=k.y,I=[],D=0;for(let F of b)switch(F|0){case r.OPS.rectangle:R=C[D++],B=C[D++];let z=C[D++],q=C[D++],G=R+z,Y=B+q;I.push("M",c(R),c(B),"L",c(G),c(B),"L",c(G),c(Y),"L",c(R),c(Y),"Z");break;case r.OPS.moveTo:R=C[D++],B=C[D++],I.push("M",c(R),c(B));break;case r.OPS.lineTo:R=C[D++],B=C[D++],I.push("L",c(R),c(B));break;case r.OPS.curveTo:R=C[D+4],B=C[D+5],I.push("C",c(C[D]),c(C[D+1]),c(C[D+2]),c(C[D+3]),c(R),c(B)),D+=6;break;case r.OPS.curveTo2:I.push("C",c(R),c(B),c(C[D]),c(C[D+1]),c(C[D+2]),c(C[D+3])),R=C[D+2],B=C[D+3],D+=4;break;case r.OPS.curveTo3:R=C[D+2],B=C[D+3],I.push("C",c(C[D]),c(C[D+1]),c(R),c(B),c(R),c(B)),D+=4;break;case r.OPS.closePath:I.push("Z");break}I=I.join(" "),k.path&&b.length>0&&b[0]!==r.OPS.rectangle&&b[0]!==r.OPS.moveTo?I=k.path.getAttributeNS(null,"d")+I:(k.path=this.svgFactory.createElement("svg:path"),this._ensureTransformGroup().appendChild(k.path)),k.path.setAttributeNS(null,"d",I),k.path.setAttributeNS(null,"fill","none"),k.element=k.path,k.setCurrentPoint(R,B)}endPath(){let b=this.current;if(b.path=null,!this.pendingClip)return;if(!b.element){this.pendingClip=null;return}let C=`clippath${w++}`,k=this.svgFactory.createElement("svg:clipPath");k.setAttributeNS(null,"id",C),k.setAttributeNS(null,"transform",p(this.transformMatrix));let R=b.element.cloneNode(!0);if(this.pendingClip==="evenodd"?R.setAttributeNS(null,"clip-rule","evenodd"):R.setAttributeNS(null,"clip-rule","nonzero"),this.pendingClip=null,k.appendChild(R),this.defs.appendChild(k),b.activeClipUrl){b.clipGroup=null;for(let B of this.extraStack)B.clipGroup=null;k.setAttributeNS(null,"clip-path",b.activeClipUrl)}b.activeClipUrl=`url(#${C})`,this.tgrp=null}clip(b){this.pendingClip=b}closePath(){let b=this.current;if(b.path){let C=`${b.path.getAttributeNS(null,"d")}Z`;b.path.setAttributeNS(null,"d",C)}}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[C,k]of b)switch(C){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,r.warn)(`Unimplemented graphic state operator ${C}`);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,C=1){let k=this.current,R=k.dashArray;C!==1&&R.length>0&&(R=R.map(function(B){return C*B})),b.setAttributeNS(null,"stroke",k.strokeColor),b.setAttributeNS(null,"stroke-opacity",k.strokeAlpha),b.setAttributeNS(null,"stroke-miterlimit",c(k.miterLimit)),b.setAttributeNS(null,"stroke-linecap",k.lineCap),b.setAttributeNS(null,"stroke-linejoin",k.lineJoin),b.setAttributeNS(null,"stroke-width",c(C*k.lineWidth)+"px"),b.setAttributeNS(null,"stroke-dasharray",R.map(c).join(" ")),b.setAttributeNS(null,"stroke-dashoffset",c(C*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 C=b.startsWith("g_")?this.commonObjs.get(b):this.objs.get(b);if(!C){(0,r.warn)(`Dependent image with object ID ${b} is not ready yet`);return}this.paintInlineImageXObject(C)}paintInlineImageXObject(b,C){let k=b.width,R=b.height,B=v(b,this.forceDataSchema,!!C),I=this.svgFactory.createElement("svg:rect");I.setAttributeNS(null,"x","0"),I.setAttributeNS(null,"y","0"),I.setAttributeNS(null,"width",c(k)),I.setAttributeNS(null,"height",c(R)),this.current.element=I,this.clip("nonzero");let D=this.svgFactory.createElement("svg:image");D.setAttributeNS(u,"xlink:href",B),D.setAttributeNS(null,"x","0"),D.setAttributeNS(null,"y",c(-R)),D.setAttributeNS(null,"width",c(k)+"px"),D.setAttributeNS(null,"height",c(R)+"px"),D.setAttributeNS(null,"transform",`scale(${c(1/k)} ${c(-1/R)})`),C?C.appendChild(D):this._ensureTransformGroup().appendChild(D)}paintImageMaskXObject(b){let C=this.current,k=b.width,R=b.height,B=C.fillColor;C.maskId=`mask${A++}`;let I=this.svgFactory.createElement("svg:mask");I.setAttributeNS(null,"id",C.maskId);let D=this.svgFactory.createElement("svg:rect");D.setAttributeNS(null,"x","0"),D.setAttributeNS(null,"y","0"),D.setAttributeNS(null,"width",c(k)),D.setAttributeNS(null,"height",c(R)),D.setAttributeNS(null,"fill",B),D.setAttributeNS(null,"mask",`url(#${C.maskId})`),this.defs.appendChild(I),this._ensureTransformGroup().appendChild(D),this.paintInlineImageXObject(b,I)}paintFormXObjectBegin(b,C){if(Array.isArray(b)&&b.length===6&&this.transform(b[0],b[1],b[2],b[3],b[4],b[5]),C){let k=C[2]-C[0],R=C[3]-C[1],B=this.svgFactory.createElement("svg:rect");B.setAttributeNS(null,"x",C[0]),B.setAttributeNS(null,"y",C[1]),B.setAttributeNS(null,"width",c(k)),B.setAttributeNS(null,"height",c(R)),this.current.element=B,this.clip("nonzero"),this.endPath()}}paintFormXObjectEnd(){}_initialize(b){let C=this.svgFactory.create(b.width,b.height),k=this.svgFactory.createElement("svg:defs");C.appendChild(k),this.defs=k;let R=this.svgFactory.createElement("svg:g");return R.setAttributeNS(null,"transform",p(b.transform)),C.appendChild(R),this.svg=R,C}_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}}}},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PDFNodeStream=void 0;var r=t(1),i=t(26);let o=pf(),s=BE(),l=DE(),f=hf(),u=/^file:\/\/\/[a-zA-Z]:\//;function y(A){let E=f.parse(A);return E.protocol==="file:"||E.host?E:/^[a-z]:[/\\]/i.test(A)?f.parse(`file:///${A}`):(E.host||(E.protocol="file:"),E)}class m{constructor(E){this.source=E,this.url=y(E.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=this.isHttp&&E.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){var E;return((E=this._fullRequestReader)==null?void 0:E._loaded)??0}getFullReader(){return(0,r.assert)(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new p(this):new h(this),this._fullRequestReader}getRangeReader(E,b){if(b<=this._progressiveDataLength)return null;let C=this.isFsUrl?new w(this,E,b):new c(this,E,b);return this._rangeRequestReaders.push(C),C}cancelAllRequests(E){this._fullRequestReader&&this._fullRequestReader.cancel(E);for(let b of this._rangeRequestReaders.slice(0))b.cancel(E)}}e.PDFNodeStream=m;class _{constructor(E){this._url=E.url,this._done=!1,this._storedError=null,this.onProgress=null;let b=E.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,r.createPromiseCapability)(),this._headersCapability=(0,r.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 E=this._readableStream.read();return E===null?(this._readCapability=(0,r.createPromiseCapability)(),this.read()):(this._loaded+=E.length,this.onProgress&&this.onProgress({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(E).buffer,done:!1})}cancel(E){if(!this._readableStream){this._error(E);return}this._readableStream.destroy(E)}_error(E){this._storedError=E,this._readCapability.resolve()}_setReadableStream(E){this._readableStream=E,E.on("readable",()=>{this._readCapability.resolve()}),E.on("end",()=>{E.destroy(),this._done=!0,this._readCapability.resolve()}),E.on("error",b=>{this._error(b)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new r.AbortException("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class v{constructor(E){this._url=E.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=(0,r.createPromiseCapability)();let b=E.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 E=this._readableStream.read();return E===null?(this._readCapability=(0,r.createPromiseCapability)(),this.read()):(this._loaded+=E.length,this.onProgress&&this.onProgress({loaded:this._loaded}),{value:new Uint8Array(E).buffer,done:!1})}cancel(E){if(!this._readableStream){this._error(E);return}this._readableStream.destroy(E)}_error(E){this._storedError=E,this._readCapability.resolve()}_setReadableStream(E){this._readableStream=E,E.on("readable",()=>{this._readCapability.resolve()}),E.on("end",()=>{E.destroy(),this._done=!0,this._readCapability.resolve()}),E.on("error",b=>{this._error(b)}),this._storedError&&this._readableStream.destroy(this._storedError)}}function g(A,E){return{protocol:A.protocol,auth:A.auth,host:A.hostname,port:A.port,path:A.path,method:"GET",headers:E}}class h extends _{constructor(E){super(E);let b=C=>{if(C.statusCode===404){let I=new r.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=I,this._headersCapability.reject(I);return}this._headersCapability.resolve(),this._setReadableStream(C);let k=I=>this._readableStream.headers[I.toLowerCase()],{allowRangeRequests:R,suggestedLength:B}=(0,i.validateRangeRequestCapabilities)({getResponseHeader:k,isHttp:E.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=R,this._contentLength=B||this._contentLength,this._filename=(0,i.extractFilenameFromHeader)(k)};this._request=null,this._url.protocol==="http:"?this._request=s.request(g(this._url,E.httpHeaders),b):this._request=l.request(g(this._url,E.httpHeaders),b),this._request.on("error",C=>{this._storedError=C,this._headersCapability.reject(C)}),this._request.end()}}class c extends v{constructor(E,b,C){super(E),this._httpHeaders={};for(let R in E.httpHeaders){let B=E.httpHeaders[R];typeof B>"u"||(this._httpHeaders[R]=B)}this._httpHeaders.Range=`bytes=${b}-${C-1}`;let k=R=>{if(R.statusCode===404){let B=new r.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=B;return}this._setReadableStream(R)};this._request=null,this._url.protocol==="http:"?this._request=s.request(g(this._url,this._httpHeaders),k):this._request=l.request(g(this._url,this._httpHeaders),k),this._request.on("error",R=>{this._storedError=R}),this._request.end()}}class p extends _{constructor(E){super(E);let b=decodeURIComponent(this._url.path);u.test(this._url.href)&&(b=b.replace(/^\//,"")),o.lstat(b,(C,k)=>{if(C){C.code==="ENOENT"&&(C=new r.MissingPDFException(`Missing PDF "${b}".`)),this._storedError=C,this._headersCapability.reject(C);return}this._contentLength=k.size,this._setReadableStream(o.createReadStream(b)),this._headersCapability.resolve()})}}class w extends v{constructor(E,b,C){super(E);let k=decodeURIComponent(this._url.path);u.test(this._url.href)&&(k=k.replace(/^\//,"")),this._setReadableStream(o.createReadStream(k,{start:b,end:C-1}))}}},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createResponseStatusError=f,e.extractFilenameFromHeader=l,e.validateRangeRequestCapabilities=s,e.validateResponseStatus=u;var r=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 l(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 r.MissingPDFException('Missing PDF "'+m+'".'):new r.UnexpectedResponseException(`Unexpected server response (${y}) while retrieving PDF "${m}".`,y)}function u(y){return y===200||y===206}},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getFilenameFromContentDispositionHeader=i;var r=t(1);function i(o){let s=!0,l=f("filename\\*","i").exec(o);if(l){l=l[1];let h=_(l);return h=unescape(h),h=v(h),h=g(h),y(h)}if(l=m(o),l){let h=g(l);return y(h)}if(l=f("filename","i").exec(o),l){l=l[1];let h=_(l);return h=g(h),y(h)}function f(h,c){return new RegExp("(?:^|;)\\s*"+h+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',c)}function u(h,c){if(h){if(!/^[\x00-\xFF]+$/.test(c))return c;try{let p=new TextDecoder(h,{fatal:!0}),w=(0,r.stringToBytes)(c);c=p.decode(w),s=!1}catch{}}return c}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 c=[],p,w=f("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(p=w.exec(h))!==null;){let[,E,b,C]=p;if(E=parseInt(E,10),E in c){if(E===0)break;continue}c[E]=[b,C]}let A=[];for(let E=0;E<c.length&&E in c;++E){let[b,C]=c[E];C=_(C),b&&(C=unescape(C),E===0&&(C=v(C))),A.push(C)}return A.join("")}function _(h){if(h.startsWith('"')){let c=h.slice(1).split('\\"');for(let p=0;p<c.length;++p){let w=c[p].indexOf('"');w!==-1&&(c[p]=c[p].slice(0,w),c.length=p+1),c[p]=c[p].replace(/\\(.)/g,"$1")}h=c.join('"')}return h}function v(h){let c=h.indexOf("'");if(c===-1)return h;let p=h.slice(0,c),A=h.slice(c+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(c,p,w,A){if(w==="q"||w==="Q")return A=A.replace(/_/g," "),A=A.replace(/=([0-9a-fA-F]{2})/g,function(E,b){return String.fromCharCode(parseInt(b,16))}),u(p,A);try{A=atob(A)}catch{}return u(p,A)})}return""}},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PDFNetworkStream=void 0;var r=t(1),i=t(26);let o=200,s=206;function l(_){let v=_.response;return typeof v!="string"?v:(0,r.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 c={begin:v,end:g};for(let p in h)c[p]=h[p];return this.request(c)}requestFull(v){return this.request(v)}request(v){let g=this.getXhr(),h=this.currXhrId++,c=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}`),c.expectedStatus=s):c.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),c.onHeadersReceived=v.onHeadersReceived,c.onDone=v.onDone,c.onError=v.onError,c.onProgress=v.onProgress,g.send(null),h}onProgress(v,g){var c;let h=this.pendingRequests[v];h&&((c=h.onProgress)==null||c.call(h,g))}onStateChange(v,g){var E,b,C;let h=this.pendingRequests[v];if(!h)return;let c=h.xhr;if(c.readyState>=2&&h.onHeadersReceived&&(h.onHeadersReceived(),delete h.onHeadersReceived),c.readyState!==4||!(v in this.pendingRequests))return;if(delete this.pendingRequests[v],c.status===0&&this.isHttp){(E=h.onError)==null||E.call(h,c.status);return}let p=c.status||o;if(!(p===o&&h.expectedStatus===s)&&p!==h.expectedStatus){(b=h.onError)==null||b.call(h,c.status);return}let A=l(c);if(p===s){let k=c.getResponseHeader("Content-Range"),R=/bytes (\d+)-(\d+)\/(\d+)/.exec(k);h.onDone({begin:parseInt(R[1],10),chunk:A})}else A?h.onDone({begin:0,chunk:A}):(C=h.onError)==null||C.call(h,c.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,r.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,r.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:c,suggestedLength:p}=(0,i.validateRangeRequestCapabilities)({getResponseHeader:h,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});c&&(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,r.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 c={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,c),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,r.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()}}},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PDFFetchStream=void 0;var r=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 l{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,r.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=l;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,r.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:c,suggestedLength:p}=(0,i.validateRangeRequestCapabilities)({getResponseHeader:h,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=c,this._contentLength=p||this._contentLength,this._filename=(0,i.extractFilenameFromHeader)(h),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new r.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,r.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(c=>{if(!(0,i.validateResponseStatus)(c.status))throw(0,i.createResponseStatusError)(c.status,h);this._readCapability.resolve(),this._reader=c.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__(n){var e=__webpack_module_cache__[n];if(e!==void 0)return e.exports;var t=__webpack_module_cache__[n]={exports:{}};return __webpack_modules__[n](t,t.exports,__w_pdfjs_require__),t.exports}var __webpack_exports__={};return(()=>{var n=__webpack_exports__;Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"AnnotationLayer",{enumerable:!0,get:function(){return i.AnnotationLayer}}),Object.defineProperty(n,"AnnotationMode",{enumerable:!0,get:function(){return e.AnnotationMode}}),Object.defineProperty(n,"CMapCompressionType",{enumerable:!0,get:function(){return e.CMapCompressionType}}),Object.defineProperty(n,"GlobalWorkerOptions",{enumerable:!0,get:function(){return o.GlobalWorkerOptions}}),Object.defineProperty(n,"InvalidPDFException",{enumerable:!0,get:function(){return e.InvalidPDFException}}),Object.defineProperty(n,"LoopbackPort",{enumerable:!0,get:function(){return t.LoopbackPort}}),Object.defineProperty(n,"MissingPDFException",{enumerable:!0,get:function(){return e.MissingPDFException}}),Object.defineProperty(n,"OPS",{enumerable:!0,get:function(){return e.OPS}}),Object.defineProperty(n,"PDFDataRangeTransport",{enumerable:!0,get:function(){return t.PDFDataRangeTransport}}),Object.defineProperty(n,"PDFDateString",{enumerable:!0,get:function(){return r.PDFDateString}}),Object.defineProperty(n,"PDFWorker",{enumerable:!0,get:function(){return t.PDFWorker}}),Object.defineProperty(n,"PasswordResponses",{enumerable:!0,get:function(){return e.PasswordResponses}}),Object.defineProperty(n,"PermissionFlag",{enumerable:!0,get:function(){return e.PermissionFlag}}),Object.defineProperty(n,"PixelsPerInch",{enumerable:!0,get:function(){return r.PixelsPerInch}}),Object.defineProperty(n,"RenderingCancelledException",{enumerable:!0,get:function(){return r.RenderingCancelledException}}),Object.defineProperty(n,"SVGGraphics",{enumerable:!0,get:function(){return f.SVGGraphics}}),Object.defineProperty(n,"UNSUPPORTED_FEATURES",{enumerable:!0,get:function(){return e.UNSUPPORTED_FEATURES}}),Object.defineProperty(n,"UnexpectedResponseException",{enumerable:!0,get:function(){return e.UnexpectedResponseException}}),Object.defineProperty(n,"Util",{enumerable:!0,get:function(){return e.Util}}),Object.defineProperty(n,"VerbosityLevel",{enumerable:!0,get:function(){return e.VerbosityLevel}}),Object.defineProperty(n,"XfaLayer",{enumerable:!0,get:function(){return u.XfaLayer}}),Object.defineProperty(n,"build",{enumerable:!0,get:function(){return t.build}}),Object.defineProperty(n,"createPromiseCapability",{enumerable:!0,get:function(){return e.createPromiseCapability}}),Object.defineProperty(n,"createValidAbsoluteUrl",{enumerable:!0,get:function(){return e.createValidAbsoluteUrl}}),Object.defineProperty(n,"getDocument",{enumerable:!0,get:function(){return t.getDocument}}),Object.defineProperty(n,"getFilenameFromUrl",{enumerable:!0,get:function(){return r.getFilenameFromUrl}}),Object.defineProperty(n,"getPdfFilenameFromUrl",{enumerable:!0,get:function(){return r.getPdfFilenameFromUrl}}),Object.defineProperty(n,"getXfaPageViewport",{enumerable:!0,get:function(){return r.getXfaPageViewport}}),Object.defineProperty(n,"isPdfFile",{enumerable:!0,get:function(){return r.isPdfFile}}),Object.defineProperty(n,"loadScript",{enumerable:!0,get:function(){return r.loadScript}}),Object.defineProperty(n,"renderTextLayer",{enumerable:!0,get:function(){return l.renderTextLayer}}),Object.defineProperty(n,"shadow",{enumerable:!0,get:function(){return e.shadow}}),Object.defineProperty(n,"version",{enumerable:!0,get:function(){return t.version}});var e=__w_pdfjs_require__(1),t=__w_pdfjs_require__(4),r=__w_pdfjs_require__(5),i=__w_pdfjs_require__(20),o=__w_pdfjs_require__(13),s=__w_pdfjs_require__(3),l=__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,r.isValidFetchUrl)(g.url)?new v(g):new _(g))}})(),__webpack_exports__})())});var JU={};D0(JU,{Link:()=>lu,default:()=>VU,load:()=>$U});L();L();L();var e4=rt(Q3()),t4=rt(Or());L();var Z3=rt(Or());function _a(n,e){return Z3.TaJson.deserialize(n,e)}var lo=class extends e4.Publication{static async fromUrl(e,t){let i=await(await fetch(e.href,t)).json(),o=_a(i,lo);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 r;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((r=this.TOC)==null?void 0:r.map(i=>{var o,s;if(i.Href){let l=this.positionsByHref(this.getRelativeHref(i.Href));if((l==null?void 0:l.length)>0){let f=l[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(r=>r.Href&&this.getAbsoluteHref(r.Href)===e)}getAbsoluteHref(e){return new URL(e,this.manifestUrl.href).href}getRelativeHref(e){let t=this.manifestUrl.href.replace("/manifest.json",""),r=e.replace(t,"");return r.indexOf("#")>0&&(r=r.slice(0,r.indexOf("#"))),r.charAt(0)==="/"&&(r=r.substring(1)),r}getTOCItemAbsolute(e){let t=this.getAbsoluteHref(e),r=(o,s)=>{for(let l=0;l<s.length;l++){let f=s[l];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=r(o,f.Children);if(u!==void 0)return u}}},i=r(t,this.tableOfContents);return i===void 0&&this.readingOrder!==void 0&&(i=r(t,this.readingOrder)),i}getTOCItem(e){let t=(i,o)=>{for(let s=0;s<o.length;s++){let l=o[s];if(l.Href&&this.getAbsoluteHref(l.Href)===i)return l;if(l.Children){let f=t(i,l.Children);if(f!==void 0)return f}}},r=t(e,this.tableOfContents);if(r===void 0&&this.readingOrder!==void 0&&(r=t(e,this.readingOrder)),r===void 0&&e.indexOf("#")!==-1){let i=e.slice(0,e.indexOf("#"));r=t(i,this.tableOfContents),r===void 0&&this.readingOrder!==void 0&&(r=t(i,this.readingOrder))}return r}positionsByHref(e){var r;let t=decodeURI(e)??"";return(r=this.positions)==null?void 0:r.filter(i=>t.includes(i.href))}async autoGeneratePositions(e,t=YR){let r=0,i=0,o=[];if(this.readingOrder!==void 0)for(let l of this.readingOrder)if(this.isFixedLayout){let f={href:l.Href,locations:{progression:0,position:r+1},type:l.TypeLink};o.push(f),r=r+1}else{let f=this.getAbsoluteHref(l.Href),u=await t(f,e);l.contentLength=u,i+=u;let m=Math.max(1,Math.ceil(u/1024));for(let _=0;_<m;_++){let v={href:l.Href,locations:{progression:_/m,position:r+(_+1)},type:l.TypeLink};o.push(v)}r=r+m}var s=0;if(this.isReflowable&&this.readingOrder!==void 0)for(let l of this.readingOrder){if(!l.contentLength){console.error("Link is missing contentLength",l);return}l.contentWeight=100/i*l.contentLength,s=s+l.contentWeight}for(let l of o){let f=o.filter(y=>y.href===decodeURI(l.href)),u=Math.ceil((l.locations.progression?l.locations.progression:0)*(f.length-1));l.locations.position&&(l.locations.totalProgression=(l.locations.position-1)/o.length),l.locations.remainingPositions=Math.abs(u-(f.length-1)),l.locations.position&&(l.locations.totalRemainingPositions=Math.abs(l.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]})}};lo=Nc([(0,t4.JsonObject)()],lo);var YR=async(n,e)=>(await(await fetch(n,e)).blob()).size;L();L();var As=class{json(){return JSON.stringify(this)}},Hp=class extends As{constructor(e,t,r){super(),this.value=e,this.ref=t,this.name=r}toString(){return this.value}},Up=class extends As{constructor(e,t,r){super(),this.value=e,this.ref=t,this.name=r}toString(){return this.value}toJson(){return JSON.parse(this.value)}},jp=class extends As{constructor(e,t,r,i){super(),this.value=e,this.values=t,this.ref=r,this.name=i}toString(){return this.values[this.value]}},qp=class extends As{constructor(t,r,i,o,s,l,f){super();this.countDecimals=function(t){return t%1!==0?t.toString().split(".")[1].length:1};this.value=t,this.min=r,this.max=i,this.step=o,this.suffix=s,this.ref=l,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)}},wa=class extends As{constructor(e,t,r,i,o){super(),this.value=r,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}},Li=class{constructor(){this.properties=[]}addIncremental(e,t,r,i,o,s,l){this.properties.push(new qp(e,t,r,i,o,s,l))}addStringable(e,t,r){this.properties.push(new Hp(e,t,r))}addJSONable(e,t,r){this.properties.push(new Up(e,t,r))}addSwitchable(e,t,r,i,o){this.properties.push(new wa(e,t,r,i,o))}addEnumerable(e,t,r,i){this.properties.push(new jp(e,t,r,i))}getByRef(e){let t=this.properties.filter(r=>r.ref===e);return t.length>0?t[0]:null}getByKey(e){let t=this.properties.filter(r=>r.key===e);return t.length>0?t[0]:null}};L();var mt=class mt{};mt.FONT_SIZE_REF="fontSize",mt.FONT_FAMILY_REF="fontFamily",mt.FONT_OVERRIDE_REF="fontOverride",mt.APPEARANCE_REF="appearance",mt.SCROLL_REF="scroll",mt.TEXT_ALIGNMENT_REF="textAlign",mt.COLUMN_COUNT_REF="colCount",mt.DIRECTION_REF="direction",mt.WORD_SPACING_REF="wordSpacing",mt.LETTER_SPACING_REF="letterSpacing",mt.PAGE_MARGINS_REF="pageMargins",mt.LINE_HEIGHT_REF="lineHeight",mt.FONT_SIZE_KEY="--USER__"+mt.FONT_SIZE_REF,mt.FONT_FAMILY_KEY="--USER__"+mt.FONT_FAMILY_REF,mt.FONT_OVERRIDE_KEY="--USER__"+mt.FONT_OVERRIDE_REF,mt.APPEARANCE_KEY="--USER__"+mt.APPEARANCE_REF,mt.SCROLL_KEY="--USER__"+mt.SCROLL_REF,mt.TEXT_ALIGNMENT_KEY="--USER__"+mt.TEXT_ALIGNMENT_REF,mt.COLUMN_COUNT_KEY="--USER__"+mt.COLUMN_COUNT_REF,mt.DIRECTION_KEY="--USER__"+mt.DIRECTION_REF,mt.WORD_SPACING_KEY="--USER__"+mt.WORD_SPACING_REF,mt.LETTER_SPACING_KEY="--USER__"+mt.LETTER_SPACING_REF,mt.PAGE_MARGINS_KEY="--USER__"+mt.PAGE_MARGINS_REF,mt.LINE_HEIGHT_KEY="--USER__"+mt.LINE_HEIGHT_REF;var _e=mt;L();function Le(n,e){return n.querySelector(e)}function yt(n,e){let t=Le(n,e);if(t&&t instanceof HTMLElement)return t;throw new Error("required element "+e+" not found")}function cr(n,e){if(n===null)throw new Error("parent element is null");return n.querySelector(e)}function co(n,e){let t=cr(n,e);if(t)return t;throw new Error("required element "+e+" not found in iframe")}function Ir(n,e,t){n.setAttribute(e,t)}L();L();var Y6=rt(Fg());var Ba=class{constructor(e){this.getScrollingElement=e=>e.scrollingElement?e.scrollingElement:e.body;this.navigator=e}async handleFootnote(e,t){var i,o;let r=e.getAttribute("href");if(r&&r.indexOf("#")>0){let l=function(u){let y=document.location.href;return new URL(u,y).href},s=r.substring(r.indexOf("#")+1),f=l(r);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(r).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 r,i;let e=(r=this.navigator.iframes[0].contentDocument)==null?void 0:r.getElementById("d2-popover");e&&((i=e.parentElement)==null||i.removeChild(e));let t=yt(document,"#iframe-wrapper");t.style.overflow="auto"}async showPopover(e,t){var s,l,f,u,y,m;let r=e.getAttribute("href"),i=e.getAttribute("src");function o(_){let v=document.location.href;return new URL(_,v).href}if(r){let _=o(r);if(_){t.preventDefault(),t.stopPropagation();let v=(s=this.navigator.iframes[0].contentDocument)==null?void 0:s.getElementById("d2-popover");v&&((l=v.parentElement)==null||l.removeChild(v));let g=document.createElement("div");g.id="d2-popover",g.className="d2-popover is-active";let h=yt(document,"#iframe-wrapper");h.style.overflow="hidden",g.style.top=h.scrollTop+"px",g.style.height=h.clientHeight*.9+"px";let c=document.createElement("div");c.className="d2-popover-wrapper",g.appendChild(c);let p=document.createElement("div");p.className="d2-popover-content",c.appendChild(p),(f=this.navigator.api)!=null&&f.getContent?await((u=this.navigator.api)==null?void 0:u.getContent(r).then(E=>{p.innerHTML=E;let b=this.navigator.iframes[0].contentDocument;b&&b.body.appendChild(g)})):await fetch(_,this.navigator.requestConfig).then(E=>E.text()).then(async E=>{p.innerHTML=E;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.addEventListener("click",function(E){t.target!==E.target&&g.parentElement&&(A.hidePopover(),E.stopImmediatePropagation())},{once:!0,capture:!0})}}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=yt(document,"#iframe-wrapper");h.style.overflow="hidden",g.style.top=h.scrollTop+"px",g.style.height=h.clientHeight*.9+"px";let c=document.createElement("div");c.className="d2-popover-wrapper",g.appendChild(c);let p=document.createElement("img");p.className="d2-popover-content",c.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 E=this;A.addEventListener("click",function(b){t.target!==b.target&&g.parentElement&&(E.hidePopover(),b.stopImmediatePropagation())},{once:!0,capture:!0})}}showPopup(e,t){var c,p,w;let r=(c=this.navigator.iframes[0].contentDocument)==null?void 0:c.getElementById("d2-popup");r&&((p=r.parentElement)==null||p.removeChild(r));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 l=document.createElement("p");s.appendChild(l),typeof e=="string"?l.innerHTML=e:l.innerHTML=(0,Y6.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 Tf=rt($t());function we(n,e,t){n&&n.addEventListener(e,t,!0)}function Ue(n,e,t){n&&n.removeEventListener(e,t,!0)}var _l=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(r=>{var i;return!((i=r.Rel)!=null&&i.includes("external"))&&this.navigator.publication.getRelativeHref(t).includes(r.Href)});this.isReadingOrderInternal=e=>(Tf.default.log("clickedLink: ",e),this.linkInPublication(this.navigator.publication.readingOrder,e.href));this.isResourceInternal=e=>(Tf.default.log("clickedLink: ",e),this.linkInPublication(this.navigator.publication.resources,e.href));this.handleLinks=async e=>{var r;Tf.default.log("R2 Click Handler");let t=this.checkForLink(e);if(t){let i=window.location.protocol===t.protocol&&window.location.port===t.port&&window.location.hostname===t.hostname,o=this.isReadingOrderInternal(t),s=this.isResourceInternal(t);s||await this.popup.hidePopover();let l=t.href.indexOf("#");if(!o&&!s)window.open(t.href,t.target??"_blank"),e.preventDefault(),e.stopPropagation();else if(e.target.href=t.href,(i||o)&&l!==-1){let f=e.target;f?f.getAttribute("epub:type")==="noteref"?await this.popup.handleFootnote(f,e):s&&!o?await this.popup.showPopover(f,e):this.onInternalLink(e):this.onInternalLink(e)}else(i||o)&&l===-1&&this.onInternalLink(e)}else(r=this.navigator.highlighter)!=null&&r.isSelectionMenuOpen||this.onClickThrough(e)};this.navigator=e,this.popup=new Ba(this.navigator)}setupEvents(e){if(e!==null)e.addEventListener("dblclick",async t=>{let r=t.target;t.target&&r.tagName.toLowerCase()==="img"&&await this.popup.showPopover(r,t)},!0),e.addEventListener("click",this.handleLinks.bind(this),!0);else throw"cannot setup events for null"}};L();L();function Q6(){return yt(document,"#iframe-wrapper").clientWidth}function gi(){return yt(document,"#iframe-wrapper").clientHeight}var ew=rt(Vo()),wl=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 r=this.iframe.contentDocument;if(r){let i=cr(r,"head");if(i){let s=Le(i,"meta[name=viewport]");s&&s.remove()}let o=cr(r,"html");o&&o.style.setProperty("--USER__scroll","readium-scroll-on")}this.setSize(),this.setIframeHeight(this.iframe)}else{this.height=gi()-40-this.attributes.margin,this.name="readium-scroll-off",this.label="Paginated",this.checkForFixedScrollWidth();let r=this.iframe.contentDocument;if(r){let i=cr(r,"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 r=Le(t,"meta[name=viewport]");r&&r.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"),r=Array.prototype.slice.call(t.querySelectorAll("img"));for(let i of r)i.style.maxWidth=""}}getCurrentPosition(){let e=yt(document,"#iframe-wrapper");if(this.scrollMode)return e.scrollTop/this.scrollingElement.scrollHeight;{let t=this.getColumnWidth(),r=this.getLeftColumnsWidth(),i=this.getRightColumnsWidth(),o=r+t+i;return r/o}}goToProgression(e){let t=yt(document,"#iframe-wrapper");if(this.scrollMode)t.scrollTop=this.scrollingElement.scrollHeight*e;else{let r=this.getColumnWidth(),i=this.getLeftColumnsWidth(),o=this.getRightColumnsWidth(),s=i+r+o,l=e*s,f=Math.round(l/r)*r;f>=s&&(f=f-r),this.setLeftColumnsWidth(f)}}goToCssSelector(e,t){let r=this.iframe.contentDocument;if(r){let i=r.querySelector(e);this.goToElement(i,t)}}goToFragment(e,t){let r=this.iframe.contentDocument;if(r){let i=r.getElementById(e);this.goToElement(i,t)}}snap(e,t){var r;if(e&&!this.scrollMode){let i=e.style.height;e.style.height="0";let o=this.getColumnWidth(),s=this.getLeftColumnsWidth()+e.getBoundingClientRect().left,l=Math.floor(s/o)*o;e.style.height=i,this.setLeftColumnsWidth(l),this.navigator.rights.enableContentProtection&&((r=this.navigator.contentProtectionModule)==null||r.recalculate(0))}}goToElement(e,t){var r;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(),l=this.scrollingElement.scrollLeft-s,f=Math.ceil(o/s)*s+l;if(t){let u=this.getLeftColumnsWidth();f=Math.ceil(o/s)*s+u}e.style.height=i,this.setLeftColumnsWidth(f),this.navigator.rights.enableContentProtection&&((r=this.navigator.contentProtectionModule)==null||r.recalculate(200))}}atStart(){return this.scrollMode?yt(document,"#iframe-wrapper").scrollTop===0:this.getLeftColumnsWidth()<=0}atEnd(){if(this.scrollMode){let e=yt(document,"#iframe-wrapper");return Math.ceil(this.scrollingElement.scrollHeight-e.scrollTop)-1<=gi()}else return Math.floor(this.getRightColumnsWidth())<=0||Math.ceil(this.getCurrentPage())===this.getPageCount()}goToPreviousPage(){var t;let e=yt(document,"#iframe-wrapper");if(this.scrollMode){let r=e.scrollTop,i=this.getScreenHeight()-40,o=r-i;o>=0?e.scrollTop=o:e.scrollTop=0}else{let r=this.getLeftColumnsWidth(),i=this.getColumnWidth(),o=r-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=yt(document,"#iframe-wrapper");if(this.scrollMode){let r=e.scrollTop,i=this.getScreenHeight()-40,o=this.scrollingElement.scrollHeight,s=r+i;s<o?e.scrollTop=s:e.scrollTop=o}else{let r=this.getLeftColumnsWidth(),i=this.getColumnWidth(),o=this.scrollWidth,s=r+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 r=JSON.parse(t);return r=r.filter(i=>i.name===e),r.length===0?null:r[0]}return null}getScreenHeight(){return yt(document,"#iframe-wrapper").clientHeight}setIframeHeight(e){(0,ew.default)(r=>{if(r){let i=r.contentWindow.document.body,o=r.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 l=gi()-this.attributes.margin;r.height=Math.max(l,s)+"px"}}},200)(e)}checkForFixedScrollWidth(){let e=this.iframe.contentDocument;if(e){let t=cr(e,"body"),r=t==null?void 0:t.scrollWidth;this.hasFixedScrollWidth=(t==null?void 0:t.scrollWidth)===r}}setSize(){var e,t;if(this.iframe.width=Q6()+"px",this.scrollMode){let r=(t=(e=this.iframe.contentWindow)==null?void 0:e.document)==null?void 0:t.documentElement;this.iframe.height=(r==null?void 0:r.offsetHeight)+"px"}else{let r=this.iframe.contentDocument;r&&r.documentElement&&(r.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 r=this.getLeftColumnsWidth();t=Math.max(0,t-r)}return t}getColumnWidth(){return this.scrollingElement.clientWidth}setLeftColumnsWidth(e){this.scrollingElement.scrollLeft=e}get scrollingElement(){var e,t,r,i;return(e=this.iframe.contentDocument)!=null&&e.scrollingElement?(t=this.iframe.contentDocument)==null?void 0:t.scrollingElement:(r=this.iframe.contentDocument)!=null&&r.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 Sl=class{constructor(){this.layout="fixed";this.sideMargin=20;this.height=0;this.attributes={margin:0}}start(){}stop(){}getCurrentPosition(){return 0}getScreenHeight(){return yt(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 dn=rt($t()),dt=class dt{constructor(e,t,r,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.direction=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 Sl:new wl(this.store),this.headerMenu=t,this.api=r,this.injectables=i,(s=this.injectables)==null||s.forEach(l=>{l.type==="style"&&(l.fontFamily&&this.addFont(l.fontFamily),l.appearance&&this.addAppearance(l.appearance))})}async isPaginated(){return!await this.getPropertyAndFallback("verticalScroll",_e.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 r=e.initialUserSettings;if(r.verticalScroll!==void 0){t.verticalScroll=this.parseScrollSetting(r.verticalScroll);let i=t.userProperties.getByRef(_e.SCROLL_REF);i&&(i.value=t.verticalScroll,await t.saveProperty(i)),dn.default.log(t.verticalScroll)}if(r.appearance){t.appearance=dt.parseAppearanceSetting(r.appearance);let i=t.userProperties.getByRef(_e.APPEARANCE_REF);i&&(i.value=t.appearance,await t.saveProperty(i)),dn.default.log(t.appearance)}if(r.fontSize){t.fontSize=r.fontSize;let i=t.userProperties.getByRef(_e.FONT_SIZE_REF);i&&(i.value=t.fontSize,await t.saveProperty(i)),dn.default.log(t.fontSize)}if(r.fontFamily){t.fontFamily=dt.fontFamilyValues.findIndex(o=>o===r.fontFamily);let i=t.userProperties.getByRef(_e.FONT_FAMILY_REF);i&&(i.value=t.fontFamily,await t.saveProperty(i)),dn.default.log(t.fontFamily),t.fontFamily!==0&&(t.fontOverride=!0)}if(r.textAlignment){t.textAlignment=dt.textAlignmentValues.findIndex(o=>o===r.textAlignment);let i=t.userProperties.getByRef(_e.TEXT_ALIGNMENT_REF);i&&(i.value=t.textAlignment,await t.saveProperty(i)),dn.default.log(t.textAlignment)}if(r.columnCount){t.columnCount=dt.columnCountValues.findIndex(o=>o===r.columnCount);let i=t.userProperties.getByRef(_e.COLUMN_COUNT_REF);i&&(i.value=t.columnCount,await t.saveProperty(i)),dn.default.log(t.columnCount)}if(r.direction){t.direction=dt.directionValues.findIndex(o=>o===r.direction);let i=t.userProperties.getByRef(_e.DIRECTION_REF);i&&(i.value=t.direction,await t.saveProperty(i)),dn.default.log(t.direction)}if(r.wordSpacing){t.wordSpacing=r.wordSpacing;let i=t.userProperties.getByRef(_e.WORD_SPACING_REF);i&&(i.value=t.wordSpacing,await t.saveProperty(i)),dn.default.log(t.wordSpacing)}if(r.letterSpacing){t.letterSpacing=r.letterSpacing;let i=t.userProperties.getByRef(_e.LETTER_SPACING_REF);i&&(i.value=t.letterSpacing,await t.saveProperty(i)),dn.default.log(t.letterSpacing)}if(r.pageMargins){t.pageMargins=r.pageMargins;let i=t.userProperties.getByRef(_e.PAGE_MARGINS_REF);i&&(i.value=t.pageMargins,await t.saveProperty(i)),dn.default.log(t.pageMargins)}if(r.lineHeight){t.lineHeight=r.lineHeight;let i=t.userProperties.getByRef(_e.LINE_HEIGHT_REF);i&&(i.value=t.lineHeight,await t.saveProperty(i)),dn.default.log(t.lineHeight)}t.userProperties=t.getUserSettings(),await t.initialise()}return await t.initializeSelections(),new Promise(r=>r(t))}stop(){dn.default.log("book settings stop")}async initialise(){this.appearance=await this.getPropertyAndFallback("appearance",_e.APPEARANCE_KEY),this.verticalScroll=await this.getPropertyAndFallback("verticalScroll",_e.SCROLL_KEY),this.fontFamily=await this.getPropertyAndFallback("fontFamily",_e.FONT_FAMILY_KEY),this.fontFamily!==0&&(this.fontOverride=!0),this.textAlignment=await this.getPropertyAndFallback("textAlignment",_e.TEXT_ALIGNMENT_KEY),this.columnCount=await this.getPropertyAndFallback("columnCount",_e.COLUMN_COUNT_KEY),this.direction=await this.getPropertyAndFallback("direction",_e.DIRECTION_KEY),this.fontSize=await this.getPropertyAndFallback("fontSize",_e.FONT_SIZE_KEY),this.wordSpacing=await this.getPropertyAndFallback("wordSpacing",_e.WORD_SPACING_KEY),this.letterSpacing=await this.getPropertyAndFallback("letterSpacing",_e.LETTER_SPACING_KEY),this.pageMargins=await this.getPropertyAndFallback("pageMargins",_e.PAGE_MARGINS_KEY),this.lineHeight=await this.getPropertyAndFallback("lineHeight",_e.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.direction=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 r=Le(document,"#root")||document.documentElement,i=Le(t,"body");t.style.removeProperty(_e.FONT_SIZE_KEY),t.style.removeProperty(_e.WORD_SPACING_KEY),t.style.removeProperty(_e.LETTER_SPACING_KEY),t.style.removeProperty(_e.COLUMN_COUNT_KEY),t.style.removeProperty(_e.DIRECTION_KEY),t.style.removeProperty(_e.TEXT_ALIGNMENT_KEY),t.style.removeProperty(_e.LINE_HEIGHT_KEY),t.style.removeProperty(_e.PAGE_MARGINS_KEY),t.style.removeProperty(_e.APPEARANCE_KEY),r&&Ir(r,"data-viewer-theme","day"),i&&Ir(i,"data-viewer-theme","day"),t.style.removeProperty(_e.FONT_FAMILY_KEY),Ir(t,"data-viewer-font","publisher"),t.style.setProperty(_e.FONT_OVERRIDE_KEY,"readium-font-off")}}}async initializeSelections(){this.headerMenu&&(this.settingsView=Le(this.headerMenu,"#container-view-settings"))}async applyProperties(){var t,r,i,o,s,l,f,u,y,m,_,v,g,h,c,p,w,A,E,b,C,k,R,B;this.userProperties=this.getUserSettings();let e=this.iframe.contentDocument;if(e){let I=cr(e,"html");if(I){let D=Le(document,"#root")||document.documentElement,F=Le(I,"body");if((t=this.view)!=null&&t.navigator.publication.isReflowable&&(await this.getProperty(_e.FONT_SIZE_KEY)&&I.style.setProperty(_e.FONT_SIZE_KEY,((r=this.userProperties.getByRef(_e.FONT_SIZE_REF))==null?void 0:r.toString())??null),await this.getProperty(_e.WORD_SPACING_KEY)&&I.style.setProperty(_e.WORD_SPACING_KEY,((i=this.userProperties.getByRef(_e.WORD_SPACING_REF))==null?void 0:i.toString())??null),await this.getProperty(_e.LETTER_SPACING_KEY)&&I.style.setProperty(_e.LETTER_SPACING_KEY,((o=this.userProperties.getByRef(_e.LETTER_SPACING_REF))==null?void 0:o.toString())??null)),await this.getProperty(_e.COLUMN_COUNT_KEY)&&I.style.setProperty(_e.COLUMN_COUNT_KEY,((s=this.userProperties.getByRef(_e.COLUMN_COUNT_REF))==null?void 0:s.toString())??null),(l=this.view)!=null&&l.navigator.publication.isReflowable&&(await this.getProperty(_e.TEXT_ALIGNMENT_KEY)&&(((f=this.userProperties.getByRef(_e.TEXT_ALIGNMENT_REF))==null?void 0:f.toString())==="auto"?I.style.removeProperty(_e.TEXT_ALIGNMENT_KEY):I.style.setProperty(_e.TEXT_ALIGNMENT_KEY,((u=this.userProperties.getByRef(_e.TEXT_ALIGNMENT_REF))==null?void 0:u.toString())??null)),await this.getProperty(_e.LINE_HEIGHT_KEY)&&I.style.setProperty(_e.LINE_HEIGHT_KEY,((y=this.userProperties.getByRef(_e.LINE_HEIGHT_REF))==null?void 0:y.toString())??null),await this.getProperty(_e.PAGE_MARGINS_KEY)&&I.style.setProperty(_e.PAGE_MARGINS_KEY,((m=this.userProperties.getByRef(_e.PAGE_MARGINS_REF))==null?void 0:m.toString())??null)),await this.getProperty(_e.APPEARANCE_KEY)?(I.style.setProperty(_e.APPEARANCE_KEY,((_=this.userProperties.getByRef(_e.APPEARANCE_REF))==null?void 0:_.toString())??null),((v=this.userProperties.getByRef(_e.APPEARANCE_REF))==null?void 0:v.value)===0?(D&&Ir(D,"data-viewer-theme","day"),F&&Ir(F,"data-viewer-theme","day")):((g=this.userProperties.getByRef(_e.APPEARANCE_REF))==null?void 0:g.value)===1?(D&&Ir(D,"data-viewer-theme","sepia"),F&&Ir(F,"data-viewer-theme","sepia")):((h=this.userProperties.getByRef(_e.APPEARANCE_REF))==null?void 0:h.value)===2&&(D&&Ir(D,"data-viewer-theme","night"),F&&Ir(F,"data-viewer-theme","night"))):(I.style.setProperty(_e.APPEARANCE_KEY,((c=this.userProperties.getByRef(_e.APPEARANCE_REF))==null?void 0:c.toString())??null),D&&Ir(D,"data-viewer-theme","day"),F&&Ir(F,"data-viewer-theme","day")),(p=this.view)!=null&&p.navigator.publication.isFixedLayout&&await this.getProperty(_e.DIRECTION_KEY)){let z=((w=this.userProperties.getByRef(_e.DIRECTION_REF))==null?void 0:w.toString())??null;I.style.setProperty(_e.DIRECTION_KEY,z),this.view.navigator.setDirection(z)}if((A=this.view)!=null&&A.navigator.publication.isReflowable){if(await this.getProperty(_e.FONT_FAMILY_KEY))if(I.style.setProperty(_e.FONT_FAMILY_KEY,((E=this.userProperties.getByRef(_e.FONT_FAMILY_REF))==null?void 0:E.toString())??null),((b=this.userProperties.getByRef(_e.FONT_FAMILY_REF))==null?void 0:b.value)===0)Ir(I,"data-viewer-font","publisher"),I.style.setProperty(_e.FONT_OVERRIDE_KEY,"readium-font-off");else if(((C=this.userProperties.getByRef(_e.FONT_FAMILY_REF))==null?void 0:C.value)===1)Ir(I,"data-viewer-font","serif"),I.style.setProperty(_e.FONT_OVERRIDE_KEY,"readium-font-on");else if(((k=this.userProperties.getByRef(_e.FONT_FAMILY_REF))==null?void 0:k.value)===2)Ir(I,"data-viewer-font","sans"),I.style.setProperty(_e.FONT_OVERRIDE_KEY,"readium-font-on");else{let z=this.userProperties.getByRef(_e.FONT_FAMILY_REF);z&&Ir(I,"data-viewer-font",z.toString()),I.style.setProperty(_e.FONT_OVERRIDE_KEY,"readium-font-on")}else I.style.setProperty(_e.FONT_FAMILY_KEY,((R=this.userProperties.getByRef(_e.FONT_FAMILY_REF))==null?void 0:R.toString())??null),Ir(I,"data-viewer-font","publisher"),I.style.setProperty(_e.FONT_OVERRIDE_KEY,"readium-font-off");await this.getProperty(_e.SCROLL_KEY)?((B=this.userProperties.getByRef(_e.SCROLL_REF))==null?void 0:B.value)===!0?I.style.setProperty("--USER__scroll","readium-scroll-on"):I.style.setProperty("--USER__scroll","readium-scroll-off"):I.style.setProperty("--USER__scroll","readium-scroll-on"),I.style.setProperty("--USER__advancedSettings","readium-advanced-on"),this.isScrollMode().then(z=>{var q,G;(G=(q=this.view)==null?void 0:q.setMode)==null||G.call(q,z)})}}}}setIframe(e){this.iframe=e,this.view&&(this.view.iframe=e),this.settingsView&&dt.renderControls(this.settingsView)}static renderControls(e){we(Le(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){dt.appearanceValues.includes(e)||dt.appearanceValues.push(e)}initAddedAppearance(){this.applyProperties()}addFont(e){dt.fontFamilyValues.includes(e)||dt.fontFamilyValues.push(e)}initAddedFont(){this.applyProperties()}async updateUserSettings(){var t,r,i,o,s,l,f,u,y,m,_,v,g,h,c,p,w,A,E,b;let e={fontFamily:dt.fontFamilyValues[await((r=(t=this.userProperties)==null?void 0:t.getByRef(_e.FONT_FAMILY_REF))==null?void 0:r.value)],fontSize:(o=(i=this.userProperties)==null?void 0:i.getByRef(_e.FONT_SIZE_REF))==null?void 0:o.value,appearance:dt.appearanceValues[await((l=(s=this.userProperties)==null?void 0:s.getByRef(_e.APPEARANCE_REF))==null?void 0:l.value)],textAlignment:dt.textAlignmentValues[await((u=(f=this.userProperties)==null?void 0:f.getByRef(_e.TEXT_ALIGNMENT_REF))==null?void 0:u.value)],columnCount:dt.columnCountValues[await((m=(y=this.userProperties)==null?void 0:y.getByRef(_e.COLUMN_COUNT_REF))==null?void 0:m.value)],direction:dt.directionValues[await((v=(_=this.userProperties)==null?void 0:_.getByRef(_e.DIRECTION_REF))==null?void 0:v.value)],wordSpacing:(h=(g=this.userProperties)==null?void 0:g.getByRef(_e.WORD_SPACING_REF))==null?void 0:h.value,letterSpacing:(p=(c=this.userProperties)==null?void 0:c.getByRef(_e.LETTER_SPACING_REF))==null?void 0:p.value,verticalScroll:(A=(w=this.userProperties)==null?void 0:w.getByRef(_e.SCROLL_REF))==null?void 0:A.value};(E=this.api)!=null&&E.updateSettings&&((b=this.api)==null||b.updateSettings(e).then(C=>{dn.default.log("api updated user settings",JSON.stringify(e))}))}getUserSettings(){let e=new Li;return e.addSwitchable("readium-font-on","readium-font-off",this.fontOverride,_e.FONT_OVERRIDE_REF,_e.FONT_OVERRIDE_KEY),e.addEnumerable(this.columnCount,dt.columnCountValues,_e.COLUMN_COUNT_REF,_e.COLUMN_COUNT_KEY),e.addEnumerable(this.direction,dt.directionValues,_e.DIRECTION_REF,_e.DIRECTION_KEY),e.addEnumerable(this.appearance,dt.appearanceValues,_e.APPEARANCE_REF,_e.APPEARANCE_KEY),e.addIncremental(this.pageMargins,.5,4,.25,"",_e.PAGE_MARGINS_REF,_e.PAGE_MARGINS_KEY),e.addEnumerable(this.textAlignment,dt.textAlignmentValues,_e.TEXT_ALIGNMENT_REF,_e.TEXT_ALIGNMENT_KEY),e.addEnumerable(this.fontFamily,dt.fontFamilyValues,_e.FONT_FAMILY_REF,_e.FONT_FAMILY_KEY),e.addIncremental(this.fontSize,100,300,25,"%",_e.FONT_SIZE_REF,_e.FONT_SIZE_KEY),e.addIncremental(this.lineHeight,1,2,.25,"em",_e.LINE_HEIGHT_REF,_e.LINE_HEIGHT_KEY),e.addIncremental(this.wordSpacing,0,1,.25,"rem",_e.WORD_SPACING_REF,_e.WORD_SPACING_KEY),e.addIncremental(this.letterSpacing,0,.5,.0625,"em",_e.LETTER_SPACING_REF,_e.LETTER_SPACING_KEY),e.addSwitchable("readium-scroll-on","readium-scroll-off",this.verticalScroll,_e.SCROLL_REF,_e.SCROLL_KEY),e}async saveProperty(e){let t=await this.store.get(this.USERSETTINGS);if(t){let r=JSON.parse(t);r=r.filter(i=>i.name!==e.name),e.value!==void 0&&r.push(e),await this.store.set(this.USERSETTINGS,JSON.stringify(r))}else{let r=[];r.push(e),await this.store.set(this.USERSETTINGS,JSON.stringify(r))}return new Promise(r=>r(e))}async getProperty(e){let t=await this.store.get(this.USERSETTINGS);if(t){let r=JSON.parse(t);return r=r.filter(i=>i.name===e),r.length===0?null:r[0]}return null}async getPropertyAndFallback(e,t){var r;return((r=await this.getProperty(t))==null?void 0:r.value)??this[e]}async resetUserSettings(){this.store.remove(this.USERSETTINGS),await this.reset(),this.viewChangeCallback(),this.settingsChangeCallback()}get currentSettings(){var e,t,r,i,o,s,l,f,u,y;return{appearance:dt.appearanceValues[(t=(e=this.userProperties)==null?void 0:e.getByRef(_e.APPEARANCE_REF))==null?void 0:t.value],fontFamily:dt.fontFamilyValues[(i=(r=this.userProperties)==null?void 0:r.getByRef(_e.FONT_FAMILY_REF))==null?void 0:i.value],textAlignment:dt.textAlignmentValues[(s=(o=this.userProperties)==null?void 0:o.getByRef(_e.TEXT_ALIGNMENT_REF))==null?void 0:s.value],columnCount:dt.columnCountValues[(f=(l=this.userProperties)==null?void 0:l.getByRef(_e.COLUMN_COUNT_REF))==null?void 0:f.value],direction:dt.directionValues[(y=(u=this.userProperties)==null?void 0:u.getByRef(_e.DIRECTION_REF))==null?void 0:y.value],verticalScroll:this.verticalScroll,fontSize:this.fontSize,wordSpacing:this.wordSpacing,letterSpacing:this.letterSpacing,pageMargins:this.pageMargins,lineHeight:this.lineHeight}}async applyUserSettings(e){var t,r,i,o,s,l,f,u,y,m,_,v,g,h,c;if(e.appearance){this.appearance=dt.parseAppearanceSetting(e.appearance);let p=(t=this.userProperties)==null?void 0:t.getByRef(_e.APPEARANCE_REF);p&&(p.value=this.appearance,await this.storeProperty(p))}if(e.fontSize){this.fontSize=e.fontSize;let p=(r=this.userProperties)==null?void 0:r.getByRef(_e.FONT_SIZE_REF);p&&(p.value=this.fontSize,await this.storeProperty(p))}if(e.fontFamily){this.fontFamily=dt.fontFamilyValues.findIndex(w=>w===e.fontFamily);let p=(i=this.userProperties)==null?void 0:i.getByRef(_e.FONT_FAMILY_REF);p&&(p.value=this.fontFamily,await this.storeProperty(p))}if(e.letterSpacing){this.letterSpacing=e.letterSpacing;let p=(o=this.userProperties)==null?void 0:o.getByRef(_e.LETTER_SPACING_REF);p&&(p.value=this.letterSpacing,await this.storeProperty(p))}if(e.wordSpacing){this.wordSpacing=e.wordSpacing;let p=(s=this.userProperties)==null?void 0:s.getByRef(_e.WORD_SPACING_REF);p&&(p.value=this.wordSpacing,await this.storeProperty(p))}if(e.columnCount){this.columnCount=dt.columnCountValues.findIndex(w=>w===e.columnCount);let p=(l=this.userProperties)==null?void 0:l.getByRef(_e.COLUMN_COUNT_REF);p&&(p.value=this.columnCount,await this.storeProperty(p)),this.settingsColumnsChangeCallback()}if(e.direction){this.direction=dt.directionValues.findIndex(w=>w===e.direction);let p=(f=this.userProperties)==null?void 0:f.getByRef(_e.DIRECTION_REF);p&&(p.value=this.direction,await this.storeProperty(p))}if(e.textAlignment){this.textAlignment=dt.textAlignmentValues.findIndex(w=>w===e.textAlignment);let p=(u=this.userProperties)==null?void 0:u.getByRef(_e.TEXT_ALIGNMENT_REF);p&&(p.value=this.textAlignment,await this.storeProperty(p))}if(e.lineHeight){this.lineHeight=e.lineHeight;let p=(y=this.userProperties)==null?void 0:y.getByRef(_e.LINE_HEIGHT_REF);p&&(p.value=this.lineHeight,await this.storeProperty(p))}if(e.pageMargins){this.pageMargins=e.pageMargins;let p=(m=this.userProperties)==null?void 0:m.getByRef(_e.PAGE_MARGINS_REF);p&&(p.value=this.pageMargins,await this.storeProperty(p))}if(e.verticalScroll!==void 0){let p=(_=this.view)==null?void 0:_.getCurrentPosition();this.verticalScroll=dt.parseScrollSetting(e.verticalScroll);let w=(v=this.userProperties)==null?void 0:v.getByRef(_e.SCROLL_REF);w&&(w.value=this.verticalScroll,await this.saveProperty(w)),(h=(g=this.view)==null?void 0:g.setMode)==null||h.call(g,this.verticalScroll),p&&((c=this.view)==null||c.goToProgression(p)),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=dt.appearanceValues[0]:e==="sepia"||e==="readium-sepia-on"?t=dt.appearanceValues[1]:e==="night"||e==="readium-night-on"?t=dt.appearanceValues[2]:t=e,dt.appearanceValues.findIndex(r=>r===t)}async scroll(e){var i,o,s,l,f;let t=(i=this.view)==null?void 0:i.getCurrentPosition();this.verticalScroll=e;let r=(o=this.userProperties)==null?void 0:o.getByRef(_e.SCROLL_REF);r&&(r.value=this.verticalScroll,await this.saveProperty(r)),await this.applyProperties(),(l=(s=this.view)==null?void 0:s.setMode)==null||l.call(s,this.verticalScroll),t&&((f=this.view)==null||f.goToProgression(t)),this.viewChangeCallback()}async increase(e){var t,r,i,o,s,l,f,u,y,m,_,v,g,h,c,p;if(e==="fontSize"){((t=this.userProperties)==null?void 0:t.getByRef(_e.FONT_SIZE_REF)).increment(),this.fontSize=(i=(r=this.userProperties)==null?void 0:r.getByRef(_e.FONT_SIZE_REF))==null?void 0:i.value;let w=(o=this.userProperties)==null?void 0:o.getByRef(_e.FONT_SIZE_REF);w&&await this.storeProperty(w)}else if(e==="letterSpacing"){((s=this.userProperties)==null?void 0:s.getByRef(_e.LETTER_SPACING_REF)).increment(),this.letterSpacing=(f=(l=this.userProperties)==null?void 0:l.getByRef(_e.LETTER_SPACING_REF))==null?void 0:f.value;let w=(u=this.userProperties)==null?void 0:u.getByRef(_e.LETTER_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="wordSpacing"){((y=this.userProperties)==null?void 0:y.getByRef(_e.WORD_SPACING_REF)).increment(),this.wordSpacing=(_=(m=this.userProperties)==null?void 0:m.getByRef(_e.WORD_SPACING_REF))==null?void 0:_.value;let w=(v=this.userProperties)==null?void 0:v.getByRef(_e.WORD_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="lineHeight"){((g=this.userProperties)==null?void 0:g.getByRef(_e.LINE_HEIGHT_REF)).increment(),this.lineHeight=(c=(h=this.userProperties)==null?void 0:h.getByRef(_e.LINE_HEIGHT_REF))==null?void 0:c.value;let w=(p=this.userProperties)==null?void 0:p.getByRef(_e.LINE_HEIGHT_REF);w&&await this.storeProperty(w)}await this.applyProperties(),this.settingsChangeCallback()}async decrease(e){var t,r,i,o,s,l,f,u,y,m,_,v,g,h,c,p;if(e==="fontSize"){((t=this.userProperties)==null?void 0:t.getByRef(_e.FONT_SIZE_REF)).decrement(),this.fontSize=(i=(r=this.userProperties)==null?void 0:r.getByRef(_e.FONT_SIZE_REF))==null?void 0:i.value;let w=(o=this.userProperties)==null?void 0:o.getByRef(_e.FONT_SIZE_REF);w&&await this.storeProperty(w)}else if(e==="letterSpacing"){((s=this.userProperties)==null?void 0:s.getByRef(_e.LETTER_SPACING_REF)).decrement(),this.letterSpacing=(f=(l=this.userProperties)==null?void 0:l.getByRef(_e.LETTER_SPACING_REF))==null?void 0:f.value;let w=(u=this.userProperties)==null?void 0:u.getByRef(_e.LETTER_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="wordSpacing"){((y=this.userProperties)==null?void 0:y.getByRef(_e.WORD_SPACING_REF)).decrement(),this.wordSpacing=(_=(m=this.userProperties)==null?void 0:m.getByRef(_e.WORD_SPACING_REF))==null?void 0:_.value;let w=(v=this.userProperties)==null?void 0:v.getByRef(_e.WORD_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="lineHeight"){((g=this.userProperties)==null?void 0:g.getByRef(_e.LINE_HEIGHT_REF)).decrement(),this.wordSpacing=(c=(h=this.userProperties)==null?void 0:h.getByRef(_e.LINE_HEIGHT_REF))==null?void 0:c.value;let w=(p=this.userProperties)==null?void 0:p.getByRef(_e.LINE_HEIGHT_REF);w&&await this.storeProperty(w)}await this.applyProperties(),this.settingsChangeCallback()}};dt.appearanceValues=["readium-default-on","readium-sepia-on","readium-night-on"],dt.fontFamilyValues=["Original","serif","sans-serif"],dt.textAlignmentValues=["auto","justify","start"],dt.columnCountValues=["auto","1","2"],dt.directionValues=["auto","ltr","rtl"];var Al=dt;L();L();L();L();L();L();L();L();var tw={stringify(n){let e=n.nSigBytes,t=n.words,r=[];for(let i=0;i<e;i++){let o=t[i>>>2]>>>24-i%4*8&255;r.push((o>>>4).toString(16)),r.push((o&15).toString(16))}return r.join("")},parse(n){let e=n.length;if(e%2!==0)throw new Error("Hex string count must be even");if(!/^[a-fA-F0-9]+$/.test(n))throw new Error(`Invalid Hex string: ${n}`);let t=[];for(let r=0;r<e;r+=2)t[r>>>3]|=parseInt(n.substr(r,2),16)<<24-r%8*4;return new In(t,e/2)}};L();L();var rw=typeof navigator<"u"&&navigator.userAgent?navigator.userAgent.toLowerCase():"",Ms=(()=>{let n=parseInt((/msie (\d+)/.exec(rw)||[])[1],10);return isNaN(n)?(n=parseInt((/trident\/.*; rv:(\d+)/.exec(rw)||[])[1],10),isNaN(n)?!1:n):n})();function nw(n,e){return Ms===!1?!1:e?n==="<"?Ms<e:n==="<="?Ms<=e:n===">"?Ms>e:n===">="?Ms>=e:Ms===e:!0}function CB(){if(typeof window<"u"){let n=window.crypto||window.msCrypto;if(!n){if(nw("<",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 n.getRandomValues(new Uint32Array(1))[0]}}else{if(typeof globalThis<"u"&&globalThis.crypto)return function(){return globalThis.crypto.randomBytes(4).readInt32LE()};if(typeof Tu=="function")return function(){return __non_webpack_require__("crypto").randomBytes(4).readInt32LE()}}throw new Error("Unable to find crypto module")}var iw=CB();var In=class n{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 n){this._words=e.words.slice(),this._nSignificantBytes=e.nSigBytes;return}let r;try{e instanceof ArrayBuffer?r=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)&&(r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}catch{throw new Error("Invalid argument")}if(!r)throw new Error("Invalid argument");let i=r.byteLength,o=[];for(let s=0;s<i;s++)o[s>>>2]|=r[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):tw.stringify(this)}toUint8Array(){let e=this._words,t=this._nSignificantBytes,r=new Uint8Array(t);for(let i=0;i<t;i++)r[i]=e[i>>>2]>>>24-i%4*8&255;return r}concat(e){let t=e.words.slice(),r=e.nSigBytes;if(this.clamp(),this._nSignificantBytes%4)for(let i=0;i<r;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<r;i+=4)this._words[this._nSignificantBytes+i>>>2]=t[i>>>2];return this._nSignificantBytes+=r,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 n(this._words.slice(),this._nSignificantBytes)}static random(e){let t=[];for(let r=0;r<e;r+=4)t.push(iw());return new n(t,e)}};L();L();var jg={stringify(n){let e=n.nSigBytes,t=n.words,r=[];for(let i=0;i<e;i++){let o=t[i>>>2]>>>24-i%4*8&255;r.push(String.fromCharCode(o))}return r.join("")},parse(n){let e=n.length,t=[];for(let r=0;r<e;r++)t[r>>>2]|=(n.charCodeAt(r)&255)<<24-r%4*8;return new In(t,e)}};var ow={stringify(n){try{return decodeURIComponent(escape(jg.stringify(n)))}catch{throw new Error("Malformed UTF-8 data")}},parse(n){return jg.parse(unescape(encodeURIComponent(n)))}};var Pf=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"?ow.parse(e):e;this._data.concat(t),this._nBytes+=t.nSigBytes}_process(e){let t,r=this._data.words,i=this._data.nSigBytes,o=this._blockSize,s=this._blockSize*4,l=i/s;e?l=Math.ceil(l):l=Math.max((l|0)-this._minBufferSize,0);let f=l*o,u=Math.min(f*4,i);if(f){for(let y=0;y<f;y+=o)this._doProcessBlock(r,y);t=r.splice(0,f),this._data.nSigBytes-=u}return new In(t,u)}_doProcessBlock(e,t){throw new Error("Not implemented")}};var Of=class extends Pf{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 qg=[],aw=[];function xB(n){let e=Math.sqrt(n);for(let t=2;t<=e;t++)if(!(n%t))return!1;return!0}function sw(n){return(n-(n|0))*4294967296|0}(function(){let e=2,t=0;for(;t<64;)xB(e)&&(t<8&&(qg[t]=sw(Math.pow(e,1/2))),aw[t]=sw(Math.pow(e,1/3)),t++),e++})();var ks=[],Ui=class n extends Of{constructor(e){super(e),this._hash=new In(qg.slice(0)),this._props=e,e&&typeof e.hash<"u"&&(this._hash=e.hash.clone())}_doReset(){this._hash=new In(qg.slice(0))}_doProcessBlock(e,t){let r=this._hash.words,i=r[0],o=r[1],s=r[2],l=r[3],f=r[4],u=r[5],y=r[6],m=r[7];for(let _=0;_<64;_++){if(_<16)ks[_]=e[t+_]|0;else{let A=ks[_-15],E=(A<<25|A>>>7)^(A<<14|A>>>18)^A>>>3,b=ks[_-2],C=(b<<15|b>>>17)^(b<<13|b>>>19)^b>>>10;ks[_]=E+ks[_-7]+C+ks[_-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),c=(f<<26|f>>>6)^(f<<21|f>>>11)^(f<<7|f>>>25),p=m+c+v+aw[_]+ks[_],w=h+g;m=y,y=u,u=f,f=l+p|0,l=s,s=o,o=i,i=p+w|0}r[0]=r[0]+i|0,r[1]=r[1]+o|0,r[2]=r[2]+s|0,r[3]=r[3]+l|0,r[4]=r[4]+f|0,r[5]=r[5]+u|0,r[6]=r[6]+y|0,r[7]=r[7]+m|0}_doFinalize(){let e=this._data.words,t=this._nBytes*8,r=this._data.nSigBytes*8;return e[r>>>5]|=128<<24-r%32,e[(r+64>>>9<<4)+14]=Math.floor(t/4294967296),e[(r+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 n(e)}static hash(e,t){return new n(t).finalize(e)}};var xl=rt(Vo());L();L();var Ur=rt($t());function kf(n,e){let t=n.getClientRects();return Gg(t,e)}function Gg(n,e){let r=[];for(let f of n)r.push({bottom:f.bottom,height:f.height,left:f.left,right:f.right,top:f.top,width:f.width});let i=lw(r,1,e),o=RB(i,1),s=cw(o),l=2*2;for(let f=s.length-1;f>=0;f--){let u=s[f];if(!(u.width*u.height>l))if(s.length>1)Ur.default.log("CLIENT RECT: remove small"),s.splice(f,1);else{Ur.default.log("CLIENT RECT: remove small, but keep otherwise empty!");break}}return dw(s),Ur.default.log(`CLIENT RECT: reduced ${r.length} --> ${s.length}`),s}function Zn(n,e,t){return Math.abs(n-e)<=t}function TB(n,e){let t=Math.max(n.left,e.left),r=Math.min(n.right,e.right),i=Math.max(n.top,e.top),o=Math.min(n.bottom,e.bottom);return{bottom:o,height:Math.max(0,o-i),left:t,right:r,top:i,width:Math.max(0,r-t)}}function uw(n,e){let t=TB(e,n);if(t.height===0||t.width===0)return[n];let r=[];{let i={bottom:n.bottom,height:0,left:n.left,right:t.left,top:n.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&r.push(i)}{let i={bottom:t.top,height:0,left:t.left,right:t.right,top:n.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&r.push(i)}{let i={bottom:n.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&&r.push(i)}{let i={bottom:n.bottom,height:0,left:t.right,right:n.right,top:n.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&r.push(i)}return r}function Mf(n,e,t,r){return(n.left<e||Zn(n.left,e,r))&&(n.right>e||Zn(n.right,e,r))&&(n.top<t||Zn(n.top,t,r))&&(n.bottom>t||Zn(n.bottom,t,r))}function PB(n,e,t){return Mf(n,e.left,e.top,t)&&Mf(n,e.right,e.top,t)&&Mf(n,e.left,e.bottom,t)&&Mf(n,e.right,e.bottom,t)}function OB(n,e){let t=Math.min(n.left,e.left),r=Math.max(n.right,e.right),i=Math.min(n.top,e.top),o=Math.max(n.bottom,e.bottom);return{bottom:o,height:o-i,left:t,right:r,top:i,width:r-t}}function Wg(n,e,t){return(n.left<e.right||t>=0&&Zn(n.left,e.right,t))&&(e.left<n.right||t>=0&&Zn(e.left,n.right,t))&&(n.top<e.bottom||t>=0&&Zn(n.top,e.bottom,t))&&(e.top<n.bottom||t>=0&&Zn(e.top,n.bottom,t))}function lw(n,e,t){for(let r=0;r<n.length;r++)for(let i=r+1;i<n.length;i++){let o=n[r],s=n[i];if(o===s){Ur.default.log("mergeTouchingRects rect1 === rect2 ??!");continue}let l=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||l&&!f)&&Wg(o,s,e)){Ur.default.log(`CLIENT RECT: merging two into one, VERTICAL: ${l} HORIZONTAL: ${f} (${t})`);let _=n.filter(g=>g!==o&&g!==s),v=OB(o,s);return _.push(v),lw(_,e,t)}}return n}function cw(n){for(let e=0;e<n.length;e++)for(let t=e+1;t<n.length;t++){let r=n[e],i=n[t];if(r===i){Ur.default.log("replaceOverlappingRects rect1 === rect2 ??!");continue}if(Wg(r,i,-1)){let o=[],s,l,f=uw(r,i);if(f.length===1)o=f,s=r,l=i;else{let m=uw(i,r);f.length<m.length?(o=f,s=r,l=i):(o=m,s=i,l=r)}let u=[];u.push(l),Array.prototype.push.apply(u,o),dw(u),Ur.default.log(`CLIENT RECT: overlap, cut one rect into ${o.length}`);let y=n.filter(m=>m!==s);return Array.prototype.push.apply(y,o),cw(y)}}return n}function MB(n,e){return Math.max(0,Math.min(n.right,e.right)-Math.max(n.left,e.left))}function kB(n,e){return Math.max(0,Math.min(n.bottom,e.bottom)-Math.max(n.top,e.top))}function RB(n,e){let t=new Set(n);for(let r of n){if(!(r.width>1&&r.height>1)){Ur.default.log("CLIENT RECT: remove tiny"),t.delete(r);continue}for(let o of n)if(r!==o&&t.has(o)&&PB(o,r,e)){Ur.default.log("CLIENT RECT: remove contained"),t.delete(r);break}}return Array.from(t)}function dw(n){let e=[];for(let t of n)for(let r of n){if(t===r)continue;let i=e.indexOf(t)>=0,o=e.indexOf(r)>=0;if((!i||!o)&&Wg(t,r,-1)){i||e.push(t),o||e.push(r),Ur.default.log("CLIENT RECT: overlap ---"),Ur.default.log(`#1 TOP:${t.top} BOTTOM:${t.bottom} LEFT:${t.left} RIGHT:${t.right} WIDTH:${t.width} HEIGHT:${t.height}`),Ur.default.log(`#2 TOP:${r.top} BOTTOM:${r.bottom} LEFT:${r.left} RIGHT:${r.right} WIDTH:${r.width} HEIGHT:${r.height}`);let s=MB(t,r);Ur.default.log(`xOverlap: ${s}`);let l=kB(t,r);Ur.default.log(`yOverlap: ${l}`)}}e.length&&Ur.default.log(`CLIENT RECT: overlaps ${e.length}`)}L();var Ft=rt($t());function ji(n,e){let t=n?n.getSelection():null;if(!t)return;if(t.isCollapsed){Ft.default.log("^^^ SELECTION COLLAPSED.");return}let r=t.toString(),i=r.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):pw(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset);if(!o||o.collapsed){Ft.default.log("$$$$$$$$$$$$$$$$$ CANNOT GET NON-COLLAPSED SELECTION RANGE?!");return}let s=IB(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 l=mo(s,e);if(!l){Ft.default.log("^^^ SELECTION RANGE INFO FAIL?!");return}return{rangeInfo:l,cleanText:i,rawText:r,range:s}}function pw(n,e,t,r){try{let i=new Range;if(i.setStart(n,e),i.setEnd(t,r),!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,r),o.setEnd(n,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 mo(n,e){let t=n.startContainer.nodeType===Node.ELEMENT_NODE,r=t?n.startContainer:n.startContainer.parentNode&&n.startContainer.parentNode.nodeType===Node.ELEMENT_NODE?n.startContainer.parentNode:void 0;if(!r)return;let i=t?-1:Array.from(r.childNodes).indexOf(n.startContainer);if(i<-1)return;let o=e(r),s=n.endContainer.nodeType===Node.ELEMENT_NODE,l=s?n.endContainer:n.endContainer.parentNode&&n.endContainer.parentNode.nodeType===Node.ELEMENT_NODE?n.endContainer.parentNode:void 0;if(!l)return;let f=s?-1:Array.from(l.childNodes).indexOf(n.endContainer);if(f<-1)return;let u=e(l),y=LB(n.startContainer,n.endContainer);if(!y){Ft.default.log("^^^ NO RANGE COMMON ANCESTOR?!");return}if(n.commonAncestorContainer){let m=n.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?n.commonAncestorContainer:n.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:n.endOffset,startContainerChildTextNodeIndex:i,startContainerElementCssSelector:o,startOffset:n.startOffset}}function Rf(n,e){let t=n.querySelector(e.startContainerElementCssSelector);if(!t){Ft.default.log("^^^ convertRangeInfo NO START ELEMENT CSS SELECTOR?!");return}let r=t;if(e.startContainerChildTextNodeIndex>=0){if(e.startContainerChildTextNodeIndex>=t.childNodes.length){Ft.default.log("^^^ convertRangeInfo rangeInfo.startContainerChildTextNodeIndex >= startElement.childNodes.length?!");return}if(r=t.childNodes[e.startContainerChildTextNodeIndex],r.nodeType!==Node.TEXT_NODE){Ft.default.log("^^^ convertRangeInfo startContainer.nodeType !== Node.TEXT_NODE?!");return}}let i=n.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 pw(r,e.startOffset,o,e.endOffset)}function LB(n,e){if(n.nodeType===Node.ELEMENT_NODE&&n===e||n.nodeType===Node.ELEMENT_NODE&&n.contains(e))return n;if(e.nodeType===Node.ELEMENT_NODE&&e.contains(n))return e;let t=[],r=n.parentNode;for(;r&&r.nodeType===Node.ELEMENT_NODE;)t.push(r),r=r.parentNode;let i=[];for(r=e.parentNode;r&&r.nodeType===Node.ELEMENT_NODE;)i.push(r),r=r.parentNode;let o=t.find(s=>i.indexOf(s)>=0);return o||(o=i.find(s=>t.indexOf(s)>=0)),o}function IB(n){let e=n.cloneRange(),t=e.startContainer,r=e.startOffset,i=e.endContainer,o=e.endOffset;t.childNodes.length&&r>0&&(t=hw(t.childNodes[r-1]),r=t.length||0),o<i.childNodes.length&&(i=fw(i.childNodes[o]),o=0);let s=fw(t),l=hw(i);function f(u){if(u.childNodes.length)return!1;let y=u.length||0;return u===t&&r===y?!1:!(u===i&&o===0)}for(;s&&!f(s)&&s!==l;)s=NB(s);for(s===t?e.setStart(t,r):s!==null&&(s.nodeType===3?e.setStart(s,0):e.setStartBefore(s));l&&!f(l)&&l!==s;)l=BB(l);return l===i?e.setEnd(i,o):l!==null&&(l.nodeType===3?e.setEnd(l,l.length):e.setEndAfter(l)),e}function NB(n){if(n.firstChild)return n.firstChild;let e=n;for(;!e.nextSibling;)if(e=e.parentNode,!e)return null;return e.nextSibling}function BB(n){if(n.lastChild)return n.lastChild;let e=n;for(;!e.previousSibling;)if(e=e.parentNode,!e)return null;return e.previousSibling}function fw(n){for(;n.firstChild;)n=n.firstChild;return n}function hw(n){for(;n.lastChild;)n=n.lastChild;return n}L();var Yg=rt(mw());var yo,Xg;function Cr(n,e,t){if(n.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if(n.tagName.toLowerCase()==="html")return n.tagName.toLowerCase();let r={className:o=>!0,idName:o=>!0,optimizedMinLength:2,root:e.body,seedMinLength:1,tagName:o=>!0,threshold:1e3};yo={...r,...t},Xg=GB(yo.root,r);let i=Vg(n,0,()=>Vg(n,1,()=>Vg(n,2)));if(i){let o=ww(Sw(i,n));return o.length>0&&(i=o[0]),Lf(i)}else throw new Error("Selector was not found.")}function GB(n,e){return n.nodeType===Node.DOCUMENT_NODE?n:n===e.root?n.ownerDocument:n}function Vg(n,e,t){let r=null,i=[],o=n,s=0;for(;o&&o!==yo.root.parentElement;){let l=Kg(WB(o))||Kg(...zB(o))||Kg(VB(o))||[$B()],f=JB(o);if(e===0)f&&(l=l.concat(l.filter(Jg).map(u=>$g(u,f))));else if(e===1)l=l.slice(0,1),f&&(l=l.concat(l.filter(Jg).map(u=>$g(u,f))));else if(e===2){let[u]=l=l.slice(0,1);f&&Jg(u)&&(l=[$g(u,f)])}for(let u of l)u.level=s;if(i.push(l),i.length>=yo.seedMinLength&&(r=yw(i,t),r))break;o=o.parentElement,s++}return r||(r=yw(i,t)),r}function yw(n,e){let t=ww(_w(n));if(t.length>yo.threshold)return e?e():null;for(let r of t)if(vw(r))return r;return null}function Lf(n){let e=n[0],t=e.name;for(let r=1;r<n.length;r++){let i=n[r].level||0;e.level===i-1?t=`${n[r].name} > ${t}`:t=`${n[r].name} ${t}`,e=n[r]}return t}function bw(n){return n.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function vw(n){switch(Xg.querySelectorAll(Lf(n)).length){case 0:throw new Error(`Can't select any node with this selector: ${Lf(n)}`);case 1:return!0;default:return!1}}function WB(n){let e=n.getAttribute("id");return e&&yo.idName(e)?{name:"#"+(0,Yg.default)(e,{isIdentifier:!0}),penalty:0}:null}function zB(n){return Array.from(n.classList).filter(yo.className).map(t=>({name:"."+(0,Yg.default)(t,{isIdentifier:!0}),penalty:1}))}function VB(n){let e=n.tagName.toLowerCase();return yo.tagName(e)?{name:e,penalty:2}:null}function $B(){return{name:"*",penalty:3}}function JB(n){let e=n.parentNode;if(!e)return null;let t=e.firstChild;if(!t)return null;let r=0;for(;t&&(t.nodeType===Node.ELEMENT_NODE&&r++,t!==n);)t=t.nextSibling;return r}function $g(n,e){return{name:n.name+`:nth-child(${e})`,penalty:n.penalty+1}}function Jg(n){return n.name!=="html"&&!n.name.startsWith("#")}function Kg(...n){let e=n.filter(KB);return e.length>0?e:null}function KB(n){return n!=null}function*_w(n,e=[]){if(n.length>0)for(let t of n[0])yield*_w(n.slice(1,n.length),e.concat(t));else yield e}function ww(n){return Array.from(n).sort((e,t)=>bw(e)-bw(t))}function*Sw(n,e){if(n.length>2&&n.length>yo.optimizedMinLength)for(let t=1;t<n.length-1;t++){let r=[...n];r.splice(t,1),vw(r)&&YB(r,e)&&(yield r,yield*Sw(r,e))}}function YB(n,e){return Xg.querySelector(Lf(n))===e}L();L();var Aw="0 0 24 24",fn=(n,e,t,r="icon")=>`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="${Aw}" preserveAspectRatio="xMidYMid meet" role="img" class="${r}" aria-labelledBy="${n}">
|
|
73
|
+
`}setFont(b){let C=this.current,k=this.commonObjs.get(b[0]),R=b[1];C.font=k,this.embedFonts&&!k.missingFile&&!this.embeddedFonts[k.loadedName]&&(this.addFontStyle(k),this.embeddedFonts[k.loadedName]=k),C.fontMatrix=k.fontMatrix||r.FONT_IDENTITY_MATRIX;let B="normal";k.black?B="900":k.bold&&(B="bold");let I=k.italic?"italic":"normal";R<0?(R=-R,C.fontDirection=-1):C.fontDirection=1,C.fontSize=R,C.fontFamily=k.loadedName,C.fontWeight=B,C.fontStyle=I,C.tspan=this.svgFactory.createElement("svg:tspan"),C.tspan.setAttributeNS(null,"y",c(-C.y)),C.xcoords=[],C.ycoords=[]}endText(){var C;let b=this.current;b.textRenderingMode&r.TextRenderingMode.ADD_TO_PATH_FLAG&&((C=b.txtElement)!=null&&C.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,C,k){this.current.strokeColor=r.Util.makeHexColor(b,C,k)}setFillAlpha(b){this.current.fillAlpha=b}setFillRGBColor(b,C,k){this.current.fillColor=r.Util.makeHexColor(b,C,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 C=this.viewport.width,k=this.viewport.height,R=r.Util.inverseTransform(this.transformMatrix),B=r.Util.applyTransform([0,0],R),I=r.Util.applyTransform([0,k],R),D=r.Util.applyTransform([C,0],R),F=r.Util.applyTransform([C,k],R),z=Math.min(B[0],I[0],D[0],F[0]),q=Math.min(B[1],I[1],D[1],F[1]),G=Math.max(B[0],I[0],D[0],F[0]),Y=Math.max(B[1],I[1],D[1],F[1]),X=this.svgFactory.createElement("svg:rect");X.setAttributeNS(null,"x",z),X.setAttributeNS(null,"y",q),X.setAttributeNS(null,"width",G-z),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 C=b[1],k=b[2],R=b[3]||r.IDENTITY_MATRIX,[B,I,D,F]=b[4],z=b[5],q=b[6],G=b[7],Y=`shading${E++}`,[X,Q,se,ve]=r.Util.normalizeRect([...r.Util.applyTransform([B,I],R),...r.Util.applyTransform([D,F],R)]),[ce,W]=r.Util.singularValueDecompose2dScale(R),H=z*ce,M=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",M),x.setAttributeNS(null,"x",`${X}`),x.setAttributeNS(null,"y",`${Q}`);let T=this.svg,P=this.transformMatrix,N=this.current.fillColor,U=this.current.strokeColor,V=this.svgFactory.create(se-X,ve-Q);if(this.svg=V,this.transformMatrix=R,G===2){let Z=r.Util.makeHexColor(...C);this.current.fillColor=Z,this.current.strokeColor=Z}return this.executeOpTree(this.convertOpList(k)),this.svg=T,this.transformMatrix=P,this.current.fillColor=N,this.current.strokeColor=U,x.appendChild(V.childNodes[0]),this.defs.appendChild(x),`url(#${Y})`}_makeShadingPattern(b){switch(typeof b=="string"&&(b=this.objs.get(b)),b[0]){case"RadialAxial":let C=`shading${E++}`,k=b[3],R;switch(b[1]){case"axial":let B=b[4],I=b[5];R=this.svgFactory.createElement("svg:linearGradient"),R.setAttributeNS(null,"id",C),R.setAttributeNS(null,"gradientUnits","userSpaceOnUse"),R.setAttributeNS(null,"x1",B[0]),R.setAttributeNS(null,"y1",B[1]),R.setAttributeNS(null,"x2",I[0]),R.setAttributeNS(null,"y2",I[1]);break;case"radial":let D=b[4],F=b[5],z=b[6],q=b[7];R=this.svgFactory.createElement("svg:radialGradient"),R.setAttributeNS(null,"id",C),R.setAttributeNS(null,"gradientUnits","userSpaceOnUse"),R.setAttributeNS(null,"cx",F[0]),R.setAttributeNS(null,"cy",F[1]),R.setAttributeNS(null,"r",q),R.setAttributeNS(null,"fx",D[0]),R.setAttributeNS(null,"fy",D[1]),R.setAttributeNS(null,"fr",z);break;default:throw new Error(`Unknown RadialAxial type: ${b[1]}`)}for(let B of k){let I=this.svgFactory.createElement("svg:stop");I.setAttributeNS(null,"offset",B[0]),I.setAttributeNS(null,"stop-color",B[1]),R.appendChild(I)}return this.defs.appendChild(R),`url(#${C})`;case"Mesh":return(0,r.warn)("Unimplemented pattern Mesh"),null;case"Dummy":return"hotpink";default:throw new Error(`Unknown IR type: ${b[0]}`)}}setDash(b,C){this.current.dashArray=b,this.current.dashPhase=C}constructPath(b,C){let k=this.current,R=k.x,B=k.y,I=[],D=0;for(let F of b)switch(F|0){case r.OPS.rectangle:R=C[D++],B=C[D++];let z=C[D++],q=C[D++],G=R+z,Y=B+q;I.push("M",c(R),c(B),"L",c(G),c(B),"L",c(G),c(Y),"L",c(R),c(Y),"Z");break;case r.OPS.moveTo:R=C[D++],B=C[D++],I.push("M",c(R),c(B));break;case r.OPS.lineTo:R=C[D++],B=C[D++],I.push("L",c(R),c(B));break;case r.OPS.curveTo:R=C[D+4],B=C[D+5],I.push("C",c(C[D]),c(C[D+1]),c(C[D+2]),c(C[D+3]),c(R),c(B)),D+=6;break;case r.OPS.curveTo2:I.push("C",c(R),c(B),c(C[D]),c(C[D+1]),c(C[D+2]),c(C[D+3])),R=C[D+2],B=C[D+3],D+=4;break;case r.OPS.curveTo3:R=C[D+2],B=C[D+3],I.push("C",c(C[D]),c(C[D+1]),c(R),c(B),c(R),c(B)),D+=4;break;case r.OPS.closePath:I.push("Z");break}I=I.join(" "),k.path&&b.length>0&&b[0]!==r.OPS.rectangle&&b[0]!==r.OPS.moveTo?I=k.path.getAttributeNS(null,"d")+I:(k.path=this.svgFactory.createElement("svg:path"),this._ensureTransformGroup().appendChild(k.path)),k.path.setAttributeNS(null,"d",I),k.path.setAttributeNS(null,"fill","none"),k.element=k.path,k.setCurrentPoint(R,B)}endPath(){let b=this.current;if(b.path=null,!this.pendingClip)return;if(!b.element){this.pendingClip=null;return}let C=`clippath${w++}`,k=this.svgFactory.createElement("svg:clipPath");k.setAttributeNS(null,"id",C),k.setAttributeNS(null,"transform",p(this.transformMatrix));let R=b.element.cloneNode(!0);if(this.pendingClip==="evenodd"?R.setAttributeNS(null,"clip-rule","evenodd"):R.setAttributeNS(null,"clip-rule","nonzero"),this.pendingClip=null,k.appendChild(R),this.defs.appendChild(k),b.activeClipUrl){b.clipGroup=null;for(let B of this.extraStack)B.clipGroup=null;k.setAttributeNS(null,"clip-path",b.activeClipUrl)}b.activeClipUrl=`url(#${C})`,this.tgrp=null}clip(b){this.pendingClip=b}closePath(){let b=this.current;if(b.path){let C=`${b.path.getAttributeNS(null,"d")}Z`;b.path.setAttributeNS(null,"d",C)}}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[C,k]of b)switch(C){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,r.warn)(`Unimplemented graphic state operator ${C}`);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,C=1){let k=this.current,R=k.dashArray;C!==1&&R.length>0&&(R=R.map(function(B){return C*B})),b.setAttributeNS(null,"stroke",k.strokeColor),b.setAttributeNS(null,"stroke-opacity",k.strokeAlpha),b.setAttributeNS(null,"stroke-miterlimit",c(k.miterLimit)),b.setAttributeNS(null,"stroke-linecap",k.lineCap),b.setAttributeNS(null,"stroke-linejoin",k.lineJoin),b.setAttributeNS(null,"stroke-width",c(C*k.lineWidth)+"px"),b.setAttributeNS(null,"stroke-dasharray",R.map(c).join(" ")),b.setAttributeNS(null,"stroke-dashoffset",c(C*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 C=b.startsWith("g_")?this.commonObjs.get(b):this.objs.get(b);if(!C){(0,r.warn)(`Dependent image with object ID ${b} is not ready yet`);return}this.paintInlineImageXObject(C)}paintInlineImageXObject(b,C){let k=b.width,R=b.height,B=v(b,this.forceDataSchema,!!C),I=this.svgFactory.createElement("svg:rect");I.setAttributeNS(null,"x","0"),I.setAttributeNS(null,"y","0"),I.setAttributeNS(null,"width",c(k)),I.setAttributeNS(null,"height",c(R)),this.current.element=I,this.clip("nonzero");let D=this.svgFactory.createElement("svg:image");D.setAttributeNS(u,"xlink:href",B),D.setAttributeNS(null,"x","0"),D.setAttributeNS(null,"y",c(-R)),D.setAttributeNS(null,"width",c(k)+"px"),D.setAttributeNS(null,"height",c(R)+"px"),D.setAttributeNS(null,"transform",`scale(${c(1/k)} ${c(-1/R)})`),C?C.appendChild(D):this._ensureTransformGroup().appendChild(D)}paintImageMaskXObject(b){let C=this.current,k=b.width,R=b.height,B=C.fillColor;C.maskId=`mask${A++}`;let I=this.svgFactory.createElement("svg:mask");I.setAttributeNS(null,"id",C.maskId);let D=this.svgFactory.createElement("svg:rect");D.setAttributeNS(null,"x","0"),D.setAttributeNS(null,"y","0"),D.setAttributeNS(null,"width",c(k)),D.setAttributeNS(null,"height",c(R)),D.setAttributeNS(null,"fill",B),D.setAttributeNS(null,"mask",`url(#${C.maskId})`),this.defs.appendChild(I),this._ensureTransformGroup().appendChild(D),this.paintInlineImageXObject(b,I)}paintFormXObjectBegin(b,C){if(Array.isArray(b)&&b.length===6&&this.transform(b[0],b[1],b[2],b[3],b[4],b[5]),C){let k=C[2]-C[0],R=C[3]-C[1],B=this.svgFactory.createElement("svg:rect");B.setAttributeNS(null,"x",C[0]),B.setAttributeNS(null,"y",C[1]),B.setAttributeNS(null,"width",c(k)),B.setAttributeNS(null,"height",c(R)),this.current.element=B,this.clip("nonzero"),this.endPath()}}paintFormXObjectEnd(){}_initialize(b){let C=this.svgFactory.create(b.width,b.height),k=this.svgFactory.createElement("svg:defs");C.appendChild(k),this.defs=k;let R=this.svgFactory.createElement("svg:g");return R.setAttributeNS(null,"transform",p(b.transform)),C.appendChild(R),this.svg=R,C}_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}}}},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PDFNodeStream=void 0;var r=t(1),i=t(26);let o=pf(),s=BE(),l=DE(),f=hf(),u=/^file:\/\/\/[a-zA-Z]:\//;function y(A){let E=f.parse(A);return E.protocol==="file:"||E.host?E:/^[a-z]:[/\\]/i.test(A)?f.parse(`file:///${A}`):(E.host||(E.protocol="file:"),E)}class m{constructor(E){this.source=E,this.url=y(E.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=this.isHttp&&E.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){var E;return((E=this._fullRequestReader)==null?void 0:E._loaded)??0}getFullReader(){return(0,r.assert)(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new p(this):new h(this),this._fullRequestReader}getRangeReader(E,b){if(b<=this._progressiveDataLength)return null;let C=this.isFsUrl?new w(this,E,b):new c(this,E,b);return this._rangeRequestReaders.push(C),C}cancelAllRequests(E){this._fullRequestReader&&this._fullRequestReader.cancel(E);for(let b of this._rangeRequestReaders.slice(0))b.cancel(E)}}e.PDFNodeStream=m;class _{constructor(E){this._url=E.url,this._done=!1,this._storedError=null,this.onProgress=null;let b=E.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,r.createPromiseCapability)(),this._headersCapability=(0,r.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 E=this._readableStream.read();return E===null?(this._readCapability=(0,r.createPromiseCapability)(),this.read()):(this._loaded+=E.length,this.onProgress&&this.onProgress({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(E).buffer,done:!1})}cancel(E){if(!this._readableStream){this._error(E);return}this._readableStream.destroy(E)}_error(E){this._storedError=E,this._readCapability.resolve()}_setReadableStream(E){this._readableStream=E,E.on("readable",()=>{this._readCapability.resolve()}),E.on("end",()=>{E.destroy(),this._done=!0,this._readCapability.resolve()}),E.on("error",b=>{this._error(b)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new r.AbortException("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class v{constructor(E){this._url=E.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=(0,r.createPromiseCapability)();let b=E.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 E=this._readableStream.read();return E===null?(this._readCapability=(0,r.createPromiseCapability)(),this.read()):(this._loaded+=E.length,this.onProgress&&this.onProgress({loaded:this._loaded}),{value:new Uint8Array(E).buffer,done:!1})}cancel(E){if(!this._readableStream){this._error(E);return}this._readableStream.destroy(E)}_error(E){this._storedError=E,this._readCapability.resolve()}_setReadableStream(E){this._readableStream=E,E.on("readable",()=>{this._readCapability.resolve()}),E.on("end",()=>{E.destroy(),this._done=!0,this._readCapability.resolve()}),E.on("error",b=>{this._error(b)}),this._storedError&&this._readableStream.destroy(this._storedError)}}function g(A,E){return{protocol:A.protocol,auth:A.auth,host:A.hostname,port:A.port,path:A.path,method:"GET",headers:E}}class h extends _{constructor(E){super(E);let b=C=>{if(C.statusCode===404){let I=new r.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=I,this._headersCapability.reject(I);return}this._headersCapability.resolve(),this._setReadableStream(C);let k=I=>this._readableStream.headers[I.toLowerCase()],{allowRangeRequests:R,suggestedLength:B}=(0,i.validateRangeRequestCapabilities)({getResponseHeader:k,isHttp:E.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=R,this._contentLength=B||this._contentLength,this._filename=(0,i.extractFilenameFromHeader)(k)};this._request=null,this._url.protocol==="http:"?this._request=s.request(g(this._url,E.httpHeaders),b):this._request=l.request(g(this._url,E.httpHeaders),b),this._request.on("error",C=>{this._storedError=C,this._headersCapability.reject(C)}),this._request.end()}}class c extends v{constructor(E,b,C){super(E),this._httpHeaders={};for(let R in E.httpHeaders){let B=E.httpHeaders[R];typeof B>"u"||(this._httpHeaders[R]=B)}this._httpHeaders.Range=`bytes=${b}-${C-1}`;let k=R=>{if(R.statusCode===404){let B=new r.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=B;return}this._setReadableStream(R)};this._request=null,this._url.protocol==="http:"?this._request=s.request(g(this._url,this._httpHeaders),k):this._request=l.request(g(this._url,this._httpHeaders),k),this._request.on("error",R=>{this._storedError=R}),this._request.end()}}class p extends _{constructor(E){super(E);let b=decodeURIComponent(this._url.path);u.test(this._url.href)&&(b=b.replace(/^\//,"")),o.lstat(b,(C,k)=>{if(C){C.code==="ENOENT"&&(C=new r.MissingPDFException(`Missing PDF "${b}".`)),this._storedError=C,this._headersCapability.reject(C);return}this._contentLength=k.size,this._setReadableStream(o.createReadStream(b)),this._headersCapability.resolve()})}}class w extends v{constructor(E,b,C){super(E);let k=decodeURIComponent(this._url.path);u.test(this._url.href)&&(k=k.replace(/^\//,"")),this._setReadableStream(o.createReadStream(k,{start:b,end:C-1}))}}},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createResponseStatusError=f,e.extractFilenameFromHeader=l,e.validateRangeRequestCapabilities=s,e.validateResponseStatus=u;var r=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 l(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 r.MissingPDFException('Missing PDF "'+m+'".'):new r.UnexpectedResponseException(`Unexpected server response (${y}) while retrieving PDF "${m}".`,y)}function u(y){return y===200||y===206}},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getFilenameFromContentDispositionHeader=i;var r=t(1);function i(o){let s=!0,l=f("filename\\*","i").exec(o);if(l){l=l[1];let h=_(l);return h=unescape(h),h=v(h),h=g(h),y(h)}if(l=m(o),l){let h=g(l);return y(h)}if(l=f("filename","i").exec(o),l){l=l[1];let h=_(l);return h=g(h),y(h)}function f(h,c){return new RegExp("(?:^|;)\\s*"+h+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',c)}function u(h,c){if(h){if(!/^[\x00-\xFF]+$/.test(c))return c;try{let p=new TextDecoder(h,{fatal:!0}),w=(0,r.stringToBytes)(c);c=p.decode(w),s=!1}catch{}}return c}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 c=[],p,w=f("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(p=w.exec(h))!==null;){let[,E,b,C]=p;if(E=parseInt(E,10),E in c){if(E===0)break;continue}c[E]=[b,C]}let A=[];for(let E=0;E<c.length&&E in c;++E){let[b,C]=c[E];C=_(C),b&&(C=unescape(C),E===0&&(C=v(C))),A.push(C)}return A.join("")}function _(h){if(h.startsWith('"')){let c=h.slice(1).split('\\"');for(let p=0;p<c.length;++p){let w=c[p].indexOf('"');w!==-1&&(c[p]=c[p].slice(0,w),c.length=p+1),c[p]=c[p].replace(/\\(.)/g,"$1")}h=c.join('"')}return h}function v(h){let c=h.indexOf("'");if(c===-1)return h;let p=h.slice(0,c),A=h.slice(c+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(c,p,w,A){if(w==="q"||w==="Q")return A=A.replace(/_/g," "),A=A.replace(/=([0-9a-fA-F]{2})/g,function(E,b){return String.fromCharCode(parseInt(b,16))}),u(p,A);try{A=atob(A)}catch{}return u(p,A)})}return""}},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PDFNetworkStream=void 0;var r=t(1),i=t(26);let o=200,s=206;function l(_){let v=_.response;return typeof v!="string"?v:(0,r.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 c={begin:v,end:g};for(let p in h)c[p]=h[p];return this.request(c)}requestFull(v){return this.request(v)}request(v){let g=this.getXhr(),h=this.currXhrId++,c=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}`),c.expectedStatus=s):c.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),c.onHeadersReceived=v.onHeadersReceived,c.onDone=v.onDone,c.onError=v.onError,c.onProgress=v.onProgress,g.send(null),h}onProgress(v,g){var c;let h=this.pendingRequests[v];h&&((c=h.onProgress)==null||c.call(h,g))}onStateChange(v,g){var E,b,C;let h=this.pendingRequests[v];if(!h)return;let c=h.xhr;if(c.readyState>=2&&h.onHeadersReceived&&(h.onHeadersReceived(),delete h.onHeadersReceived),c.readyState!==4||!(v in this.pendingRequests))return;if(delete this.pendingRequests[v],c.status===0&&this.isHttp){(E=h.onError)==null||E.call(h,c.status);return}let p=c.status||o;if(!(p===o&&h.expectedStatus===s)&&p!==h.expectedStatus){(b=h.onError)==null||b.call(h,c.status);return}let A=l(c);if(p===s){let k=c.getResponseHeader("Content-Range"),R=/bytes (\d+)-(\d+)\/(\d+)/.exec(k);h.onDone({begin:parseInt(R[1],10),chunk:A})}else A?h.onDone({begin:0,chunk:A}):(C=h.onError)==null||C.call(h,c.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,r.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,r.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:c,suggestedLength:p}=(0,i.validateRangeRequestCapabilities)({getResponseHeader:h,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});c&&(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,r.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 c={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,c),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,r.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()}}},(n,e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.PDFFetchStream=void 0;var r=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 l{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,r.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=l;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,r.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:c,suggestedLength:p}=(0,i.validateRangeRequestCapabilities)({getResponseHeader:h,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=c,this._contentLength=p||this._contentLength,this._filename=(0,i.extractFilenameFromHeader)(h),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new r.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,r.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(c=>{if(!(0,i.validateResponseStatus)(c.status))throw(0,i.createResponseStatusError)(c.status,h);this._readCapability.resolve(),this._reader=c.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__(n){var e=__webpack_module_cache__[n];if(e!==void 0)return e.exports;var t=__webpack_module_cache__[n]={exports:{}};return __webpack_modules__[n](t,t.exports,__w_pdfjs_require__),t.exports}var __webpack_exports__={};return(()=>{var n=__webpack_exports__;Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"AnnotationLayer",{enumerable:!0,get:function(){return i.AnnotationLayer}}),Object.defineProperty(n,"AnnotationMode",{enumerable:!0,get:function(){return e.AnnotationMode}}),Object.defineProperty(n,"CMapCompressionType",{enumerable:!0,get:function(){return e.CMapCompressionType}}),Object.defineProperty(n,"GlobalWorkerOptions",{enumerable:!0,get:function(){return o.GlobalWorkerOptions}}),Object.defineProperty(n,"InvalidPDFException",{enumerable:!0,get:function(){return e.InvalidPDFException}}),Object.defineProperty(n,"LoopbackPort",{enumerable:!0,get:function(){return t.LoopbackPort}}),Object.defineProperty(n,"MissingPDFException",{enumerable:!0,get:function(){return e.MissingPDFException}}),Object.defineProperty(n,"OPS",{enumerable:!0,get:function(){return e.OPS}}),Object.defineProperty(n,"PDFDataRangeTransport",{enumerable:!0,get:function(){return t.PDFDataRangeTransport}}),Object.defineProperty(n,"PDFDateString",{enumerable:!0,get:function(){return r.PDFDateString}}),Object.defineProperty(n,"PDFWorker",{enumerable:!0,get:function(){return t.PDFWorker}}),Object.defineProperty(n,"PasswordResponses",{enumerable:!0,get:function(){return e.PasswordResponses}}),Object.defineProperty(n,"PermissionFlag",{enumerable:!0,get:function(){return e.PermissionFlag}}),Object.defineProperty(n,"PixelsPerInch",{enumerable:!0,get:function(){return r.PixelsPerInch}}),Object.defineProperty(n,"RenderingCancelledException",{enumerable:!0,get:function(){return r.RenderingCancelledException}}),Object.defineProperty(n,"SVGGraphics",{enumerable:!0,get:function(){return f.SVGGraphics}}),Object.defineProperty(n,"UNSUPPORTED_FEATURES",{enumerable:!0,get:function(){return e.UNSUPPORTED_FEATURES}}),Object.defineProperty(n,"UnexpectedResponseException",{enumerable:!0,get:function(){return e.UnexpectedResponseException}}),Object.defineProperty(n,"Util",{enumerable:!0,get:function(){return e.Util}}),Object.defineProperty(n,"VerbosityLevel",{enumerable:!0,get:function(){return e.VerbosityLevel}}),Object.defineProperty(n,"XfaLayer",{enumerable:!0,get:function(){return u.XfaLayer}}),Object.defineProperty(n,"build",{enumerable:!0,get:function(){return t.build}}),Object.defineProperty(n,"createPromiseCapability",{enumerable:!0,get:function(){return e.createPromiseCapability}}),Object.defineProperty(n,"createValidAbsoluteUrl",{enumerable:!0,get:function(){return e.createValidAbsoluteUrl}}),Object.defineProperty(n,"getDocument",{enumerable:!0,get:function(){return t.getDocument}}),Object.defineProperty(n,"getFilenameFromUrl",{enumerable:!0,get:function(){return r.getFilenameFromUrl}}),Object.defineProperty(n,"getPdfFilenameFromUrl",{enumerable:!0,get:function(){return r.getPdfFilenameFromUrl}}),Object.defineProperty(n,"getXfaPageViewport",{enumerable:!0,get:function(){return r.getXfaPageViewport}}),Object.defineProperty(n,"isPdfFile",{enumerable:!0,get:function(){return r.isPdfFile}}),Object.defineProperty(n,"loadScript",{enumerable:!0,get:function(){return r.loadScript}}),Object.defineProperty(n,"renderTextLayer",{enumerable:!0,get:function(){return l.renderTextLayer}}),Object.defineProperty(n,"shadow",{enumerable:!0,get:function(){return e.shadow}}),Object.defineProperty(n,"version",{enumerable:!0,get:function(){return t.version}});var e=__w_pdfjs_require__(1),t=__w_pdfjs_require__(4),r=__w_pdfjs_require__(5),i=__w_pdfjs_require__(20),o=__w_pdfjs_require__(13),s=__w_pdfjs_require__(3),l=__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,r.isValidFetchUrl)(g.url)?new v(g):new _(g))}})(),__webpack_exports__})())});var JU={};D0(JU,{Link:()=>lu,default:()=>VU,load:()=>$U});L();L();L();var e4=rt(Q3()),t4=rt(Or());L();var Z3=rt(Or());function _a(n,e){return Z3.TaJson.deserialize(n,e)}var lo=class extends e4.Publication{static async fromUrl(e,t){let i=await(await fetch(e.href,t)).json(),o=_a(i,lo);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 r;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((r=this.TOC)==null?void 0:r.map(i=>{var o,s;if(i.Href){let l=this.positionsByHref(this.getRelativeHref(i.Href));if((l==null?void 0:l.length)>0){let f=l[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(r=>r.Href&&this.getAbsoluteHref(r.Href)===e)}getAbsoluteHref(e){return new URL(e,this.manifestUrl.href).href}getRelativeHref(e){let t=this.manifestUrl.href.replace("/manifest.json",""),r=e.replace(t,"");return r.indexOf("#")>0&&(r=r.slice(0,r.indexOf("#"))),r.charAt(0)==="/"&&(r=r.substring(1)),r}getTOCItemAbsolute(e){let t=this.getAbsoluteHref(e),r=(o,s)=>{for(let l=0;l<s.length;l++){let f=s[l];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=r(o,f.Children);if(u!==void 0)return u}}},i=r(t,this.tableOfContents);return i===void 0&&this.readingOrder!==void 0&&(i=r(t,this.readingOrder)),i}getTOCItem(e){let t=(i,o)=>{for(let s=0;s<o.length;s++){let l=o[s];if(l.Href&&this.getAbsoluteHref(l.Href)===i)return l;if(l.Children){let f=t(i,l.Children);if(f!==void 0)return f}}},r=t(e,this.tableOfContents);if(r===void 0&&this.readingOrder!==void 0&&(r=t(e,this.readingOrder)),r===void 0&&e.indexOf("#")!==-1){let i=e.slice(0,e.indexOf("#"));r=t(i,this.tableOfContents),r===void 0&&this.readingOrder!==void 0&&(r=t(i,this.readingOrder))}return r}positionsByHref(e){var r;let t=decodeURI(e)??"";return(r=this.positions)==null?void 0:r.filter(i=>t.includes(i.href))}async autoGeneratePositions(e,t=YR){let r=0,i=0,o=[];if(this.readingOrder!==void 0)for(let l of this.readingOrder)if(this.isFixedLayout){let f={href:l.Href,locations:{progression:0,position:r+1},type:l.TypeLink};o.push(f),r=r+1}else{let f=this.getAbsoluteHref(l.Href),u=await t(f,e);l.contentLength=u,i+=u;let m=Math.max(1,Math.ceil(u/1024));for(let _=0;_<m;_++){let v={href:l.Href,locations:{progression:_/m,position:r+(_+1)},type:l.TypeLink};o.push(v)}r=r+m}var s=0;if(this.isReflowable&&this.readingOrder!==void 0)for(let l of this.readingOrder){if(!l.contentLength){console.error("Link is missing contentLength",l);return}l.contentWeight=100/i*l.contentLength,s=s+l.contentWeight}for(let l of o){let f=o.filter(y=>y.href===decodeURI(l.href)),u=Math.ceil((l.locations.progression?l.locations.progression:0)*(f.length-1));l.locations.position&&(l.locations.totalProgression=(l.locations.position-1)/o.length),l.locations.remainingPositions=Math.abs(u-(f.length-1)),l.locations.position&&(l.locations.totalRemainingPositions=Math.abs(l.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]})}};lo=Nc([(0,t4.JsonObject)()],lo);var YR=async(n,e)=>(await(await fetch(n,e)).blob()).size;L();L();var As=class{json(){return JSON.stringify(this)}},Hp=class extends As{constructor(e,t,r){super(),this.value=e,this.ref=t,this.name=r}toString(){return this.value}},Up=class extends As{constructor(e,t,r){super(),this.value=e,this.ref=t,this.name=r}toString(){return this.value}toJson(){return JSON.parse(this.value)}},jp=class extends As{constructor(e,t,r,i){super(),this.value=e,this.values=t,this.ref=r,this.name=i}toString(){return this.values[this.value]}},qp=class extends As{constructor(t,r,i,o,s,l,f){super();this.countDecimals=function(t){return t%1!==0?t.toString().split(".")[1].length:1};this.value=t,this.min=r,this.max=i,this.step=o,this.suffix=s,this.ref=l,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)}},wa=class extends As{constructor(e,t,r,i,o){super(),this.value=r,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}},Li=class{constructor(){this.properties=[]}addIncremental(e,t,r,i,o,s,l){this.properties.push(new qp(e,t,r,i,o,s,l))}addStringable(e,t,r){this.properties.push(new Hp(e,t,r))}addJSONable(e,t,r){this.properties.push(new Up(e,t,r))}addSwitchable(e,t,r,i,o){this.properties.push(new wa(e,t,r,i,o))}addEnumerable(e,t,r,i){this.properties.push(new jp(e,t,r,i))}getByRef(e){let t=this.properties.filter(r=>r.ref===e);return t.length>0?t[0]:null}getByKey(e){let t=this.properties.filter(r=>r.key===e);return t.length>0?t[0]:null}};L();var mt=class mt{};mt.FONT_SIZE_REF="fontSize",mt.FONT_FAMILY_REF="fontFamily",mt.FONT_OVERRIDE_REF="fontOverride",mt.APPEARANCE_REF="appearance",mt.SCROLL_REF="scroll",mt.TEXT_ALIGNMENT_REF="textAlign",mt.COLUMN_COUNT_REF="colCount",mt.DIRECTION_REF="direction",mt.WORD_SPACING_REF="wordSpacing",mt.LETTER_SPACING_REF="letterSpacing",mt.PAGE_MARGINS_REF="pageMargins",mt.LINE_HEIGHT_REF="lineHeight",mt.FONT_SIZE_KEY="--USER__"+mt.FONT_SIZE_REF,mt.FONT_FAMILY_KEY="--USER__"+mt.FONT_FAMILY_REF,mt.FONT_OVERRIDE_KEY="--USER__"+mt.FONT_OVERRIDE_REF,mt.APPEARANCE_KEY="--USER__"+mt.APPEARANCE_REF,mt.SCROLL_KEY="--USER__"+mt.SCROLL_REF,mt.TEXT_ALIGNMENT_KEY="--USER__"+mt.TEXT_ALIGNMENT_REF,mt.COLUMN_COUNT_KEY="--USER__"+mt.COLUMN_COUNT_REF,mt.DIRECTION_KEY="--USER__"+mt.DIRECTION_REF,mt.WORD_SPACING_KEY="--USER__"+mt.WORD_SPACING_REF,mt.LETTER_SPACING_KEY="--USER__"+mt.LETTER_SPACING_REF,mt.PAGE_MARGINS_KEY="--USER__"+mt.PAGE_MARGINS_REF,mt.LINE_HEIGHT_KEY="--USER__"+mt.LINE_HEIGHT_REF;var _e=mt;L();function Le(n,e){return n.querySelector(e)}function yt(n,e){let t=Le(n,e);if(t&&t instanceof HTMLElement)return t;throw new Error("required element "+e+" not found")}function cr(n,e){if(n===null)throw new Error("parent element is null");return n.querySelector(e)}function co(n,e){let t=cr(n,e);if(t)return t;throw new Error("required element "+e+" not found in iframe")}function Ir(n,e,t){n.setAttribute(e,t)}L();L();var Y6=rt(Fg());var Ba=class{constructor(e){this.getScrollingElement=e=>e.scrollingElement?e.scrollingElement:e.body;this.navigator=e}async handleFootnote(e,t){var i,o;let r=e.getAttribute("href");if(r&&r.indexOf("#")>0){let l=function(u){let y=document.location.href;return new URL(u,y).href},s=r.substring(r.indexOf("#")+1),f=l(r);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(r).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 r,i;let e=(r=this.navigator.iframes[0].contentDocument)==null?void 0:r.getElementById("d2-popover");e&&((i=e.parentElement)==null||i.removeChild(e));let t=yt(document,"#iframe-wrapper");t.style.overflow="auto"}async showPopover(e,t){var s,l,f,u,y,m;let r=e.getAttribute("href"),i=e.getAttribute("src");function o(_){let v=document.location.href;return new URL(_,v).href}if(r){let _=o(r);if(_){t.preventDefault(),t.stopPropagation();let v=(s=this.navigator.iframes[0].contentDocument)==null?void 0:s.getElementById("d2-popover");v&&((l=v.parentElement)==null||l.removeChild(v));let g=document.createElement("div");g.id="d2-popover",g.className="d2-popover is-active";let h=yt(document,"#iframe-wrapper");h.style.overflow="hidden",g.style.top=h.scrollTop+"px",g.style.height=h.clientHeight*.9+"px";let c=document.createElement("div");c.className="d2-popover-wrapper",g.appendChild(c);let p=document.createElement("div");p.className="d2-popover-content",c.appendChild(p),(f=this.navigator.api)!=null&&f.getContent?await((u=this.navigator.api)==null?void 0:u.getContent(r).then(E=>{p.innerHTML=E;let b=this.navigator.iframes[0].contentDocument;b&&b.body.appendChild(g)})):await fetch(_,this.navigator.requestConfig).then(E=>E.text()).then(async E=>{p.innerHTML=E;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.addEventListener("click",function(E){t.target!==E.target&&g.parentElement&&(A.hidePopover(),E.stopImmediatePropagation())},{once:!0,capture:!0})}}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=yt(document,"#iframe-wrapper");h.style.overflow="hidden",g.style.top=h.scrollTop+"px",g.style.height=h.clientHeight*.9+"px";let c=document.createElement("div");c.className="d2-popover-wrapper",g.appendChild(c);let p=document.createElement("img");p.className="d2-popover-content",c.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 E=this;A.addEventListener("click",function(b){t.target!==b.target&&g.parentElement&&(E.hidePopover(),b.stopImmediatePropagation())},{once:!0,capture:!0})}}showPopup(e,t){var c,p,w;let r=(c=this.navigator.iframes[0].contentDocument)==null?void 0:c.getElementById("d2-popup");r&&((p=r.parentElement)==null||p.removeChild(r));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 l=document.createElement("p");s.appendChild(l),typeof e=="string"?l.innerHTML=e:l.innerHTML=(0,Y6.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 Tf=rt($t());function we(n,e,t){n&&n.addEventListener(e,t,!0)}function Ue(n,e,t){n&&n.removeEventListener(e,t,!0)}var _l=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(r=>{var i;return!((i=r.Rel)!=null&&i.includes("external"))&&this.navigator.publication.getRelativeHref(t).includes(r.Href)});this.isReadingOrderInternal=e=>(Tf.default.log("clickedLink: ",e),this.linkInPublication(this.navigator.publication.readingOrder,e.href));this.isResourceInternal=e=>(Tf.default.log("clickedLink: ",e),this.linkInPublication(this.navigator.publication.resources,e.href));this.clicks=0;this.clickTimer=0;this.dblClickTimeSpan=300;this.handleLinks=async e=>{Tf.default.log("R2 Click Handler"),this.clicks++,this.clicks===1&&(this.clickTimer=setTimeout(async()=>{this.clicks=0;let t=this.checkForLink(e);if(t){let r=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,(r||i)&&s!==-1){let l=e.target;l?l.getAttribute("epub:type")==="noteref"?await this.popup.handleFootnote(l,e):o&&!i?await this.popup.showPopover(l,e):this.onInternalLink(e):this.onInternalLink(e)}else(r||i)&&s===-1&&this.onInternalLink(e)}else setTimeout(()=>{var r;console.log("event.detail",e.detail),!((r=this.navigator.highlighter)!=null&&r.isSelectionMenuOpen)&&e.detail===1&&this.onClickThrough(e)},100)},this.dblClickTimeSpan)),this.clicks===2&&(clearTimeout(this.clickTimer),this.clicks=0)};this.navigator=e,this.popup=new Ba(this.navigator)}setupEvents(e){if(e!==null)e.addEventListener("dblclick",async t=>{let r=t.target;t.target&&r.tagName.toLowerCase()==="img"&&await this.popup.showPopover(r,t)},!0),e.addEventListener("click",this.handleLinks.bind(this),!0);else throw"cannot setup events for null"}};L();L();function Q6(){return yt(document,"#iframe-wrapper").clientWidth}function gi(){return yt(document,"#iframe-wrapper").clientHeight}var ew=rt(Vo()),wl=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 r=this.iframe.contentDocument;if(r){let i=cr(r,"head");if(i){let s=Le(i,"meta[name=viewport]");s&&s.remove()}let o=cr(r,"html");o&&o.style.setProperty("--USER__scroll","readium-scroll-on")}this.setSize(),this.setIframeHeight(this.iframe)}else{this.height=gi()-40-this.attributes.margin,this.name="readium-scroll-off",this.label="Paginated",this.checkForFixedScrollWidth();let r=this.iframe.contentDocument;if(r){let i=cr(r,"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 r=Le(t,"meta[name=viewport]");r&&r.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"),r=Array.prototype.slice.call(t.querySelectorAll("img"));for(let i of r)i.style.maxWidth=""}}getCurrentPosition(){let e=yt(document,"#iframe-wrapper");if(this.scrollMode)return e.scrollTop/this.scrollingElement.scrollHeight;{let t=this.getColumnWidth(),r=this.getLeftColumnsWidth(),i=this.getRightColumnsWidth(),o=r+t+i;return r/o}}goToProgression(e){let t=yt(document,"#iframe-wrapper");if(this.scrollMode)t.scrollTop=this.scrollingElement.scrollHeight*e;else{let r=this.getColumnWidth(),i=this.getLeftColumnsWidth(),o=this.getRightColumnsWidth(),s=i+r+o,l=e*s,f=Math.round(l/r)*r;f>=s&&(f=f-r),this.setLeftColumnsWidth(f)}}goToCssSelector(e,t){let r=this.iframe.contentDocument;if(r){let i=r.querySelector(e);this.goToElement(i,t)}}goToFragment(e,t){let r=this.iframe.contentDocument;if(r){let i=r.getElementById(e);this.goToElement(i,t)}}snap(e,t){var r;if(e&&!this.scrollMode){let i=e.style.height;e.style.height="0";let o=this.getColumnWidth(),s=this.getLeftColumnsWidth()+e.getBoundingClientRect().left,l=Math.floor(s/o)*o;e.style.height=i,this.setLeftColumnsWidth(l),this.navigator.rights.enableContentProtection&&((r=this.navigator.contentProtectionModule)==null||r.recalculate(0))}}goToElement(e,t){var r;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(),l=this.scrollingElement.scrollLeft-s,f=Math.ceil(o/s)*s+l;if(t){let u=this.getLeftColumnsWidth();f=Math.ceil(o/s)*s+u}e.style.height=i,this.setLeftColumnsWidth(f),this.navigator.rights.enableContentProtection&&((r=this.navigator.contentProtectionModule)==null||r.recalculate(200))}}atStart(){return this.scrollMode?yt(document,"#iframe-wrapper").scrollTop===0:this.getLeftColumnsWidth()<=0}atEnd(){if(this.scrollMode){let e=yt(document,"#iframe-wrapper");return Math.ceil(this.scrollingElement.scrollHeight-e.scrollTop)-1<=gi()}else return Math.floor(this.getRightColumnsWidth())<=0||Math.ceil(this.getCurrentPage())===this.getPageCount()}goToPreviousPage(){var t;let e=yt(document,"#iframe-wrapper");if(this.scrollMode){let r=e.scrollTop,i=this.getScreenHeight()-40,o=r-i;o>=0?e.scrollTop=o:e.scrollTop=0}else{let r=this.getLeftColumnsWidth(),i=this.getColumnWidth(),o=r-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=yt(document,"#iframe-wrapper");if(this.scrollMode){let r=e.scrollTop,i=this.getScreenHeight()-40,o=this.scrollingElement.scrollHeight,s=r+i;s<o?e.scrollTop=s:e.scrollTop=o}else{let r=this.getLeftColumnsWidth(),i=this.getColumnWidth(),o=this.scrollWidth,s=r+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 r=JSON.parse(t);return r=r.filter(i=>i.name===e),r.length===0?null:r[0]}return null}getScreenHeight(){return yt(document,"#iframe-wrapper").clientHeight}setIframeHeight(e){(0,ew.default)(r=>{if(r){let i=r.contentWindow.document.body,o=r.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 l=gi()-this.attributes.margin;r.height=Math.max(l,s)+"px"}}},200)(e)}checkForFixedScrollWidth(){let e=this.iframe.contentDocument;if(e){let t=cr(e,"body"),r=t==null?void 0:t.scrollWidth;this.hasFixedScrollWidth=(t==null?void 0:t.scrollWidth)===r}}setSize(){var e,t;if(this.iframe.width=Q6()+"px",this.scrollMode){let r=(t=(e=this.iframe.contentWindow)==null?void 0:e.document)==null?void 0:t.documentElement;this.iframe.height=(r==null?void 0:r.offsetHeight)+"px"}else{let r=this.iframe.contentDocument;r&&r.documentElement&&(r.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 r=this.getLeftColumnsWidth();t=Math.max(0,t-r)}return t}getColumnWidth(){return this.scrollingElement.clientWidth}setLeftColumnsWidth(e){this.scrollingElement.scrollLeft=e}get scrollingElement(){var e,t,r,i;return(e=this.iframe.contentDocument)!=null&&e.scrollingElement?(t=this.iframe.contentDocument)==null?void 0:t.scrollingElement:(r=this.iframe.contentDocument)!=null&&r.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 Sl=class{constructor(){this.layout="fixed";this.sideMargin=20;this.height=0;this.attributes={margin:0}}start(){}stop(){}getCurrentPosition(){return 0}getScreenHeight(){return yt(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 dn=rt($t()),dt=class dt{constructor(e,t,r,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.direction=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 Sl:new wl(this.store),this.headerMenu=t,this.api=r,this.injectables=i,(s=this.injectables)==null||s.forEach(l=>{l.type==="style"&&(l.fontFamily&&this.addFont(l.fontFamily),l.appearance&&this.addAppearance(l.appearance))})}async isPaginated(){return!await this.getPropertyAndFallback("verticalScroll",_e.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 r=e.initialUserSettings;if(r.verticalScroll!==void 0){t.verticalScroll=this.parseScrollSetting(r.verticalScroll);let i=t.userProperties.getByRef(_e.SCROLL_REF);i&&(i.value=t.verticalScroll,await t.saveProperty(i)),dn.default.log(t.verticalScroll)}if(r.appearance){t.appearance=dt.parseAppearanceSetting(r.appearance);let i=t.userProperties.getByRef(_e.APPEARANCE_REF);i&&(i.value=t.appearance,await t.saveProperty(i)),dn.default.log(t.appearance)}if(r.fontSize){t.fontSize=r.fontSize;let i=t.userProperties.getByRef(_e.FONT_SIZE_REF);i&&(i.value=t.fontSize,await t.saveProperty(i)),dn.default.log(t.fontSize)}if(r.fontFamily){t.fontFamily=dt.fontFamilyValues.findIndex(o=>o===r.fontFamily);let i=t.userProperties.getByRef(_e.FONT_FAMILY_REF);i&&(i.value=t.fontFamily,await t.saveProperty(i)),dn.default.log(t.fontFamily),t.fontFamily!==0&&(t.fontOverride=!0)}if(r.textAlignment){t.textAlignment=dt.textAlignmentValues.findIndex(o=>o===r.textAlignment);let i=t.userProperties.getByRef(_e.TEXT_ALIGNMENT_REF);i&&(i.value=t.textAlignment,await t.saveProperty(i)),dn.default.log(t.textAlignment)}if(r.columnCount){t.columnCount=dt.columnCountValues.findIndex(o=>o===r.columnCount);let i=t.userProperties.getByRef(_e.COLUMN_COUNT_REF);i&&(i.value=t.columnCount,await t.saveProperty(i)),dn.default.log(t.columnCount)}if(r.direction){t.direction=dt.directionValues.findIndex(o=>o===r.direction);let i=t.userProperties.getByRef(_e.DIRECTION_REF);i&&(i.value=t.direction,await t.saveProperty(i)),dn.default.log(t.direction)}if(r.wordSpacing){t.wordSpacing=r.wordSpacing;let i=t.userProperties.getByRef(_e.WORD_SPACING_REF);i&&(i.value=t.wordSpacing,await t.saveProperty(i)),dn.default.log(t.wordSpacing)}if(r.letterSpacing){t.letterSpacing=r.letterSpacing;let i=t.userProperties.getByRef(_e.LETTER_SPACING_REF);i&&(i.value=t.letterSpacing,await t.saveProperty(i)),dn.default.log(t.letterSpacing)}if(r.pageMargins){t.pageMargins=r.pageMargins;let i=t.userProperties.getByRef(_e.PAGE_MARGINS_REF);i&&(i.value=t.pageMargins,await t.saveProperty(i)),dn.default.log(t.pageMargins)}if(r.lineHeight){t.lineHeight=r.lineHeight;let i=t.userProperties.getByRef(_e.LINE_HEIGHT_REF);i&&(i.value=t.lineHeight,await t.saveProperty(i)),dn.default.log(t.lineHeight)}t.userProperties=t.getUserSettings(),await t.initialise()}return await t.initializeSelections(),new Promise(r=>r(t))}stop(){dn.default.log("book settings stop")}async initialise(){this.appearance=await this.getPropertyAndFallback("appearance",_e.APPEARANCE_KEY),this.verticalScroll=await this.getPropertyAndFallback("verticalScroll",_e.SCROLL_KEY),this.fontFamily=await this.getPropertyAndFallback("fontFamily",_e.FONT_FAMILY_KEY),this.fontFamily!==0&&(this.fontOverride=!0),this.textAlignment=await this.getPropertyAndFallback("textAlignment",_e.TEXT_ALIGNMENT_KEY),this.columnCount=await this.getPropertyAndFallback("columnCount",_e.COLUMN_COUNT_KEY),this.direction=await this.getPropertyAndFallback("direction",_e.DIRECTION_KEY),this.fontSize=await this.getPropertyAndFallback("fontSize",_e.FONT_SIZE_KEY),this.wordSpacing=await this.getPropertyAndFallback("wordSpacing",_e.WORD_SPACING_KEY),this.letterSpacing=await this.getPropertyAndFallback("letterSpacing",_e.LETTER_SPACING_KEY),this.pageMargins=await this.getPropertyAndFallback("pageMargins",_e.PAGE_MARGINS_KEY),this.lineHeight=await this.getPropertyAndFallback("lineHeight",_e.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.direction=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 r=Le(document,"#root")||document.documentElement,i=Le(t,"body");t.style.removeProperty(_e.FONT_SIZE_KEY),t.style.removeProperty(_e.WORD_SPACING_KEY),t.style.removeProperty(_e.LETTER_SPACING_KEY),t.style.removeProperty(_e.COLUMN_COUNT_KEY),t.style.removeProperty(_e.DIRECTION_KEY),t.style.removeProperty(_e.TEXT_ALIGNMENT_KEY),t.style.removeProperty(_e.LINE_HEIGHT_KEY),t.style.removeProperty(_e.PAGE_MARGINS_KEY),t.style.removeProperty(_e.APPEARANCE_KEY),r&&Ir(r,"data-viewer-theme","day"),i&&Ir(i,"data-viewer-theme","day"),t.style.removeProperty(_e.FONT_FAMILY_KEY),Ir(t,"data-viewer-font","publisher"),t.style.setProperty(_e.FONT_OVERRIDE_KEY,"readium-font-off")}}}async initializeSelections(){this.headerMenu&&(this.settingsView=Le(this.headerMenu,"#container-view-settings"))}async applyProperties(){var t,r,i,o,s,l,f,u,y,m,_,v,g,h,c,p,w,A,E,b,C,k,R,B;this.userProperties=this.getUserSettings();let e=this.iframe.contentDocument;if(e){let I=cr(e,"html");if(I){let D=Le(document,"#root")||document.documentElement,F=Le(I,"body");if((t=this.view)!=null&&t.navigator.publication.isReflowable&&(await this.getProperty(_e.FONT_SIZE_KEY)&&I.style.setProperty(_e.FONT_SIZE_KEY,((r=this.userProperties.getByRef(_e.FONT_SIZE_REF))==null?void 0:r.toString())??null),await this.getProperty(_e.WORD_SPACING_KEY)&&I.style.setProperty(_e.WORD_SPACING_KEY,((i=this.userProperties.getByRef(_e.WORD_SPACING_REF))==null?void 0:i.toString())??null),await this.getProperty(_e.LETTER_SPACING_KEY)&&I.style.setProperty(_e.LETTER_SPACING_KEY,((o=this.userProperties.getByRef(_e.LETTER_SPACING_REF))==null?void 0:o.toString())??null)),await this.getProperty(_e.COLUMN_COUNT_KEY)&&I.style.setProperty(_e.COLUMN_COUNT_KEY,((s=this.userProperties.getByRef(_e.COLUMN_COUNT_REF))==null?void 0:s.toString())??null),(l=this.view)!=null&&l.navigator.publication.isReflowable&&(await this.getProperty(_e.TEXT_ALIGNMENT_KEY)&&(((f=this.userProperties.getByRef(_e.TEXT_ALIGNMENT_REF))==null?void 0:f.toString())==="auto"?I.style.removeProperty(_e.TEXT_ALIGNMENT_KEY):I.style.setProperty(_e.TEXT_ALIGNMENT_KEY,((u=this.userProperties.getByRef(_e.TEXT_ALIGNMENT_REF))==null?void 0:u.toString())??null)),await this.getProperty(_e.LINE_HEIGHT_KEY)&&I.style.setProperty(_e.LINE_HEIGHT_KEY,((y=this.userProperties.getByRef(_e.LINE_HEIGHT_REF))==null?void 0:y.toString())??null),await this.getProperty(_e.PAGE_MARGINS_KEY)&&I.style.setProperty(_e.PAGE_MARGINS_KEY,((m=this.userProperties.getByRef(_e.PAGE_MARGINS_REF))==null?void 0:m.toString())??null)),await this.getProperty(_e.APPEARANCE_KEY)?(I.style.setProperty(_e.APPEARANCE_KEY,((_=this.userProperties.getByRef(_e.APPEARANCE_REF))==null?void 0:_.toString())??null),((v=this.userProperties.getByRef(_e.APPEARANCE_REF))==null?void 0:v.value)===0?(D&&Ir(D,"data-viewer-theme","day"),F&&Ir(F,"data-viewer-theme","day")):((g=this.userProperties.getByRef(_e.APPEARANCE_REF))==null?void 0:g.value)===1?(D&&Ir(D,"data-viewer-theme","sepia"),F&&Ir(F,"data-viewer-theme","sepia")):((h=this.userProperties.getByRef(_e.APPEARANCE_REF))==null?void 0:h.value)===2&&(D&&Ir(D,"data-viewer-theme","night"),F&&Ir(F,"data-viewer-theme","night"))):(I.style.setProperty(_e.APPEARANCE_KEY,((c=this.userProperties.getByRef(_e.APPEARANCE_REF))==null?void 0:c.toString())??null),D&&Ir(D,"data-viewer-theme","day"),F&&Ir(F,"data-viewer-theme","day")),(p=this.view)!=null&&p.navigator.publication.isFixedLayout&&await this.getProperty(_e.DIRECTION_KEY)){let z=((w=this.userProperties.getByRef(_e.DIRECTION_REF))==null?void 0:w.toString())??null;I.style.setProperty(_e.DIRECTION_KEY,z),this.view.navigator.setDirection(z)}if((A=this.view)!=null&&A.navigator.publication.isReflowable){if(await this.getProperty(_e.FONT_FAMILY_KEY))if(I.style.setProperty(_e.FONT_FAMILY_KEY,((E=this.userProperties.getByRef(_e.FONT_FAMILY_REF))==null?void 0:E.toString())??null),((b=this.userProperties.getByRef(_e.FONT_FAMILY_REF))==null?void 0:b.value)===0)Ir(I,"data-viewer-font","publisher"),I.style.setProperty(_e.FONT_OVERRIDE_KEY,"readium-font-off");else if(((C=this.userProperties.getByRef(_e.FONT_FAMILY_REF))==null?void 0:C.value)===1)Ir(I,"data-viewer-font","serif"),I.style.setProperty(_e.FONT_OVERRIDE_KEY,"readium-font-on");else if(((k=this.userProperties.getByRef(_e.FONT_FAMILY_REF))==null?void 0:k.value)===2)Ir(I,"data-viewer-font","sans"),I.style.setProperty(_e.FONT_OVERRIDE_KEY,"readium-font-on");else{let z=this.userProperties.getByRef(_e.FONT_FAMILY_REF);z&&Ir(I,"data-viewer-font",z.toString()),I.style.setProperty(_e.FONT_OVERRIDE_KEY,"readium-font-on")}else I.style.setProperty(_e.FONT_FAMILY_KEY,((R=this.userProperties.getByRef(_e.FONT_FAMILY_REF))==null?void 0:R.toString())??null),Ir(I,"data-viewer-font","publisher"),I.style.setProperty(_e.FONT_OVERRIDE_KEY,"readium-font-off");await this.getProperty(_e.SCROLL_KEY)?((B=this.userProperties.getByRef(_e.SCROLL_REF))==null?void 0:B.value)===!0?I.style.setProperty("--USER__scroll","readium-scroll-on"):I.style.setProperty("--USER__scroll","readium-scroll-off"):I.style.setProperty("--USER__scroll","readium-scroll-on"),I.style.setProperty("--USER__advancedSettings","readium-advanced-on"),this.isScrollMode().then(z=>{var q,G;(G=(q=this.view)==null?void 0:q.setMode)==null||G.call(q,z)})}}}}setIframe(e){this.iframe=e,this.view&&(this.view.iframe=e),this.settingsView&&dt.renderControls(this.settingsView)}static renderControls(e){we(Le(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){dt.appearanceValues.includes(e)||dt.appearanceValues.push(e)}initAddedAppearance(){this.applyProperties()}addFont(e){dt.fontFamilyValues.includes(e)||dt.fontFamilyValues.push(e)}initAddedFont(){this.applyProperties()}async updateUserSettings(){var t,r,i,o,s,l,f,u,y,m,_,v,g,h,c,p,w,A,E,b;let e={fontFamily:dt.fontFamilyValues[await((r=(t=this.userProperties)==null?void 0:t.getByRef(_e.FONT_FAMILY_REF))==null?void 0:r.value)],fontSize:(o=(i=this.userProperties)==null?void 0:i.getByRef(_e.FONT_SIZE_REF))==null?void 0:o.value,appearance:dt.appearanceValues[await((l=(s=this.userProperties)==null?void 0:s.getByRef(_e.APPEARANCE_REF))==null?void 0:l.value)],textAlignment:dt.textAlignmentValues[await((u=(f=this.userProperties)==null?void 0:f.getByRef(_e.TEXT_ALIGNMENT_REF))==null?void 0:u.value)],columnCount:dt.columnCountValues[await((m=(y=this.userProperties)==null?void 0:y.getByRef(_e.COLUMN_COUNT_REF))==null?void 0:m.value)],direction:dt.directionValues[await((v=(_=this.userProperties)==null?void 0:_.getByRef(_e.DIRECTION_REF))==null?void 0:v.value)],wordSpacing:(h=(g=this.userProperties)==null?void 0:g.getByRef(_e.WORD_SPACING_REF))==null?void 0:h.value,letterSpacing:(p=(c=this.userProperties)==null?void 0:c.getByRef(_e.LETTER_SPACING_REF))==null?void 0:p.value,verticalScroll:(A=(w=this.userProperties)==null?void 0:w.getByRef(_e.SCROLL_REF))==null?void 0:A.value};(E=this.api)!=null&&E.updateSettings&&((b=this.api)==null||b.updateSettings(e).then(C=>{dn.default.log("api updated user settings",JSON.stringify(e))}))}getUserSettings(){let e=new Li;return e.addSwitchable("readium-font-on","readium-font-off",this.fontOverride,_e.FONT_OVERRIDE_REF,_e.FONT_OVERRIDE_KEY),e.addEnumerable(this.columnCount,dt.columnCountValues,_e.COLUMN_COUNT_REF,_e.COLUMN_COUNT_KEY),e.addEnumerable(this.direction,dt.directionValues,_e.DIRECTION_REF,_e.DIRECTION_KEY),e.addEnumerable(this.appearance,dt.appearanceValues,_e.APPEARANCE_REF,_e.APPEARANCE_KEY),e.addIncremental(this.pageMargins,.5,4,.25,"",_e.PAGE_MARGINS_REF,_e.PAGE_MARGINS_KEY),e.addEnumerable(this.textAlignment,dt.textAlignmentValues,_e.TEXT_ALIGNMENT_REF,_e.TEXT_ALIGNMENT_KEY),e.addEnumerable(this.fontFamily,dt.fontFamilyValues,_e.FONT_FAMILY_REF,_e.FONT_FAMILY_KEY),e.addIncremental(this.fontSize,100,300,25,"%",_e.FONT_SIZE_REF,_e.FONT_SIZE_KEY),e.addIncremental(this.lineHeight,1,2,.25,"em",_e.LINE_HEIGHT_REF,_e.LINE_HEIGHT_KEY),e.addIncremental(this.wordSpacing,0,1,.25,"rem",_e.WORD_SPACING_REF,_e.WORD_SPACING_KEY),e.addIncremental(this.letterSpacing,0,.5,.0625,"em",_e.LETTER_SPACING_REF,_e.LETTER_SPACING_KEY),e.addSwitchable("readium-scroll-on","readium-scroll-off",this.verticalScroll,_e.SCROLL_REF,_e.SCROLL_KEY),e}async saveProperty(e){let t=await this.store.get(this.USERSETTINGS);if(t){let r=JSON.parse(t);r=r.filter(i=>i.name!==e.name),e.value!==void 0&&r.push(e),await this.store.set(this.USERSETTINGS,JSON.stringify(r))}else{let r=[];r.push(e),await this.store.set(this.USERSETTINGS,JSON.stringify(r))}return new Promise(r=>r(e))}async getProperty(e){let t=await this.store.get(this.USERSETTINGS);if(t){let r=JSON.parse(t);return r=r.filter(i=>i.name===e),r.length===0?null:r[0]}return null}async getPropertyAndFallback(e,t){var r;return((r=await this.getProperty(t))==null?void 0:r.value)??this[e]}async resetUserSettings(){this.store.remove(this.USERSETTINGS),await this.reset(),this.viewChangeCallback(),this.settingsChangeCallback()}get currentSettings(){var e,t,r,i,o,s,l,f,u,y;return{appearance:dt.appearanceValues[(t=(e=this.userProperties)==null?void 0:e.getByRef(_e.APPEARANCE_REF))==null?void 0:t.value],fontFamily:dt.fontFamilyValues[(i=(r=this.userProperties)==null?void 0:r.getByRef(_e.FONT_FAMILY_REF))==null?void 0:i.value],textAlignment:dt.textAlignmentValues[(s=(o=this.userProperties)==null?void 0:o.getByRef(_e.TEXT_ALIGNMENT_REF))==null?void 0:s.value],columnCount:dt.columnCountValues[(f=(l=this.userProperties)==null?void 0:l.getByRef(_e.COLUMN_COUNT_REF))==null?void 0:f.value],direction:dt.directionValues[(y=(u=this.userProperties)==null?void 0:u.getByRef(_e.DIRECTION_REF))==null?void 0:y.value],verticalScroll:this.verticalScroll,fontSize:this.fontSize,wordSpacing:this.wordSpacing,letterSpacing:this.letterSpacing,pageMargins:this.pageMargins,lineHeight:this.lineHeight}}async applyUserSettings(e){var t,r,i,o,s,l,f,u,y,m,_,v,g,h,c;if(e.appearance){this.appearance=dt.parseAppearanceSetting(e.appearance);let p=(t=this.userProperties)==null?void 0:t.getByRef(_e.APPEARANCE_REF);p&&(p.value=this.appearance,await this.storeProperty(p))}if(e.fontSize){this.fontSize=e.fontSize;let p=(r=this.userProperties)==null?void 0:r.getByRef(_e.FONT_SIZE_REF);p&&(p.value=this.fontSize,await this.storeProperty(p))}if(e.fontFamily){this.fontFamily=dt.fontFamilyValues.findIndex(w=>w===e.fontFamily);let p=(i=this.userProperties)==null?void 0:i.getByRef(_e.FONT_FAMILY_REF);p&&(p.value=this.fontFamily,await this.storeProperty(p))}if(e.letterSpacing){this.letterSpacing=e.letterSpacing;let p=(o=this.userProperties)==null?void 0:o.getByRef(_e.LETTER_SPACING_REF);p&&(p.value=this.letterSpacing,await this.storeProperty(p))}if(e.wordSpacing){this.wordSpacing=e.wordSpacing;let p=(s=this.userProperties)==null?void 0:s.getByRef(_e.WORD_SPACING_REF);p&&(p.value=this.wordSpacing,await this.storeProperty(p))}if(e.columnCount){this.columnCount=dt.columnCountValues.findIndex(w=>w===e.columnCount);let p=(l=this.userProperties)==null?void 0:l.getByRef(_e.COLUMN_COUNT_REF);p&&(p.value=this.columnCount,await this.storeProperty(p)),this.settingsColumnsChangeCallback()}if(e.direction){this.direction=dt.directionValues.findIndex(w=>w===e.direction);let p=(f=this.userProperties)==null?void 0:f.getByRef(_e.DIRECTION_REF);p&&(p.value=this.direction,await this.storeProperty(p))}if(e.textAlignment){this.textAlignment=dt.textAlignmentValues.findIndex(w=>w===e.textAlignment);let p=(u=this.userProperties)==null?void 0:u.getByRef(_e.TEXT_ALIGNMENT_REF);p&&(p.value=this.textAlignment,await this.storeProperty(p))}if(e.lineHeight){this.lineHeight=e.lineHeight;let p=(y=this.userProperties)==null?void 0:y.getByRef(_e.LINE_HEIGHT_REF);p&&(p.value=this.lineHeight,await this.storeProperty(p))}if(e.pageMargins){this.pageMargins=e.pageMargins;let p=(m=this.userProperties)==null?void 0:m.getByRef(_e.PAGE_MARGINS_REF);p&&(p.value=this.pageMargins,await this.storeProperty(p))}if(e.verticalScroll!==void 0){let p=(_=this.view)==null?void 0:_.getCurrentPosition();this.verticalScroll=dt.parseScrollSetting(e.verticalScroll);let w=(v=this.userProperties)==null?void 0:v.getByRef(_e.SCROLL_REF);w&&(w.value=this.verticalScroll,await this.saveProperty(w)),(h=(g=this.view)==null?void 0:g.setMode)==null||h.call(g,this.verticalScroll),p&&((c=this.view)==null||c.goToProgression(p)),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=dt.appearanceValues[0]:e==="sepia"||e==="readium-sepia-on"?t=dt.appearanceValues[1]:e==="night"||e==="readium-night-on"?t=dt.appearanceValues[2]:t=e,dt.appearanceValues.findIndex(r=>r===t)}async scroll(e){var i,o,s,l,f;let t=(i=this.view)==null?void 0:i.getCurrentPosition();this.verticalScroll=e;let r=(o=this.userProperties)==null?void 0:o.getByRef(_e.SCROLL_REF);r&&(r.value=this.verticalScroll,await this.saveProperty(r)),await this.applyProperties(),(l=(s=this.view)==null?void 0:s.setMode)==null||l.call(s,this.verticalScroll),t&&((f=this.view)==null||f.goToProgression(t)),this.viewChangeCallback()}async increase(e){var t,r,i,o,s,l,f,u,y,m,_,v,g,h,c,p;if(e==="fontSize"){((t=this.userProperties)==null?void 0:t.getByRef(_e.FONT_SIZE_REF)).increment(),this.fontSize=(i=(r=this.userProperties)==null?void 0:r.getByRef(_e.FONT_SIZE_REF))==null?void 0:i.value;let w=(o=this.userProperties)==null?void 0:o.getByRef(_e.FONT_SIZE_REF);w&&await this.storeProperty(w)}else if(e==="letterSpacing"){((s=this.userProperties)==null?void 0:s.getByRef(_e.LETTER_SPACING_REF)).increment(),this.letterSpacing=(f=(l=this.userProperties)==null?void 0:l.getByRef(_e.LETTER_SPACING_REF))==null?void 0:f.value;let w=(u=this.userProperties)==null?void 0:u.getByRef(_e.LETTER_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="wordSpacing"){((y=this.userProperties)==null?void 0:y.getByRef(_e.WORD_SPACING_REF)).increment(),this.wordSpacing=(_=(m=this.userProperties)==null?void 0:m.getByRef(_e.WORD_SPACING_REF))==null?void 0:_.value;let w=(v=this.userProperties)==null?void 0:v.getByRef(_e.WORD_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="lineHeight"){((g=this.userProperties)==null?void 0:g.getByRef(_e.LINE_HEIGHT_REF)).increment(),this.lineHeight=(c=(h=this.userProperties)==null?void 0:h.getByRef(_e.LINE_HEIGHT_REF))==null?void 0:c.value;let w=(p=this.userProperties)==null?void 0:p.getByRef(_e.LINE_HEIGHT_REF);w&&await this.storeProperty(w)}await this.applyProperties(),this.settingsChangeCallback()}async decrease(e){var t,r,i,o,s,l,f,u,y,m,_,v,g,h,c,p;if(e==="fontSize"){((t=this.userProperties)==null?void 0:t.getByRef(_e.FONT_SIZE_REF)).decrement(),this.fontSize=(i=(r=this.userProperties)==null?void 0:r.getByRef(_e.FONT_SIZE_REF))==null?void 0:i.value;let w=(o=this.userProperties)==null?void 0:o.getByRef(_e.FONT_SIZE_REF);w&&await this.storeProperty(w)}else if(e==="letterSpacing"){((s=this.userProperties)==null?void 0:s.getByRef(_e.LETTER_SPACING_REF)).decrement(),this.letterSpacing=(f=(l=this.userProperties)==null?void 0:l.getByRef(_e.LETTER_SPACING_REF))==null?void 0:f.value;let w=(u=this.userProperties)==null?void 0:u.getByRef(_e.LETTER_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="wordSpacing"){((y=this.userProperties)==null?void 0:y.getByRef(_e.WORD_SPACING_REF)).decrement(),this.wordSpacing=(_=(m=this.userProperties)==null?void 0:m.getByRef(_e.WORD_SPACING_REF))==null?void 0:_.value;let w=(v=this.userProperties)==null?void 0:v.getByRef(_e.WORD_SPACING_REF);w&&await this.storeProperty(w)}else if(e==="lineHeight"){((g=this.userProperties)==null?void 0:g.getByRef(_e.LINE_HEIGHT_REF)).decrement(),this.wordSpacing=(c=(h=this.userProperties)==null?void 0:h.getByRef(_e.LINE_HEIGHT_REF))==null?void 0:c.value;let w=(p=this.userProperties)==null?void 0:p.getByRef(_e.LINE_HEIGHT_REF);w&&await this.storeProperty(w)}await this.applyProperties(),this.settingsChangeCallback()}};dt.appearanceValues=["readium-default-on","readium-sepia-on","readium-night-on"],dt.fontFamilyValues=["Original","serif","sans-serif"],dt.textAlignmentValues=["auto","justify","start"],dt.columnCountValues=["auto","1","2"],dt.directionValues=["auto","ltr","rtl"];var Al=dt;L();L();L();L();L();L();L();L();var tw={stringify(n){let e=n.nSigBytes,t=n.words,r=[];for(let i=0;i<e;i++){let o=t[i>>>2]>>>24-i%4*8&255;r.push((o>>>4).toString(16)),r.push((o&15).toString(16))}return r.join("")},parse(n){let e=n.length;if(e%2!==0)throw new Error("Hex string count must be even");if(!/^[a-fA-F0-9]+$/.test(n))throw new Error(`Invalid Hex string: ${n}`);let t=[];for(let r=0;r<e;r+=2)t[r>>>3]|=parseInt(n.substr(r,2),16)<<24-r%8*4;return new In(t,e/2)}};L();L();var rw=typeof navigator<"u"&&navigator.userAgent?navigator.userAgent.toLowerCase():"",Ms=(()=>{let n=parseInt((/msie (\d+)/.exec(rw)||[])[1],10);return isNaN(n)?(n=parseInt((/trident\/.*; rv:(\d+)/.exec(rw)||[])[1],10),isNaN(n)?!1:n):n})();function nw(n,e){return Ms===!1?!1:e?n==="<"?Ms<e:n==="<="?Ms<=e:n===">"?Ms>e:n===">="?Ms>=e:Ms===e:!0}function CB(){if(typeof window<"u"){let n=window.crypto||window.msCrypto;if(!n){if(nw("<",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 n.getRandomValues(new Uint32Array(1))[0]}}else{if(typeof globalThis<"u"&&globalThis.crypto)return function(){return globalThis.crypto.randomBytes(4).readInt32LE()};if(typeof Tu=="function")return function(){return __non_webpack_require__("crypto").randomBytes(4).readInt32LE()}}throw new Error("Unable to find crypto module")}var iw=CB();var In=class n{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 n){this._words=e.words.slice(),this._nSignificantBytes=e.nSigBytes;return}let r;try{e instanceof ArrayBuffer?r=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)&&(r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}catch{throw new Error("Invalid argument")}if(!r)throw new Error("Invalid argument");let i=r.byteLength,o=[];for(let s=0;s<i;s++)o[s>>>2]|=r[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):tw.stringify(this)}toUint8Array(){let e=this._words,t=this._nSignificantBytes,r=new Uint8Array(t);for(let i=0;i<t;i++)r[i]=e[i>>>2]>>>24-i%4*8&255;return r}concat(e){let t=e.words.slice(),r=e.nSigBytes;if(this.clamp(),this._nSignificantBytes%4)for(let i=0;i<r;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<r;i+=4)this._words[this._nSignificantBytes+i>>>2]=t[i>>>2];return this._nSignificantBytes+=r,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 n(this._words.slice(),this._nSignificantBytes)}static random(e){let t=[];for(let r=0;r<e;r+=4)t.push(iw());return new n(t,e)}};L();L();var jg={stringify(n){let e=n.nSigBytes,t=n.words,r=[];for(let i=0;i<e;i++){let o=t[i>>>2]>>>24-i%4*8&255;r.push(String.fromCharCode(o))}return r.join("")},parse(n){let e=n.length,t=[];for(let r=0;r<e;r++)t[r>>>2]|=(n.charCodeAt(r)&255)<<24-r%4*8;return new In(t,e)}};var ow={stringify(n){try{return decodeURIComponent(escape(jg.stringify(n)))}catch{throw new Error("Malformed UTF-8 data")}},parse(n){return jg.parse(unescape(encodeURIComponent(n)))}};var Pf=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"?ow.parse(e):e;this._data.concat(t),this._nBytes+=t.nSigBytes}_process(e){let t,r=this._data.words,i=this._data.nSigBytes,o=this._blockSize,s=this._blockSize*4,l=i/s;e?l=Math.ceil(l):l=Math.max((l|0)-this._minBufferSize,0);let f=l*o,u=Math.min(f*4,i);if(f){for(let y=0;y<f;y+=o)this._doProcessBlock(r,y);t=r.splice(0,f),this._data.nSigBytes-=u}return new In(t,u)}_doProcessBlock(e,t){throw new Error("Not implemented")}};var Of=class extends Pf{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 qg=[],aw=[];function xB(n){let e=Math.sqrt(n);for(let t=2;t<=e;t++)if(!(n%t))return!1;return!0}function sw(n){return(n-(n|0))*4294967296|0}(function(){let e=2,t=0;for(;t<64;)xB(e)&&(t<8&&(qg[t]=sw(Math.pow(e,1/2))),aw[t]=sw(Math.pow(e,1/3)),t++),e++})();var ks=[],Ui=class n extends Of{constructor(e){super(e),this._hash=new In(qg.slice(0)),this._props=e,e&&typeof e.hash<"u"&&(this._hash=e.hash.clone())}_doReset(){this._hash=new In(qg.slice(0))}_doProcessBlock(e,t){let r=this._hash.words,i=r[0],o=r[1],s=r[2],l=r[3],f=r[4],u=r[5],y=r[6],m=r[7];for(let _=0;_<64;_++){if(_<16)ks[_]=e[t+_]|0;else{let A=ks[_-15],E=(A<<25|A>>>7)^(A<<14|A>>>18)^A>>>3,b=ks[_-2],C=(b<<15|b>>>17)^(b<<13|b>>>19)^b>>>10;ks[_]=E+ks[_-7]+C+ks[_-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),c=(f<<26|f>>>6)^(f<<21|f>>>11)^(f<<7|f>>>25),p=m+c+v+aw[_]+ks[_],w=h+g;m=y,y=u,u=f,f=l+p|0,l=s,s=o,o=i,i=p+w|0}r[0]=r[0]+i|0,r[1]=r[1]+o|0,r[2]=r[2]+s|0,r[3]=r[3]+l|0,r[4]=r[4]+f|0,r[5]=r[5]+u|0,r[6]=r[6]+y|0,r[7]=r[7]+m|0}_doFinalize(){let e=this._data.words,t=this._nBytes*8,r=this._data.nSigBytes*8;return e[r>>>5]|=128<<24-r%32,e[(r+64>>>9<<4)+14]=Math.floor(t/4294967296),e[(r+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 n(e)}static hash(e,t){return new n(t).finalize(e)}};var xl=rt(Vo());L();L();var Ur=rt($t());function kf(n,e){let t=n.getClientRects();return Gg(t,e)}function Gg(n,e){let r=[];for(let f of n)r.push({bottom:f.bottom,height:f.height,left:f.left,right:f.right,top:f.top,width:f.width});let i=lw(r,1,e),o=RB(i,1),s=cw(o),l=2*2;for(let f=s.length-1;f>=0;f--){let u=s[f];if(!(u.width*u.height>l))if(s.length>1)Ur.default.log("CLIENT RECT: remove small"),s.splice(f,1);else{Ur.default.log("CLIENT RECT: remove small, but keep otherwise empty!");break}}return dw(s),Ur.default.log(`CLIENT RECT: reduced ${r.length} --> ${s.length}`),s}function Zn(n,e,t){return Math.abs(n-e)<=t}function TB(n,e){let t=Math.max(n.left,e.left),r=Math.min(n.right,e.right),i=Math.max(n.top,e.top),o=Math.min(n.bottom,e.bottom);return{bottom:o,height:Math.max(0,o-i),left:t,right:r,top:i,width:Math.max(0,r-t)}}function uw(n,e){let t=TB(e,n);if(t.height===0||t.width===0)return[n];let r=[];{let i={bottom:n.bottom,height:0,left:n.left,right:t.left,top:n.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&r.push(i)}{let i={bottom:t.top,height:0,left:t.left,right:t.right,top:n.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&r.push(i)}{let i={bottom:n.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&&r.push(i)}{let i={bottom:n.bottom,height:0,left:t.right,right:n.right,top:n.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&r.push(i)}return r}function Mf(n,e,t,r){return(n.left<e||Zn(n.left,e,r))&&(n.right>e||Zn(n.right,e,r))&&(n.top<t||Zn(n.top,t,r))&&(n.bottom>t||Zn(n.bottom,t,r))}function PB(n,e,t){return Mf(n,e.left,e.top,t)&&Mf(n,e.right,e.top,t)&&Mf(n,e.left,e.bottom,t)&&Mf(n,e.right,e.bottom,t)}function OB(n,e){let t=Math.min(n.left,e.left),r=Math.max(n.right,e.right),i=Math.min(n.top,e.top),o=Math.max(n.bottom,e.bottom);return{bottom:o,height:o-i,left:t,right:r,top:i,width:r-t}}function Wg(n,e,t){return(n.left<e.right||t>=0&&Zn(n.left,e.right,t))&&(e.left<n.right||t>=0&&Zn(e.left,n.right,t))&&(n.top<e.bottom||t>=0&&Zn(n.top,e.bottom,t))&&(e.top<n.bottom||t>=0&&Zn(e.top,n.bottom,t))}function lw(n,e,t){for(let r=0;r<n.length;r++)for(let i=r+1;i<n.length;i++){let o=n[r],s=n[i];if(o===s){Ur.default.log("mergeTouchingRects rect1 === rect2 ??!");continue}let l=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||l&&!f)&&Wg(o,s,e)){Ur.default.log(`CLIENT RECT: merging two into one, VERTICAL: ${l} HORIZONTAL: ${f} (${t})`);let _=n.filter(g=>g!==o&&g!==s),v=OB(o,s);return _.push(v),lw(_,e,t)}}return n}function cw(n){for(let e=0;e<n.length;e++)for(let t=e+1;t<n.length;t++){let r=n[e],i=n[t];if(r===i){Ur.default.log("replaceOverlappingRects rect1 === rect2 ??!");continue}if(Wg(r,i,-1)){let o=[],s,l,f=uw(r,i);if(f.length===1)o=f,s=r,l=i;else{let m=uw(i,r);f.length<m.length?(o=f,s=r,l=i):(o=m,s=i,l=r)}let u=[];u.push(l),Array.prototype.push.apply(u,o),dw(u),Ur.default.log(`CLIENT RECT: overlap, cut one rect into ${o.length}`);let y=n.filter(m=>m!==s);return Array.prototype.push.apply(y,o),cw(y)}}return n}function MB(n,e){return Math.max(0,Math.min(n.right,e.right)-Math.max(n.left,e.left))}function kB(n,e){return Math.max(0,Math.min(n.bottom,e.bottom)-Math.max(n.top,e.top))}function RB(n,e){let t=new Set(n);for(let r of n){if(!(r.width>1&&r.height>1)){Ur.default.log("CLIENT RECT: remove tiny"),t.delete(r);continue}for(let o of n)if(r!==o&&t.has(o)&&PB(o,r,e)){Ur.default.log("CLIENT RECT: remove contained"),t.delete(r);break}}return Array.from(t)}function dw(n){let e=[];for(let t of n)for(let r of n){if(t===r)continue;let i=e.indexOf(t)>=0,o=e.indexOf(r)>=0;if((!i||!o)&&Wg(t,r,-1)){i||e.push(t),o||e.push(r),Ur.default.log("CLIENT RECT: overlap ---"),Ur.default.log(`#1 TOP:${t.top} BOTTOM:${t.bottom} LEFT:${t.left} RIGHT:${t.right} WIDTH:${t.width} HEIGHT:${t.height}`),Ur.default.log(`#2 TOP:${r.top} BOTTOM:${r.bottom} LEFT:${r.left} RIGHT:${r.right} WIDTH:${r.width} HEIGHT:${r.height}`);let s=MB(t,r);Ur.default.log(`xOverlap: ${s}`);let l=kB(t,r);Ur.default.log(`yOverlap: ${l}`)}}e.length&&Ur.default.log(`CLIENT RECT: overlaps ${e.length}`)}L();var Ft=rt($t());function ji(n,e){let t=n?n.getSelection():null;if(!t)return;if(t.isCollapsed){Ft.default.log("^^^ SELECTION COLLAPSED.");return}let r=t.toString(),i=r.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):pw(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset);if(!o||o.collapsed){Ft.default.log("$$$$$$$$$$$$$$$$$ CANNOT GET NON-COLLAPSED SELECTION RANGE?!");return}let s=IB(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 l=mo(s,e);if(!l){Ft.default.log("^^^ SELECTION RANGE INFO FAIL?!");return}return{rangeInfo:l,cleanText:i,rawText:r,range:s}}function pw(n,e,t,r){try{let i=new Range;if(i.setStart(n,e),i.setEnd(t,r),!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,r),o.setEnd(n,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 mo(n,e){let t=n.startContainer.nodeType===Node.ELEMENT_NODE,r=t?n.startContainer:n.startContainer.parentNode&&n.startContainer.parentNode.nodeType===Node.ELEMENT_NODE?n.startContainer.parentNode:void 0;if(!r)return;let i=t?-1:Array.from(r.childNodes).indexOf(n.startContainer);if(i<-1)return;let o=e(r),s=n.endContainer.nodeType===Node.ELEMENT_NODE,l=s?n.endContainer:n.endContainer.parentNode&&n.endContainer.parentNode.nodeType===Node.ELEMENT_NODE?n.endContainer.parentNode:void 0;if(!l)return;let f=s?-1:Array.from(l.childNodes).indexOf(n.endContainer);if(f<-1)return;let u=e(l),y=LB(n.startContainer,n.endContainer);if(!y){Ft.default.log("^^^ NO RANGE COMMON ANCESTOR?!");return}if(n.commonAncestorContainer){let m=n.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?n.commonAncestorContainer:n.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:n.endOffset,startContainerChildTextNodeIndex:i,startContainerElementCssSelector:o,startOffset:n.startOffset}}function Rf(n,e){let t=n.querySelector(e.startContainerElementCssSelector);if(!t){Ft.default.log("^^^ convertRangeInfo NO START ELEMENT CSS SELECTOR?!");return}let r=t;if(e.startContainerChildTextNodeIndex>=0){if(e.startContainerChildTextNodeIndex>=t.childNodes.length){Ft.default.log("^^^ convertRangeInfo rangeInfo.startContainerChildTextNodeIndex >= startElement.childNodes.length?!");return}if(r=t.childNodes[e.startContainerChildTextNodeIndex],r.nodeType!==Node.TEXT_NODE){Ft.default.log("^^^ convertRangeInfo startContainer.nodeType !== Node.TEXT_NODE?!");return}}let i=n.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 pw(r,e.startOffset,o,e.endOffset)}function LB(n,e){if(n.nodeType===Node.ELEMENT_NODE&&n===e||n.nodeType===Node.ELEMENT_NODE&&n.contains(e))return n;if(e.nodeType===Node.ELEMENT_NODE&&e.contains(n))return e;let t=[],r=n.parentNode;for(;r&&r.nodeType===Node.ELEMENT_NODE;)t.push(r),r=r.parentNode;let i=[];for(r=e.parentNode;r&&r.nodeType===Node.ELEMENT_NODE;)i.push(r),r=r.parentNode;let o=t.find(s=>i.indexOf(s)>=0);return o||(o=i.find(s=>t.indexOf(s)>=0)),o}function IB(n){let e=n.cloneRange(),t=e.startContainer,r=e.startOffset,i=e.endContainer,o=e.endOffset;t.childNodes.length&&r>0&&(t=hw(t.childNodes[r-1]),r=t.length||0),o<i.childNodes.length&&(i=fw(i.childNodes[o]),o=0);let s=fw(t),l=hw(i);function f(u){if(u.childNodes.length)return!1;let y=u.length||0;return u===t&&r===y?!1:!(u===i&&o===0)}for(;s&&!f(s)&&s!==l;)s=NB(s);for(s===t?e.setStart(t,r):s!==null&&(s.nodeType===3?e.setStart(s,0):e.setStartBefore(s));l&&!f(l)&&l!==s;)l=BB(l);return l===i?e.setEnd(i,o):l!==null&&(l.nodeType===3?e.setEnd(l,l.length):e.setEndAfter(l)),e}function NB(n){if(n.firstChild)return n.firstChild;let e=n;for(;!e.nextSibling;)if(e=e.parentNode,!e)return null;return e.nextSibling}function BB(n){if(n.lastChild)return n.lastChild;let e=n;for(;!e.previousSibling;)if(e=e.parentNode,!e)return null;return e.previousSibling}function fw(n){for(;n.firstChild;)n=n.firstChild;return n}function hw(n){for(;n.lastChild;)n=n.lastChild;return n}L();var Yg=rt(mw());var yo,Xg;function Cr(n,e,t){if(n.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if(n.tagName.toLowerCase()==="html")return n.tagName.toLowerCase();let r={className:o=>!0,idName:o=>!0,optimizedMinLength:2,root:e.body,seedMinLength:1,tagName:o=>!0,threshold:1e3};yo={...r,...t},Xg=GB(yo.root,r);let i=Vg(n,0,()=>Vg(n,1,()=>Vg(n,2)));if(i){let o=ww(Sw(i,n));return o.length>0&&(i=o[0]),Lf(i)}else throw new Error("Selector was not found.")}function GB(n,e){return n.nodeType===Node.DOCUMENT_NODE?n:n===e.root?n.ownerDocument:n}function Vg(n,e,t){let r=null,i=[],o=n,s=0;for(;o&&o!==yo.root.parentElement;){let l=Kg(WB(o))||Kg(...zB(o))||Kg(VB(o))||[$B()],f=JB(o);if(e===0)f&&(l=l.concat(l.filter(Jg).map(u=>$g(u,f))));else if(e===1)l=l.slice(0,1),f&&(l=l.concat(l.filter(Jg).map(u=>$g(u,f))));else if(e===2){let[u]=l=l.slice(0,1);f&&Jg(u)&&(l=[$g(u,f)])}for(let u of l)u.level=s;if(i.push(l),i.length>=yo.seedMinLength&&(r=yw(i,t),r))break;o=o.parentElement,s++}return r||(r=yw(i,t)),r}function yw(n,e){let t=ww(_w(n));if(t.length>yo.threshold)return e?e():null;for(let r of t)if(vw(r))return r;return null}function Lf(n){let e=n[0],t=e.name;for(let r=1;r<n.length;r++){let i=n[r].level||0;e.level===i-1?t=`${n[r].name} > ${t}`:t=`${n[r].name} ${t}`,e=n[r]}return t}function bw(n){return n.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function vw(n){switch(Xg.querySelectorAll(Lf(n)).length){case 0:throw new Error(`Can't select any node with this selector: ${Lf(n)}`);case 1:return!0;default:return!1}}function WB(n){let e=n.getAttribute("id");return e&&yo.idName(e)?{name:"#"+(0,Yg.default)(e,{isIdentifier:!0}),penalty:0}:null}function zB(n){return Array.from(n.classList).filter(yo.className).map(t=>({name:"."+(0,Yg.default)(t,{isIdentifier:!0}),penalty:1}))}function VB(n){let e=n.tagName.toLowerCase();return yo.tagName(e)?{name:e,penalty:2}:null}function $B(){return{name:"*",penalty:3}}function JB(n){let e=n.parentNode;if(!e)return null;let t=e.firstChild;if(!t)return null;let r=0;for(;t&&(t.nodeType===Node.ELEMENT_NODE&&r++,t!==n);)t=t.nextSibling;return r}function $g(n,e){return{name:n.name+`:nth-child(${e})`,penalty:n.penalty+1}}function Jg(n){return n.name!=="html"&&!n.name.startsWith("#")}function Kg(...n){let e=n.filter(KB);return e.length>0?e:null}function KB(n){return n!=null}function*_w(n,e=[]){if(n.length>0)for(let t of n[0])yield*_w(n.slice(1,n.length),e.concat(t));else yield e}function ww(n){return Array.from(n).sort((e,t)=>bw(e)-bw(t))}function*Sw(n,e){if(n.length>2&&n.length>yo.optimizedMinLength)for(let t=1;t<n.length-1;t++){let r=[...n];r.splice(t,1),vw(r)&&YB(r,e)&&(yield r,yield*Sw(r,e))}}function YB(n,e){return Xg.querySelector(Lf(n))===e}L();L();var Aw="0 0 24 24",fn=(n,e,t,r="icon")=>`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="${Aw}" preserveAspectRatio="xMidYMid meet" role="img" class="${r}" aria-labelledBy="${n}">
|
|
74
74
|
<title id="${n}">${e}</title>
|
|
75
75
|
${t}
|
|
76
76
|
</svg>`,XB=(n,e,t,r,i="icon")=>`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="${r}" preserveAspectRatio="xMidYMid meet" role="img" class="${i}" aria-labelledBy="${n}">
|
|
@@ -79,7 +79,7 @@ function print() { __p += __j.call(arguments, '') }
|
|
|
79
79
|
</svg>`,Da=(n,e,t,r="icon",i,o)=>`<svg xmlns="http://www.w3.org/2000/svg" width="${i}" height="${i}" viewBox="${Aw}" style="fill:${o}" preserveAspectRatio="xMidYMid meet" role="img" class="${r}" aria-labelledBy="${n}">
|
|
80
80
|
<title id="${n}">${e}</title>
|
|
81
81
|
${t}
|
|
82
|
-
</svg>`,mi={error:fn("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:fn("expand-icon","Enter fullscreen",'<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>',"icon active-icon"),loading:XB("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:fn("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:fn("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:fn("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:fn("toc-icon","Table of Contents",'<path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/>',"icon open"),bookmarks:fn("toc-icon","Bookmarks",'<path d="M4,6H2v16h16v-2H4V6z"/><path d="M22,2H6v16h16V2z M20,12l-2.5-1.5L15,12V4h5V12z"/>',"icon open"),bookmark:fn("toc-icon","Bookmark",'<path d="M19,3H5v18l7-3l7,3V3z"/>',"icon open"),delete:fn("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:fn("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:fn("text-icon","Text",'<path d="M5 4v3h5.5v12h3V7H19V4z"/>',"icon open"),speak:fn("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:fn("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:fn("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 e1=rt(If());var Yr=rt($t()),Rs=(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))(Rs||{}),Cw="R2_CLASS_HIGHLIGHT_CONTAINER",Tl="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",jr="R2_CLASS_HIGHLIGHT_AREA",Cl="R2_CLASS_HIGHLIGHT_ICON",qi=.5,Ew=.75,Ls={blue:100,green:50,red:230},er=[],ZB="data-highlighted",eD="data-timestamp",Ha={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",Cw,jr,Tl],Qg=-1,Zg=-1,Jt=class n{constructor(e,t,r,i,o){this.lastSelectedHighlight=void 0;this.activeAnnotationMarkerId=void 0;this.showTool=(0,xl.default)(e=>{this.isAndroid()||this.snapSelectionToWord(e),this.toolboxShow()},navigator.userAgent.toLowerCase().indexOf("firefox")>-1?200:100);this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,xl.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,xl.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,xl.default)((e,t)=>{var r,i;(r=this.api)!=null&&r.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=r,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(r=>r(t))}async initialize(e){var o;let t=e.contentDocument;t&&this.dom(t.body).addClass(this.options.contextClass),this.bindEvents((o=e.contentDocument)==null?void 0:o.body,this,this.hasEventListener),this.initializeToolbox(),Qg=-1,Zg=-1;let r=this;async function i(){r.lastSelectedHighlight===void 0||(r.lastSelectedHighlight=void 0)}setTimeout(async()=>{var l;let s=e.contentDocument;s&&await((l=s.body)==null?void 0:l.addEventListener("click",i))},100)}haveSameColor(e,t){return this.dom(e).color()===this.dom(t).color()}defaults(e,t){e=e||{};for(let r in t)t.hasOwnProperty(r)&&e[r]===void 0&&(e[r]=t[r]);return e}unique(e){return e.filter(function(t,r,i){return i.indexOf(t)===r})}refineRangeBoundaries(e){let t=e.startContainer,r=e.endContainer,i=e.commonAncestorContainer,o=!0;if(e.endOffset===0){for(;!r.previousSibling&&r.parentNode!==i;)r=r.parentNode;r=r.previousSibling}else r.nodeType===Ha.TEXT_NODE?e.endOffset<r.nodeValue.length&&r.splitText(e.endOffset):e.endOffset>0&&(r=r.childNodes.item(e.endOffset-1));return t.nodeType===Ha.TEXT_NODE?e.startOffset===t.nodeValue.length?o=!1:e.startOffset>0&&(t=t.splitText(e.startOffset),r===t.previousSibling&&(r=t)):e.startOffset<t.childNodes.length?t=t.childNodes.item(e.startOffset):t=t.nextSibling,{startContainer:t,endContainer:r,goDeeper:o}}sortByDepth(e,t){let r=this;e.sort(function(i,o){return r.dom(t?o:i).parents().length-r.dom(t?i:o).parents().length})}groupHighlights(e){let t=[],r={},i=[];return e.forEach(function(o){let s=o.getAttribute(eD);typeof r[s]>"u"&&(r[s]=[],t.push(s)),r[s].push(o)}),t.forEach(function(o){let s=r[o];i.push({chunks:s,timestamp:o,toString:function(){return s.map(function(l){return l.textContent}).join("")}})}),i}dom(e){let t=this;return{addClass:function(r){e.classList?e.classList.add(r):e.className+=" "+r},removeClass:function(r){e.classList?e.classList.remove(r):e.className=e.className.replace(new RegExp("(^|\\b)"+r+"(\\b|$)","gi")," ")},prepend:function(r){let i=Array.prototype.slice.call(r),o=i.length;for(;o--;)e.insertBefore(i[o],e.firstChild)},append:function(r){let i=Array.prototype.slice.call(r);for(let o=0,s=i.length;o<s;++o)e.appendChild(i[o])},insertAfter:function(r){var i;return(i=r.parentNode)==null?void 0:i.insertBefore(e,r.nextSibling)},insertBefore:function(r){var i;return(i=r.parentNode)==null?void 0:i.insertBefore(e,r)},remove:function(){e.parentNode.removeChild(e),e=null},contains:function(r){return e!==r&&e.contains(r)},wrap:function(r){return e.parentNode&&e.parentNode.insertBefore(r,e),r.appendChild(e),r},unwrap:function(){let r=Array.prototype.slice.call(e.childNodes),i;return r.forEach(function(o){i=o.parentNode,t.dom(o).insertBefore(o.parentNode),t.dom(i).remove()}),r},parents:function(){let r,i=[];for(;r=e.parentNode;)i.push(r),e=r;return i},normalizeTextNodes:function(){if(e){if(e.nodeType===Ha.TEXT_NODE)for(;e.nextSibling&&e.nextSibling.nodeType===Ha.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(r){let i=document.createElement("div");return i.innerHTML=r,i.childNodes},getRange:function(){var o;let r=(o=t.dom(e))==null?void 0:o.getSelection(),i;return(r==null?void 0:r.rangeCount)>0&&(i=r==null?void 0:r.getRangeAt(0)),i},removeAllRanges:function(){var i;let r=(i=t.dom(e))==null?void 0:i.getSelection();r==null||r.removeAllRanges(),t.toolboxHide()},getSelection:function(){var r;return(r=t.dom(e).getWindow())==null?void 0:r.getSelection()},getWindow:function(){var r;return(r=t.dom(e).getDocument())==null?void 0:r.defaultView},getDocument:function(){return(e==null?void 0:e.ownerDocument)||e}}}disableContext(e){return e.preventDefault(),e.stopPropagation(),!1}bindEvents(e,t,r){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)),r||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(Qg=e.clientX,Zg=e.clientY,(t=this.properties)!=null&&t.preventScrollOnSelection){let r=yt(document,"#iframe-wrapper");r.style.overflow="hidden"}}async mouseup(e){Math.abs(Qg-e.clientX)<3&&Math.abs(Zg-e.clientY)<3&&await this.processMouseEvent(e)}async mousemove(e){await this.processMouseEvent(e)}unbindEvents(e,t){let r=e.ownerDocument;e.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),e.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),r.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),r.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),window.removeEventListener("resize",this.toolboxPlacement.bind(this)),r.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"),r=["#fce300","#48e200","#00bae5","#157cf9","#6a39b7","#ea426a","#ff8500"],i=document.getElementById("colorIcon"),o=document.getElementById("actionIcon"),s=document.getElementById("dismissIcon"),l=document.getElementById("collapseIcon"),f=document.getElementById("highlightIcon"),u=this;if(s&&(s.innerHTML=mi.close,s.addEventListener("click",function(){u.toolboxMode("add")})),l&&(l.innerHTML=mi.close,l.addEventListener("click",function(){u.toolboxMode("add")})),i){i.style.position="relative",i.style.zIndex="20",r.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;r.forEach(v=>{_--;let g=i==null?void 0:i.cloneNode(!0),h=g.lastChild,c=n.hexToRgbChannels(v);h.style.backgroundColor="rgba("+[c.red,c.green,c.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)})}r.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,E,b;u.setColor(_);let h=i==null?void 0:i.lastChild;h&&(h.style.backgroundColor=_);let c=document.getElementById("highlightIcon"),p=document.getElementById("underlineIcon"),w=document.getElementById("noteIcon");(((A=c==null?void 0:c.getElementsByTagName)==null?void 0:A.call(c,"span").length)??0)>0&&((c==null?void 0:c.getElementsByTagName("span")[0]).style.background=u.getColor()),(((E=p==null?void 0:p.getElementsByTagName)==null?void 0:E.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"),r=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"),r&&(r.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none");break;case"edit":t&&(t.style.display="none"),r&&(r.style.display="none"),i&&(i.style.display="unset"),o&&(o.style.display="none");break;case"action":t&&(t.style.display="none"),r&&(r.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="unset");break;default:t&&(t.style.display="none"),r&&(r.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 r=yt(document,"#iframe-wrapper");r.style.overflow="auto"}}toolboxShowDelayed(e){this.showTool(e.detail===1)}snapSelectionToWord(e=!1){var o;let t=this,r=this.navigator.iframes[0].contentDocument;if(r){let s=(o=t.dom(r.body))==null?void 0:o.getSelection();if(t.dom(r.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)},l=s.toString(),f=l.length-l.trimStart().length,u=l.length-l.trimEnd().length,m=l.length;var i=/[-!$%^&*()_+|~=`{}[\]:/;<>?,.@#]/;l=l.replace(i,""),f=m-l.trimStart().length,l=y(l),u=m-l.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 c=["forward","backward"];v&&(c=["backward","forward"]),e?(s.modify("move",c[0],"character"),s.modify("move",c[1],"word"),s.extend(g,h),s.modify("extend",c[1],"character"),s.modify("extend",c[0],"word")):s.extend(g,h),this.selection(s.toString(),s)}return s}}toolboxShow(){var e;if(this.activeAnnotationMarkerId===void 0){let t=this,r=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)&&r){getComputedStyle(r).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 l(_){let v={className:h=>Nn.indexOf(h)<0,idName:h=>Nn.indexOf(h)<0},g=t.navigator.iframes[0].contentDocument;if(g)return Cr(_,g,v)}let f=t.navigator.iframes[0].contentWindow,u=ji(f,l);(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,l,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(),r=document.getElementById("highlight-toolbox");r&&(((o=this.properties)==null?void 0:o.menuPosition)==="top"?(r.style.left="0px",r.style.transform="revert",r.style.width="100%",r.style.textAlign="center",r.style.position="absolute",r.style.setProperty("--content","revert")):((s=this.properties)==null?void 0:s.menuPosition)==="bottom"?(r.style.bottom="0px",r.style.left="0px",r.style.transform="revert",r.style.width="100%",r.style.textAlign="center",r.style.position="absolute",r.style.setProperty("--content","revert")):(((l=this.navigator.view)==null?void 0:l.isPaginated())?r.style.top=t.top+(((f=this.navigator.attributes)==null?void 0:f.navHeight)??0)+"px":r.style.top=t.top+"px",r.style.left=(t.right-t.left)/2+t.left+"px"))}toolboxHandler(){var t,r,i,o,s,l,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"),c=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);(r=m==null?void 0:m.parentNode)==null||r.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(c){let p=function(){c==null||c.removeEventListener("click",p),y.speak()},w=c.cloneNode(!0);(s=c==null?void 0:c.parentNode)==null||s.replaceChild(w,c),c=document.getElementById("speakIcon"),c==null||c.addEventListener("click",p)}}else c&&c.style.setProperty("display","none");(((l=this.properties)==null?void 0:l.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 E(){var R,B,I,D,F,z,q;w==null||w.removeEventListener("click",E);function C(G){let Y={className:Q=>Nn.indexOf(Q)<0,idName:Q=>Nn.indexOf(Q)<0},X=A.navigator.iframes[0].contentDocument;if(X)return Cr(G,X,Y)}let k=A.navigator.iframes[0].contentWindow;if(k){let G=ji(k,C);if(G===void 0){let Y=A.navigator.iframes[0].contentDocument;G=(B=(R=A.navigator.annotationModule)==null?void 0:R.annotator)==null?void 0:B.getTemporarySelectionInfo(Y)}if(G!==void 0)if(p.callback)p.callback(G.cleanText,(I=G.range)==null?void 0:I.startContainer.parentElement);else{let Y=(D=p.highlight)==null?void 0:D.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 se=A.createHighlight(A.dom(Q.body).getWindow(),G,(F=p.highlight)==null?void 0:F.color,!0,X,p.icon,p.popup,Y);A.options.onAfterHighlight(se,X),A.navigator.rights.enableAnnotations?(z=A.navigator.annotationModule)==null||z.saveAnnotation(se[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 M;(M=A.navigator.annotationModule)==null||M.updateAnnotation(H).then(async()=>{Yr.default.log("update highlight "+H.id)})}))}):A.navigator.rights.enableBookmarks&&((q=A.navigator.bookmarkModule)==null||q.saveAnnotation(se[0]))}}}}A.callbackComplete()}if(w){let C=w.cloneNode(!0);(b=w==null?void 0:w.parentNode)==null||b.replaceChild(C,w),w=document.getElementById(p.id),w==null||w.addEventListener("click",E)}})}}doHighlight(e,t){var s,l,f,u,y,m;let r=this;function i(_){let v={className:h=>Nn.indexOf(h)<0,idName:h=>Nn.indexOf(h)<0},g=r.navigator.iframes[0].contentDocument;if(g)return Cr(_,g,v)}let o=r.navigator.iframes[0].contentWindow;if(o){let _=ji(o,i);if(_===void 0){let v=r.navigator.iframes[0].contentDocument;_=(l=(s=this.navigator.annotationModule)==null?void 0:s.annotator)==null?void 0:l.getTemporarySelectionInfo(v)}if(_){if(this.options.onBeforeHighlight(_)===!0){let v;v=this.getColor(),n.isHexColor(v)&&(v=n.hexToRgbChannels(v));let g=r.navigator.iframes[0].contentDocument;if(g){let h=this.createHighlight(r.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=r.navigator.iframes[0].contentDocument;if(y)return Cr(f,y,u)},r=this,o=r.navigator.iframes[0].contentWindow;if(o){let f=ji(o,i);if(f===void 0){let u=r.navigator.iframes[0].contentDocument;f=(t=(e=r.navigator.annotationModule)==null?void 0:e.annotator)==null?void 0:t.getTemporarySelectionInfo(u)}f!==void 0&&this.navigator.ttsModule.speak(f,!0,()=>{})}let s=r.navigator.iframes[0].contentDocument;s&&r.dom(s.body).getSelection().removeAllRanges();let l=document.getElementById("highlight-toolbox");l&&(l.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=yt(document,"#iframe-wrapper"),r=t.scrollLeft,i=r+t.clientWidth,o=e.left+e.width,s=e.top+e.height,l=t.scrollTop,f=l+t.clientHeight,u=s<l,y=e.top>f,m=o<r,_=e.left>i;return u||y||m||_}isInsideViewport(e){let t=yt(document,"#iframe-wrapper"),r=t.scrollTop,i=r+t.clientHeight,o=e.top+20>=r,s=e.top<=i,l=t.scrollLeft,f=l+t.clientWidth,u=e.left+e.width,y=e.left>l,m=u<f;return o&&s&&y&&m}get visibleTextRects(){let e=this.navigator.iframes[0].contentDocument;if(e){let r=function(l,f=[]){var y;let u=l.firstChild;for(;u;)u.nodeType===1&&r(u,f),u.nodeType===3&&(y=u.textContent)!=null&&y.trim()&&f.push(u),u=u.nextSibling;return f},i=function(l){return r(l).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(l){try{let f=document.createRange();f.selectNode(l);let u=f.getBoundingClientRect();return f.detach(),u}catch(f){Yr.default.log("measureTextNode "+f),Yr.default.log("measureTextNode "+l),Yr.default.log(`${l.textContent}`)}},t=co(e,"body");return i(t).filter(l=>this.isInsideViewport(l))}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(r){return r.parentElement?r:null}),t=this.unique(t),t.sort(function(r,i){return r.offsetTop-i.offsetTop||r.offsetLeft-i.offsetLeft}),t}flattenNestedHighlights(e){let t,r=this;r.sortByDepth(e,!0);function i(){let o=!1;return e.forEach(function(s,l){let f=s.parentElement,u=f.previousSibling,y=f.nextSibling;r.isHighlight(f)&&(r.haveSameColor(f,s)?(f.replaceChild(s.firstChild,s),e[l]=f,o=!0):(s.nextSibling||(r.dom(s).insertBefore(y||f),o=!0),s.previousSibling||(r.dom(s).insertAfter(u||f),o=!0),f.hasChildNodes()||r.dom(f).remove()))}),o}do t=i();while(t)}mergeSiblingHighlights(e){let t=this;function r(i,o){return o&&o.nodeType===Ha.ELEMENT_NODE&&t.haveSameColor(i,o)&&t.isHighlight(o)}e.forEach(function(i){let o=i.previousSibling,s=i.nextSibling;r(i,o)&&(t.dom(i).prepend(o.childNodes),t.dom(o).remove()),r(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===Ha.ELEMENT_NODE&&e.hasAttribute(ZB)}createWrapper(){let e=document.createElement("mark");return e.style.background="linear-gradient("+n.hexToRgbA(this.options.color)+", "+n.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 r=e;return"rgba("+[r.red,r.green,r.blue].join(",")+",.5)"}throw new Error("Bad Hex")}static hexToRgbAWithOpacity(e,t){let r;if(this.isHexColor(e))return r=this.hexToRgbChannels(e),"rgba("+[r.red,r.green,r.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,l,f,u,y,m,_,v,g,h,c,p,w,A;let r=(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 E=er.find(b=>b.id===i);if(E){if(E.marker===3||E.marker===2)if((s=E.style)!=null&&s.hover){if((l=E.style)!=null&&l.hover)for(let k=0;k<((u=(f=E.style)==null?void 0:f.hover)==null?void 0:u.length);k++){let R=(y=E.style)==null?void 0:y.hover[k];e.style.removeProperty(R.property)}let C="";if((m=E.style)!=null&&m.default)for(let k=0;k<((v=(_=E.style)==null?void 0:_.default)==null?void 0:v.length);k++){let R=(g=E.style)==null?void 0:g.default[k];e.style.removeProperty(R.property),C+=`${R.property}: ${R.value} !${R.priority};`}e.setAttribute("style",`${e.getAttribute("style")}; ${C}`)}else if((h=E.style)!=null&&h.hoverClass){(c=E.style)!=null&&c.hoverClass&&e.classList.remove((p=E.style)==null?void 0:p.hoverClass);let C="";(w=E.style)!=null&&w.defaultClass&&e.classList.add((A=E.style)==null?void 0:A.defaultClass),e.setAttribute("style",`${e.getAttribute("style")}; ${C}`)}else if(n.isHexColor(E.color)){let C=n.hexToRgbChannels(E.color);e.style.setProperty("background-color",`rgba(${C.red}, ${C.green}, ${C.blue}, 0)`,"important")}else e.classList.remove("hover");else if(E.marker===1||E.marker===4)if(typeof E.color=="object"){let C=E.color;e.style.setProperty("background-color",`rgba(${C.red}, ${C.green}, ${C.blue}, 0)`,"important"),e.style.setProperty("border-bottom",`2px solid rgba(${C.red}, ${C.green}, ${C.blue}, 1)`,"important")}else if(n.isHexColor(E.color)){let C=n.hexToRgbChannels(E.color);e.style.setProperty("background-color",`rgba(${C.red}, ${C.green}, ${C.blue}, 0)`,"important"),e.style.setProperty("border-bottom",`2px solid rgba(${C.red}, ${C.green}, ${C.blue}, 1)`,"important")}else e.classList.remove("hover");else if(typeof E.color=="object"){let C=E.color;e.style.setProperty("background-color",`rgba(${C.red}, ${C.green}, ${C.blue}, ${qi})`,"important")}else if(n.isHexColor(E.color)){let C=n.hexToRgbChannels(E.color);e.style.setProperty("background-color",`rgba(${C.red}, ${C.green}, ${C.blue}, ${qi})`,"important")}else e.classList.remove("hover");let b;if(r){let C=r.getElementById(t);C&&(b=C.querySelector(`#${E.id}`))}if(b){let C=b.getElementsByClassName(Cl);if(C.length>0){let k=C.item(0).getElementsByClassName("icon-tooltip");k.length>0&&k.item(0).style.removeProperty("display")}}}}}setHighlightAreaStyle(e,t,r){var i,o,s,l,f,u,y,m,_,v,g,h;for(let c of t){if(r.marker===3||r.marker===2)if((i=r.style)!=null&&i.hover){if((o=r.style)!=null&&o.default)for(let w=0;w<((l=(s=r.style)==null?void 0:s.default)==null?void 0:l.length);w++){let A=(f=r.style)==null?void 0:f.default[w];c.style.removeProperty(A.property)}let p="";for(let w=0;w<((y=(u=r.style)==null?void 0:u.hover)==null?void 0:y.length);w++){let A=(m=r.style)==null?void 0:m.hover[w];c.style.removeProperty(A.property),p+=`${A.property}: ${A.value} !${A.priority};`}c.setAttribute("style",`${c.getAttribute("style")}; ${p}`)}else if((_=r.style)!=null&&_.hoverClass){(v=r.style)!=null&&v.defaultClass&&c.classList.remove((g=r.style)==null?void 0:g.defaultClass);let p="";c.classList.add((h=r.style)==null?void 0:h.hoverClass),c.setAttribute("style",`${c.getAttribute("style")}; ${p}`)}else if(n.isHexColor(r.color)){let p=n.hexToRgbChannels(r.color);c.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${.1})`,"important")}else c.classList.add("hover");else if(r.marker===1||r.marker===4)if(typeof r.color=="object"){let p=r.color;c.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${.1})`,"important"),c.style.setProperty("border-bottom",`2px solid rgba(${p.red}, ${p.green}, ${p.blue}, 1)`,"important")}else if(n.isHexColor(r.color)){let p=n.hexToRgbChannels(r.color);c.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${.1})`,"important"),c.style.setProperty("border-bottom",`2px solid rgba(${p.red}, ${p.green}, ${p.blue}, 1)`,"important")}else c.classList.add("hover");else if(typeof r.color=="object"){let p=r.color;c.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${Ew})`,"important")}else if(n.isHexColor(r.color)){let p=n.hexToRgbChannels(r.color);c.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${Ew})`,"important")}else c.classList.add("hover");if(r.type!==4){let w=e.getElementById("R2_ID_HIGHLIGHTS_CONTAINER").querySelector(`#${r.id}`).getElementsByClassName(Cl);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 r=(o=this.navigator.iframes[0].contentWindow)==null?void 0:o.document,i=Array.from(r.getElementById("R2_ID_SEARCH_CONTAINER").querySelectorAll(`.${jr}`));for(let s of i){let l=s,f=l.parentNode&&l.parentNode.nodeType===Node.ELEMENT_NODE&&l.parentNode.getAttribute?l.parentNode.getAttribute("id"):void 0;if(t.forEach(u=>{if(f===u.id&&u){if(typeof u.color=="object"){let _=u.color;l.style.setProperty("background-color",`rgba(${_.red}, ${_.green}, ${_.blue}, ${qi})`,"important")}else if(n.isHexColor(u.color)){let _=n.hexToRgbChannels(u.color);l.style.setProperty("background-color",`rgba(${_.red}, ${_.green}, ${_.blue}, ${qi})`,"important")}else l.classList.remove("hover");let m=r.getElementById("R2_ID_SEARCH_CONTAINER").querySelector(`#${u.id}`).getElementsByClassName(Cl);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;l.style.setProperty("background-color",`rgba(${m.red}, ${m.green}, ${m.blue}, ${qi})`,"important")}else if(n.isHexColor(e.color)){let m=n.hexToRgbChannels(e.color);l.style.setProperty("background-color",`rgba(${m.red}, ${m.green}, ${m.blue}, ${qi})`,"important")}else l.classList.remove("hover");let y=r.getElementById("R2_ID_SEARCH_CONTAINER").querySelector(`#${e.id}`).getElementsByClassName(Cl);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,l,f,u,y,m,_,v,g,h,c,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 r=e.target,i=er.find(w=>{var A;return w.id===((A=e.target.parentElement)==null?void 0:A.id)});if(!i||!r){for(let w in Rs){let A=t.getElementById(w);if(A){let E=A.querySelectorAll(`.${Tl}`);for(let C of E)this.resetHighlightBoundingStyle(C);let b=Array.from(A.querySelectorAll(`.${jr}`));for(let C of b)this.resetHighlightAreaStyle(C,w)}}return}if(r.getAttribute("data-click")&&(e.type==="mouseup"||e.type==="click"||e.type==="touchup")&&((s=r.parentElement)==null?void 0:s.style.display)!=="none"){let w={highlight:i};Yr.default.log(JSON.stringify(w));let A=this,E;if(A.navigator.rights.enableAnnotations?E=await((l=this.navigator.annotationModule)==null?void 0:l.getAnnotation(w.highlight)):A.navigator.rights.enableBookmarks&&(E=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(E).then(async()=>{})),E!=null&&E.id){Yr.default.log("selected highlight "+E.id),A.lastSelectedHighlight=E.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 R=function(){var q,G;(G=(q=A.navigator.annotationModule)==null?void 0:q.api)==null||G.addCommentToAnnotation(E).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(),B==null||B.removeEventListener("click",R,!1)})},D=function(){var q,G;A.navigator.rights.enableAnnotations?(q=A.navigator.annotationModule)==null||q.deleteSelectedHighlight(E).then(async()=>{Yr.default.log("delete highlight "+E.id),b&&(b.style.display="none"),A.selectionMenuClosed()}):A.navigator.rights.enableBookmarks&&((G=A.navigator.bookmarkModule)==null||G.deleteSelectedHighlight(E).then(async()=>{Yr.default.log("delete highlight "+E.id),b&&(b.style.display="none"),A.selectionMenuClosed()}))};b.style.display="block",this.toolboxMode("edit");let C=document.getElementById("colorIcon"),k=document.getElementById("highlightIcon");C&&(C.style.display="none"),k&&(k.style.display="none");let B=document.getElementById("commentIcon"),I=document.getElementById("cloneCommentIcon");if(I){let q=I.parentElement;q&&q.removeChild(I)}if(B){B.style.display="none";let q=B.cloneNode(!0),G=B.parentElement;q.style.display="unset",q.id="cloneCommentIcon",q.addEventListener("click",R,!1),G&&G.append(q)}let F=document.getElementById("deleteIcon"),z=document.getElementById("cloneDeleteIcon");if(z){let q=z.parentElement;q&&q.removeChild(z)}if(F){F.style.display="none";let q=F.cloneNode(!0),G=F.parentElement;q.style.display="unset",q.id="cloneDeleteIcon",q.addEventListener("click",D,!1),G&&G.append(q)}}else b.style.display="none",this.selectionMenuClosed(),b.offsetWidth,b.style.display="block"}else{r.dataset.definition&&new Ba(this.navigator).showPopup(r.dataset.definition,e);let b=(g=(v=(_=this.navigator.definitionsModule)==null?void 0:_.properties)==null?void 0:v.definitions)==null?void 0:g.filter(C=>C.order===Number(r==null?void 0:r.dataset.order))[0];Yr.default.log(b),(c=(h=this.navigator.definitionsModule)==null?void 0:h.api)!=null&&c.click&&((p=this.navigator.definitionsModule.api)==null||p.click(e1.omit(b,"callbacks"),e1.omit(i,"definition")),this.navigator.emit("definition.click",b,i))}}}async prepareContainers(e){for(let t in Rs)await this.ensureHighlightsContainer(e,t)}async ensureHighlightsContainer(e,t){var i,o;let r=e.document;if(!r.getElementById(t)){let s=r.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")),r.body&&r.body.append(s),((o=await this.layerSettings.getProperty(t))==null?void 0:o.value)===!1&&(s.style.display="none")}return r.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 r;let t=(r=this.navigator.iframes[0].contentWindow)==null?void 0:r.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 r=-1;er.find((s,l)=>(r=l,s.id===t))&&r>=0&&r<er.length&&er.splice(r,1);let o=e.getElementById(t);o&&this.removeAllChildNodes(o)}createHighlight(e,t,r,i,o,s,l,f,u,y){try{let m=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,_=Ui.hash(m),v=(y||"R2_HIGHLIGHT_")+_;this.destroyHighlight(e.document,v);let g=`rgb(${Ls.red}, ${Ls.green}, ${Ls.blue})`,h={color:r||g,id:v,pointerInteraction:i,selectionInfo:t,marker:o,icon:s,popup:l,style:f,type:u||0};(u===0||u===4||u===void 0)&&er.push(h);let c=this.createHighlightDom(e,h);return h.position=parseInt((c!=null&&c.hasChildNodes()?c.childNodes[0]:c).style.top.replace("px","")),[h,c]}catch(m){throw"Can't create highlight: "+m}}createHighlightDom(e,t){var F,z,q,G,Y,X,Q,se,ve,ce,W,H,M,x,T,P,N,U,V,Z,re,ne,ae,fe,he,Te,Ne,Se,ye,oe,Ee,xe;let r=e.document,i=Rf(r,t.selectionInfo.rangeInfo);if(!i)return;for(let K in Rs)this.ensureHighlightsContainer(e,K);let o=r.createElement("div");o.setAttribute("id",t.id),o.setAttribute("class",Cw),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,Ce=er.find(Re=>Re.id===K.currentTarget.id);if(K.type==="mouseover"&&((ie=be.parentElement)==null?void 0:ie.style.display)!=="none"&&Ce){let Re=Array.from(be.querySelectorAll(`.${jr}`));this.setHighlightAreaStyle(r,Re,Ce)}}}),o.addEventListener("mouseleave",K=>{let ie=K.currentTarget,be=Array.from(ie.querySelectorAll(`.${jr}`));for(let Ke of be)this.resetHighlightAreaStyle(Ke,ie.id);let Ce=ie.querySelector(`.${Tl}`),Re=ie.querySelectorAll(`.${Tl}`);for(let Ke of Re)(!Ce||Ke!==Ce)&&this.resetHighlightBoundingStyle(Ke)}));let s=(F=this.navigator.view)==null?void 0:F.isPaginated();s?r.body.style.position="revert":r.body.style.position="relative";let l=r.body.getBoundingClientRect(),f=this.getScrollingElement(r),u=s?-f.scrollLeft:l.left,y=s?-f.scrollTop:l.top,m=1,_=!1,v=!1,h=_||v||!1;Yr.default.debug(h),h=!0;let c=kf(i,h),p=3,w=2,A=3,E=0,b=24,C,k;for(let K of c){let ie=r.createElement("div");ie.setAttribute("class",jr),ie.dataset.marker=""+t.marker;let be="";if(_&&t.marker!==3&&t.marker!==2&&t.marker!==4){let Be=t.color;n.isHexColor(Be)&&(Be=n.hexToRgbChannels(Be)),be+=`border-bottom: ${w*m}px solid rgba(${Be.red}, ${Be.green}, ${Be.blue}, ${qi}) !important`}if(t.marker===3||t.marker===2)if((z=t.style)!=null&&z.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(n.isHexColor(t.color)){let Be=n.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}, ${qi}) !important; ${be}`)}else if(n.isHexColor(t.color)){let Be=n.hexToRgbChannels(t.color);ie.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${p}px !important; background-color: rgba(${Be.red}, ${Be.green}, ${Be.blue}, ${qi}) !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 Ce=parseInt(ie.style.top.replace("px",""));if((Ce<E||E===0)&&(E=Ce),b=parseInt(ie.style.height.replace("px","")),v){let Be=r.createElement("div");Be.setAttribute("class",jr);let ut=t.color;n.isHexColor(ut)&&(ut=n.hexToRgbChannels(ut)),Be.setAttribute("style",`background-color: rgba(${ut.red}, ${ut.green}, ${ut.blue}, ${qi}) !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=(se=this.navigator.iframes[0].contentWindow)==null?void 0:se.innerWidth,Ke=parseInt(getComputedStyle(r.documentElement).getPropertyValue("column-count")),ze=parseInt(getComputedStyle(r.documentElement).getPropertyValue("column-width")),Ve=parseInt(getComputedStyle(r.body).getPropertyValue("padding-left")),qe=Re/(Ke||1);qe<ze&&(qe=Re),s||(qe=parseInt(getComputedStyle(r.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),C=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,C=C-Ve/Ke),s||(C=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,C=C-Ve/2))}let R=i.getBoundingClientRect(),B=r.createElement("div");B.setAttribute("class",Tl),B.style.setProperty("pointer-events","none"),B.style.position="absolute",B.scale=m,B.rect={height:R.height,left:R.left-u,top:R.top-y,width:R.width},B.style.width=`${B.rect.width*m}px`,B.style.height=`${B.rect.height*m}px`,B.style.left=`${B.rect.left*m}px`,B.style.top=`${B.rect.top*m}px`,o.append(B);let I=r.createElement("div");if(I.setAttribute("class",Cl),((W=t.icon)==null?void 0:W.position)==="left")I.setAttribute("style",`position: absolute;top:${E}px;left:${k+((M=(H=this.navigator.iframes[0].contentDocument)==null?void 0:H.scrollingElement)==null?void 0:M.scrollLeft)}px;height:${b}px; width:${b}px;`);else if(((x=t.icon)==null?void 0:x.position)==="inline")I.setAttribute("style",`position: absolute;top:${E-b/2}px;left:${parseInt(B.style.left.replace("px",""))+parseInt(B.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;I.setAttribute("style",`position: absolute;top:${E}px;left:${parseInt(B.style.left.replace("px",""))+parseInt(B.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?I.setAttribute("style",`position: absolute;top:${E-b/2}px;left:${parseInt(B.style.left.replace("px",""))+parseInt(B.style.width.replace("px",""))-b/2}px;height:${b}px; width:${b}px;`):t.note&&t.marker===4||t.marker===0||t.marker===1?I.setAttribute("style",`position: absolute;top:${E}px;left:${C+((N=(P=this.navigator.iframes[0].contentDocument)==null?void 0:P.scrollingElement)==null?void 0:N.scrollLeft)}px;height:${b}px; width:${b}px;`):I.setAttribute("style",`position: absolute;top:${E}px;left:${C+((V=(U=this.navigator.iframes[0].contentDocument)==null?void 0:U.scrollingElement)==null?void 0:V.scrollLeft)}px;height:${b}px; width:${b}px;`);if(t.marker===3||t.marker===2)(Z=t.icon)!=null&&Z.class?(I.classList.add((re=t.icon)==null?void 0:re.class),I.id=(ne=t.icon)==null?void 0:ne.id):(ae=t.icon)!=null&&ae.svgPath?I.innerHTML=Da(`${(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,`${(Ne=t.icon)==null?void 0:Ne.color} !important`):(Se=t.icon)!=null&&Se.title&&(I.innerHTML=(ye=t.icon)==null?void 0:ye.title);else if(t.note){let K=t.color;n.isHexColor(K)&&(K=n.hexToRgbChannels(K)),t.marker===4||t.marker===0||t.marker===1?I.innerHTML=Da("","",'<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`):I.innerHTML=Da("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?I.style.setProperty("pointer-events","none"):(I.style.setProperty("pointer-events","all"),I.style.setProperty("cursor","hand"));let D=this;if(t.type!==3&&t.type!==4&&I.addEventListener("click",async function(K){var Re,Ke,ze,Ve,qe;let ie;D.navigator.rights.enableAnnotations?(ie=await((Re=D.navigator.annotationModule)==null?void 0:Re.getAnnotationByID(t.id)),(ze=(Ke=D.navigator.annotationModule)==null?void 0:Ke.api)==null||ze.selectedAnnotation(ie).then(async()=>{})):D.navigator.rights.enableBookmarks&&(ie=await((Ve=D.navigator.bookmarkModule)==null?void 0:Ve.getAnnotationByID(t.id))),Yr.default.log("selected highlight "+ie.id),D.lastSelectedHighlight=ie.id;let be=document.getElementById("highlight-toolbox");if(be)if(be.style.top=K.clientY+(((qe=D.navigator.attributes)==null?void 0:qe.navHeight)??0)+"px",be.style.left=K.clientX+"px",getComputedStyle(be).display==="none"){let Be=function(){var Ht,Dr;D.navigator.rights.enableAnnotations?(Ht=D.navigator.annotationModule)==null||Ht.deleteSelectedHighlight(ie).then(async()=>{Yr.default.log("delete highlight "+ie.id),be.style.display="none",D.selectionMenuClosed()}):D.navigator.rights.enableBookmarks&&((Dr=D.navigator.bookmarkModule)==null||Dr.deleteSelectedHighlight(ie).then(async()=>{Yr.default.log("delete highlight "+ie.id),be.style.display="none",D.selectionMenuClosed()}))};be.style.display="block",D.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),Dr=ut.parentElement;Ht.style.display="unset",Ht.id="cloneDeleteIcon",Ht.addEventListener("click",Be,!1),Dr&&Dr.append(Ht)}}else be.style.display="none",D.selectionMenuClosed(),be.offsetWidth,be.style.display="block";let Ce=Array.from(o.querySelectorAll(`.${jr}`));D.setHighlightAreaStyle(r,Ce,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),(Ee=t.popup)!=null&&Ee.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(I),t.type){case 1:r.getElementById("R2_ID_SEARCH_CONTAINER").append(o);break;case 2:r.getElementById("R2_ID_READALOUD_CONTAINER").append(o);break;case 3:r.getElementById("R2_ID_PAGEBREAK_CONTAINER").append(o);break;case 4:r.getElementById("R2_ID_DEFINITIONS_CONTAINER").append(o);break;default:r.getElementById("R2_ID_HIGHLIGHTS_CONTAINER").append(o);break}return o}addSelectionMenuItem(e){var t,r;(((t=this.properties)==null?void 0:t.selectionMenuItems)??[])&&(((r=this.properties)==null?void 0:r.selectionMenuItems)??[]).push(e)}};var Fw=rt(c1());L();var lD=rt($t());var Jo={className:n=>!0,idName:n=>!0,tagName:n=>!0};var Hw=rt(If()),ei=rt($t());L();var Bw=rt($t());var ja=class{constructor(e,t,r){this.currSeconds=0;this.publication=e,this.properties=t,this.api=r}static async create(e){let t=new this(e.publication,e,e.api);return await t.start(),t}async start(){this.startResearchSession()}async stop(){Bw.default.log("Consumption module stop"),this.endResearchSession()}initialize(e){let t=e.contentWindow;if(t){let r=this;t.onload=function(){r.resetTimer()},t.onmousemove=function(){r.resetTimer()},t.onmousedown=function(){r.resetTimer()},t.ontouchstart=function(){r.resetTimer()},t.onclick=function(){r.resetTimer()},t.onkeypress=function(){r.resetTimer()}}}trackAction(e,t){var r;(r=this.api)==null||r.actionTracked(e,t)}startReadingSession(e){if(this.firstReadingLocator&&this.lastReadingLocator){let t=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,r=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:r,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 r=this;this.readingSessionsInterval=setInterval(function(){r.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 r=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;(e=this.api)==null||e.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(r)),(t=this.api)==null||t.endResearchSession(this.researchSessionId,this.readingSessions,Math.round(r)),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 qa=class n{constructor(e,t,r,i,o,s,l,f){this.hide=Le(document,"#menu-button-hide");this.show=Le(document,"#menu-button-show");this.annotator=e,this.rights=t,this.publication=r,this.headerMenu=f,this.initialAnnotations=i,this.highlighter=s,this.properties=o,this.api=l}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=Le(this.headerMenu,"#container-view-highlights")),this.initialAnnotations){var e=this.initialAnnotations.highlights||null;e&&((t=this.annotator)==null||t.initAnnotations(e))}setTimeout(()=>{var r;(r=this.properties)!=null&&r.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)}hideAnnotationLayer(){let e=this.navigator.iframes[0].contentDocument;if(e){let t=Le(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=Le(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(e){return new Promise(async t=>{await document.fonts.ready,this.rights.enableAnnotations&&setTimeout(()=>{var r;this.drawHighlights(),this.showHighlights(),we((r=e.contentDocument)==null?void 0:r.body,"click",this.click.bind(this))},300),t(null)})}click(e){var t,r,i,o,s,l,f;if(this.activeAnnotationMarkerId){let u=(i=(r=(t=this.highlighter)==null?void 0:t.properties)==null?void 0:r.selectionMenuItems)==null?void 0:i.filter(y=>y.id===this.activeAnnotationMarkerId);if(u&&(u==null?void 0:u.length)>0){let y=Hw.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 c=function(w){try{let A=h.navigator.iframes[0].contentDocument;return A?Cr(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=mo(v,c);if(_.removeAllRanges(),p){let w={rangeInfo:p},A=(l=this.navigator.highlighter)==null?void 0:l.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(E=>{ei.default.log("saved bookmark "+E.id)})}(f=m.getSelection())==null||f.removeAllRanges()}}}}async scrollToHighlight(e){var r;ei.default.log("still need to scroll to "+e);var t=await((r=this.annotator)==null?void 0:r.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),r=await this.addAnnotation(e);return ei.default.log("Highlight deleted "+JSON.stringify(t)),ei.default.log("Highlight added "+JSON.stringify(r)),await this.showHighlights(),await this.drawHighlights(),r}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(r=>r(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,r;(t=this.api)!=null&&t.deleteAnnotation?(r=this.api)==null||r.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 r,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=(r=this.navigator.view)==null?void 0:r.getCurrentPosition(),l=this.navigator.iframes[0].contentDocument;if(l){let f=co(l,"body"),u=e.position?e.position/f.scrollHeight:s,y=(0,Fw.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,r,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 l of s){er.push(l.highlight);let f=l,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,l.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(l.id,this.navigator.iframes[0].contentWindow))+'px;width:20px"></div>',h=document.createElement("div");h.innerHTML=g;let c=h.childNodes[0],p=document.createElement("i");p.innerHTML="sticky_note_2",p.className="material-icons",p.style.color=f.highlight.color,c.appendChild(p),we(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&&((r=this.navigator.iframes[0].contentDocument)==null?void 0:r.readyState)==="complete"){await this.highlighter.destroyHighlights(0);for(let l of s){er.push(l.highlight);let f=l,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,l.highlight),setTimeout(async()=>{var _,v,g;if(((_=f.highlight)==null?void 0:_.marker)===1){let c='<div class="comment" style="top: '+await((v=this.annotator)==null?void 0:v.getAnnotationPosition(l.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=c,p.childNodes[0].innerHTML=mi.note,we(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,r,i,o,s,l;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()&&((r=this.properties)!=null&&r.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())&&((l=this.properties)!=null&&l.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,C;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(jr)[0];let h=parseInt(v.style.height.replace("px","")),c=u.highlight.position,p=e.createElement("div");p.setAttribute("style",`position: absolute;top:${c}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=Da("","",'<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 E=e.createElement("div");E.innerHTML=(b=u.highlight)==null?void 0:b.note,E.setAttribute("style",`height:${h}px;overflow: hidden;padding-left: 5px;`),p.appendChild(E),we(p,"click",k=>{k.preventDefault(),k.stopPropagation(),this.scrollToHighlight(u.highlight.id)}),(C=this.commentGutter)==null||C.appendChild(p)})))}}createTree(e,t,r){if(t){let i=this,o=this.publication.readingOrder;if(o.length){let s=(l,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),c=this.publication.getTOCItemAbsolute(h);_.href=h,_.innerHTML=(c==null?void 0:c.Title)||"",m.appendChild(_)}else v.innerHTML=y.Title||"",v.className="chapter-title",m.appendChild(v);we(_,"click",h=>{h.preventDefault(),h.stopPropagation();let c={href:_.href,locations:{progression:0},type:y.TypeLink,title:_.title};this.navigator.stopReadAloud(),this.navigator.navigate(c)});let g=document.createElement("ol");t.forEach(function(h){var p,w,A,E,b,C,k;let c=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&h.href.endsWith(c)){let R=document.createElement("li");R.className="annotation-item";let B=document.createElement("a");if(B.setAttribute("href",h.href),e===1){B.className="highlight-link";let D=document.createElement("span"),F=document.createElement("span");if(D.className="title",F.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&&F.style.setProperty("border-bottom",`2px solid ${Jt.hexToRgbA(G)}`,"important")}else F.style.setProperty("border-bottom",`2px solid ${(E=h.highlight)==null?void 0:E.color}`,"important");else if(typeof((b=h.highlight)==null?void 0:b.color)=="object"){let G=(C=h.highlight)==null?void 0:C.color;G&&(F.style.backgroundColor=Jt.hexToRgbA(G))}else{let G=(k=h.highlight)==null?void 0:k.color;G&&(F.style.backgroundColor=G)}D.appendChild(F),B.appendChild(D);let z=document.createElement("span"),q=Math.round((h.locations.progression??0)*100)+"% through resource";z.className="subtitle",z.innerHTML=q,B.appendChild(z)}let I=document.createElement("span");if(I.className="timestamp",I.innerHTML=n.readableTimestamp(h.created),B.appendChild(I),we(B,"click",D=>{D.preventDefault(),D.stopPropagation(),i.handleAnnotationLinkClick(D,h)}),R.appendChild(B),i.navigator.sideNavExpanded){let D=document.createElement("button");D.className="delete",D.innerHTML=mi.delete,we(D,"click",F=>{F.preventDefault(),F.stopPropagation(),i.handleAnnotationLinkDeleteClick(e,F,h)}),R.appendChild(D)}g.appendChild(R)}}),g.children.length>0&&(u.appendChild(m),u.appendChild(g)),u.children.length>0&&l.appendChild(u),y.Children&&y.Children.length>0&&s(l,y.Children)}};r.innerHTML="",s(r,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,r){ei.default.log("annotation data locator: ",r),r?e===1&&this.deleteHighlight(r):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,r=(i,o)=>{let s=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),l,f;s&&(l=s.querySelector(`#${o.highlight.id}`)),f=l.getElementsByClassName(jr)[0];let y=parseInt(f.style.top.replace("px","")),m={...o,highlight:{...o.highlight,position:y}};return[...i,m]};return e.reduce(r,[])}reposition(e){let t=this.navigator.iframes[0].contentDocument,r=(i,o,s)=>{let l=e[0],f=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),u,y;f&&(u=f.querySelector(`#${l.highlight.id}`)),y=u.getElementsByClassName(jr)[0];let _=parseInt(y.style.height.replace("px","")),v=o.highlight.position,g=i[s-1]&&i[s-1].highlight.position,c=s===0?0:g+_+0,p=c>v?c: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(r,[])}};L();var d1=rt(c1());var ti=rt($t());var Ga=class n{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(r=>r(t))}constructor(e,t,r,i,o,s,l){this.annotator=e,this.rights=t,this.publication=r,this.headerMenu=l,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=Le(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=Le(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){let r=Le(this.headerMenu,"#menu-button-bookmark");r&&((e=r.parentElement)==null||e.style.removeProperty("display")),r&&we(r,"click",this.saveBookmark.bind(this))}if(this.initialAnnotations){let r=this.initialAnnotations.bookmarks||null;r&&((t=this.annotator)==null||t.initBookmarks(r))}}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,r;if(this.annotator)if((t=this.api)!=null&&t.deleteBookmark){await((r=this.api)==null?void 0:r.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,r,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(),l=(0,d1.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:l,href:o,created:new Date,title:this.navigator.currentChapterLink.title}}else f={id:l,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((r=this.navigator.consumptionModule)==null||r.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 l,f,u,y,m,_,v,g,h,c,p,w,A;let e=this,t=(l=this.navigator.highlighter)==null?void 0:l.visibleTextRects[0],r=this.navigator.iframes[0].contentDocument;if(r){let E=(f=this.navigator.highlighter)==null?void 0:f.dom(r.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&&E.selectNodeContents(t.node),b.addRange(E);let C=kf(E,!1),k=0;for(let R of C){if(!((m=this.navigator.highlighter)!=null&&m.isOutsideViewport(R))){let B=b.focusNode,I=b.focusOffset;b.collapse(b.anchorNode,b.anchorOffset);for(let q=0;q<k;q++)b.modify("move","forward","line");b.extend(B,I);let D=b.focusNode,F=b.focusNode.length;b.collapse(b.anchorNode,b.anchorOffset);let z=F;b.anchorOffset>F?z=F:z=b.anchorOffset+1,b.modify("move","forward","character"),b.modify("move","backward","word"),b.extend(D,z),b.modify("extend","backward","character"),b.modify("extend","forward","word");break}k++}}function i(E){var k;let b={},C=e.navigator.iframes[0].contentDocument;if(C)return Cr(E,(k=e.navigator.highlighter)==null?void 0:k.dom(C.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 E=ji(o,i);if(E===void 0){let C=e.navigator.iframes[0].contentDocument;E=(v=(_=this.navigator.annotationModule)==null?void 0:_.annotator)==null?void 0:v.getTemporarySelectionInfo(C)}let b=e.navigator.iframes[0].contentDocument;if(E&&b){let C=(p=this.navigator.highlighter)==null?void 0:p.createHighlight((g=this.navigator.highlighter)==null?void 0:g.dom(b.body).getWindow(),E,(h=s.highlight)==null?void 0:h.color,!0,2,s.icon,s.popup,(c=s.highlight)==null?void 0:c.style);if((A=(w=this.navigator.iframes[0].contentDocument)==null?void 0:w.getSelection())==null||A.removeAllRanges(),C)return this.saveAnnotation(C[0]).then(k=>{ti.default.log("saved bookmark "+(k==null?void 0:k.id))})}}}async saveAnnotation(e){var r,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=(r=this.navigator.view)==null?void 0:r.getCurrentPosition(),l=this.navigator.iframes[0].contentDocument;if(l){let f=co(l,"body"),u=e.position?e.position/f.scrollHeight:s,y=(0,d1.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(r=>r.highlight.marker===2),e?e.push.apply(e,t):e=t)),this.bookmarksView&&this.createTree(0,e,this.bookmarksView)}async drawBookmarks(){var t,r;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,l=this.navigator.currentChapterLink.href;var e=this.publication.getTOCItem(l);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&&((r=this.navigator.iframes[0].contentDocument)==null?void 0:r.readyState)==="complete"){await this.navigator.highlighter.destroyHighlights(0);for(let o of i){er.push(o.highlight);let s=o,l=this.navigator.currentChapterLink.href,f=this.publication.getTOCItem(l);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(r=>r(null))}createTree(e,t,r){if(t){let i=this,o=this.publication.readingOrder;if(o.length){let s=(l,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),c=this.publication.getTOCItemAbsolute(h);_.href=h,_.innerHTML=(c==null?void 0:c.Title)||"",m.appendChild(_)}else v.innerHTML=y.Title||"",v.className="chapter-title",m.appendChild(v);we(_,"click",h=>{h.preventDefault(),h.stopPropagation();let c={href:_.href,locations:{progression:0},type:y.TypeLink,title:_.title};this.navigator.stopReadAloud(),this.navigator.navigate(c)});let g=document.createElement("ol");t.forEach(function(h){let c=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&h.href.endsWith(c)){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 E=document.createElement("span"),b=Math.round((h.locations.progression??0)*100)+"% through resource";E.className="title",E.innerHTML=b,w.appendChild(E)}let A=document.createElement("span");if(A.className="timestamp",A.innerHTML=n.readableTimestamp(h.created),w.appendChild(A),we(w,"click",E=>{E.preventDefault(),E.stopPropagation(),i.handleAnnotationLinkClick(E,h)}),p.appendChild(w),i.navigator.sideNavExpanded){let E=document.createElement("button");E.className="delete",E.innerHTML=mi.delete,we(E,"click",b=>{b.preventDefault(),b.stopPropagation(),i.handleAnnotationLinkDeleteClick(e,b,h)}),p.appendChild(E)}g.appendChild(p)}}),g.children.length>0&&(u.appendChild(m),u.appendChild(g)),u.children.length>0&&l.appendChild(u),y.Children&&y.Children.length>0&&s(l,y.Children)}};r.innerHTML="",s(r,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,r){ti.default.log("bookmark data locator: ",r),r?e===0&&this.deleteBookmark(r):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 jw=rt(Uw());L();var hn=rt($t()),f1="r2-mo-active",Nr=class Nr{};Nr.COLOR_REF="color",Nr.AUTO_SCROLL_REF="autoscroll",Nr.AUTO_TURN_REF="autoturn",Nr.VOLUME_REF="volume",Nr.RATE_REF="rate",Nr.COLOR_KEY="mediaoverlay-"+Nr.COLOR_REF,Nr.AUTO_SCROLL_KEY="mediaoverlay-"+Nr.AUTO_SCROLL_REF,Nr.AUTO_TURN_KEY="mediaoverlay-"+Nr.AUTO_TURN_REF,Nr.VOLUME_KEY="mediaoverlay-"+Nr.VOLUME_REF,Nr.RATE_KEY="mediaoverlay-"+Nr.RATE_REF;var st=Nr,Nf=class{constructor(e,t,r){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=r,this.initialise(),hn.default.log(this.api)}static create(e){let t=new this(e.store,e.api,e.headerMenu);if(e.initialMediaOverlaySettings){let r=e.initialMediaOverlaySettings;r!=null&&r.color&&(t.color=r.color,hn.default.log(t.color)),r!=null&&r.autoScroll&&(t.autoScroll=r.autoScroll,hn.default.log(t.autoScroll)),r!=null&&r.autoTurn&&(t.autoTurn=r.autoTurn,hn.default.log(t.autoScroll)),r!=null&&r.volume&&(t.volume=r.volume,hn.default.log(t.volume)),r!=null&&r.rate&&(t.rate=r.rate,hn.default.log(t.rate)),r!=null&&r.wait&&(t.wait=r.wait,hn.default.log(t.wait))}return t.initializeSelections(),t}stop(){hn.default.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(st.AUTO_SCROLL_KEY)!=null?this.getProperty(st.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(st.AUTO_TURN_KEY)!=null?this.getProperty(st.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(st.COLOR_KEY)!=null?this.getProperty(st.COLOR_KEY).value:this.color,this.volume=this.getProperty(st.VOLUME_KEY)!=null?this.getProperty(st.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(st.RATE_KEY)!=null?this.getProperty(st.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=Le(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(e){this.headerMenu&&(this.speechAutoTurn=Le(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=Le(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=Le(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=Le(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()),we(Le(e,"ul"),"click",t=>{t.stopPropagation()})}onSettingsChange(e){this.settingsChangeCallback=e}storeProperty(e){this.updateUserSettings(),this.saveProperty(e)}updateUserSettings(){var t,r,i,o,s,l,f;let e={color:(t=this.userProperties.getByRef(st.COLOR_REF))==null?void 0:t.value,autoScroll:(r=this.userProperties.getByRef(st.AUTO_SCROLL_REF))==null?void 0:r.value,autoTurn:(i=this.userProperties.getByRef(st.AUTO_TURN_REF))==null?void 0:i.value,volume:(o=this.userProperties.getByRef(st.VOLUME_REF))==null?void 0:o.value,rate:(s=this.userProperties.getByRef(st.RATE_REF))==null?void 0:s.value};this.applyMediaOverlaySettings(e),(l=this.api)!=null&&l.updateSettings&&((f=this.api)==null||f.updateSettings(e).then(async u=>{hn.default.log("api updated sync settings",u)}))}getMediaOverlaySettings(){let e=new Li;return e.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,st.AUTO_SCROLL_REF,st.AUTO_SCROLL_KEY),e.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,st.AUTO_TURN_REF,st.AUTO_TURN_KEY),e.addStringable(this.color,st.COLOR_REF,st.COLOR_KEY),e.addIncremental(this.volume,.1,1,.1,"",st.VOLUME_REF,st.VOLUME_KEY),e.addIncremental(this.rate,.1,3,.1,"",st.RATE_REF,st.RATE_KEY),e}saveProperty(e){let t=this.store.get(this.MEDIAOVERLAYSETTINGS);if(t){let r=JSON.parse(t);r=r.filter(i=>i.name!==e.name),r.push(e),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(r))}else{let r=[];r.push(e),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(r))}return e}getProperty(e){let t=this.store.get(this.MEDIAOVERLAYSETTINGS);if(t){let r=JSON.parse(t);return r=r.filter(i=>i.name===e),r.length===0?null:r[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(st.COLOR_REF);t&&(t.value=this.color,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoScroll!==void 0){hn.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.autoTurn!==void 0){hn.default.log("autoTurn "+this.autoTurn),this.autoTurn=e.autoTurn;let t=this.userProperties.getByRef(st.AUTO_TURN_REF);t&&(t.value=this.autoTurn,this.saveProperty(t)),this.settingsChangeCallback()}if(e.volume){hn.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()}if(e.rate){hn.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()}}applyMediaOverlaySetting(e,t){if(e===st.COLOR_REF){this.color=t;let r=this.userProperties.getByRef(st.COLOR_REF);r&&(r.value=this.color,this.saveProperty(r)),this.settingsChangeCallback()}else if(e===st.AUTO_SCROLL_REF){this.autoScroll=t;let r=this.userProperties.getByRef(st.AUTO_SCROLL_REF);r&&(r.value=this.autoScroll,this.saveProperty(r)),this.settingsChangeCallback()}else if(e===st.AUTO_TURN_REF){this.autoTurn=t;let r=this.userProperties.getByRef(st.AUTO_TURN_REF);r&&(r.value=this.autoTurn,this.saveProperty(r)),this.settingsChangeCallback()}}increase(e){var t,r;if(e==="mo_volume"){this.userProperties.getByRef(st.VOLUME_REF).increment(),this.volume=(t=this.userProperties.getByRef(st.VOLUME_REF))==null?void 0:t.value;let i=this.userProperties.getByRef(st.VOLUME_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}else if(e==="mo_rate"){this.userProperties.getByRef(st.RATE_REF).increment(),this.rate=(r=this.userProperties.getByRef(st.RATE_REF))==null?void 0:r.value;let i=this.userProperties.getByRef(st.RATE_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}}decrease(e){var t,r;if(e==="mo_volume"){this.userProperties.getByRef(st.VOLUME_REF).decrement(),this.volume=(t=this.userProperties.getByRef(st.VOLUME_REF))==null?void 0:t.value;let i=this.userProperties.getByRef(st.VOLUME_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}else if(e==="mo_rate"){this.userProperties.getByRef(st.RATE_REF).decrement(),this.rate=(r=this.userProperties.getByRef(st.RATE_REF))==null?void 0:r.value;let i=this.userProperties.getByRef(st.RATE_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}}};var Ze=rt($t()),Wa=class{constructor(e,t,r){this.play=Le(document,"#menu-button-play");this.pause=Le(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=r}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,r;let e=this.currentLinks[this.currentLinkIndex];if((t=e==null?void 0:e.Properties)!=null&&t.MediaOverlay){this.ensureOnTimeUpdate(!1,!1);let i=(r=e.Properties)==null?void 0:r.MediaOverlay,s=new URL(i,this.publication.manifestUrl).toString(),l;try{l=await fetch(s,this.navigator.requestConfig)}catch(m){console.error(m,s);return}l.ok||Ze.default.log("BAD RESPONSE?!");let f;try{f=await l.json()}catch(m){console.error(m)}if(!f){Ze.default.log("## moJson"+f);return}e.MediaOverlays=_a(f,jw.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,r){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&&r){o=!1;let u=f.hash.substr(1);for(let y of r)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&&!r?(Ze.default.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),t):void 0}let s=r,l=r;for(let f of t.Children){Ze.default.log("findDepthFirstTextAudioPair() - child"),Ze.default.log(JSON.stringify(f));let u=this.findDepthFirstTextAudioPair(e,f,l);if(u===null&&(Ze.default.log("findDepthFirstTextAudioPair() - child - match null (skip)"),l=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&&!l)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 r=!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),r=!0)}r?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,r,i){if(!e.Children||!e.Children.length){if((r==null?void 0:r.prev)===t)return Ze.default.log("findNextTextAudioPair() - prevMo === moToMatch"),e;Ze.default.log("findNextTextAudioPair() - set previous"),Ze.default.log(JSON.stringify(e)),r.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,r,i);if(s)return Ze.default.log("findNextTextAudioPair() - match"),Ze.default.log(JSON.stringify(s)),s}}async playMediaOverlaysAudio(e,t,r){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 l=s.toString(),f=typeof t<"u",u=typeof r<"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=r;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 c=function(){h.settings.resourceReady?setTimeout(async()=>{await h.audioElement.play(),h.ensureOnTimeUpdate(!1,!0)},h.settings.wait*1e3):setTimeout(c,200)},h=this;c()}};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||l!==this.currentAudioUrl){this.currentAudioUrl=l,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,r){Ze.default.log("playMediaOverlays()");let i=r?r.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 l,f,u,y,m,_,v,g,h;Ze.default.log("moHighlight: ## "+e);let t=(f=(l=this.publication.Metadata)==null?void 0:l.MediaOverlay)==null?void 0:f.ActiveClass;t||(t=this.settings.color);let r=(u=this.navigator.iframes[0].contentDocument)==null?void 0:u.documentElement.getAttribute("style"),i=r?r.indexOf("readium-night-on")>0:!1,o=r?r.indexOf("readium-sepia-on")>0:!1;if((((y=this.publication.Metadata.Rendition)==null?void 0:y.Layout)??"unknown")!=="fixed"&&(t=i||o?f1:t||f1),this.pid){let c;this.currentLinkIndex===0?c=(m=this.navigator.iframes[0].contentDocument)==null?void 0:m.getElementById(this.pid):c=(_=this.navigator.iframes[1].contentDocument)==null?void 0:_.getElementById(this.pid),c&&c.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 h1=rt($t()),za=class{static async create(e){let t=new this(e.publication);return await t.start(),t}constructor(e){this.publication=e}async stop(){h1.default.log("Timeline module stop")}async start(){this.timelineContainer=Le(document,"#container-view-timeline"),this.positionSlider=Le(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 r;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=""),(r=this.publication.readingOrder)==null||r.forEach(i=>{var _,v;let o=this.publication.getAbsoluteHref(i.Href),s=this.publication.getTOCItemAbsolute(o),l=(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(l??"");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)}we(y,"click",g=>{g.preventDefault(),g.stopPropagation();var h;this.publication.positions||this.navigator.rights.autoGeneratePositions&&this.publication.positions?(h={...this.publication.positions.filter(c=>c.href===i.Href)[0]},h.href=this.publication.getAbsoluteHref(h.href)):h={href:f,locations:{progression:0},type:i.TypeLink,title:i.Title},h1.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 X1=rt(Vo());L();var qw=rt($t());function Gw(n,e){return new Promise(function(t){setTimeout(t.bind(null,e),n)})}var hD=!1;qw.default.setLevel(hD?"trace":"warn",!0);var fh=rt(Ww()),Br=rt($t());L();var oE=rt(I8(),1),bi=rt(YA(),1);L();var XA=[{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 V1(n){return typeof n=="number"?n:n.length===1?n[0]:[n[0],n[n.length-1]]}var fr;(function(n){n[n.Major=0]="Major",n[n.Minor=1]="Minor",n[n.Patch=2]="Patch"})(fr||(fr={}));function QA(n){let e=Array.isArray(n)?n:n.toString().split(".");if(e[0]==="all")return[1/0,0,0];let t=null,r=null,i=[0,0,0];for(let o=0;o<3;o++)if(t=e[o],!(typeof t>"u")){if(r=typeof t=="number"?t:parseInt(t,10),isNaN(r))return null;i[o]=r}return i}function rU(n,e){let t=0,r=[];for(let i=2;i>=0;i--)if(n[i]!==e[i]){t=i;break}for(let i=n[t],o=e[t];i<=o;i++)r.push(n.map((s,l)=>l===t?i:s));return r}function ZA(n,e,t){let[r,i,o]=n,[s,l,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<l?!1:r>=s:v&&o!==f||_&&i!==l?!1:r===s}function nU(n,e){let{ignoreMinor:t,ignorePatch:r,allowZeroSubversions:i}=e,o=t?1:r?2:3;if(i)for(let s=o-1;s>0&&!(n[s]!==0||o===1);s--)o--;return o}function iU(n){return n.reduce((e,t)=>{let[r,i,o]=t.split(/ |-/),s=QA(i);return(s?o?rU(s,QA(o)):[s]:[]).reduce((f,u)=>(u&&f.push({family:r,version:u}),f),e)},[])}function oU(n={}){let{browsers:e,...t}=n,r=(0,oE.default)(e,t);return iU(r)}function sU(n,e,t=0){let r=n.length;for(let i=t;i<r;i++)if(n[i]!==e[i])return!1;return!0}function sE(n){if(n===null||typeof n!="object")return n;let e=Array.isArray(n)?[]:{},t;for(t in n)e[t]=sE(n[t]);return e}function ch(n){return[].concat(...n)}function aU(n){let e=new Map;return n.forEach(({family:t,version:r})=>{let i=e.get(t);if(i){let o=r.join(".");i.every(s=>s.join(".")!==o)&&i.push(r);return}e.set(t,[r])}),e.forEach(t=>{t.sort((r,i)=>{for(let o in r)if(r[o]!==i[o])return r[o]-i[o];return 0})}),e}function uU(n){if(n.length<2)return n;let e=n.length+1,t=[],r=null,i=n[0],o=[i[fr.Major]],s=[i[fr.Minor]],l=[i[fr.Patch]],f=null;for(let u=1;u<e;u++){r=n[u-1],i=n[u]||[];for(let y=fr.Major;y<=fr.Patch;y++){if((y===f||f===null)&&r[y]+1===i[y]&&sU(r,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?l.push(i[fr.Patch]):l=i[fr.Patch];break}if(f===y||r[y]!==i[y]){t.push([V1(o),V1(s),V1(l)]),o=[i[fr.Major]],s=[i[fr.Minor]],l=[i[fr.Patch]],f=null;break}}}return t}function lU(n){return{type:"RegExp",body:n,flags:""}}function Ao(...n){let e=ch(n).filter(Boolean);return e.length===1?e[0]:{type:"Alternative",expressions:e}}function ri(n){return{type:"Char",kind:"simple",value:String(n),codePoint:NaN}}function cU(n){return{type:"Char",kind:"meta",value:n,codePoint:NaN}}function aE(n,e){return{type:"ClassRange",from:n,to:e}}function $1(...n){return{type:"CharacterClass",expressions:ch(n).filter(Boolean)}}function dU(n){return{type:"Quantifier",kind:n,greedy:!0}}function fU(n,e){return{type:"Quantifier",kind:"Range",from:n,to:e,greedy:!0}}function uE(n){return{type:"Group",capturing:!0,expression:n,number:null}}function hU(n,e){return{type:"Repetition",expression:n,quantifier:e}}function pU(...n){let e=ch(n).filter(Boolean);if(e.length===1)return e[0];let t={type:"Disjunction",left:null,right:e.pop()};return e.reduceRight((r,i,o)=>o===0?(r.left=i,r):(r.left={type:"Disjunction",left:null,right:i},r.left),t),t}function dh(...n){let e=pU(...n);return e.type==="Disjunction"?uE(e):e}function ru(){return cU("\\d")}function tu(n=dU("+")){return hU(ru(),n)}function eE(n){return Ao(Array.from(String(n),ri))}function lh(n){if(n.type==="Group"&&n.expression.type==="Repetition"){let{expression:e,quantifier:t}=n.expression;return e.type==="Char"&&e.value==="\\d"&&t.kind==="+"&&t.greedy}return!1}function eu(n,e){return n&&n.type==="Char"?typeof e>"u"||e instanceof RegExp&&e.test(n.value)||String(e)===n.value:!1}function tE(n){if(n.type==="CharacterClass"&&n.expressions.length===1){let[e]=n.expressions;return e.type==="ClassRange"&&eu(e.from,/\d/)&&eu(e.to,/\d/)}return!1}function rE(n){return n.type!=="RegExp"&&n.type!=="ClassRange"&&n.type!=="Quantifier"}function nu(n){return typeof n=="string"?bi.default.parse(n.replace(/^([^/])/,"/$1").replace(/([^/])$/,"$1/")):n instanceof RegExp?bi.default.parse(n):n}function gU(n){return typeof n=="string"?new RegExp(n):new RegExp(bi.default.generate(n.body),n.flags)}function mU(n){return typeof n=="string"?n:n instanceof RegExp?n.toString():bi.default.generate(n)}var yU=["RegExp","Disjunction","Alternative","Assertion","Char","CharacterClass","ClassRange","Backreference","Group","Repetition","Quantifier"];function Y1(n){let{every:e}=n;return e?typeof e=="function"?{"*":e,...n}:yU.reduce((t,r)=>{let i=n[r],o=i?"pre"in i?i.pre:i:null,s=i&&"post"in i?i.post:null;return t[r]={pre(l){return e.pre(l)!==!1&&o?o(l):!0},post(l){return e.post(l)!==!1&&s?s(l):!0}},t},{}):n}function bU(n){let e=bi.default.optimize(nu(mU(n))).getAST();return bi.default.traverse(e,{Group(t){let{parent:r,node:i}=t,{expression:o}=i;i.capturing=!0,(r.type==="RegExp"||o.type!=="Disjunction"&&r.type!=="Repetition"||o.type==="Disjunction"&&r.type==="Disjunction")&&t.replace(t.node.expression)}}),e}function vU(n,e){return eu(n)&&eu(e)&&n.value===e.value?e:eu(n,/\d/)&&tE(e)&&Number(e.expressions[0].from.value)-Number(n.value)===1?{...e,expressions:[{...e.expressions[0],from:n}]}:tE(n)&&eu(e,/\d/)&&Number(e.value)-Number(n.expressions[0].to.value)===1?{...n,expressions:[{...n.expressions[0],to:e}]}:null}function _U(n){return n.reduce((e,t)=>{let r=e[e.length-1];if(r&&t.type==="Alternative"&&r.type==="Alternative"&&t.expressions.length===r.expressions.length){let i=r.expressions.reduceRight((o,s,l)=>{if(!o)return o;let f=vU(s,t.expressions[l]);if(f)o.unshift(f);else return null;return o},[]);i&&(t.expressions=i,e.pop())}return e.push(t),e},[])}function J1(n){return Array.from(n.toString(),Number)}function nE(n,e){let t=n+ +!e;return t===0?ru():t===9?ri("9"):t>9?null:$1(aE(ri(t),ri("9")))}function wU(n){if(n===0)return[tu()];let e=J1(n),t=e.length,r=tu(fU(t+1)),i=t-1;if(n/Math.pow(10,i)===e[0])return[Ao(nE(e[0],!0),Array.from({length:i},ru)),r];let s=e.reduce((l,f,u)=>{let y=t-u-1,m=u===0,_=ri(""),v=e.reduce((g,h,c)=>{if(c<y)g.push(ri(h));else if(_)if(c>y)g.push(ru());else if(_=nE(h,m),_)g.push(_);else return[];return g},[]);return v.length&&l.push(v),l},[]).map(l=>Ao(l));return s.push(r),s}function Za(n,e,t){if(e<n)return null;let r=ri(n),i=ri(e),o=typeof t=="number"&&t>0?Array.from({length:t},()=>ri(0)):[],s=o.length?l=>Ao(o,l):l=>l;return n===e?s(r):n===0&&e===9?s(ru()):e-n===1?s($1(r,i)):s($1(aE(r,i)))}function SU(n,e){let t=[],r=n,i=1;do i*=10,r<i&&(t.push([r,Math.min(i-1,e)]),r=i);while(i<=e);return t}function AU(n,e){let t=n.length;if(t!==e.length||n[0]!==e[0])return null;let r=n[0].toString(),i=0,o=0,s="",l="";for(let f=1;f<t;f++)i=n[f],o=e[f],i===o?r+=i:(s+=i,l+=o);return[r,parseInt(s,10),parseInt(l,10)]}function K1(n,e,t=0){let r=J1(n),i=r.length;if(n<10&&e<10||n===e){let y=t-i;return[Za(n,e,y)]}let o=J1(e);if(i!==o.length){let y=SU(n,e);return ch(y.map(([_,v])=>K1(_,v,t)))}let s=AU(r,o);if(Array.isArray(s)){let[y,m,_]=s,v=i-y.length,g=K1(m,_,v);return[Ao(Array.from(y,ri),dh(g))]}let l=Array.from({length:i-1}),f=Za(r[0]+1,o[0]-1),u=[...l.map((y,m)=>{let _=i-m-1,v=+(m>0);return Ao(r.map((g,h)=>h<_?ri(g):h>_?Za(0,9):Za(g+v,9)))}),...f?[Ao(f,Array.from({length:i-1},()=>ru()))]:[],...l.map((y,m)=>{let _=i-m-1,v=+(m>0);return Ao(o.map((g,h)=>h<_?ri(g):h>_?Za(0,9):Za(0,g-v)))})];return _U(u)}function iE(n,e=1/0){if(n===1/0)return tu();let t=e===1/0?wU(n):K1(n,e);return dh(t)}function EU(n,e,t,r){let i={...r,allowHigherVersions:!0},o=f=>ZA(f,n,i),s=f=>ZA(e,f,i),l=n&&e?f=>o(f)&&s(f):n?o:e?s:()=>!0;return t.filter(l)}function CU(n,e,t=XA){let r=[],i="",o=!1;return t.forEach(s=>{let l=n.get(s.family);if(!l)return;let{version:f,minVersion:u,maxVersion:y}=s;f&&(u=f,y=f);let m=EU(u,y,l,e);m.length&&(i===s.family&&o&&(f=void 0,u=void 0,y=void 0,m=l,r.pop()),r.push({...s,version:f,minVersion:u,maxVersion:y,requestVersions:l,matchedVersions:m})),o=!f&&!u&&!y,i=s.family}),r}function xU(n){let e=n.map(({regexAst:r})=>uE(r.body)),t=bU(lU(dh(e)));return gU(t)}function TU(n){let e=nu(n),t=0;return bi.default.traverse(e,{Group(r){lh(r.node)&&t++}}),t}function PU(n,e,t){let r=nu(n),i=typeof t=="number"&&t<e.length?e.slice(0,t):e.slice();return bi.default.traverse(r,Y1({every(){return!!i.length},Group(o){return lh(o.node)&&i.length?(r===o.node?r=i.shift():o.replace(i.shift()),!1):!0}})),r}function lE(n,e){let t=nu(n),r=Math.min(TU(t),e||1/0),i=[],o=0,s=!1;return bi.default.traverse(t,Y1({every:{pre({node:l,parent:f}){return l===t?!0:rE(l)?(f===t&&(s=!1),o<r):!1},post({node:l,parent:f}){l!==t&&f===t&&rE(l)&&(s||o>0&&o<r)&&i.push(l)}},Group(l){return lh(l.node)&&o<r?(s=!0,o++,!1):!0}})),i.length===1&&!lh(i[0])?lE(i[0],r):i}function OU(n,e){let{ignoreMinor:t,ignorePatch:r,allowHigherVersions:i}=e,o=n[0]===1/0?0:t?1:r?2:3;if(i){let l=[],f=!0,u=0,y=0,m=_=>(v,g)=>g>=o?tu():(y=Array.isArray(v)?v[0]:v,g<_?eE(y):g>_?tu():iE(y+u));for(let _=o-1;_>=0;_--)f&&!n[_]||(f=!1,l.push(n.map(m(_))),u=1);return l}return[n.map((l,f)=>f>=o?tu():Array.isArray(l)?iE(l[0],l[1]):eE(l))]}function MU(n,e,t){let{allowHigherVersions:r}=t,i=nu(n),o=r&&e.length?[e[0]]:e,s=o.reduce((u,y)=>Math.max(u,nU(y,t)),1),l=lE(i,s),f=dh(...o.map(u=>OU(u,t).map(y=>PU(Ao(sE(l)),y,s))));return bi.default.traverse(i,Y1({every(u){return l.length?(u.node===l[0]&&(l.length===1?u.replace(f):u.remove(),l.shift()),!0):!1}})),i}function kU(n,e){return n.map(({regex:t,version:r,maxVersion:i,matchedVersions:o,...s})=>{let l=nu(t);return r||(l=MU(l,uU(o),{...e,allowHigherVersions:!i&&e.allowHigherVersions})),{regex:null,sourceRegex:t,regexAst:l,version:r,maxVersion:i,matchedVersions:o,...s}})}var RU={ignoreMinor:!1,ignorePatch:!0,allowZeroSubversions:!1,allowHigherVersions:!1};function LU(n={}){let e={...RU,...n},t=oU(e),r=aU(t),i=CU(r,e);return kU(i,e)}function cE(n={}){return xU(LU(n))}var Bs=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,fh.addListener)(r=>{var i;r&&(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,fh.launch)(),await Gw(e.detectInspectInitDelay??100)}static isCurrentBrowserSupported(e){if(!e.enforceSupportedBrowsers)return!0;let t=[];return(e.supportedBrowsers??[]).forEach(i=>{t.push("last 1 "+i+" version")}),cE({browsers:t,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){var t;if((t=this.properties)!=null&&t.enableObfuscation){this.wrapper=yt(document,"#iframe-wrapper"),this.securityContainer=Le(document,"#container-view-security");var e=this;this.mutationObserver=new MutationObserver(function(r){r.forEach(function(i){Br.default.log(i.type),e.isHacked=!0})})}}async stop(){var e,t,r,i,o,s,l,f;if(Br.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((r=this.properties)!=null&&r.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)}(l=this.properties)!=null&&l.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 r=co(t.contentDocument,"body");this.rects=this.findRects(r),this.rects.forEach(i=>this.toggleRect(i,this.securityContainer,this.isHacked))}}}setupEvents(){var e,t,r,i,o,s,l,f,u,y,m,_,v,g,h;if((e=this.properties)!=null&&e.disableKeys){we(this.navigator.mainElement,"keydown",this.disableSave),we(this.navigator.headerMenu,"keydown",this.disableSave);for(let c of this.navigator.iframes)we(c,"keydown",this.disableSave),we(c.ownerDocument,"keydown",this.disableSave),we(c.contentDocument,"keydown",this.disableSave),we(c.contentWindow,"keydown",this.disableSave),we((t=c.contentWindow)==null?void 0:t.document,"keydown",this.disableSave);we(window,"keydown",this.disableSave),we(document,"keydown",this.disableSave)}if((r=this.properties)!=null&&r.disableCopy){we(this.navigator.mainElement,"copy",this.preventCopy),we(this.navigator.headerMenu,"copy",this.preventCopy);for(let c of this.navigator.iframes)we(c,"copy",this.preventCopy),we(c.ownerDocument,"copy",this.preventCopy),we(c.contentDocument,"copy",this.preventCopy),we(c.contentWindow,"copy",this.preventCopy),we((i=c.contentWindow)==null?void 0:i.document,"copy",this.preventCopy);we(window,"copy",this.preventCopy),we(document,"copy",this.preventCopy),we(this.navigator.mainElement,"cut",this.preventCopy),we(this.navigator.headerMenu,"cut",this.preventCopy);for(let c of this.navigator.iframes)we(c,"cut",this.preventCopy),we(c.ownerDocument,"cut",this.preventCopy),we(c.contentDocument,"cut",this.preventCopy),we(c.contentWindow,"cut",this.preventCopy),we((o=c.contentWindow)==null?void 0:o.document,"cut",this.preventCopy);we(window,"cut",this.preventCopy),we(document,"cut",this.preventCopy),we(this.navigator.mainElement,"keydown",this.preventCopyKey),we(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let c of this.navigator.iframes)we(c,"keydown",this.preventCopyKey),we(c.ownerDocument,"keydown",this.preventCopyKey),we(c.contentDocument,"keydown",this.preventCopyKey),we(c.contentWindow,"keydown",this.preventCopyKey),we((s=c.contentWindow)==null?void 0:s.document,"keydown",this.preventCopyKey);we(window,"keydown",this.preventCopyKey),we(document,"keydown",this.preventCopyKey)}else if((l=this.properties)!=null&&l.canCopy){we(this.navigator.mainElement,"copy",this.restrictCopy.bind(this)),we(this.navigator.headerMenu,"copy",this.restrictCopy.bind(this));for(let c of this.navigator.iframes)we(c,"copy",this.restrictCopy),we(c.ownerDocument,"copy",this.restrictCopy.bind(this)),we(c.contentDocument,"copy",this.restrictCopy.bind(this)),we(c.contentWindow,"copy",this.restrictCopy.bind(this)),we((f=c.contentWindow)==null?void 0:f.document,"copy",this.restrictCopy.bind(this));we(window,"copy",this.restrictCopy.bind(this)),we(document,"copy",this.restrictCopy.bind(this)),we(this.navigator.mainElement,"cut",this.restrictCopy.bind(this)),we(this.navigator.headerMenu,"cut",this.restrictCopy.bind(this));for(let c of this.navigator.iframes)we(c,"cut",this.restrictCopy.bind(this)),we(c.ownerDocument,"cut",this.restrictCopy.bind(this)),we(c.contentDocument,"cut",this.restrictCopy.bind(this)),we(c.contentWindow,"cut",this.restrictCopy.bind(this)),we((u=c.contentWindow)==null?void 0:u.document,"cut",this.restrictCopy.bind(this));we(window,"cut",this.restrictCopy.bind(this)),we(document,"cut",this.restrictCopy.bind(this)),we(this.navigator.mainElement,"keydown",this.restrictCopyKey.bind(this)),we(this.navigator.headerMenu,"keydown",this.restrictCopyKey.bind(this));for(let c of this.navigator.iframes)we(c,"keydown",this.restrictCopyKey.bind(this)),we(c.ownerDocument,"keydown",this.restrictCopyKey.bind(this)),we(c.contentDocument,"keydown",this.restrictCopyKey.bind(this)),we(c.contentWindow,"keydown",this.restrictCopyKey.bind(this)),we((y=c.contentWindow)==null?void 0:y.document,"keydown",this.restrictCopyKey.bind(this));we(window,"keydown",this.restrictCopyKey.bind(this)),we(document,"keydown",this.restrictCopyKey.bind(this))}if((m=this.properties)!=null&&m.disablePrint){we(this.navigator.mainElement,"beforeprint",this.beforePrint),we(this.navigator.headerMenu,"beforeprint",this.beforePrint);for(let c of this.navigator.iframes)we(c,"beforeprint",this.beforePrint.bind(this)),we(c.ownerDocument,"beforeprint",this.beforePrint.bind(this)),we(c.contentDocument,"beforeprint",this.beforePrint.bind(this)),we(c.contentWindow,"beforeprint",this.beforePrint.bind(this)),we((_=c.contentWindow)==null?void 0:_.document,"beforeprint",this.beforePrint.bind(this));we(window,"beforeprint",this.beforePrint.bind(this)),we(document,"beforeprint",this.beforePrint.bind(this)),we(this.navigator.mainElement,"afterprint",this.afterPrint),we(this.navigator.headerMenu,"afterprint",this.afterPrint);for(let c of this.navigator.iframes)we(c,"afterprint",this.afterPrint.bind(this)),we(c.ownerDocument,"afterprint",this.afterPrint.bind(this)),we(c.contentDocument,"afterprint",this.afterPrint.bind(this)),we(c.contentWindow,"afterprint",this.afterPrint.bind(this)),we((v=c.contentWindow)==null?void 0:v.document,"afterprint",this.afterPrint.bind(this));we(window,"afterprint",this.afterPrint.bind(this)),we(document,"afterprint",this.afterPrint.bind(this))}if((g=this.properties)!=null&&g.disableContextMenu){we(this.navigator.mainElement,"contextmenu",this.disableContext),we(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let c of this.navigator.iframes)we(c,"contextmenu",this.disableContext),we(c.ownerDocument,"contextmenu",this.disableContext),we(c.contentDocument,"contextmenu",this.disableContext),we(c.contentWindow,"contextmenu",this.disableContext),we((h=c.contentWindow)==null?void 0:h.document,"contextmenu",this.disableContext);we(window,"contextmenu",this.disableContext),we(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(e){var t;if((t=this.properties)!=null&&t.enableObfuscation)return new Promise(async r=>{if(await document.fonts.ready,e.contentDocument){let i=co(e.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,we(this.wrapper,"scroll",this.handleScroll.bind(this))),r()},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,X1.default)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(r=>this.toggleRect(r,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 Br.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 r,i,o,s;if(this.citation)return;Br.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},_=l.navigator.iframes[0].contentDocument;if(_)return Cr(y,_,m)},l=this,u=ji(t,f);if(u===void 0){let y=this.navigator.iframes[0].contentDocument;u=(i=(r=this.navigator.annotationModule)==null?void 0:r.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,r,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},_=l.navigator.iframes[0].contentDocument;if(_)return Cr(y,_,m)},l=this,u=ji(s,f);if(u===void 0){let y=this.navigator.iframes[0].contentDocument;u=(r=(t=this.navigator.annotationModule)==null?void 0:t.annotator)==null?void 0:r.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 r=this.createElementForExecCommand(e);this.selectContent(r);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),document.execCommand("copy",!1)}catch{}document.body.removeChild(r)}}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 r=window.getSelection();r==null||r.removeAllRanges(),r==null||r.addRange(t)}beforePrint(e){return Br.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 Br.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 r;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=(r=i.contentDocument)==null?void 0:r.querySelectorAll("a");o==null||o.forEach(s=>{let l=s.getAttribute("data-href"),f=s.getAttribute("href");!l&&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 l=s.getAttribute("data-href");l&&s.setAttribute("href",l),s.removeEventListener("click",t)})}}preventDrag(e){var i,o,s,l,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;",r=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",r),(s=u.contentDocument)==null||s.body.setAttribute("style",y+t)):((l=u.contentDocument)==null||l.body.removeEventListener("dragstart",r),(f=u.contentDocument)==null||f.body.setAttribute("style",y.replace(t,"")))}}recalculate(e=0){return new Promise(t=>{var r;if((r=this.properties)!=null&&r.enableObfuscation){let i=(0,X1.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:r,height:i,left:o,width:s}=this.measureTextNode(t.node);t.top=r,t.height=i,t.width=s,t.left=o}catch(r){Br.default.log("error "+r),Br.default.log(t),Br.default.log(t.node),Br.default.log("scrambledTextContent "+t.scrambledTextContent),Br.default.log("textContent "+t.textContent),Br.default.log("isObfuscated "+t.isObfuscated)}})}deactivateRect(e,t,r){this.isBeingHacked(t)||r?(e.node.textContent=e.scrambledTextContent,e.isObfuscated=!0):(e.node.textContent=e.textContent,e.isObfuscated=!1)}toggleRect(e,t,r){let i=this.isOutsideViewport(e),o=this.isBeingHacked(t);e.isObfuscated&&!i&&!o&&!r&&(e.node.textContent=e.textContent,e.isObfuscated=!1),!e.isObfuscated&&(i||o||r)&&(e.node.textContent=e.scrambledTextContent,e.isObfuscated=!0)}findRects(e){return this.findTextNodes(e).map(r=>{var y,m,_,v;let{top:i,height:o,left:s,width:l}=this.measureTextNode(r),f=r.parentElement&&((y=this.properties)!=null&&y.excludeNodes&&((m=this.properties)==null?void 0:m.excludeNodes.indexOf(r.parentElement.nodeName.toLowerCase()))>-1||((_=r.parentElement)==null?void 0:_.nodeName.toLowerCase())==="option"||((v=r.parentElement)==null?void 0:v.nodeName.toLowerCase())==="script")?r.textContent:this.obfuscateText(r.textContent??"");return{top:i,height:o,width:l,left:s,node:r,textContent:r.textContent??"",scrambledTextContent:f??"",isObfuscated:!1}})}obfuscateText(e){return this.scramble(e,!0)}measureTextNode(e){try{let t=document.createRange();t.selectNode(e);let r=t.getBoundingClientRect();return t.detach(),r}catch(t){Br.default.log("measureTextNode "+t),Br.default.log("measureTextNode "+e),Br.default.log(e.textContent)}}isBeingHacked(e){return e.style.animation||e.style.transition||e.style.position||e.hasAttribute("style")?(Br.default.log("content being hacked"),!0):!1}isOutsideViewport(e){let t=this.wrapper.scrollLeft,r=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),l=s+this.wrapper.clientHeight+(e.node.parentElement?parseInt(getComputedStyle(e.node.parentElement).lineHeight.replace("px","")):10),f=o<s,u=e.top>l,y=i<t-window.innerWidth,m=e.left>r+window.innerWidth;return f||u||y||m}findTextNodes(e,t=[]){var i;let r=e.firstChild;for(;r;)r.nodeType===1&&this.findTextNodes(r,t),r.nodeType===3&&(i=r.textContent)!=null&&i.trim()&&t.push(r),r=r.nextSibling;return t}scramble(e,t=!1,r=!1){var i=e.split(" ");function o(s){for(var l=s.length,f,u;l>0;)u=Math.floor(Math.random()*l),l--,f=s[l],s[l]=s[u],s[u]=f;return s}return t&&(i=i.map(function(s){return s.includes("-")?s:o(s.split("")).join("")})),r?o(i).join(" "):i.join(" ")}};L();var mE=rt(fE());L();var hh=n=>n.replace(/\n/g," ").replace(/\s\s+/g," "),IU=n=>hh(n).trim(),pE=/[\\^$.*+?()[\]{}|]/g,NU=RegExp(pE.source);function hE(n){return n&&NU.test(n)?n.replace(pE,"\\$&"):n||""}var ph=0,BU=()=>()=>Number.isSafeInteger(++ph)?ph:ph=1,gE=()=>{ph=0},DU=BU(),FU=n=>e=>{try{return Cr(e,n,Jo)}catch(t){return console.error("uniqueCssSelector:",t),""}};async function ts(n,e,t,r,i=!1){var v,g,h;if(!e)return[];let o=(v=e.body)==null?void 0:v.textContent;if(!o)return[];if(n=IU(n),!n.length)return[];let s=e.createNodeIterator(e.body,NodeFilter.SHOW_TEXT,{acceptNode:c=>NodeFilter.FILTER_ACCEPT}),l=new RegExp(hE(n).replace(/ /g,"\\s+"),"gim");i&&(l=new RegExp("\\b"+hE(n).replace(/ /g,"\\s+")+"\\b","gim"));let f=[],u=100,y=30,m=0,_;for(;_=l.exec(o);){let c=Math.max(0,_.index-u),p=Math.min(u,_.index),w=hh(o.substr(c,p));w=w.substr(w.length-y),c=l.lastIndex,p=Math.min(u,o.length-c);let A=hh(o.substr(c,p)).substr(0,y),E=new Range,b=_.index;for(;m<=b;){let R=s.nextNode();R&&R.nodeValue&&(m+=R.nodeValue.length)}let C=s.referenceNode.nodeValue?((g=s.referenceNode.nodeValue)==null?void 0:g.length)-(m-b):0;for(E.setStart(s.referenceNode,C),b=_.index+_[0].length;m<=b;){let R=s.nextNode(),B=R==null?void 0:R.nodeValue;B&&(m+=B.length)}C=s.referenceNode.nodeValue?((h=s.referenceNode.nodeValue)==null?void 0:h.length)-(m-b):0,E.setEnd(s.referenceNode,C),e.getCssSelector||(e.getCssSelector=FU(e));let k=mo(E,e.getCssSelector);k&&f.push({textMatch:hh(_[0]),textBefore:w,textAfter:A,rangeInfo:k,href:t,title:r,uuid:DU().toString()})}return f}var yE=rt($t()),iu=class{constructor(e,t,r,i,o){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.headerMenu=o,this.publication=e,this.properties=t,this.api=i,this.highlighter=r}static async create(e){let t=new this(e.publication,e,e.highlighter,e.api,e.headerMenu);return await t.start(),t}async stop(){yE.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=Le(this.headerMenu,"#searchInput"),we(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=Le(this.headerMenu,"#searchGo"),we(this.searchGo,"click",this.handleSearch.bind(this));var e=Le(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,r=this.searchInput.value;let i=this.navigator.currentChapterLink.href,o=this.publication.getSpineItem(i);if(this.headerMenu)var s=Le(document,"#searchResultChapter");t.currentChapterSearchResult=[],t.currentSearchHighlights=[];var l=[];await this.searchAndPaintChapter(r,e,async u=>{var y;l=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(l,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 c=document.createElement("a"),p=y.data[h];c.className="collection-item",c.href=(o==null?void 0:o.Href)??"",c.innerHTML="..."+p.textBefore+"<mark>"+p.textMatch+"</mark>"+p.textAfter+"...",we(c,"click",w=>{w.preventDefault(),w.stopPropagation(),t.jumpToMark(h+u*10-10)}),s.appendChild(c)}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",we(v,"click",c=>{c.preventDefault(),c.stopPropagation(),f(h)})}_.appendChild(v);for(let h=1;h<=y.total_pages;h++){let c,p=document.createElement("li");p.className="waves-effect",h===y.page&&(p.className="active",c=p),p.innerHTML='<a href="#!">'+h+"</a>",we(p,"click",w=>{w.preventDefault(),w.stopPropagation(),c&&(c.className="waves-effect"),p.className="active",c=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",we(g,"click",c=>{c.preventDefault(),c.stopPropagation(),f(h)})}_.appendChild(g),m.appendChild(_),s.appendChild(m)}}}async searchAndPaintChapter(e,t=0,r){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 l=0;if(o){let y=this.navigator.iframes[0].contentDocument;y&&o&&ts(e,y,o.Href,o.Title).then(m=>{m.forEach(_=>{let v={rangeInfo:_.rangeInfo};setTimeout(()=>{var h,c;let g;l===t?(g=this.createSearchHighlight(v,(h=this.properties)==null?void 0:h.current),this.jumpToMark(t)):g=this.createSearchHighlight(v,(c=this.properties)==null?void 0:c.color),_.highlight=g,s.push(_),this.currentChapterSearchResult.push(_),this.currentSearchHighlights.push(g),l++},500)}),setTimeout(()=>{r(s)},500)})}}createSearchHighlight(e,t){var o;try{var r=t;Jt.isHexColor(r)&&(r=Jt.hexToRgbChannels(r));let s=`${e.rangeInfo.startContainerElementCssSelector}${e.rangeInfo.startContainerChildTextNodeIndex}${e.rangeInfo.startOffset}${e.rangeInfo.endContainerElementCssSelector}${e.rangeInfo.endContainerChildTextNodeIndex}${e.rangeInfo.endOffset}`,f="R2_SEARCH_"+mE.SHA256.hash(s);var i=!1;let u={color:r||Ls,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=[],gE(),await this.searchAndPaintChapter(e,0,async()=>{var r;this.navigator.rights.enableContentProtection&&((r=this.navigator.contentProtectionModule)==null||r.recalculate(200))}),t?(await this.searchBook(e),await this.searchChapter(e)):(await this.searchChapter(e),await this.searchBook(e))}async goToSearchID(e,t,r){var i=t,o;let s=this.navigator.currentChapterLink.href;var l=this.publication.getAbsoluteHref(e);let f=this.bookSearchResult.filter(u=>u.href===e);if(r?(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===l)this.jumpToMark(i);else{let y={href:l,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,r){var i=t,o;let s=this.navigator.currentChapterLink.href;var l=this.publication.getAbsoluteHref(e);let f=this.bookSearchResult.filter(u=>u.href===e);if(r?o=this.currentChapterSearchResult[i]:o=f[i],o!==void 0)if(s===l)this.jumpToMark(i);else{let y={href:l,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 r=Le(document,"#searchResultBook");i(1);async function i(s){r.innerHTML="";var l,f=await e.searchBook(t);if(l=e.paginate(f,s,10),l.total===0){let u=document.createElement("a");u.className="collection-item",u.innerHTML="nothing found",r.appendChild(u)}else{o(l.data,g=>g.href).forEach(g=>{let h=document.createElement("div");if(h.style.marginBottom="10px",g[0].title){let c=document.createElement("span");c.className="collection-item",c.style.display="block",c.innerHTML=g[0].title,h.appendChild(c)}r.appendChild(h),g.forEach(c=>{let p=document.createElement("a");p.className="collection-item";var w=e.publication.getAbsoluteHref(c.href);p.innerHTML="..."+c.textBefore+"<mark>"+c.textMatch+"</mark>"+c.textAfter+"...",we(p,"click",A=>{A.preventDefault(),A.stopPropagation();let b=f.filter(k=>k.href===c.href).findIndex(k=>k===c);if(e.navigator.currentChapterLink.href===w)e.jumpToMark(b);else{let R={href:w,locations:{progression:0},title:"title"};e.navigator.navigate(R),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>',l.pre_page!=null){let g=l.pre_page;_.className="waves-effect",we(_,"click",h=>{h.preventDefault(),h.stopPropagation(),i(g)})}m.appendChild(_);for(let g=1;g<=l.total_pages;g++){let h,c=document.createElement("li");c.className="waves-effect",g===l.page&&(c.className="active",h=c),c.innerHTML='<a href="#!">'+g+"</a>",we(c,"click",p=>{p.preventDefault(),p.stopPropagation(),h&&(h.className="waves-effect"),c.className="active",h=c,i(g)}),m.appendChild(c)}let v=document.createElement("li");if(v.className="disabled",v.innerHTML='<a href="#!"> > </a>',l.next_page!=null){let g=l.next_page;v.className="waves-effect",we(v,"click",h=>{h.preventDefault(),h.stopPropagation(),i(g)})}m.appendChild(v),y.appendChild(m),r.appendChild(y)}}function o(s,l){let f=new Map;return s.forEach(u=>{let y=l(u),m=f.get(y);m?m.push(u):f.set(y,[u])}),Array.from(f.values())}}async searchBook(e){var r,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:""),l=this.publication.getTOCItem(s);if(l===void 0&&this.publication.readingOrder&&(l=this.publication.readingOrder[o]),l){let f=this.publication.getAbsoluteHref(l.Href);(r=this.navigator.api)!=null&&r.getContent?await((i=this.navigator.api)==null?void 0:i.getContent(f).then(u=>{let m=new DOMParser().parseFromString(u,"application/xhtml+xml");l&&ts(e,m,l.Href,l.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");l&&ts(e,m,l.Href,l.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),r=t.length,i=new Uint8Array(r);for(let s=0;s<r;s++)i[s]=t.charCodeAt(s);return new TextDecoder().decode(i)}async searchChapter(e){var o,s;let t=[],r=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),i=this.publication.getTOCItem(r);if(i===null&&(i=this.publication.readingOrder[this.navigator.currentResource()??0]),i){let l=this.publication.getAbsoluteHref(i.Href);(o=this.navigator.api)!=null&&o.getContent?await((s=this.navigator.api)==null?void 0:s.getContent(l).then(f=>{let y=new DOMParser().parseFromString(f,"application/xhtml+xml");i&&ts(e,y,i.Href,i.Title).then(m=>{m.forEach(_=>{t.push(_)})})})):await fetch(l,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&&ts(e,y,i.Href,i.Title).then(_=>{_.forEach(v=>{t.push(v)})})})}return t}drawSearch(){setTimeout(()=>{this.currentSearchHighlights=[],this.currentChapterSearchResult.forEach(e=>{var r,i;let t={rangeInfo:e.rangeInfo};if((r=this.properties)!=null&&r.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(l=>{var u;var f=(u=this.properties)==null?void 0:u.color;Jt.isHexColor(f)&&(f=Jt.hexToRgbChannels(f)),l.color=f});var r=(i=this.properties)==null?void 0:i.current;Jt.isHexColor(r)&&(r=Jt.hexToRgbChannels(r)),t.highlight.color=r,(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,r){let i=t||1,o=r||10,s=(i-1)*o,l=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:l}}};L();var mn=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 at=sr,gh=class{constructor(e,t,r){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=r,this.initialise()}static create(e){let t=new this(e.store,e.api,e.headerMenu);if(e.initialTTSSettings){let r=e.initialTTSSettings;r!=null&&r.rate&&(t.rate=r.rate,mn.default.log(t.rate)),r!=null&&r.pitch&&(t.pitch=r.pitch,mn.default.log(t.pitch)),r!=null&&r.volume&&(t.volume=r.volume,mn.default.log(t.volume)),r!=null&&r.color&&(t.color=r.color,mn.default.log(t.color)),r!=null&&r.autoScroll&&(t.autoScroll=r.autoScroll,mn.default.log(t.autoScroll)),r!=null&&r.voice&&(t.voice=r.voice,mn.default.log(t.voice))}return t.initializeSelections(),t}stop(){mn.default.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty(at.AUTO_SCROLL_KEY)!=null?this.getProperty(at.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty(at.RATE_KEY)!=null?this.getProperty(at.RATE_KEY).value:this.rate,this.pitch=this.getProperty(at.PITCH_KEY)!=null?this.getProperty(at.PITCH_KEY).value:this.pitch,this.volume=this.getProperty(at.VOLUME_KEY)!=null?this.getProperty(at.VOLUME_KEY).value:this.volume,this.color=this.getProperty(at.COLOR_KEY)!=null?this.getProperty(at.COLOR_KEY).value:this.color,this.voice=this.getProperty(at.VOICE_REF)!=null?this.getProperty(at.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=Le(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(e){this.headerMenu&&(this.speechRate=Le(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=Le(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=Le(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=Le(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),we(Le(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,r,i,o,s,l,f,u;var e={rate:(t=this.userProperties.getByRef(at.RATE_REF))==null?void 0:t.value,pitch:(r=this.userProperties.getByRef(at.PITCH_REF))==null?void 0:r.value,volume:(i=this.userProperties.getByRef(at.VOLUME_REF))==null?void 0:i.value,voice:(o=this.userProperties.getByRef(at.VOLUME_REF))==null?void 0:o.value,color:(s=this.userProperties.getByRef(at.COLOR_REF))==null?void 0:s.value,autoScroll:(l=this.userProperties.getByRef(at.AUTO_SCROLL_REF))==null?void 0:l.value};this.applyTTSSettings(e),(f=this.api)!=null&&f.updateSettings&&((u=this.api)==null||u.updateSettings(e).then(async y=>{mn.default.log("api updated tts settings",y)}))}getTTSSettings(){var e=new Li;return e.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,at.AUTO_SCROLL_REF,at.AUTO_SCROLL_KEY),e.addIncremental(this.rate,.1,10,.1,"",at.RATE_REF,at.RATE_KEY),e.addIncremental(this.pitch,.1,2,.1,"",at.PITCH_REF,at.PITCH_KEY),e.addIncremental(this.volume,.1,1,.1,"",at.VOLUME_REF,at.VOLUME_KEY),e.addStringable(this.color,at.COLOR_REF,at.COLOR_KEY),e.addJSONable(JSON.stringify(this.voice),at.VOICE_REF,at.VOICE_KEY),e}saveProperty(e){let t=this.store.get(this.TTSSETTINGS);if(t){let r=JSON.parse(t);r=r.filter(i=>i.name!==e.name),r.push(e),this.store.set(this.TTSSETTINGS,JSON.stringify(r))}else{let r=[];r.push(e),this.store.set(this.TTSSETTINGS,JSON.stringify(r))}return e}getProperty(e){let t=this.store.get(this.TTSSETTINGS);if(t){let r=JSON.parse(t);return r=r.filter(i=>i.name===e),r.length===0?void 0:r[0]}}resetTTSSettings(){this.store.remove(this.TTSSETTINGS),this.reset(),this.settingsChangeCallback(),this.restartCallback()}applyTTSSettings(e){if(e.rate){mn.default.log("rate "+this.rate),this.rate=e.rate;let t=this.userProperties.getByRef(at.RATE_REF);t&&(t.value=this.rate,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.pitch){mn.default.log("pitch "+this.pitch),this.pitch=e.pitch;let t=this.userProperties.getByRef(at.PITCH_REF);t&&(t.value=this.pitch,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.volume){mn.default.log("volume "+this.volume),this.volume=e.volume;let t=this.userProperties.getByRef(at.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(at.COLOR_REF);t&&(t.value=this.color,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoScroll!==void 0){mn.default.log("autoScroll "+this.autoScroll),this.autoScroll=e.autoScroll;let t=this.userProperties.getByRef(at.AUTO_SCROLL_REF);t&&(t.value=this.autoScroll,this.saveProperty(t)),this.settingsChangeCallback()}if(e.voice){mn.default.log("voice "+this.voice),this.voice=e.voice;let t=this.userProperties.getByRef(at.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,r=e.indexOf(":")!==-1?e.slice(e.indexOf(":")+1):e;t!==void 0&&r!==void 0?this.applyTTSSettings({voice:{usePublication:!0,name:t,lang:r}}):r!==void 0&&t===void 0&&this.applyTTSSettings({voice:{usePublication:!0,lang:r}})}increase(e){if(e==="rate"){this.userProperties.getByRef(at.RATE_REF).increment();let t=this.userProperties.getByRef(at.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="pitch"){this.userProperties.getByRef(at.PITCH_REF).increment();let t=this.userProperties.getByRef(at.PITCH_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="volume"){this.userProperties.getByRef(at.VOLUME_REF).increment();let t=this.userProperties.getByRef(at.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}}decrease(e){if(e==="rate"){this.userProperties.getByRef(at.RATE_REF).decrement();let t=this.userProperties.getByRef(at.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="pitch"){this.userProperties.getByRef(at.PITCH_REF).decrement();let t=this.userProperties.getByRef(at.PITCH_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="volume"){this.userProperties.getByRef(at.VOLUME_REF).decrement();let t=this.userProperties.getByRef(at.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}}};L();L();var mh=`${mi.loading}`,bE=`
|
|
82
|
+
</svg>`,mi={error:fn("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:fn("expand-icon","Enter fullscreen",'<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>',"icon active-icon"),loading:XB("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:fn("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:fn("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:fn("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:fn("toc-icon","Table of Contents",'<path d="M3 9h14V7H3v2zm0 4h14v-2H3v2zm0 4h14v-2H3v2zm16 0h2v-2h-2v2zm0-10v2h2V7h-2zm0 6h2v-2h-2v2z"/>',"icon open"),bookmarks:fn("toc-icon","Bookmarks",'<path d="M4,6H2v16h16v-2H4V6z"/><path d="M22,2H6v16h16V2z M20,12l-2.5-1.5L15,12V4h5V12z"/>',"icon open"),bookmark:fn("toc-icon","Bookmark",'<path d="M19,3H5v18l7-3l7,3V3z"/>',"icon open"),delete:fn("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:fn("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:fn("text-icon","Text",'<path d="M5 4v3h5.5v12h3V7H19V4z"/>',"icon open"),speak:fn("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:fn("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:fn("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 e1=rt(If());var Yr=rt($t()),Rs=(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))(Rs||{}),Cw="R2_CLASS_HIGHLIGHT_CONTAINER",Tl="R2_CLASS_HIGHLIGHT_BOUNDING_AREA",jr="R2_CLASS_HIGHLIGHT_AREA",Cl="R2_CLASS_HIGHLIGHT_ICON",qi=.5,Ew=.75,Ls={blue:100,green:50,red:230},er=[],ZB="data-highlighted",eD="data-timestamp",Ha={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",Cw,jr,Tl],Qg=-1,Zg=-1,Jt=class n{constructor(e,t,r,i,o){this.lastSelectedHighlight=void 0;this.activeAnnotationMarkerId=void 0;this.showTool=(0,xl.default)(e=>{this.isAndroid()||this.snapSelectionToWord(e),this.toolboxShow()},navigator.userAgent.toLowerCase().indexOf("firefox")>-1?200:100);this.isSelectionMenuOpen=!1;this.selectionMenuOpened=(0,xl.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,xl.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,xl.default)((e,t)=>{var r,i;(r=this.api)!=null&&r.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=r,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(r=>r(t))}async initialize(e){var o;let t=e.contentDocument;t&&this.dom(t.body).addClass(this.options.contextClass),this.bindEvents((o=e.contentDocument)==null?void 0:o.body,this,this.hasEventListener),this.initializeToolbox(),Qg=-1,Zg=-1;let r=this;async function i(){r.lastSelectedHighlight===void 0||(r.lastSelectedHighlight=void 0)}setTimeout(async()=>{var l;let s=e.contentDocument;s&&await((l=s.body)==null?void 0:l.addEventListener("click",i))},100)}haveSameColor(e,t){return this.dom(e).color()===this.dom(t).color()}defaults(e,t){e=e||{};for(let r in t)t.hasOwnProperty(r)&&e[r]===void 0&&(e[r]=t[r]);return e}unique(e){return e.filter(function(t,r,i){return i.indexOf(t)===r})}refineRangeBoundaries(e){let t=e.startContainer,r=e.endContainer,i=e.commonAncestorContainer,o=!0;if(e.endOffset===0){for(;!r.previousSibling&&r.parentNode!==i;)r=r.parentNode;r=r.previousSibling}else r.nodeType===Ha.TEXT_NODE?e.endOffset<r.nodeValue.length&&r.splitText(e.endOffset):e.endOffset>0&&(r=r.childNodes.item(e.endOffset-1));return t.nodeType===Ha.TEXT_NODE?e.startOffset===t.nodeValue.length?o=!1:e.startOffset>0&&(t=t.splitText(e.startOffset),r===t.previousSibling&&(r=t)):e.startOffset<t.childNodes.length?t=t.childNodes.item(e.startOffset):t=t.nextSibling,{startContainer:t,endContainer:r,goDeeper:o}}sortByDepth(e,t){let r=this;e.sort(function(i,o){return r.dom(t?o:i).parents().length-r.dom(t?i:o).parents().length})}groupHighlights(e){let t=[],r={},i=[];return e.forEach(function(o){let s=o.getAttribute(eD);typeof r[s]>"u"&&(r[s]=[],t.push(s)),r[s].push(o)}),t.forEach(function(o){let s=r[o];i.push({chunks:s,timestamp:o,toString:function(){return s.map(function(l){return l.textContent}).join("")}})}),i}dom(e){let t=this;return{addClass:function(r){e.classList?e.classList.add(r):e.className+=" "+r},removeClass:function(r){e.classList?e.classList.remove(r):e.className=e.className.replace(new RegExp("(^|\\b)"+r+"(\\b|$)","gi")," ")},prepend:function(r){let i=Array.prototype.slice.call(r),o=i.length;for(;o--;)e.insertBefore(i[o],e.firstChild)},append:function(r){let i=Array.prototype.slice.call(r);for(let o=0,s=i.length;o<s;++o)e.appendChild(i[o])},insertAfter:function(r){var i;return(i=r.parentNode)==null?void 0:i.insertBefore(e,r.nextSibling)},insertBefore:function(r){var i;return(i=r.parentNode)==null?void 0:i.insertBefore(e,r)},remove:function(){e.parentNode.removeChild(e),e=null},contains:function(r){return e!==r&&e.contains(r)},wrap:function(r){return e.parentNode&&e.parentNode.insertBefore(r,e),r.appendChild(e),r},unwrap:function(){let r=Array.prototype.slice.call(e.childNodes),i;return r.forEach(function(o){i=o.parentNode,t.dom(o).insertBefore(o.parentNode),t.dom(i).remove()}),r},parents:function(){let r,i=[];for(;r=e.parentNode;)i.push(r),e=r;return i},normalizeTextNodes:function(){if(e){if(e.nodeType===Ha.TEXT_NODE)for(;e.nextSibling&&e.nextSibling.nodeType===Ha.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(r){let i=document.createElement("div");return i.innerHTML=r,i.childNodes},getRange:function(){var o;let r=(o=t.dom(e))==null?void 0:o.getSelection(),i;return(r==null?void 0:r.rangeCount)>0&&(i=r==null?void 0:r.getRangeAt(0)),i},removeAllRanges:function(){var i;let r=(i=t.dom(e))==null?void 0:i.getSelection();r==null||r.removeAllRanges(),t.toolboxHide()},getSelection:function(){var r;return(r=t.dom(e).getWindow())==null?void 0:r.getSelection()},getWindow:function(){var r;return(r=t.dom(e).getDocument())==null?void 0:r.defaultView},getDocument:function(){return(e==null?void 0:e.ownerDocument)||e}}}disableContext(e){return e.preventDefault(),e.stopPropagation(),!1}bindEvents(e,t,r){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)),r||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(Qg=e.clientX,Zg=e.clientY,(t=this.properties)!=null&&t.preventScrollOnSelection){let r=yt(document,"#iframe-wrapper");r.style.overflow="hidden"}}async mouseup(e){Math.abs(Qg-e.clientX)<3&&Math.abs(Zg-e.clientY)<3&&await this.processMouseEvent(e)}async mousemove(e){await this.processMouseEvent(e)}unbindEvents(e,t){let r=e.ownerDocument;e.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),e.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),r.removeEventListener("mouseup",this.toolboxShowDelayed.bind(this)),r.removeEventListener("touchend",this.toolboxShowDelayed.bind(this)),window.removeEventListener("resize",this.toolboxPlacement.bind(this)),r.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"),r=["#fce300","#48e200","#00bae5","#157cf9","#6a39b7","#ea426a","#ff8500"],i=document.getElementById("colorIcon"),o=document.getElementById("actionIcon"),s=document.getElementById("dismissIcon"),l=document.getElementById("collapseIcon"),f=document.getElementById("highlightIcon"),u=this;if(s&&(s.innerHTML=mi.close,s.addEventListener("click",function(){u.toolboxMode("add")})),l&&(l.innerHTML=mi.close,l.addEventListener("click",function(){u.toolboxMode("add")})),i){i.style.position="relative",i.style.zIndex="20",r.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;r.forEach(v=>{_--;let g=i==null?void 0:i.cloneNode(!0),h=g.lastChild,c=n.hexToRgbChannels(v);h.style.backgroundColor="rgba("+[c.red,c.green,c.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)})}r.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,E,b;u.setColor(_);let h=i==null?void 0:i.lastChild;h&&(h.style.backgroundColor=_);let c=document.getElementById("highlightIcon"),p=document.getElementById("underlineIcon"),w=document.getElementById("noteIcon");(((A=c==null?void 0:c.getElementsByTagName)==null?void 0:A.call(c,"span").length)??0)>0&&((c==null?void 0:c.getElementsByTagName("span")[0]).style.background=u.getColor()),(((E=p==null?void 0:p.getElementsByTagName)==null?void 0:E.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"),r=document.getElementById("highlight-toolbox-mode-add"),i=document.getElementById("highlight-toolbox-mode-edit"),o=document.getElementById("highlight-toolbox-mode-action");switch(e){case"colors":this.selectionMenuOpened(),t&&(t.style.display="unset"),r&&(r.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none");break;case"edit":this.selectionMenuOpened(),t&&(t.style.display="none"),r&&(r.style.display="none"),i&&(i.style.display="unset"),o&&(o.style.display="none");break;case"action":this.selectionMenuOpened(),t&&(t.style.display="none"),r&&(r.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="unset");break;default:this.selectionMenuOpened(),t&&(t.style.display="none"),r&&(r.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 r=yt(document,"#iframe-wrapper");r.style.overflow="auto"}}toolboxShowDelayed(e){this.showTool(e.detail===1)}snapSelectionToWord(e=!1){var o;let t=this,r=this.navigator.iframes[0].contentDocument;if(r){let s=(o=t.dom(r.body))==null?void 0:o.getSelection();if(t.dom(r.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)},l=s.toString(),f=l.length-l.trimStart().length,u=l.length-l.trimEnd().length,m=l.length;var i=/[-!$%^&*()_+|~=`{}[\]:/;<>?,.@#]/;l=l.replace(i,""),f=m-l.trimStart().length,l=y(l),u=m-l.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 c=["forward","backward"];v&&(c=["backward","forward"]),e?(s.modify("move",c[0],"character"),s.modify("move",c[1],"word"),s.extend(g,h),s.modify("extend",c[1],"character"),s.modify("extend",c[0],"word")):s.extend(g,h),this.selection(s.toString(),s)}return s}}toolboxShow(){var e;if(this.activeAnnotationMarkerId===void 0){let t=this,r=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)&&r){getComputedStyle(r).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 l(_){let v={className:h=>Nn.indexOf(h)<0,idName:h=>Nn.indexOf(h)<0},g=t.navigator.iframes[0].contentDocument;if(g)return Cr(_,g,v)}let f=t.navigator.iframes[0].contentWindow,u=ji(f,l);(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,l,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(),r=document.getElementById("highlight-toolbox");r&&(((o=this.properties)==null?void 0:o.menuPosition)==="top"?(r.style.left="0px",r.style.transform="revert",r.style.width="100%",r.style.textAlign="center",r.style.position="absolute",r.style.setProperty("--content","revert")):((s=this.properties)==null?void 0:s.menuPosition)==="bottom"?(r.style.bottom="0px",r.style.left="0px",r.style.transform="revert",r.style.width="100%",r.style.textAlign="center",r.style.position="absolute",r.style.setProperty("--content","revert")):(((l=this.navigator.view)==null?void 0:l.isPaginated())?r.style.top=t.top+(((f=this.navigator.attributes)==null?void 0:f.navHeight)??0)+"px":r.style.top=t.top+"px",r.style.left=(t.right-t.left)/2+t.left+"px"))}toolboxHandler(){var t,r,i,o,s,l,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"),c=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);(r=m==null?void 0:m.parentNode)==null||r.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(c){let p=function(){c==null||c.removeEventListener("click",p),y.speak()},w=c.cloneNode(!0);(s=c==null?void 0:c.parentNode)==null||s.replaceChild(w,c),c=document.getElementById("speakIcon"),c==null||c.addEventListener("click",p)}}else c&&c.style.setProperty("display","none");(((l=this.properties)==null?void 0:l.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 E(){var R,B,I,D,F,z,q;w==null||w.removeEventListener("click",E);function C(G){let Y={className:Q=>Nn.indexOf(Q)<0,idName:Q=>Nn.indexOf(Q)<0},X=A.navigator.iframes[0].contentDocument;if(X)return Cr(G,X,Y)}let k=A.navigator.iframes[0].contentWindow;if(k){let G=ji(k,C);if(G===void 0){let Y=A.navigator.iframes[0].contentDocument;G=(B=(R=A.navigator.annotationModule)==null?void 0:R.annotator)==null?void 0:B.getTemporarySelectionInfo(Y)}if(G!==void 0)if(p.callback)p.callback(G.cleanText,(I=G.range)==null?void 0:I.startContainer.parentElement);else{let Y=(D=p.highlight)==null?void 0:D.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 se=A.createHighlight(A.dom(Q.body).getWindow(),G,(F=p.highlight)==null?void 0:F.color,!0,X,p.icon,p.popup,Y);A.options.onAfterHighlight(se,X),A.navigator.rights.enableAnnotations?(z=A.navigator.annotationModule)==null||z.saveAnnotation(se[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 M;(M=A.navigator.annotationModule)==null||M.updateAnnotation(H).then(async()=>{Yr.default.log("update highlight "+H.id)})}))}):A.navigator.rights.enableBookmarks&&((q=A.navigator.bookmarkModule)==null||q.saveAnnotation(se[0]))}}}}A.callbackComplete()}if(w){let C=w.cloneNode(!0);(b=w==null?void 0:w.parentNode)==null||b.replaceChild(C,w),w=document.getElementById(p.id),w==null||w.addEventListener("click",E)}})}}doHighlight(e,t){var s,l,f,u,y,m;let r=this;function i(_){let v={className:h=>Nn.indexOf(h)<0,idName:h=>Nn.indexOf(h)<0},g=r.navigator.iframes[0].contentDocument;if(g)return Cr(_,g,v)}let o=r.navigator.iframes[0].contentWindow;if(o){let _=ji(o,i);if(_===void 0){let v=r.navigator.iframes[0].contentDocument;_=(l=(s=this.navigator.annotationModule)==null?void 0:s.annotator)==null?void 0:l.getTemporarySelectionInfo(v)}if(_){if(this.options.onBeforeHighlight(_)===!0){let v;v=this.getColor(),n.isHexColor(v)&&(v=n.hexToRgbChannels(v));let g=r.navigator.iframes[0].contentDocument;if(g){let h=this.createHighlight(r.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=r.navigator.iframes[0].contentDocument;if(y)return Cr(f,y,u)},r=this,o=r.navigator.iframes[0].contentWindow;if(o){let f=ji(o,i);if(f===void 0){let u=r.navigator.iframes[0].contentDocument;f=(t=(e=r.navigator.annotationModule)==null?void 0:e.annotator)==null?void 0:t.getTemporarySelectionInfo(u)}f!==void 0&&this.navigator.ttsModule.speak(f,!0,()=>{})}let s=r.navigator.iframes[0].contentDocument;s&&r.dom(s.body).getSelection().removeAllRanges();let l=document.getElementById("highlight-toolbox");l&&(l.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=yt(document,"#iframe-wrapper"),r=t.scrollLeft,i=r+t.clientWidth,o=e.left+e.width,s=e.top+e.height,l=t.scrollTop,f=l+t.clientHeight,u=s<l,y=e.top>f,m=o<r,_=e.left>i;return u||y||m||_}isInsideViewport(e){let t=yt(document,"#iframe-wrapper"),r=t.scrollTop,i=r+t.clientHeight,o=e.top+20>=r,s=e.top<=i,l=t.scrollLeft,f=l+t.clientWidth,u=e.left+e.width,y=e.left>l,m=u<f;return o&&s&&y&&m}get visibleTextRects(){let e=this.navigator.iframes[0].contentDocument;if(e){let r=function(l,f=[]){var y;let u=l.firstChild;for(;u;)u.nodeType===1&&r(u,f),u.nodeType===3&&(y=u.textContent)!=null&&y.trim()&&f.push(u),u=u.nextSibling;return f},i=function(l){return r(l).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(l){try{let f=document.createRange();f.selectNode(l);let u=f.getBoundingClientRect();return f.detach(),u}catch(f){Yr.default.log("measureTextNode "+f),Yr.default.log("measureTextNode "+l),Yr.default.log(`${l.textContent}`)}},t=co(e,"body");return i(t).filter(l=>this.isInsideViewport(l))}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(r){return r.parentElement?r:null}),t=this.unique(t),t.sort(function(r,i){return r.offsetTop-i.offsetTop||r.offsetLeft-i.offsetLeft}),t}flattenNestedHighlights(e){let t,r=this;r.sortByDepth(e,!0);function i(){let o=!1;return e.forEach(function(s,l){let f=s.parentElement,u=f.previousSibling,y=f.nextSibling;r.isHighlight(f)&&(r.haveSameColor(f,s)?(f.replaceChild(s.firstChild,s),e[l]=f,o=!0):(s.nextSibling||(r.dom(s).insertBefore(y||f),o=!0),s.previousSibling||(r.dom(s).insertAfter(u||f),o=!0),f.hasChildNodes()||r.dom(f).remove()))}),o}do t=i();while(t)}mergeSiblingHighlights(e){let t=this;function r(i,o){return o&&o.nodeType===Ha.ELEMENT_NODE&&t.haveSameColor(i,o)&&t.isHighlight(o)}e.forEach(function(i){let o=i.previousSibling,s=i.nextSibling;r(i,o)&&(t.dom(i).prepend(o.childNodes),t.dom(o).remove()),r(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===Ha.ELEMENT_NODE&&e.hasAttribute(ZB)}createWrapper(){let e=document.createElement("mark");return e.style.background="linear-gradient("+n.hexToRgbA(this.options.color)+", "+n.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 r=e;return"rgba("+[r.red,r.green,r.blue].join(",")+",.5)"}throw new Error("Bad Hex")}static hexToRgbAWithOpacity(e,t){let r;if(this.isHexColor(e))return r=this.hexToRgbChannels(e),"rgba("+[r.red,r.green,r.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,l,f,u,y,m,_,v,g,h,c,p,w,A;let r=(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 E=er.find(b=>b.id===i);if(E){if(E.marker===3||E.marker===2)if((s=E.style)!=null&&s.hover){if((l=E.style)!=null&&l.hover)for(let k=0;k<((u=(f=E.style)==null?void 0:f.hover)==null?void 0:u.length);k++){let R=(y=E.style)==null?void 0:y.hover[k];e.style.removeProperty(R.property)}let C="";if((m=E.style)!=null&&m.default)for(let k=0;k<((v=(_=E.style)==null?void 0:_.default)==null?void 0:v.length);k++){let R=(g=E.style)==null?void 0:g.default[k];e.style.removeProperty(R.property),C+=`${R.property}: ${R.value} !${R.priority};`}e.setAttribute("style",`${e.getAttribute("style")}; ${C}`)}else if((h=E.style)!=null&&h.hoverClass){(c=E.style)!=null&&c.hoverClass&&e.classList.remove((p=E.style)==null?void 0:p.hoverClass);let C="";(w=E.style)!=null&&w.defaultClass&&e.classList.add((A=E.style)==null?void 0:A.defaultClass),e.setAttribute("style",`${e.getAttribute("style")}; ${C}`)}else if(n.isHexColor(E.color)){let C=n.hexToRgbChannels(E.color);e.style.setProperty("background-color",`rgba(${C.red}, ${C.green}, ${C.blue}, 0)`,"important")}else e.classList.remove("hover");else if(E.marker===1||E.marker===4)if(typeof E.color=="object"){let C=E.color;e.style.setProperty("background-color",`rgba(${C.red}, ${C.green}, ${C.blue}, 0)`,"important"),e.style.setProperty("border-bottom",`2px solid rgba(${C.red}, ${C.green}, ${C.blue}, 1)`,"important")}else if(n.isHexColor(E.color)){let C=n.hexToRgbChannels(E.color);e.style.setProperty("background-color",`rgba(${C.red}, ${C.green}, ${C.blue}, 0)`,"important"),e.style.setProperty("border-bottom",`2px solid rgba(${C.red}, ${C.green}, ${C.blue}, 1)`,"important")}else e.classList.remove("hover");else if(typeof E.color=="object"){let C=E.color;e.style.setProperty("background-color",`rgba(${C.red}, ${C.green}, ${C.blue}, ${qi})`,"important")}else if(n.isHexColor(E.color)){let C=n.hexToRgbChannels(E.color);e.style.setProperty("background-color",`rgba(${C.red}, ${C.green}, ${C.blue}, ${qi})`,"important")}else e.classList.remove("hover");let b;if(r){let C=r.getElementById(t);C&&(b=C.querySelector(`#${E.id}`))}if(b){let C=b.getElementsByClassName(Cl);if(C.length>0){let k=C.item(0).getElementsByClassName("icon-tooltip");k.length>0&&k.item(0).style.removeProperty("display")}}}}}setHighlightAreaStyle(e,t,r){var i,o,s,l,f,u,y,m,_,v,g,h;for(let c of t){if(r.marker===3||r.marker===2)if((i=r.style)!=null&&i.hover){if((o=r.style)!=null&&o.default)for(let w=0;w<((l=(s=r.style)==null?void 0:s.default)==null?void 0:l.length);w++){let A=(f=r.style)==null?void 0:f.default[w];c.style.removeProperty(A.property)}let p="";for(let w=0;w<((y=(u=r.style)==null?void 0:u.hover)==null?void 0:y.length);w++){let A=(m=r.style)==null?void 0:m.hover[w];c.style.removeProperty(A.property),p+=`${A.property}: ${A.value} !${A.priority};`}c.setAttribute("style",`${c.getAttribute("style")}; ${p}`)}else if((_=r.style)!=null&&_.hoverClass){(v=r.style)!=null&&v.defaultClass&&c.classList.remove((g=r.style)==null?void 0:g.defaultClass);let p="";c.classList.add((h=r.style)==null?void 0:h.hoverClass),c.setAttribute("style",`${c.getAttribute("style")}; ${p}`)}else if(n.isHexColor(r.color)){let p=n.hexToRgbChannels(r.color);c.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${.1})`,"important")}else c.classList.add("hover");else if(r.marker===1||r.marker===4)if(typeof r.color=="object"){let p=r.color;c.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${.1})`,"important"),c.style.setProperty("border-bottom",`2px solid rgba(${p.red}, ${p.green}, ${p.blue}, 1)`,"important")}else if(n.isHexColor(r.color)){let p=n.hexToRgbChannels(r.color);c.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${.1})`,"important"),c.style.setProperty("border-bottom",`2px solid rgba(${p.red}, ${p.green}, ${p.blue}, 1)`,"important")}else c.classList.add("hover");else if(typeof r.color=="object"){let p=r.color;c.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${Ew})`,"important")}else if(n.isHexColor(r.color)){let p=n.hexToRgbChannels(r.color);c.style.setProperty("background-color",`rgba(${p.red}, ${p.green}, ${p.blue}, ${Ew})`,"important")}else c.classList.add("hover");if(r.type!==4){let w=e.getElementById("R2_ID_HIGHLIGHTS_CONTAINER").querySelector(`#${r.id}`).getElementsByClassName(Cl);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 r=(o=this.navigator.iframes[0].contentWindow)==null?void 0:o.document,i=Array.from(r.getElementById("R2_ID_SEARCH_CONTAINER").querySelectorAll(`.${jr}`));for(let s of i){let l=s,f=l.parentNode&&l.parentNode.nodeType===Node.ELEMENT_NODE&&l.parentNode.getAttribute?l.parentNode.getAttribute("id"):void 0;if(t.forEach(u=>{if(f===u.id&&u){if(typeof u.color=="object"){let _=u.color;l.style.setProperty("background-color",`rgba(${_.red}, ${_.green}, ${_.blue}, ${qi})`,"important")}else if(n.isHexColor(u.color)){let _=n.hexToRgbChannels(u.color);l.style.setProperty("background-color",`rgba(${_.red}, ${_.green}, ${_.blue}, ${qi})`,"important")}else l.classList.remove("hover");let m=r.getElementById("R2_ID_SEARCH_CONTAINER").querySelector(`#${u.id}`).getElementsByClassName(Cl);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;l.style.setProperty("background-color",`rgba(${m.red}, ${m.green}, ${m.blue}, ${qi})`,"important")}else if(n.isHexColor(e.color)){let m=n.hexToRgbChannels(e.color);l.style.setProperty("background-color",`rgba(${m.red}, ${m.green}, ${m.blue}, ${qi})`,"important")}else l.classList.remove("hover");let y=r.getElementById("R2_ID_SEARCH_CONTAINER").querySelector(`#${e.id}`).getElementsByClassName(Cl);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,l,f,u,y,m,_,v,g,h,c,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 r=e.target,i=er.find(w=>{var A;return w.id===((A=e.target.parentElement)==null?void 0:A.id)});if(!i||!r){for(let w in Rs){let A=t.getElementById(w);if(A){let E=A.querySelectorAll(`.${Tl}`);for(let C of E)this.resetHighlightBoundingStyle(C);let b=Array.from(A.querySelectorAll(`.${jr}`));for(let C of b)this.resetHighlightAreaStyle(C,w)}}return}if(r.getAttribute("data-click")&&(e.type==="mouseup"||e.type==="click"||e.type==="touchup")&&((s=r.parentElement)==null?void 0:s.style.display)!=="none"){let w={highlight:i};Yr.default.log(JSON.stringify(w));let A=this,E;if(A.navigator.rights.enableAnnotations?E=await((l=this.navigator.annotationModule)==null?void 0:l.getAnnotation(w.highlight)):A.navigator.rights.enableBookmarks&&(E=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(E).then(async()=>{})),E!=null&&E.id){Yr.default.log("selected highlight "+E.id),A.lastSelectedHighlight=E.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 R=function(){var q,G;(G=(q=A.navigator.annotationModule)==null?void 0:q.api)==null||G.addCommentToAnnotation(E).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(),B==null||B.removeEventListener("click",R,!1)})},D=function(){var q,G;A.navigator.rights.enableAnnotations?(q=A.navigator.annotationModule)==null||q.deleteSelectedHighlight(E).then(async()=>{Yr.default.log("delete highlight "+E.id),b&&(b.style.display="none"),A.selectionMenuClosed()}):A.navigator.rights.enableBookmarks&&((G=A.navigator.bookmarkModule)==null||G.deleteSelectedHighlight(E).then(async()=>{Yr.default.log("delete highlight "+E.id),b&&(b.style.display="none"),A.selectionMenuClosed()}))};b.style.display="block",this.toolboxMode("edit");let C=document.getElementById("colorIcon"),k=document.getElementById("highlightIcon");C&&(C.style.display="none"),k&&(k.style.display="none");let B=document.getElementById("commentIcon"),I=document.getElementById("cloneCommentIcon");if(I){let q=I.parentElement;q&&q.removeChild(I)}if(B){B.style.display="none";let q=B.cloneNode(!0),G=B.parentElement;q.style.display="unset",q.id="cloneCommentIcon",q.addEventListener("click",R,!1),G&&G.append(q)}let F=document.getElementById("deleteIcon"),z=document.getElementById("cloneDeleteIcon");if(z){let q=z.parentElement;q&&q.removeChild(z)}if(F){F.style.display="none";let q=F.cloneNode(!0),G=F.parentElement;q.style.display="unset",q.id="cloneDeleteIcon",q.addEventListener("click",D,!1),G&&G.append(q)}}else b.style.display="none",this.selectionMenuClosed(),b.offsetWidth,b.style.display="block"}else{r.dataset.definition&&new Ba(this.navigator).showPopup(r.dataset.definition,e);let b=(g=(v=(_=this.navigator.definitionsModule)==null?void 0:_.properties)==null?void 0:v.definitions)==null?void 0:g.filter(C=>C.order===Number(r==null?void 0:r.dataset.order))[0];Yr.default.log(b),(c=(h=this.navigator.definitionsModule)==null?void 0:h.api)!=null&&c.click&&((p=this.navigator.definitionsModule.api)==null||p.click(e1.omit(b,"callbacks"),e1.omit(i,"definition")),this.navigator.emit("definition.click",b,i))}}}async prepareContainers(e){for(let t in Rs)await this.ensureHighlightsContainer(e,t)}async ensureHighlightsContainer(e,t){var i,o;let r=e.document;if(!r.getElementById(t)){let s=r.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")),r.body&&r.body.append(s),((o=await this.layerSettings.getProperty(t))==null?void 0:o.value)===!1&&(s.style.display="none")}return r.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 r;let t=(r=this.navigator.iframes[0].contentWindow)==null?void 0:r.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 r=-1;er.find((s,l)=>(r=l,s.id===t))&&r>=0&&r<er.length&&er.splice(r,1);let o=e.getElementById(t);o&&this.removeAllChildNodes(o)}createHighlight(e,t,r,i,o,s,l,f,u,y){try{let m=`${t.rangeInfo.startContainerElementCssSelector}${t.rangeInfo.startContainerChildTextNodeIndex}${t.rangeInfo.startOffset}${t.rangeInfo.endContainerElementCssSelector}${t.rangeInfo.endContainerChildTextNodeIndex}${t.rangeInfo.endOffset}`,_=Ui.hash(m),v=(y||"R2_HIGHLIGHT_")+_;this.destroyHighlight(e.document,v);let g=`rgb(${Ls.red}, ${Ls.green}, ${Ls.blue})`,h={color:r||g,id:v,pointerInteraction:i,selectionInfo:t,marker:o,icon:s,popup:l,style:f,type:u||0};(u===0||u===4||u===void 0)&&er.push(h);let c=this.createHighlightDom(e,h);return h.position=parseInt((c!=null&&c.hasChildNodes()?c.childNodes[0]:c).style.top.replace("px","")),[h,c]}catch(m){throw"Can't create highlight: "+m}}createHighlightDom(e,t){var F,z,q,G,Y,X,Q,se,ve,ce,W,H,M,x,T,P,N,U,V,Z,re,ne,ae,fe,he,Te,Ne,Se,ye,oe,Ee,xe;let r=e.document,i=Rf(r,t.selectionInfo.rangeInfo);if(!i)return;for(let K in Rs)this.ensureHighlightsContainer(e,K);let o=r.createElement("div");o.setAttribute("id",t.id),o.setAttribute("class",Cw),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,Ce=er.find(Re=>Re.id===K.currentTarget.id);if(K.type==="mouseover"&&((ie=be.parentElement)==null?void 0:ie.style.display)!=="none"&&Ce){let Re=Array.from(be.querySelectorAll(`.${jr}`));this.setHighlightAreaStyle(r,Re,Ce)}}}),o.addEventListener("mouseleave",K=>{let ie=K.currentTarget,be=Array.from(ie.querySelectorAll(`.${jr}`));for(let Ke of be)this.resetHighlightAreaStyle(Ke,ie.id);let Ce=ie.querySelector(`.${Tl}`),Re=ie.querySelectorAll(`.${Tl}`);for(let Ke of Re)(!Ce||Ke!==Ce)&&this.resetHighlightBoundingStyle(Ke)}));let s=(F=this.navigator.view)==null?void 0:F.isPaginated();s?r.body.style.position="revert":r.body.style.position="relative";let l=r.body.getBoundingClientRect(),f=this.getScrollingElement(r),u=s?-f.scrollLeft:l.left,y=s?-f.scrollTop:l.top,m=1,_=!1,v=!1,h=_||v||!1;Yr.default.debug(h),h=!0;let c=kf(i,h),p=3,w=2,A=3,E=0,b=24,C,k;for(let K of c){let ie=r.createElement("div");ie.setAttribute("class",jr),ie.dataset.marker=""+t.marker;let be="";if(_&&t.marker!==3&&t.marker!==2&&t.marker!==4){let Be=t.color;n.isHexColor(Be)&&(Be=n.hexToRgbChannels(Be)),be+=`border-bottom: ${w*m}px solid rgba(${Be.red}, ${Be.green}, ${Be.blue}, ${qi}) !important`}if(t.marker===3||t.marker===2)if((z=t.style)!=null&&z.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(n.isHexColor(t.color)){let Be=n.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}, ${qi}) !important; ${be}`)}else if(n.isHexColor(t.color)){let Be=n.hexToRgbChannels(t.color);ie.setAttribute("style",`mix-blend-mode: multiply; border-radius: ${p}px !important; background-color: rgba(${Be.red}, ${Be.green}, ${Be.blue}, ${qi}) !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 Ce=parseInt(ie.style.top.replace("px",""));if((Ce<E||E===0)&&(E=Ce),b=parseInt(ie.style.height.replace("px","")),v){let Be=r.createElement("div");Be.setAttribute("class",jr);let ut=t.color;n.isHexColor(ut)&&(ut=n.hexToRgbChannels(ut)),Be.setAttribute("style",`background-color: rgba(${ut.red}, ${ut.green}, ${ut.blue}, ${qi}) !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=(se=this.navigator.iframes[0].contentWindow)==null?void 0:se.innerWidth,Ke=parseInt(getComputedStyle(r.documentElement).getPropertyValue("column-count")),ze=parseInt(getComputedStyle(r.documentElement).getPropertyValue("column-width")),Ve=parseInt(getComputedStyle(r.body).getPropertyValue("padding-left")),qe=Re/(Ke||1);qe<ze&&(qe=Re),s||(qe=parseInt(getComputedStyle(r.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),C=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,C=C-Ve/Ke),s||(C=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,C=C-Ve/2))}let R=i.getBoundingClientRect(),B=r.createElement("div");B.setAttribute("class",Tl),B.style.setProperty("pointer-events","none"),B.style.position="absolute",B.scale=m,B.rect={height:R.height,left:R.left-u,top:R.top-y,width:R.width},B.style.width=`${B.rect.width*m}px`,B.style.height=`${B.rect.height*m}px`,B.style.left=`${B.rect.left*m}px`,B.style.top=`${B.rect.top*m}px`,o.append(B);let I=r.createElement("div");if(I.setAttribute("class",Cl),((W=t.icon)==null?void 0:W.position)==="left")I.setAttribute("style",`position: absolute;top:${E}px;left:${k+((M=(H=this.navigator.iframes[0].contentDocument)==null?void 0:H.scrollingElement)==null?void 0:M.scrollLeft)}px;height:${b}px; width:${b}px;`);else if(((x=t.icon)==null?void 0:x.position)==="inline")I.setAttribute("style",`position: absolute;top:${E-b/2}px;left:${parseInt(B.style.left.replace("px",""))+parseInt(B.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;I.setAttribute("style",`position: absolute;top:${E}px;left:${parseInt(B.style.left.replace("px",""))+parseInt(B.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?I.setAttribute("style",`position: absolute;top:${E-b/2}px;left:${parseInt(B.style.left.replace("px",""))+parseInt(B.style.width.replace("px",""))-b/2}px;height:${b}px; width:${b}px;`):t.note&&t.marker===4||t.marker===0||t.marker===1?I.setAttribute("style",`position: absolute;top:${E}px;left:${C+((N=(P=this.navigator.iframes[0].contentDocument)==null?void 0:P.scrollingElement)==null?void 0:N.scrollLeft)}px;height:${b}px; width:${b}px;`):I.setAttribute("style",`position: absolute;top:${E}px;left:${C+((V=(U=this.navigator.iframes[0].contentDocument)==null?void 0:U.scrollingElement)==null?void 0:V.scrollLeft)}px;height:${b}px; width:${b}px;`);if(t.marker===3||t.marker===2)(Z=t.icon)!=null&&Z.class?(I.classList.add((re=t.icon)==null?void 0:re.class),I.id=(ne=t.icon)==null?void 0:ne.id):(ae=t.icon)!=null&&ae.svgPath?I.innerHTML=Da(`${(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,`${(Ne=t.icon)==null?void 0:Ne.color} !important`):(Se=t.icon)!=null&&Se.title&&(I.innerHTML=(ye=t.icon)==null?void 0:ye.title);else if(t.note){let K=t.color;n.isHexColor(K)&&(K=n.hexToRgbChannels(K)),t.marker===4||t.marker===0||t.marker===1?I.innerHTML=Da("","",'<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`):I.innerHTML=Da("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?I.style.setProperty("pointer-events","none"):(I.style.setProperty("pointer-events","all"),I.style.setProperty("cursor","hand"));let D=this;if(t.type!==3&&t.type!==4&&I.addEventListener("click",async function(K){var Re,Ke,ze,Ve,qe;let ie;D.navigator.rights.enableAnnotations?(ie=await((Re=D.navigator.annotationModule)==null?void 0:Re.getAnnotationByID(t.id)),(ze=(Ke=D.navigator.annotationModule)==null?void 0:Ke.api)==null||ze.selectedAnnotation(ie).then(async()=>{})):D.navigator.rights.enableBookmarks&&(ie=await((Ve=D.navigator.bookmarkModule)==null?void 0:Ve.getAnnotationByID(t.id))),Yr.default.log("selected highlight "+ie.id),D.lastSelectedHighlight=ie.id;let be=document.getElementById("highlight-toolbox");if(be)if(be.style.top=K.clientY+(((qe=D.navigator.attributes)==null?void 0:qe.navHeight)??0)+"px",be.style.left=K.clientX+"px",getComputedStyle(be).display==="none"){let Be=function(){var Ht,Dr;D.navigator.rights.enableAnnotations?(Ht=D.navigator.annotationModule)==null||Ht.deleteSelectedHighlight(ie).then(async()=>{Yr.default.log("delete highlight "+ie.id),be.style.display="none",D.selectionMenuClosed()}):D.navigator.rights.enableBookmarks&&((Dr=D.navigator.bookmarkModule)==null||Dr.deleteSelectedHighlight(ie).then(async()=>{Yr.default.log("delete highlight "+ie.id),be.style.display="none",D.selectionMenuClosed()}))};be.style.display="block",D.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),Dr=ut.parentElement;Ht.style.display="unset",Ht.id="cloneDeleteIcon",Ht.addEventListener("click",Be,!1),Dr&&Dr.append(Ht)}}else be.style.display="none",D.selectionMenuClosed(),be.offsetWidth,be.style.display="block";let Ce=Array.from(o.querySelectorAll(`.${jr}`));D.setHighlightAreaStyle(r,Ce,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),(Ee=t.popup)!=null&&Ee.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(I),t.type){case 1:r.getElementById("R2_ID_SEARCH_CONTAINER").append(o);break;case 2:r.getElementById("R2_ID_READALOUD_CONTAINER").append(o);break;case 3:r.getElementById("R2_ID_PAGEBREAK_CONTAINER").append(o);break;case 4:r.getElementById("R2_ID_DEFINITIONS_CONTAINER").append(o);break;default:r.getElementById("R2_ID_HIGHLIGHTS_CONTAINER").append(o);break}return o}addSelectionMenuItem(e){var t,r;(((t=this.properties)==null?void 0:t.selectionMenuItems)??[])&&(((r=this.properties)==null?void 0:r.selectionMenuItems)??[]).push(e)}};var Fw=rt(c1());L();var lD=rt($t());var Jo={className:n=>!0,idName:n=>!0,tagName:n=>!0};var Hw=rt(If()),ei=rt($t());L();var Bw=rt($t());var ja=class{constructor(e,t,r){this.currSeconds=0;this.publication=e,this.properties=t,this.api=r}static async create(e){let t=new this(e.publication,e,e.api);return await t.start(),t}async start(){this.startResearchSession()}async stop(){Bw.default.log("Consumption module stop"),this.endResearchSession()}initialize(e){let t=e.contentWindow;if(t){let r=this;t.onload=function(){r.resetTimer()},t.onmousemove=function(){r.resetTimer()},t.onmousedown=function(){r.resetTimer()},t.ontouchstart=function(){r.resetTimer()},t.onclick=function(){r.resetTimer()},t.onkeypress=function(){r.resetTimer()}}}trackAction(e,t){var r;(r=this.api)==null||r.actionTracked(e,t)}startReadingSession(e){if(this.firstReadingLocator&&this.lastReadingLocator){let t=this.lastReadingLocator.locations.totalProgression-this.firstReadingLocator.locations.totalProgression,r=(new Date().getTime()-this.startReadingTimer.getTime())/1e3;this.readingSessions.push({lastLocator:this.lastReadingLocator,firstLocator:this.firstReadingLocator,time:r,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 r=this;this.readingSessionsInterval=setInterval(function(){r.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 r=(new Date().getTime()-this.startResearchTimer.getTime())/1e3;(e=this.api)==null||e.updateResearchSession(this.researchSessionId,this.readingSessions,Math.round(r)),(t=this.api)==null||t.endResearchSession(this.researchSessionId,this.readingSessions,Math.round(r)),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 qa=class n{constructor(e,t,r,i,o,s,l,f){this.hide=Le(document,"#menu-button-hide");this.show=Le(document,"#menu-button-show");this.annotator=e,this.rights=t,this.publication=r,this.headerMenu=f,this.initialAnnotations=i,this.highlighter=s,this.properties=o,this.api=l}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=Le(this.headerMenu,"#container-view-highlights")),this.initialAnnotations){var e=this.initialAnnotations.highlights||null;e&&((t=this.annotator)==null||t.initAnnotations(e))}setTimeout(()=>{var r;(r=this.properties)!=null&&r.hideLayer?this.navigator.hideLayer("highlights"):this.navigator.showLayer("highlights")},10)}hideAnnotationLayer(){let e=this.navigator.iframes[0].contentDocument;if(e){let t=Le(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=Le(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(e){return new Promise(async t=>{await document.fonts.ready,this.rights.enableAnnotations&&setTimeout(()=>{var r;this.drawHighlights(),this.showHighlights(),we((r=e.contentDocument)==null?void 0:r.body,"click",this.click.bind(this))},300),t(null)})}click(e){var t,r,i,o,s,l,f;if(this.activeAnnotationMarkerId){let u=(i=(r=(t=this.highlighter)==null?void 0:t.properties)==null?void 0:r.selectionMenuItems)==null?void 0:i.filter(y=>y.id===this.activeAnnotationMarkerId);if(u&&(u==null?void 0:u.length)>0){let y=Hw.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 c=function(w){try{let A=h.navigator.iframes[0].contentDocument;return A?Cr(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=mo(v,c);if(_.removeAllRanges(),p){let w={rangeInfo:p},A=(l=this.navigator.highlighter)==null?void 0:l.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(E=>{ei.default.log("saved bookmark "+E.id)})}(f=m.getSelection())==null||f.removeAllRanges()}}}}async scrollToHighlight(e){var r;ei.default.log("still need to scroll to "+e);var t=await((r=this.annotator)==null?void 0:r.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),r=await this.addAnnotation(e);return ei.default.log("Highlight deleted "+JSON.stringify(t)),ei.default.log("Highlight added "+JSON.stringify(r)),await this.showHighlights(),await this.drawHighlights(),r}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(r=>r(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,r;(t=this.api)!=null&&t.deleteAnnotation?(r=this.api)==null||r.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 r,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=(r=this.navigator.view)==null?void 0:r.getCurrentPosition(),l=this.navigator.iframes[0].contentDocument;if(l){let f=co(l,"body"),u=e.position?e.position/f.scrollHeight:s,y=(0,Fw.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,r,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 l of s){er.push(l.highlight);let f=l,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,l.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(l.id,this.navigator.iframes[0].contentWindow))+'px;width:20px"></div>',h=document.createElement("div");h.innerHTML=g;let c=h.childNodes[0],p=document.createElement("i");p.innerHTML="sticky_note_2",p.className="material-icons",p.style.color=f.highlight.color,c.appendChild(p),we(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&&((r=this.navigator.iframes[0].contentDocument)==null?void 0:r.readyState)==="complete"){await this.highlighter.destroyHighlights(0);for(let l of s){er.push(l.highlight);let f=l,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,l.highlight),setTimeout(async()=>{var _,v,g;if(((_=f.highlight)==null?void 0:_.marker)===1){let c='<div class="comment" style="top: '+await((v=this.annotator)==null?void 0:v.getAnnotationPosition(l.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=c,p.childNodes[0].innerHTML=mi.note,we(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,r,i,o,s,l;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()&&((r=this.properties)!=null&&r.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())&&((l=this.properties)!=null&&l.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,C;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(jr)[0];let h=parseInt(v.style.height.replace("px","")),c=u.highlight.position,p=e.createElement("div");p.setAttribute("style",`position: absolute;top:${c}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=Da("","",'<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 E=e.createElement("div");E.innerHTML=(b=u.highlight)==null?void 0:b.note,E.setAttribute("style",`height:${h}px;overflow: hidden;padding-left: 5px;`),p.appendChild(E),we(p,"click",k=>{k.preventDefault(),k.stopPropagation(),this.scrollToHighlight(u.highlight.id)}),(C=this.commentGutter)==null||C.appendChild(p)})))}}createTree(e,t,r){if(t){let i=this,o=this.publication.readingOrder;if(o.length){let s=(l,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),c=this.publication.getTOCItemAbsolute(h);_.href=h,_.innerHTML=(c==null?void 0:c.Title)||"",m.appendChild(_)}else v.innerHTML=y.Title||"",v.className="chapter-title",m.appendChild(v);we(_,"click",h=>{h.preventDefault(),h.stopPropagation();let c={href:_.href,locations:{progression:0},type:y.TypeLink,title:_.title};this.navigator.stopReadAloud(),this.navigator.navigate(c)});let g=document.createElement("ol");t.forEach(function(h){var p,w,A,E,b,C,k;let c=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&h.href.endsWith(c)){let R=document.createElement("li");R.className="annotation-item";let B=document.createElement("a");if(B.setAttribute("href",h.href),e===1){B.className="highlight-link";let D=document.createElement("span"),F=document.createElement("span");if(D.className="title",F.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&&F.style.setProperty("border-bottom",`2px solid ${Jt.hexToRgbA(G)}`,"important")}else F.style.setProperty("border-bottom",`2px solid ${(E=h.highlight)==null?void 0:E.color}`,"important");else if(typeof((b=h.highlight)==null?void 0:b.color)=="object"){let G=(C=h.highlight)==null?void 0:C.color;G&&(F.style.backgroundColor=Jt.hexToRgbA(G))}else{let G=(k=h.highlight)==null?void 0:k.color;G&&(F.style.backgroundColor=G)}D.appendChild(F),B.appendChild(D);let z=document.createElement("span"),q=Math.round((h.locations.progression??0)*100)+"% through resource";z.className="subtitle",z.innerHTML=q,B.appendChild(z)}let I=document.createElement("span");if(I.className="timestamp",I.innerHTML=n.readableTimestamp(h.created),B.appendChild(I),we(B,"click",D=>{D.preventDefault(),D.stopPropagation(),i.handleAnnotationLinkClick(D,h)}),R.appendChild(B),i.navigator.sideNavExpanded){let D=document.createElement("button");D.className="delete",D.innerHTML=mi.delete,we(D,"click",F=>{F.preventDefault(),F.stopPropagation(),i.handleAnnotationLinkDeleteClick(e,F,h)}),R.appendChild(D)}g.appendChild(R)}}),g.children.length>0&&(u.appendChild(m),u.appendChild(g)),u.children.length>0&&l.appendChild(u),y.Children&&y.Children.length>0&&s(l,y.Children)}};r.innerHTML="",s(r,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,r){ei.default.log("annotation data locator: ",r),r?e===1&&this.deleteHighlight(r):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,r=(i,o)=>{let s=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),l,f;s&&(l=s.querySelector(`#${o.highlight.id}`)),f=l.getElementsByClassName(jr)[0];let y=parseInt(f.style.top.replace("px","")),m={...o,highlight:{...o.highlight,position:y}};return[...i,m]};return e.reduce(r,[])}reposition(e){let t=this.navigator.iframes[0].contentDocument,r=(i,o,s)=>{let l=e[0],f=t.getElementById("R2_ID_HIGHLIGHTS_CONTAINER"),u,y;f&&(u=f.querySelector(`#${l.highlight.id}`)),y=u.getElementsByClassName(jr)[0];let _=parseInt(y.style.height.replace("px","")),v=o.highlight.position,g=i[s-1]&&i[s-1].highlight.position,c=s===0?0:g+_+0,p=c>v?c: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(r,[])}};L();var d1=rt(c1());var ti=rt($t());var Ga=class n{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(r=>r(t))}constructor(e,t,r,i,o,s,l){this.annotator=e,this.rights=t,this.publication=r,this.headerMenu=l,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=Le(this.headerMenu,"#container-view-bookmarks")),this.headerMenu&&(this.sideNavSectionBookmarks=Le(this.headerMenu,"#sidenav-section-bookmarks")),this.headerMenu){let r=Le(this.headerMenu,"#menu-button-bookmark");r&&((e=r.parentElement)==null||e.style.removeProperty("display")),r&&we(r,"click",this.saveBookmark.bind(this))}if(this.initialAnnotations){let r=this.initialAnnotations.bookmarks||null;r&&((t=this.annotator)==null||t.initBookmarks(r))}}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,r;if(this.annotator)if((t=this.api)!=null&&t.deleteBookmark){await((r=this.api)==null?void 0:r.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,r,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(),l=(0,d1.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:l,href:o,created:new Date,title:this.navigator.currentChapterLink.title}}else f={id:l,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((r=this.navigator.consumptionModule)==null||r.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 l,f,u,y,m,_,v,g,h,c,p,w,A;let e=this,t=(l=this.navigator.highlighter)==null?void 0:l.visibleTextRects[0],r=this.navigator.iframes[0].contentDocument;if(r){let E=(f=this.navigator.highlighter)==null?void 0:f.dom(r.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&&E.selectNodeContents(t.node),b.addRange(E);let C=kf(E,!1),k=0;for(let R of C){if(!((m=this.navigator.highlighter)!=null&&m.isOutsideViewport(R))){let B=b.focusNode,I=b.focusOffset;b.collapse(b.anchorNode,b.anchorOffset);for(let q=0;q<k;q++)b.modify("move","forward","line");b.extend(B,I);let D=b.focusNode,F=b.focusNode.length;b.collapse(b.anchorNode,b.anchorOffset);let z=F;b.anchorOffset>F?z=F:z=b.anchorOffset+1,b.modify("move","forward","character"),b.modify("move","backward","word"),b.extend(D,z),b.modify("extend","backward","character"),b.modify("extend","forward","word");break}k++}}function i(E){var k;let b={},C=e.navigator.iframes[0].contentDocument;if(C)return Cr(E,(k=e.navigator.highlighter)==null?void 0:k.dom(C.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 E=ji(o,i);if(E===void 0){let C=e.navigator.iframes[0].contentDocument;E=(v=(_=this.navigator.annotationModule)==null?void 0:_.annotator)==null?void 0:v.getTemporarySelectionInfo(C)}let b=e.navigator.iframes[0].contentDocument;if(E&&b){let C=(p=this.navigator.highlighter)==null?void 0:p.createHighlight((g=this.navigator.highlighter)==null?void 0:g.dom(b.body).getWindow(),E,(h=s.highlight)==null?void 0:h.color,!0,2,s.icon,s.popup,(c=s.highlight)==null?void 0:c.style);if((A=(w=this.navigator.iframes[0].contentDocument)==null?void 0:w.getSelection())==null||A.removeAllRanges(),C)return this.saveAnnotation(C[0]).then(k=>{ti.default.log("saved bookmark "+(k==null?void 0:k.id))})}}}async saveAnnotation(e){var r,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=(r=this.navigator.view)==null?void 0:r.getCurrentPosition(),l=this.navigator.iframes[0].contentDocument;if(l){let f=co(l,"body"),u=e.position?e.position/f.scrollHeight:s,y=(0,d1.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(r=>r.highlight.marker===2),e?e.push.apply(e,t):e=t)),this.bookmarksView&&this.createTree(0,e,this.bookmarksView)}async drawBookmarks(){var t,r;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,l=this.navigator.currentChapterLink.href;var e=this.publication.getTOCItem(l);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&&((r=this.navigator.iframes[0].contentDocument)==null?void 0:r.readyState)==="complete"){await this.navigator.highlighter.destroyHighlights(0);for(let o of i){er.push(o.highlight);let s=o,l=this.navigator.currentChapterLink.href,f=this.publication.getTOCItem(l);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(r=>r(null))}createTree(e,t,r){if(t){let i=this,o=this.publication.readingOrder;if(o.length){let s=(l,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),c=this.publication.getTOCItemAbsolute(h);_.href=h,_.innerHTML=(c==null?void 0:c.Title)||"",m.appendChild(_)}else v.innerHTML=y.Title||"",v.className="chapter-title",m.appendChild(v);we(_,"click",h=>{h.preventDefault(),h.stopPropagation();let c={href:_.href,locations:{progression:0},type:y.TypeLink,title:_.title};this.navigator.stopReadAloud(),this.navigator.navigate(c)});let g=document.createElement("ol");t.forEach(function(h){let c=y.Href.indexOf("#")!==-1?y.Href.slice(0,y.Href.indexOf("#")):y.Href;if(y.Href&&h.href.endsWith(c)){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 E=document.createElement("span"),b=Math.round((h.locations.progression??0)*100)+"% through resource";E.className="title",E.innerHTML=b,w.appendChild(E)}let A=document.createElement("span");if(A.className="timestamp",A.innerHTML=n.readableTimestamp(h.created),w.appendChild(A),we(w,"click",E=>{E.preventDefault(),E.stopPropagation(),i.handleAnnotationLinkClick(E,h)}),p.appendChild(w),i.navigator.sideNavExpanded){let E=document.createElement("button");E.className="delete",E.innerHTML=mi.delete,we(E,"click",b=>{b.preventDefault(),b.stopPropagation(),i.handleAnnotationLinkDeleteClick(e,b,h)}),p.appendChild(E)}g.appendChild(p)}}),g.children.length>0&&(u.appendChild(m),u.appendChild(g)),u.children.length>0&&l.appendChild(u),y.Children&&y.Children.length>0&&s(l,y.Children)}};r.innerHTML="",s(r,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,r){ti.default.log("bookmark data locator: ",r),r?e===0&&this.deleteBookmark(r):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 jw=rt(Uw());L();var hn=rt($t()),f1="r2-mo-active",Nr=class Nr{};Nr.COLOR_REF="color",Nr.AUTO_SCROLL_REF="autoscroll",Nr.AUTO_TURN_REF="autoturn",Nr.VOLUME_REF="volume",Nr.RATE_REF="rate",Nr.COLOR_KEY="mediaoverlay-"+Nr.COLOR_REF,Nr.AUTO_SCROLL_KEY="mediaoverlay-"+Nr.AUTO_SCROLL_REF,Nr.AUTO_TURN_KEY="mediaoverlay-"+Nr.AUTO_TURN_REF,Nr.VOLUME_KEY="mediaoverlay-"+Nr.VOLUME_REF,Nr.RATE_KEY="mediaoverlay-"+Nr.RATE_REF;var st=Nr,Nf=class{constructor(e,t,r){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=r,this.initialise(),hn.default.log(this.api)}static create(e){let t=new this(e.store,e.api,e.headerMenu);if(e.initialMediaOverlaySettings){let r=e.initialMediaOverlaySettings;r!=null&&r.color&&(t.color=r.color,hn.default.log(t.color)),r!=null&&r.autoScroll&&(t.autoScroll=r.autoScroll,hn.default.log(t.autoScroll)),r!=null&&r.autoTurn&&(t.autoTurn=r.autoTurn,hn.default.log(t.autoScroll)),r!=null&&r.volume&&(t.volume=r.volume,hn.default.log(t.volume)),r!=null&&r.rate&&(t.rate=r.rate,hn.default.log(t.rate)),r!=null&&r.wait&&(t.wait=r.wait,hn.default.log(t.wait))}return t.initializeSelections(),t}stop(){hn.default.log("MediaOverlay settings stop")}initialise(){this.autoScroll=this.getProperty(st.AUTO_SCROLL_KEY)!=null?this.getProperty(st.AUTO_SCROLL_KEY).value:this.autoScroll,this.autoTurn=this.getProperty(st.AUTO_TURN_KEY)!=null?this.getProperty(st.AUTO_TURN_KEY).value:this.autoTurn,this.color=this.getProperty(st.COLOR_KEY)!=null?this.getProperty(st.COLOR_KEY).value:this.color,this.volume=this.getProperty(st.VOLUME_KEY)!=null?this.getProperty(st.VOLUME_KEY).value:this.volume,this.rate=this.getProperty(st.RATE_KEY)!=null?this.getProperty(st.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=Le(this.headerMenu,"#container-view-mediaoverlay-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(e){this.headerMenu&&(this.speechAutoTurn=Le(this.headerMenu,"#mediaOverlayAutoTurn")),this.headerMenu&&(this.speechAutoScroll=Le(this.headerMenu,"#mediaOverlayAutoScroll")),this.headerMenu&&(this.speechVolume=Le(this.headerMenu,"#mediaOverlayVolume")),this.headerMenu&&(this.speechRate=Le(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()),we(Le(e,"ul"),"click",t=>{t.stopPropagation()})}onSettingsChange(e){this.settingsChangeCallback=e}storeProperty(e){this.updateUserSettings(),this.saveProperty(e)}updateUserSettings(){var t,r,i,o,s,l,f;let e={color:(t=this.userProperties.getByRef(st.COLOR_REF))==null?void 0:t.value,autoScroll:(r=this.userProperties.getByRef(st.AUTO_SCROLL_REF))==null?void 0:r.value,autoTurn:(i=this.userProperties.getByRef(st.AUTO_TURN_REF))==null?void 0:i.value,volume:(o=this.userProperties.getByRef(st.VOLUME_REF))==null?void 0:o.value,rate:(s=this.userProperties.getByRef(st.RATE_REF))==null?void 0:s.value};this.applyMediaOverlaySettings(e),(l=this.api)!=null&&l.updateSettings&&((f=this.api)==null||f.updateSettings(e).then(async u=>{hn.default.log("api updated sync settings",u)}))}getMediaOverlaySettings(){let e=new Li;return e.addSwitchable("mediaoverlay-auto-scroll-off","mediaoverlay-auto-scroll-on",this.autoScroll,st.AUTO_SCROLL_REF,st.AUTO_SCROLL_KEY),e.addSwitchable("mediaoverlay-auto-turn-off","mediaoverlay-auto-turn-on",this.autoTurn,st.AUTO_TURN_REF,st.AUTO_TURN_KEY),e.addStringable(this.color,st.COLOR_REF,st.COLOR_KEY),e.addIncremental(this.volume,.1,1,.1,"",st.VOLUME_REF,st.VOLUME_KEY),e.addIncremental(this.rate,.1,3,.1,"",st.RATE_REF,st.RATE_KEY),e}saveProperty(e){let t=this.store.get(this.MEDIAOVERLAYSETTINGS);if(t){let r=JSON.parse(t);r=r.filter(i=>i.name!==e.name),r.push(e),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(r))}else{let r=[];r.push(e),this.store.set(this.MEDIAOVERLAYSETTINGS,JSON.stringify(r))}return e}getProperty(e){let t=this.store.get(this.MEDIAOVERLAYSETTINGS);if(t){let r=JSON.parse(t);return r=r.filter(i=>i.name===e),r.length===0?null:r[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(st.COLOR_REF);t&&(t.value=this.color,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoScroll!==void 0){hn.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.autoTurn!==void 0){hn.default.log("autoTurn "+this.autoTurn),this.autoTurn=e.autoTurn;let t=this.userProperties.getByRef(st.AUTO_TURN_REF);t&&(t.value=this.autoTurn,this.saveProperty(t)),this.settingsChangeCallback()}if(e.volume){hn.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()}if(e.rate){hn.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()}}applyMediaOverlaySetting(e,t){if(e===st.COLOR_REF){this.color=t;let r=this.userProperties.getByRef(st.COLOR_REF);r&&(r.value=this.color,this.saveProperty(r)),this.settingsChangeCallback()}else if(e===st.AUTO_SCROLL_REF){this.autoScroll=t;let r=this.userProperties.getByRef(st.AUTO_SCROLL_REF);r&&(r.value=this.autoScroll,this.saveProperty(r)),this.settingsChangeCallback()}else if(e===st.AUTO_TURN_REF){this.autoTurn=t;let r=this.userProperties.getByRef(st.AUTO_TURN_REF);r&&(r.value=this.autoTurn,this.saveProperty(r)),this.settingsChangeCallback()}}increase(e){var t,r;if(e==="mo_volume"){this.userProperties.getByRef(st.VOLUME_REF).increment(),this.volume=(t=this.userProperties.getByRef(st.VOLUME_REF))==null?void 0:t.value;let i=this.userProperties.getByRef(st.VOLUME_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}else if(e==="mo_rate"){this.userProperties.getByRef(st.RATE_REF).increment(),this.rate=(r=this.userProperties.getByRef(st.RATE_REF))==null?void 0:r.value;let i=this.userProperties.getByRef(st.RATE_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}}decrease(e){var t,r;if(e==="mo_volume"){this.userProperties.getByRef(st.VOLUME_REF).decrement(),this.volume=(t=this.userProperties.getByRef(st.VOLUME_REF))==null?void 0:t.value;let i=this.userProperties.getByRef(st.VOLUME_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}else if(e==="mo_rate"){this.userProperties.getByRef(st.RATE_REF).decrement(),this.rate=(r=this.userProperties.getByRef(st.RATE_REF))==null?void 0:r.value;let i=this.userProperties.getByRef(st.RATE_REF);i&&this.storeProperty(i),this.settingsChangeCallback()}}};var Ze=rt($t()),Wa=class{constructor(e,t,r){this.play=Le(document,"#menu-button-play");this.pause=Le(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=r}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,r;let e=this.currentLinks[this.currentLinkIndex];if((t=e==null?void 0:e.Properties)!=null&&t.MediaOverlay){this.ensureOnTimeUpdate(!1,!1);let i=(r=e.Properties)==null?void 0:r.MediaOverlay,s=new URL(i,this.publication.manifestUrl).toString(),l;try{l=await fetch(s,this.navigator.requestConfig)}catch(m){console.error(m,s);return}l.ok||Ze.default.log("BAD RESPONSE?!");let f;try{f=await l.json()}catch(m){console.error(m)}if(!f){Ze.default.log("## moJson"+f);return}e.MediaOverlays=_a(f,jw.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,r){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&&r){o=!1;let u=f.hash.substr(1);for(let y of r)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&&!r?(Ze.default.log("findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain"),t):void 0}let s=r,l=r;for(let f of t.Children){Ze.default.log("findDepthFirstTextAudioPair() - child"),Ze.default.log(JSON.stringify(f));let u=this.findDepthFirstTextAudioPair(e,f,l);if(u===null&&(Ze.default.log("findDepthFirstTextAudioPair() - child - match null (skip)"),l=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&&!l)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 r=!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),r=!0)}r?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,r,i){if(!e.Children||!e.Children.length){if((r==null?void 0:r.prev)===t)return Ze.default.log("findNextTextAudioPair() - prevMo === moToMatch"),e;Ze.default.log("findNextTextAudioPair() - set previous"),Ze.default.log(JSON.stringify(e)),r.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,r,i);if(s)return Ze.default.log("findNextTextAudioPair() - match"),Ze.default.log(JSON.stringify(s)),s}}async playMediaOverlaysAudio(e,t,r){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 l=s.toString(),f=typeof t<"u",u=typeof r<"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=r;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 c=function(){h.settings.resourceReady?setTimeout(async()=>{await h.audioElement.play(),h.ensureOnTimeUpdate(!1,!0)},h.settings.wait*1e3):setTimeout(c,200)},h=this;c()}};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||l!==this.currentAudioUrl){this.currentAudioUrl=l,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,r){Ze.default.log("playMediaOverlays()");let i=r?r.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 l,f,u,y,m,_,v,g,h;Ze.default.log("moHighlight: ## "+e);let t=(f=(l=this.publication.Metadata)==null?void 0:l.MediaOverlay)==null?void 0:f.ActiveClass;t||(t=this.settings.color);let r=(u=this.navigator.iframes[0].contentDocument)==null?void 0:u.documentElement.getAttribute("style"),i=r?r.indexOf("readium-night-on")>0:!1,o=r?r.indexOf("readium-sepia-on")>0:!1;if((((y=this.publication.Metadata.Rendition)==null?void 0:y.Layout)??"unknown")!=="fixed"&&(t=i||o?f1:t||f1),this.pid){let c;this.currentLinkIndex===0?c=(m=this.navigator.iframes[0].contentDocument)==null?void 0:m.getElementById(this.pid):c=(_=this.navigator.iframes[1].contentDocument)==null?void 0:_.getElementById(this.pid),c&&c.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 h1=rt($t()),za=class{static async create(e){let t=new this(e.publication);return await t.start(),t}constructor(e){this.publication=e}async stop(){h1.default.log("Timeline module stop")}async start(){this.timelineContainer=Le(document,"#container-view-timeline"),this.positionSlider=Le(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 r;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=""),(r=this.publication.readingOrder)==null||r.forEach(i=>{var _,v;let o=this.publication.getAbsoluteHref(i.Href),s=this.publication.getTOCItemAbsolute(o),l=(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(l??"");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)}we(y,"click",g=>{g.preventDefault(),g.stopPropagation();var h;this.publication.positions||this.navigator.rights.autoGeneratePositions&&this.publication.positions?(h={...this.publication.positions.filter(c=>c.href===i.Href)[0]},h.href=this.publication.getAbsoluteHref(h.href)):h={href:f,locations:{progression:0},type:i.TypeLink,title:i.Title},h1.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 X1=rt(Vo());L();var qw=rt($t());function Gw(n,e){return new Promise(function(t){setTimeout(t.bind(null,e),n)})}var hD=!1;qw.default.setLevel(hD?"trace":"warn",!0);var fh=rt(Ww()),Br=rt($t());L();var oE=rt(I8(),1),bi=rt(YA(),1);L();var XA=[{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 V1(n){return typeof n=="number"?n:n.length===1?n[0]:[n[0],n[n.length-1]]}var fr;(function(n){n[n.Major=0]="Major",n[n.Minor=1]="Minor",n[n.Patch=2]="Patch"})(fr||(fr={}));function QA(n){let e=Array.isArray(n)?n:n.toString().split(".");if(e[0]==="all")return[1/0,0,0];let t=null,r=null,i=[0,0,0];for(let o=0;o<3;o++)if(t=e[o],!(typeof t>"u")){if(r=typeof t=="number"?t:parseInt(t,10),isNaN(r))return null;i[o]=r}return i}function rU(n,e){let t=0,r=[];for(let i=2;i>=0;i--)if(n[i]!==e[i]){t=i;break}for(let i=n[t],o=e[t];i<=o;i++)r.push(n.map((s,l)=>l===t?i:s));return r}function ZA(n,e,t){let[r,i,o]=n,[s,l,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<l?!1:r>=s:v&&o!==f||_&&i!==l?!1:r===s}function nU(n,e){let{ignoreMinor:t,ignorePatch:r,allowZeroSubversions:i}=e,o=t?1:r?2:3;if(i)for(let s=o-1;s>0&&!(n[s]!==0||o===1);s--)o--;return o}function iU(n){return n.reduce((e,t)=>{let[r,i,o]=t.split(/ |-/),s=QA(i);return(s?o?rU(s,QA(o)):[s]:[]).reduce((f,u)=>(u&&f.push({family:r,version:u}),f),e)},[])}function oU(n={}){let{browsers:e,...t}=n,r=(0,oE.default)(e,t);return iU(r)}function sU(n,e,t=0){let r=n.length;for(let i=t;i<r;i++)if(n[i]!==e[i])return!1;return!0}function sE(n){if(n===null||typeof n!="object")return n;let e=Array.isArray(n)?[]:{},t;for(t in n)e[t]=sE(n[t]);return e}function ch(n){return[].concat(...n)}function aU(n){let e=new Map;return n.forEach(({family:t,version:r})=>{let i=e.get(t);if(i){let o=r.join(".");i.every(s=>s.join(".")!==o)&&i.push(r);return}e.set(t,[r])}),e.forEach(t=>{t.sort((r,i)=>{for(let o in r)if(r[o]!==i[o])return r[o]-i[o];return 0})}),e}function uU(n){if(n.length<2)return n;let e=n.length+1,t=[],r=null,i=n[0],o=[i[fr.Major]],s=[i[fr.Minor]],l=[i[fr.Patch]],f=null;for(let u=1;u<e;u++){r=n[u-1],i=n[u]||[];for(let y=fr.Major;y<=fr.Patch;y++){if((y===f||f===null)&&r[y]+1===i[y]&&sU(r,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?l.push(i[fr.Patch]):l=i[fr.Patch];break}if(f===y||r[y]!==i[y]){t.push([V1(o),V1(s),V1(l)]),o=[i[fr.Major]],s=[i[fr.Minor]],l=[i[fr.Patch]],f=null;break}}}return t}function lU(n){return{type:"RegExp",body:n,flags:""}}function Ao(...n){let e=ch(n).filter(Boolean);return e.length===1?e[0]:{type:"Alternative",expressions:e}}function ri(n){return{type:"Char",kind:"simple",value:String(n),codePoint:NaN}}function cU(n){return{type:"Char",kind:"meta",value:n,codePoint:NaN}}function aE(n,e){return{type:"ClassRange",from:n,to:e}}function $1(...n){return{type:"CharacterClass",expressions:ch(n).filter(Boolean)}}function dU(n){return{type:"Quantifier",kind:n,greedy:!0}}function fU(n,e){return{type:"Quantifier",kind:"Range",from:n,to:e,greedy:!0}}function uE(n){return{type:"Group",capturing:!0,expression:n,number:null}}function hU(n,e){return{type:"Repetition",expression:n,quantifier:e}}function pU(...n){let e=ch(n).filter(Boolean);if(e.length===1)return e[0];let t={type:"Disjunction",left:null,right:e.pop()};return e.reduceRight((r,i,o)=>o===0?(r.left=i,r):(r.left={type:"Disjunction",left:null,right:i},r.left),t),t}function dh(...n){let e=pU(...n);return e.type==="Disjunction"?uE(e):e}function ru(){return cU("\\d")}function tu(n=dU("+")){return hU(ru(),n)}function eE(n){return Ao(Array.from(String(n),ri))}function lh(n){if(n.type==="Group"&&n.expression.type==="Repetition"){let{expression:e,quantifier:t}=n.expression;return e.type==="Char"&&e.value==="\\d"&&t.kind==="+"&&t.greedy}return!1}function eu(n,e){return n&&n.type==="Char"?typeof e>"u"||e instanceof RegExp&&e.test(n.value)||String(e)===n.value:!1}function tE(n){if(n.type==="CharacterClass"&&n.expressions.length===1){let[e]=n.expressions;return e.type==="ClassRange"&&eu(e.from,/\d/)&&eu(e.to,/\d/)}return!1}function rE(n){return n.type!=="RegExp"&&n.type!=="ClassRange"&&n.type!=="Quantifier"}function nu(n){return typeof n=="string"?bi.default.parse(n.replace(/^([^/])/,"/$1").replace(/([^/])$/,"$1/")):n instanceof RegExp?bi.default.parse(n):n}function gU(n){return typeof n=="string"?new RegExp(n):new RegExp(bi.default.generate(n.body),n.flags)}function mU(n){return typeof n=="string"?n:n instanceof RegExp?n.toString():bi.default.generate(n)}var yU=["RegExp","Disjunction","Alternative","Assertion","Char","CharacterClass","ClassRange","Backreference","Group","Repetition","Quantifier"];function Y1(n){let{every:e}=n;return e?typeof e=="function"?{"*":e,...n}:yU.reduce((t,r)=>{let i=n[r],o=i?"pre"in i?i.pre:i:null,s=i&&"post"in i?i.post:null;return t[r]={pre(l){return e.pre(l)!==!1&&o?o(l):!0},post(l){return e.post(l)!==!1&&s?s(l):!0}},t},{}):n}function bU(n){let e=bi.default.optimize(nu(mU(n))).getAST();return bi.default.traverse(e,{Group(t){let{parent:r,node:i}=t,{expression:o}=i;i.capturing=!0,(r.type==="RegExp"||o.type!=="Disjunction"&&r.type!=="Repetition"||o.type==="Disjunction"&&r.type==="Disjunction")&&t.replace(t.node.expression)}}),e}function vU(n,e){return eu(n)&&eu(e)&&n.value===e.value?e:eu(n,/\d/)&&tE(e)&&Number(e.expressions[0].from.value)-Number(n.value)===1?{...e,expressions:[{...e.expressions[0],from:n}]}:tE(n)&&eu(e,/\d/)&&Number(e.value)-Number(n.expressions[0].to.value)===1?{...n,expressions:[{...n.expressions[0],to:e}]}:null}function _U(n){return n.reduce((e,t)=>{let r=e[e.length-1];if(r&&t.type==="Alternative"&&r.type==="Alternative"&&t.expressions.length===r.expressions.length){let i=r.expressions.reduceRight((o,s,l)=>{if(!o)return o;let f=vU(s,t.expressions[l]);if(f)o.unshift(f);else return null;return o},[]);i&&(t.expressions=i,e.pop())}return e.push(t),e},[])}function J1(n){return Array.from(n.toString(),Number)}function nE(n,e){let t=n+ +!e;return t===0?ru():t===9?ri("9"):t>9?null:$1(aE(ri(t),ri("9")))}function wU(n){if(n===0)return[tu()];let e=J1(n),t=e.length,r=tu(fU(t+1)),i=t-1;if(n/Math.pow(10,i)===e[0])return[Ao(nE(e[0],!0),Array.from({length:i},ru)),r];let s=e.reduce((l,f,u)=>{let y=t-u-1,m=u===0,_=ri(""),v=e.reduce((g,h,c)=>{if(c<y)g.push(ri(h));else if(_)if(c>y)g.push(ru());else if(_=nE(h,m),_)g.push(_);else return[];return g},[]);return v.length&&l.push(v),l},[]).map(l=>Ao(l));return s.push(r),s}function Za(n,e,t){if(e<n)return null;let r=ri(n),i=ri(e),o=typeof t=="number"&&t>0?Array.from({length:t},()=>ri(0)):[],s=o.length?l=>Ao(o,l):l=>l;return n===e?s(r):n===0&&e===9?s(ru()):e-n===1?s($1(r,i)):s($1(aE(r,i)))}function SU(n,e){let t=[],r=n,i=1;do i*=10,r<i&&(t.push([r,Math.min(i-1,e)]),r=i);while(i<=e);return t}function AU(n,e){let t=n.length;if(t!==e.length||n[0]!==e[0])return null;let r=n[0].toString(),i=0,o=0,s="",l="";for(let f=1;f<t;f++)i=n[f],o=e[f],i===o?r+=i:(s+=i,l+=o);return[r,parseInt(s,10),parseInt(l,10)]}function K1(n,e,t=0){let r=J1(n),i=r.length;if(n<10&&e<10||n===e){let y=t-i;return[Za(n,e,y)]}let o=J1(e);if(i!==o.length){let y=SU(n,e);return ch(y.map(([_,v])=>K1(_,v,t)))}let s=AU(r,o);if(Array.isArray(s)){let[y,m,_]=s,v=i-y.length,g=K1(m,_,v);return[Ao(Array.from(y,ri),dh(g))]}let l=Array.from({length:i-1}),f=Za(r[0]+1,o[0]-1),u=[...l.map((y,m)=>{let _=i-m-1,v=+(m>0);return Ao(r.map((g,h)=>h<_?ri(g):h>_?Za(0,9):Za(g+v,9)))}),...f?[Ao(f,Array.from({length:i-1},()=>ru()))]:[],...l.map((y,m)=>{let _=i-m-1,v=+(m>0);return Ao(o.map((g,h)=>h<_?ri(g):h>_?Za(0,9):Za(0,g-v)))})];return _U(u)}function iE(n,e=1/0){if(n===1/0)return tu();let t=e===1/0?wU(n):K1(n,e);return dh(t)}function EU(n,e,t,r){let i={...r,allowHigherVersions:!0},o=f=>ZA(f,n,i),s=f=>ZA(e,f,i),l=n&&e?f=>o(f)&&s(f):n?o:e?s:()=>!0;return t.filter(l)}function CU(n,e,t=XA){let r=[],i="",o=!1;return t.forEach(s=>{let l=n.get(s.family);if(!l)return;let{version:f,minVersion:u,maxVersion:y}=s;f&&(u=f,y=f);let m=EU(u,y,l,e);m.length&&(i===s.family&&o&&(f=void 0,u=void 0,y=void 0,m=l,r.pop()),r.push({...s,version:f,minVersion:u,maxVersion:y,requestVersions:l,matchedVersions:m})),o=!f&&!u&&!y,i=s.family}),r}function xU(n){let e=n.map(({regexAst:r})=>uE(r.body)),t=bU(lU(dh(e)));return gU(t)}function TU(n){let e=nu(n),t=0;return bi.default.traverse(e,{Group(r){lh(r.node)&&t++}}),t}function PU(n,e,t){let r=nu(n),i=typeof t=="number"&&t<e.length?e.slice(0,t):e.slice();return bi.default.traverse(r,Y1({every(){return!!i.length},Group(o){return lh(o.node)&&i.length?(r===o.node?r=i.shift():o.replace(i.shift()),!1):!0}})),r}function lE(n,e){let t=nu(n),r=Math.min(TU(t),e||1/0),i=[],o=0,s=!1;return bi.default.traverse(t,Y1({every:{pre({node:l,parent:f}){return l===t?!0:rE(l)?(f===t&&(s=!1),o<r):!1},post({node:l,parent:f}){l!==t&&f===t&&rE(l)&&(s||o>0&&o<r)&&i.push(l)}},Group(l){return lh(l.node)&&o<r?(s=!0,o++,!1):!0}})),i.length===1&&!lh(i[0])?lE(i[0],r):i}function OU(n,e){let{ignoreMinor:t,ignorePatch:r,allowHigherVersions:i}=e,o=n[0]===1/0?0:t?1:r?2:3;if(i){let l=[],f=!0,u=0,y=0,m=_=>(v,g)=>g>=o?tu():(y=Array.isArray(v)?v[0]:v,g<_?eE(y):g>_?tu():iE(y+u));for(let _=o-1;_>=0;_--)f&&!n[_]||(f=!1,l.push(n.map(m(_))),u=1);return l}return[n.map((l,f)=>f>=o?tu():Array.isArray(l)?iE(l[0],l[1]):eE(l))]}function MU(n,e,t){let{allowHigherVersions:r}=t,i=nu(n),o=r&&e.length?[e[0]]:e,s=o.reduce((u,y)=>Math.max(u,nU(y,t)),1),l=lE(i,s),f=dh(...o.map(u=>OU(u,t).map(y=>PU(Ao(sE(l)),y,s))));return bi.default.traverse(i,Y1({every(u){return l.length?(u.node===l[0]&&(l.length===1?u.replace(f):u.remove(),l.shift()),!0):!1}})),i}function kU(n,e){return n.map(({regex:t,version:r,maxVersion:i,matchedVersions:o,...s})=>{let l=nu(t);return r||(l=MU(l,uU(o),{...e,allowHigherVersions:!i&&e.allowHigherVersions})),{regex:null,sourceRegex:t,regexAst:l,version:r,maxVersion:i,matchedVersions:o,...s}})}var RU={ignoreMinor:!1,ignorePatch:!0,allowZeroSubversions:!1,allowHigherVersions:!1};function LU(n={}){let e={...RU,...n},t=oU(e),r=aU(t),i=CU(r,e);return kU(i,e)}function cE(n={}){return xU(LU(n))}var Bs=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,fh.addListener)(r=>{var i;r&&(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,fh.launch)(),await Gw(e.detectInspectInitDelay??100)}static isCurrentBrowserSupported(e){if(!e.enforceSupportedBrowsers)return!0;let t=[];return(e.supportedBrowsers??[]).forEach(i=>{t.push("last 1 "+i+" version")}),cE({browsers:t,allowHigherVersions:!0}).test(navigator.userAgent)}async start(){var t;if((t=this.properties)!=null&&t.enableObfuscation){this.wrapper=yt(document,"#iframe-wrapper"),this.securityContainer=Le(document,"#container-view-security");var e=this;this.mutationObserver=new MutationObserver(function(r){r.forEach(function(i){Br.default.log(i.type),e.isHacked=!0})})}}async stop(){var e,t,r,i,o,s,l,f;if(Br.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((r=this.properties)!=null&&r.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)}(l=this.properties)!=null&&l.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 r=co(t.contentDocument,"body");this.rects=this.findRects(r),this.rects.forEach(i=>this.toggleRect(i,this.securityContainer,this.isHacked))}}}setupEvents(){var e,t,r,i,o,s,l,f,u,y,m,_,v,g,h;if((e=this.properties)!=null&&e.disableKeys){we(this.navigator.mainElement,"keydown",this.disableSave),we(this.navigator.headerMenu,"keydown",this.disableSave);for(let c of this.navigator.iframes)we(c,"keydown",this.disableSave),we(c.ownerDocument,"keydown",this.disableSave),we(c.contentDocument,"keydown",this.disableSave),we(c.contentWindow,"keydown",this.disableSave),we((t=c.contentWindow)==null?void 0:t.document,"keydown",this.disableSave);we(window,"keydown",this.disableSave),we(document,"keydown",this.disableSave)}if((r=this.properties)!=null&&r.disableCopy){we(this.navigator.mainElement,"copy",this.preventCopy),we(this.navigator.headerMenu,"copy",this.preventCopy);for(let c of this.navigator.iframes)we(c,"copy",this.preventCopy),we(c.ownerDocument,"copy",this.preventCopy),we(c.contentDocument,"copy",this.preventCopy),we(c.contentWindow,"copy",this.preventCopy),we((i=c.contentWindow)==null?void 0:i.document,"copy",this.preventCopy);we(window,"copy",this.preventCopy),we(document,"copy",this.preventCopy),we(this.navigator.mainElement,"cut",this.preventCopy),we(this.navigator.headerMenu,"cut",this.preventCopy);for(let c of this.navigator.iframes)we(c,"cut",this.preventCopy),we(c.ownerDocument,"cut",this.preventCopy),we(c.contentDocument,"cut",this.preventCopy),we(c.contentWindow,"cut",this.preventCopy),we((o=c.contentWindow)==null?void 0:o.document,"cut",this.preventCopy);we(window,"cut",this.preventCopy),we(document,"cut",this.preventCopy),we(this.navigator.mainElement,"keydown",this.preventCopyKey),we(this.navigator.headerMenu,"keydown",this.preventCopyKey);for(let c of this.navigator.iframes)we(c,"keydown",this.preventCopyKey),we(c.ownerDocument,"keydown",this.preventCopyKey),we(c.contentDocument,"keydown",this.preventCopyKey),we(c.contentWindow,"keydown",this.preventCopyKey),we((s=c.contentWindow)==null?void 0:s.document,"keydown",this.preventCopyKey);we(window,"keydown",this.preventCopyKey),we(document,"keydown",this.preventCopyKey)}else if((l=this.properties)!=null&&l.canCopy){we(this.navigator.mainElement,"copy",this.restrictCopy.bind(this)),we(this.navigator.headerMenu,"copy",this.restrictCopy.bind(this));for(let c of this.navigator.iframes)we(c,"copy",this.restrictCopy),we(c.ownerDocument,"copy",this.restrictCopy.bind(this)),we(c.contentDocument,"copy",this.restrictCopy.bind(this)),we(c.contentWindow,"copy",this.restrictCopy.bind(this)),we((f=c.contentWindow)==null?void 0:f.document,"copy",this.restrictCopy.bind(this));we(window,"copy",this.restrictCopy.bind(this)),we(document,"copy",this.restrictCopy.bind(this)),we(this.navigator.mainElement,"cut",this.restrictCopy.bind(this)),we(this.navigator.headerMenu,"cut",this.restrictCopy.bind(this));for(let c of this.navigator.iframes)we(c,"cut",this.restrictCopy.bind(this)),we(c.ownerDocument,"cut",this.restrictCopy.bind(this)),we(c.contentDocument,"cut",this.restrictCopy.bind(this)),we(c.contentWindow,"cut",this.restrictCopy.bind(this)),we((u=c.contentWindow)==null?void 0:u.document,"cut",this.restrictCopy.bind(this));we(window,"cut",this.restrictCopy.bind(this)),we(document,"cut",this.restrictCopy.bind(this)),we(this.navigator.mainElement,"keydown",this.restrictCopyKey.bind(this)),we(this.navigator.headerMenu,"keydown",this.restrictCopyKey.bind(this));for(let c of this.navigator.iframes)we(c,"keydown",this.restrictCopyKey.bind(this)),we(c.ownerDocument,"keydown",this.restrictCopyKey.bind(this)),we(c.contentDocument,"keydown",this.restrictCopyKey.bind(this)),we(c.contentWindow,"keydown",this.restrictCopyKey.bind(this)),we((y=c.contentWindow)==null?void 0:y.document,"keydown",this.restrictCopyKey.bind(this));we(window,"keydown",this.restrictCopyKey.bind(this)),we(document,"keydown",this.restrictCopyKey.bind(this))}if((m=this.properties)!=null&&m.disablePrint){we(this.navigator.mainElement,"beforeprint",this.beforePrint),we(this.navigator.headerMenu,"beforeprint",this.beforePrint);for(let c of this.navigator.iframes)we(c,"beforeprint",this.beforePrint.bind(this)),we(c.ownerDocument,"beforeprint",this.beforePrint.bind(this)),we(c.contentDocument,"beforeprint",this.beforePrint.bind(this)),we(c.contentWindow,"beforeprint",this.beforePrint.bind(this)),we((_=c.contentWindow)==null?void 0:_.document,"beforeprint",this.beforePrint.bind(this));we(window,"beforeprint",this.beforePrint.bind(this)),we(document,"beforeprint",this.beforePrint.bind(this)),we(this.navigator.mainElement,"afterprint",this.afterPrint),we(this.navigator.headerMenu,"afterprint",this.afterPrint);for(let c of this.navigator.iframes)we(c,"afterprint",this.afterPrint.bind(this)),we(c.ownerDocument,"afterprint",this.afterPrint.bind(this)),we(c.contentDocument,"afterprint",this.afterPrint.bind(this)),we(c.contentWindow,"afterprint",this.afterPrint.bind(this)),we((v=c.contentWindow)==null?void 0:v.document,"afterprint",this.afterPrint.bind(this));we(window,"afterprint",this.afterPrint.bind(this)),we(document,"afterprint",this.afterPrint.bind(this))}if((g=this.properties)!=null&&g.disableContextMenu){we(this.navigator.mainElement,"contextmenu",this.disableContext),we(this.navigator.headerMenu,"contextmenu",this.disableContext);for(let c of this.navigator.iframes)we(c,"contextmenu",this.disableContext),we(c.ownerDocument,"contextmenu",this.disableContext),we(c.contentDocument,"contextmenu",this.disableContext),we(c.contentWindow,"contextmenu",this.disableContext),we((h=c.contentWindow)==null?void 0:h.document,"contextmenu",this.disableContext);we(window,"contextmenu",this.disableContext),we(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(e){var t;if((t=this.properties)!=null&&t.enableObfuscation)return new Promise(async r=>{if(await document.fonts.ready,e.contentDocument){let i=co(e.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,we(this.wrapper,"scroll",this.handleScroll.bind(this))),r()},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,X1.default)(()=>{this.calcRects(this.rects),this.rects!==void 0&&this.rects.forEach(r=>this.toggleRect(r,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 Br.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 r,i,o,s;if(this.citation)return;Br.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},_=l.navigator.iframes[0].contentDocument;if(_)return Cr(y,_,m)},l=this,u=ji(t,f);if(u===void 0){let y=this.navigator.iframes[0].contentDocument;u=(i=(r=this.navigator.annotationModule)==null?void 0:r.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,r,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},_=l.navigator.iframes[0].contentDocument;if(_)return Cr(y,_,m)},l=this,u=ji(s,f);if(u===void 0){let y=this.navigator.iframes[0].contentDocument;u=(r=(t=this.navigator.annotationModule)==null?void 0:t.annotator)==null?void 0:r.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 r=this.createElementForExecCommand(e);this.selectContent(r);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),document.execCommand("copy",!1)}catch{}document.body.removeChild(r)}}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 r=window.getSelection();r==null||r.removeAllRanges(),r==null||r.addRange(t)}beforePrint(e){return Br.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 Br.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 r;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=(r=i.contentDocument)==null?void 0:r.querySelectorAll("a");o==null||o.forEach(s=>{let l=s.getAttribute("data-href"),f=s.getAttribute("href");!l&&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 l=s.getAttribute("data-href");l&&s.setAttribute("href",l),s.removeEventListener("click",t)})}}preventDrag(e){var i,o,s,l,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;",r=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",r),(s=u.contentDocument)==null||s.body.setAttribute("style",y+t)):((l=u.contentDocument)==null||l.body.removeEventListener("dragstart",r),(f=u.contentDocument)==null||f.body.setAttribute("style",y.replace(t,"")))}}recalculate(e=0){return new Promise(t=>{var r;if((r=this.properties)!=null&&r.enableObfuscation){let i=(0,X1.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:r,height:i,left:o,width:s}=this.measureTextNode(t.node);t.top=r,t.height=i,t.width=s,t.left=o}catch(r){Br.default.log("error "+r),Br.default.log(t),Br.default.log(t.node),Br.default.log("scrambledTextContent "+t.scrambledTextContent),Br.default.log("textContent "+t.textContent),Br.default.log("isObfuscated "+t.isObfuscated)}})}deactivateRect(e,t,r){this.isBeingHacked(t)||r?(e.node.textContent=e.scrambledTextContent,e.isObfuscated=!0):(e.node.textContent=e.textContent,e.isObfuscated=!1)}toggleRect(e,t,r){let i=this.isOutsideViewport(e),o=this.isBeingHacked(t);e.isObfuscated&&!i&&!o&&!r&&(e.node.textContent=e.textContent,e.isObfuscated=!1),!e.isObfuscated&&(i||o||r)&&(e.node.textContent=e.scrambledTextContent,e.isObfuscated=!0)}findRects(e){return this.findTextNodes(e).map(r=>{var y,m,_,v;let{top:i,height:o,left:s,width:l}=this.measureTextNode(r),f=r.parentElement&&((y=this.properties)!=null&&y.excludeNodes&&((m=this.properties)==null?void 0:m.excludeNodes.indexOf(r.parentElement.nodeName.toLowerCase()))>-1||((_=r.parentElement)==null?void 0:_.nodeName.toLowerCase())==="option"||((v=r.parentElement)==null?void 0:v.nodeName.toLowerCase())==="script")?r.textContent:this.obfuscateText(r.textContent??"");return{top:i,height:o,width:l,left:s,node:r,textContent:r.textContent??"",scrambledTextContent:f??"",isObfuscated:!1}})}obfuscateText(e){return this.scramble(e,!0)}measureTextNode(e){try{let t=document.createRange();t.selectNode(e);let r=t.getBoundingClientRect();return t.detach(),r}catch(t){Br.default.log("measureTextNode "+t),Br.default.log("measureTextNode "+e),Br.default.log(e.textContent)}}isBeingHacked(e){return e.style.animation||e.style.transition||e.style.position||e.hasAttribute("style")?(Br.default.log("content being hacked"),!0):!1}isOutsideViewport(e){let t=this.wrapper.scrollLeft,r=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),l=s+this.wrapper.clientHeight+(e.node.parentElement?parseInt(getComputedStyle(e.node.parentElement).lineHeight.replace("px","")):10),f=o<s,u=e.top>l,y=i<t-window.innerWidth,m=e.left>r+window.innerWidth;return f||u||y||m}findTextNodes(e,t=[]){var i;let r=e.firstChild;for(;r;)r.nodeType===1&&this.findTextNodes(r,t),r.nodeType===3&&(i=r.textContent)!=null&&i.trim()&&t.push(r),r=r.nextSibling;return t}scramble(e,t=!1,r=!1){var i=e.split(" ");function o(s){for(var l=s.length,f,u;l>0;)u=Math.floor(Math.random()*l),l--,f=s[l],s[l]=s[u],s[u]=f;return s}return t&&(i=i.map(function(s){return s.includes("-")?s:o(s.split("")).join("")})),r?o(i).join(" "):i.join(" ")}};L();var mE=rt(fE());L();var hh=n=>n.replace(/\n/g," ").replace(/\s\s+/g," "),IU=n=>hh(n).trim(),pE=/[\\^$.*+?()[\]{}|]/g,NU=RegExp(pE.source);function hE(n){return n&&NU.test(n)?n.replace(pE,"\\$&"):n||""}var ph=0,BU=()=>()=>Number.isSafeInteger(++ph)?ph:ph=1,gE=()=>{ph=0},DU=BU(),FU=n=>e=>{try{return Cr(e,n,Jo)}catch(t){return console.error("uniqueCssSelector:",t),""}};async function ts(n,e,t,r,i=!1){var v,g,h;if(!e)return[];let o=(v=e.body)==null?void 0:v.textContent;if(!o)return[];if(n=IU(n),!n.length)return[];let s=e.createNodeIterator(e.body,NodeFilter.SHOW_TEXT,{acceptNode:c=>NodeFilter.FILTER_ACCEPT}),l=new RegExp(hE(n).replace(/ /g,"\\s+"),"gim");i&&(l=new RegExp("\\b"+hE(n).replace(/ /g,"\\s+")+"\\b","gim"));let f=[],u=100,y=30,m=0,_;for(;_=l.exec(o);){let c=Math.max(0,_.index-u),p=Math.min(u,_.index),w=hh(o.substr(c,p));w=w.substr(w.length-y),c=l.lastIndex,p=Math.min(u,o.length-c);let A=hh(o.substr(c,p)).substr(0,y),E=new Range,b=_.index;for(;m<=b;){let R=s.nextNode();R&&R.nodeValue&&(m+=R.nodeValue.length)}let C=s.referenceNode.nodeValue?((g=s.referenceNode.nodeValue)==null?void 0:g.length)-(m-b):0;for(E.setStart(s.referenceNode,C),b=_.index+_[0].length;m<=b;){let R=s.nextNode(),B=R==null?void 0:R.nodeValue;B&&(m+=B.length)}C=s.referenceNode.nodeValue?((h=s.referenceNode.nodeValue)==null?void 0:h.length)-(m-b):0,E.setEnd(s.referenceNode,C),e.getCssSelector||(e.getCssSelector=FU(e));let k=mo(E,e.getCssSelector);k&&f.push({textMatch:hh(_[0]),textBefore:w,textAfter:A,rangeInfo:k,href:t,title:r,uuid:DU().toString()})}return f}var yE=rt($t()),iu=class{constructor(e,t,r,i,o){this.currentChapterSearchResult=[];this.bookSearchResult=[];this.currentSearchHighlights=[];this.headerMenu=o,this.publication=e,this.properties=t,this.api=i,this.highlighter=r}static async create(e){let t=new this(e.publication,e,e.highlighter,e.api,e.headerMenu);return await t.start(),t}async stop(){yE.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=Le(this.headerMenu,"#searchInput"),we(this.searchInput,"keypress",this.handleSearch.bind(this)),this.searchGo=Le(this.headerMenu,"#searchGo"),we(this.searchGo,"click",this.handleSearch.bind(this));var e=Le(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,r=this.searchInput.value;let i=this.navigator.currentChapterLink.href,o=this.publication.getSpineItem(i);if(this.headerMenu)var s=Le(document,"#searchResultChapter");t.currentChapterSearchResult=[],t.currentSearchHighlights=[];var l=[];await this.searchAndPaintChapter(r,e,async u=>{var y;l=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(l,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 c=document.createElement("a"),p=y.data[h];c.className="collection-item",c.href=(o==null?void 0:o.Href)??"",c.innerHTML="..."+p.textBefore+"<mark>"+p.textMatch+"</mark>"+p.textAfter+"...",we(c,"click",w=>{w.preventDefault(),w.stopPropagation(),t.jumpToMark(h+u*10-10)}),s.appendChild(c)}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",we(v,"click",c=>{c.preventDefault(),c.stopPropagation(),f(h)})}_.appendChild(v);for(let h=1;h<=y.total_pages;h++){let c,p=document.createElement("li");p.className="waves-effect",h===y.page&&(p.className="active",c=p),p.innerHTML='<a href="#!">'+h+"</a>",we(p,"click",w=>{w.preventDefault(),w.stopPropagation(),c&&(c.className="waves-effect"),p.className="active",c=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",we(g,"click",c=>{c.preventDefault(),c.stopPropagation(),f(h)})}_.appendChild(g),m.appendChild(_),s.appendChild(m)}}}async searchAndPaintChapter(e,t=0,r){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 l=0;if(o){let y=this.navigator.iframes[0].contentDocument;y&&o&&ts(e,y,o.Href,o.Title).then(m=>{m.forEach(_=>{let v={rangeInfo:_.rangeInfo};setTimeout(()=>{var h,c;let g;l===t?(g=this.createSearchHighlight(v,(h=this.properties)==null?void 0:h.current),this.jumpToMark(t)):g=this.createSearchHighlight(v,(c=this.properties)==null?void 0:c.color),_.highlight=g,s.push(_),this.currentChapterSearchResult.push(_),this.currentSearchHighlights.push(g),l++},500)}),setTimeout(()=>{r(s)},500)})}}createSearchHighlight(e,t){var o;try{var r=t;Jt.isHexColor(r)&&(r=Jt.hexToRgbChannels(r));let s=`${e.rangeInfo.startContainerElementCssSelector}${e.rangeInfo.startContainerChildTextNodeIndex}${e.rangeInfo.startOffset}${e.rangeInfo.endContainerElementCssSelector}${e.rangeInfo.endContainerChildTextNodeIndex}${e.rangeInfo.endOffset}`,f="R2_SEARCH_"+mE.SHA256.hash(s);var i=!1;let u={color:r||Ls,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=[],gE(),await this.searchAndPaintChapter(e,0,async()=>{var r;this.navigator.rights.enableContentProtection&&((r=this.navigator.contentProtectionModule)==null||r.recalculate(200))}),t?(await this.searchBook(e),await this.searchChapter(e)):(await this.searchChapter(e),await this.searchBook(e))}async goToSearchID(e,t,r){var i=t,o;let s=this.navigator.currentChapterLink.href;var l=this.publication.getAbsoluteHref(e);let f=this.bookSearchResult.filter(u=>u.href===e);if(r?(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===l)this.jumpToMark(i);else{let y={href:l,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,r){var i=t,o;let s=this.navigator.currentChapterLink.href;var l=this.publication.getAbsoluteHref(e);let f=this.bookSearchResult.filter(u=>u.href===e);if(r?o=this.currentChapterSearchResult[i]:o=f[i],o!==void 0)if(s===l)this.jumpToMark(i);else{let y={href:l,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 r=Le(document,"#searchResultBook");i(1);async function i(s){r.innerHTML="";var l,f=await e.searchBook(t);if(l=e.paginate(f,s,10),l.total===0){let u=document.createElement("a");u.className="collection-item",u.innerHTML="nothing found",r.appendChild(u)}else{o(l.data,g=>g.href).forEach(g=>{let h=document.createElement("div");if(h.style.marginBottom="10px",g[0].title){let c=document.createElement("span");c.className="collection-item",c.style.display="block",c.innerHTML=g[0].title,h.appendChild(c)}r.appendChild(h),g.forEach(c=>{let p=document.createElement("a");p.className="collection-item";var w=e.publication.getAbsoluteHref(c.href);p.innerHTML="..."+c.textBefore+"<mark>"+c.textMatch+"</mark>"+c.textAfter+"...",we(p,"click",A=>{A.preventDefault(),A.stopPropagation();let b=f.filter(k=>k.href===c.href).findIndex(k=>k===c);if(e.navigator.currentChapterLink.href===w)e.jumpToMark(b);else{let R={href:w,locations:{progression:0},title:"title"};e.navigator.navigate(R),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>',l.pre_page!=null){let g=l.pre_page;_.className="waves-effect",we(_,"click",h=>{h.preventDefault(),h.stopPropagation(),i(g)})}m.appendChild(_);for(let g=1;g<=l.total_pages;g++){let h,c=document.createElement("li");c.className="waves-effect",g===l.page&&(c.className="active",h=c),c.innerHTML='<a href="#!">'+g+"</a>",we(c,"click",p=>{p.preventDefault(),p.stopPropagation(),h&&(h.className="waves-effect"),c.className="active",h=c,i(g)}),m.appendChild(c)}let v=document.createElement("li");if(v.className="disabled",v.innerHTML='<a href="#!"> > </a>',l.next_page!=null){let g=l.next_page;v.className="waves-effect",we(v,"click",h=>{h.preventDefault(),h.stopPropagation(),i(g)})}m.appendChild(v),y.appendChild(m),r.appendChild(y)}}function o(s,l){let f=new Map;return s.forEach(u=>{let y=l(u),m=f.get(y);m?m.push(u):f.set(y,[u])}),Array.from(f.values())}}async searchBook(e){var r,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:""),l=this.publication.getTOCItem(s);if(l===void 0&&this.publication.readingOrder&&(l=this.publication.readingOrder[o]),l){let f=this.publication.getAbsoluteHref(l.Href);(r=this.navigator.api)!=null&&r.getContent?await((i=this.navigator.api)==null?void 0:i.getContent(f).then(u=>{let m=new DOMParser().parseFromString(u,"application/xhtml+xml");l&&ts(e,m,l.Href,l.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");l&&ts(e,m,l.Href,l.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),r=t.length,i=new Uint8Array(r);for(let s=0;s<r;s++)i[s]=t.charCodeAt(s);return new TextDecoder().decode(i)}async searchChapter(e){var o,s;let t=[],r=this.publication.getAbsoluteHref(this.publication.readingOrder[this.navigator.currentResource()??0].Href),i=this.publication.getTOCItem(r);if(i===null&&(i=this.publication.readingOrder[this.navigator.currentResource()??0]),i){let l=this.publication.getAbsoluteHref(i.Href);(o=this.navigator.api)!=null&&o.getContent?await((s=this.navigator.api)==null?void 0:s.getContent(l).then(f=>{let y=new DOMParser().parseFromString(f,"application/xhtml+xml");i&&ts(e,y,i.Href,i.Title).then(m=>{m.forEach(_=>{t.push(_)})})})):await fetch(l,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&&ts(e,y,i.Href,i.Title).then(_=>{_.forEach(v=>{t.push(v)})})})}return t}drawSearch(){setTimeout(()=>{this.currentSearchHighlights=[],this.currentChapterSearchResult.forEach(e=>{var r,i;let t={rangeInfo:e.rangeInfo};if((r=this.properties)!=null&&r.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(l=>{var u;var f=(u=this.properties)==null?void 0:u.color;Jt.isHexColor(f)&&(f=Jt.hexToRgbChannels(f)),l.color=f});var r=(i=this.properties)==null?void 0:i.current;Jt.isHexColor(r)&&(r=Jt.hexToRgbChannels(r)),t.highlight.color=r,(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,r){let i=t||1,o=r||10,s=(i-1)*o,l=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:l}}};L();var mn=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 at=sr,gh=class{constructor(e,t,r){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=r,this.initialise()}static create(e){let t=new this(e.store,e.api,e.headerMenu);if(e.initialTTSSettings){let r=e.initialTTSSettings;r!=null&&r.rate&&(t.rate=r.rate,mn.default.log(t.rate)),r!=null&&r.pitch&&(t.pitch=r.pitch,mn.default.log(t.pitch)),r!=null&&r.volume&&(t.volume=r.volume,mn.default.log(t.volume)),r!=null&&r.color&&(t.color=r.color,mn.default.log(t.color)),r!=null&&r.autoScroll&&(t.autoScroll=r.autoScroll,mn.default.log(t.autoScroll)),r!=null&&r.voice&&(t.voice=r.voice,mn.default.log(t.voice))}return t.initializeSelections(),t}stop(){mn.default.log("tts settings stop")}initialise(){this.autoScroll=this.getProperty(at.AUTO_SCROLL_KEY)!=null?this.getProperty(at.AUTO_SCROLL_KEY).value:this.autoScroll,this.rate=this.getProperty(at.RATE_KEY)!=null?this.getProperty(at.RATE_KEY).value:this.rate,this.pitch=this.getProperty(at.PITCH_KEY)!=null?this.getProperty(at.PITCH_KEY).value:this.pitch,this.volume=this.getProperty(at.VOLUME_KEY)!=null?this.getProperty(at.VOLUME_KEY).value:this.volume,this.color=this.getProperty(at.COLOR_KEY)!=null?this.getProperty(at.COLOR_KEY).value:this.color,this.voice=this.getProperty(at.VOICE_REF)!=null?this.getProperty(at.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=Le(this.headerMenu,"#container-view-tts-settings"))}setControls(){this.settingsView&&this.renderControls(this.settingsView)}renderControls(e){this.headerMenu&&(this.speechRate=Le(this.headerMenu,"#speechRate")),this.headerMenu&&(this.speechPitch=Le(this.headerMenu,"#speechPitch")),this.headerMenu&&(this.speechVolume=Le(this.headerMenu,"#speechVolume")),this.headerMenu&&(this.speechAutoScroll=Le(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),we(Le(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,r,i,o,s,l,f,u;var e={rate:(t=this.userProperties.getByRef(at.RATE_REF))==null?void 0:t.value,pitch:(r=this.userProperties.getByRef(at.PITCH_REF))==null?void 0:r.value,volume:(i=this.userProperties.getByRef(at.VOLUME_REF))==null?void 0:i.value,voice:(o=this.userProperties.getByRef(at.VOLUME_REF))==null?void 0:o.value,color:(s=this.userProperties.getByRef(at.COLOR_REF))==null?void 0:s.value,autoScroll:(l=this.userProperties.getByRef(at.AUTO_SCROLL_REF))==null?void 0:l.value};this.applyTTSSettings(e),(f=this.api)!=null&&f.updateSettings&&((u=this.api)==null||u.updateSettings(e).then(async y=>{mn.default.log("api updated tts settings",y)}))}getTTSSettings(){var e=new Li;return e.addSwitchable("tts-auto-scroll-off","tts-auto-scroll-on",this.autoScroll,at.AUTO_SCROLL_REF,at.AUTO_SCROLL_KEY),e.addIncremental(this.rate,.1,10,.1,"",at.RATE_REF,at.RATE_KEY),e.addIncremental(this.pitch,.1,2,.1,"",at.PITCH_REF,at.PITCH_KEY),e.addIncremental(this.volume,.1,1,.1,"",at.VOLUME_REF,at.VOLUME_KEY),e.addStringable(this.color,at.COLOR_REF,at.COLOR_KEY),e.addJSONable(JSON.stringify(this.voice),at.VOICE_REF,at.VOICE_KEY),e}saveProperty(e){let t=this.store.get(this.TTSSETTINGS);if(t){let r=JSON.parse(t);r=r.filter(i=>i.name!==e.name),r.push(e),this.store.set(this.TTSSETTINGS,JSON.stringify(r))}else{let r=[];r.push(e),this.store.set(this.TTSSETTINGS,JSON.stringify(r))}return e}getProperty(e){let t=this.store.get(this.TTSSETTINGS);if(t){let r=JSON.parse(t);return r=r.filter(i=>i.name===e),r.length===0?void 0:r[0]}}resetTTSSettings(){this.store.remove(this.TTSSETTINGS),this.reset(),this.settingsChangeCallback(),this.restartCallback()}applyTTSSettings(e){if(e.rate){mn.default.log("rate "+this.rate),this.rate=e.rate;let t=this.userProperties.getByRef(at.RATE_REF);t&&(t.value=this.rate,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.pitch){mn.default.log("pitch "+this.pitch),this.pitch=e.pitch;let t=this.userProperties.getByRef(at.PITCH_REF);t&&(t.value=this.pitch,this.saveProperty(t)),this.settingsChangeCallback(),this.restartCallback()}if(e.volume){mn.default.log("volume "+this.volume),this.volume=e.volume;let t=this.userProperties.getByRef(at.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(at.COLOR_REF);t&&(t.value=this.color,this.saveProperty(t)),this.settingsChangeCallback()}if(e.autoScroll!==void 0){mn.default.log("autoScroll "+this.autoScroll),this.autoScroll=e.autoScroll;let t=this.userProperties.getByRef(at.AUTO_SCROLL_REF);t&&(t.value=this.autoScroll,this.saveProperty(t)),this.settingsChangeCallback()}if(e.voice){mn.default.log("voice "+this.voice),this.voice=e.voice;let t=this.userProperties.getByRef(at.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,r=e.indexOf(":")!==-1?e.slice(e.indexOf(":")+1):e;t!==void 0&&r!==void 0?this.applyTTSSettings({voice:{usePublication:!0,name:t,lang:r}}):r!==void 0&&t===void 0&&this.applyTTSSettings({voice:{usePublication:!0,lang:r}})}increase(e){if(e==="rate"){this.userProperties.getByRef(at.RATE_REF).increment();let t=this.userProperties.getByRef(at.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="pitch"){this.userProperties.getByRef(at.PITCH_REF).increment();let t=this.userProperties.getByRef(at.PITCH_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="volume"){this.userProperties.getByRef(at.VOLUME_REF).increment();let t=this.userProperties.getByRef(at.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}}decrease(e){if(e==="rate"){this.userProperties.getByRef(at.RATE_REF).decrement();let t=this.userProperties.getByRef(at.RATE_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="pitch"){this.userProperties.getByRef(at.PITCH_REF).decrement();let t=this.userProperties.getByRef(at.PITCH_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}else if(e==="volume"){this.userProperties.getByRef(at.VOLUME_REF).decrement();let t=this.userProperties.getByRef(at.VOLUME_REF);t&&this.storeProperty(t),this.settingsChangeCallback(),this.restartCallback()}}};L();L();var mh=`${mi.loading}`,bE=`
|
|
83
83
|
<span>
|
|
84
84
|
${mi.error}
|
|
85
85
|
</span>
|