@d-i-t-a/reader 2.4.6 → 2.4.8

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/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=>{Tf.default.log("R2 Click Handler");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 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.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}">
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}">
@@ -86,7 +86,7 @@ function print() { __p += __j.call(arguments, '') }
86
86
  <span>There was an error loading this page.</span>
87
87
  <button class="go-back">Go back</button>
88
88
  <button class="try-again">Try again</button>
89
- `;var _h=rt(Vo());L();var Eo=class Eo{constructor(e){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=e=>{let t=null,r=null,i=this;e&&(e.addEventListener("touchstart",function(o){o.changedTouches.length===1&&(t=o)},!1),e.addEventListener("touchend",function(o){if(o.changedTouches.length!==1||!t)return;let s=t.changedTouches[0],l=o.changedTouches[0];if(!s)return;let f=window.devicePixelRatio,u=(s.clientX-l.clientX)/f,y=(s.clientY-l.clientY)/f;if(Math.abs(u)<Eo.TAP_TOLERANCE&&Math.abs(y)<Eo.TAP_TOLERANCE){if(r){t=null,r=null;return}if(o.timeStamp-t.timeStamp>Eo.LONG_PRESS_MS){t=null,r=null;return}t=null,r=o;return}if(r=null,o.timeStamp-t.timeStamp>Eo.SLOW_SWIPE_MS){t=null;return}let m=(s.clientY-l.clientY)/(s.clientX-l.clientX);if(Math.abs(m)>.5){t=null;return}u<0?i.onBackwardSwipe(o):i.onForwardSwipe(o),t=null},!1))};this.navigator=e}};Eo.TAP_TOLERANCE=10,Eo.LONG_PRESS_MS=500,Eo.SLOW_SWIPE_MS=500;var Hl=Eo;L();var Ul=class{constructor(e){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.onKeydown=()=>{};this.setupEvents=e=>{e&&(this.focusin(e),this.keydown(e))};this.removeEvents=e=>{if(e){let t=this;e.removeEventListener("focusin",this.onFocusIn(t),!0),e.removeEventListener("keydown",this.onKeyDown(t),!1)}};this.focusin=e=>{let t=this;e.addEventListener("focusin",this.onFocusIn(t),!0)};this.keydown=e=>{let t=this;this.navigator.rights.customKeyboardEvents||e.addEventListener("keydown",this.onKeyDown(t),!1)};this.handlers={};this.navigator=e,this.rtl=!1}onFocusIn(e){return this.handlers.onFocusIn||(this.handlers.onFocusIn=function(t){var r;(r=e.navigator.view)==null||r.snap(t.target)})}onKeyDown(e){return this.handlers.onKeyDown||(this.handlers.onKeyDown=function(t){let r=t.target;if(/input|select|option|textarea/i.test(r.tagName)||!(r.ownerDocument||r).defaultView.getSelection().isCollapsed)return;switch(t.key){case"ArrowRight":e.rtl?e.onBackwardSwipe(t):e.onForwardSwipe(t);return;case"ArrowLeft":e.rtl?e.onForwardSwipe(t):e.onBackwardSwipe(t);return}switch(t.code){case"Space":if(t.ctrlKey){e.onBackwardSwipe(t);return}else{e.onForwardSwipe(t);return}}e.onKeydown(t)})}};L();var vE=rt(Vo()),jl=class{constructor(e){this.enforceSampleRead=(0,vE.default)(e=>{var g,h,c,p,w,A;let t=Math.round(e.locations.totalProgression*100),r=!1;(g=this.navigator.sample)!=null&&g.limit&&(r=t<=((h=this.navigator.sample)==null?void 0:h.limit),((c=this.navigator.view)==null?void 0:c.layout)==="fixed"&&!r&&(p=this.navigator.sample)!=null&&p.minimum&&e.locations.position<=((w=this.navigator.sample)==null?void 0:w.minimum)&&(r=!0));let i={37:1,38:0,39:1,40:1,32:1,33:1,34:1,35:1,36:1};function o(E){E.preventDefault()}function s(E){i[E.keyCode]&&!r&&o(E)}let l=!1,f=Object.defineProperty&&Object.defineProperty({},"passive",{get:function(){l=!0}});window.addEventListener("test",function(){},f);let u=l?{passive:!1}:!1;function y(E){E=E||window.event;let b=Math.max(-1,Math.min(1,E.wheelDelta||-E.detail));return b===-1&&!r&&E.preventDefault(),!1}let m;function _(E){E=E||window.event;let b=E.target||E.srcElement,C=E.touches[0].clientY;if(!(C>m)){if(C<m&&!r)return b.className.match(/\baltNav\b/)||(E.returnValue=!1,E.cancelable&&(E.cancelBubble=!0),E.preventDefault&&E.cancelable&&(E.preventDefault(),E.stopPropagation())),!1}return m=C,!1}function v(E){return E=E||window.event,m=E.touches[0].clientY,!1}window.addEventListener("mousewheel",y,u),window.addEventListener("DOMMouseScroll",y,u),window.addEventListener("keydown",s,u),window.addEventListener("touchmove",_,u),window.addEventListener("touchstart",v,u),r?(this.navigator.iframes[0].focus(),this.navigator.errorMessage&&(this.navigator.errorMessage.style.display="none",this.navigator.errorMessage.style.removeProperty("background-color"))):(this.navigator.iframes[0].blur(),this.navigator.errorMessage&&(this.navigator.errorMessage.style.display="block",this.navigator.errorMessage.style.backgroundColor="rgb(255, 255, 255)",this.navigator.errorMessage.innerHTML=`<span>${(A=this.navigator.sample)==null?void 0:A.popup}</span>`??""))},300);this.navigator=e}};L();var ql=rt($t()),ou=class{static async create(e){let t=new this(e.publication,e,e.headerMenu);return await t.start(),t}constructor(e,t,r){this.headerMenu=r,this.publication=e,this.properties=t}async stop(){ql.default.log("Page Break module stop")}async start(){var e,t;this.headerMenu&&(this.goToPageView=Le(this.headerMenu,"#sidenav-section-gotopage")),this.headerMenu&&(this.goToPageNumberInput=Le(this.headerMenu,"#goToPageNumberInput")),this.headerMenu&&(this.goToPageNumberButton=Le(this.headerMenu,"#goToPageNumberButton")),we(this.goToPageNumberInput,"keypress",this.goToPageNumber.bind(this)),we(this.goToPageNumberButton,"click",this.goToPageNumber.bind(this)),this.goToPageView&&((e=this.publication.pageList)!=null&&e.length||(t=this.goToPageView.parentElement)==null||t.removeChild(this.goToPageView)),setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("pagebreak"):this.navigator.showLayer("pagebreak")},10)}async goToPageNumber(e){var i;if(this.goToPageNumberInput.value&&(e.key==="Enter"||e.type==="click")){var t=(i=this.publication.pageList)==null?void 0:i.filter(o=>o.Href.slice(o.Href.indexOf("#")+1).replace(/[^0-9]/g,"")===this.goToPageNumberInput.value);if(t&&t.length>0){var r=t[0];let o={progression:0};if(r.Href.indexOf("#")!==-1){let l=r.Href.slice(r.Href.indexOf("#")+1);l!==null&&(o={fragment:l})}let s={href:this.publication.getAbsoluteHref(r.Href),locations:o,type:r.TypeLink,title:r.Title};this.navigator.goTo(s)}}}async handleResize(){var e;await((e=this.navigator.highlighter)==null?void 0:e.destroyHighlights(3)),await this.drawPageBreaks()}async drawPageBreaks(){setTimeout(()=>{var o,s,l;let e=(o=this.navigator.iframes[0].contentDocument)==null?void 0:o.body,t=e==null?void 0:e.querySelectorAll('[*|type="pagebreak"]');(t==null?void 0:t.length)===0&&(t=e==null?void 0:e.querySelectorAll("[epub\\:type='pagebreak']")),(t==null?void 0:t.length)===0&&(t=e==null?void 0:e.querySelectorAll("[role='doc-pagebreak']"));let r=this;function i(f){try{let u=r.navigator.iframes[0].contentDocument;return u?Cr(f,u,Jo):""}catch(u){return ql.default.log("uniqueCssSelector:"),ql.default.error(u),""}}if(t)for(let f=0;f<t.length;f++){let u=t[f];ql.default.log(u);let y=u.innerHTML,m=!1;u.innerHTML.length===0&&(y=u.getAttribute("title")??"",u.innerHTML=y,m=!0),u.innerHTML.length===0&&(y=(u.getAttribute("id")??"").replace(/[^0-9]/g,""),u.innerHTML=y,m=!0);let _=this.navigator.iframes[0].contentDocument;if(_){let v=(s=this.navigator.highlighter)==null?void 0:s.dom(_.body).getWindow().document.createRange(),g=(l=this.navigator.highlighter)==null?void 0:l.dom(_.body).getSelection();if(g.removeAllRanges(),v.selectNodeContents(u),g.addRange(v),!g.isCollapsed){let h=mo(v,i);g.removeAllRanges(),h&&this.createPageBreakHighlight({rangeInfo:h,cleanText:"",rawText:""},y)}}m&&(u.innerHTML="")}},200)}createPageBreakHighlight(e,t){var i;try{let o=`${e.rangeInfo.startContainerElementCssSelector}${e.rangeInfo.startContainerChildTextNodeIndex}${e.rangeInfo.startOffset}${e.rangeInfo.endContainerElementCssSelector}${e.rangeInfo.endContainerChildTextNodeIndex}${e.rangeInfo.endOffset}`,l="R2_PAGEBREAK_"+Ui.hash(o);var r=!1;let f={color:"#000000",id:l,pointerInteraction:r,selectionInfo:e,marker:3,icon:{id:"pageBreak",title:t,color:"#000000",position:"left"},type:3};er.push(f);let u=(i=this.navigator.highlighter)==null?void 0:i.createHighlightDom(this.navigator.iframes[0].contentWindow,f);return f.position=parseInt((u!=null&&u.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px","")),f}catch(o){throw"Can't create highlight: "+o}}};L();var wE=rt(Fg());var SE=rt(Vo());var Pt=rt($t()),Hs=class{constructor(e,t,r,i,o,s){this.voices=[];this.hasEventListener=!1;this.startX=0;this.startY=0;this.index=0;this.userScrolled=!1;this.scrollPartial=!1;this.speaking=!1;this.restartIndex=-1;this.ttsQueueIndex=-1;this.ttsQueue=void 0;this.ttsPlayQueueIndexDebounced=(0,SE.default)((e,t)=>{this.restartIndex>=0?(this.ttsQueueIndex=this.restartIndex,this.restartIndex=-1):this.ttsQueueIndex=e,this.ttsQueue=t,this.ttsPlayQueueIndex(this.ttsQueueIndex,t)},150);this.tts=e,this.headerMenu=s,this.rights=t,this.highlighter=r,this.properties=i,this.api=o}initialize(e){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onRestart(this.restart.bind(this)),this.body=e,this.clean=(0,wE.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),this.wrapper=yt(document,"#iframe-wrapper"),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,we(document,"wheel",this.wheel.bind(this)),we(this.body,"wheel",this.wheel.bind(this)),we(document,"keydown",this.wheel.bind(this)),we(this.navigator.iframes[0].contentDocument,"keydown",this.wheel.bind(this))),we(this.body,"mousedown",this.clickStart.bind(this)),we(this.body,"mouseup",this.click.bind(this)))}clickStart(e){"clientX"in e&&(this.startX=e.clientX),"clientY"in e&&(this.startY=e.clientY)}click(e){var i;let t=0,r=0;if("clientX"in e&&(t=e.clientX),"clientY"in e&&(r=e.clientY),window.speechSynthesis.speaking&&this.speaking&&t===this.startX&&r===this.startY){let o=this.navigator.iframes[0].contentDocument;if(o){let s=this.highlighter.dom(o.body).getSelection(),l=s.getRangeAt(0),f=s.anchorNode;for(;l.toString().indexOf(" ")!==0;)try{l.setStart(f,l.startOffset-1)}catch{break}l.setStart(f,l.startOffset+1);do l.setEnd(f,f.length<l.endOffset?l.endOffset+1:f.length);while(l.toString().indexOf(" ")===-1&&l.toString().trim()!=="");let y=(i=document.querySelector("main#iframe-wrapper iframe").contentWindow)==null?void 0:i.document.body;if(this.ttsQueue&&y){let m=this.findTtsQueueItemIndex(this.ttsQueue,s.anchorNode,s.anchorNode,s.anchorOffset,y);s.removeAllRanges(),m>=0&&(window.speechSynthesis.cancel(),this.restartIndex=m,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}}}}initVoices(e){function t(){return new Promise(function(i,o){let s=window.speechSynthesis,l;l=setInterval(()=>{s.getVoices().length!==0&&(i(s.getVoices()),clearInterval(l))},10)})}t().then(async i=>{if(Pt.default.log(i),this.voices=[],i.forEach(s=>{s.localService===!0&&this.voices.push(s)}),Pt.default.log(this.voices),e&&this.headerMenu){var o=Le(this.headerMenu,"#preferred-languages");o&&this.voices.forEach(s=>{var l=document.createElement("option");l.value=s.name+":"+s.lang,l.innerHTML=s.name+" ("+s.lang+")",o.add(l)})}})}cancel(e=!0){var t,r,i;e&&((t=this.api)!=null&&t.stopped&&((r=this.api)==null||r.stopped()),this.navigator.emit("readaloud.stopped","stopped")),this.userScrolled=!1,this.speaking=!1,setTimeout(()=>{window.speechSynthesis.cancel()},0),this._ttsQueueItemHighlightsWord&&((i=this.navigator.highlighter)==null||i.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0)}async speak(e,t,r){var m,_,v,g,h,c,p;t||this.navigator.rights.enableContentProtection&&((m=this.navigator.contentProtectionModule)==null||m.deactivate()),(_=this.api)!=null&&_.started&&((v=this.api)==null||v.started()),this.navigator.emit("readaloud.started","started");let i=this;this.userScrolled=!1,this.cancel(!1);let o;if(t){let A=(g=document.querySelector("main#iframe-wrapper iframe").contentWindow)==null?void 0:g.document.body,E=this.navigator.iframes[0].contentDocument;if(E){let b=this.highlighter.dom(E.body).getSelection();if(b.isCollapsed){let C=i.navigator.iframes[0].contentDocument,k=(c=(h=i.navigator.annotationModule)==null?void 0:h.annotator)==null?void 0:c.getTemporarySelectionInfo(C);b.addRange(k.range)}if(A){var s=this.generateTtsQueue(A);if(!s.length)return;var l=this.findTtsQueueItemIndex(s,b.anchorNode,b.anchorNode,b.anchorOffset,A),f=this.findTtsQueueItemIndex(s,b.focusNode,b.focusNode,b.focusOffset,A);let C=Ds(s,l),k=Ds(s,f);var u;if(C&&e&&e.cleanText){let R=Fs(C),B=e.rangeInfo.startOffset,I=e.cleanText;if(k&&l+1===f){let F=Fs(k);B=(R+" "+F).indexOf(e.cleanText),I=R.slice(B,R.length),u=e.cleanText.replace(I,"").trim()}else if(f>l){let F="";for(let z=l+1;z<f;z++){let q=Ds(s,z);if(q){let G=Fs(q);F+=G,u=e.cleanText.replace(G,"")}}if(k){let z=Fs(k);F+=" "+z}B=(R+" "+F).indexOf(e.cleanText),I=R.slice(B,R.length),u=u.replace(I,"").trim()}o=new SpeechSynthesisUtterance(I),o.rate=this.tts.rate,o.pitch=this.tts.pitch,o.volume=this.tts.volume,this.setVoice(this,o),Pt.default.log(e),Pt.default.log(I,(p=e.range)==null?void 0:p.commonAncestorContainer.textContent),Pt.default.log(C),Pt.default.log(C.item.textNodes),Pt.default.log(B),Pt.default.log(C.item.combinedText);let D=C.item.textNodes.filter(F=>{var z;return F===((z=e.range)==null?void 0:z.commonAncestorContainer)})[0];Pt.default.log(D),o.onboundary=F=>{this.updateTTSInfo(C,F.charIndex,F.charLength,B,o.text)}}}}}else o=new SpeechSynthesisUtterance(this.clean);o.rate=this.tts.rate,o.pitch=this.tts.pitch,o.volume=this.tts.volume,this.setVoice(i,o),this.index=0;function y(){o.onend=function(){var w,A;if(f>l)if(l=l+1,l!==f){let E=Ds(s,l);if(E){let b=Fs(E);o=new SpeechSynthesisUtterance(b),o.rate=i.tts.rate,o.pitch=i.tts.pitch,o.volume=i.tts.volume,i.setVoice(i,o),o.onboundary=C=>{i.updateTTSInfo(E,C.charIndex,C.charLength,0,o.text)},setTimeout(()=>{window.speechSynthesis.speak(o)},0),y()}}else{let E=Ds(s,l);E&&(o=new SpeechSynthesisUtterance(u),o.rate=i.tts.rate,o.pitch=i.tts.pitch,o.volume=i.tts.volume,i.setVoice(i,o),o.onboundary=b=>{i.updateTTSInfo(E,b.charIndex,b.charLength,0,o.text)},setTimeout(()=>{window.speechSynthesis.speak(o)},0),y()),l>f&&(Pt.default.log("utterance ended"),i.highlighter.doneSpeaking(),(w=i.api)==null||w.finished(),i.navigator.emit("readaloud.finished","finished"))}else Pt.default.log("utterance ended"),i.highlighter.doneSpeaking(),(A=i.api)==null||A.finished(),i.navigator.emit("readaloud.finished","finished")}}setTimeout(()=>{var w;window.speechSynthesis.speak(o),t||this.navigator.rights.enableContentProtection&&((w=this.navigator.contentProtectionModule)==null||w.recalculate(200))},0),y(),r()}setVoice(e,t){Pt.default.log("this.tts.voice.lang",this.tts.voice.lang);let r=!0;this.tts.voice&&this.tts.voice.lang&&(r=this.tts.voice.lang.indexOf("-")!==-1,r||(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),r=!0)),Pt.default.log("initialVoiceHasHyphen",r),Pt.default.log("voices",this.voices);let i;r?(i=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(u=>{var y=u.lang.replace("_","-");return y===this.tts.voice.lang&&u.name===this.tts.voice.name})[0]:void 0,i===void 0&&(i=this.tts.voice&&this.tts.voice.lang?this.voices.filter(u=>u.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(i=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(u=>u.lang===this.tts.voice.lang&&u.name===this.tts.voice.name)[0]:void 0,i===void 0&&(i=this.tts.voice&&this.tts.voice.lang?this.voices.filter(u=>u.lang===this.tts.voice.lang)[0]:void 0)),Pt.default.log("initialVoice",i);let o=e.navigator.publication.Metadata.Language[0].indexOf("-")!==-1;Pt.default.log("publicationVoiceHasHyphen",o);let s;o?s=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(u=>{var y=u.lang.replace("_","-");return y.startsWith(e.navigator.publication.Metadata.Language[0])||y.endsWith(e.navigator.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:s=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(u=>u.lang.startsWith(e.navigator.publication.Metadata.Language[0])||u.lang.endsWith(e.navigator.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,Pt.default.log("publicationVoice",s);let l=navigator.language.indexOf("-")!==-1;Pt.default.log("defaultVoiceHasHyphen",l);let f;l?f=this.voices.filter(u=>u.lang.replace("_","-")===navigator.language&&u.localService)[0]:f=this.voices.filter(u=>u.lang===navigator.language&&u.localService)[0],f===void 0&&(f=this.voices.filter(u=>u.lang.includes(navigator.language)&&u.localService)[0]),Pt.default.log("defaultVoice",f),i?(Pt.default.log("initialVoice"),t.voice=i):s?(Pt.default.log("publicationVoice"),t.voice=s):f&&(Pt.default.log("defaultVoice"),t.voice=f),t.voice!==void 0&&t.voice!==null&&(t.lang=t.voice.lang,Pt.default.log("utterance.voice.lang",t.voice.lang),Pt.default.log("utterance.lang",t.lang)),Pt.default.log("navigator.language",navigator.language)}speakPlay(){var i,o,s,l,f;this.navigator.rights.enableContentProtection&&((i=this.navigator.contentProtectionModule)==null||i.deactivate()),this.scrollPartial=!0,this.cancel(!1),(o=this.api)!=null&&o.started&&((s=this.api)==null||s.started()),this.navigator.emit("readaloud.started","started");let e=this,r=(l=document.querySelector("main#iframe-wrapper iframe").contentWindow)==null?void 0:l.document.body;if(r){let m=function(){var g;let _=e.highlighter.visibleTextRects[0],v=e.navigator.iframes[0].contentDocument;if(v){let h=e.highlighter.dom(v.body).getWindow().document.createRange(),c=e.highlighter.dom((g=e.navigator.iframes[0].contentDocument)==null?void 0:g.body).getSelection();c.removeAllRanges(),h.selectNodeContents(_.node),c.addRange(h);let p=0,w=c.focusNode,A=c.focusOffset;c.collapse(c.anchorNode,c.anchorOffset);for(let E=0;E<p;E++)c.modify("move","forward","line");if(c.extend(w,A),c.collapse(c.anchorNode,c.anchorOffset),r){let E=e.findTtsQueueItemIndex(u,c.anchorNode,c.anchorNode,c.anchorOffset,r);E>=0&&(y=E)}c.removeAllRanges()}},u=this.generateTtsQueue(r);if(!u.length)return;let y=0;m(),y<0&&(y=0),setTimeout(()=>{this.startTTSSession(u,y)},200)}this.navigator.rights.enableContentProtection&&((f=this.navigator.contentProtectionModule)==null||f.recalculate(200))}speakPause(){var e,t,r;window.speechSynthesis.speaking&&((e=this.api)!=null&&e.paused&&((t=this.api)==null||t.paused()),this.navigator.emit("readaloud.paused","paused"),this.userScrolled=!1,window.speechSynthesis.pause(),this.speaking=!1,this._ttsQueueItemHighlightsWord&&((r=this.navigator.highlighter)==null||r.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0))}speakResume(){var e,t;window.speechSynthesis.speaking&&((e=this.api)!=null&&e.resumed&&((t=this.api)==null||t.resumed()),this.navigator.emit("readaloud.resumed","resumed"),this.userScrolled=!1,window.speechSynthesis.resume(),this.speaking=!0)}static async create(e){let t=new this(e.tts,e.rights,e.highlighter,e,e.api,e.headerMenu);return await t.start(),t}async start(){var t;if(this.headerMenu){var e=Le(this.headerMenu,"#menu-button-tts");e&&((t=e.parentElement)==null||t.style.removeProperty("display"))}setTimeout(()=>{var r;(r=this.properties)!=null&&r.hideLayer?this.navigator.hideLayer("readaloud"):this.navigator.showLayer("readaloud")},10)}wheel(e){if(e instanceof KeyboardEvent)switch(e.key){case"ArrowUp":this.userScrolled=!0;break;case"ArrowDown":this.userScrolled=!0;break}else this.userScrolled=!0}stop(){Pt.default.log("TTS module stop"),Ue(document,"wheel",this.wheel.bind(this)),Ue(this.body,"wheel",this.wheel.bind(this)),Ue(document,"keydown",this.wheel.bind(this)),Ue(this.navigator.iframes[0].contentDocument,"keydown",this.wheel.bind(this)),Ue(this.body,"click",this.click.bind(this))}generateTtsQueue(e){let t=[],r=[];function i(f){if(f.nodeType!==Node.TEXT_NODE||!f.nodeValue||!f.nodeValue.trim().length)return;let u=r[r.length-1];if(!u)return;let y=f.parentElement?_E(f.parentElement):void 0,m=f.parentElement?HU(f.parentElement):void 0,_=t[t.length-1];(!_||_.parentElement!==u||_.lang!==y||_.dir!==m)&&(_={combinedText:"",dir:m,lang:y,parentElement:u,textNodes:[]},t.push(_)),_.textNodes.push(f)}let o=!0;function s(f){if(f.nodeType!==Node.ELEMENT_NODE)return;let u=o||f.matches("h1, h2, h3, h4, h5, h6, p, th, td, caption, li, blockquote, q, dt, dd, figcaption, div, pre");o=!1,u&&r.push(f);for(let y of f.childNodes)switch(y.nodeType){case Node.ELEMENT_NODE:let m=y;if(!m.matches("img, sup, sub, audio, video, source, button, canvas, del, dialog, embed, form, head, iframe, meter, noscript, object, s, script, select, style, textarea"))s(m);else if(m.tagName&&m.tagName.toLowerCase()==="img"&&m.src){let v=m.getAttribute("alt");if(v){let g=v.trim();if(g){let h=_E(m);t.push({combinedText:g,dir:void 0,lang:h,parentElement:m,textNodes:[]})}}}break;case Node.TEXT_NODE:r.length!==0&&i(y);break;default:break}u&&r.pop()}s(e);function l(f){if(!f.textNodes||!f.textNodes.length){(!f.combinedText||!f.combinedText.length)&&(f.combinedText="");return}f.combinedText=UU(f.textNodes,!0).replace(/[\r\n]/g," ");let u=f.parentElement;for(;u;){if(u.tagName){let y=u.tagName.toLowerCase();if(y==="pre"||y==="code"||y==="video"||y==="audio")break}u=u.parentElement}}for(let f of t)l(f);return t}findTtsQueueItemIndex(e,t,r,i,o){let s=0;for(let l of e){if(r&&l.textNodes){if(l.textNodes.includes(r))return s}else if(t===l.parentElement||l.parentElement!==t.ownerDocument.body&&l.parentElement!==o&&l.parentElement.contains(t)||t.contains(l.parentElement))return s;s++}return-1}restart(){window.speechSynthesis.speaking&&(window.speechSynthesis.cancel(),this.restartIndex=this.ttsQueueIndex,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}startTTSSession(e,t){if(!Ds(e,t)){this.cancel();return}this.speaking=!0,this.ttsPlayQueueIndexDebounced(t,e)}ttsPlayQueueIndex(e,t){if(e<0){this.cancel();return}let r=Ds(t,e);if(!r){this.cancel();return}let i=Fs(r);if(!i){this.cancel();return}let o=new SpeechSynthesisUtterance(i);o.rate=this.tts.rate,o.pitch=this.tts.pitch,o.volume=this.tts.volume;let s=this;this.setVoice(s,o),o.onboundary=l=>{Pt.default.log(l.name),this.updateTTSInfo(r,l.charIndex,l.charLength,0,o.text)},setTimeout(()=>{window.speechSynthesis.speak(o),s.speaking||window.speechSynthesis.pause()},0),o.onend=function(){s.speaking&&s.ttsPlayQueueIndexDebounced(e+1,t)}}updateTTSInfo(e,t,r,i,o){if(!e)return;Pt.default.log(e,t,r,o);let s=o||Fs(e);if(t>=0&&o){let l=o.slice(0,t+1).search(/\S+$/),f=o.slice(t).search(/\s/),u=f<0?o.slice(l):o.slice(l,f+t),y=l+u.length;if(r===void 0){let m=o.substring(t).match(/^[a-z\d']*/i);m&&(r=m[0].length)}r===void 0&&(r=u.length),this.wrapHighlightWord(e,o,t+i,r,u,l,y)}return s}wrapHighlightWord(e,t,r,i,o,s,l){var c,p,w,A,E,b,C,k,R,B;Pt.default.log(e),Pt.default.log(t),Pt.default.log(r,i,o,s,l),this._ttsQueueItemHighlightsWord&&((c=this.navigator.highlighter)==null||c.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0);let f=e.item,u=r,y=0,m,_=-1,v,g=-1,h=u+i;for(let I of f.textNodes){if(!I.nodeValue&&I.nodeValue!=="")continue;let D=I.nodeValue.length;if(y+=D,m||u<y&&(m=I,_=D-(y-u)),m&&h<=y&&(v=I,g=D-(y-h)),v)break}if(m&&v){let F=function(G){try{let Y=D.navigator.iframes[0].contentDocument;return Y?Cr(G,Y,Jo):""}catch(Y){return Pt.default.log("uniqueCssSelector:"),Pt.default.error(Y),""}},I=new Range;I.setStart(m,_),I.setEnd(v,g);let D=this,z=mo(I,F);if(!z)return;let q=(p=this.navigator.highlighter)==null?void 0:p.createHighlight(this.navigator.iframes[0].contentWindow,{rangeInfo:z,cleanText:"",rawText:"",range:void 0},this.tts.color,!1,3,{id:"tts",title:"",position:"right"},void 0,{defaultClass:this.tts.color},2,"R2_READALOUD_");if(q){this._ttsQueueItemHighlightsWord=q[0];let X=((A=(w=q[1])==null?void 0:w.firstChild)==null?void 0:A.getBoundingClientRect()).top-this.wrapper.scrollTop>window.innerHeight/2-65;(E=this.navigator.view)!=null&&E.isScrollMode()&&this.tts.autoScroll&&!this.userScrolled&&this.scrollPartial&&X?(C=(b=q[1])==null?void 0:b.firstChild)==null||C.scrollIntoView({block:"center",behavior:"smooth"}):(k=this.navigator.view)!=null&&k.isPaginated()&&((B=D.navigator.view)==null||B.snap((R=q[1])==null?void 0:R.firstChild))}}}};function _E(n){let e=n;for(;e&&e.nodeType===Node.ELEMENT_NODE;){let t=e.getAttribute("xml:lang");if(t||(t=e.getAttributeNS("http://www.w3.org/XML/1998/namespace","lang")),t||(t=e.getAttribute("lang")),t)return t;e=e.parentNode}}function HU(n){let e=n;for(;e&&e.nodeType===Node.ELEMENT_NODE;){let t=e.getAttribute("dir");if(t)return t;e=e.parentNode}}function UU(n,e){if(n&&n.length){let t="";for(let r of n)r.nodeValue&&(t+=e?r.nodeValue:qU(r.nodeValue));return t}return""}function jU(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function qU(n){return jU(n).replace(/\n/g," ").replace(/\s\s+/g," ")}function Ds(n,e){let t=-1,r=-1;for(let i of n)if(r++,t++,e===t)return{item:i,iArray:r,iGlobal:t,iSentence:-1}}function Fs(n){return n.item.combinedText}L();var Gl=rt(If());var AE=rt(Vo());var EE=rt($t()),su=class{constructor(e,t,r,i){this.currentChapterPopupResult=[];this.currentPopupHighlights=[];this.definitions=(0,AE.default)(async()=>{if(await this.highlighter.destroyHighlights(4),this.properties.definitions)for(let e of this.properties.definitions)await this.define(e)},200);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);return await t.start(),t}async stop(){EE.default.log("Definitions module stop")}async start(){setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("definitions"):this.navigator.showLayer("definitions")},10)}async searchAndPaint(e,t){var s;let r=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[this.navigator.currentResource()??0].Href:""),i=this.publication.getTOCItem(r);i===void 0&&this.publication.readingOrder&&(i=this.publication.readingOrder[this.navigator.currentResource()??0]);let o=[];if(i)for(let l of e.terms){let f=e.terms.indexOf(l);i&&await ts(l,this.navigator.iframes[0].contentDocument,i.Href,i.Title,(s=this.navigator.definitionsModule)==null?void 0:s.properties.fullWordSearch).then(u=>{let y;e.result===1?y=0:e.result===2&&(y=Math.floor(Math.random()*u.length-1)+1),u.forEach((m,_)=>{if(y===void 0||y===_){let v={rangeInfo:m.rangeInfo},g=this.createDefinitionHighlight(v,e);m.highlight=g,o.push(Gl.omit(g,"definition")),this.currentChapterPopupResult.push(m),this.currentPopupHighlights.push(g)}}),f===e.terms.length-1&&t(o)})}}async define(e){await this.searchAndPaint(e,async t=>{var r,i,o;(r=this.api)!=null&&r.success&&((i=this.api)==null||i.success(Gl.omit(e,"callbacks"),t),this.navigator.emit("definition.success",t),(o=this.api)!=null&&o.visible&&t.forEach(s=>{var y;let l=(y=this.navigator.iframes[0].contentDocument)==null?void 0:y.querySelector(`#${s.id}`),f=l==null?void 0:l.querySelectorAll(`.${jr}`),u=new IntersectionObserver((m,_)=>{m.forEach(v=>{var g;v.intersectionRatio===1&&((g=this.api)==null||g.visible(Gl.omit(e,"callbacks"),Gl.omit(s,"definition")),this.navigator.emit("definition.visible",e,s))})},{threshold:1});f&&f.length>0&&u.observe(f[0])}))})}async drawDefinitions(){setTimeout(async()=>{await this.definitions()},100)}async handleResize(){await this.drawDefinitions()}createDefinitionHighlight(e,t){var r;try{let i=(r=this.navigator.definitionsModule)==null?void 0:r.properties.color;Jt.isHexColor(i)&&(i=Jt.hexToRgbChannels(i));let o=`${e.rangeInfo.startContainerElementCssSelector}${e.rangeInfo.startContainerChildTextNodeIndex}${e.rangeInfo.startOffset}${e.rangeInfo.endContainerElementCssSelector}${e.rangeInfo.endContainerChildTextNodeIndex}${e.rangeInfo.endOffset}`,l="R2_DEFINITION_"+Ui.hash(o);this.highlighter.destroyHighlight(this.navigator.iframes[0].contentDocument,l);let f={color:i||Ls,id:l,pointerInteraction:!0,selectionInfo:e,marker:1,type:4};er.push(f);let u=this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,f);return u&&(t.definition&&(u.dataset.definition=t.definition),u.dataset.order=String(t.order),f.definition=t,f.position=parseInt((u!=null&&u.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px",""))),f}catch(i){throw"Can't create definitions highlight: "+i}}async addDefinition(e){await this.define(e)}async clearDefinitions(){await this.highlighter.destroyHighlights(4)}};L();var TE=rt(xE(),1);var bh=TE.default;L();var rs=rt($t()),PE=.5,Us=class{constructor(e,t,r){this.hasEventListener=!1;this.lines=[];this.index=0;this.isActive=!1;this.isDebug=!1;this.lineFocusContainer=document.getElementById("lineFocusContainer");this.readerContainer=document.getElementById("D2Reader-Container");this.lineFocusTopBlinder=document.getElementById("lineFocusTopBlinder");this.lineFocusBottomBlinder=document.getElementById("lineFocusBottomBlinder");this.wrapperHeight=void 0;this.properties=e,this.api=r,this.highlighter=t}static async create(e){let t=new this(e,e.highlighter,e.api);return await t.start(),t}async stop(){rs.default.log("Definitions module stop"),this.hasEventListener=!1,Ue(document,"keydown",this.keydown.bind(this)),Ue(document,"keyup",this.keyup.bind(this)),Ue(this.navigator.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),Ue(this.navigator.iframes[0].contentDocument,"keyup",this.keyup.bind(this))}async start(){let e=yt(document,"#iframe-wrapper");e.style.height.length>0&&(this.wrapperHeight=e.style.height,this.lineFocusContainer&&this.lineFocusContainer.style.height.length===0&&(this.lineFocusContainer.style.height=this.wrapperHeight),this.readerContainer&&this.readerContainer.style.height.length===0&&(this.readerContainer.style.height=this.wrapperHeight),this.readerContainer&&(this.readerContainer.style.overflow="hidden"))}initialize(e){return new Promise(async t=>{await document.fonts.ready,this.hasEventListener||(this.hasEventListener=!0,we(document,"keydown",this.keydown.bind(this)),we(document,"keyup",this.keyup.bind(this)),we(e.contentDocument,"keydown",this.keydown.bind(this)),we(e.contentDocument,"keyup",this.keyup.bind(this))),t(null)})}keydown(e){if(e instanceof KeyboardEvent&&this.isActive)switch(e.key){case"ArrowUp":e.stopPropagation();break;case"ArrowDown":e.stopPropagation();break}}keyup(e){if(e instanceof KeyboardEvent&&this.isActive)switch(e.key){case"ArrowUp":this.lineUp();break;case"ArrowDown":this.lineDown();break}}handleResize(){this.isActive&&this.lineFocus()}async enableLineFocus(){this.isActive=!0,await this.navigator.settings.scroll(!0),this.lineFocus()}disableLineFocus(e=!0){this.isActive=!1;let t=yt(document,"#iframe-wrapper");this.wrapperHeight&&(t.style.height=this.wrapperHeight),e||(this.index=0);let r=this.navigator.iframes[0].contentDocument;cr(r,"html").style.removeProperty("--USER__maxMediaHeight"),this.wrapperHeight=void 0,this.lineFocusContainer&&(this.lineFocusContainer.style.display="none");let o=document.getElementById("container-view-timeline");o&&o.style.removeProperty("display");let s=document.getElementById("divBefore");s&&s.remove();let l=document.getElementById("divAfter");l&&l.remove(),this.highlighter.destroyHighlights(5)}lineFocus(){var y;let e=yt(document,"#iframe-wrapper"),t=this.navigator.iframes[0].contentDocument,r=cr(t,"html"),i=this.properties.maxHeight?gi()*this.properties.maxHeight/100:gi()/2;r.style.setProperty("--USER__maxMediaHeight",i+"px");function o(m,_){m.parentNode.insertBefore(_,m.nextSibling)}function s(m,_){m.parentNode.insertBefore(_,m)}let l=document.getElementById("container-view-timeline");l&&(l.style.display="none"),this.lineFocusContainer&&this.lineFocusContainer.style.removeProperty("display");let f=document.getElementById("divBefore");if(f)f.style.height=e.clientHeight/2+"px";else{let m=document.createElement("div");m.style.height=e.clientHeight/2+"px",m.id="divBefore",s(e,m)}let u=document.getElementById("divAfter");if(u)u.style.height=e.clientHeight/2+"px";else{let m=document.createElement("div");m.style.height=e.clientHeight/2+"px",m.id="divAfter",o(e,m)}if(this.lines=[],t){let v=function(){let A=Math.round,E=Math.random,b=255;return{blue:A(E()*b),green:A(E()*b),red:A(E()*b)}},g=function(A,E){let b=[];for(let C=0,k=0;C<A.length;C++)C>=E&&C%E===0&&k++,b[k]=b[k]||[],b[k].push(A[C]);return b},h=function(A,E){let b=Math.min(A.left,E.left),C=Math.max(A.right,E.right),k=Math.min(A.top,E.top),R=Math.max(A.bottom,E.bottom);return{bottom:R,height:R-k,left:b,right:C,top:k,width:C-b}},c=function(A){if(A.length>1){let E=h(A[0],A[1]);if(A.length>2){let b=h(E,A[2]);if(A.length>3){let C=h(b,A[3]);return A.length>4?h(C,A[4]):C}return b}return E}return A[0]},m=this.findRects(t.body);m=Gg(m,!0),m=m.sort(function(A,E){return A.top-E.top});let _=[];m=m.filter(function(A){let E=A.top;return _.indexOf(E)===-1&&_.indexOf(E+1)===-1&&_.indexOf(E+2)===-1&&_.indexOf(E+3)===-1&&_.indexOf(E+4)===-1&&_.indexOf(E-1)===-1&&_.indexOf(E-2)===-1&&_.indexOf(E-3)===-1&&_.indexOf(E-4)===-1?(_.push(E),!0):!1}),this.highlighter.destroyHighlights(5);let p=[];this.properties.lines&&this.properties.lines>1?g(m,this.properties.lines).forEach(E=>{p.push(c(E))}):p=m;let w=Le(t,"#"+"R2_ID_LINEFOCUS_CONTAINER");if(w)for(let A of p){let E=document.createElement("div");E.setAttribute("class",jr);let b=v();if(Jt.isHexColor(b)&&(b=Jt.hexToRgbChannels(b)),this.isDebug){let ve=`border-bottom: 1px solid rgba(${b.red}, ${b.green}, ${b.blue}, ${PE}) !important`;E.setAttribute("style",`mix-blend-mode: multiply; border-radius: 1px !important; background-color: rgba(${b.red}, ${b.green}, ${b.blue}, ${PE}) !important; ${ve}`)}E.style.outline="none",E.tabIndex=0;let C=this.navigator.iframes[0].contentWindow.document,k=this.navigator.view.isPaginated();k?C.body.style.position="revert":C.body.style.position="relative";let R=C.body.getBoundingClientRect(),B=this.highlighter.getScrollingElement(C),I=k?-B.scrollLeft:R.left,D=k?-B.scrollTop:R.top,F=1,z=24,q,G,Y=(y=this.navigator.iframes[0].contentWindow)==null?void 0:y.innerWidth,X=parseInt(getComputedStyle(t.documentElement).getPropertyValue("column-count")),Q=parseInt(getComputedStyle(t.documentElement).getPropertyValue("column-width")),se=parseInt(getComputedStyle(t.body).getPropertyValue("padding-left"));if(Y){let ve=Y/(X||1);ve<Q&&(ve=Y),k||(ve=parseInt(getComputedStyle(t.body).width.replace("px","")));let ce=this.navigator.settings.fontSize/100,W=20*ce;ce<=1&&(W=-60);let H=0;ce<=1&&(H=-60),q=Math.floor(A.left/ve)*ve+ve-(z<40?40:z)+H,G=Math.floor(A.left/ve)*ve+(z<40?40:z)-W;let M=parseInt(t.documentElement.style.getPropertyValue("--USER__pageMargins"));M>=2&&(G=G+se/X,q=q-se/X),k||(q=parseInt(getComputedStyle(t.body).width.replace("px","")),G=parseInt(getComputedStyle(t.body).width.replace("px",""))-ve,M>=2&&(G=G+se/2,q=q-se/2))}E.style.setProperty("pointer-events","none"),E.style.position="absolute",E.scale=F,E.rect={height:A.height,left:A.left-I,top:A.top-D,width:A.width},E.style.width=`${E.rect.width*F}px`,E.style.height=`${E.rect.height*F}px`,E.style.left=`${E.rect.left*F}px`,E.style.top=`${E.rect.top*F}px`,this.lines.push(E),w.append(E)}setTimeout(()=>{this.currentLine()},100)}}currentLine(){let e=this.lines[this.index],t=e.style.top,i=parseInt(e.style.top.replace("px",""))+parseInt(e.style.height.replace("px",""))-parseInt(t.replace("px",""));if(this.lineFocusContainer){let s=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-i)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=s+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=s+"px")}e.scrollIntoView({block:"center",behavior:"smooth"})}lineDown(){if(this.index<this.lines.length-1){this.index+=1,this.index>this.lines.length-1&&(this.index=this.lines.length-1);let e=this.lines[this.index],t=e.style.top,i=parseInt(e.style.top.replace("px",""))+parseInt(e.style.height.replace("px",""))-parseInt(t.replace("px",""));if(this.lineFocusContainer){let s=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-i)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=s+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=s+"px")}e.scrollIntoView({block:"center",behavior:"smooth"})}}lineUp(){if(this.index>0){this.index-=1,this.index<0&&(this.index=0);let e=this.lines[this.index],t=e.style.top,i=parseInt(e.style.top.replace("px",""))+parseInt(e.style.height.replace("px",""))-parseInt(t.replace("px",""));if(this.lineFocusContainer){let s=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-i)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=s+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=s+"px")}e.scrollIntoView({block:"center",behavior:"smooth"})}}almostEqual(e,t,r){return Math.abs(e-t)<=r}findRects(e){let t=this.findTextNodes(e),r=Array.from(e.getElementsByTagName("img")),i=[];return t.forEach(o=>{i.push(...this.measureTextNodes(o))}),r.forEach(o=>{i.push(...this.measureImageNodes(o))}),i}findTextNodes(e,t=[]){var i,o,s,l,f,u,y;let r=e.firstChild;for(;r;)r.nodeType===1&&this.findTextNodes(r,t),r.nodeType===3&&(i=r.textContent)!=null&&i.trim()&&(r.textContent.trim().length>1||((o=r.parentElement)==null?void 0:o.tagName.toLowerCase())==="h1"||((s=r.parentElement)==null?void 0:s.tagName.toLowerCase())==="h2"||((l=r.parentElement)==null?void 0:l.tagName.toLowerCase())==="h3"||((f=r.parentElement)==null?void 0:f.tagName.toLowerCase())==="h4"||((u=r.parentElement)==null?void 0:u.tagName.toLowerCase())==="h5"||((y=r.parentElement)==null?void 0:y.tagName.toLowerCase())==="h6")&&r.parentElement&&getComputedStyle(r.parentElement).verticalAlign==="baseline"&&t.push(r),r=r.nextSibling;return t}measureTextNodes(e){try{let t=document.createRange();t.selectNodeContents(e);let r=Array.from(t.getClientRects());return t.detach(),r}catch(t){rs.default.log("measureTextNode "+t),rs.default.log("measureTextNode "+e),rs.default.log(`${e.textContent}`)}}measureImageNodes(e){try{let t=document.createRange();t.selectNode(e);let r=Array.from(t.getClientRects());return t.detach(),r}catch(t){rs.default.log("measureTextNode "+t),rs.default.log("measureTextNode "+e),rs.default.log(`${e.textContent}`)}}};L();var OE=rt($t()),au=class{constructor(e,t,r,i){this.history=[];this.headerMenu=i,this.publication=t,this.properties=r,this.annotator=e}static async create(e){let t=new this(e.annotator,e.publication,e,e.headerMenu);return await t.start(),t}async stop(){OE.default.log("Page Break module stop"),Ue(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),Ue(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleResize(){await this.setup()}setup(){this.history.length>0&&(this.historyForwardAnchorElement&&this.historyCurrentIndex+1<this.history.length?this.historyForwardAnchorElement.className=this.historyForwardAnchorElement.className.replace(" disabled",""):this.historyForwardAnchorElement&&(this.historyForwardAnchorElement.removeAttribute("href"),this.historyForwardAnchorElement.className+=" disabled"),this.historyBackAnchorElement&&this.historyCurrentIndex>0?this.historyBackAnchorElement.className=this.historyBackAnchorElement.className.replace(" disabled",""):this.historyBackAnchorElement&&(this.historyBackAnchorElement.removeAttribute("href"),this.historyBackAnchorElement.className+=" disabled"))}async push(e,t){if(t&&this.annotator){let r=await this.annotator.getLastReadingPosition();if(r){let o=this.publication.getAbsoluteHref(r.href);if(r.href=o,this.historyCurrentIndex<this.history.length-1)this.history=this.history.slice(0,this.historyCurrentIndex),this.history.push(r),this.historyCurrentIndex=this.history.length-1;else if(r!=null&&r.locations.progression&&(r==null?void 0:r.locations.progression)>0)this.history.push(r),this.historyCurrentIndex=this.history.length-1;else{let s=this.history[this.history.length-1];(s&&s.href!==e.href&&s.locations!==e.locations||s===void 0)&&(this.history.push(r),this.historyCurrentIndex=this.history.length-1)}}this.historyCurrentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyCurrentIndex));let i=this.history[this.history.length-1];(i&&i.href!==e.href||i===void 0)&&(this.history.push(e),this.historyCurrentIndex=this.history.length-1)}}async start(){this.headerMenu&&(this.historyForwardAnchorElement=Le(this.headerMenu,"#history-forward")),this.headerMenu&&(this.historyBackAnchorElement=Le(this.headerMenu,"#history-back")),this.historyCurrentIndex=this.history.length-1,we(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),we(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleHistoryForwardClick(e){await this.historyForward(),e.preventDefault(),e.stopPropagation()}async historyForward(){this.history.length>0&&this.historyCurrentIndex+1<this.history.length&&(this.historyCurrentIndex=this.historyCurrentIndex+1,await this.navigator.navigate(this.history[this.historyCurrentIndex],!1))}async handleHistoryBackClick(e){await this.historyBack(),e.preventDefault(),e.stopPropagation()}async historyBack(){this.history.length>0&&this.historyCurrentIndex>0&&(this.historyCurrentIndex=this.historyCurrentIndex-1,await this.navigator.navigate(this.history[this.historyCurrentIndex],!1))}};L();var ME=rt($t()),vh=(r=>(r[r.Chicago=0]="Chicago",r[r.MLA=1]="MLA",r[r.APA=2]="APA",r))(vh||{});var js=class{constructor(e,t,r,i){this.highlighter=t,this.properties=r,this.publication=e,this.api=i}static async create(e){let t=new this(e.publication,e.highlighter,e,e.api);return await t.start(),t}async stop(){ME.default.log("Citation module stop")}copyToClipboard(e){var r,i,o;(r=this.navigator)!=null&&r.contentProtectionModule&&(this.navigator.contentProtectionModule.citation=!0);let t=!0;if(window.clipboardData)window.clipboardData.setData("text/plain",e);else{let s=this.createElementForExecCommand(e);this.selectContent(s);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),t=document.execCommand("copy",!1)}catch{t=!1}document.body.removeChild(s)}t?(i=this.api)==null||i.citationCreated("The text was copied to the clipboard!"):(o=this.api)==null||o.citationFailed("Your browser doesn't allow clipboard access!")}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)}async start(){var r;let e=this,t={id:"citationIcon",callback:function(i){var B,I,D;let o=function(){var G;let F="",z="",q="";return e.properties.author?(q=q+e.properties.author,z=z+e.properties.author,F=F+e.properties.author):((G=e.publication.Metadata.Author)==null?void 0:G.length)>0&&0===0&&e.publication.Metadata.Author[0].Name&&e.publication.Metadata.Author[0].Name instanceof String&&e.publication.Metadata.Author[0].Name.length>0&&(q=q+e.publication.Metadata.Author[0].Name,z=z+e.publication.Metadata.Author[0].Name,F=F+e.publication.Metadata.Author[0].Name),q.length>0&&z.length>0&&F.length>0?[F+". ",z+". ",q+". "]:["","",""]},s=function(){let F="",z="",q="";return e.properties.publisher?(z=z+e.properties.publisher,F=F+e.properties.publisher):e.publication.Metadata.Publisher&&e.publication.Metadata.Publisher[0].Name&&(z=z+e.publication.Metadata.Publisher[0].Name,F=F+e.publication.Metadata.Publisher[0].Name),e.properties.published?(q=q+"("+e.properties.published+")",z=z+", "+e.properties.published,F=F+", "+e.properties.published):e.publication.Metadata.PublicationDate&&e.publication.Metadata.PublicationDate.getFullYear()>0&&(q=q+"("+e.publication.Metadata.PublicationDate.getFullYear()+")",z=z+", "+e.publication.Metadata.PublicationDate.getFullYear(),F=F+", "+e.publication.Metadata.PublicationDate.getFullYear()),q.length>0&&z.length>0&&F.length>0?[F+". ",z+". ",q+". "]:["","",""]},l=function(){return e.properties.title?["<em>"+e.properties.title+"</em>. ","<em>"+e.properties.title+"</em>. ","<em>"+e.properties.title+"</em>. "]:e.publication.Metadata.Title?["<em>"+e.publication.Metadata.Title+"</em>. ","<em>"+e.publication.Metadata.Title+"</em>. ","<em>"+e.publication.Metadata.Title+"</em>. "]:["","",""]},f=function(){return["","",""]},u=function(){let F="",z="",q="";return e.properties.publisher?(z=z+e.properties.publisher+", ",F=F+e.properties.publisher+", ",q=q+e.properties.publisher):e.publication.Metadata.Publisher&&e.publication.Metadata.Publisher[0].Name&&(z=z+e.publication.Metadata.Publisher[0].Name+", ",F=F+e.publication.Metadata.Publisher[0].Name+", ",q=q+e.publication.Metadata.Publisher[0].Name),q.length>0&&z.length>0&&F.length>0?[F+". ",z+". ",q+". "]:["","",""]},y=function(){return["","",""]},m=function(){return["","",""]},_=function(){return["","",""]},v=function(){return e.properties.library?["Retrieved from "+e.properties.library+". ","Retrieved from "+e.properties.library+". ","Retrieved from "+e.properties.library+". "]:["","",""]},g=function(){return e.properties.appName?[e.properties.appName+". ",e.properties.appName+". ",e.properties.appName+". "]:["","",""]},h=function(){return e.properties.appLink?[e.properties.appLink+". ",e.properties.appLink+". ",e.properties.appLink+". "]:["","",""]},c=function(){return["","",""]},p=function(F,z){return F.length>z?F.substring(0,z)+"...":F},w=o()[0]+l()[0]+y()[0]+f()[0]+_()[0]+s()[0]+m()[0]+v()[0]+g()[0]+h()[0],A=o()[2]+s()[2]+l()[2]+f()[2]+u()[2]+y()[2]+m()[2]+_()[2]+v()[2]+g()[2]+h()[2],E=o()[1]+l()[1]+y()[1]+f()[1]+_()[1]+s()[1]+c()[1]+v()[1]+g()[1]+h()[1],b="\u201C"+p(i,e.properties.characters)+"\u201C<br><br>"+w,C="\u201C"+p(i,e.properties.characters)+"\u201C<br><br>"+A,k="\u201C"+p(i,e.properties.characters)+"\u201C<br><br>"+E,R="";(B=e.properties.styles)!=null&&B.includes(vh[0])&&(e.properties.styles.length>1&&(R=R+"Chicago: <br>"),R=R+b+"<br><br>"),(I=e.properties.styles)!=null&&I.includes(vh[2])&&(e.properties.styles.length>1&&(R=R+"APA: <br>"),R=R+C+"<br><br>"),(D=e.properties.styles)!=null&&D.includes(vh[1])&&(e.properties.styles.length>1&&(R=R+"MLA: <br>"),R=R+k+"<br><br>"),e.copyToClipboard(R)}};(r=this.highlighter)==null||r.addSelectionMenuItem(t)}};var yn=rt($t());var Tt=class n extends bh{constructor(t,r=void 0,i=void 0,o,s,l,f,u,y,m,_,v,g,h){super();this.iframes=[];this.sideNavExpanded=!1;this.currentChapterLink={href:""};this.currentSpreadLinks={};this.rights={autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};this.didInitKeyboardEventHandler=!1;this.onResize=()=>{clearTimeout(this.timeout),this.timeout=setTimeout(this.handleResize.bind(this),200)};this.reload=async()=>{let t;if(this.annotator&&(t=await this.annotator.getLastReadingPosition()),t){let r=this.publication.getAbsoluteHref(t.href);yn.default.log(t.href),yn.default.log(r),t.href=r,await this.navigate(t)}};this.savePosition=(0,_h.default)(()=>{this.annotator&&this.saveCurrentReadingPosition()},200);this.checkResourcePosition=(0,_h.default)(()=>{var t,r,i,o,s,l,f,u,y,m;(t=this.view)!=null&&t.atStart()&&((r=this.view)!=null&&r.atEnd())?((i=this.api)!=null&&i.resourceFitsScreen&&((o=this.api)==null||o.resourceFitsScreen()),this.emit("resource.fits")):(s=this.view)!=null&&s.atEnd()?((l=this.api)!=null&&l.resourceAtEnd&&((f=this.api)==null||f.resourceAtEnd()),this.emit("resource.end")):(u=this.view)!=null&&u.atStart()&&((y=this.api)!=null&&y.resourceAtStart&&((m=this.api)==null||m.resourceAtStart()),this.emit("resource.start"))},200);this.highlighter=g,this.highlighter&&(this.highlighter.navigator=this);for(let c in h){let p=h[c];p&&(p.navigator=this),h[c]instanceof qa&&(this.annotationModule=p),h[c]instanceof Ga&&(this.bookmarkModule=p),h[c]instanceof Hs&&(this.ttsModule=p),h[c]instanceof Hs&&(this.ttsModule=p),h[c]instanceof iu&&(this.searchModule=p),h[c]instanceof su&&(this.definitionsModule=p),h[c]instanceof za&&(this.timelineModule=p),h[c]instanceof Bs&&(this.contentProtectionModule=p),h[c]instanceof js&&(this.citationModule=p),h[c]instanceof Wa&&(this.mediaOverlayModule=p),h[c]instanceof ou&&(this.pageBreakModule=p),h[c]instanceof Us&&(this.lineFocusModule=p),h[c]instanceof au&&(this.historyModule=p),h[c]instanceof ja&&(this.consumptionModule=p)}this.settings=t,this.annotator=r,this.view=t.view,this.view.attributes=y,this.view.navigator=this,this.eventHandler=new _l(this),this.touchEventHandler=new Hl(this),this.keyboardEventHandler=new Ul(this),this.initialLastReadingPosition=i,this.publication=o,this.api=s,this.rights=l??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1},this.tts=f,this.injectables=u,this.attributes=y||{margin:0},this.services=m,this.sample=_,this.requestConfig=v,this.sampleReadEventHandler=new jl(this)}static async create(t){let r=new this(t.settings,t.annotator||void 0,t.initialLastReadingPosition||void 0,t.publication,t.api,t.rights,t.tts,t.injectables,t.attributes||{margin:0},t.services,t.sample,t.requestConfig,t.highlighter,t.modules);return await r.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(i=>i(r))}stop(){yn.default.log("Iframe navigator stop"),Ue(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),Ue(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),Ue(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ue(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),Ue(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ue(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),Ue(this.tryAgainButton,"click",this.tryAgain.bind(this)),Ue(this.goBackButton,"click",n.goBack.bind(this)),Ue(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),Ue(window,"resize",this.onResize),this.iframes.forEach(t=>{Ue(t,"resize",this.onResize)}),this.didInitKeyboardEventHandler&&this.keyboardEventHandler.removeEvents(document)}setDirection(t){var i,o;let r="";(t==="rtl"||t==="ltr")&&(r=t),t==="auto"&&(r=this.publication.Metadata.Direction2),r&&(r==="rtl"&&(this.spreads.style.flexDirection="row-reverse"),r==="ltr"&&(this.spreads.style.flexDirection="row"),this.keyboardEventHandler.rtl=r==="rtl",(i=this.api)!=null&&i.direction&&((o=this.api)==null||o.direction(r)),this.emit("direction",r))}async start(t,r,i){var g,h,c,p,w,A,E,b,C,k,R,B,I,D,F,z,q;this.headerMenu=r,this.mainElement=t;try{let G=yt(t,"main#iframe-wrapper");G.style.overflow="auto";let Y=Le(t,"main#iframe-wrapper iframe"),X=Le(t,"#second");if(Y&&this.iframes.push(Y),X&&this.iframes.push(X),window.matchMedia("screen and (max-width: 600px)").matches&&(this.settings.columnCount=1),this.iframes.length===0){G.style.overflow="auto";let Q=document.createElement("iframe");if(Q.setAttribute("SCROLLING","no"),Q.setAttribute("allowtransparency","true"),this.iframes.push(Q),this.publication.isFixedLayout){this.spreads=document.createElement("div"),this.firstSpread=document.createElement("div"),this.spreads.style.display="flex",this.spreads.style.alignItems="center",this.spreads.style.justifyContent="center",this.spreads.appendChild(this.firstSpread),this.firstSpread.appendChild(this.iframes[0]),G.appendChild(this.spreads);let se="";switch(this.settings.direction){case 0:se="auto";break;case 1:se="ltr";break;case 2:se="rtl";break}this.setDirection(se)}else Q.setAttribute("height","100%"),Q.setAttribute("width","100%"),G.appendChild(this.iframes[0]);if(this.publication.isFixedLayout)if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){let se=document.createElement("div");this.spreads.appendChild(se);let ve=document.createElement("iframe");ve.setAttribute("SCROLLING","no"),ve.setAttribute("allowtransparency","true"),ve.style.opacity="1",ve.style.border="none",ve.style.overflow="hidden",this.iframes.push(ve),se.appendChild(this.iframes[1]),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",se.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",se.style.boxShadow="0 0 8px 2px #ccc"}else this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc";else this.iframes[0].style.paddingTop=(((g=this.attributes)==null?void 0:g.iframePaddingTop)??0)+"px"}if(this.publication.isFixedLayout){let Q=G.clientHeight;var o=(h=this.iframes[0].parentElement)==null?void 0:h.parentElement;o.style.height=Q+40+"px"}else this.iframes.length===2&&this.iframes.pop();if(this.loadingMessage=Le(t,"#reader-loading"),this.loadingMessage&&(this.loadingMessage.innerHTML=mh,this.loadingMessage.style.display="none"),this.errorMessage=Le(t,"#reader-error"),this.errorMessage&&(this.errorMessage.innerHTML=bE,this.errorMessage.style.display="none"),this.tryAgainButton=Le(t,"button[class=try-again]"),this.goBackButton=Le(t,"button[class=go-back]"),this.infoTop=Le(t,"div[class='info top']"),this.infoBottom=Le(t,"div[class='info bottom']"),this.headerMenu&&(this.bookTitle=Le(this.headerMenu,"#book-title")),this.infoBottom&&(this.chapterTitle=Le(this.infoBottom,"span[class=chapter-title]")),this.infoBottom&&(this.chapterPosition=Le(this.infoBottom,"span[class=chapter-position]")),this.infoBottom&&(this.remainingPositions=Le(this.infoBottom,"span[class=remaining-positions]")),this.headerMenu&&(this.espandMenuIcon=Le(this.headerMenu,"#expand-menu")),this.headerMenu&&(this.links=Le(this.headerMenu,"ul.links.top")),this.headerMenu&&(this.linksTopLeft=Le(this.headerMenu,"#nav-mobile-left")),this.headerMenu&&(this.tocView=Le(this.headerMenu,"#container-view-toc")),this.headerMenu&&(this.landmarksView=Le(this.headerMenu,"#container-view-landmarks")),this.headerMenu&&(this.landmarksSection=Le(this.headerMenu,"#sidenav-section-landmarks")),this.headerMenu&&(this.pageListView=Le(this.headerMenu,"#container-view-pagelist")),i&&(this.linksBottom=Le(i,"ul.links.bottom")),i&&(this.linksMiddle=Le(i,"ul.links.middle")),this.headerMenu&&(this.nextChapterAnchorElement=Le(this.headerMenu,"a[rel=next]")),this.headerMenu&&(this.nextChapterBottomAnchorElement=Le(t,"#next-chapter")),i&&(this.nextPageAnchorElement=Le(i,"a[rel=next]")),this.headerMenu&&(this.previousChapterAnchorElement=Le(this.headerMenu,"a[rel=prev]")),this.headerMenu&&(this.previousChapterTopAnchorElement=Le(t,"#previous-chapter")),i&&(this.previousPageAnchorElement=Le(i,"a[rel=prev]")),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.newPosition=void 0,this.newElementId=void 0,this.isBeingStyled=!0,this.isLoading=!0,this.settings.setIframe(this.iframes[0]),this.settings.onSettingsChange(this.handleResize.bind(this)),this.settings.onColumnSettingsChange(this.handleNumberOfIframes.bind(this)),this.settings.onViewChange(this.updateBookView.bind(this)),this.initialLastReadingPosition&&((c=this.annotator)==null||c.initLastReadingPosition(this.initialLastReadingPosition)),this.headerMenu){var s=Le(this.headerMenu,"#menu-button-search"),l=Le(this.headerMenu,"#menu-button-tts"),f=Le(this.headerMenu,"#menu-button-bookmark"),u=Le(this.headerMenu,"#menu-button-play"),y=Le(this.headerMenu,"#menu-button-pause"),m=Le(this.headerMenu,"#menu-button-mediaoverlay");if(!this.rights.enableBookmarks){f&&((p=f.parentElement)==null||p.style.setProperty("display","none"));var _=Le(this.headerMenu,"#sidenav-section-bookmarks");_&&_.style.setProperty("display","none")}if(!this.rights.enableAnnotations){var v=Le(this.headerMenu,"#sidenav-section-highlights");v&&v.style.setProperty("display","none")}this.rights.enableTTS||l&&((w=l.parentElement)==null||w.style.setProperty("display","none")),this.rights.enableSearch||s&&((A=s.parentElement)==null||A.style.setProperty("display","none")),s&&((E=this.view)!=null&&E.navigator.publication.isFixedLayout)&&((b=s.parentElement)==null||b.style.setProperty("display","none")),this.hasMediaOverlays?(u&&((C=u.parentElement)==null||C.style.removeProperty("display")),y&&((k=y.parentElement)==null||k.style.removeProperty("display")),m&&((R=m.parentElement)==null||R.style.removeProperty("display"))):(u&&((B=u.parentElement)==null||B.style.setProperty("display","none")),y&&((I=y.parentElement)==null||I.style.setProperty("display","none")),m&&((D=m.parentElement)==null||D.style.setProperty("display","none")))}else s&&((F=s.parentElement)==null||F.style.setProperty("display","none")),l&&((z=l.parentElement)==null||z.style.setProperty("display","none")),f&&((q=f.parentElement)==null||q.style.setProperty("display","none"));return this.setupEvents(),await this.loadManifest()}catch(G){return yn.default.error(G),this.abortOnError(G),Promise.reject(G)}}setupEvents(){for(let t of this.iframes)we(t,"load",this.handleIFrameLoad.bind(this,t));we(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),we(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),we(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),we(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),we(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),we(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),we(this.tryAgainButton,"click",this.tryAgain.bind(this)),we(this.goBackButton,"click",n.goBack.bind(this)),we(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),we(window,"resize",this.onResize);for(let t of this.iframes)we(t,"resize",this.onResize)}updateBookView(t){var r;((r=this.view)==null?void 0:r.layout)==="fixed"?(this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="none"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.eventHandler&&(this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousChapterClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextChapterClick.bind(this),this.keyboardEventHandler.onKeydown=this.handleKeydownFallthrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this))):(this.settings.isPaginated().then(i=>{var o,s,l,f,u,y;if(i)this.view.height=gi()-40-(((o=this.attributes)==null?void 0:o.margin)??0),this.infoBottom&&this.infoBottom.style.removeProperty("display"),document.body.onscroll=()=>{},this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="unset"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="unset"),this.chapterTitle&&(this.chapterTitle.style.display="inline"),this.chapterPosition&&(this.chapterPosition.style.display="inline"),this.remainingPositions&&(this.remainingPositions.style.display="inline"),this.eventHandler&&(this.eventHandler.onInternalLink=this.handleInternalLink.bind(this),this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this),this.keyboardEventHandler.onKeydown=this.handleKeydownFallthrough.bind(this));else{this.infoBottom&&(this.infoBottom.style.display="none"),this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="none"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="none"),((s=this.view)==null?void 0:s.layout)==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")):(l=this.view)!=null&&l.atStart()&&((f=this.view)!=null&&f.atEnd())?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(u=this.view)!=null&&u.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):(y=this.view)!=null&&y.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"));let m=(0,_h.default)(()=>{this.isScrolling=!1},200),_=yt(document,"#iframe-wrapper");_.onscroll=async()=>{var v,g;this.isScrolling=!0,await this.savePosition(),(v=this.view)!=null&&v.atEnd(),((g=this.view)==null?void 0:g.layout)==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")):(this.settings.isPaginated().then(h=>{var c,p,w,A;h||((c=this.view)!=null&&c.atStart()&&((p=this.view)!=null&&p.atEnd())?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(w=this.view)!=null&&w.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):(A=this.view)!=null&&A.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")))}),this.checkResourcePosition()),m()},this.chapterTitle&&(this.chapterTitle.style.display="none"),this.chapterPosition&&(this.chapterPosition.style.display="none"),this.remainingPositions&&(this.remainingPositions.style.display="none"),this.eventHandler&&(this.eventHandler.onInternalLink=this.handleInternalLink.bind(this),this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this),this.keyboardEventHandler.onKeydown=this.handleKeydownFallthrough.bind(this))}}),t!=null&&t.skipDrawingAnnotations||setTimeout(async()=>{var i;await((i=this.highlighter)==null?void 0:i.prepareContainers(this.iframes[0].contentWindow)),this.highlighter&&(this.rights.enableAnnotations&&this.annotationModule&&await this.annotationModule.drawHighlights(),this.rights.enableBookmarks&&this.bookmarkModule&&await this.bookmarkModule.drawBookmarks(),this.rights.enableSearch&&this.searchModule&&(await this.highlighter.destroyHighlights(1),this.searchModule.drawSearch()),this.rights.enablePageBreaks&&this.pageBreakModule&&(await this.highlighter.destroyHighlights(3),await this.pageBreakModule.drawPageBreaks()),this.rights.enableDefinitions&&this.definitionsModule&&await this.definitionsModule.drawDefinitions())},200))}async loadManifest(){var t,r,i,o,s;try{let l=(g,h,c=!1)=>{var p=document.createElement("ul");c&&(p=document.createElement("ol")),p.className="sidenav-toc";for(let w of h){let A=document.createElement("li"),E=document.createElement("a"),b=document.createElement("span");E.className="chapter-link",E.tabIndex=-1;let C="";w.Href?(C=this.publication.getAbsoluteHref(w.Href),E.href=C,E.innerHTML=w.Title||"",A.appendChild(E)):(b.innerHTML=w.Title||"",b.className="chapter-title",A.appendChild(b)),w.Children&&w.Children.length>0&&l(A,w.Children,!0),p.appendChild(A)}we(p,"click",w=>{if(w.preventDefault(),w.stopPropagation(),w.target&&w.target.tagName.toLowerCase()==="a"){let A=w.target;if(A.className.indexOf("active")!==-1)this.hideView();else{let E={progression:0};if(A.href.indexOf("#")!==-1){let C=A.href.slice(A.href.indexOf("#")+1);C!==void 0&&(E={fragment:C})}let b={href:A.href,locations:E,type:A.type,title:A.title};this.hideView(),this.navigate(b)}}}),g.appendChild(p)},f=this.publication.tableOfContents,u=this.publication.landmarks,y=this.publication.pageList;this.tocView&&(f.length?l(this.tocView,f):(r=(t=this.tocView.parentElement)==null?void 0:t.parentElement)==null||r.removeChild(this.tocView.parentElement)),this.pageListView&&(y!=null&&y.length?l(this.pageListView,y):(o=(i=this.pageListView.parentElement)==null?void 0:i.parentElement)==null||o.removeChild(this.pageListView.parentElement)),this.landmarksView&&(u!=null&&u.length?l(this.landmarksView,u):(s=this.landmarksSection.parentElement)==null||s.removeChild(this.landmarksSection));let m;this.annotator&&(m=await this.annotator.getLastReadingPosition());let _=this.publication.getStartLink(),v;if(_&&_.Href&&(v=this.publication.getAbsoluteHref(_.Href)),m){let g=this.publication.getAbsoluteHref(m.href);yn.default.log(m.href),yn.default.log(g),m.href=g,await this.navigate(m)}else if(v){let g={href:v,locations:{progression:0},created:new Date,title:_==null?void 0:_.Title};await this.navigate(g)}return new Promise(g=>g())}catch(l){return yn.default.error(l),this.abortOnError(l),new Promise((f,u)=>u(l)).catch(()=>{})}}async handleIFrameLoad(t){var r,i,o,s,l,f,u;this.errorMessage&&(this.errorMessage.style.display="none"),this.showLoadingMessageAfterDelay();try{let y=0;this.newPosition&&(y=this.newPosition.locations.progression),await this.handleResize(),this.updateBookView({skipDrawingAnnotations:!0}),await this.settings.applyProperties();let m=this.currentChapterLink.href;if(m){let p=this.publication.getPreviousSpineItem(m);p&&p.Href&&(this.previousChapterLink={href:p.Href,title:p.Title,type:p.TypeLink})}this.previousChapterAnchorElement&&(this.previousChapterLink&&this.previousChapterLink.href?(this.previousChapterAnchorElement.href=this.publication.getAbsoluteHref(this.previousChapterLink.href),this.previousChapterAnchorElement.className=this.previousChapterAnchorElement.className.replace(" disabled","")):(this.previousChapterAnchorElement.removeAttribute("href"),this.previousChapterAnchorElement.className+=" disabled"));let _=this.publication.getNextSpineItem(m);_?this.nextChapterLink={href:_.Href,title:_.Title,type:_.TypeLink}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink&&this.nextChapterLink.href?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.historyModule&&this.historyModule.setup(),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(m),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let v=this.publication.getSpineItem(m);v!==void 0&&(this.currentChapterLink.title=v.Title,this.currentChapterLink.type=v.TypeLink);let g=this.publication.getTOCItem(m);this.currentTocUrl!==void 0&&(g=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&g!==void 0&&g.Title&&(this.currentChapterLink.title=g.Title),!this.currentChapterLink.type&&g!==void 0&&g.TypeLink&&(this.currentChapterLink.title=g.Title),this.currentChapterLink.title?this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"):this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),await this.injectInjectablesIntoIframeHead(t),((r=this.view)==null?void 0:r.layout)!=="fixed"&&this.highlighter!==void 0&&await this.highlighter.initialize(t);let h=(i=t.contentDocument)==null?void 0:i.body,c=h==null?void 0:h.querySelector("details");if(c){let p=this;c.addEventListener("toggle",async w=>{var A,E;await((E=(A=p.view)==null?void 0:A.setIframeHeight)==null?void 0:E.call(A,t))})}if(this.eventHandler&&(this.eventHandler.setupEvents(t.contentDocument),this.touchEventHandler.setupEvents(t.contentDocument),this.keyboardEventHandler.setupEvents(t.contentDocument),this.touchEventHandler.setupEvents(this.errorMessage),this.didInitKeyboardEventHandler||(this.keyboardEventHandler.keydown(document),this.didInitKeyboardEventHandler=!0)),((o=this.view)==null?void 0:o.layout)!=="fixed"&&(s=this.view)!=null&&s.isScrollMode()&&(t.height="0",(f=(l=this.view)==null?void 0:l.setIframeHeight)==null||f.call(l,t)),this.rights.enableContentProtection&&this.contentProtectionModule&&await this.contentProtectionModule.initialize(t),this.rights.enableConsumption&&this.consumptionModule&&await this.consumptionModule.initialize(t),this.rights.enableAnnotations&&this.annotationModule&&await this.annotationModule.initialize(t),this.rights.enableBookmarks&&this.bookmarkModule&&await this.bookmarkModule.initialize(),this.rights.enableLineFocus&&this.lineFocusModule&&await this.lineFocusModule.initialize(t),this.rights.enableTTS&&this.ttsModule){let p=(u=t.contentDocument)==null?void 0:u.body;await this.ttsModule.initialize(p)}return this.rights.enableTimeline&&this.timelineModule&&await this.timelineModule.initialize(),this.rights.enableMediaOverlays&&this.mediaOverlayModule&&this.hasMediaOverlays&&await this.mediaOverlayModule.initialize(),setTimeout(async()=>{var p,w,A,E,b,C,k,R;if(this.newElementId){let B=t.contentDocument.getElementById(this.newElementId);(w=(p=this.view)==null?void 0:p.goToElement)==null||w.call(p,B),this.newElementId=void 0}else if(this.newPosition&&this.newPosition.highlight){let B=(A=this.newPosition.highlight)==null?void 0:A.selectionInfo.rangeInfo.startContainerElementCssSelector;B&&((E=this.view)==null||E.goToCssSelector(B))}else y&&y>=0&&((b=this.view)==null||b.goToProgression(y));if(this.newPosition=void 0,(C=this.rights)!=null&&C.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.recalculate(10),this.hideLoadingMessage(),this.showIframeContents(t),this.rights.enableMediaOverlays&&this.mediaOverlayModule&&this.hasMediaOverlays){let B=this.currentLink();await((k=this.mediaOverlayModule)==null?void 0:k.initializeResource(B))}await this.updatePositionInfo(),await((R=this.view)==null?void 0:R.setSize()),setTimeout(()=>{this.mediaOverlayModule&&(this.mediaOverlayModule.settings.resourceReady=!0)},300)},200),new Promise(p=>p())}catch(y){return yn.default.error(y),this.abortOnError(y),Promise.reject(y)}}async injectInjectablesIntoIframeHead(t){var s,l;let r=[],i=f=>{let u=new Promise((y,m)=>{f.onload=()=>{y(!0)},f.onerror=_=>{let v=typeof _=="string"?_:`Injectable failed to load at: ${"href"in f?f.href:f.src}`;m(new Error(v))}});r.push(u)},o=(s=t.contentDocument)==null?void 0:s.head;o&&(t.contentDocument.getElementsByTagName("base").length===0&&o.insertBefore(n.createBase(this.currentChapterLink.href),o.firstChild),(l=this.injectables)==null||l.forEach(u=>{if(u.type==="style"){if(u.fontFamily){if(this.settings.initAddedFont(),!u.systemFont&&u.url){let y=n.createCssLink(u.url);o.appendChild(y),i(y)}}else if(u.r2before&&u.url){let y=n.createCssLink(u.url);o.insertBefore(y,o.firstChild),i(y)}else if(u.r2default&&u.url){let y=n.createCssLink(u.url);o.insertBefore(y,o.childNodes[1]),i(y)}else if(u.r2after&&u.url){u.appearance&&this.settings.initAddedAppearance();let y=n.createCssLink(u.url);o.appendChild(y),i(y)}else if(u.url){let y=n.createCssLink(u.url);o.appendChild(y),i(y)}}else if(u.type==="script"&&u.url){let y=n.createJavascriptLink(u.url,u.async??!1);o.appendChild(y),i(y)}})),r.length!==0&&await Promise.all(r)}abortOnError(t){var r;if((r=this.api)!=null&&r.onError){let i=t instanceof Error?t:typeof t=="string"?new Error(t):new Error("An unknown error occurred in the IFrameNavigator.");this.api.onError(i)}else this.errorMessage&&(this.errorMessage.style.display="block"),this.isLoading&&this.hideLoadingMessage()}tryAgain(){this.precessContentForIframe()}precessContentForIframe(){var u,y,m,_,v,g;let t=this;var r=this.publication.getSpineIndex(this.currentChapterLink.href),i=(r??0)%2===1;this.showLoadingMessageAfterDelay();function o(h,c){let w=new DOMParser().parseFromString(h,"application/xhtml+xml");w.head&&w.getElementsByTagName("base").length===0&&w.head.insertBefore(n.createBase(c),w.head.firstChild);let A=w.documentElement.outerHTML,E=t.iframes[0].contentDocument;E&&(E.open(),E.write(A),E.close())}function s(h,c){let w=new DOMParser().parseFromString(h,"application/xhtml+xml");w.head&&w.getElementsByTagName("base").length===0&&w.head.insertBefore(n.createBase(c),w.head.firstChild);let A=w.documentElement.outerHTML,E=t.iframes[1].contentDocument;E&&(E.open(),E.write(A),E.close())}let l=new URL(this.currentChapterLink.href),f=window.location.protocol===l.protocol&&window.location.port===l.port&&window.location.hostname===l.hostname;if((u=this.api)!=null&&u.getContent)if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(i){if(this.currentSpreadLinks.left={href:this.currentChapterLink.href},(y=this.api)==null||y.getContent(this.currentChapterLink.href).then(h=>{h===void 0?f?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{o.call(this,c,this.currentChapterLink.href)}):o.call(this,h,this.currentChapterLink.href)}),this.iframes.length===2)if((r??0)<this.publication.readingOrder.length-1){let h=this.publication.getNextSpineItem(this.currentChapterLink.href);if(h){let c=this.publication.getAbsoluteHref(h.Href);this.currentSpreadLinks.right={href:c},(m=this.api)==null||m.getContent(c).then(p=>{p===void 0?f?this.iframes[1].src=c:fetch(c,this.requestConfig).then(w=>w.text()).then(async w=>{s.call(this,w,c),this.currentSpreadLinks.right={href:c}}):s.call(this,p,c)})}}else this.iframes[1].src="about:blank"}else{if((r??0)>0){let h=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(h){let c=this.publication.getAbsoluteHref(h.Href);this.currentSpreadLinks.left={href:c},(_=this.api)==null||_.getContent(c).then(p=>{p===void 0?f?this.iframes[0].src=c:fetch(c,this.requestConfig).then(w=>w.text()).then(async w=>{o.call(this,w,c)}):o.call(this,p,c)})}}else this.iframes[0].src="about:blank";this.iframes.length===2&&this.publication.isFixedLayout&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},this.api.getContent(this.currentChapterLink.href).then(h=>{h===void 0?f?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{s.call(this,c,this.currentChapterLink.href)}):s.call(this,h,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},(v=this.api)==null||v.getContent(this.currentChapterLink.href).then(h=>{h===void 0?f?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{o.call(this,c,this.currentChapterLink.href)}):o.call(this,h,this.currentChapterLink.href)});else(g=this.api)==null||g.getContent(this.currentChapterLink.href).then(h=>{this.currentSpreadLinks.left={href:this.currentChapterLink.href},h===void 0?f?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{o.call(this,c,this.currentChapterLink.href)}):o.call(this,h,this.currentChapterLink.href)});else if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(i){if(f){if(this.iframes[0].src=this.currentChapterLink.href,this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.iframes.length===2)if((r??0)<this.publication.readingOrder.length-1){let h=this.publication.getNextSpineItem(this.currentChapterLink.href);if(h){let c=this.publication.getAbsoluteHref(h.Href);this.iframes[1].src=c,this.currentSpreadLinks.right={href:c}}}else this.iframes[1].src="about:blank"}else if(fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)}),this.iframes.length===2)if((r??0)<this.publication.readingOrder.length-1){let h=this.publication.getNextSpineItem(this.currentChapterLink.href);if(h){let c=this.publication.getAbsoluteHref(h.Href);this.currentSpreadLinks.right={href:c},fetch(c,this.requestConfig).then(p=>p.text()).then(async p=>{s.call(this,p,c)})}}else this.iframes[1].src="about:blank"}else if((r??0)>0){let h=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(h){let c=this.publication.getAbsoluteHref(h.Href);this.currentSpreadLinks.left={href:c},f?(this.iframes[0].src=c,this.iframes.length===2&&(this.iframes[1].src=this.currentChapterLink.href)):(fetch(c,this.requestConfig).then(p=>p.text()).then(async p=>{o.call(this,p,c)}),this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},fetch(this.currentChapterLink.href,this.requestConfig).then(p=>p.text()).then(async p=>{s.call(this,p,this.currentChapterLink.href)})))}}else this.iframes[0].src="about:blank",this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},f?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{s.call(this,h,this.currentChapterLink.href)}));else this.currentSpreadLinks.left={href:this.currentChapterLink.href},f?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)});else this.currentSpreadLinks.left={href:this.currentChapterLink.href},f?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)});this.publication.isFixedLayout&&setTimeout(()=>{var R,B,I;let h,c,p;if(r===0&&((R=this.iframes)==null?void 0:R.length)===2?p=this.iframes[1].contentDocument:p=this.iframes[0].contentDocument,p&&p.body&&(h=getComputedStyle(p.body).height,c=getComputedStyle(p.body).width,parseInt(h==null?void 0:h.replace("px",""))===0||parseInt(c==null?void 0:c.replace("px",""))===0)){let D=cr(p,"head");if(D){let F=Le(D,"meta[name=viewport]");if(F){var w=F.content,A=w.split(",").reduce((z,q)=>{var[G,Y]=q.match(/[^\s;=]+/g);return z[G]=isNaN(Number(Y))?Y:+Y,z},{});h=A.height+"px",c=A.width+"px"}}}var E=r===0&&this.iframes.length===2?(B=this.iframes[1].parentElement)==null?void 0:B.parentElement:(I=this.iframes[0].parentElement)==null?void 0:I.parentElement;if(E&&c){var b=(parseInt(getComputedStyle(E).width)-100)/(this.iframes.length===2?parseInt(c==null?void 0:c.replace("px",""))*2+200:parseInt(c==null?void 0:c.replace("px",""))),C=(parseInt(getComputedStyle(E).height)-100)/parseInt(h==null?void 0:h.replace("px","")),k=Math.min(b,C);E.style.transform="scale("+k+")";for(let D of this.iframes)D.style.height=h,D.style.width=c,D.parentElement&&(D.parentElement.style.height=h)}},400)}static goBack(){window.history.back()}handleEditClick(t){var o,s,l,f;var r=t.target;if(this.headerMenu){var i=Le(document,".sidenav");r.className.indexOf(" active")===-1?(r.className+=" active",i.className+=" expanded",r.innerText="unfold_less",this.sideNavExpanded=!0,(o=this.bookmarkModule)==null||o.showBookmarks(),(s=this.annotationModule)==null||s.showHighlights()):(r.className=r.className.replace(" active",""),i.className=i.className.replace(" expanded",""),r.innerText="unfold_more",this.sideNavExpanded=!1,(l=this.bookmarkModule)==null||l.showBookmarks(),(f=this.annotationModule)==null||f.showHighlights())}t.preventDefault(),t.stopPropagation()}get hasMediaOverlays(){return this.publication.hasMediaOverlays}startReadAloud(){this.rights.enableTTS&&this.ttsModule.speakPlay()}startReadAlong(){var t;this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&((t=this.mediaOverlayModule)==null||t.startReadAloud())}stopReadAloud(){var t;this.rights.enableTTS&&((t=this.highlighter)==null||t.stopReadAloud())}stopReadAlong(){var t;this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&((t=this.mediaOverlayModule)==null||t.stopReadAloud())}pauseReadAloud(){this.rights.enableTTS&&(this.ttsModule.speakPause(),this.annotationModule!==void 0&&this.annotationModule.drawHighlights())}pauseReadAlong(){var t;this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&((t=this.mediaOverlayModule)==null||t.pauseReadAloud())}resumeReadAloud(){this.rights.enableTTS&&this.ttsModule.speakResume()}resumeReadAlong(){var t;this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&((t=this.mediaOverlayModule)==null||t.resumeReadAloud())}totalResources(){return this.publication.readingOrder.length}mostRecentNavigatedTocItem(){return this.publication.getRelativeHref(this.currentTOCRawLink)}currentResource(){let t=this.currentChapterLink.href;return this.publication.getSpineIndex(t)}currentLink(){if(this.settings.columnCount!==1&&this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0){let r=this.publication.getSpineItem(this.currentSpreadLinks.left.href),i=this.publication.getSpineItem(this.currentSpreadLinks.right.href);return[r,i]}let t=this.currentChapterLink.href;return[this.publication.getSpineItem(t)]}tableOfContents(){return this.publication.tableOfContents}landmarks(){return this.publication.landmarks}pageList(){return this.publication.pageList}readingOrder(){return this.publication.readingOrder}atStart(){var t;return((t=this.view)==null?void 0:t.atStart())??!1}atEnd(){var t;return((t=this.view)==null?void 0:t.atEnd())??!1}previousPage(){this.handlePreviousPageClick(void 0)}nextPage(){this.handleNextPageClick(void 0)}previousResource(){this.handlePreviousChapterClick(void 0)}nextResource(){this.handleNextChapterClick(void 0)}goTo(t){let r=t.locations??{progression:0};if(t.href.indexOf("#")!==-1){let s=t.href.slice(t.href.indexOf("#")+1);s!==void 0&&(r={...r,fragment:s})}let i={...t};i.locations=r;let o=this.publication.getAbsoluteHref(t.href);yn.default.log(t.href),yn.default.log(o),i.href=o,this.stopReadAloud(),this.navigate(i)}currentLocator(){var r,i,o,s;let t;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let l=this.publication.positionsByHref(this.publication.getRelativeHref(this.currentChapterLink.href)),f=Math.ceil((((r=this.view)==null?void 0:r.getCurrentPosition())??0)*(l.length-1));t=l[f]}else{let l=this.publication.getTOCItem(this.currentChapterLink.href);l&&(this.currentTocUrl!==void 0&&(l=this.publication.getTOCItem(this.currentTocUrl)),l===void 0&&(l=this.publication.getTOCItemAbsolute(this.currentChapterLink.href)),l&&(t={href:l.Href,type:this.currentChapterLink.type,title:this.currentChapterLink.title,locations:{}}))}return t&&(t.locations.progression=(i=this.view)==null?void 0:i.getCurrentPosition(),t.displayInfo={resourceScreenIndex:Math.round(((o=this.view)==null?void 0:o.getCurrentPage())??0),resourceScreenCount:Math.round(((s=this.view)==null?void 0:s.getPageCount())??0)}),t}positions(){return this.publication.positions?this.publication.positions:[]}goToPosition(t){if(this.publication.positions){let r=this.publication.positions.filter(i=>i.locations.position===parseInt(String(t)))[0];this.goTo(r)}}async goToPage(t){this.pageBreakModule!==void 0&&await this.pageBreakModule.goToPageNumber(t)}snapToSelector(t){var i;let r=this.iframes[0].contentDocument;if(r){yn.default.log(t);let o=r.querySelectorAll(t);o.length>0&&((i=this.view)==null||i.snap(o[0]))}}applyAttributes(t){this.attributes=t,this.view.attributes=t,this.handleResize()}handlePreviousPageClick(t){var r,i,o,s;this.stopReadAloud(),((r=this.view)==null?void 0:r.layout)==="fixed"?this.handlePreviousChapterClick(t):((i=this.view)!=null&&i.atStart()?this.handlePreviousChapterClick(t):((s=(o=this.view)==null?void 0:o.goToPreviousPage)==null||s.call(o),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))}handleNextPageClick(t){var i,o,s,l,f,u,y,m,_,v,g,h,c;let r=!0;if((i=this.sample)!=null&&i.isSampleRead&&this.publication.positions){let p=this.currentLocator(),w=Math.round((p.locations.totalProgression??0)*100);(o=this.sample)!=null&&o.limit&&(r=w<=((s=this.sample)==null?void 0:s.limit),((l=this.view)==null?void 0:l.layout)==="fixed"&&((!r&&((f=this.sample)==null?void 0:f.minimum)&&p.locations.position)??0<=(((u=this.sample)==null?void 0:u.minimum)??0))&&(r=!0))}(r&&((y=this.sample)!=null&&y.isSampleRead)&&this.publication.positions||!((m=this.sample)!=null&&m.isSampleRead)||!this.publication.positions)&&(this.stopReadAloud(),((_=this.view)==null?void 0:_.layout)==="fixed"?this.handleNextChapterClick(t):((v=this.view)!=null&&v.atEnd()?this.handleNextChapterClick(t):((h=(g=this.view)==null?void 0:g.goToNextPage)==null||h.call(g),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))),!r&&((c=this.sample)!=null&&c.isSampleRead)&&this.publication.positions&&t&&(t.preventDefault(),t.stopPropagation())}handleClickThrough(t){var r,i;(r=this.api)!=null&&r.clickThrough&&((i=this.api)==null||i.clickThrough(t)),this.emit("click",t)}handleInternalLink(t){let r=t.target,i={progression:0},o=r;if(o.href.indexOf("#")!==-1){let l=o.href.slice(o.href.indexOf("#")+1);l!==void 0&&(i={fragment:l})}let s={href:o.href,locations:i,type:o.type,title:o.title};t.preventDefault(),t.stopPropagation(),this.stopReadAloud(),this.navigate(s)}handleNumberOfIframes(){if(this.publication.isFixedLayout){if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){if(this.iframes.length===1){var t=document.createElement("iframe");t.setAttribute("SCROLLING","no"),t.setAttribute("allowtransparency","true"),t.style.opacity="1",t.style.border="none",t.style.overflow="hidden",this.iframes.push(t)}let r=document.createElement("div");this.spreads.appendChild(r),r.appendChild(this.iframes[1]),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",r.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",r.style.boxShadow="0 0 8px 2px #ccc"}else this.iframes.length===2&&(this.iframes.pop(),this.spreads.lastChild&&this.spreads.removeChild(this.spreads.lastChild)),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc";this.precessContentForIframe()}}async handleResize(){var y,m,_,v,g,h,c;if(this.isScrolling)return;if(this.publication.isFixedLayout){var t=this.publication.getSpineIndex(this.currentChapterLink.href);let p=gi()-40-(((y=this.attributes)==null?void 0:y.margin)??0);var r=t===0&&this.iframes.length===2?(m=this.iframes[1].parentElement)==null?void 0:m.parentElement:(_=this.iframes[0].parentElement)==null?void 0:_.parentElement;if(r){r.style.height=p+40+"px";let w,A,E;t===0&&((v=this.iframes)==null?void 0:v.length)===2?E=this.iframes[1].contentDocument:E=this.iframes[0].contentDocument,E&&E.body&&(w=getComputedStyle(E.body).height,A=getComputedStyle(E.body).width);let b=cr(E,"head");if(b){let C=Le(b,"meta[name=viewport]");if(C){var i=C.content,o=i.split(",").reduce((k,R)=>{var[B,I]=R.match(/[^\s;=]+/g);return k[B]=isNaN(Number(I))?I:+I,k},{});(parseInt(o.height)!==0||parseInt(o.width)!==0)&&(w=o.height.endsWith("px")?o.height:o.height+"px",A=o.width.endsWith("px")?o.width:o.width+"px")}}var s=(parseInt(getComputedStyle(r).width)-100)/(this.iframes.length===2?parseInt(A==null?void 0:A.replace("px",""))*2+200:parseInt(A==null?void 0:A.replace("px",""))),l=(parseInt(getComputedStyle(r).height)-100)/parseInt(w==null?void 0:w.replace("px","")),f=Math.min(s,l);r.style.transform="scale("+f+")";for(let C of this.iframes)C.style.height=w,C.style.width=A,C.parentElement&&(C.parentElement.style.height=w)}}let u=(g=this.view)==null?void 0:g.getCurrentPosition();await this.settings.applyProperties(),this.infoTop&&(this.infoTop.style.height="0px"),this.infoTop&&(this.infoTop.style.minHeight="0px"),this.infoBottom&&(this.infoBottom.style.height=(h=this.attributes)!=null&&h.bottomInfoHeight?this.attributes.bottomInfoHeight+"px":"40px"),((c=this.view)==null?void 0:c.layout)!=="fixed"&&this.settings.isPaginated().then(p=>{var w;p?(this.view.height=gi()-40-(((w=this.attributes)==null?void 0:w.margin)??0),this.infoBottom&&this.infoBottom.style.removeProperty("display")):this.infoBottom&&(this.infoBottom.style.display="none")}),setTimeout(()=>{var p,w,A,E;((p=this.view)==null?void 0:p.layout)!=="fixed"&&(w=this.view)!=null&&w.isScrollMode()&&((E=(A=this.view)==null?void 0:A.setIframeHeight)==null||E.call(A,this.iframes[0]))},100),setTimeout(async()=>{var p;u&&((p=this.view)==null||p.goToProgression(u)),this.updatePositionInfo(!1),this.contentProtectionModule!==void 0&&await this.contentProtectionModule.handleResize(),this.annotationModule!==void 0&&await this.annotationModule.handleResize(),this.bookmarkModule!==void 0&&await this.bookmarkModule.handleResize(),this.searchModule!==void 0&&await this.searchModule.handleResize(),this.definitionsModule!==void 0&&await this.definitionsModule.handleResize(),this.pageBreakModule!==void 0&&await this.pageBreakModule.handleResize(),this.lineFocusModule!==void 0&&this.lineFocusModule.handleResize(),this.historyModule!==void 0&&await this.historyModule.handleResize()},150)}updatePositionInfo(t=!0){var r,i;if(((r=this.view)==null?void 0:r.layout)==="fixed")this.chapterPosition&&(this.chapterPosition.innerHTML=""),this.remainingPositions&&(this.remainingPositions.innerHTML="");else if((i=this.view)!=null&&i.isPaginated()){let o=this.currentLocator();if(o){let s=o.displayInfo.resourceScreenIndex,l=o.displayInfo.resourceScreenCount;this.chapterPosition&&(this.chapterPosition.innerHTML="Page "+s+" of "+l)}}else this.chapterPosition&&(this.chapterPosition.innerHTML=""),this.remainingPositions&&(this.remainingPositions.innerHTML="");t&&this.savePosition()}handlePreviousChapterClick(t){var r;if(((r=this.view)==null?void 0:r.layout)==="fixed"&&this.settings.columnCount!==1){let i=this.publication.getSpineIndex(this.currentChapterLink.href)??0;i=i-2,i<0&&(i=0);let o=this.publication.readingOrder[i],s={href:this.publication.getAbsoluteHref(o.Href),locations:{progression:0},type:o.TypeLink,title:o.Title};this.stopReadAloud(),this.navigate(s,!1)}else if(this.previousChapterLink){let i={href:this.publication.getAbsoluteHref(this.previousChapterLink.href),locations:{progression:1},type:this.previousChapterLink.type,title:this.previousChapterLink.title};this.stopReadAloud(),this.navigate(i,!1)}t&&(t.preventDefault(),t.stopPropagation())}handleNextChapterClick(t){var r;if(((r=this.view)==null?void 0:r.layout)==="fixed"&&this.settings.columnCount!==1){let i=this.publication.getSpineIndex(this.currentChapterLink.href)??0;i=i+2,i>=this.publication.readingOrder.length-1&&(i=this.publication.readingOrder.length-1);let o=this.publication.readingOrder[i],s={href:this.publication.getAbsoluteHref(o.Href),locations:{progression:0},type:o.TypeLink,title:o.Title};this.stopReadAloud(),this.navigate(s,!1)}else if(this.nextChapterLink){let i={href:this.publication.getAbsoluteHref(this.nextChapterLink.href),locations:{progression:0},type:this.nextChapterLink.type,title:this.nextChapterLink.title};this.stopReadAloud(),this.navigate(i,!1)}t&&(t.preventDefault(),t.stopPropagation())}handleKeydownFallthrough(t){var r,i;(r=this.api)!=null&&r.keydownFallthrough&&((i=this.api)==null||i.keydownFallthrough(t)),this.emit("keydown",t)}hideView(){var t,r;((t=this.view)==null?void 0:t.layout)!=="fixed"&&(r=this.view)!=null&&r.isScrollMode()&&(document.body.style.overflow="auto")}setActiveTOCItem(t){if(this.tocView){let r=Array.prototype.slice.call(this.tocView.querySelectorAll("li > a"));for(let o of r)o.className=o.className.replace(" active","");let i=this.tocView.querySelector('li > a[href^="'+t+'"]');i&&(i.className+=" active")}}async navigate(t,r=!0){var s,l,f,u,y,m,_,v,g;if(this.rights.enableConsumption&&this.consumptionModule&&r&&this.consumptionModule.startReadingSession(t),this.historyModule&&await this.historyModule.push(t,r),this.publication.getTOCItem(t.href)){var o=!1;if(t.href.indexOf("#")!==-1){let h=t.href.slice(0,t.href.indexOf("#"));h===this.currentChapterLink.href&&(o=!0),this.currentChapterLink.href=h,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title}else t.href===this.currentChapterLink.href&&(o=!0),this.currentChapterLink.href=t.href,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title;if(this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0&&(t.href===this.currentSpreadLinks.left.href||t.href===this.currentSpreadLinks.right.href))return;if(o){if(t.href.indexOf("#")!==-1){let E=t.href.slice(t.href.indexOf("#")+1);t.locations={fragment:E}}if(this.newPosition=t,this.currentTOCRawLink=t.href,t.locations.fragment===void 0?this.currentTocUrl=void 0:(this.newElementId=t.locations.fragment,this.currentTocUrl=this.currentChapterLink.href+"#"+this.newElementId),this.newElementId){for(let E of this.iframes){let b=E.contentDocument.getElementById(this.newElementId);(l=(s=this.view)==null?void 0:s.goToElement)==null||l.call(s,b)}this.newElementId=void 0}else if(t.highlight){let E=(f=t.highlight)==null?void 0:f.selectionInfo.rangeInfo.startContainerElementCssSelector;E&&((u=this.view)==null||u.goToCssSelector(E))}else(y=this.view)==null||y.goToProgression(t.locations.progression??0);let h=this.currentChapterLink.href,c=this.publication.getPreviousSpineItem(h);c&&c.Href&&(this.previousChapterLink={href:c.Href,type:c.TypeLink,title:c.Title}),this.previousChapterAnchorElement&&(this.previousChapterLink?(this.previousChapterAnchorElement.href=this.publication.getAbsoluteHref(this.previousChapterLink.href),this.previousChapterAnchorElement.className=this.previousChapterAnchorElement.className.replace(" disabled","")):(this.previousChapterAnchorElement.removeAttribute("href"),this.previousChapterAnchorElement.className+=" disabled"));let p=this.publication.getNextSpineItem(h);p?this.nextChapterLink={href:p.Href,type:p.TypeLink,title:p.Title}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(h),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let w=this.publication.getSpineItem(h);w!==void 0&&(this.currentChapterLink.title=w.Title,this.currentChapterLink.type=w.TypeLink);let A=this.publication.getTOCItem(h);this.currentTocUrl!==void 0&&(A=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&A!==void 0&&A.Title&&(this.currentChapterLink.title=A.Title),!this.currentChapterLink.type&&A!==void 0&&A.TypeLink&&(this.currentChapterLink.title=A.Title),this.currentChapterLink.title?this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"):this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),await this.updatePositionInfo()}else this.lineFocusModule!==void 0&&this.lineFocusModule.disableLineFocus(!1),this.searchModule!==void 0&&this.searchModule.clearSearch(),t.locations.fragment===void 0?this.currentTocUrl=void 0:(this.newElementId=t.locations.fragment,this.currentTocUrl=this.currentChapterLink.href+"#"+this.newElementId),this.hideIframeContents(),this.showLoadingMessageAfterDelay(),t.locations===void 0&&(t.locations={progression:0}),this.newPosition=t,this.currentTOCRawLink=t.href,this.precessContentForIframe(),this.rights.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.initializeResource(),this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&await this.mediaOverlayModule.initializeResource(this.currentLink()),this.rights.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.recalculate(300),this.bookmarkModule&&(await this.bookmarkModule.drawBookmarks(),await this.bookmarkModule.showBookmarks()),this.pageBreakModule&&(await((m=this.highlighter)==null?void 0:m.destroyHighlights(3)),await this.pageBreakModule.drawPageBreaks()),this.rights.enableSearch&&this.searchModule!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(1),this.searchModule.drawSearch()),this.rights.enableDefinitions&&this.definitionsModule&&this.highlighter&&await this.definitionsModule.drawDefinitions(),this.rights.enableConsumption&&this.consumptionModule&&this.consumptionModule.continueReadingSession(t),((_=this.view)==null?void 0:_.layout)==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),(v=this.api)!=null&&v.resourceFitsScreen&&((g=this.api)==null||g.resourceFitsScreen()),this.emit("resource.fits")):this.settings.isPaginated().then(h=>{var c,p,w,A;h||((c=this.view)!=null&&c.atStart()&&((p=this.view)!=null&&p.atEnd())?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(w=this.view)!=null&&w.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):(A=this.view)!=null&&A.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")))})}else{let h=this.publication.getStartLink(),c;if(h&&h.Href&&(c=this.publication.getAbsoluteHref(h.Href),c)){let p={href:c,locations:{progression:0},created:new Date,title:h.Title};await this.navigate(p)}}}showIframeContents(t){this.isBeingStyled=!1,setTimeout(()=>{this.isBeingStyled||(t.style.opacity="1",t.style.border="none",t.style.overflow="hidden")},150)}showLoadingMessageAfterDelay(){this.isLoading=!0,this.isLoading&&this.loadingMessage&&(this.loadingMessage.style.display="block",this.loadingMessage.classList.add("is-loading")),this.mediaOverlayModule!==void 0&&(this.mediaOverlayModule.settings.resourceReady=!1)}hideIframeContents(){this.isBeingStyled=!0,this.iframes.forEach(t=>{t.style.opacity="0",t.style.border="none",t.style.overflow="hidden"})}hideLoadingMessage(){setTimeout(()=>{var t,r,i,o,s,l,f,u,y,m,_,v,g;this.isLoading=!1,this.loadingMessage&&(this.loadingMessage.style.display="none",this.loadingMessage.classList.remove("is-loading")),((t=this.view)==null?void 0:t.layout)!=="fixed"&&((r=this.view)!=null&&r.atStart()&&((i=this.view)!=null&&i.atEnd())?((o=this.api)!=null&&o.resourceFitsScreen&&((s=this.api)==null||s.resourceFitsScreen()),this.emit("resource.fits")):(l=this.view)!=null&&l.atEnd()?((f=this.api)!=null&&f.resourceAtEnd&&((u=this.api)==null||u.resourceAtEnd()),this.emit("resource.end")):(y=this.view)!=null&&y.atStart()&&((m=this.api)!=null&&m.resourceAtStart&&((_=this.api)==null||_.resourceAtStart()),this.emit("resource.start"))),(v=this.api)!=null&&v.resourceReady&&((g=this.api)==null||g.resourceReady()),this.emit("resource.ready")},150)}saveCurrentReadingPosition(){var r,i,o,s,l,f;if(this.annotator){var t=this.publication.getTOCItem(this.currentChapterLink.href);this.currentTocUrl!==void 0&&(t=this.publication.getTOCItem(this.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.currentChapterLink.href));let u={progression:(r=this.view)==null?void 0:r.getCurrentPosition()};if(t){if(t.Href.indexOf("#")!==-1){let m=t.Href.slice(t.Href.indexOf("#")+1);m!==void 0&&(u={progression:(i=this.view)==null?void 0:i.getCurrentPosition(),fragment:m})}let y;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let m=this.publication.positionsByHref(this.publication.getRelativeHref(t.Href));if(m.length>0){let _=Math.ceil((u.progression??0)*(m.length-1)),v=m[_];v&&(v.locations.fragment=u.fragment,y={...v,href:t.Href,created:new Date,title:this.currentChapterLink.title})}}else y={href:t.Href,locations:u,created:new Date,type:this.currentChapterLink.type,title:this.currentChapterLink.title};y&&((o=this.sample)!=null&&o.isSampleRead&&this.publication.positions&&((s=this.sampleReadEventHandler)==null||s.enforceSampleRead(y)),(l=this.api)!=null&&l.updateCurrentLocation?(f=this.api)==null||f.updateCurrentLocation(y).then(async m=>{var _;return yn.default.log("api updated current location",y),(_=this.annotator)==null?void 0:_.saveLastReadingPosition(y)}):(yn.default.log("save last reading position",y),this.annotator.saveLastReadingPosition(y)),this.consumptionModule&&this.consumptionModule.continueReadingSession(y))}}}static createBase(t){let r=document.createElement("base");return r.target="_self",r.href=t,r}static createCssLink(t){let r=document.createElement("link");return r.rel="stylesheet",r.type="text/css",r.href=t,r}static createJavascriptLink(t,r){let i=document.createElement("script");return i.type="text/javascript",i.src=t,i.async=r,i}activateMarker(t,r){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId===void 0||this.annotationModule.activeAnnotationMarkerId!==t?(this.annotationModule.activeAnnotationMarkerId=t,this.annotationModule.activeAnnotationMarkerPosition=r,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=t)):this.deactivateMarker())}deactivateMarker(){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId=void 0,this.annotationModule.activeAnnotationMarkerPosition=void 0,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=void 0))}showLayer(t){var s;let r="#",i=new wa("layer-on","layer-off",!0,t,"layer-"+t);switch(t){case"annotations":case"highlights":r+="R2_ID_HIGHLIGHTS_CONTAINER",i.name="R2_ID_HIGHLIGHTS_CONTAINER";break;case"readaloud":r+="R2_ID_READALOUD_CONTAINER",i.name="R2_ID_READALOUD_CONTAINER";break;case"pagebreak":r+="R2_ID_PAGEBREAK_CONTAINER",i.name="R2_ID_PAGEBREAK_CONTAINER";break;case"search":r+="R2_ID_SEARCH_CONTAINER",i.name="R2_ID_SEARCH_CONTAINER";break;case"definitions":r+="R2_ID_DEFINITIONS_CONTAINER",i.name="R2_ID_DEFINITIONS_CONTAINER";break}(s=this.highlighter)==null||s.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let l=Le(o,r);l&&(l.style.display="block")}}hideLayer(t){var s;let r="#",i=new wa("layer-on","layer-off",!1,t,"layer-"+t);switch(t){case"annotations":case"highlights":r+="R2_ID_HIGHLIGHTS_CONTAINER",i.name="R2_ID_HIGHLIGHTS_CONTAINER";break;case"readaloud":r+="R2_ID_READALOUD_CONTAINER",i.name="R2_ID_READALOUD_CONTAINER";break;case"pagebreak":r+="R2_ID_PAGEBREAK_CONTAINER",i.name="R2_ID_PAGEBREAK_CONTAINER";break;case"search":r+="R2_ID_SEARCH_CONTAINER",i.name="R2_ID_SEARCH_CONTAINER";break;case"definitions":r+="R2_ID_DEFINITIONS_CONTAINER",i.name="R2_ID_DEFINITIONS_CONTAINER";break}(s=this.highlighter)==null||s.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let l=Le(o,r);l&&(l.style.display="none")}}};L();var St=class St{constructor(e){this.store=e.store}getLastReadingPosition(){let e=this.store.get(St.LAST_READING_POSITION);return e?JSON.parse(e):null}initLastReadingPosition(e){if(typeof e=="string")this.store.set(St.LAST_READING_POSITION,e);else{let t=JSON.stringify(e);this.store.set(St.LAST_READING_POSITION,t)}}saveLastReadingPosition(e){if(typeof e=="string")this.store.set(St.LAST_READING_POSITION,e);else{let t=JSON.stringify(e);this.store.set(St.LAST_READING_POSITION,t)}}initBookmarks(e){if(typeof e=="string"){let t=JSON.parse(e);this.store.set(St.BOOKMARKS,JSON.stringify(t))}else this.store.set(St.BOOKMARKS,JSON.stringify(e));return e}saveBookmark(e){let t=this.store.get(St.BOOKMARKS);if(t){let r=JSON.parse(t);r.push(e),this.store.set(St.BOOKMARKS,JSON.stringify(r))}else{let r=[];r.push(e),this.store.set(St.BOOKMARKS,JSON.stringify(r))}return e}locatorExists(e,t){let r;switch(t){case 0:r=St.BOOKMARKS;break}let i=this.store.get(r);return i&&JSON.parse(i).filter(l=>l.href===e.href&&l.locations.progression===e.locations.progression).length>0?e:null}deleteBookmark(e){let t=this.store.get(St.BOOKMARKS);if(t){let r=JSON.parse(t);r=r.filter(i=>i.id!==e.id),this.store.set(St.BOOKMARKS,JSON.stringify(r))}return e}getBookmarks(e){let t=this.store.get(St.BOOKMARKS);if(t){let r=JSON.parse(t);if(e){let i=r.filter(o=>o.href===e);return i=i.sort((o,s)=>{if(o.locations.progression&&s.locations.progression)return o.locations.progression-s.locations.progression}),i}return r=r.sort((i,o)=>{if(i.locations.progression&&o.locations.progression)return i.locations.progression-o.locations.progression}),r}return[]}initAnnotations(e){let t;typeof e=="string"?t=JSON.parse(e):t=e;let r=[];return t.forEach(i=>{let o=`${i.highlight.selectionInfo.rangeInfo.startContainerElementCssSelector}${i.highlight.selectionInfo.rangeInfo.startContainerChildTextNodeIndex}${i.highlight.selectionInfo.rangeInfo.startOffset}${i.highlight.selectionInfo.rangeInfo.endContainerElementCssSelector}${i.highlight.selectionInfo.rangeInfo.endContainerChildTextNodeIndex}${i.highlight.selectionInfo.rangeInfo.endOffset}`,s=Ui.hash(o);i.highlight.id="R2_HIGHLIGHT_"+s;let l;i.highlight.color?l=i.highlight.color:i.color&&(l=i.color),Jt.isHexColor(l)&&(l=Jt.hexToRgbString(l)),i.highlight.color=l,i.highlight.pointerInteraction=!0,i.highlight.selectionInfo.cleanText=i.highlight.selectionInfo.rawText.trim().replace(/\n/g," ").replace(/\s\s+/g," "),r.push(i)}),this.store.set(St.ANNOTATIONS,JSON.stringify(r)),r}saveTemporarySelectionInfo(e){this.store.set(St.SELECTIONINFO,JSON.stringify(e))}getTemporarySelectionInfo(e){let t=this.store.get(St.SELECTIONINFO);if(t){let r=JSON.parse(t);return r.range=Rf(e,r.rangeInfo),r}return[]}deleteTemporarySelectionInfo(){this.store.remove(St.SELECTIONINFO)}saveAnnotation(e){let t=this.store.get(St.ANNOTATIONS);if(t){let r=JSON.parse(t);r.push(e),this.store.set(St.ANNOTATIONS,JSON.stringify(r))}else{let r=[];r.push(e),this.store.set(St.ANNOTATIONS,JSON.stringify(r))}return e}deleteAnnotation(e){let t=this.store.get(St.ANNOTATIONS);if(t){let r=JSON.parse(t);r=r.filter(i=>i.id!==e),this.store.set(St.ANNOTATIONS,JSON.stringify(r))}return e}deleteSelectedAnnotation(e){let t=this.store.get(St.ANNOTATIONS);if(t){let r=JSON.parse(t);r=r.filter(i=>{var o;return((o=i.highlight)==null?void 0:o.id)!==e.highlight.id}),this.store.set(St.ANNOTATIONS,JSON.stringify(r))}return e}getAnnotations(){let e=this.store.get(St.ANNOTATIONS);if(e){let t=JSON.parse(e);return t=t.sort((r,i)=>{if(r.locations.progression&&i.locations.progression)return r.locations.progression-i.locations.progression}),t}return[]}getAnnotationsByChapter(e){let t=this.store.get(St.ANNOTATIONS);if(t){let r=JSON.parse(t);return r=r.filter(i=>i.href===e),r=r.sort((i,o)=>{if(i.locations.progression&&o.locations.progression)return i.locations.progression-o.locations.progression}),r}return[]}getAnnotationPosition(e,t){let r=this.store.get(St.ANNOTATIONS);if(r){let o=JSON.parse(r).filter(s=>{var l;return((l=s.highlight)==null?void 0:l.id)===e||s.id===e});if(o.length>0){let s=t.document.getElementById(`${o[0].highlight.id}`);if(s){let l=0;if(s.hasChildNodes)for(let f=0;f<s.childNodes.length;f++){let u=s.childNodes[f],y=parseInt(u.style.top.replace("px",""));(y<l||l===0)&&(l=y)}else l=parseInt(s.style.top.replace("px",""));return l}}}return null}getAnnotationElement(e,t){let r=this.store.get(St.ANNOTATIONS);if(r){let o=JSON.parse(r).filter(s=>{var l;return((l=s.highlight)==null?void 0:l.id)===e});if(o.length>0){let s=t.document.getElementById(`${o[0].highlight.id}`);if(s){let l=0;if(s.hasChildNodes)for(let f=0;f<s.childNodes.length;f++){let u=s.childNodes[f],y=parseInt(u.style.top.replace("px",""));if(y<l||l===0)return l=y,u}else l=parseInt(s.style.top.replace("px",""));return s}}}return null}getAnnotation(e){let t=this.store.get(St.ANNOTATIONS);if(t){let i=JSON.parse(t).filter(o=>{var s;return((s=o.highlight)==null?void 0:s.id)===e.id});if(i.length>0)return i[0]}return null}getAnnotationByID(e){let t=this.store.get(St.ANNOTATIONS);if(t){let i=JSON.parse(t).filter(o=>{var s;return((s=o.highlight)==null?void 0:s.id)===e});if(i.length>0)return i[0]}return null}};St.LAST_READING_POSITION="last-reading-position",St.BOOKMARKS="bookmarks",St.ANNOTATIONS="annotations",St.SELECTIONINFO="selectionInfo";var zl=St;L();L();var uu=class{constructor(){this.store={}}get(e){return this.store[e]||null}set(e,t){this.store[e]=t}remove(e){this.store[e]=null}};var qs=class{constructor(e){this.prefix=e.prefix,this.useLocalStorage=e.useLocalStorage,this.useStorageType=e.useStorageType;try{let t=e.prefix+"-"+String(Math.random());this.useStorageType==="memory"?this.fallbackStore=new uu:this.useStorageType==="local"||this.useLocalStorage?(window.localStorage.setItem(t,"test"),window.localStorage.removeItem(t),this.fallbackStore=null):(this.useStorageType==="session"||!this.useLocalStorage)&&(window.sessionStorage.setItem(t,"test"),window.sessionStorage.removeItem(t),this.fallbackStore=null)}catch{this.fallbackStore=new uu}}getLocalStorageKey(e){return this.prefix+"-"+e}get(e){let t;return this.fallbackStore?t=this.fallbackStore.get(e):this.useStorageType==="local"||this.useLocalStorage?t=window.localStorage.getItem(this.getLocalStorageKey(e)):t=window.sessionStorage.getItem(this.getLocalStorageKey(e)),t}set(e,t){this.fallbackStore?this.fallbackStore.set(e,t):this.useStorageType==="local"||this.useLocalStorage?window.localStorage.setItem(this.getLocalStorageKey(e),t):window.sessionStorage.setItem(this.getLocalStorageKey(e),t)}remove(e){this.fallbackStore?this.fallbackStore.remove(e):this.useStorageType==="local"||this.useLocalStorage?window.localStorage.removeItem(this.getLocalStorageKey(e)):window.sessionStorage.removeItem(this.getLocalStorageKey(e))}};L();var kE=rt(Nu()),RE=rt(Or());var lu=class extends kE.Link{};lu=Nc([(0,RE.JsonObject)()],lu);function Gs(n){let e,t,r,i;if(n instanceof Array)return n.map(function(o){return typeof o=="object"&&(o=Gs(o)),o});e={};for(t in n)n.hasOwnProperty(t)&&(r=(t.charAt(0).toLowerCase()+t.slice(1)||t).toString(),i=n[t],(i instanceof Array||i!=null&&i.constructor===Object)&&(i=Gs(i)),r==="href1"?e.href=i:r==="typeLink"?e.type=i:e[r]=i);return e}L();var LE=rt($t()),wh=class{constructor(e){this.LAYERSETTINGS="layerSetting";this.store=e,this.initialize()}static async create(e){let t=new this(e.store);return new Promise(r=>r(t))}async stop(){LE.default.log("MediaOverlay settings stop")}async initialize(){this.userProperties=await this.getLayerSettings()}async getLayerSettings(){let e=new Li,t=await this.store.get(this.LAYERSETTINGS);if(t){let r=JSON.parse(t);e.properties=r}return e}async saveProperty(e){let t=await this.store.get(this.LAYERSETTINGS);if(t){let r=JSON.parse(t);r=r.filter(i=>i.name!==e.name),r.push(e),await this.store.set(this.LAYERSETTINGS,JSON.stringify(r))}else{let r=[];r.push(e),await this.store.set(this.LAYERSETTINGS,JSON.stringify(r))}return new Promise(r=>r(e))}async getProperty(e){let t=await this.store.get(this.LAYERSETTINGS);if(t){let r=JSON.parse(t);return r=r.filter(i=>i.name===e),r.length===0?null:r[0]}return null}};L();var cu=rt(FE());L();var HE="grab-to-pan-grab",Ah,UE,Eh,jE,Ch,qE,Sh=class{constructor(e){Tr(this,Ah);Tr(this,Eh);Tr(this,Ch);this.element=e.element,this.document=e.element.ownerDocument,typeof e.ignoreTarget=="function"&&(this.ignoreTarget=e.ignoreTarget),this.onActiveChanged=e.onActiveChanged,this.activate=this.activate.bind(this),this.deactivate=this.deactivate.bind(this),this.toggle=this.toggle.bind(this),this._onMouseDown=ro(this,Ah,UE).bind(this),this._onMouseMove=ro(this,Eh,jE).bind(this),this._endPan=ro(this,Ch,qE).bind(this);let t=this.overlay=document.createElement("div");t.className="grab-to-pan-grabbing"}activate(){var e;this.active||(this.active=!0,this.element.addEventListener("mousedown",this._onMouseDown,!0),this.element.classList.add(HE),(e=this.onActiveChanged)==null||e.call(this,!0))}deactivate(){var e;this.active&&(this.active=!1,this.element.removeEventListener("mousedown",this._onMouseDown,!0),this._endPan(),this.element.classList.remove(HE),(e=this.onActiveChanged)==null||e.call(this,!1))}toggle(){this.active?this.deactivate():this.activate()}ignoreTarget(e){return e.matches("a[href], a[href] *, input, textarea, button, button *, select, option")}};Ah=new WeakSet,UE=function(e){if(e.button!==0||this.ignoreTarget(e.target))return;if(e.originalTarget)try{e.originalTarget.tagName}catch{return}this.scrollLeftStart=this.element.scrollLeft,this.scrollTopStart=this.element.scrollTop,this.clientXStart=e.clientX,this.clientYStart=e.clientY,this.document.addEventListener("mousemove",this._onMouseMove,!0),this.document.addEventListener("mouseup",this._endPan,!0),this.element.addEventListener("scroll",this._endPan,!0),e.preventDefault(),e.stopPropagation();let t=document.activeElement;t&&!t.contains(e.target)&&t.blur()},Eh=new WeakSet,jE=function(e){if(this.element.removeEventListener("scroll",this._endPan,!0),!(e.buttons&1)){this._endPan();return}let t=e.clientX-this.clientXStart,r=e.clientY-this.clientYStart,i=this.scrollTopStart-r,o=this.scrollLeftStart-t;this.element.scrollTo?this.element.scrollTo({top:i,left:o,behavior:"instant"}):(this.element.scrollTop=i,this.element.scrollLeft=o),this.overlay.parentNode||document.body.append(this.overlay)},Ch=new WeakSet,qE=function(){this.element.removeEventListener("scroll",this._endPan,!0),this.document.removeEventListener("mousemove",this._onMouseMove,!0),this.document.removeEventListener("mouseup",this._endPan,!0),this.overlay.remove()};var vi=class extends bh{constructor(t,r,i){super();this.pdfDoc=null;this.pageNum=1;this.scaleType=0;this.pageRendering=!1;this.pageNumPending=null;this.scale=1;this.resourceIndex=0;this.onResize=()=>{clearTimeout(this.timeout),this.timeout=setTimeout(this.handleResize.bind(this),200)};this.settings=t,this.publication=r,this.api=i}static async create(t){let r=new this(t.settings,t.publication,t.api);return await r.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(i=>i(r))}async start(t,r,i){this.headerMenu=r,this.footerMenu=i,this.mainElement=t,this.resourceIndex=0,this.resource=this.publication.readingOrder[this.resourceIndex],cu.GlobalWorkerOptions.workerSrc="//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.14.305/pdf.worker.js",this.wrapper=yt(this.mainElement,"main#iframe-wrapper"),this.pdfContainer=yt(this.mainElement,"#pdf-container"),this.handTool=new Sh({element:this.pdfContainer});let o=this,s=document.createElement("div");s.id="loadingpdf",s.innerHTML=mh,s.style.width=getComputedStyle(this.wrapper).width,s.style.height=getComputedStyle(this.wrapper).height,s.style.display="flex",s.style.zIndex="100",s.style.position="absolute",s.style.alignItems="center",s.style.justifyContent="center",s.style.background="white",s.className="loading is-loading",this.pdfContainer.appendChild(s),(0,cu.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(l){o.pdfDoc=l,o.loadPDFJS(o.pageNum)}),this.setupEvents()}async handleResize(){this.loadPDFJS(this.pageNum)}setupEvents(){we(window,"resize",this.onResize)}loadPDFJS(t){let r=this,i=1;this.wrapper.style.height="calc(100vh - 10px)",this.pdfContainer.style.height="calc(100vh - 10px)",this.pdfContainer.style.flexDirection="column";let o=document.getElementsByTagName("canvas");Array.from(o).forEach(function(l){var f;(f=l==null?void 0:l.parentNode)==null||f.removeChild(l)});function s(l){let f=document.createElement("canvas");f.id=String(i),f.style.border="1px solid gray",f.style.margin="1px";let u=l.getViewport({scale:r.scale});if(r.scale===1){let g=r.wrapper.clientHeight/u.height,h=r.wrapper.clientWidth/u.width;r.scaleType===0?u=l.getViewport({scale:g<h?g:h}):u=l.getViewport({scale:h})}r.pdfContainer.appendChild(f);let y=f.getContext("2d");f.height=u.height,f.width=u.width;let m={canvasContext:y,viewport:u},_=document.getElementById("loadingpdf");_.style.display="flex",_.style.width=getComputedStyle(r.wrapper).width,_.style.height=getComputedStyle(r.wrapper).height,l.render(m).promise.then(function(){var g,h,c;i<r.pdfDoc.numPages?(i++,r.pdfDoc.getPage(i).then(s)):((g=document.getElementById(String(t)))==null||g.scrollIntoView(),_.style.display="none",(h=r.api)!=null&&h.resourceReady&&((c=r.api)==null||c.resourceReady()),r.emit("resource.ready"))})}this.pdfDoc.getPage(i).then(s)}queueRenderPage(t){var i;let r=this;r.pageRendering?r.pageNumPending=t:(this.pageNum=t,(i=document.getElementById(String(t)))==null||i.scrollIntoView())}readingOrder(){return this.publication.readingOrder}tableOfContents(){return this.publication.tableOfContents}landmarks(){}pageList(){}currentResource(){}totalResources(){return this.publication.readingOrder.length}currentLocator(){}positions(){return this.publication.positions?this.publication.positions:[]}nextPage(){let t=this;if(t.pageNum>=t.pdfDoc.numPages){this.nextResource();return}this.pageNum++,this.queueRenderPage(t.pageNum)}previousPage(){let t=this;if(t.pageNum<=1){this.previousResource();return}t.pageNum--,t.queueRenderPage(t.pageNum)}nextResource(){let t=this;this.resourceIndex>=this.publication.readingOrder.length-1||(t.resourceIndex++,t.resource=this.publication.readingOrder[t.resourceIndex],(0,cu.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(r){t.pdfDoc=r,t.pageNum=1,t.loadPDFJS(t.pageNum)}))}previousResource(){let t=this;this.resourceIndex!==0&&(t.resourceIndex--,t.resource=this.publication.readingOrder[t.resourceIndex],(0,cu.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(r){t.pdfDoc=r,t.pageNum=t.pdfDoc.numPages,t.loadPDFJS(t.pageNum)}))}goTo(t){let r=new URL(t.href);if(r.searchParams.has("start")){let i=r.searchParams.get("start");i&&this.queueRenderPage(parseInt(i))}else this.queueRenderPage(1)}goToPosition(t){this.queueRenderPage(t)}async goToPage(t){this.queueRenderPage(t)}fitToWidth(){this.scale=1,this.scaleType=1,this.loadPDFJS(this.pageNum)}fitToPage(){this.scale=1,this.scaleType=0,this.loadPDFJS(this.pageNum)}zoomIn(){this.scale=this.scale+.2,this.loadPDFJS(this.pageNum)}zoomOut(){this.scale=this.scale-.2,this.loadPDFJS(this.pageNum)}activateHand(){this.handTool.activate()}deactivateHand(){this.handTool.deactivate()}async scroll(t,r){t?(r==="horizontal"?this.pdfContainer.style.flexDirection="row":this.pdfContainer.style.flexDirection="column",this.pdfContainer.style.overflow="auto"):(this.pdfContainer.style.flexDirection="column",this.pdfContainer.style.overflow="hidden")}stop(){Ue(window,"resize",this.onResize)}};var du=class n{constructor(e,t,r,i,o,s,l,f,u,y,m,_,v,g,h,c,p,w){this.settings=e;this.navigator=t;this.highlighter=r;this.bookmarkModule=i;this.annotationModule=o;this.ttsSettings=s;this.ttsModule=l;this.searchModule=f;this.definitionsModule=u;this.contentProtectionModule=y;this.timelineModule=m;this.mediaOverlaySettings=_;this.mediaOverlayModule=v;this.pageBreakModule=g;this.lineFocusModule=h;this.historyModule=c;this.citationModule=p;this.consumptionModule=w;this.startReadAloud=()=>{this.navigator instanceof Tt&&this.navigator.startReadAloud()};this.stopReadAloud=()=>{this.navigator instanceof Tt&&this.navigator.stopReadAloud()};this.pauseReadAloud=()=>{this.navigator instanceof Tt&&this.navigator.pauseReadAloud()};this.resumeReadAloud=()=>{this.navigator instanceof Tt&&this.navigator.resumeReadAloud()};this.startReadAlong=()=>{this.navigator instanceof Tt&&this.navigator.startReadAlong()};this.stopReadAlong=()=>{this.navigator instanceof Tt&&this.navigator.stopReadAlong()};this.pauseReadAlong=()=>{this.navigator instanceof Tt&&this.navigator.pauseReadAlong()};this.resumeReadAlong=()=>{this.navigator instanceof Tt&&this.navigator.resumeReadAlong()};this.saveBookmark=async()=>{var e;return await((e=this.bookmarkModule)==null?void 0:e.saveBookmark())??!1};this.saveBookmarkPlus=async()=>{var e;return(e=this.bookmarkModule)==null?void 0:e.saveBookmarkPlus()};this.deleteBookmark=async e=>{var t;return await((t=this.bookmarkModule)==null?void 0:t.deleteBookmark(e))??!1};this.deleteAnnotation=async e=>{var t;return await((t=this.annotationModule)==null?void 0:t.deleteAnnotation(e))??!1};this.addAnnotation=async e=>{var t;return await((t=this.annotationModule)==null?void 0:t.addAnnotation(e))??!1};this.hideAnnotationLayer=()=>{var e;return(e=this.annotationModule)==null?void 0:e.hideAnnotationLayer()};this.showAnnotationLayer=()=>{var e;return(e=this.annotationModule)==null?void 0:e.showAnnotationLayer()};this.hideLayer=e=>{var t;return this.navigator instanceof Tt?(t=this.navigator)==null?void 0:t.hideLayer(e):!1};this.showLayer=e=>{var t;return this.navigator instanceof Tt?(t=this.navigator)==null?void 0:t.showLayer(e):!1};this.activateMarker=(e,t)=>{var r;return this.navigator instanceof Tt?(r=this.navigator)==null?void 0:r.activateMarker(e,t):!1};this.deactivateMarker=()=>{var e;return this.navigator instanceof Tt?(e=this.navigator)==null?void 0:e.deactivateMarker():!1};this.clearDefinitions=async()=>{var e;await((e=this.definitionsModule)==null?void 0:e.clearDefinitions())};this.addDefinition=async e=>{var t;await((t=this.definitionsModule)==null?void 0:t.addDefinition(e))};this.historyBack=async()=>{var e;return(e=this.historyModule)==null?void 0:e.historyBack()};this.historyForward=async()=>{var e;return(e=this.historyModule)==null?void 0:e.historyForward()};this.search=async(e,t)=>{var r;return await((r=this.searchModule)==null?void 0:r.search(e,t))??[]};this.goToSearchIndex=async(e,t,r)=>{var i;this.navigator instanceof Tt&&this.navigator.rights.enableSearch&&await((i=this.searchModule)==null?void 0:i.goToSearchIndex(e,t,r))};this.goToSearchID=async(e,t,r)=>{var i;this.navigator instanceof Tt&&this.navigator.rights.enableSearch&&await((i=this.searchModule)==null?void 0:i.goToSearchID(e,t,r))};this.clearSearch=async()=>{var e;this.navigator instanceof Tt&&this.navigator.rights.enableSearch&&await((e=this.searchModule)==null?void 0:e.clearSearch())};this.resetUserSettings=async()=>await this.settings.resetUserSettings();this.applyUserSettings=async e=>await this.settings.applyUserSettings(e);this.scroll=async(e,t)=>this.navigator instanceof vi?this.navigator.scroll(e,t):await this.settings.scroll(e);this.increase=async e=>{var t,r;this.isTTSIncrementable(e)?this.navigator instanceof Tt&&this.navigator.rights.enableTTS&&await((t=this.ttsSettings)==null?void 0:t.increase(e)):this.isMOIncrementable(e)?this.navigator instanceof Tt&&this.navigator.rights.enableMediaOverlays&&await((r=this.mediaOverlaySettings)==null?void 0:r.increase(e)):await this.settings.increase(e)};this.decrease=async e=>{var t,r;this.isTTSIncrementable(e)?this.navigator instanceof Tt&&this.navigator.rights.enableTTS&&await((t=this.ttsSettings)==null?void 0:t.decrease(e)):this.isMOIncrementable(e)?this.navigator instanceof Tt&&this.navigator.rights.enableMediaOverlays&&await((r=this.mediaOverlaySettings)==null?void 0:r.decrease(e)):await this.settings.decrease(e)};this.resetTTSSettings=()=>{var e;this.navigator instanceof Tt&&this.navigator.rights.enableTTS&&((e=this.ttsSettings)==null||e.resetTTSSettings())};this.applyTTSSettings=async e=>{var t;this.navigator instanceof Tt&&this.navigator.rights.enableTTS&&await((t=this.ttsSettings)==null?void 0:t.applyTTSSettings(e))};this.applyPreferredVoice=async e=>{var t;this.navigator instanceof Tt&&this.navigator.rights.enableTTS&&await((t=this.ttsSettings)==null?void 0:t.applyPreferredVoice(e))};this.resetMediaOverlaySettings=async()=>{var e;this.navigator instanceof Tt&&this.navigator.rights.enableMediaOverlays&&await((e=this.mediaOverlaySettings)==null?void 0:e.resetMediaOverlaySettings())};this.applyMediaOverlaySettings=async e=>{var t;this.navigator instanceof Tt&&this.navigator.rights.enableMediaOverlays&&await((t=this.mediaOverlaySettings)==null?void 0:t.applyMediaOverlaySettings(e))};this.goTo=async e=>{this.navigator.goTo(e)};this.goToPosition=async e=>this.navigator.goToPosition(e);this.goToPage=async e=>{await this.navigator.goToPage(e)};this.fitToPage=()=>{this.navigator instanceof vi&&this.navigator.fitToPage()};this.fitToWidth=()=>{this.navigator instanceof vi&&this.navigator.fitToWidth()};this.zoomIn=()=>{this.navigator instanceof vi&&this.navigator.zoomIn()};this.zoomOut=()=>{this.navigator instanceof vi&&this.navigator.zoomOut()};this.activateHand=()=>{this.navigator instanceof vi&&this.navigator.activateHand()};this.deactivateHand=()=>{this.navigator instanceof vi&&this.navigator.deactivateHand()};this.copyToClipboard=e=>{var t;(t=this.contentProtectionModule)==null||t.copyToClipboard(e)};this.nextResource=()=>{this.navigator.nextResource()};this.previousResource=()=>{this.navigator.previousResource()};this.nextPage=async()=>{this.navigator.nextPage()};this.previousPage=async()=>{this.navigator.previousPage()};this.snapToSelector=async e=>{this.navigator instanceof Tt&&this.navigator.snapToSelector(e)};this.applyAttributes=e=>{this.navigator instanceof Tt&&this.navigator.applyAttributes(e)};this.stop=()=>{var e,t,r,i,o,s,l,f,u,y,m,_,v,g;document.body.onscroll=()=>{},this.navigator.stop(),this.settings.stop(),(e=this.ttsSettings)==null||e.stop(),(t=this.ttsModule)==null||t.stop(),(r=this.bookmarkModule)==null||r.stop(),(i=this.annotationModule)==null||i.stop(),(o=this.searchModule)==null||o.stop(),(s=this.definitionsModule)==null||s.stop(),(l=this.contentProtectionModule)==null||l.stop(),(f=this.timelineModule)==null||f.stop(),(u=this.mediaOverlaySettings)==null||u.stop(),(y=this.mediaOverlayModule)==null||y.stop(),(m=this.pageBreakModule)==null||m.stop(),(_=this.lineFocusModule)==null||_.stop(),(v=this.citationModule)==null||v.stop(),(g=this.consumptionModule)==null||g.stop()}}addEventListener(){this.navigator instanceof Tt&&this.navigator.addListener(arguments[0],arguments[1])}static async load(e){var _,v,g,h,c,p,w;let t=e.rights??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};t.enableContentProtection&&e.protection&&await Bs.setupPreloadProtection(e.protection);let r=yt(document,"#D2Reader-Container"),i=Le(document,"#headerMenu"),o=Le(document,"#footerMenu"),s=e.url,l;e.publication?(l=_a(e.publication,lo),l.manifestUrl=new URL(s)):l=await lo.fromUrl(s,e.requestConfig);let f=new qs({prefix:l.manifestUrl,useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),u=new qs({prefix:"r2d2bc-reader",useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),y=new qs({prefix:"r2d2bc-layers",useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),m=new zl({store:f});if(l.sample=e.sample,t=zU(t,l),l.Metadata.ConformsTo&&l.Metadata.ConformsTo.includes("https://readium.org/webpub-manifest/profiles/pdf")){let A=await Al.create({store:u,initialUserSettings:e.userSettings,layout:""}),E=await vi.create({mainElement:r,publication:l,settings:A,api:e.api});return new n(A,E)}else{t.autoGeneratePositions?await l.autoGeneratePositions(e.requestConfig):((_=e.services)!=null&&_.positions&&await l.fetchPositionsFromService((v=e.services)==null?void 0:v.positions.href,e.requestConfig),(g=e.services)!=null&&g.weight&&await l.fetchWeightsFromService((h=e.services)==null?void 0:h.weight.href,e.requestConfig));let A=await wh.create({store:y}),E=await Al.create({store:u,initialUserSettings:e.userSettings,headerMenu:i,api:e.api,injectables:(((c=l.Metadata.Rendition)==null?void 0:c.Layout)??"unknown")==="fixed"?e.injectablesFixed:e.injectables,layout:(((p=l.Metadata.Rendition)==null?void 0:p.Layout)??"unknown")==="fixed"?"fixed":"reflowable"}),b=await Jt.create({layerSettings:A,...e.highlighter}),C=t.enableBookmarks?await Ga.create({annotator:m,headerMenu:i,rights:t,publication:l,initialAnnotations:e.initialAnnotations,...e.bookmarks}):void 0,k=t.enableAnnotations?await qa.create({annotator:m,rights:t,publication:l,initialAnnotations:e.initialAnnotations,highlighter:b,headerMenu:i,...e.annotations}):void 0,R=t.enableTTS,B=R?await gh.create({store:u,initialTTSSettings:e.tts,headerMenu:i}):void 0,I;R&&B&&(I=await Hs.create({tts:B,headerMenu:i,rights:t,highlighter:b,...e.tts}));let D=t.enableSearch?await iu.create({headerMenu:i,publication:l,highlighter:b,...e.search}):void 0,F=t.enableDefinitions?await su.create({publication:l,highlighter:b,...e.define}):void 0,z=t.enableTimeline?await za.create({publication:l}):void 0,q=t.enableContentProtection?await Bs.create({...e.protection}):void 0,G=t.enableCitations?await js.create({publication:l,highlighter:b,...e.citations}):void 0,Y=t.enableMediaOverlays,X=Y?await Nf.create({store:u,initialMediaOverlaySettings:e.mediaOverlays,headerMenu:i,...e.mediaOverlays}):void 0,Q=Y?await Wa.create({publication:l,settings:X,...e.mediaOverlays}):void 0,ve=t.enablePageBreaks&&l.isReflowable?await ou.create({publication:l,headerMenu:i,...e.pagebreak}):void 0,ce=t.enableLineFocus?await Us.create({publication:l,highlighter:b,...e.lineFocus}):void 0,W=t.enableHistory?await au.create({annotator:m,publication:l,headerMenu:i}):void 0,H=t.enableConsumption?await ja.create({publication:l,...e.consumption}):void 0,M=await Tt.create({mainElement:r,headerMenu:i,footerMenu:o,publication:l,settings:E,annotator:m,initialLastReadingPosition:e.lastReadingPosition,api:e.api,rights:t,tts:e.tts,sample:e.sample,requestConfig:e.requestConfig,injectables:(((w=l.Metadata.Rendition)==null?void 0:w.Layout)??"unknown")==="fixed"?e.injectablesFixed??[]:e.injectables,attributes:e.attributes,services:e.services,highlighter:b,modules:[C,k,I,D,F,z,q,G,Q,ve,ce,W,H]});return new n(E,M,b,C,k,B,I,D,F,q,z,X,Q,ve,ce,W,G,H)}}get hasMediaOverlays(){return this.navigator instanceof Tt?this.navigator.hasMediaOverlays:!1}get tableOfContents(){return Gs(this.navigator.tableOfContents())??[]}get landmarks(){return Gs(this.navigator.landmarks())??[]}get pageList(){return Gs(this.navigator.pageList())??[]}get readingOrder(){return Gs(this.navigator.readingOrder())??[]}get bookmarks(){var e;return((e=this.bookmarkModule)==null?void 0:e.getBookmarks())??[]}get annotations(){var e;return(e=this.annotationModule)==null?void 0:e.getAnnotations()}get publicationLayout(){return this.navigator.publication.layout}get history(){var e;return(e=this.historyModule)==null?void 0:e.history}get historyCurrentIndex(){var e;return(e=this.historyModule)==null?void 0:e.historyCurrentIndex}get currentResource(){return this.navigator.currentResource()}get mostRecentNavigatedTocItem(){return this.navigator instanceof Tt?this.navigator.mostRecentNavigatedTocItem():!1}get totalResources(){return this.navigator.totalResources()}get publicationLanguage(){return this.navigator.publication.Metadata.Language}get currentSettings(){return this.settings.currentSettings}isTTSIncrementable(e){return e==="pitch"||e==="rate"||e==="volume"}isMOIncrementable(e){return e==="mo_rate"||e==="mo_volume"}get currentLocator(){return this.navigator.currentLocator()}get positions(){return this.navigator.positions()}get atStart(){return this.navigator instanceof Tt?this.navigator.atStart():!1}get atEnd(){return this.navigator instanceof Tt?this.navigator.atEnd():!1}async applyLineFocusSettings(e){if(e.lines&&this.lineFocusModule){let t=this.lineFocusModule.properties.lines??1;this.lineFocusModule.index=this.lineFocusModule.index*t/parseInt(e.lines),this.lineFocusModule.index=Math.abs(parseInt(this.lineFocusModule.index.toFixed())),this.lineFocusModule.properties.lines=parseInt(e.lines),this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus()}e.debug!==void 0&&this.lineFocusModule&&(this.lineFocusModule.isDebug=e.debug,this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus())}lineUp(){var e;(e=this.lineFocusModule)==null||e.lineUp()}lineDown(){var e;(e=this.lineFocusModule)==null||e.lineDown()}async enableLineFocus(){var e;await((e=this.lineFocusModule)==null?void 0:e.enableLineFocus())}async lineFocus(e){var t,r;e?await((t=this.lineFocusModule)==null?void 0:t.enableLineFocus()):(r=this.lineFocusModule)==null||r.disableLineFocus()}disableLineFocus(){var e;(e=this.lineFocusModule)==null||e.disableLineFocus()}};function zU(n,e){var t;return e.isFixedLayout&&(n.enableAnnotations=!1,n.enableSearch=!1,n.enableTTS=!1,n.enableDefinitions=!1,n.enablePageBreaks=!1,n.enableLineFocus=!1),(t=e.sample)!=null&&t.isSampleRead&&(n.enableAnnotations=!1,n.enableSearch=!1,n.enableTTS=!1,n.enableDefinitions=!1,n.enableTimeline=!1,n.enableMediaOverlays=!1,n.enablePageBreaks=!1,n.enableLineFocus=!1),n}var VU=du,$U=du.load;return Cn(JU);})();
89
+ `;var _h=rt(Vo());L();var Eo=class Eo{constructor(e){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.setupEvents=e=>{let t=null,r=null,i=this;e&&(e.addEventListener("touchstart",function(o){o.changedTouches.length===1&&(t=o)},!1),e.addEventListener("touchend",function(o){if(o.changedTouches.length!==1||!t)return;let s=t.changedTouches[0],l=o.changedTouches[0];if(!s)return;let f=window.devicePixelRatio,u=(s.clientX-l.clientX)/f,y=(s.clientY-l.clientY)/f;if(Math.abs(u)<Eo.TAP_TOLERANCE&&Math.abs(y)<Eo.TAP_TOLERANCE){if(r){t=null,r=null;return}if(o.timeStamp-t.timeStamp>Eo.LONG_PRESS_MS){t=null,r=null;return}t=null,r=o;return}if(r=null,o.timeStamp-t.timeStamp>Eo.SLOW_SWIPE_MS){t=null;return}let m=(s.clientY-l.clientY)/(s.clientX-l.clientX);if(Math.abs(m)>.5){t=null;return}u<0?i.onBackwardSwipe(o):i.onForwardSwipe(o),t=null},!1))};this.navigator=e}};Eo.TAP_TOLERANCE=10,Eo.LONG_PRESS_MS=500,Eo.SLOW_SWIPE_MS=500;var Hl=Eo;L();var Ul=class{constructor(e){this.onBackwardSwipe=()=>{};this.onForwardSwipe=()=>{};this.onKeydown=()=>{};this.setupEvents=e=>{e&&(this.focusin(e),this.keydown(e))};this.removeEvents=e=>{if(e){let t=this;e.removeEventListener("focusin",this.onFocusIn(t),!0),e.removeEventListener("keydown",this.onKeyDown(t),!1)}};this.focusin=e=>{let t=this;e.addEventListener("focusin",this.onFocusIn(t),!0)};this.keydown=e=>{let t=this;this.navigator.rights.customKeyboardEvents||e.addEventListener("keydown",this.onKeyDown(t),!1)};this.handlers={};this.navigator=e,this.rtl=!1}onFocusIn(e){return this.handlers.onFocusIn||(this.handlers.onFocusIn=function(t){var r;(r=e.navigator.view)==null||r.snap(t.target)})}onKeyDown(e){return this.handlers.onKeyDown||(this.handlers.onKeyDown=function(t){let r=t.target;if(/input|select|option|textarea/i.test(r.tagName)||!(r.ownerDocument||r).defaultView.getSelection().isCollapsed)return;switch(t.key){case"ArrowRight":e.rtl?e.onBackwardSwipe(t):e.onForwardSwipe(t);return;case"ArrowLeft":e.rtl?e.onForwardSwipe(t):e.onBackwardSwipe(t);return}switch(t.code){case"Space":if(t.ctrlKey){e.onBackwardSwipe(t);return}else{e.onForwardSwipe(t);return}}e.onKeydown(t)})}};L();var vE=rt(Vo()),jl=class{constructor(e){this.enforceSampleRead=(0,vE.default)(e=>{var g,h,c,p,w,A;let t=Math.round(e.locations.totalProgression*100),r=!1;(g=this.navigator.sample)!=null&&g.limit&&(r=t<=((h=this.navigator.sample)==null?void 0:h.limit),((c=this.navigator.view)==null?void 0:c.layout)==="fixed"&&!r&&(p=this.navigator.sample)!=null&&p.minimum&&e.locations.position<=((w=this.navigator.sample)==null?void 0:w.minimum)&&(r=!0));let i={37:1,38:0,39:1,40:1,32:1,33:1,34:1,35:1,36:1};function o(E){E.preventDefault()}function s(E){i[E.keyCode]&&!r&&o(E)}let l=!1,f=Object.defineProperty&&Object.defineProperty({},"passive",{get:function(){l=!0}});window.addEventListener("test",function(){},f);let u=l?{passive:!1}:!1;function y(E){E=E||window.event;let b=Math.max(-1,Math.min(1,E.wheelDelta||-E.detail));return b===-1&&!r&&E.preventDefault(),!1}let m;function _(E){E=E||window.event;let b=E.target||E.srcElement,C=E.touches[0].clientY;if(!(C>m)){if(C<m&&!r)return b.className.match(/\baltNav\b/)||(E.returnValue=!1,E.cancelable&&(E.cancelBubble=!0),E.preventDefault&&E.cancelable&&(E.preventDefault(),E.stopPropagation())),!1}return m=C,!1}function v(E){return E=E||window.event,m=E.touches[0].clientY,!1}window.addEventListener("mousewheel",y,u),window.addEventListener("DOMMouseScroll",y,u),window.addEventListener("keydown",s,u),window.addEventListener("touchmove",_,u),window.addEventListener("touchstart",v,u),r?(this.navigator.iframes[0].focus(),this.navigator.errorMessage&&(this.navigator.errorMessage.style.display="none",this.navigator.errorMessage.style.removeProperty("background-color"))):(this.navigator.iframes[0].blur(),this.navigator.errorMessage&&(this.navigator.errorMessage.style.display="block",this.navigator.errorMessage.style.backgroundColor="rgb(255, 255, 255)",this.navigator.errorMessage.innerHTML=`<span>${(A=this.navigator.sample)==null?void 0:A.popup}</span>`??""))},300);this.navigator=e}};L();var ql=rt($t()),ou=class{static async create(e){let t=new this(e.publication,e,e.headerMenu);return await t.start(),t}constructor(e,t,r){this.headerMenu=r,this.publication=e,this.properties=t}async stop(){ql.default.log("Page Break module stop")}async start(){var e,t;this.headerMenu&&(this.goToPageView=Le(this.headerMenu,"#sidenav-section-gotopage")),this.headerMenu&&(this.goToPageNumberInput=Le(this.headerMenu,"#goToPageNumberInput")),this.headerMenu&&(this.goToPageNumberButton=Le(this.headerMenu,"#goToPageNumberButton")),we(this.goToPageNumberInput,"keypress",this.goToPageNumber.bind(this)),we(this.goToPageNumberButton,"click",this.goToPageNumber.bind(this)),this.goToPageView&&((e=this.publication.pageList)!=null&&e.length||(t=this.goToPageView.parentElement)==null||t.removeChild(this.goToPageView)),setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("pagebreak"):this.navigator.showLayer("pagebreak")},10)}async goToPageNumber(e){var i;if(this.goToPageNumberInput.value&&(e.key==="Enter"||e.type==="click")){var t=(i=this.publication.pageList)==null?void 0:i.filter(o=>o.Href.slice(o.Href.indexOf("#")+1).replace(/[^0-9]/g,"")===this.goToPageNumberInput.value);if(t&&t.length>0){var r=t[0];let o={progression:0};if(r.Href.indexOf("#")!==-1){let l=r.Href.slice(r.Href.indexOf("#")+1);l!==null&&(o={fragment:l})}let s={href:this.publication.getAbsoluteHref(r.Href),locations:o,type:r.TypeLink,title:r.Title};this.navigator.goTo(s)}}}async handleResize(){var e;await((e=this.navigator.highlighter)==null?void 0:e.destroyHighlights(3)),await this.drawPageBreaks()}async drawPageBreaks(){setTimeout(()=>{var o,s,l;let e=(o=this.navigator.iframes[0].contentDocument)==null?void 0:o.body,t=e==null?void 0:e.querySelectorAll('[*|type="pagebreak"]');(t==null?void 0:t.length)===0&&(t=e==null?void 0:e.querySelectorAll("[epub\\:type='pagebreak']")),(t==null?void 0:t.length)===0&&(t=e==null?void 0:e.querySelectorAll("[role='doc-pagebreak']"));let r=this;function i(f){try{let u=r.navigator.iframes[0].contentDocument;return u?Cr(f,u,Jo):""}catch(u){return ql.default.log("uniqueCssSelector:"),ql.default.error(u),""}}if(t)for(let f=0;f<t.length;f++){let u=t[f];ql.default.log(u);let y=u.innerHTML,m=!1;u.innerHTML.length===0&&(y=u.getAttribute("title")??"",u.innerHTML=y,m=!0),u.innerHTML.length===0&&(y=(u.getAttribute("id")??"").replace(/[^0-9]/g,""),u.innerHTML=y,m=!0);let _=this.navigator.iframes[0].contentDocument;if(_){let v=(s=this.navigator.highlighter)==null?void 0:s.dom(_.body).getWindow().document.createRange(),g=(l=this.navigator.highlighter)==null?void 0:l.dom(_.body).getSelection();if(g.removeAllRanges(),v.selectNodeContents(u),g.addRange(v),!g.isCollapsed){let h=mo(v,i);g.removeAllRanges(),h&&this.createPageBreakHighlight({rangeInfo:h,cleanText:"",rawText:""},y)}}m&&(u.innerHTML="")}},200)}createPageBreakHighlight(e,t){var i;try{let o=`${e.rangeInfo.startContainerElementCssSelector}${e.rangeInfo.startContainerChildTextNodeIndex}${e.rangeInfo.startOffset}${e.rangeInfo.endContainerElementCssSelector}${e.rangeInfo.endContainerChildTextNodeIndex}${e.rangeInfo.endOffset}`,l="R2_PAGEBREAK_"+Ui.hash(o);var r=!1;let f={color:"#000000",id:l,pointerInteraction:r,selectionInfo:e,marker:3,icon:{id:"pageBreak",title:t,color:"#000000",position:"left"},type:3};er.push(f);let u=(i=this.navigator.highlighter)==null?void 0:i.createHighlightDom(this.navigator.iframes[0].contentWindow,f);return f.position=parseInt((u!=null&&u.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px","")),f}catch(o){throw"Can't create highlight: "+o}}};L();var wE=rt(Fg());var SE=rt(Vo());var Pt=rt($t()),Hs=class{constructor(e,t,r,i,o,s){this.voices=[];this.hasEventListener=!1;this.startX=0;this.startY=0;this.index=0;this.userScrolled=!1;this.scrollPartial=!1;this.speaking=!1;this.restartIndex=-1;this.ttsQueueIndex=-1;this.ttsQueue=void 0;this.ttsPlayQueueIndexDebounced=(0,SE.default)((e,t)=>{this.restartIndex>=0?(this.ttsQueueIndex=this.restartIndex,this.restartIndex=-1):this.ttsQueueIndex=e,this.ttsQueue=t,this.ttsPlayQueueIndex(this.ttsQueueIndex,t)},150);this.tts=e,this.headerMenu=s,this.rights=t,this.highlighter=r,this.properties=i,this.api=o}initialize(e){this.highlighter!==void 0&&(this.tts.setControls(),this.tts.onRestart(this.restart.bind(this)),this.body=e,this.clean=(0,wE.default)(this.body.innerHTML,{allowedTags:[],allowedAttributes:{}}),this.wrapper=yt(document,"#iframe-wrapper"),window.speechSynthesis.getVoices(),this.initVoices(!0),this.hasEventListener||(this.hasEventListener=!0,we(document,"wheel",this.wheel.bind(this)),we(this.body,"wheel",this.wheel.bind(this)),we(document,"keydown",this.wheel.bind(this)),we(this.navigator.iframes[0].contentDocument,"keydown",this.wheel.bind(this))),we(this.body,"mousedown",this.clickStart.bind(this)),we(this.body,"mouseup",this.click.bind(this)))}clickStart(e){"clientX"in e&&(this.startX=e.clientX),"clientY"in e&&(this.startY=e.clientY)}click(e){var i;let t=0,r=0;if("clientX"in e&&(t=e.clientX),"clientY"in e&&(r=e.clientY),window.speechSynthesis.speaking&&this.speaking&&t===this.startX&&r===this.startY){let o=this.navigator.iframes[0].contentDocument;if(o){let s=this.highlighter.dom(o.body).getSelection(),l=s.getRangeAt(0),f=s.anchorNode;for(;l.toString().indexOf(" ")!==0;)try{l.setStart(f,l.startOffset-1)}catch{break}l.setStart(f,l.startOffset+1);do l.setEnd(f,f.length<l.endOffset?l.endOffset+1:f.length);while(l.toString().indexOf(" ")===-1&&l.toString().trim()!=="");let y=(i=document.querySelector("main#iframe-wrapper iframe").contentWindow)==null?void 0:i.document.body;if(this.ttsQueue&&y){let m=this.findTtsQueueItemIndex(this.ttsQueue,s.anchorNode,s.anchorNode,s.anchorOffset,y);s.removeAllRanges(),m>=0&&(window.speechSynthesis.cancel(),this.restartIndex=m,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}}}}initVoices(e){function t(){return new Promise(function(i,o){let s=window.speechSynthesis,l;l=setInterval(()=>{s.getVoices().length!==0&&(i(s.getVoices()),clearInterval(l))},10)})}t().then(async i=>{if(Pt.default.log(i),this.voices=[],i.forEach(s=>{s.localService===!0&&this.voices.push(s)}),Pt.default.log(this.voices),e&&this.headerMenu){var o=Le(this.headerMenu,"#preferred-languages");o&&this.voices.forEach(s=>{var l=document.createElement("option");l.value=s.name+":"+s.lang,l.innerHTML=s.name+" ("+s.lang+")",o.add(l)})}})}cancel(e=!0){var t,r,i;e&&((t=this.api)!=null&&t.stopped&&((r=this.api)==null||r.stopped()),this.navigator.emit("readaloud.stopped","stopped")),this.userScrolled=!1,this.speaking=!1,setTimeout(()=>{window.speechSynthesis.cancel()},0),this._ttsQueueItemHighlightsWord&&((i=this.navigator.highlighter)==null||i.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0)}async speak(e,t,r){var m,_,v,g,h,c,p;t||this.navigator.rights.enableContentProtection&&((m=this.navigator.contentProtectionModule)==null||m.deactivate()),(_=this.api)!=null&&_.started&&((v=this.api)==null||v.started()),this.navigator.emit("readaloud.started","started");let i=this;this.userScrolled=!1,this.cancel(!1);let o;if(t){let A=(g=document.querySelector("main#iframe-wrapper iframe").contentWindow)==null?void 0:g.document.body,E=this.navigator.iframes[0].contentDocument;if(E){let b=this.highlighter.dom(E.body).getSelection();if(b.isCollapsed){let C=i.navigator.iframes[0].contentDocument,k=(c=(h=i.navigator.annotationModule)==null?void 0:h.annotator)==null?void 0:c.getTemporarySelectionInfo(C);b.addRange(k.range)}if(A){var s=this.generateTtsQueue(A);if(!s.length)return;var l=this.findTtsQueueItemIndex(s,b.anchorNode,b.anchorNode,b.anchorOffset,A),f=this.findTtsQueueItemIndex(s,b.focusNode,b.focusNode,b.focusOffset,A);let C=Ds(s,l),k=Ds(s,f);var u;if(C&&e&&e.cleanText){let R=Fs(C),B=e.rangeInfo.startOffset,I=e.cleanText;if(k&&l+1===f){let F=Fs(k);B=(R+" "+F).indexOf(e.cleanText),I=R.slice(B,R.length),u=e.cleanText.replace(I,"").trim()}else if(f>l){let F="";for(let z=l+1;z<f;z++){let q=Ds(s,z);if(q){let G=Fs(q);F+=G,u=e.cleanText.replace(G,"")}}if(k){let z=Fs(k);F+=" "+z}B=(R+" "+F).indexOf(e.cleanText),I=R.slice(B,R.length),u=u.replace(I,"").trim()}o=new SpeechSynthesisUtterance(I),o.rate=this.tts.rate,o.pitch=this.tts.pitch,o.volume=this.tts.volume,this.setVoice(this,o),Pt.default.log(e),Pt.default.log(I,(p=e.range)==null?void 0:p.commonAncestorContainer.textContent),Pt.default.log(C),Pt.default.log(C.item.textNodes),Pt.default.log(B),Pt.default.log(C.item.combinedText);let D=C.item.textNodes.filter(F=>{var z;return F===((z=e.range)==null?void 0:z.commonAncestorContainer)})[0];Pt.default.log(D),o.onboundary=F=>{this.updateTTSInfo(C,F.charIndex,F.charLength,B,o.text)}}}}}else o=new SpeechSynthesisUtterance(this.clean);o.rate=this.tts.rate,o.pitch=this.tts.pitch,o.volume=this.tts.volume,this.setVoice(i,o),this.index=0;function y(){o.onend=function(){var w,A;if(f>l)if(l=l+1,l!==f){let E=Ds(s,l);if(E){let b=Fs(E);o=new SpeechSynthesisUtterance(b),o.rate=i.tts.rate,o.pitch=i.tts.pitch,o.volume=i.tts.volume,i.setVoice(i,o),o.onboundary=C=>{i.updateTTSInfo(E,C.charIndex,C.charLength,0,o.text)},setTimeout(()=>{window.speechSynthesis.speak(o)},0),y()}}else{let E=Ds(s,l);E&&(o=new SpeechSynthesisUtterance(u),o.rate=i.tts.rate,o.pitch=i.tts.pitch,o.volume=i.tts.volume,i.setVoice(i,o),o.onboundary=b=>{i.updateTTSInfo(E,b.charIndex,b.charLength,0,o.text)},setTimeout(()=>{window.speechSynthesis.speak(o)},0),y()),l>f&&(Pt.default.log("utterance ended"),i.highlighter.doneSpeaking(),(w=i.api)==null||w.finished(),i.navigator.emit("readaloud.finished","finished"))}else Pt.default.log("utterance ended"),i.highlighter.doneSpeaking(),(A=i.api)==null||A.finished(),i.navigator.emit("readaloud.finished","finished")}}setTimeout(()=>{var w;window.speechSynthesis.speak(o),t||this.navigator.rights.enableContentProtection&&((w=this.navigator.contentProtectionModule)==null||w.recalculate(200))},0),y(),r()}setVoice(e,t){Pt.default.log("this.tts.voice.lang",this.tts.voice.lang);let r=!0;this.tts.voice&&this.tts.voice.lang&&(r=this.tts.voice.lang.indexOf("-")!==-1,r||(this.tts.voice.lang=this.tts.voice.lang.replace("_","-"),r=!0)),Pt.default.log("initialVoiceHasHyphen",r),Pt.default.log("voices",this.voices);let i;r?(i=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(u=>{var y=u.lang.replace("_","-");return y===this.tts.voice.lang&&u.name===this.tts.voice.name})[0]:void 0,i===void 0&&(i=this.tts.voice&&this.tts.voice.lang?this.voices.filter(u=>u.lang.replace("_","-")===this.tts.voice.lang)[0]:void 0)):(i=this.tts.voice&&this.tts.voice.lang&&this.tts.voice.name?this.voices.filter(u=>u.lang===this.tts.voice.lang&&u.name===this.tts.voice.name)[0]:void 0,i===void 0&&(i=this.tts.voice&&this.tts.voice.lang?this.voices.filter(u=>u.lang===this.tts.voice.lang)[0]:void 0)),Pt.default.log("initialVoice",i);let o=e.navigator.publication.Metadata.Language[0].indexOf("-")!==-1;Pt.default.log("publicationVoiceHasHyphen",o);let s;o?s=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(u=>{var y=u.lang.replace("_","-");return y.startsWith(e.navigator.publication.Metadata.Language[0])||y.endsWith(e.navigator.publication.Metadata.Language[0].toUpperCase())})[0]:void 0:s=this.tts.voice&&this.tts.voice.usePublication?this.voices.filter(u=>u.lang.startsWith(e.navigator.publication.Metadata.Language[0])||u.lang.endsWith(e.navigator.publication.Metadata.Language[0].toUpperCase()))[0]:void 0,Pt.default.log("publicationVoice",s);let l=navigator.language.indexOf("-")!==-1;Pt.default.log("defaultVoiceHasHyphen",l);let f;l?f=this.voices.filter(u=>u.lang.replace("_","-")===navigator.language&&u.localService)[0]:f=this.voices.filter(u=>u.lang===navigator.language&&u.localService)[0],f===void 0&&(f=this.voices.filter(u=>u.lang.includes(navigator.language)&&u.localService)[0]),Pt.default.log("defaultVoice",f),i?(Pt.default.log("initialVoice"),t.voice=i):s?(Pt.default.log("publicationVoice"),t.voice=s):f&&(Pt.default.log("defaultVoice"),t.voice=f),t.voice!==void 0&&t.voice!==null&&(t.lang=t.voice.lang,Pt.default.log("utterance.voice.lang",t.voice.lang),Pt.default.log("utterance.lang",t.lang)),Pt.default.log("navigator.language",navigator.language)}speakPlay(){var i,o,s,l,f;this.navigator.rights.enableContentProtection&&((i=this.navigator.contentProtectionModule)==null||i.deactivate()),this.scrollPartial=!0,this.cancel(!1),(o=this.api)!=null&&o.started&&((s=this.api)==null||s.started()),this.navigator.emit("readaloud.started","started");let e=this,r=(l=document.querySelector("main#iframe-wrapper iframe").contentWindow)==null?void 0:l.document.body;if(r){let m=function(){var g;let _=e.highlighter.visibleTextRects[0],v=e.navigator.iframes[0].contentDocument;if(v){let h=e.highlighter.dom(v.body).getWindow().document.createRange(),c=e.highlighter.dom((g=e.navigator.iframes[0].contentDocument)==null?void 0:g.body).getSelection();c.removeAllRanges(),h.selectNodeContents(_.node),c.addRange(h);let p=0,w=c.focusNode,A=c.focusOffset;c.collapse(c.anchorNode,c.anchorOffset);for(let E=0;E<p;E++)c.modify("move","forward","line");if(c.extend(w,A),c.collapse(c.anchorNode,c.anchorOffset),r){let E=e.findTtsQueueItemIndex(u,c.anchorNode,c.anchorNode,c.anchorOffset,r);E>=0&&(y=E)}c.removeAllRanges()}},u=this.generateTtsQueue(r);if(!u.length)return;let y=0;m(),y<0&&(y=0),setTimeout(()=>{this.startTTSSession(u,y)},200)}this.navigator.rights.enableContentProtection&&((f=this.navigator.contentProtectionModule)==null||f.recalculate(200))}speakPause(){var e,t,r;window.speechSynthesis.speaking&&((e=this.api)!=null&&e.paused&&((t=this.api)==null||t.paused()),this.navigator.emit("readaloud.paused","paused"),this.userScrolled=!1,window.speechSynthesis.pause(),this.speaking=!1,this._ttsQueueItemHighlightsWord&&((r=this.navigator.highlighter)==null||r.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0))}speakResume(){var e,t;window.speechSynthesis.speaking&&((e=this.api)!=null&&e.resumed&&((t=this.api)==null||t.resumed()),this.navigator.emit("readaloud.resumed","resumed"),this.userScrolled=!1,window.speechSynthesis.resume(),this.speaking=!0)}static async create(e){let t=new this(e.tts,e.rights,e.highlighter,e,e.api,e.headerMenu);return await t.start(),t}async start(){var t;if(this.headerMenu){var e=Le(this.headerMenu,"#menu-button-tts");e&&((t=e.parentElement)==null||t.style.removeProperty("display"))}setTimeout(()=>{var r;(r=this.properties)!=null&&r.hideLayer?this.navigator.hideLayer("readaloud"):this.navigator.showLayer("readaloud")},10)}wheel(e){if(e instanceof KeyboardEvent)switch(e.key){case"ArrowUp":this.userScrolled=!0;break;case"ArrowDown":this.userScrolled=!0;break}else this.userScrolled=!0}stop(){Pt.default.log("TTS module stop"),Ue(document,"wheel",this.wheel.bind(this)),Ue(this.body,"wheel",this.wheel.bind(this)),Ue(document,"keydown",this.wheel.bind(this)),Ue(this.navigator.iframes[0].contentDocument,"keydown",this.wheel.bind(this)),Ue(this.body,"click",this.click.bind(this))}generateTtsQueue(e){let t=[],r=[];function i(f){if(f.nodeType!==Node.TEXT_NODE||!f.nodeValue||!f.nodeValue.trim().length)return;let u=r[r.length-1];if(!u)return;let y=f.parentElement?_E(f.parentElement):void 0,m=f.parentElement?HU(f.parentElement):void 0,_=t[t.length-1];(!_||_.parentElement!==u||_.lang!==y||_.dir!==m)&&(_={combinedText:"",dir:m,lang:y,parentElement:u,textNodes:[]},t.push(_)),_.textNodes.push(f)}let o=!0;function s(f){if(f.nodeType!==Node.ELEMENT_NODE)return;let u=o||f.matches("h1, h2, h3, h4, h5, h6, p, th, td, caption, li, blockquote, q, dt, dd, figcaption, div, pre");o=!1,u&&r.push(f);for(let y of f.childNodes)switch(y.nodeType){case Node.ELEMENT_NODE:let m=y;if(!m.matches("img, sup, sub, audio, video, source, button, canvas, del, dialog, embed, form, head, iframe, meter, noscript, object, s, script, select, style, textarea"))s(m);else if(m.tagName&&m.tagName.toLowerCase()==="img"&&m.src){let v=m.getAttribute("alt");if(v){let g=v.trim();if(g){let h=_E(m);t.push({combinedText:g,dir:void 0,lang:h,parentElement:m,textNodes:[]})}}}break;case Node.TEXT_NODE:r.length!==0&&i(y);break;default:break}u&&r.pop()}s(e);function l(f){if(!f.textNodes||!f.textNodes.length){(!f.combinedText||!f.combinedText.length)&&(f.combinedText="");return}f.combinedText=UU(f.textNodes,!0).replace(/[\r\n]/g," ");let u=f.parentElement;for(;u;){if(u.tagName){let y=u.tagName.toLowerCase();if(y==="pre"||y==="code"||y==="video"||y==="audio")break}u=u.parentElement}}for(let f of t)l(f);return t}findTtsQueueItemIndex(e,t,r,i,o){let s=0;for(let l of e){if(r&&l.textNodes){if(l.textNodes.includes(r))return s}else if(t===l.parentElement||l.parentElement!==t.ownerDocument.body&&l.parentElement!==o&&l.parentElement.contains(t)||t.contains(l.parentElement))return s;s++}return-1}restart(){window.speechSynthesis.speaking&&(window.speechSynthesis.cancel(),this.restartIndex=this.ttsQueueIndex,this.ttsPlayQueueIndexDebounced(this.restartIndex,this.ttsQueue))}startTTSSession(e,t){if(!Ds(e,t)){this.cancel();return}this.speaking=!0,this.ttsPlayQueueIndexDebounced(t,e)}ttsPlayQueueIndex(e,t){if(e<0){this.cancel();return}let r=Ds(t,e);if(!r){this.cancel();return}let i=Fs(r);if(!i){this.cancel();return}let o=new SpeechSynthesisUtterance(i);o.rate=this.tts.rate,o.pitch=this.tts.pitch,o.volume=this.tts.volume;let s=this;this.setVoice(s,o),o.onboundary=l=>{Pt.default.log(l.name),this.updateTTSInfo(r,l.charIndex,l.charLength,0,o.text)},setTimeout(()=>{window.speechSynthesis.speak(o),s.speaking||window.speechSynthesis.pause()},0),o.onend=function(){s.speaking&&s.ttsPlayQueueIndexDebounced(e+1,t)}}updateTTSInfo(e,t,r,i,o){if(!e)return;Pt.default.log(e,t,r,o);let s=o||Fs(e);if(t>=0&&o){let l=o.slice(0,t+1).search(/\S+$/),f=o.slice(t).search(/\s/),u=f<0?o.slice(l):o.slice(l,f+t),y=l+u.length;if(r===void 0){let m=o.substring(t).match(/^[a-z\d']*/i);m&&(r=m[0].length)}r===void 0&&(r=u.length),this.wrapHighlightWord(e,o,t+i,r,u,l,y)}return s}wrapHighlightWord(e,t,r,i,o,s,l){var c,p,w,A,E,b,C,k,R,B;Pt.default.log(e),Pt.default.log(t),Pt.default.log(r,i,o,s,l),this._ttsQueueItemHighlightsWord&&((c=this.navigator.highlighter)==null||c.destroyHighlights(2),this._ttsQueueItemHighlightsWord=void 0);let f=e.item,u=r,y=0,m,_=-1,v,g=-1,h=u+i;for(let I of f.textNodes){if(!I.nodeValue&&I.nodeValue!=="")continue;let D=I.nodeValue.length;if(y+=D,m||u<y&&(m=I,_=D-(y-u)),m&&h<=y&&(v=I,g=D-(y-h)),v)break}if(m&&v){let F=function(G){try{let Y=D.navigator.iframes[0].contentDocument;return Y?Cr(G,Y,Jo):""}catch(Y){return Pt.default.log("uniqueCssSelector:"),Pt.default.error(Y),""}},I=new Range;I.setStart(m,_),I.setEnd(v,g);let D=this,z=mo(I,F);if(!z)return;let q=(p=this.navigator.highlighter)==null?void 0:p.createHighlight(this.navigator.iframes[0].contentWindow,{rangeInfo:z,cleanText:"",rawText:"",range:void 0},this.tts.color,!1,3,{id:"tts",title:"",position:"right"},void 0,{defaultClass:this.tts.color},2,"R2_READALOUD_");if(q){this._ttsQueueItemHighlightsWord=q[0];let X=((A=(w=q[1])==null?void 0:w.firstChild)==null?void 0:A.getBoundingClientRect()).top-this.wrapper.scrollTop>window.innerHeight/2-65;(E=this.navigator.view)!=null&&E.isScrollMode()&&this.tts.autoScroll&&!this.userScrolled&&this.scrollPartial&&X?(C=(b=q[1])==null?void 0:b.firstChild)==null||C.scrollIntoView({block:"center",behavior:"smooth"}):(k=this.navigator.view)!=null&&k.isPaginated()&&((B=D.navigator.view)==null||B.snap((R=q[1])==null?void 0:R.firstChild))}}}};function _E(n){let e=n;for(;e&&e.nodeType===Node.ELEMENT_NODE;){let t=e.getAttribute("xml:lang");if(t||(t=e.getAttributeNS("http://www.w3.org/XML/1998/namespace","lang")),t||(t=e.getAttribute("lang")),t)return t;e=e.parentNode}}function HU(n){let e=n;for(;e&&e.nodeType===Node.ELEMENT_NODE;){let t=e.getAttribute("dir");if(t)return t;e=e.parentNode}}function UU(n,e){if(n&&n.length){let t="";for(let r of n)r.nodeValue&&(t+=e?r.nodeValue:qU(r.nodeValue));return t}return""}function jU(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function qU(n){return jU(n).replace(/\n/g," ").replace(/\s\s+/g," ")}function Ds(n,e){let t=-1,r=-1;for(let i of n)if(r++,t++,e===t)return{item:i,iArray:r,iGlobal:t,iSentence:-1}}function Fs(n){return n.item.combinedText}L();var Gl=rt(If());var AE=rt(Vo());var EE=rt($t()),su=class{constructor(e,t,r,i){this.currentChapterPopupResult=[];this.currentPopupHighlights=[];this.definitions=(0,AE.default)(async()=>{if(await this.highlighter.destroyHighlights(4),this.properties.definitions)for(let e of this.properties.definitions)await this.define(e)},200);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);return await t.start(),t}async stop(){EE.default.log("Definitions module stop")}async start(){setTimeout(()=>{this.properties.hideLayer?this.navigator.hideLayer("definitions"):this.navigator.showLayer("definitions")},10)}async searchAndPaint(e,t){var s;let r=this.publication.getAbsoluteHref(this.publication.readingOrder?this.publication.readingOrder[this.navigator.currentResource()??0].Href:""),i=this.publication.getTOCItem(r);i===void 0&&this.publication.readingOrder&&(i=this.publication.readingOrder[this.navigator.currentResource()??0]);let o=[];if(i)for(let l of e.terms){let f=e.terms.indexOf(l);i&&await ts(l,this.navigator.iframes[0].contentDocument,i.Href,i.Title,(s=this.navigator.definitionsModule)==null?void 0:s.properties.fullWordSearch).then(u=>{let y;e.result===1?y=0:e.result===2&&(y=Math.floor(Math.random()*u.length-1)+1),u.forEach((m,_)=>{if(y===void 0||y===_){let v={rangeInfo:m.rangeInfo},g=this.createDefinitionHighlight(v,e);m.highlight=g,o.push(Gl.omit(g,"definition")),this.currentChapterPopupResult.push(m),this.currentPopupHighlights.push(g)}}),f===e.terms.length-1&&t(o)})}}async define(e){await this.searchAndPaint(e,async t=>{var r,i,o;(r=this.api)!=null&&r.success&&((i=this.api)==null||i.success(Gl.omit(e,"callbacks"),t),this.navigator.emit("definition.success",t),(o=this.api)!=null&&o.visible&&t.forEach(s=>{var y;let l=(y=this.navigator.iframes[0].contentDocument)==null?void 0:y.querySelector(`#${s.id}`),f=l==null?void 0:l.querySelectorAll(`.${jr}`),u=new IntersectionObserver((m,_)=>{m.forEach(v=>{var g;v.intersectionRatio===1&&((g=this.api)==null||g.visible(Gl.omit(e,"callbacks"),Gl.omit(s,"definition")),this.navigator.emit("definition.visible",e,s))})},{threshold:1});f&&f.length>0&&u.observe(f[0])}))})}async drawDefinitions(){setTimeout(async()=>{await this.definitions()},100)}async handleResize(){await this.drawDefinitions()}createDefinitionHighlight(e,t){var r;try{let i=(r=this.navigator.definitionsModule)==null?void 0:r.properties.color;Jt.isHexColor(i)&&(i=Jt.hexToRgbChannels(i));let o=`${e.rangeInfo.startContainerElementCssSelector}${e.rangeInfo.startContainerChildTextNodeIndex}${e.rangeInfo.startOffset}${e.rangeInfo.endContainerElementCssSelector}${e.rangeInfo.endContainerChildTextNodeIndex}${e.rangeInfo.endOffset}`,l="R2_DEFINITION_"+Ui.hash(o);this.highlighter.destroyHighlight(this.navigator.iframes[0].contentDocument,l);let f={color:i||Ls,id:l,pointerInteraction:!0,selectionInfo:e,marker:1,type:4};er.push(f);let u=this.highlighter.createHighlightDom(this.navigator.iframes[0].contentWindow,f);return u&&(t.definition&&(u.dataset.definition=t.definition),u.dataset.order=String(t.order),f.definition=t,f.position=parseInt((u!=null&&u.hasChildNodes()?u.childNodes[0]:u).style.top.replace("px",""))),f}catch(i){throw"Can't create definitions highlight: "+i}}async addDefinition(e){await this.define(e)}async clearDefinitions(){await this.highlighter.destroyHighlights(4)}};L();var TE=rt(xE(),1);var bh=TE.default;L();var rs=rt($t()),PE=.5,Us=class{constructor(e,t,r){this.hasEventListener=!1;this.lines=[];this.index=0;this.isActive=!1;this.isDebug=!1;this.lineFocusContainer=document.getElementById("lineFocusContainer");this.readerContainer=document.getElementById("D2Reader-Container");this.lineFocusTopBlinder=document.getElementById("lineFocusTopBlinder");this.lineFocusBottomBlinder=document.getElementById("lineFocusBottomBlinder");this.wrapperHeight=void 0;this.properties=e,this.api=r,this.highlighter=t}static async create(e){let t=new this(e,e.highlighter,e.api);return await t.start(),t}async stop(){rs.default.log("Definitions module stop"),this.hasEventListener=!1,Ue(document,"keydown",this.keydown.bind(this)),Ue(document,"keyup",this.keyup.bind(this)),Ue(this.navigator.iframes[0].contentDocument,"keydown",this.keydown.bind(this)),Ue(this.navigator.iframes[0].contentDocument,"keyup",this.keyup.bind(this))}async start(){let e=yt(document,"#iframe-wrapper");e.style.height.length>0&&(this.wrapperHeight=e.style.height,this.lineFocusContainer&&this.lineFocusContainer.style.height.length===0&&(this.lineFocusContainer.style.height=this.wrapperHeight),this.readerContainer&&this.readerContainer.style.height.length===0&&(this.readerContainer.style.height=this.wrapperHeight),this.readerContainer&&(this.readerContainer.style.overflow="hidden"))}initialize(e){return new Promise(async t=>{await document.fonts.ready,this.hasEventListener||(this.hasEventListener=!0,we(document,"keydown",this.keydown.bind(this)),we(document,"keyup",this.keyup.bind(this)),we(e.contentDocument,"keydown",this.keydown.bind(this)),we(e.contentDocument,"keyup",this.keyup.bind(this))),t(null)})}keydown(e){if(e instanceof KeyboardEvent&&this.isActive)switch(e.key){case"ArrowUp":e.stopPropagation();break;case"ArrowDown":e.stopPropagation();break}}keyup(e){if(e instanceof KeyboardEvent&&this.isActive)switch(e.key){case"ArrowUp":this.lineUp();break;case"ArrowDown":this.lineDown();break}}handleResize(){this.isActive&&this.lineFocus()}async enableLineFocus(){this.isActive=!0,await this.navigator.settings.scroll(!0),this.lineFocus()}disableLineFocus(e=!0){this.isActive=!1;let t=yt(document,"#iframe-wrapper");this.wrapperHeight&&(t.style.height=this.wrapperHeight),e||(this.index=0);let r=this.navigator.iframes[0].contentDocument;cr(r,"html").style.removeProperty("--USER__maxMediaHeight"),this.wrapperHeight=void 0,this.lineFocusContainer&&(this.lineFocusContainer.style.display="none");let o=document.getElementById("container-view-timeline");o&&o.style.removeProperty("display");let s=document.getElementById("divBefore");s&&s.remove();let l=document.getElementById("divAfter");l&&l.remove(),this.highlighter.destroyHighlights(5)}lineFocus(){var y;let e=yt(document,"#iframe-wrapper"),t=this.navigator.iframes[0].contentDocument,r=cr(t,"html"),i=this.properties.maxHeight?gi()*this.properties.maxHeight/100:gi()/2;r.style.setProperty("--USER__maxMediaHeight",i+"px");function o(m,_){m.parentNode.insertBefore(_,m.nextSibling)}function s(m,_){m.parentNode.insertBefore(_,m)}let l=document.getElementById("container-view-timeline");l&&(l.style.display="none"),this.lineFocusContainer&&this.lineFocusContainer.style.removeProperty("display");let f=document.getElementById("divBefore");if(f)f.style.height=e.clientHeight/2+"px";else{let m=document.createElement("div");m.style.height=e.clientHeight/2+"px",m.id="divBefore",s(e,m)}let u=document.getElementById("divAfter");if(u)u.style.height=e.clientHeight/2+"px";else{let m=document.createElement("div");m.style.height=e.clientHeight/2+"px",m.id="divAfter",o(e,m)}if(this.lines=[],t){let v=function(){let A=Math.round,E=Math.random,b=255;return{blue:A(E()*b),green:A(E()*b),red:A(E()*b)}},g=function(A,E){let b=[];for(let C=0,k=0;C<A.length;C++)C>=E&&C%E===0&&k++,b[k]=b[k]||[],b[k].push(A[C]);return b},h=function(A,E){let b=Math.min(A.left,E.left),C=Math.max(A.right,E.right),k=Math.min(A.top,E.top),R=Math.max(A.bottom,E.bottom);return{bottom:R,height:R-k,left:b,right:C,top:k,width:C-b}},c=function(A){if(A.length>1){let E=h(A[0],A[1]);if(A.length>2){let b=h(E,A[2]);if(A.length>3){let C=h(b,A[3]);return A.length>4?h(C,A[4]):C}return b}return E}return A[0]},m=this.findRects(t.body);m=Gg(m,!0),m=m.sort(function(A,E){return A.top-E.top});let _=[];m=m.filter(function(A){let E=A.top;return _.indexOf(E)===-1&&_.indexOf(E+1)===-1&&_.indexOf(E+2)===-1&&_.indexOf(E+3)===-1&&_.indexOf(E+4)===-1&&_.indexOf(E-1)===-1&&_.indexOf(E-2)===-1&&_.indexOf(E-3)===-1&&_.indexOf(E-4)===-1?(_.push(E),!0):!1}),this.highlighter.destroyHighlights(5);let p=[];this.properties.lines&&this.properties.lines>1?g(m,this.properties.lines).forEach(E=>{p.push(c(E))}):p=m;let w=Le(t,"#"+"R2_ID_LINEFOCUS_CONTAINER");if(w)for(let A of p){let E=document.createElement("div");E.setAttribute("class",jr);let b=v();if(Jt.isHexColor(b)&&(b=Jt.hexToRgbChannels(b)),this.isDebug){let ve=`border-bottom: 1px solid rgba(${b.red}, ${b.green}, ${b.blue}, ${PE}) !important`;E.setAttribute("style",`mix-blend-mode: multiply; border-radius: 1px !important; background-color: rgba(${b.red}, ${b.green}, ${b.blue}, ${PE}) !important; ${ve}`)}E.style.outline="none",E.tabIndex=0;let C=this.navigator.iframes[0].contentWindow.document,k=this.navigator.view.isPaginated();k?C.body.style.position="revert":C.body.style.position="relative";let R=C.body.getBoundingClientRect(),B=this.highlighter.getScrollingElement(C),I=k?-B.scrollLeft:R.left,D=k?-B.scrollTop:R.top,F=1,z=24,q,G,Y=(y=this.navigator.iframes[0].contentWindow)==null?void 0:y.innerWidth,X=parseInt(getComputedStyle(t.documentElement).getPropertyValue("column-count")),Q=parseInt(getComputedStyle(t.documentElement).getPropertyValue("column-width")),se=parseInt(getComputedStyle(t.body).getPropertyValue("padding-left"));if(Y){let ve=Y/(X||1);ve<Q&&(ve=Y),k||(ve=parseInt(getComputedStyle(t.body).width.replace("px","")));let ce=this.navigator.settings.fontSize/100,W=20*ce;ce<=1&&(W=-60);let H=0;ce<=1&&(H=-60),q=Math.floor(A.left/ve)*ve+ve-(z<40?40:z)+H,G=Math.floor(A.left/ve)*ve+(z<40?40:z)-W;let M=parseInt(t.documentElement.style.getPropertyValue("--USER__pageMargins"));M>=2&&(G=G+se/X,q=q-se/X),k||(q=parseInt(getComputedStyle(t.body).width.replace("px","")),G=parseInt(getComputedStyle(t.body).width.replace("px",""))-ve,M>=2&&(G=G+se/2,q=q-se/2))}E.style.setProperty("pointer-events","none"),E.style.position="absolute",E.scale=F,E.rect={height:A.height,left:A.left-I,top:A.top-D,width:A.width},E.style.width=`${E.rect.width*F}px`,E.style.height=`${E.rect.height*F}px`,E.style.left=`${E.rect.left*F}px`,E.style.top=`${E.rect.top*F}px`,this.lines.push(E),w.append(E)}setTimeout(()=>{this.currentLine()},100)}}currentLine(){let e=this.lines[this.index],t=e.style.top,i=parseInt(e.style.top.replace("px",""))+parseInt(e.style.height.replace("px",""))-parseInt(t.replace("px",""));if(this.lineFocusContainer){let s=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-i)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=s+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=s+"px")}e.scrollIntoView({block:"center",behavior:"smooth"})}lineDown(){if(this.index<this.lines.length-1){this.index+=1,this.index>this.lines.length-1&&(this.index=this.lines.length-1);let e=this.lines[this.index],t=e.style.top,i=parseInt(e.style.top.replace("px",""))+parseInt(e.style.height.replace("px",""))-parseInt(t.replace("px",""));if(this.lineFocusContainer){let s=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-i)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=s+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=s+"px")}e.scrollIntoView({block:"center",behavior:"smooth"})}}lineUp(){if(this.index>0){this.index-=1,this.index<0&&(this.index=0);let e=this.lines[this.index],t=e.style.top,i=parseInt(e.style.top.replace("px",""))+parseInt(e.style.height.replace("px",""))-parseInt(t.replace("px",""));if(this.lineFocusContainer){let s=(parseInt(getComputedStyle(this.lineFocusContainer).height.replace("px",""))-i)/2;this.lineFocusTopBlinder&&(this.lineFocusTopBlinder.style.height=s+"px"),this.lineFocusBottomBlinder&&(this.lineFocusBottomBlinder.style.height=s+"px")}e.scrollIntoView({block:"center",behavior:"smooth"})}}almostEqual(e,t,r){return Math.abs(e-t)<=r}findRects(e){let t=this.findTextNodes(e),r=Array.from(e.getElementsByTagName("img")),i=[];return t.forEach(o=>{i.push(...this.measureTextNodes(o))}),r.forEach(o=>{i.push(...this.measureImageNodes(o))}),i}findTextNodes(e,t=[]){var i,o,s,l,f,u,y;let r=e.firstChild;for(;r;)r.nodeType===1&&this.findTextNodes(r,t),r.nodeType===3&&(i=r.textContent)!=null&&i.trim()&&(r.textContent.trim().length>1||((o=r.parentElement)==null?void 0:o.tagName.toLowerCase())==="h1"||((s=r.parentElement)==null?void 0:s.tagName.toLowerCase())==="h2"||((l=r.parentElement)==null?void 0:l.tagName.toLowerCase())==="h3"||((f=r.parentElement)==null?void 0:f.tagName.toLowerCase())==="h4"||((u=r.parentElement)==null?void 0:u.tagName.toLowerCase())==="h5"||((y=r.parentElement)==null?void 0:y.tagName.toLowerCase())==="h6")&&r.parentElement&&getComputedStyle(r.parentElement).verticalAlign==="baseline"&&t.push(r),r=r.nextSibling;return t}measureTextNodes(e){try{let t=document.createRange();t.selectNodeContents(e);let r=Array.from(t.getClientRects());return t.detach(),r}catch(t){rs.default.log("measureTextNode "+t),rs.default.log("measureTextNode "+e),rs.default.log(`${e.textContent}`)}}measureImageNodes(e){try{let t=document.createRange();t.selectNode(e);let r=Array.from(t.getClientRects());return t.detach(),r}catch(t){rs.default.log("measureTextNode "+t),rs.default.log("measureTextNode "+e),rs.default.log(`${e.textContent}`)}}};L();var OE=rt($t()),au=class{constructor(e,t,r,i){this.history=[];this.headerMenu=i,this.publication=t,this.properties=r,this.annotator=e}static async create(e){let t=new this(e.annotator,e.publication,e,e.headerMenu);return await t.start(),t}async stop(){OE.default.log("Page Break module stop"),Ue(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),Ue(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleResize(){await this.setup()}setup(){this.history.length>0&&(this.historyForwardAnchorElement&&this.historyCurrentIndex+1<this.history.length?this.historyForwardAnchorElement.className=this.historyForwardAnchorElement.className.replace(" disabled",""):this.historyForwardAnchorElement&&(this.historyForwardAnchorElement.removeAttribute("href"),this.historyForwardAnchorElement.className+=" disabled"),this.historyBackAnchorElement&&this.historyCurrentIndex>0?this.historyBackAnchorElement.className=this.historyBackAnchorElement.className.replace(" disabled",""):this.historyBackAnchorElement&&(this.historyBackAnchorElement.removeAttribute("href"),this.historyBackAnchorElement.className+=" disabled"))}async push(e,t){if(t&&this.annotator){let r=await this.annotator.getLastReadingPosition();if(r){let o=this.publication.getAbsoluteHref(r.href);if(r.href=o,this.historyCurrentIndex<this.history.length-1)this.history=this.history.slice(0,this.historyCurrentIndex),this.history.push(r),this.historyCurrentIndex=this.history.length-1;else if(r!=null&&r.locations.progression&&(r==null?void 0:r.locations.progression)>0)this.history.push(r),this.historyCurrentIndex=this.history.length-1;else{let s=this.history[this.history.length-1];(s&&s.href!==e.href&&s.locations!==e.locations||s===void 0)&&(this.history.push(r),this.historyCurrentIndex=this.history.length-1)}}this.historyCurrentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyCurrentIndex));let i=this.history[this.history.length-1];(i&&i.href!==e.href||i===void 0)&&(this.history.push(e),this.historyCurrentIndex=this.history.length-1)}}async start(){this.headerMenu&&(this.historyForwardAnchorElement=Le(this.headerMenu,"#history-forward")),this.headerMenu&&(this.historyBackAnchorElement=Le(this.headerMenu,"#history-back")),this.historyCurrentIndex=this.history.length-1,we(this.historyForwardAnchorElement,"click",this.handleHistoryForwardClick.bind(this)),we(this.historyBackAnchorElement,"click",this.handleHistoryBackClick.bind(this))}async handleHistoryForwardClick(e){await this.historyForward(),e.preventDefault(),e.stopPropagation()}async historyForward(){this.history.length>0&&this.historyCurrentIndex+1<this.history.length&&(this.historyCurrentIndex=this.historyCurrentIndex+1,await this.navigator.navigate(this.history[this.historyCurrentIndex],!1))}async handleHistoryBackClick(e){await this.historyBack(),e.preventDefault(),e.stopPropagation()}async historyBack(){this.history.length>0&&this.historyCurrentIndex>0&&(this.historyCurrentIndex=this.historyCurrentIndex-1,await this.navigator.navigate(this.history[this.historyCurrentIndex],!1))}};L();var ME=rt($t()),vh=(r=>(r[r.Chicago=0]="Chicago",r[r.MLA=1]="MLA",r[r.APA=2]="APA",r))(vh||{});var js=class{constructor(e,t,r,i){this.highlighter=t,this.properties=r,this.publication=e,this.api=i}static async create(e){let t=new this(e.publication,e.highlighter,e,e.api);return await t.start(),t}async stop(){ME.default.log("Citation module stop")}copyToClipboard(e){var r,i,o;(r=this.navigator)!=null&&r.contentProtectionModule&&(this.navigator.contentProtectionModule.citation=!0);let t=!0;if(window.clipboardData)window.clipboardData.setData("text/plain",e);else{let s=this.createElementForExecCommand(e);this.selectContent(s);try{window.netscape&&netscape.security&&netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"),t=document.execCommand("copy",!1)}catch{t=!1}document.body.removeChild(s)}t?(i=this.api)==null||i.citationCreated("The text was copied to the clipboard!"):(o=this.api)==null||o.citationFailed("Your browser doesn't allow clipboard access!")}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)}async start(){var r;let e=this,t={id:"citationIcon",callback:function(i){var B,I,D;let o=function(){var G;let F="",z="",q="";return e.properties.author?(q=q+e.properties.author,z=z+e.properties.author,F=F+e.properties.author):((G=e.publication.Metadata.Author)==null?void 0:G.length)>0&&0===0&&e.publication.Metadata.Author[0].Name&&e.publication.Metadata.Author[0].Name instanceof String&&e.publication.Metadata.Author[0].Name.length>0&&(q=q+e.publication.Metadata.Author[0].Name,z=z+e.publication.Metadata.Author[0].Name,F=F+e.publication.Metadata.Author[0].Name),q.length>0&&z.length>0&&F.length>0?[F+". ",z+". ",q+". "]:["","",""]},s=function(){let F="",z="",q="";return e.properties.publisher?(z=z+e.properties.publisher,F=F+e.properties.publisher):e.publication.Metadata.Publisher&&e.publication.Metadata.Publisher[0].Name&&(z=z+e.publication.Metadata.Publisher[0].Name,F=F+e.publication.Metadata.Publisher[0].Name),e.properties.published?(q=q+"("+e.properties.published+")",z=z+", "+e.properties.published,F=F+", "+e.properties.published):e.publication.Metadata.PublicationDate&&e.publication.Metadata.PublicationDate.getFullYear()>0&&(q=q+"("+e.publication.Metadata.PublicationDate.getFullYear()+")",z=z+", "+e.publication.Metadata.PublicationDate.getFullYear(),F=F+", "+e.publication.Metadata.PublicationDate.getFullYear()),q.length>0&&z.length>0&&F.length>0?[F+". ",z+". ",q+". "]:["","",""]},l=function(){return e.properties.title?["<em>"+e.properties.title+"</em>. ","<em>"+e.properties.title+"</em>. ","<em>"+e.properties.title+"</em>. "]:e.publication.Metadata.Title?["<em>"+e.publication.Metadata.Title+"</em>. ","<em>"+e.publication.Metadata.Title+"</em>. ","<em>"+e.publication.Metadata.Title+"</em>. "]:["","",""]},f=function(){return["","",""]},u=function(){let F="",z="",q="";return e.properties.publisher?(z=z+e.properties.publisher+", ",F=F+e.properties.publisher+", ",q=q+e.properties.publisher):e.publication.Metadata.Publisher&&e.publication.Metadata.Publisher[0].Name&&(z=z+e.publication.Metadata.Publisher[0].Name+", ",F=F+e.publication.Metadata.Publisher[0].Name+", ",q=q+e.publication.Metadata.Publisher[0].Name),q.length>0&&z.length>0&&F.length>0?[F+". ",z+". ",q+". "]:["","",""]},y=function(){return["","",""]},m=function(){return["","",""]},_=function(){return["","",""]},v=function(){return e.properties.library?["Retrieved from "+e.properties.library+". ","Retrieved from "+e.properties.library+". ","Retrieved from "+e.properties.library+". "]:["","",""]},g=function(){return e.properties.appName?[e.properties.appName+". ",e.properties.appName+". ",e.properties.appName+". "]:["","",""]},h=function(){return e.properties.appLink?[e.properties.appLink+". ",e.properties.appLink+". ",e.properties.appLink+". "]:["","",""]},c=function(){return["","",""]},p=function(F,z){return F.length>z?F.substring(0,z)+"...":F},w=o()[0]+l()[0]+y()[0]+f()[0]+_()[0]+s()[0]+m()[0]+v()[0]+g()[0]+h()[0],A=o()[2]+s()[2]+l()[2]+f()[2]+u()[2]+y()[2]+m()[2]+_()[2]+v()[2]+g()[2]+h()[2],E=o()[1]+l()[1]+y()[1]+f()[1]+_()[1]+s()[1]+c()[1]+v()[1]+g()[1]+h()[1],b="\u201C"+p(i,e.properties.characters)+"\u201C<br><br>"+w,C="\u201C"+p(i,e.properties.characters)+"\u201C<br><br>"+A,k="\u201C"+p(i,e.properties.characters)+"\u201C<br><br>"+E,R="";(B=e.properties.styles)!=null&&B.includes(vh[0])&&(e.properties.styles.length>1&&(R=R+"Chicago: <br>"),R=R+b+"<br><br>"),(I=e.properties.styles)!=null&&I.includes(vh[2])&&(e.properties.styles.length>1&&(R=R+"APA: <br>"),R=R+C+"<br><br>"),(D=e.properties.styles)!=null&&D.includes(vh[1])&&(e.properties.styles.length>1&&(R=R+"MLA: <br>"),R=R+k+"<br><br>"),e.copyToClipboard(R)}};(r=this.highlighter)==null||r.addSelectionMenuItem(t)}};var yn=rt($t());var Tt=class n extends bh{constructor(t,r=void 0,i=void 0,o,s,l,f,u,y,m,_,v,g,h){super();this.iframes=[];this.sideNavExpanded=!1;this.currentChapterLink={href:""};this.currentSpreadLinks={};this.rights={autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};this.didInitKeyboardEventHandler=!1;this.onResize=()=>{clearTimeout(this.timeout),this.timeout=setTimeout(this.handleResize.bind(this),200)};this.reload=async()=>{let t;if(this.annotator&&(t=await this.annotator.getLastReadingPosition()),t){let r=this.publication.getAbsoluteHref(t.href);yn.default.log(t.href),yn.default.log(r),t.href=r,await this.navigate(t)}};this.savePosition=(0,_h.default)(()=>{this.annotator&&this.saveCurrentReadingPosition()},200);this.checkResourcePosition=(0,_h.default)(()=>{var t,r,i,o,s,l,f,u,y,m;(t=this.view)!=null&&t.atStart()&&((r=this.view)!=null&&r.atEnd())?((i=this.api)!=null&&i.resourceFitsScreen&&((o=this.api)==null||o.resourceFitsScreen()),this.emit("resource.fits")):(s=this.view)!=null&&s.atEnd()?((l=this.api)!=null&&l.resourceAtEnd&&((f=this.api)==null||f.resourceAtEnd()),this.emit("resource.end")):(u=this.view)!=null&&u.atStart()&&((y=this.api)!=null&&y.resourceAtStart&&((m=this.api)==null||m.resourceAtStart()),this.emit("resource.start"))},200);this.highlighter=g,this.highlighter&&(this.highlighter.navigator=this);for(let c in h){let p=h[c];p&&(p.navigator=this),h[c]instanceof qa&&(this.annotationModule=p),h[c]instanceof Ga&&(this.bookmarkModule=p),h[c]instanceof Hs&&(this.ttsModule=p),h[c]instanceof Hs&&(this.ttsModule=p),h[c]instanceof iu&&(this.searchModule=p),h[c]instanceof su&&(this.definitionsModule=p),h[c]instanceof za&&(this.timelineModule=p),h[c]instanceof Bs&&(this.contentProtectionModule=p),h[c]instanceof js&&(this.citationModule=p),h[c]instanceof Wa&&(this.mediaOverlayModule=p),h[c]instanceof ou&&(this.pageBreakModule=p),h[c]instanceof Us&&(this.lineFocusModule=p),h[c]instanceof au&&(this.historyModule=p),h[c]instanceof ja&&(this.consumptionModule=p)}this.settings=t,this.annotator=r,this.view=t.view,this.view.attributes=y,this.view.navigator=this,this.eventHandler=new _l(this),this.touchEventHandler=new Hl(this),this.keyboardEventHandler=new Ul(this),this.initialLastReadingPosition=i,this.publication=o,this.api=s,this.rights=l??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1},this.tts=f,this.injectables=u,this.attributes=y||{margin:0},this.services=m,this.sample=_,this.requestConfig=v,this.sampleReadEventHandler=new jl(this)}static async create(t){let r=new this(t.settings,t.annotator||void 0,t.initialLastReadingPosition||void 0,t.publication,t.api,t.rights,t.tts,t.injectables,t.attributes||{margin:0},t.services,t.sample,t.requestConfig,t.highlighter,t.modules);return await r.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(i=>i(r))}stop(){yn.default.log("Iframe navigator stop"),Ue(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),Ue(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),Ue(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ue(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),Ue(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),Ue(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),Ue(this.tryAgainButton,"click",this.tryAgain.bind(this)),Ue(this.goBackButton,"click",n.goBack.bind(this)),Ue(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),Ue(window,"resize",this.onResize),this.iframes.forEach(t=>{Ue(t,"resize",this.onResize)}),this.didInitKeyboardEventHandler&&this.keyboardEventHandler.removeEvents(document)}setDirection(t){var i,o;let r="";(t==="rtl"||t==="ltr")&&(r=t),t==="auto"&&(r=this.publication.Metadata.Direction2),r&&(r==="rtl"&&(this.spreads.style.flexDirection="row-reverse"),r==="ltr"&&(this.spreads.style.flexDirection="row"),this.keyboardEventHandler.rtl=r==="rtl",(i=this.api)!=null&&i.direction&&((o=this.api)==null||o.direction(r)),this.emit("direction",r))}async start(t,r,i){var g,h,c,p,w,A,E,b,C,k,R,B,I,D,F,z,q;this.headerMenu=r,this.mainElement=t;try{let G=yt(t,"main#iframe-wrapper");G.style.overflow="auto";let Y=Le(t,"main#iframe-wrapper iframe"),X=Le(t,"#second");if(Y&&this.iframes.push(Y),X&&this.iframes.push(X),window.matchMedia("screen and (max-width: 600px)").matches&&(this.settings.columnCount=1),this.iframes.length===0){G.style.overflow="auto";let Q=document.createElement("iframe");if(Q.setAttribute("SCROLLING","no"),Q.setAttribute("allowtransparency","true"),this.iframes.push(Q),this.publication.isFixedLayout){this.spreads=document.createElement("div"),this.firstSpread=document.createElement("div"),this.spreads.style.display="flex",this.spreads.style.alignItems="center",this.spreads.style.justifyContent="center",this.spreads.appendChild(this.firstSpread),this.firstSpread.appendChild(this.iframes[0]),G.appendChild(this.spreads);let se="";switch(this.settings.direction){case 0:se="auto";break;case 1:se="ltr";break;case 2:se="rtl";break}this.setDirection(se)}else Q.setAttribute("height","100%"),Q.setAttribute("width","100%"),G.appendChild(this.iframes[0]);if(this.publication.isFixedLayout)if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){let se=document.createElement("div");this.spreads.appendChild(se);let ve=document.createElement("iframe");ve.setAttribute("SCROLLING","no"),ve.setAttribute("allowtransparency","true"),ve.style.opacity="1",ve.style.border="none",ve.style.overflow="hidden",this.iframes.push(ve),se.appendChild(this.iframes[1]),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",se.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",se.style.boxShadow="0 0 8px 2px #ccc"}else this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc";else this.iframes[0].style.paddingTop=(((g=this.attributes)==null?void 0:g.iframePaddingTop)??0)+"px"}if(this.publication.isFixedLayout){let Q=G.clientHeight;var o=(h=this.iframes[0].parentElement)==null?void 0:h.parentElement;o.style.height=Q+40+"px"}else this.iframes.length===2&&this.iframes.pop();if(this.loadingMessage=Le(t,"#reader-loading"),this.loadingMessage&&(this.loadingMessage.innerHTML=mh,this.loadingMessage.style.display="none"),this.errorMessage=Le(t,"#reader-error"),this.errorMessage&&(this.errorMessage.innerHTML=bE,this.errorMessage.style.display="none"),this.tryAgainButton=Le(t,"button[class=try-again]"),this.goBackButton=Le(t,"button[class=go-back]"),this.infoTop=Le(t,"div[class='info top']"),this.infoBottom=Le(t,"div[class='info bottom']"),this.headerMenu&&(this.bookTitle=Le(this.headerMenu,"#book-title")),this.infoBottom&&(this.chapterTitle=Le(this.infoBottom,"span[class=chapter-title]")),this.infoBottom&&(this.chapterPosition=Le(this.infoBottom,"span[class=chapter-position]")),this.infoBottom&&(this.remainingPositions=Le(this.infoBottom,"span[class=remaining-positions]")),this.headerMenu&&(this.espandMenuIcon=Le(this.headerMenu,"#expand-menu")),this.headerMenu&&(this.links=Le(this.headerMenu,"ul.links.top")),this.headerMenu&&(this.linksTopLeft=Le(this.headerMenu,"#nav-mobile-left")),this.headerMenu&&(this.tocView=Le(this.headerMenu,"#container-view-toc")),this.headerMenu&&(this.landmarksView=Le(this.headerMenu,"#container-view-landmarks")),this.headerMenu&&(this.landmarksSection=Le(this.headerMenu,"#sidenav-section-landmarks")),this.headerMenu&&(this.pageListView=Le(this.headerMenu,"#container-view-pagelist")),i&&(this.linksBottom=Le(i,"ul.links.bottom")),i&&(this.linksMiddle=Le(i,"ul.links.middle")),this.headerMenu&&(this.nextChapterAnchorElement=Le(this.headerMenu,"a[rel=next]")),this.headerMenu&&(this.nextChapterBottomAnchorElement=Le(t,"#next-chapter")),i&&(this.nextPageAnchorElement=Le(i,"a[rel=next]")),this.headerMenu&&(this.previousChapterAnchorElement=Le(this.headerMenu,"a[rel=prev]")),this.headerMenu&&(this.previousChapterTopAnchorElement=Le(t,"#previous-chapter")),i&&(this.previousPageAnchorElement=Le(i,"a[rel=prev]")),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.newPosition=void 0,this.newElementId=void 0,this.isBeingStyled=!0,this.isLoading=!0,this.settings.setIframe(this.iframes[0]),this.settings.onSettingsChange(this.handleResize.bind(this)),this.settings.onColumnSettingsChange(this.handleNumberOfIframes.bind(this)),this.settings.onViewChange(this.updateBookView.bind(this)),this.initialLastReadingPosition&&((c=this.annotator)==null||c.initLastReadingPosition(this.initialLastReadingPosition)),this.headerMenu){var s=Le(this.headerMenu,"#menu-button-search"),l=Le(this.headerMenu,"#menu-button-tts"),f=Le(this.headerMenu,"#menu-button-bookmark"),u=Le(this.headerMenu,"#menu-button-play"),y=Le(this.headerMenu,"#menu-button-pause"),m=Le(this.headerMenu,"#menu-button-mediaoverlay");if(!this.rights.enableBookmarks){f&&((p=f.parentElement)==null||p.style.setProperty("display","none"));var _=Le(this.headerMenu,"#sidenav-section-bookmarks");_&&_.style.setProperty("display","none")}if(!this.rights.enableAnnotations){var v=Le(this.headerMenu,"#sidenav-section-highlights");v&&v.style.setProperty("display","none")}this.rights.enableTTS||l&&((w=l.parentElement)==null||w.style.setProperty("display","none")),this.rights.enableSearch||s&&((A=s.parentElement)==null||A.style.setProperty("display","none")),s&&((E=this.view)!=null&&E.navigator.publication.isFixedLayout)&&((b=s.parentElement)==null||b.style.setProperty("display","none")),this.hasMediaOverlays?(u&&((C=u.parentElement)==null||C.style.removeProperty("display")),y&&((k=y.parentElement)==null||k.style.removeProperty("display")),m&&((R=m.parentElement)==null||R.style.removeProperty("display"))):(u&&((B=u.parentElement)==null||B.style.setProperty("display","none")),y&&((I=y.parentElement)==null||I.style.setProperty("display","none")),m&&((D=m.parentElement)==null||D.style.setProperty("display","none")))}else s&&((F=s.parentElement)==null||F.style.setProperty("display","none")),l&&((z=l.parentElement)==null||z.style.setProperty("display","none")),f&&((q=f.parentElement)==null||q.style.setProperty("display","none"));return this.setupEvents(),await this.loadManifest()}catch(G){return yn.default.error(G),this.abortOnError(G),Promise.reject(G)}}setupEvents(){for(let t of this.iframes)we(t,"load",this.handleIFrameLoad.bind(this,t));we(this.previousChapterAnchorElement,"click",this.handlePreviousChapterClick.bind(this)),we(this.nextChapterAnchorElement,"click",this.handleNextChapterClick.bind(this)),we(this.previousChapterTopAnchorElement,"click",this.handlePreviousPageClick.bind(this)),we(this.nextChapterBottomAnchorElement,"click",this.handleNextPageClick.bind(this)),we(this.previousPageAnchorElement,"click",this.handlePreviousPageClick.bind(this)),we(this.nextPageAnchorElement,"click",this.handleNextPageClick.bind(this)),we(this.tryAgainButton,"click",this.tryAgain.bind(this)),we(this.goBackButton,"click",n.goBack.bind(this)),we(this.espandMenuIcon,"click",this.handleEditClick.bind(this)),we(window,"resize",this.onResize);for(let t of this.iframes)we(t,"resize",this.onResize)}updateBookView(t){var r;((r=this.view)==null?void 0:r.layout)==="fixed"?(this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="none"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.eventHandler&&(this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousChapterClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextChapterClick.bind(this),this.keyboardEventHandler.onKeydown=this.handleKeydownFallthrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this))):(this.settings.isPaginated().then(i=>{var o,s,l,f,u,y;if(i)this.view.height=gi()-40-(((o=this.attributes)==null?void 0:o.margin)??0),this.infoBottom&&this.infoBottom.style.removeProperty("display"),document.body.onscroll=()=>{},this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="unset"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="unset"),this.chapterTitle&&(this.chapterTitle.style.display="inline"),this.chapterPosition&&(this.chapterPosition.style.display="inline"),this.remainingPositions&&(this.remainingPositions.style.display="inline"),this.eventHandler&&(this.eventHandler.onInternalLink=this.handleInternalLink.bind(this),this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this),this.keyboardEventHandler.onKeydown=this.handleKeydownFallthrough.bind(this));else{this.infoBottom&&(this.infoBottom.style.display="none"),this.nextPageAnchorElement&&(this.nextPageAnchorElement.style.display="none"),this.previousPageAnchorElement&&(this.previousPageAnchorElement.style.display="none"),((s=this.view)==null?void 0:s.layout)==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")):(l=this.view)!=null&&l.atStart()&&((f=this.view)!=null&&f.atEnd())?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(u=this.view)!=null&&u.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):(y=this.view)!=null&&y.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"));let m=(0,_h.default)(()=>{this.isScrolling=!1},200),_=yt(document,"#iframe-wrapper");_.onscroll=async()=>{var v,g;this.isScrolling=!0,await this.savePosition(),(v=this.view)!=null&&v.atEnd(),((g=this.view)==null?void 0:g.layout)==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")):(this.settings.isPaginated().then(h=>{var c,p,w,A;h||((c=this.view)!=null&&c.atStart()&&((p=this.view)!=null&&p.atEnd())?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(w=this.view)!=null&&w.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):(A=this.view)!=null&&A.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")))}),this.checkResourcePosition()),m()},this.chapterTitle&&(this.chapterTitle.style.display="none"),this.chapterPosition&&(this.chapterPosition.style.display="none"),this.remainingPositions&&(this.remainingPositions.style.display="none"),this.eventHandler&&(this.eventHandler.onInternalLink=this.handleInternalLink.bind(this),this.eventHandler.onClickThrough=this.handleClickThrough.bind(this)),this.touchEventHandler&&(this.touchEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.touchEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this)),this.keyboardEventHandler&&(this.keyboardEventHandler.onBackwardSwipe=this.handlePreviousPageClick.bind(this),this.keyboardEventHandler.onForwardSwipe=this.handleNextPageClick.bind(this),this.keyboardEventHandler.onKeydown=this.handleKeydownFallthrough.bind(this))}}),t!=null&&t.skipDrawingAnnotations||setTimeout(async()=>{var i;await((i=this.highlighter)==null?void 0:i.prepareContainers(this.iframes[0].contentWindow)),this.highlighter&&(this.rights.enableAnnotations&&this.annotationModule&&await this.annotationModule.drawHighlights(),this.rights.enableBookmarks&&this.bookmarkModule&&await this.bookmarkModule.drawBookmarks(),this.rights.enableSearch&&this.searchModule&&(await this.highlighter.destroyHighlights(1),this.searchModule.drawSearch()),this.rights.enablePageBreaks&&this.pageBreakModule&&(await this.highlighter.destroyHighlights(3),await this.pageBreakModule.drawPageBreaks()),this.rights.enableDefinitions&&this.definitionsModule&&await this.definitionsModule.drawDefinitions())},200))}async loadManifest(){var t,r,i,o,s;try{let l=(g,h,c=!1)=>{var p=document.createElement("ul");c&&(p=document.createElement("ol")),p.className="sidenav-toc";for(let w of h){let A=document.createElement("li"),E=document.createElement("a"),b=document.createElement("span");E.className="chapter-link",E.tabIndex=-1;let C="";w.Href?(C=this.publication.getAbsoluteHref(w.Href),E.href=C,E.innerHTML=w.Title||"",A.appendChild(E)):(b.innerHTML=w.Title||"",b.className="chapter-title",A.appendChild(b)),w.Children&&w.Children.length>0&&l(A,w.Children,!0),p.appendChild(A)}we(p,"click",w=>{if(w.preventDefault(),w.stopPropagation(),w.target&&w.target.tagName.toLowerCase()==="a"){let A=w.target;if(A.className.indexOf("active")!==-1)this.hideView();else{let E={progression:0};if(A.href.indexOf("#")!==-1){let C=A.href.slice(A.href.indexOf("#")+1);C!==void 0&&(E={fragment:C})}let b={href:A.href,locations:E,type:A.type,title:A.title};this.hideView(),this.navigate(b)}}}),g.appendChild(p)},f=this.publication.tableOfContents,u=this.publication.landmarks,y=this.publication.pageList;this.tocView&&(f.length?l(this.tocView,f):(r=(t=this.tocView.parentElement)==null?void 0:t.parentElement)==null||r.removeChild(this.tocView.parentElement)),this.pageListView&&(y!=null&&y.length?l(this.pageListView,y):(o=(i=this.pageListView.parentElement)==null?void 0:i.parentElement)==null||o.removeChild(this.pageListView.parentElement)),this.landmarksView&&(u!=null&&u.length?l(this.landmarksView,u):(s=this.landmarksSection.parentElement)==null||s.removeChild(this.landmarksSection));let m;this.annotator&&(m=await this.annotator.getLastReadingPosition());let _=this.publication.getStartLink(),v;if(_&&_.Href&&(v=this.publication.getAbsoluteHref(_.Href)),m){let g=this.publication.getAbsoluteHref(m.href);yn.default.log(m.href),yn.default.log(g),m.href=g,await this.navigate(m)}else if(v){let g={href:v,locations:{progression:0},created:new Date,title:_==null?void 0:_.Title};await this.navigate(g)}return new Promise(g=>g())}catch(l){return yn.default.error(l),this.abortOnError(l),new Promise((f,u)=>u(l)).catch(()=>{})}}async handleIFrameLoad(t){var r,i,o,s,l,f,u;this.errorMessage&&(this.errorMessage.style.display="none"),this.showLoadingMessageAfterDelay();try{let y=0;this.newPosition&&(y=this.newPosition.locations.progression),await this.handleResize(),this.updateBookView({skipDrawingAnnotations:!0}),await this.settings.applyProperties();let m=this.currentChapterLink.href;if(m){let p=this.publication.getPreviousSpineItem(m);p&&p.Href&&(this.previousChapterLink={href:p.Href,title:p.Title,type:p.TypeLink})}this.previousChapterAnchorElement&&(this.previousChapterLink&&this.previousChapterLink.href?(this.previousChapterAnchorElement.href=this.publication.getAbsoluteHref(this.previousChapterLink.href),this.previousChapterAnchorElement.className=this.previousChapterAnchorElement.className.replace(" disabled","")):(this.previousChapterAnchorElement.removeAttribute("href"),this.previousChapterAnchorElement.className+=" disabled"));let _=this.publication.getNextSpineItem(m);_?this.nextChapterLink={href:_.Href,title:_.Title,type:_.TypeLink}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink&&this.nextChapterLink.href?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.historyModule&&this.historyModule.setup(),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(m),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let v=this.publication.getSpineItem(m);v!==void 0&&(this.currentChapterLink.title=v.Title,this.currentChapterLink.type=v.TypeLink);let g=this.publication.getTOCItem(m);this.currentTocUrl!==void 0&&(g=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&g!==void 0&&g.Title&&(this.currentChapterLink.title=g.Title),!this.currentChapterLink.type&&g!==void 0&&g.TypeLink&&(this.currentChapterLink.title=g.Title),this.currentChapterLink.title?this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"):this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),await this.injectInjectablesIntoIframeHead(t),((r=this.view)==null?void 0:r.layout)!=="fixed"&&this.highlighter!==void 0&&await this.highlighter.initialize(t);let h=(i=t.contentDocument)==null?void 0:i.body,c=h==null?void 0:h.querySelector("details");if(c){let p=this;c.addEventListener("toggle",async w=>{var A,E;await((E=(A=p.view)==null?void 0:A.setIframeHeight)==null?void 0:E.call(A,t))})}if(this.eventHandler&&(this.eventHandler.setupEvents(t.contentDocument),this.touchEventHandler.setupEvents(t.contentDocument),this.keyboardEventHandler.setupEvents(t.contentDocument),this.touchEventHandler.setupEvents(this.errorMessage),this.didInitKeyboardEventHandler||(this.keyboardEventHandler.keydown(document),this.didInitKeyboardEventHandler=!0)),((o=this.view)==null?void 0:o.layout)!=="fixed"&&(s=this.view)!=null&&s.isScrollMode()&&(t.height="0",(f=(l=this.view)==null?void 0:l.setIframeHeight)==null||f.call(l,t)),this.rights.enableContentProtection&&this.contentProtectionModule&&await this.contentProtectionModule.initialize(t),this.rights.enableConsumption&&this.consumptionModule&&await this.consumptionModule.initialize(t),this.rights.enableAnnotations&&this.annotationModule&&await this.annotationModule.initialize(t),this.rights.enableBookmarks&&this.bookmarkModule&&await this.bookmarkModule.initialize(),this.rights.enableLineFocus&&this.lineFocusModule&&await this.lineFocusModule.initialize(t),this.rights.enableTTS&&this.ttsModule){let p=(u=t.contentDocument)==null?void 0:u.body;await this.ttsModule.initialize(p)}return this.rights.enableTimeline&&this.timelineModule&&await this.timelineModule.initialize(),this.rights.enableMediaOverlays&&this.mediaOverlayModule&&this.hasMediaOverlays&&await this.mediaOverlayModule.initialize(),setTimeout(async()=>{var p,w,A,E,b,C,k,R;if(this.newElementId){let B=t.contentDocument.getElementById(this.newElementId);(w=(p=this.view)==null?void 0:p.goToElement)==null||w.call(p,B),this.newElementId=void 0}else if(this.newPosition&&this.newPosition.highlight){let B=(A=this.newPosition.highlight)==null?void 0:A.selectionInfo.rangeInfo.startContainerElementCssSelector;B&&((E=this.view)==null||E.goToCssSelector(B))}else y&&y>=0&&((b=this.view)==null||b.goToProgression(y));if(this.newPosition=void 0,(C=this.rights)!=null&&C.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.recalculate(10),this.hideLoadingMessage(),this.showIframeContents(t),this.rights.enableMediaOverlays&&this.mediaOverlayModule&&this.hasMediaOverlays){let B=this.currentLink();await((k=this.mediaOverlayModule)==null?void 0:k.initializeResource(B))}await this.updatePositionInfo(),await((R=this.view)==null?void 0:R.setSize()),setTimeout(()=>{this.mediaOverlayModule&&(this.mediaOverlayModule.settings.resourceReady=!0)},300)},200),new Promise(p=>p())}catch(y){return yn.default.error(y),this.abortOnError(y),Promise.reject(y)}}async injectInjectablesIntoIframeHead(t){var s,l;let r=[],i=f=>{let u=new Promise((y,m)=>{f.onload=()=>{y(!0)},f.onerror=_=>{let v=typeof _=="string"?_:`Injectable failed to load at: ${"href"in f?f.href:f.src}`;m(new Error(v))}});r.push(u)},o=(s=t.contentDocument)==null?void 0:s.head;o&&(t.contentDocument.getElementsByTagName("base").length===0&&o.insertBefore(n.createBase(this.currentChapterLink.href),o.firstChild),(l=this.injectables)==null||l.forEach(u=>{if(u.type==="style"){if(u.fontFamily){if(this.settings.initAddedFont(),!u.systemFont&&u.url){let y=n.createCssLink(u.url);o.appendChild(y),i(y)}}else if(u.r2before&&u.url){let y=n.createCssLink(u.url);o.insertBefore(y,o.firstChild),i(y)}else if(u.r2default&&u.url){let y=n.createCssLink(u.url);o.insertBefore(y,o.childNodes[1]),i(y)}else if(u.r2after&&u.url){u.appearance&&this.settings.initAddedAppearance();let y=n.createCssLink(u.url);o.appendChild(y),i(y)}else if(u.url){let y=n.createCssLink(u.url);o.appendChild(y),i(y)}}else if(u.type==="script"&&u.url){let y=n.createJavascriptLink(u.url,u.async??!1);o.appendChild(y),i(y)}})),r.length!==0&&await Promise.all(r)}abortOnError(t){var r;if((r=this.api)!=null&&r.onError){let i=t instanceof Error?t:typeof t=="string"?new Error(t):new Error("An unknown error occurred in the IFrameNavigator.");this.api.onError(i)}else this.errorMessage&&(this.errorMessage.style.display="block"),this.isLoading&&this.hideLoadingMessage()}tryAgain(){this.precessContentForIframe()}precessContentForIframe(){var u,y,m,_,v,g;let t=this;var r=this.publication.getSpineIndex(this.currentChapterLink.href),i=(r??0)%2===1;this.showLoadingMessageAfterDelay();function o(h,c){let w=new DOMParser().parseFromString(h,"application/xhtml+xml");w.head&&w.getElementsByTagName("base").length===0&&w.head.insertBefore(n.createBase(c),w.head.firstChild);let A=w.documentElement.outerHTML,E=t.iframes[0].contentDocument;E&&(E.open(),E.write(A),E.close())}function s(h,c){let w=new DOMParser().parseFromString(h,"application/xhtml+xml");w.head&&w.getElementsByTagName("base").length===0&&w.head.insertBefore(n.createBase(c),w.head.firstChild);let A=w.documentElement.outerHTML,E=t.iframes[1].contentDocument;E&&(E.open(),E.write(A),E.close())}let l=new URL(this.currentChapterLink.href),f=window.location.protocol===l.protocol&&window.location.port===l.port&&window.location.hostname===l.hostname;if((u=this.api)!=null&&u.getContent)if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(i){if(this.currentSpreadLinks.left={href:this.currentChapterLink.href},(y=this.api)==null||y.getContent(this.currentChapterLink.href).then(h=>{h===void 0?f?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{o.call(this,c,this.currentChapterLink.href)}):o.call(this,h,this.currentChapterLink.href)}),this.iframes.length===2)if((r??0)<this.publication.readingOrder.length-1){let h=this.publication.getNextSpineItem(this.currentChapterLink.href);if(h){let c=this.publication.getAbsoluteHref(h.Href);this.currentSpreadLinks.right={href:c},(m=this.api)==null||m.getContent(c).then(p=>{p===void 0?f?this.iframes[1].src=c:fetch(c,this.requestConfig).then(w=>w.text()).then(async w=>{s.call(this,w,c),this.currentSpreadLinks.right={href:c}}):s.call(this,p,c)})}}else this.iframes[1].src="about:blank"}else{if((r??0)>0){let h=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(h){let c=this.publication.getAbsoluteHref(h.Href);this.currentSpreadLinks.left={href:c},(_=this.api)==null||_.getContent(c).then(p=>{p===void 0?f?this.iframes[0].src=c:fetch(c,this.requestConfig).then(w=>w.text()).then(async w=>{o.call(this,w,c)}):o.call(this,p,c)})}}else this.iframes[0].src="about:blank";this.iframes.length===2&&this.publication.isFixedLayout&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},this.api.getContent(this.currentChapterLink.href).then(h=>{h===void 0?f?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{s.call(this,c,this.currentChapterLink.href)}):s.call(this,h,this.currentChapterLink.href)}))}else this.currentSpreadLinks.left={href:this.currentChapterLink.href},(v=this.api)==null||v.getContent(this.currentChapterLink.href).then(h=>{h===void 0?f?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{o.call(this,c,this.currentChapterLink.href)}):o.call(this,h,this.currentChapterLink.href)});else(g=this.api)==null||g.getContent(this.currentChapterLink.href).then(h=>{this.currentSpreadLinks.left={href:this.currentChapterLink.href},h===void 0?f?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(c=>c.text()).then(async c=>{o.call(this,c,this.currentChapterLink.href)}):o.call(this,h,this.currentChapterLink.href)});else if(this.publication.isFixedLayout)if(this.settings.columnCount!==1)if(i){if(f){if(this.iframes[0].src=this.currentChapterLink.href,this.currentSpreadLinks.left={href:this.currentChapterLink.href},this.iframes.length===2)if((r??0)<this.publication.readingOrder.length-1){let h=this.publication.getNextSpineItem(this.currentChapterLink.href);if(h){let c=this.publication.getAbsoluteHref(h.Href);this.iframes[1].src=c,this.currentSpreadLinks.right={href:c}}}else this.iframes[1].src="about:blank"}else if(fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)}),this.iframes.length===2)if((r??0)<this.publication.readingOrder.length-1){let h=this.publication.getNextSpineItem(this.currentChapterLink.href);if(h){let c=this.publication.getAbsoluteHref(h.Href);this.currentSpreadLinks.right={href:c},fetch(c,this.requestConfig).then(p=>p.text()).then(async p=>{s.call(this,p,c)})}}else this.iframes[1].src="about:blank"}else if((r??0)>0){let h=this.publication.getPreviousSpineItem(this.currentChapterLink.href);if(h){let c=this.publication.getAbsoluteHref(h.Href);this.currentSpreadLinks.left={href:c},f?(this.iframes[0].src=c,this.iframes.length===2&&(this.iframes[1].src=this.currentChapterLink.href)):(fetch(c,this.requestConfig).then(p=>p.text()).then(async p=>{o.call(this,p,c)}),this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},fetch(this.currentChapterLink.href,this.requestConfig).then(p=>p.text()).then(async p=>{s.call(this,p,this.currentChapterLink.href)})))}}else this.iframes[0].src="about:blank",this.iframes.length===2&&(this.currentSpreadLinks.right={href:this.currentChapterLink.href},f?this.iframes[1].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{s.call(this,h,this.currentChapterLink.href)}));else this.currentSpreadLinks.left={href:this.currentChapterLink.href},f?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)});else this.currentSpreadLinks.left={href:this.currentChapterLink.href},f?this.iframes[0].src=this.currentChapterLink.href:fetch(this.currentChapterLink.href,this.requestConfig).then(h=>h.text()).then(async h=>{o.call(this,h,this.currentChapterLink.href)});this.publication.isFixedLayout&&setTimeout(()=>{var R,B,I;let h,c,p;if(r===0&&((R=this.iframes)==null?void 0:R.length)===2?p=this.iframes[1].contentDocument:p=this.iframes[0].contentDocument,p&&p.body&&(h=getComputedStyle(p.body).height,c=getComputedStyle(p.body).width,parseInt(h.toString().replace("px",""))===0||parseInt(c.toString().replace("px",""))===0)){let D=cr(p,"head");if(D){let F=Le(D,"meta[name=viewport]");if(F){var w=F.content,A=w.split(",").reduce((z,q)=>{var[G,Y]=q.match(/[^\s;=]+/g);return z[G]=isNaN(Number(Y))?Y:+Y,z},{});h=A.height+"px",c=A.width+"px"}}}var E=r===0&&this.iframes.length===2?(B=this.iframes[1].parentElement)==null?void 0:B.parentElement:(I=this.iframes[0].parentElement)==null?void 0:I.parentElement;if(E&&c){var b=(parseInt(getComputedStyle(E).width)-100)/(this.iframes.length===2?parseInt(c.toString().replace("px",""))*2+200:parseInt(c.toString().replace("px",""))),C=(parseInt(getComputedStyle(E).height)-100)/parseInt(h.toString().replace("px","")),k=Math.min(b,C);E.style.transform="scale("+k+")";for(let D of this.iframes)D.style.height=h,D.style.width=c,D.parentElement&&(D.parentElement.style.height=h)}},400)}static goBack(){window.history.back()}handleEditClick(t){var o,s,l,f;var r=t.target;if(this.headerMenu){var i=Le(document,".sidenav");r.className.indexOf(" active")===-1?(r.className+=" active",i.className+=" expanded",r.innerText="unfold_less",this.sideNavExpanded=!0,(o=this.bookmarkModule)==null||o.showBookmarks(),(s=this.annotationModule)==null||s.showHighlights()):(r.className=r.className.replace(" active",""),i.className=i.className.replace(" expanded",""),r.innerText="unfold_more",this.sideNavExpanded=!1,(l=this.bookmarkModule)==null||l.showBookmarks(),(f=this.annotationModule)==null||f.showHighlights())}t.preventDefault(),t.stopPropagation()}get hasMediaOverlays(){return this.publication.hasMediaOverlays}startReadAloud(){this.rights.enableTTS&&this.ttsModule.speakPlay()}startReadAlong(){var t;this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&((t=this.mediaOverlayModule)==null||t.startReadAloud())}stopReadAloud(){var t;this.rights.enableTTS&&((t=this.highlighter)==null||t.stopReadAloud())}stopReadAlong(){var t;this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&((t=this.mediaOverlayModule)==null||t.stopReadAloud())}pauseReadAloud(){this.rights.enableTTS&&(this.ttsModule.speakPause(),this.annotationModule!==void 0&&this.annotationModule.drawHighlights())}pauseReadAlong(){var t;this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&((t=this.mediaOverlayModule)==null||t.pauseReadAloud())}resumeReadAloud(){this.rights.enableTTS&&this.ttsModule.speakResume()}resumeReadAlong(){var t;this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&((t=this.mediaOverlayModule)==null||t.resumeReadAloud())}totalResources(){return this.publication.readingOrder.length}mostRecentNavigatedTocItem(){return this.publication.getRelativeHref(this.currentTOCRawLink)}currentResource(){let t=this.currentChapterLink.href;return this.publication.getSpineIndex(t)}currentLink(){if(this.settings.columnCount!==1&&this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0){let r=this.publication.getSpineItem(this.currentSpreadLinks.left.href),i=this.publication.getSpineItem(this.currentSpreadLinks.right.href);return[r,i]}let t=this.currentChapterLink.href;return[this.publication.getSpineItem(t)]}tableOfContents(){return this.publication.tableOfContents}landmarks(){return this.publication.landmarks}pageList(){return this.publication.pageList}readingOrder(){return this.publication.readingOrder}atStart(){var t;return((t=this.view)==null?void 0:t.atStart())??!1}atEnd(){var t;return((t=this.view)==null?void 0:t.atEnd())??!1}previousPage(){this.handlePreviousPageClick(void 0)}nextPage(){this.handleNextPageClick(void 0)}previousResource(){this.handlePreviousChapterClick(void 0)}nextResource(){this.handleNextChapterClick(void 0)}goTo(t){let r=t.locations??{progression:0};if(t.href.indexOf("#")!==-1){let s=t.href.slice(t.href.indexOf("#")+1);s!==void 0&&(r={...r,fragment:s})}let i={...t};i.locations=r;let o=this.publication.getAbsoluteHref(t.href);yn.default.log(t.href),yn.default.log(o),i.href=o,this.stopReadAloud(),this.navigate(i)}currentLocator(){var r,i,o,s;let t;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let l=this.publication.positionsByHref(this.publication.getRelativeHref(this.currentChapterLink.href)),f=Math.ceil((((r=this.view)==null?void 0:r.getCurrentPosition())??0)*(l.length-1));t=l[f]}else{let l=this.publication.getTOCItem(this.currentChapterLink.href);l&&(this.currentTocUrl!==void 0&&(l=this.publication.getTOCItem(this.currentTocUrl)),l===void 0&&(l=this.publication.getTOCItemAbsolute(this.currentChapterLink.href)),l&&(t={href:l.Href,type:this.currentChapterLink.type,title:this.currentChapterLink.title,locations:{}}))}return t&&(t.locations.progression=(i=this.view)==null?void 0:i.getCurrentPosition(),t.displayInfo={resourceScreenIndex:Math.round(((o=this.view)==null?void 0:o.getCurrentPage())??0),resourceScreenCount:Math.round(((s=this.view)==null?void 0:s.getPageCount())??0)}),t}positions(){return this.publication.positions?this.publication.positions:[]}goToPosition(t){if(this.publication.positions){let r=this.publication.positions.filter(i=>i.locations.position===parseInt(String(t)))[0];this.goTo(r)}}async goToPage(t){this.pageBreakModule!==void 0&&await this.pageBreakModule.goToPageNumber(t)}snapToSelector(t){var i;let r=this.iframes[0].contentDocument;if(r){yn.default.log(t);let o=r.querySelectorAll(t);o.length>0&&((i=this.view)==null||i.snap(o[0]))}}applyAttributes(t){this.attributes=t,this.view.attributes=t,this.handleResize()}handlePreviousPageClick(t){var r,i,o,s;this.stopReadAloud(),((r=this.view)==null?void 0:r.layout)==="fixed"?this.handlePreviousChapterClick(t):((i=this.view)!=null&&i.atStart()?this.handlePreviousChapterClick(t):((s=(o=this.view)==null?void 0:o.goToPreviousPage)==null||s.call(o),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))}handleNextPageClick(t){var i,o,s,l,f,u,y,m,_,v,g,h,c;let r=!0;if((i=this.sample)!=null&&i.isSampleRead&&this.publication.positions){let p=this.currentLocator(),w=Math.round((p.locations.totalProgression??0)*100);(o=this.sample)!=null&&o.limit&&(r=w<=((s=this.sample)==null?void 0:s.limit),((l=this.view)==null?void 0:l.layout)==="fixed"&&((!r&&((f=this.sample)==null?void 0:f.minimum)&&p.locations.position)??0<=(((u=this.sample)==null?void 0:u.minimum)??0))&&(r=!0))}(r&&((y=this.sample)!=null&&y.isSampleRead)&&this.publication.positions||!((m=this.sample)!=null&&m.isSampleRead)||!this.publication.positions)&&(this.stopReadAloud(),((_=this.view)==null?void 0:_.layout)==="fixed"?this.handleNextChapterClick(t):((v=this.view)!=null&&v.atEnd()?this.handleNextChapterClick(t):((h=(g=this.view)==null?void 0:g.goToNextPage)==null||h.call(g),this.updatePositionInfo(),this.savePosition()),t&&(t.preventDefault(),t.stopPropagation()))),!r&&((c=this.sample)!=null&&c.isSampleRead)&&this.publication.positions&&t&&(t.preventDefault(),t.stopPropagation())}handleClickThrough(t){var r,i;(r=this.api)!=null&&r.clickThrough&&((i=this.api)==null||i.clickThrough(t)),this.emit("click",t)}handleInternalLink(t){let r=t.target,i={progression:0},o=r;if(o.href.indexOf("#")!==-1){let l=o.href.slice(o.href.indexOf("#")+1);l!==void 0&&(i={fragment:l})}let s={href:o.href,locations:i,type:o.type,title:o.title};t.preventDefault(),t.stopPropagation(),this.stopReadAloud(),this.navigate(s)}handleNumberOfIframes(){if(this.publication.isFixedLayout){if(this.settings.columnCount!==1&&!window.matchMedia("screen and (max-width: 600px)").matches){if(this.iframes.length===1){var t=document.createElement("iframe");t.setAttribute("SCROLLING","no"),t.setAttribute("allowtransparency","true"),t.style.opacity="1",t.style.border="none",t.style.overflow="hidden",this.iframes.push(t)}let r=document.createElement("div");this.spreads.appendChild(r),r.appendChild(this.iframes[1]),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 100% 120%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc",r.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, 0% 120%)",r.style.boxShadow="0 0 8px 2px #ccc"}else this.iframes.length===2&&(this.iframes.pop(),this.spreads.lastChild&&this.spreads.removeChild(this.spreads.lastChild)),this.firstSpread.style.clipPath="polygon(0% -20%, 100% -20%, 120% 100%, -20% 120%)",this.firstSpread.style.boxShadow="0 0 8px 2px #ccc";this.precessContentForIframe()}}async handleResize(){var y,m,_,v,g,h,c;if(this.isScrolling)return;if(this.publication.isFixedLayout){var t=this.publication.getSpineIndex(this.currentChapterLink.href);let p=gi()-40-(((y=this.attributes)==null?void 0:y.margin)??0);var r=t===0&&this.iframes.length===2?(m=this.iframes[1].parentElement)==null?void 0:m.parentElement:(_=this.iframes[0].parentElement)==null?void 0:_.parentElement;if(r){r.style.height=p+40+"px";let w,A,E;t===0&&((v=this.iframes)==null?void 0:v.length)===2?E=this.iframes[1].contentDocument:E=this.iframes[0].contentDocument,E&&E.body&&(w=getComputedStyle(E.body).height,A=getComputedStyle(E.body).width);let b=cr(E,"head");if(b){let C=Le(b,"meta[name=viewport]");if(C){var i=C.content,o=i.split(",").reduce((k,R)=>{var[B,I]=R.match(/[^\s;=]+/g);return k[B]=isNaN(Number(I))?I:+I,k},{});(parseInt(o.height)!==0||parseInt(o.width)!==0)&&(w=o.height.toString().endsWith("px")?o.height:o.height+"px",A=o.width.toString().endsWith("px")?o.width:o.width+"px")}}var s=(parseInt(getComputedStyle(r).width)-100)/(this.iframes.length===2?parseInt(A.toString().endsWith("px")?A==null?void 0:A.replace("px",""):A)*2+200:parseInt(A.toString().endsWith("px")?A==null?void 0:A.replace("px",""):A)),l=(parseInt(getComputedStyle(r).height)-100)/parseInt(w.toString().replace("px","")),f=Math.min(s,l);r.style.transform="scale("+f+")";for(let C of this.iframes)C.style.height=w,C.style.width=A,C.parentElement&&(C.parentElement.style.height=w)}}let u=(g=this.view)==null?void 0:g.getCurrentPosition();await this.settings.applyProperties(),this.infoTop&&(this.infoTop.style.height="0px"),this.infoTop&&(this.infoTop.style.minHeight="0px"),this.infoBottom&&(this.infoBottom.style.height=(h=this.attributes)!=null&&h.bottomInfoHeight?this.attributes.bottomInfoHeight+"px":"40px"),((c=this.view)==null?void 0:c.layout)!=="fixed"&&this.settings.isPaginated().then(p=>{var w;p?(this.view.height=gi()-40-(((w=this.attributes)==null?void 0:w.margin)??0),this.infoBottom&&this.infoBottom.style.removeProperty("display")):this.infoBottom&&(this.infoBottom.style.display="none")}),setTimeout(()=>{var p,w,A,E;((p=this.view)==null?void 0:p.layout)!=="fixed"&&(w=this.view)!=null&&w.isScrollMode()&&((E=(A=this.view)==null?void 0:A.setIframeHeight)==null||E.call(A,this.iframes[0]))},100),setTimeout(async()=>{var p;u&&((p=this.view)==null||p.goToProgression(u)),this.updatePositionInfo(!1),this.contentProtectionModule!==void 0&&await this.contentProtectionModule.handleResize(),this.annotationModule!==void 0&&await this.annotationModule.handleResize(),this.bookmarkModule!==void 0&&await this.bookmarkModule.handleResize(),this.searchModule!==void 0&&await this.searchModule.handleResize(),this.definitionsModule!==void 0&&await this.definitionsModule.handleResize(),this.pageBreakModule!==void 0&&await this.pageBreakModule.handleResize(),this.lineFocusModule!==void 0&&this.lineFocusModule.handleResize(),this.historyModule!==void 0&&await this.historyModule.handleResize()},150)}updatePositionInfo(t=!0){var r,i;if(((r=this.view)==null?void 0:r.layout)==="fixed")this.chapterPosition&&(this.chapterPosition.innerHTML=""),this.remainingPositions&&(this.remainingPositions.innerHTML="");else if((i=this.view)!=null&&i.isPaginated()){let o=this.currentLocator();if(o){let s=o.displayInfo.resourceScreenIndex,l=o.displayInfo.resourceScreenCount;this.chapterPosition&&(this.chapterPosition.innerHTML="Page "+s+" of "+l)}}else this.chapterPosition&&(this.chapterPosition.innerHTML=""),this.remainingPositions&&(this.remainingPositions.innerHTML="");t&&this.savePosition()}handlePreviousChapterClick(t){var r;if(((r=this.view)==null?void 0:r.layout)==="fixed"&&this.settings.columnCount!==1){let i=this.publication.getSpineIndex(this.currentChapterLink.href)??0;i=i-2,i<0&&(i=0);let o=this.publication.readingOrder[i],s={href:this.publication.getAbsoluteHref(o.Href),locations:{progression:0},type:o.TypeLink,title:o.Title};this.stopReadAloud(),this.navigate(s,!1)}else if(this.previousChapterLink){let i={href:this.publication.getAbsoluteHref(this.previousChapterLink.href),locations:{progression:1},type:this.previousChapterLink.type,title:this.previousChapterLink.title};this.stopReadAloud(),this.navigate(i,!1)}t&&(t.preventDefault(),t.stopPropagation())}handleNextChapterClick(t){var r;if(((r=this.view)==null?void 0:r.layout)==="fixed"&&this.settings.columnCount!==1){let i=this.publication.getSpineIndex(this.currentChapterLink.href)??0;i=i+2,i>=this.publication.readingOrder.length-1&&(i=this.publication.readingOrder.length-1);let o=this.publication.readingOrder[i],s={href:this.publication.getAbsoluteHref(o.Href),locations:{progression:0},type:o.TypeLink,title:o.Title};this.stopReadAloud(),this.navigate(s,!1)}else if(this.nextChapterLink){let i={href:this.publication.getAbsoluteHref(this.nextChapterLink.href),locations:{progression:0},type:this.nextChapterLink.type,title:this.nextChapterLink.title};this.stopReadAloud(),this.navigate(i,!1)}t&&(t.preventDefault(),t.stopPropagation())}handleKeydownFallthrough(t){var r,i;(r=this.api)!=null&&r.keydownFallthrough&&((i=this.api)==null||i.keydownFallthrough(t)),this.emit("keydown",t)}hideView(){var t,r;((t=this.view)==null?void 0:t.layout)!=="fixed"&&(r=this.view)!=null&&r.isScrollMode()&&(document.body.style.overflow="auto")}setActiveTOCItem(t){if(this.tocView){let r=Array.prototype.slice.call(this.tocView.querySelectorAll("li > a"));for(let o of r)o.className=o.className.replace(" active","");let i=this.tocView.querySelector('li > a[href^="'+t+'"]');i&&(i.className+=" active")}}async navigate(t,r=!0){var s,l,f,u,y,m,_,v,g;if(this.rights.enableConsumption&&this.consumptionModule&&r&&this.consumptionModule.startReadingSession(t),this.historyModule&&await this.historyModule.push(t,r),this.publication.getTOCItem(t.href)){var o=!1;if(t.href.indexOf("#")!==-1){let h=t.href.slice(0,t.href.indexOf("#"));h===this.currentChapterLink.href&&(o=!0),this.currentChapterLink.href=h,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title}else t.href===this.currentChapterLink.href&&(o=!0),this.currentChapterLink.href=t.href,this.currentChapterLink.type=t.type,this.currentChapterLink.title=t.title;if(this.currentSpreadLinks.left!==void 0&&this.currentSpreadLinks.right!==void 0&&(t.href===this.currentSpreadLinks.left.href||t.href===this.currentSpreadLinks.right.href))return;if(o){if(t.href.indexOf("#")!==-1){let E=t.href.slice(t.href.indexOf("#")+1);t.locations={fragment:E}}if(this.newPosition=t,this.currentTOCRawLink=t.href,t.locations.fragment===void 0?this.currentTocUrl=void 0:(this.newElementId=t.locations.fragment,this.currentTocUrl=this.currentChapterLink.href+"#"+this.newElementId),this.newElementId){for(let E of this.iframes){let b=E.contentDocument.getElementById(this.newElementId);(l=(s=this.view)==null?void 0:s.goToElement)==null||l.call(s,b)}this.newElementId=void 0}else if(t.highlight){let E=(f=t.highlight)==null?void 0:f.selectionInfo.rangeInfo.startContainerElementCssSelector;E&&((u=this.view)==null||u.goToCssSelector(E))}else(y=this.view)==null||y.goToProgression(t.locations.progression??0);let h=this.currentChapterLink.href,c=this.publication.getPreviousSpineItem(h);c&&c.Href&&(this.previousChapterLink={href:c.Href,type:c.TypeLink,title:c.Title}),this.previousChapterAnchorElement&&(this.previousChapterLink?(this.previousChapterAnchorElement.href=this.publication.getAbsoluteHref(this.previousChapterLink.href),this.previousChapterAnchorElement.className=this.previousChapterAnchorElement.className.replace(" disabled","")):(this.previousChapterAnchorElement.removeAttribute("href"),this.previousChapterAnchorElement.className+=" disabled"));let p=this.publication.getNextSpineItem(h);p?this.nextChapterLink={href:p.Href,type:p.TypeLink,title:p.Title}:this.nextChapterLink=void 0,this.nextChapterAnchorElement&&(this.nextChapterLink?(this.nextChapterAnchorElement.href=this.publication.getAbsoluteHref(this.nextChapterLink.href),this.nextChapterAnchorElement.className=this.nextChapterAnchorElement.className.replace(" disabled","")):(this.nextChapterAnchorElement.removeAttribute("href"),this.nextChapterAnchorElement.className+=" disabled")),this.currentTocUrl!==void 0?this.setActiveTOCItem(this.currentTocUrl):this.setActiveTOCItem(h),this.publication.Metadata.Title&&this.bookTitle&&(this.bookTitle.innerHTML=this.publication.Metadata.Title.toString());let w=this.publication.getSpineItem(h);w!==void 0&&(this.currentChapterLink.title=w.Title,this.currentChapterLink.type=w.TypeLink);let A=this.publication.getTOCItem(h);this.currentTocUrl!==void 0&&(A=this.publication.getTOCItem(this.currentTocUrl)),!this.currentChapterLink.title&&A!==void 0&&A.Title&&(this.currentChapterLink.title=A.Title),!this.currentChapterLink.type&&A!==void 0&&A.TypeLink&&(this.currentChapterLink.title=A.Title),this.currentChapterLink.title?this.chapterTitle&&(this.chapterTitle.innerHTML="("+this.currentChapterLink.title+")"):this.chapterTitle&&(this.chapterTitle.innerHTML="(Current Chapter)"),await this.updatePositionInfo()}else this.lineFocusModule!==void 0&&this.lineFocusModule.disableLineFocus(!1),this.searchModule!==void 0&&this.searchModule.clearSearch(),t.locations.fragment===void 0?this.currentTocUrl=void 0:(this.newElementId=t.locations.fragment,this.currentTocUrl=this.currentChapterLink.href+"#"+this.newElementId),this.hideIframeContents(),this.showLoadingMessageAfterDelay(),t.locations===void 0&&(t.locations={progression:0}),this.newPosition=t,this.currentTOCRawLink=t.href,this.precessContentForIframe(),this.rights.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.initializeResource(),this.rights.enableMediaOverlays&&this.mediaOverlayModule!==void 0&&this.hasMediaOverlays&&await this.mediaOverlayModule.initializeResource(this.currentLink()),this.rights.enableContentProtection&&this.contentProtectionModule!==void 0&&await this.contentProtectionModule.recalculate(300),this.bookmarkModule&&(await this.bookmarkModule.drawBookmarks(),await this.bookmarkModule.showBookmarks()),this.pageBreakModule&&(await((m=this.highlighter)==null?void 0:m.destroyHighlights(3)),await this.pageBreakModule.drawPageBreaks()),this.rights.enableSearch&&this.searchModule!==void 0&&this.highlighter!==void 0&&(await this.highlighter.destroyHighlights(1),this.searchModule.drawSearch()),this.rights.enableDefinitions&&this.definitionsModule&&this.highlighter&&await this.definitionsModule.drawDefinitions(),this.rights.enableConsumption&&this.consumptionModule&&this.consumptionModule.continueReadingSession(t),((_=this.view)==null?void 0:_.layout)==="fixed"?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),(v=this.api)!=null&&v.resourceFitsScreen&&((g=this.api)==null||g.resourceFitsScreen()),this.emit("resource.fits")):this.settings.isPaginated().then(h=>{var c,p,w,A;h||((c=this.view)!=null&&c.atStart()&&((p=this.view)!=null&&p.atEnd())?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(w=this.view)!=null&&w.atEnd()?(this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none"),this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="unset")):(A=this.view)!=null&&A.atStart()?(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="unset")):(this.nextChapterBottomAnchorElement&&(this.nextChapterBottomAnchorElement.style.display="none"),this.previousChapterTopAnchorElement&&(this.previousChapterTopAnchorElement.style.display="none")))})}else{let h=this.publication.getStartLink(),c;if(h&&h.Href&&(c=this.publication.getAbsoluteHref(h.Href),c)){let p={href:c,locations:{progression:0},created:new Date,title:h.Title};await this.navigate(p)}}}showIframeContents(t){this.isBeingStyled=!1,setTimeout(()=>{this.isBeingStyled||(t.style.opacity="1",t.style.border="none",t.style.overflow="hidden")},150)}showLoadingMessageAfterDelay(){this.isLoading=!0,this.isLoading&&this.loadingMessage&&(this.loadingMessage.style.display="block",this.loadingMessage.classList.add("is-loading")),this.mediaOverlayModule!==void 0&&(this.mediaOverlayModule.settings.resourceReady=!1)}hideIframeContents(){this.isBeingStyled=!0,this.iframes.forEach(t=>{t.style.opacity="0",t.style.border="none",t.style.overflow="hidden"})}hideLoadingMessage(){setTimeout(()=>{var t,r,i,o,s,l,f,u,y,m,_,v,g;this.isLoading=!1,this.loadingMessage&&(this.loadingMessage.style.display="none",this.loadingMessage.classList.remove("is-loading")),((t=this.view)==null?void 0:t.layout)!=="fixed"&&((r=this.view)!=null&&r.atStart()&&((i=this.view)!=null&&i.atEnd())?((o=this.api)!=null&&o.resourceFitsScreen&&((s=this.api)==null||s.resourceFitsScreen()),this.emit("resource.fits")):(l=this.view)!=null&&l.atEnd()?((f=this.api)!=null&&f.resourceAtEnd&&((u=this.api)==null||u.resourceAtEnd()),this.emit("resource.end")):(y=this.view)!=null&&y.atStart()&&((m=this.api)!=null&&m.resourceAtStart&&((_=this.api)==null||_.resourceAtStart()),this.emit("resource.start"))),(v=this.api)!=null&&v.resourceReady&&((g=this.api)==null||g.resourceReady()),this.emit("resource.ready")},150)}saveCurrentReadingPosition(){var r,i,o,s,l,f;if(this.annotator){var t=this.publication.getTOCItem(this.currentChapterLink.href);this.currentTocUrl!==void 0&&(t=this.publication.getTOCItem(this.currentTocUrl)),t===void 0&&(t=this.publication.getTOCItemAbsolute(this.currentChapterLink.href));let u={progression:(r=this.view)==null?void 0:r.getCurrentPosition()};if(t){if(t.Href.indexOf("#")!==-1){let m=t.Href.slice(t.Href.indexOf("#")+1);m!==void 0&&(u={progression:(i=this.view)==null?void 0:i.getCurrentPosition(),fragment:m})}let y;if(this.rights.autoGeneratePositions&&this.publication.positions||this.publication.positions){let m=this.publication.positionsByHref(this.publication.getRelativeHref(t.Href));if(m.length>0){let _=Math.ceil((u.progression??0)*(m.length-1)),v=m[_];v&&(v.locations.fragment=u.fragment,y={...v,href:t.Href,created:new Date,title:this.currentChapterLink.title})}}else y={href:t.Href,locations:u,created:new Date,type:this.currentChapterLink.type,title:this.currentChapterLink.title};y&&((o=this.sample)!=null&&o.isSampleRead&&this.publication.positions&&((s=this.sampleReadEventHandler)==null||s.enforceSampleRead(y)),(l=this.api)!=null&&l.updateCurrentLocation?(f=this.api)==null||f.updateCurrentLocation(y).then(async m=>{var _;return yn.default.log("api updated current location",y),(_=this.annotator)==null?void 0:_.saveLastReadingPosition(y)}):(yn.default.log("save last reading position",y),this.annotator.saveLastReadingPosition(y)),this.consumptionModule&&this.consumptionModule.continueReadingSession(y))}}}static createBase(t){let r=document.createElement("base");return r.target="_self",r.href=t,r}static createCssLink(t){let r=document.createElement("link");return r.rel="stylesheet",r.type="text/css",r.href=t,r}static createJavascriptLink(t,r){let i=document.createElement("script");return i.type="text/javascript",i.src=t,i.async=r,i}activateMarker(t,r){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId===void 0||this.annotationModule.activeAnnotationMarkerId!==t?(this.annotationModule.activeAnnotationMarkerId=t,this.annotationModule.activeAnnotationMarkerPosition=r,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=t)):this.deactivateMarker())}deactivateMarker(){this.annotationModule!==void 0&&(this.annotationModule.activeAnnotationMarkerId=void 0,this.annotationModule.activeAnnotationMarkerPosition=void 0,this.highlighter&&(this.highlighter.activeAnnotationMarkerId=void 0))}showLayer(t){var s;let r="#",i=new wa("layer-on","layer-off",!0,t,"layer-"+t);switch(t){case"annotations":case"highlights":r+="R2_ID_HIGHLIGHTS_CONTAINER",i.name="R2_ID_HIGHLIGHTS_CONTAINER";break;case"readaloud":r+="R2_ID_READALOUD_CONTAINER",i.name="R2_ID_READALOUD_CONTAINER";break;case"pagebreak":r+="R2_ID_PAGEBREAK_CONTAINER",i.name="R2_ID_PAGEBREAK_CONTAINER";break;case"search":r+="R2_ID_SEARCH_CONTAINER",i.name="R2_ID_SEARCH_CONTAINER";break;case"definitions":r+="R2_ID_DEFINITIONS_CONTAINER",i.name="R2_ID_DEFINITIONS_CONTAINER";break}(s=this.highlighter)==null||s.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let l=Le(o,r);l&&(l.style.display="block")}}hideLayer(t){var s;let r="#",i=new wa("layer-on","layer-off",!1,t,"layer-"+t);switch(t){case"annotations":case"highlights":r+="R2_ID_HIGHLIGHTS_CONTAINER",i.name="R2_ID_HIGHLIGHTS_CONTAINER";break;case"readaloud":r+="R2_ID_READALOUD_CONTAINER",i.name="R2_ID_READALOUD_CONTAINER";break;case"pagebreak":r+="R2_ID_PAGEBREAK_CONTAINER",i.name="R2_ID_PAGEBREAK_CONTAINER";break;case"search":r+="R2_ID_SEARCH_CONTAINER",i.name="R2_ID_SEARCH_CONTAINER";break;case"definitions":r+="R2_ID_DEFINITIONS_CONTAINER",i.name="R2_ID_DEFINITIONS_CONTAINER";break}(s=this.highlighter)==null||s.layerSettings.saveProperty(i);let o=this.iframes[0].contentDocument;if(o){let l=Le(o,r);l&&(l.style.display="none")}}};L();var St=class St{constructor(e){this.store=e.store}getLastReadingPosition(){let e=this.store.get(St.LAST_READING_POSITION);return e?JSON.parse(e):null}initLastReadingPosition(e){if(typeof e=="string")this.store.set(St.LAST_READING_POSITION,e);else{let t=JSON.stringify(e);this.store.set(St.LAST_READING_POSITION,t)}}saveLastReadingPosition(e){if(typeof e=="string")this.store.set(St.LAST_READING_POSITION,e);else{let t=JSON.stringify(e);this.store.set(St.LAST_READING_POSITION,t)}}initBookmarks(e){if(typeof e=="string"){let t=JSON.parse(e);this.store.set(St.BOOKMARKS,JSON.stringify(t))}else this.store.set(St.BOOKMARKS,JSON.stringify(e));return e}saveBookmark(e){let t=this.store.get(St.BOOKMARKS);if(t){let r=JSON.parse(t);r.push(e),this.store.set(St.BOOKMARKS,JSON.stringify(r))}else{let r=[];r.push(e),this.store.set(St.BOOKMARKS,JSON.stringify(r))}return e}locatorExists(e,t){let r;switch(t){case 0:r=St.BOOKMARKS;break}let i=this.store.get(r);return i&&JSON.parse(i).filter(l=>l.href===e.href&&l.locations.progression===e.locations.progression).length>0?e:null}deleteBookmark(e){let t=this.store.get(St.BOOKMARKS);if(t){let r=JSON.parse(t);r=r.filter(i=>i.id!==e.id),this.store.set(St.BOOKMARKS,JSON.stringify(r))}return e}getBookmarks(e){let t=this.store.get(St.BOOKMARKS);if(t){let r=JSON.parse(t);if(e){let i=r.filter(o=>o.href===e);return i=i.sort((o,s)=>{if(o.locations.progression&&s.locations.progression)return o.locations.progression-s.locations.progression}),i}return r=r.sort((i,o)=>{if(i.locations.progression&&o.locations.progression)return i.locations.progression-o.locations.progression}),r}return[]}initAnnotations(e){let t;typeof e=="string"?t=JSON.parse(e):t=e;let r=[];return t.forEach(i=>{let o=`${i.highlight.selectionInfo.rangeInfo.startContainerElementCssSelector}${i.highlight.selectionInfo.rangeInfo.startContainerChildTextNodeIndex}${i.highlight.selectionInfo.rangeInfo.startOffset}${i.highlight.selectionInfo.rangeInfo.endContainerElementCssSelector}${i.highlight.selectionInfo.rangeInfo.endContainerChildTextNodeIndex}${i.highlight.selectionInfo.rangeInfo.endOffset}`,s=Ui.hash(o);i.highlight.id="R2_HIGHLIGHT_"+s;let l;i.highlight.color?l=i.highlight.color:i.color&&(l=i.color),Jt.isHexColor(l)&&(l=Jt.hexToRgbString(l)),i.highlight.color=l,i.highlight.pointerInteraction=!0,i.highlight.selectionInfo.cleanText=i.highlight.selectionInfo.rawText.trim().replace(/\n/g," ").replace(/\s\s+/g," "),r.push(i)}),this.store.set(St.ANNOTATIONS,JSON.stringify(r)),r}saveTemporarySelectionInfo(e){this.store.set(St.SELECTIONINFO,JSON.stringify(e))}getTemporarySelectionInfo(e){let t=this.store.get(St.SELECTIONINFO);if(t){let r=JSON.parse(t);return r.range=Rf(e,r.rangeInfo),r}return[]}deleteTemporarySelectionInfo(){this.store.remove(St.SELECTIONINFO)}saveAnnotation(e){let t=this.store.get(St.ANNOTATIONS);if(t){let r=JSON.parse(t);r.push(e),this.store.set(St.ANNOTATIONS,JSON.stringify(r))}else{let r=[];r.push(e),this.store.set(St.ANNOTATIONS,JSON.stringify(r))}return e}deleteAnnotation(e){let t=this.store.get(St.ANNOTATIONS);if(t){let r=JSON.parse(t);r=r.filter(i=>i.id!==e),this.store.set(St.ANNOTATIONS,JSON.stringify(r))}return e}deleteSelectedAnnotation(e){let t=this.store.get(St.ANNOTATIONS);if(t){let r=JSON.parse(t);r=r.filter(i=>{var o;return((o=i.highlight)==null?void 0:o.id)!==e.highlight.id}),this.store.set(St.ANNOTATIONS,JSON.stringify(r))}return e}getAnnotations(){let e=this.store.get(St.ANNOTATIONS);if(e){let t=JSON.parse(e);return t=t.sort((r,i)=>{if(r.locations.progression&&i.locations.progression)return r.locations.progression-i.locations.progression}),t}return[]}getAnnotationsByChapter(e){let t=this.store.get(St.ANNOTATIONS);if(t){let r=JSON.parse(t);return r=r.filter(i=>i.href===e),r=r.sort((i,o)=>{if(i.locations.progression&&o.locations.progression)return i.locations.progression-o.locations.progression}),r}return[]}getAnnotationPosition(e,t){let r=this.store.get(St.ANNOTATIONS);if(r){let o=JSON.parse(r).filter(s=>{var l;return((l=s.highlight)==null?void 0:l.id)===e||s.id===e});if(o.length>0){let s=t.document.getElementById(`${o[0].highlight.id}`);if(s){let l=0;if(s.hasChildNodes)for(let f=0;f<s.childNodes.length;f++){let u=s.childNodes[f],y=parseInt(u.style.top.replace("px",""));(y<l||l===0)&&(l=y)}else l=parseInt(s.style.top.replace("px",""));return l}}}return null}getAnnotationElement(e,t){let r=this.store.get(St.ANNOTATIONS);if(r){let o=JSON.parse(r).filter(s=>{var l;return((l=s.highlight)==null?void 0:l.id)===e});if(o.length>0){let s=t.document.getElementById(`${o[0].highlight.id}`);if(s){let l=0;if(s.hasChildNodes)for(let f=0;f<s.childNodes.length;f++){let u=s.childNodes[f],y=parseInt(u.style.top.replace("px",""));if(y<l||l===0)return l=y,u}else l=parseInt(s.style.top.replace("px",""));return s}}}return null}getAnnotation(e){let t=this.store.get(St.ANNOTATIONS);if(t){let i=JSON.parse(t).filter(o=>{var s;return((s=o.highlight)==null?void 0:s.id)===e.id});if(i.length>0)return i[0]}return null}getAnnotationByID(e){let t=this.store.get(St.ANNOTATIONS);if(t){let i=JSON.parse(t).filter(o=>{var s;return((s=o.highlight)==null?void 0:s.id)===e});if(i.length>0)return i[0]}return null}};St.LAST_READING_POSITION="last-reading-position",St.BOOKMARKS="bookmarks",St.ANNOTATIONS="annotations",St.SELECTIONINFO="selectionInfo";var zl=St;L();L();var uu=class{constructor(){this.store={}}get(e){return this.store[e]||null}set(e,t){this.store[e]=t}remove(e){this.store[e]=null}};var qs=class{constructor(e){this.prefix=e.prefix,this.useLocalStorage=e.useLocalStorage,this.useStorageType=e.useStorageType;try{let t=e.prefix+"-"+String(Math.random());this.useStorageType==="memory"?this.fallbackStore=new uu:this.useStorageType==="local"||this.useLocalStorage?(window.localStorage.setItem(t,"test"),window.localStorage.removeItem(t),this.fallbackStore=null):(this.useStorageType==="session"||!this.useLocalStorage)&&(window.sessionStorage.setItem(t,"test"),window.sessionStorage.removeItem(t),this.fallbackStore=null)}catch{this.fallbackStore=new uu}}getLocalStorageKey(e){return this.prefix+"-"+e}get(e){let t;return this.fallbackStore?t=this.fallbackStore.get(e):this.useStorageType==="local"||this.useLocalStorage?t=window.localStorage.getItem(this.getLocalStorageKey(e)):t=window.sessionStorage.getItem(this.getLocalStorageKey(e)),t}set(e,t){this.fallbackStore?this.fallbackStore.set(e,t):this.useStorageType==="local"||this.useLocalStorage?window.localStorage.setItem(this.getLocalStorageKey(e),t):window.sessionStorage.setItem(this.getLocalStorageKey(e),t)}remove(e){this.fallbackStore?this.fallbackStore.remove(e):this.useStorageType==="local"||this.useLocalStorage?window.localStorage.removeItem(this.getLocalStorageKey(e)):window.sessionStorage.removeItem(this.getLocalStorageKey(e))}};L();var kE=rt(Nu()),RE=rt(Or());var lu=class extends kE.Link{};lu=Nc([(0,RE.JsonObject)()],lu);function Gs(n){let e,t,r,i;if(n instanceof Array)return n.map(function(o){return typeof o=="object"&&(o=Gs(o)),o});e={};for(t in n)n.hasOwnProperty(t)&&(r=(t.charAt(0).toLowerCase()+t.slice(1)||t).toString(),i=n[t],(i instanceof Array||i!=null&&i.constructor===Object)&&(i=Gs(i)),r==="href1"?e.href=i:r==="typeLink"?e.type=i:e[r]=i);return e}L();var LE=rt($t()),wh=class{constructor(e){this.LAYERSETTINGS="layerSetting";this.store=e,this.initialize()}static async create(e){let t=new this(e.store);return new Promise(r=>r(t))}async stop(){LE.default.log("MediaOverlay settings stop")}async initialize(){this.userProperties=await this.getLayerSettings()}async getLayerSettings(){let e=new Li,t=await this.store.get(this.LAYERSETTINGS);if(t){let r=JSON.parse(t);e.properties=r}return e}async saveProperty(e){let t=await this.store.get(this.LAYERSETTINGS);if(t){let r=JSON.parse(t);r=r.filter(i=>i.name!==e.name),r.push(e),await this.store.set(this.LAYERSETTINGS,JSON.stringify(r))}else{let r=[];r.push(e),await this.store.set(this.LAYERSETTINGS,JSON.stringify(r))}return new Promise(r=>r(e))}async getProperty(e){let t=await this.store.get(this.LAYERSETTINGS);if(t){let r=JSON.parse(t);return r=r.filter(i=>i.name===e),r.length===0?null:r[0]}return null}};L();var cu=rt(FE());L();var HE="grab-to-pan-grab",Ah,UE,Eh,jE,Ch,qE,Sh=class{constructor(e){Tr(this,Ah);Tr(this,Eh);Tr(this,Ch);this.element=e.element,this.document=e.element.ownerDocument,typeof e.ignoreTarget=="function"&&(this.ignoreTarget=e.ignoreTarget),this.onActiveChanged=e.onActiveChanged,this.activate=this.activate.bind(this),this.deactivate=this.deactivate.bind(this),this.toggle=this.toggle.bind(this),this._onMouseDown=ro(this,Ah,UE).bind(this),this._onMouseMove=ro(this,Eh,jE).bind(this),this._endPan=ro(this,Ch,qE).bind(this);let t=this.overlay=document.createElement("div");t.className="grab-to-pan-grabbing"}activate(){var e;this.active||(this.active=!0,this.element.addEventListener("mousedown",this._onMouseDown,!0),this.element.classList.add(HE),(e=this.onActiveChanged)==null||e.call(this,!0))}deactivate(){var e;this.active&&(this.active=!1,this.element.removeEventListener("mousedown",this._onMouseDown,!0),this._endPan(),this.element.classList.remove(HE),(e=this.onActiveChanged)==null||e.call(this,!1))}toggle(){this.active?this.deactivate():this.activate()}ignoreTarget(e){return e.matches("a[href], a[href] *, input, textarea, button, button *, select, option")}};Ah=new WeakSet,UE=function(e){if(e.button!==0||this.ignoreTarget(e.target))return;if(e.originalTarget)try{e.originalTarget.tagName}catch{return}this.scrollLeftStart=this.element.scrollLeft,this.scrollTopStart=this.element.scrollTop,this.clientXStart=e.clientX,this.clientYStart=e.clientY,this.document.addEventListener("mousemove",this._onMouseMove,!0),this.document.addEventListener("mouseup",this._endPan,!0),this.element.addEventListener("scroll",this._endPan,!0),e.preventDefault(),e.stopPropagation();let t=document.activeElement;t&&!t.contains(e.target)&&t.blur()},Eh=new WeakSet,jE=function(e){if(this.element.removeEventListener("scroll",this._endPan,!0),!(e.buttons&1)){this._endPan();return}let t=e.clientX-this.clientXStart,r=e.clientY-this.clientYStart,i=this.scrollTopStart-r,o=this.scrollLeftStart-t;this.element.scrollTo?this.element.scrollTo({top:i,left:o,behavior:"instant"}):(this.element.scrollTop=i,this.element.scrollLeft=o),this.overlay.parentNode||document.body.append(this.overlay)},Ch=new WeakSet,qE=function(){this.element.removeEventListener("scroll",this._endPan,!0),this.document.removeEventListener("mousemove",this._onMouseMove,!0),this.document.removeEventListener("mouseup",this._endPan,!0),this.overlay.remove()};var vi=class extends bh{constructor(t,r,i){super();this.pdfDoc=null;this.pageNum=1;this.scaleType=0;this.pageRendering=!1;this.pageNumPending=null;this.scale=1;this.resourceIndex=0;this.onResize=()=>{clearTimeout(this.timeout),this.timeout=setTimeout(this.handleResize.bind(this),200)};this.settings=t,this.publication=r,this.api=i}static async create(t){let r=new this(t.settings,t.publication,t.api);return await r.start(t.mainElement,t.headerMenu,t.footerMenu),new Promise(i=>i(r))}async start(t,r,i){this.headerMenu=r,this.footerMenu=i,this.mainElement=t,this.resourceIndex=0,this.resource=this.publication.readingOrder[this.resourceIndex],cu.GlobalWorkerOptions.workerSrc="//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.14.305/pdf.worker.js",this.wrapper=yt(this.mainElement,"main#iframe-wrapper"),this.pdfContainer=yt(this.mainElement,"#pdf-container"),this.handTool=new Sh({element:this.pdfContainer});let o=this,s=document.createElement("div");s.id="loadingpdf",s.innerHTML=mh,s.style.width=getComputedStyle(this.wrapper).width,s.style.height=getComputedStyle(this.wrapper).height,s.style.display="flex",s.style.zIndex="100",s.style.position="absolute",s.style.alignItems="center",s.style.justifyContent="center",s.style.background="white",s.className="loading is-loading",this.pdfContainer.appendChild(s),(0,cu.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(l){o.pdfDoc=l,o.loadPDFJS(o.pageNum)}),this.setupEvents()}async handleResize(){this.loadPDFJS(this.pageNum)}setupEvents(){we(window,"resize",this.onResize)}loadPDFJS(t){let r=this,i=1;this.wrapper.style.height="calc(100vh - 10px)",this.pdfContainer.style.height="calc(100vh - 10px)",this.pdfContainer.style.flexDirection="column";let o=document.getElementsByTagName("canvas");Array.from(o).forEach(function(l){var f;(f=l==null?void 0:l.parentNode)==null||f.removeChild(l)});function s(l){let f=document.createElement("canvas");f.id=String(i),f.style.border="1px solid gray",f.style.margin="1px";let u=l.getViewport({scale:r.scale});if(r.scale===1){let g=r.wrapper.clientHeight/u.height,h=r.wrapper.clientWidth/u.width;r.scaleType===0?u=l.getViewport({scale:g<h?g:h}):u=l.getViewport({scale:h})}r.pdfContainer.appendChild(f);let y=f.getContext("2d");f.height=u.height,f.width=u.width;let m={canvasContext:y,viewport:u},_=document.getElementById("loadingpdf");_.style.display="flex",_.style.width=getComputedStyle(r.wrapper).width,_.style.height=getComputedStyle(r.wrapper).height,l.render(m).promise.then(function(){var g,h,c;i<r.pdfDoc.numPages?(i++,r.pdfDoc.getPage(i).then(s)):((g=document.getElementById(String(t)))==null||g.scrollIntoView(),_.style.display="none",(h=r.api)!=null&&h.resourceReady&&((c=r.api)==null||c.resourceReady()),r.emit("resource.ready"))})}this.pdfDoc.getPage(i).then(s)}queueRenderPage(t){var i;let r=this;r.pageRendering?r.pageNumPending=t:(this.pageNum=t,(i=document.getElementById(String(t)))==null||i.scrollIntoView())}readingOrder(){return this.publication.readingOrder}tableOfContents(){return this.publication.tableOfContents}landmarks(){}pageList(){}currentResource(){}totalResources(){return this.publication.readingOrder.length}currentLocator(){}positions(){return this.publication.positions?this.publication.positions:[]}nextPage(){let t=this;if(t.pageNum>=t.pdfDoc.numPages){this.nextResource();return}this.pageNum++,this.queueRenderPage(t.pageNum)}previousPage(){let t=this;if(t.pageNum<=1){this.previousResource();return}t.pageNum--,t.queueRenderPage(t.pageNum)}nextResource(){let t=this;this.resourceIndex>=this.publication.readingOrder.length-1||(t.resourceIndex++,t.resource=this.publication.readingOrder[t.resourceIndex],(0,cu.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(r){t.pdfDoc=r,t.pageNum=1,t.loadPDFJS(t.pageNum)}))}previousResource(){let t=this;this.resourceIndex!==0&&(t.resourceIndex--,t.resource=this.publication.readingOrder[t.resourceIndex],(0,cu.getDocument)(this.publication.getAbsoluteHref(this.resource.Href)).promise.then(function(r){t.pdfDoc=r,t.pageNum=t.pdfDoc.numPages,t.loadPDFJS(t.pageNum)}))}goTo(t){let r=new URL(t.href);if(r.searchParams.has("start")){let i=r.searchParams.get("start");i&&this.queueRenderPage(parseInt(i))}else this.queueRenderPage(1)}goToPosition(t){this.queueRenderPage(t)}async goToPage(t){this.queueRenderPage(t)}fitToWidth(){this.scale=1,this.scaleType=1,this.loadPDFJS(this.pageNum)}fitToPage(){this.scale=1,this.scaleType=0,this.loadPDFJS(this.pageNum)}zoomIn(){this.scale=this.scale+.2,this.loadPDFJS(this.pageNum)}zoomOut(){this.scale=this.scale-.2,this.loadPDFJS(this.pageNum)}activateHand(){this.handTool.activate()}deactivateHand(){this.handTool.deactivate()}async scroll(t,r){t?(r==="horizontal"?this.pdfContainer.style.flexDirection="row":this.pdfContainer.style.flexDirection="column",this.pdfContainer.style.overflow="auto"):(this.pdfContainer.style.flexDirection="column",this.pdfContainer.style.overflow="hidden")}stop(){Ue(window,"resize",this.onResize)}};var du=class n{constructor(e,t,r,i,o,s,l,f,u,y,m,_,v,g,h,c,p,w){this.settings=e;this.navigator=t;this.highlighter=r;this.bookmarkModule=i;this.annotationModule=o;this.ttsSettings=s;this.ttsModule=l;this.searchModule=f;this.definitionsModule=u;this.contentProtectionModule=y;this.timelineModule=m;this.mediaOverlaySettings=_;this.mediaOverlayModule=v;this.pageBreakModule=g;this.lineFocusModule=h;this.historyModule=c;this.citationModule=p;this.consumptionModule=w;this.startReadAloud=()=>{this.navigator instanceof Tt&&this.navigator.startReadAloud()};this.stopReadAloud=()=>{this.navigator instanceof Tt&&this.navigator.stopReadAloud()};this.pauseReadAloud=()=>{this.navigator instanceof Tt&&this.navigator.pauseReadAloud()};this.resumeReadAloud=()=>{this.navigator instanceof Tt&&this.navigator.resumeReadAloud()};this.startReadAlong=()=>{this.navigator instanceof Tt&&this.navigator.startReadAlong()};this.stopReadAlong=()=>{this.navigator instanceof Tt&&this.navigator.stopReadAlong()};this.pauseReadAlong=()=>{this.navigator instanceof Tt&&this.navigator.pauseReadAlong()};this.resumeReadAlong=()=>{this.navigator instanceof Tt&&this.navigator.resumeReadAlong()};this.saveBookmark=async()=>{var e;return await((e=this.bookmarkModule)==null?void 0:e.saveBookmark())??!1};this.saveBookmarkPlus=async()=>{var e;return(e=this.bookmarkModule)==null?void 0:e.saveBookmarkPlus()};this.deleteBookmark=async e=>{var t;return await((t=this.bookmarkModule)==null?void 0:t.deleteBookmark(e))??!1};this.deleteAnnotation=async e=>{var t;return await((t=this.annotationModule)==null?void 0:t.deleteAnnotation(e))??!1};this.addAnnotation=async e=>{var t;return await((t=this.annotationModule)==null?void 0:t.addAnnotation(e))??!1};this.hideAnnotationLayer=()=>{var e;return(e=this.annotationModule)==null?void 0:e.hideAnnotationLayer()};this.showAnnotationLayer=()=>{var e;return(e=this.annotationModule)==null?void 0:e.showAnnotationLayer()};this.hideLayer=e=>{var t;return this.navigator instanceof Tt?(t=this.navigator)==null?void 0:t.hideLayer(e):!1};this.showLayer=e=>{var t;return this.navigator instanceof Tt?(t=this.navigator)==null?void 0:t.showLayer(e):!1};this.activateMarker=(e,t)=>{var r;return this.navigator instanceof Tt?(r=this.navigator)==null?void 0:r.activateMarker(e,t):!1};this.deactivateMarker=()=>{var e;return this.navigator instanceof Tt?(e=this.navigator)==null?void 0:e.deactivateMarker():!1};this.clearDefinitions=async()=>{var e;await((e=this.definitionsModule)==null?void 0:e.clearDefinitions())};this.addDefinition=async e=>{var t;await((t=this.definitionsModule)==null?void 0:t.addDefinition(e))};this.historyBack=async()=>{var e;return(e=this.historyModule)==null?void 0:e.historyBack()};this.historyForward=async()=>{var e;return(e=this.historyModule)==null?void 0:e.historyForward()};this.search=async(e,t)=>{var r;return await((r=this.searchModule)==null?void 0:r.search(e,t))??[]};this.goToSearchIndex=async(e,t,r)=>{var i;this.navigator instanceof Tt&&this.navigator.rights.enableSearch&&await((i=this.searchModule)==null?void 0:i.goToSearchIndex(e,t,r))};this.goToSearchID=async(e,t,r)=>{var i;this.navigator instanceof Tt&&this.navigator.rights.enableSearch&&await((i=this.searchModule)==null?void 0:i.goToSearchID(e,t,r))};this.clearSearch=async()=>{var e;this.navigator instanceof Tt&&this.navigator.rights.enableSearch&&await((e=this.searchModule)==null?void 0:e.clearSearch())};this.resetUserSettings=async()=>await this.settings.resetUserSettings();this.applyUserSettings=async e=>await this.settings.applyUserSettings(e);this.scroll=async(e,t)=>this.navigator instanceof vi?this.navigator.scroll(e,t):await this.settings.scroll(e);this.increase=async e=>{var t,r;this.isTTSIncrementable(e)?this.navigator instanceof Tt&&this.navigator.rights.enableTTS&&await((t=this.ttsSettings)==null?void 0:t.increase(e)):this.isMOIncrementable(e)?this.navigator instanceof Tt&&this.navigator.rights.enableMediaOverlays&&await((r=this.mediaOverlaySettings)==null?void 0:r.increase(e)):await this.settings.increase(e)};this.decrease=async e=>{var t,r;this.isTTSIncrementable(e)?this.navigator instanceof Tt&&this.navigator.rights.enableTTS&&await((t=this.ttsSettings)==null?void 0:t.decrease(e)):this.isMOIncrementable(e)?this.navigator instanceof Tt&&this.navigator.rights.enableMediaOverlays&&await((r=this.mediaOverlaySettings)==null?void 0:r.decrease(e)):await this.settings.decrease(e)};this.resetTTSSettings=()=>{var e;this.navigator instanceof Tt&&this.navigator.rights.enableTTS&&((e=this.ttsSettings)==null||e.resetTTSSettings())};this.applyTTSSettings=async e=>{var t;this.navigator instanceof Tt&&this.navigator.rights.enableTTS&&await((t=this.ttsSettings)==null?void 0:t.applyTTSSettings(e))};this.applyPreferredVoice=async e=>{var t;this.navigator instanceof Tt&&this.navigator.rights.enableTTS&&await((t=this.ttsSettings)==null?void 0:t.applyPreferredVoice(e))};this.resetMediaOverlaySettings=async()=>{var e;this.navigator instanceof Tt&&this.navigator.rights.enableMediaOverlays&&await((e=this.mediaOverlaySettings)==null?void 0:e.resetMediaOverlaySettings())};this.applyMediaOverlaySettings=async e=>{var t;this.navigator instanceof Tt&&this.navigator.rights.enableMediaOverlays&&await((t=this.mediaOverlaySettings)==null?void 0:t.applyMediaOverlaySettings(e))};this.goTo=async e=>{this.navigator.goTo(e)};this.goToPosition=async e=>this.navigator.goToPosition(e);this.goToPage=async e=>{await this.navigator.goToPage(e)};this.fitToPage=()=>{this.navigator instanceof vi&&this.navigator.fitToPage()};this.fitToWidth=()=>{this.navigator instanceof vi&&this.navigator.fitToWidth()};this.zoomIn=()=>{this.navigator instanceof vi&&this.navigator.zoomIn()};this.zoomOut=()=>{this.navigator instanceof vi&&this.navigator.zoomOut()};this.activateHand=()=>{this.navigator instanceof vi&&this.navigator.activateHand()};this.deactivateHand=()=>{this.navigator instanceof vi&&this.navigator.deactivateHand()};this.copyToClipboard=e=>{var t;(t=this.contentProtectionModule)==null||t.copyToClipboard(e)};this.nextResource=()=>{this.navigator.nextResource()};this.previousResource=()=>{this.navigator.previousResource()};this.nextPage=async()=>{this.navigator.nextPage()};this.previousPage=async()=>{this.navigator.previousPage()};this.snapToSelector=async e=>{this.navigator instanceof Tt&&this.navigator.snapToSelector(e)};this.applyAttributes=e=>{this.navigator instanceof Tt&&this.navigator.applyAttributes(e)};this.stop=()=>{var e,t,r,i,o,s,l,f,u,y,m,_,v,g;document.body.onscroll=()=>{},this.navigator.stop(),this.settings.stop(),(e=this.ttsSettings)==null||e.stop(),(t=this.ttsModule)==null||t.stop(),(r=this.bookmarkModule)==null||r.stop(),(i=this.annotationModule)==null||i.stop(),(o=this.searchModule)==null||o.stop(),(s=this.definitionsModule)==null||s.stop(),(l=this.contentProtectionModule)==null||l.stop(),(f=this.timelineModule)==null||f.stop(),(u=this.mediaOverlaySettings)==null||u.stop(),(y=this.mediaOverlayModule)==null||y.stop(),(m=this.pageBreakModule)==null||m.stop(),(_=this.lineFocusModule)==null||_.stop(),(v=this.citationModule)==null||v.stop(),(g=this.consumptionModule)==null||g.stop()}}addEventListener(){this.navigator instanceof Tt&&this.navigator.addListener(arguments[0],arguments[1])}static async load(e){var _,v,g,h,c,p,w;let t=e.rights??{autoGeneratePositions:!1,enableAnnotations:!1,enableBookmarks:!1,enableContentProtection:!1,enableDefinitions:!1,enableLineFocus:!1,enableMediaOverlays:!1,enablePageBreaks:!1,enableSearch:!1,enableTTS:!1,enableTimeline:!1,customKeyboardEvents:!1,enableHistory:!1,enableCitations:!1};t.enableContentProtection&&e.protection&&await Bs.setupPreloadProtection(e.protection);let r=yt(document,"#D2Reader-Container"),i=Le(document,"#headerMenu"),o=Le(document,"#footerMenu"),s=e.url,l;e.publication?(l=_a(e.publication,lo),l.manifestUrl=new URL(s)):l=await lo.fromUrl(s,e.requestConfig);let f=new qs({prefix:l.manifestUrl,useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),u=new qs({prefix:"r2d2bc-reader",useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),y=new qs({prefix:"r2d2bc-layers",useLocalStorage:e.useLocalStorage??!1,useStorageType:e.useStorageType}),m=new zl({store:f});if(l.sample=e.sample,t=zU(t,l),l.Metadata.ConformsTo&&l.Metadata.ConformsTo.includes("https://readium.org/webpub-manifest/profiles/pdf")){let A=await Al.create({store:u,initialUserSettings:e.userSettings,layout:""}),E=await vi.create({mainElement:r,publication:l,settings:A,api:e.api});return new n(A,E)}else{t.autoGeneratePositions?await l.autoGeneratePositions(e.requestConfig):((_=e.services)!=null&&_.positions&&await l.fetchPositionsFromService((v=e.services)==null?void 0:v.positions.href,e.requestConfig),(g=e.services)!=null&&g.weight&&await l.fetchWeightsFromService((h=e.services)==null?void 0:h.weight.href,e.requestConfig));let A=await wh.create({store:y}),E=await Al.create({store:u,initialUserSettings:e.userSettings,headerMenu:i,api:e.api,injectables:(((c=l.Metadata.Rendition)==null?void 0:c.Layout)??"unknown")==="fixed"?e.injectablesFixed:e.injectables,layout:(((p=l.Metadata.Rendition)==null?void 0:p.Layout)??"unknown")==="fixed"?"fixed":"reflowable"}),b=await Jt.create({layerSettings:A,...e.highlighter}),C=t.enableBookmarks?await Ga.create({annotator:m,headerMenu:i,rights:t,publication:l,initialAnnotations:e.initialAnnotations,...e.bookmarks}):void 0,k=t.enableAnnotations?await qa.create({annotator:m,rights:t,publication:l,initialAnnotations:e.initialAnnotations,highlighter:b,headerMenu:i,...e.annotations}):void 0,R=t.enableTTS,B=R?await gh.create({store:u,initialTTSSettings:e.tts,headerMenu:i}):void 0,I;R&&B&&(I=await Hs.create({tts:B,headerMenu:i,rights:t,highlighter:b,...e.tts}));let D=t.enableSearch?await iu.create({headerMenu:i,publication:l,highlighter:b,...e.search}):void 0,F=t.enableDefinitions?await su.create({publication:l,highlighter:b,...e.define}):void 0,z=t.enableTimeline?await za.create({publication:l}):void 0,q=t.enableContentProtection?await Bs.create({...e.protection}):void 0,G=t.enableCitations?await js.create({publication:l,highlighter:b,...e.citations}):void 0,Y=t.enableMediaOverlays,X=Y?await Nf.create({store:u,initialMediaOverlaySettings:e.mediaOverlays,headerMenu:i,...e.mediaOverlays}):void 0,Q=Y?await Wa.create({publication:l,settings:X,...e.mediaOverlays}):void 0,ve=t.enablePageBreaks&&l.isReflowable?await ou.create({publication:l,headerMenu:i,...e.pagebreak}):void 0,ce=t.enableLineFocus?await Us.create({publication:l,highlighter:b,...e.lineFocus}):void 0,W=t.enableHistory?await au.create({annotator:m,publication:l,headerMenu:i}):void 0,H=t.enableConsumption?await ja.create({publication:l,...e.consumption}):void 0,M=await Tt.create({mainElement:r,headerMenu:i,footerMenu:o,publication:l,settings:E,annotator:m,initialLastReadingPosition:e.lastReadingPosition,api:e.api,rights:t,tts:e.tts,sample:e.sample,requestConfig:e.requestConfig,injectables:(((w=l.Metadata.Rendition)==null?void 0:w.Layout)??"unknown")==="fixed"?e.injectablesFixed??[]:e.injectables,attributes:e.attributes,services:e.services,highlighter:b,modules:[C,k,I,D,F,z,q,G,Q,ve,ce,W,H]});return new n(E,M,b,C,k,B,I,D,F,q,z,X,Q,ve,ce,W,G,H)}}get hasMediaOverlays(){return this.navigator instanceof Tt?this.navigator.hasMediaOverlays:!1}get tableOfContents(){return Gs(this.navigator.tableOfContents())??[]}get landmarks(){return Gs(this.navigator.landmarks())??[]}get pageList(){return Gs(this.navigator.pageList())??[]}get readingOrder(){return Gs(this.navigator.readingOrder())??[]}get bookmarks(){var e;return((e=this.bookmarkModule)==null?void 0:e.getBookmarks())??[]}get annotations(){var e;return(e=this.annotationModule)==null?void 0:e.getAnnotations()}get publicationLayout(){return this.navigator.publication.layout}get history(){var e;return(e=this.historyModule)==null?void 0:e.history}get historyCurrentIndex(){var e;return(e=this.historyModule)==null?void 0:e.historyCurrentIndex}get currentResource(){return this.navigator.currentResource()}get mostRecentNavigatedTocItem(){return this.navigator instanceof Tt?this.navigator.mostRecentNavigatedTocItem():!1}get totalResources(){return this.navigator.totalResources()}get publicationLanguage(){return this.navigator.publication.Metadata.Language}get currentSettings(){return this.settings.currentSettings}isTTSIncrementable(e){return e==="pitch"||e==="rate"||e==="volume"}isMOIncrementable(e){return e==="mo_rate"||e==="mo_volume"}get currentLocator(){return this.navigator.currentLocator()}get positions(){return this.navigator.positions()}get atStart(){return this.navigator instanceof Tt?this.navigator.atStart():!1}get atEnd(){return this.navigator instanceof Tt?this.navigator.atEnd():!1}async applyLineFocusSettings(e){if(e.lines&&this.lineFocusModule){let t=this.lineFocusModule.properties.lines??1;this.lineFocusModule.index=this.lineFocusModule.index*t/parseInt(e.lines),this.lineFocusModule.index=Math.abs(parseInt(this.lineFocusModule.index.toFixed())),this.lineFocusModule.properties.lines=parseInt(e.lines),this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus()}e.debug!==void 0&&this.lineFocusModule&&(this.lineFocusModule.isDebug=e.debug,this.lineFocusModule.isActive&&await this.lineFocusModule.enableLineFocus())}lineUp(){var e;(e=this.lineFocusModule)==null||e.lineUp()}lineDown(){var e;(e=this.lineFocusModule)==null||e.lineDown()}async enableLineFocus(){var e;await((e=this.lineFocusModule)==null?void 0:e.enableLineFocus())}async lineFocus(e){var t,r;e?await((t=this.lineFocusModule)==null?void 0:t.enableLineFocus()):(r=this.lineFocusModule)==null||r.disableLineFocus()}disableLineFocus(){var e;(e=this.lineFocusModule)==null||e.disableLineFocus()}};function zU(n,e){var t;return e.isFixedLayout&&(n.enableAnnotations=!1,n.enableSearch=!1,n.enableTTS=!1,n.enableDefinitions=!1,n.enablePageBreaks=!1,n.enableLineFocus=!1),(t=e.sample)!=null&&t.isSampleRead&&(n.enableAnnotations=!1,n.enableSearch=!1,n.enableTTS=!1,n.enableDefinitions=!1,n.enableTimeline=!1,n.enableMediaOverlays=!1,n.enablePageBreaks=!1,n.enableLineFocus=!1),n}var VU=du,$U=du.load;return Cn(JU);})();
90
90
  /*! Bundled license information:
91
91
 
92
92
  reflect-metadata/Reflect.js: