@d-i-t-a/reader 3.0.0-alpha.22 → 3.0.0-alpha.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.js +2 -1
- package/dist/esm/index.js.map +2 -2
- package/dist/reader.js +1 -1
- package/dist/reader.js.map +2 -2
- package/package.json +2 -1
package/dist/reader.js
CHANGED
|
@@ -601,7 +601,7 @@ pdfjs-views-manager-status-close-button-label = Close
|
|
|
601
601
|
pdfjs-views-manager-paste-button-label = Paste`)}},ene=1e3,d4=50,yM=1e3;Vh=class{#e=null;constructor({linkService:e,eventBus:t}){this.linkService=e,this.eventBus=t,this._initialized=!1,this._fingerprint="",this.reset(),this.eventBus._on("pagesinit",()=>{this._isPagesLoaded=!1,this.eventBus._on("pagesloaded",i=>{this._isPagesLoaded=!!i.pagesCount},{once:!0})})}initialize({fingerprint:e,resetHistory:t=!1,updateUrl:i=!1}){if(!e||typeof e!="string"){console.error('PDFHistory.initialize: The "fingerprint" must be a non-empty string.');return}this._initialized&&this.reset();let r=this._fingerprint!==""&&this._fingerprint!==e;this._fingerprint=e,this._updateUrl=i===!0,this._initialized=!0,this.#h();let s=window.history.state;if(this._popStateInProgress=!1,this._blockHashChange=0,this._currentHash=h4(),this._numPositionUpdates=0,this._uid=this._maxUid=0,this._destination=null,this._position=null,!this.#r(s,!0)||t){let{hash:a,page:u,rotation:l}=this.#s(!0);if(!a||r||t){this.#t(null,!0);return}this.#t({hash:a,page:u,rotation:l},!0);return}let o=s.destination;this.#o(o,s.uid,!0),o.rotation!==void 0&&(this._initialRotation=o.rotation),o.dest?(this._initialBookmark=JSON.stringify(o.dest),this._destination.page=null):o.hash?this._initialBookmark=o.hash:o.page&&(this._initialBookmark=`page=${o.page}`)}reset(){this._initialized&&(this.#u(),this._initialized=!1,this.#d()),this._updateViewareaTimeout&&(clearTimeout(this._updateViewareaTimeout),this._updateViewareaTimeout=null),this._initialBookmark=null,this._initialRotation=null}push({namedDest:e=null,explicitDest:t,pageNumber:i}){if(!this._initialized)return;if(e&&typeof e!="string"){console.error(`PDFHistory.push: "${e}" is not a valid namedDest parameter.`);return}else if(Array.isArray(t)){if(!this.#i(i)&&(i!==null||this._destination)){console.error(`PDFHistory.push: "${i}" is not a valid pageNumber parameter.`);return}}else{console.error(`PDFHistory.push: "${t}" is not a valid explicitDest parameter.`);return}let r=e||JSON.stringify(t);if(!r)return;let s=!1;if(this._destination&&(tne(this._destination.hash,r)||ine(this._destination.dest,t))){if(this._destination.page)return;s=!0}this._popStateInProgress&&!s||(this.#t({dest:t,hash:r,page:i,rotation:this.linkService.rotation},s),this._popStateInProgress||(this._popStateInProgress=!0,Promise.resolve().then(()=>{this._popStateInProgress=!1})))}pushPage(e){if(this._initialized){if(!this.#i(e)){console.error(`PDFHistory.pushPage: "${e}" is not a valid page number.`);return}this._destination?.page!==e&&(this._popStateInProgress||(this.#t({dest:null,hash:`page=${e}`,page:e,rotation:this.linkService.rotation}),this._popStateInProgress||(this._popStateInProgress=!0,Promise.resolve().then(()=>{this._popStateInProgress=!1}))))}}pushCurrentPosition(){!this._initialized||this._popStateInProgress||this.#n()}back(){if(!this._initialized||this._popStateInProgress)return;let e=window.history.state;this.#r(e)&&e.uid>0&&window.history.back()}forward(){if(!this._initialized||this._popStateInProgress)return;let e=window.history.state;this.#r(e)&&e.uid<this._maxUid&&window.history.forward()}get popStateInProgress(){return this._initialized&&(this._popStateInProgress||this._blockHashChange>0)}get initialBookmark(){return this._initialized?this._initialBookmark:null}get initialRotation(){return this._initialized?this._initialRotation:null}#t(e,t=!1){let i=t||!this._destination,r={fingerprint:this._fingerprint,uid:i?this._uid:this._uid+1,destination:e};this.#o(e,r.uid);let s;if(this._updateUrl&&e?.hash){let{href:o,protocol:a}=document.location;a!=="file:"&&(s=Ote(o,e.hash))}i?window.history.replaceState(r,"",s):window.history.pushState(r,"",s)}#n(e=!1){if(!this._position)return;let t=this._position;if(e&&(t=Object.assign(Object.create(null),this._position),t.temporary=!0),!this._destination){this.#t(t);return}if(this._destination.temporary){this.#t(t,!0);return}if(this._destination.hash===t.hash||!this._destination.page&&(d4<=0||this._numPositionUpdates<=d4))return;let i=!1;if(this._destination.page>=t.first&&this._destination.page<=t.page){if(this._destination.dest!==void 0||!this._destination.first)return;i=!0}this.#t(t,i)}#i(e){return Number.isInteger(e)&&e>0&&e<=this.linkService.pagesCount}#r(e,t=!1){if(!e)return!1;if(e.fingerprint!==this._fingerprint)if(t){if(typeof e.fingerprint!="string"||e.fingerprint.length!==this._fingerprint.length)return!1;let[i]=performance.getEntriesByType("navigation");if(i?.type!=="reload")return!1}else return!1;return!(!Number.isInteger(e.uid)||e.uid<0||e.destination===null||typeof e.destination!="object")}#o(e,t,i=!1){this._updateViewareaTimeout&&(clearTimeout(this._updateViewareaTimeout),this._updateViewareaTimeout=null),i&&e?.temporary&&delete e.temporary,this._destination=e,this._uid=t,this._maxUid=Math.max(this._maxUid,t),this._numPositionUpdates=0}#s(e=!1){let t=unescape(h4()).substring(1),i=Lm(t),r=i.get("nameddest")||"",s=i.get("page")|0;return(!this.#i(s)||e&&r.length>0)&&(s=null),{hash:t,page:s,rotation:this.linkService.rotation}}#a({location:e}){this._updateViewareaTimeout&&(clearTimeout(this._updateViewareaTimeout),this._updateViewareaTimeout=null),this._position={hash:e.pdfOpenParams.substring(1),page:this.linkService.page,first:e.pageNumber,rotation:e.rotation},!this._popStateInProgress&&(d4>0&&this._isPagesLoaded&&this._destination&&!this._destination.page&&this._numPositionUpdates++,yM>0&&(this._updateViewareaTimeout=setTimeout(()=>{this._popStateInProgress||this.#n(!0),this._updateViewareaTimeout=null},yM)))}#l({state:e}){let t=h4(),i=this._currentHash!==t;if(this._currentHash=t,!e){this._uid++;let{hash:s,page:o,rotation:a}=this.#s();this.#t({hash:s,page:o,rotation:a},!0);return}if(!this.#r(e))return;this._popStateInProgress=!0,i&&(this._blockHashChange++,hie({target:window,name:"hashchange",delay:ene}).then(()=>{this._blockHashChange--}));let r=e.destination;this.#o(r,e.uid,!0),RM(r.rotation)&&(this.linkService.rotation=r.rotation),r.dest?this.linkService.goToDestination(r.dest):r.hash?this.linkService.setHash(r.hash):r.page&&(this.linkService.page=r.page),Promise.resolve().then(()=>{this._popStateInProgress=!1})}#u(){(!this._destination||this._destination.temporary)&&this.#n()}#h(){if(this.#e)return;this.#e=new AbortController;let{signal:e}=this.#e;this.eventBus._on("updateviewarea",this.#a.bind(this),{signal:e}),window.addEventListener("popstate",this.#l.bind(this),{signal:e}),window.addEventListener("pagehide",this.#u.bind(this),{signal:e})}#d(){this.#e?.abort(),this.#e=null}};_4=class{#e=null;#t=null;#n=null;#i=null;#r=null;#o;#s=null;constructor(e){this.pageIndex=e.pageIndex,this.accessibilityManager=e.accessibilityManager,this.l10n=e.l10n,this.l10n||=new uc,this.annotationEditorLayer=null,this.div=null,this._cancelled=!1,this.#o=e.uiManager,this.#e=e.annotationLayer||null,this.#r=e.textLayer||null,this.#t=e.drawLayer||null,this.#n=e.onAppend||null,this.#i=e.structTreeLayer||null,this.#s=e.clonedFrom||null}updatePageIndex(e){this.pageIndex=e,this.annotationEditorLayer?.updatePageIndex(e)}async render({viewport:e,intent:t="display"}){if(t!=="display"||this._cancelled)return;let i=e.clone({dontFlip:!0});if(this.div){this.annotationEditorLayer.update({viewport:i}),this.show();return}let r=this.div=document.createElement("div");r.className="annotationEditorLayer",r.hidden=!0,r.dir=this.#o.direction,this.#n?.(r),this.annotationEditorLayer=new Cte({uiManager:this.#o,div:r,structTreeLayer:this.#i,accessibilityManager:this.accessibilityManager,pageIndex:this.pageIndex,l10n:this.l10n,viewport:i,annotationLayer:this.#e,textLayer:this.#r,drawLayer:this.#t}),this.annotationEditorLayer.setClonedFrom(this.#s?.annotationEditorLayer),this.#s=null;let s={viewport:i,div:r,annotations:null,intent:t};this.annotationEditorLayer.render(s),this.show()}cancel(){this._cancelled=!0,this.div&&this.annotationEditorLayer.destroy()}hide(){this.div&&(this.annotationEditorLayer.pause(!0),this.div.hidden=!0)}show(){!this.div||this.annotationEditorLayer.isInvisible||(this.div.hidden=!1,this.annotationEditorLayer.pause(!1))}};{Em=new Map;let{maxTouchPoints:n,platform:e,userAgent:t}=navigator,i=/Android/.test(t);(/\b(iPad|iPhone|iPod)(?=;)/.test(t)||e==="MacIntel"&&n>1||i)&&Em.set("maxCanvasPixels",5242880),i&&Em.set("useSystemFonts",!1)}ne={BROWSER:1,VIEWER:2,API:4,WORKER:8,EVENT_DISPATCH:16,PREFERENCE:128},P4={BOOLEAN:1,NUMBER:2,OBJECT:4,STRING:8,UNDEFINED:16},Ao={allowedGlobalEvents:{value:null,kind:ne.BROWSER},canvasMaxAreaInBytes:{value:-1,kind:ne.BROWSER+ne.API},isInAutomation:{value:!1,kind:ne.BROWSER},localeProperties:{value:{lang:navigator.language||"en-US"},kind:ne.BROWSER},maxCanvasDim:{value:32767,kind:ne.BROWSER+ne.VIEWER},nimbusDataStr:{value:"",kind:ne.BROWSER},supportsCaretBrowsingMode:{value:!1,kind:ne.BROWSER},supportsDocumentFonts:{value:!0,kind:ne.BROWSER},supportsIntegratedFind:{value:!1,kind:ne.BROWSER},supportsMouseWheelZoomCtrlKey:{value:!0,kind:ne.BROWSER},supportsMouseWheelZoomMetaKey:{value:!0,kind:ne.BROWSER},supportsPinchToZoom:{value:!0,kind:ne.BROWSER},supportsPrinting:{value:!0,kind:ne.BROWSER},toolbarDensity:{value:0,kind:ne.BROWSER+ne.EVENT_DISPATCH},altTextLearnMoreUrl:{value:"",kind:ne.VIEWER+ne.PREFERENCE},annotationEditorMode:{value:0,kind:ne.VIEWER+ne.PREFERENCE},annotationMode:{value:2,kind:ne.VIEWER+ne.PREFERENCE},capCanvasAreaFactor:{value:200,kind:ne.VIEWER+ne.PREFERENCE},commentLearnMoreUrl:{value:"",kind:ne.VIEWER+ne.PREFERENCE},cursorToolOnLoad:{value:0,kind:ne.VIEWER+ne.PREFERENCE},debuggerSrc:{value:"./debugger.mjs",kind:ne.VIEWER},defaultZoomDelay:{value:400,kind:ne.VIEWER+ne.PREFERENCE},defaultZoomValue:{value:"",kind:ne.VIEWER+ne.PREFERENCE},disableHistory:{value:!1,kind:ne.VIEWER},disablePageLabels:{value:!1,kind:ne.VIEWER+ne.PREFERENCE},enableAltText:{value:!1,kind:ne.VIEWER+ne.PREFERENCE},enableAltTextModelDownload:{value:!0,kind:ne.VIEWER+ne.PREFERENCE+ne.EVENT_DISPATCH},enableAutoLinking:{value:!0,kind:ne.VIEWER+ne.PREFERENCE},enableComment:{value:!1,kind:ne.VIEWER+ne.PREFERENCE},enableDetailCanvas:{value:!0,kind:ne.VIEWER},enableGuessAltText:{value:!0,kind:ne.VIEWER+ne.PREFERENCE+ne.EVENT_DISPATCH},enableHighlightFloatingButton:{value:!1,kind:ne.VIEWER+ne.PREFERENCE},enableNewAltTextWhenAddingImage:{value:!0,kind:ne.VIEWER+ne.PREFERENCE},enableOptimizedPartialRendering:{value:!1,kind:ne.VIEWER+ne.PREFERENCE},enablePermissions:{value:!1,kind:ne.VIEWER+ne.PREFERENCE},enablePrintAutoRotate:{value:!0,kind:ne.VIEWER+ne.PREFERENCE},enableScripting:{value:!0,kind:ne.VIEWER+ne.PREFERENCE},enableSignatureEditor:{value:!1,kind:ne.VIEWER+ne.PREFERENCE},enableSplitMerge:{value:!1,kind:ne.VIEWER+ne.PREFERENCE},enableUpdatedAddImage:{value:!1,kind:ne.VIEWER+ne.PREFERENCE},externalLinkRel:{value:"noopener noreferrer nofollow",kind:ne.VIEWER},externalLinkTarget:{value:0,kind:ne.VIEWER+ne.PREFERENCE},highlightEditorColors:{value:"yellow=#FFFF98,green=#53FFBC,blue=#80EBFF,pink=#FFCBE6,red=#FF4F5F,yellow_HCM=#FFFFCC,green_HCM=#53FFBC,blue_HCM=#80EBFF,pink_HCM=#F6B8FF,red_HCM=#C50043",kind:ne.VIEWER+ne.PREFERENCE},historyUpdateUrl:{value:!1,kind:ne.VIEWER+ne.PREFERENCE},ignoreDestinationZoom:{value:!1,kind:ne.VIEWER+ne.PREFERENCE},imageResourcesPath:{value:"./images/",kind:ne.VIEWER},maxCanvasPixels:{value:2**25,kind:ne.VIEWER},minDurationToUpdateCanvas:{value:500,kind:ne.VIEWER},forcePageColors:{value:!1,kind:ne.VIEWER+ne.PREFERENCE},pageColorsBackground:{value:"Canvas",kind:ne.VIEWER+ne.PREFERENCE},pageColorsForeground:{value:"CanvasText",kind:ne.VIEWER+ne.PREFERENCE},pdfBugEnabled:{value:!1,kind:ne.VIEWER+ne.PREFERENCE},printResolution:{value:150,kind:ne.VIEWER},sidebarViewOnLoad:{value:-1,kind:ne.VIEWER+ne.PREFERENCE},scrollModeOnLoad:{value:-1,kind:ne.VIEWER+ne.PREFERENCE},spreadModeOnLoad:{value:-1,kind:ne.VIEWER+ne.PREFERENCE},textLayerMode:{value:1,kind:ne.VIEWER+ne.PREFERENCE},viewerCssTheme:{value:0,kind:ne.VIEWER+ne.PREFERENCE},viewOnLoad:{value:0,kind:ne.VIEWER+ne.PREFERENCE},cMapPacked:{value:!0,kind:ne.API},cMapUrl:{value:"../web/cmaps/",kind:ne.API},disableAutoFetch:{value:!1,kind:ne.API+ne.PREFERENCE},disableFontFace:{value:!1,kind:ne.API+ne.PREFERENCE},disableRange:{value:!1,kind:ne.API+ne.PREFERENCE},disableStream:{value:!1,kind:ne.API+ne.PREFERENCE},docBaseUrl:{value:"",kind:ne.API},enableHWA:{value:!0,kind:ne.API+ne.VIEWER+ne.PREFERENCE},enableXfa:{value:!0,kind:ne.API+ne.PREFERENCE},fontExtraProperties:{value:!1,kind:ne.API},iccUrl:{value:"../web/iccs/",kind:ne.API},isEvalSupported:{value:!0,kind:ne.API},isOffscreenCanvasSupported:{value:!0,kind:ne.API},maxImageSize:{value:-1,kind:ne.API},pdfBug:{value:!1,kind:ne.API},standardFontDataUrl:{value:"../web/standard_fonts/",kind:ne.API},useSystemFonts:{value:void 0,kind:ne.API,type:P4.BOOLEAN+P4.UNDEFINED},verbosity:{value:1,kind:ne.API},wasmUrl:{value:"../web/wasm/",kind:ne.API},workerPort:{value:null,kind:ne.WORKER},workerSrc:{value:"../build/pdf.worker.mjs",kind:ne.WORKER}};Ao.defaultUrl={value:"compressed.tracemonkey-pldi-09.pdf",kind:ne.VIEWER},Ao.sandboxBundleSrc={value:"../build/pdf.sandbox.mjs",kind:ne.VIEWER},Ao.enableFakeMLManager={value:!0,kind:ne.VIEWER};Ao.disablePreferences={value:!1,kind:ne.VIEWER};Is=class Is{static get(e){return Mt(this,pa).get(e)}static getAll(e=null,t=!1){let i=Object.create(null);for(let r in Ao){let s=Ao[r];e&&!(e&s.kind)||(i[r]=t?s.value:Mt(this,pa).get(r))}return i}static set(e,t){this.setAll({[e]:t})}static setAll(e,t=!1){this._hasInvokedSet||=!0;let i;for(let r in e){let s=Ao[r],o=e[r];if(!s||!(typeof o==typeof s.value||P4[(typeof o).toUpperCase()]&s.type))continue;let{kind:a}=s;t&&!(a&ne.BROWSER||a&ne.PREFERENCE)||(this.eventBus&&a&ne.EVENT_DISPATCH&&(i||=new Map).set(r,o),Mt(this,pa).set(r,o))}if(i)for(let[r,s]of i)this.eventBus.dispatch(r.toLowerCase(),{source:this,value:s})}};pa=new WeakMap,tS(Is,"eventBus"),Er(Is,pa,new Map),(()=>{for(let e in Ao)Mt(Is,pa).set(e,Ao[e].value);for(let[e,t]of Em)Mt(Is,pa).set(e,t);Is._hasInvokedSet=!1,Is._checkDisablePreferences=()=>Is.get("disablePreferences")?!0:(Is._hasInvokedSet&&console.warn('The Preferences may override manually set AppOptions; please use the "disablePreferences"-option to prevent that.'),!1)})();Hh=Is;R4=class{static#e=0;static#t;static#n;static findLinks(e){this.#t??=new RegExp("\\b(?:https?:\\/\\/|mailto:|www\\.)(?:[\\S--[\\p{P}<>]]|\\/|[\\S--[\\[\\]]]+[\\S--[\\p{P}<>]])+|(?=\\p{L})[\\S--[@\\p{Ps}\\p{Pe}<>]]+@([\\S--[[\\p{P}--\\-]<>]]+(?:\\.[\\S--[[\\p{P}--\\-]<>]]+)+)","gmv");let[t,i]=wm(e,{ignoreDashEOL:!0}),r=t.matchAll(this.#t),s=[];for(let o of r){let[a,u]=o,l;if(a.startsWith("www.")||a.startsWith("http://")||a.startsWith("https://"))l=a;else if(u){let d=URL.parse(`http://${u}`)?.hostname;if(!d||(this.#n??=/\.\d+$/,this.#n.test(d)))continue}l??=a.startsWith("mailto:")?a:`mailto:${a}`;let c=xM(l,null,{addDefaultProtocol:!0});if(c){let[d,f]=LM(i,o.index,a.length);s.push({url:c.href,index:d,length:f})}}return s}static processLinks(e){return this.findLinks(e._textHighlighter.textContentItemsStr.join(`
|
|
602
602
|
`)).map(t=>rne(t,e,this.#e++))}},Tt={INITIAL:0,RUNNING:1,PAUSED:2,FINISHED:3},L4=class{renderingId="";renderTask=null;resume=null;get renderingState(){throw new Error("Abstract getter `renderingState` accessed")}set renderingState(e){throw new Error("Abstract setter `renderingState` accessed")}async draw(){throw new Error("Not implemented: draw")}},xm=class extends L4{#e=null;#t=null;#n=Tt.INITIAL;#i=null;#r=0;#o=null;canvas=null;div=null;enableOptimizedPartialRendering=!1;eventBus=null;id=null;pageColors=null;recordedBBoxes=null;renderingQueue=null;constructor(e){super(),this.eventBus=e.eventBus,this.id=e.id,this.pageColors=e.pageColors||null,this.renderingQueue=e.renderingQueue,this.enableOptimizedPartialRendering=e.enableOptimizedPartialRendering??!1,this.minDurationToUpdateCanvas=e.minDurationToUpdateCanvas??500}get renderingState(){return this.#n}set renderingState(e){if(e!==this.#n)switch(this.#n=e,this.#e&&(clearTimeout(this.#e),this.#e=null),e){case Tt.PAUSED:this.div.classList.remove("loading"),this.#r=0,this.#i?.(!1);break;case Tt.RUNNING:this.div.classList.add("loadingIcon"),this.#e=setTimeout(()=>{this.div.classList.add("loading"),this.#e=null},0),this.#r=Date.now();break;case Tt.INITIAL:case Tt.FINISHED:this.div.classList.remove("loadingIcon","loading"),this.#r=0;break}}_createCanvas(e,t=!1){let{pageColors:i}=this,r=!!(i?.background&&i?.foreground),s=this.canvas,o=!s&&!r&&!t,a=this.canvas=document.createElement("canvas");return this.#i=u=>{if(o){let l=this.#o;if(!u&&this.minDurationToUpdateCanvas>0){if(Date.now()-this.#r<this.minDurationToUpdateCanvas)return;l||(l=this.#o=a,a=this.canvas=a.cloneNode(!1),e(a))}if(l){a.getContext("2d",{alpha:!1}).drawImage(l,0,0),u?this.#a():this.#r=Date.now();return}e(a),this.#i=null;return}u&&(s?(s.replaceWith(a),s.width=s.height=0):e(a))},{canvas:a,prevCanvas:s}}#s=e=>{if(this.#i?.(!1),this.renderingQueue&&!this.renderingQueue.isHighestPriority(this)){this.renderingState=Tt.PAUSED,this.resume=()=>{this.renderingState=Tt.RUNNING,e()};return}e()};_resetCanvas(){let{canvas:e}=this;e&&(e.remove(),e.width=e.height=0,this.canvas=null,this.#a())}#a(){this.#o&&(this.#o.width=this.#o.height=0,this.#o=null)}async _drawCanvas(e,t,i){let r=this.renderTask=this.pdfPage.render(e);r.onContinue=this.#s,r.onError=o=>{o instanceof f4&&(t(),this.#t=null)};let s=null;try{await r.promise,this.#i?.(!0)}catch(o){if(o instanceof f4)return;s=o,this.#i?.(!0)}finally{this.#t=s,r===this.renderTask&&(this.renderTask=null,this.enableOptimizedPartialRendering&&(this.recordedBBoxes??=r.recordedBBoxes))}if(this.renderingState=Tt.FINISHED,i(r),s)throw s}cancelRendering({cancelExtraDelay:e=0}={}){this.renderTask&&(this.renderTask.cancel(e),this.renderTask=null),this.resume=null}dispatchPageRender(){this.eventBus.dispatch("pagerender",{source:this,pageNumber:this.id})}dispatchPageRendered(e,t){this.eventBus.dispatch("pagerendered",{source:this,pageNumber:this.id,cssTransform:e,isDetailView:t,timestamp:performance.now(),error:this.#t})}},M4=class{#e=null;async render({intent:e="display"}){e!=="display"||this.#e||this._cancelled||(this.#e=new Tte)}cancel(){this._cancelled=!0,this.#e&&(this.#e.destroy(),this.#e=null)}setParent(e){this.#e?.setParent(e)}getDrawLayer(){return this.#e}},O4=class extends xm{#e=null;renderingCancelled=!1;constructor({pageView:e}){super(e),this.pageView=e,this.renderingId="detail"+this.id,this.div=e.div}setPdfPage(e){this.pageView.setPdfPage(e)}get pdfPage(){return this.pageView.pdfPage}get renderingState(){return super.renderingState}set renderingState(e){this.renderingCancelled=!1,super.renderingState=e}reset({keepCanvas:e=!1}={}){let t=this.renderingCancelled||this.renderingState===Tt.RUNNING||this.renderingState===Tt.PAUSED;this.cancelRendering(),this.renderingState=Tt.INITIAL,this.renderingCancelled=t,e||this._resetCanvas()}#t(e){if(!this.#e)return!0;let t=this.#e.minX,i=this.#e.minY,r=this.#e.width+t,s=this.#e.height+i;if(e.minX<t||e.minY<i||e.maxX>r||e.maxY>s)return!0;let{width:o,height:a,scale:u}=this.pageView.viewport;if(this.#e.scale!==u)return!0;let l=e.minX-t,c=r-e.maxX,d=e.minY-i,f=s-e.maxY,m=.5,y=(1+m)/m;return t>0&&c/l>y||r<o&&l/c>y||i>0&&f/d>y||s<a&&d/f>y}update({visibleArea:e=null,underlyingViewUpdated:t=!1}={}){if(t){this.cancelRendering(),this.renderingState=Tt.INITIAL;return}if(!this.#t(e))return;let{viewport:i,maxCanvasPixels:r,capCanvasAreaFactor:s}=this.pageView,o=e.maxX-e.minX,a=e.maxY-e.minY,u=o*a*Am.pixelRatio**2,c=(Math.sqrt(Am.capPixels(r,s)/u)-1)/2,d=Math.min(1,c);d<0&&(d=0);let f=o*d,m=a*d,y=Math.max(0,e.minX-f),g=Math.min(i.width,e.maxX+f),b=Math.max(0,e.minY-m),v=Math.min(i.height,e.maxY+m),A=g-y,w=v-b;this.#e={minX:y,minY:b,width:A,height:w,scale:i.scale},this.reset({keepCanvas:!0})}_getRenderingContext(e,t){let i=this.pageView._getRenderingContext(e,t,!1),r=this.pdfPage.recordedBBoxes;if(!r||!this.enableOptimizedPartialRendering)return i;let{viewport:{width:s,height:o}}=this.pageView,{width:a,height:u,minX:l,minY:c}=this.#e,d=l/s,f=c/o,m=(l+a)/s,y=(c+u)/o;return{...i,operationsFilter(g){return r.isEmpty(g)?!1:r.minX(g)<=m&&r.maxX(g)>=d&&r.minY(g)<=y&&r.maxY(g)>=f}}}async draw(){if(this.pageView.detailView!==this)return;let e=this.pageView.renderingState===Tt.FINISHED||this.renderingState===Tt.FINISHED;this.renderingState!==Tt.INITIAL&&(console.error("Must be in new state before drawing"),this.reset());let{div:t,pdfPage:i,viewport:r}=this.pageView;if(!i)throw this.renderingState=Tt.FINISHED,new Error("pdfPage is not loaded");this.renderingState=Tt.RUNNING;let s=this.pageView._ensureCanvasWrapper(),{canvas:o,prevCanvas:a}=this._createCanvas(g=>{s.firstElementChild?.tagName==="CANVAS"?s.firstElementChild.after(g):s.prepend(g)},e);o.ariaHidden=!0,this.enableOptimizedPartialRendering&&(o.className="detailView");let{width:u,height:l}=r,c=this.#e,{pixelRatio:d}=Am,f=[d,0,0,d,-c.minX*d,-c.minY*d];o.width=c.width*d,o.height=c.height*d;let{style:m}=o;m.width=`${c.width*100/u}%`,m.height=`${c.height*100/l}%`,m.top=`${c.minY*100/l}%`,m.left=`${c.minX*100/u}%`;let y=this._drawCanvas(this._getRenderingContext(o,f),()=>{this.canvas?.remove(),this.canvas=a},()=>{this.dispatchPageRendered(!1,!0)});return t.setAttribute("data-loaded",!0),this.dispatchPageRender(),y}},wM={Document:null,DocumentFragment:null,Part:"group",Sect:"group",Div:"group",Aside:"note",NonStruct:"none",P:null,H:"heading",Title:null,FENote:"note",Sub:"group",Lbl:null,Span:null,Em:null,Strong:null,Link:"link",Annot:"note",Form:"form",Ruby:null,RB:null,RT:null,RP:null,Warichu:null,WT:null,WP:null,L:"list",LI:"listitem",LBody:null,Table:"table",TR:"row",TH:"columnheader",TD:"cell",THead:"rowgroup",TBody:"rowgroup",TFoot:null,Caption:null,Figure:"figure",Formula:null,Artifact:null},BM=new Set(["math","merror","mfrac","mi","mmultiscripts","mn","mo","mover","mpadded","mprescripts","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msubsup","msup","mtable","mtd","mtext","mtr","munder","munderover","semantics"]),Tm="http://www.w3.org/1998/Math/MathML",Im=class{static get sanitizer(){return Uh(this,"sanitizer",TM.isSanitizerSupported?new Sanitizer({elements:[...BM].map(e=>({name:e,namespace:Tm})),replaceWithChildrenElements:[{name:"maction",namespace:Tm}],attributes:["dir","displaystyle","mathbackground","mathcolor","mathsize","scriptlevel","encoding","display","linethickness","intent","arg","form","fence","separator","lspace","rspace","stretchy","symmetric","maxsize","minsize","largeop","movablelimits","width","height","depth","voffset","accent","accentunder","columnspan","rowspan"],comments:!1}):null)}},sne=/^H(\d+)$/,km=class{#e;#t=null;#n;#i=new Map;#r;#o=null;#s=null;#a=null;constructor(e,t){this.#e=e.getStructTree(),this.#r=t}async render(){if(this.#n)return this.#n;let{promise:e,resolve:t,reject:i}=Promise.withResolvers();this.#n=e;try{this.#t=this.#h(await this.#e)}catch(r){i(r)}return this.#e=null,this.#t?.classList.add("structTree"),t(this.#t),e}async getAriaAttributes(e){try{return await this.render(),this.#i.get(e)}catch{}return null}hide(){this.#t&&!this.#t.hidden&&(this.#t.hidden=!0)}show(){this.#t?.hidden&&(this.#t.hidden=!1)}#l(e,t){let{alt:i,id:r,lang:s}=e;if(i!==void 0){let o=!1,a=Fh(i);for(let u of e.children)u.type==="annotation"&&(this.#i.getOrInsertComputed(u.id,Rte).set("aria-label",a),o=!0);o||t.setAttribute("aria-label",a)}r!==void 0&&t.setAttribute("aria-owns",r),s!==void 0&&t.setAttribute("lang",Fh(s,!0))}#u(e,t){let{alt:i,bbox:r,children:s}=e,o=s?.[0];if(!this.#r||!i||!r||o?.type!=="content")return!1;let{id:a}=o;if(!a)return!1;t.setAttribute("aria-owns",a);let u=document.createElement("span");(this.#o||=new Map).set(a,u),u.setAttribute("role","img"),u.setAttribute("aria-label",Fh(i));let{pageHeight:l,pageX:c,pageY:d}=this.#r,f="calc(var(--total-scale-factor) *",{style:m}=u;return m.width=`${f}${r[2]-r[0]}px)`,m.height=`${f}${r[3]-r[1]}px)`,m.left=`${f}${r[0]-c}px)`,m.top=`${f}${l-r[3]+d}px)`,!0}updateTextLayer(){if(this.#o){for(let[e,t]of this.#o)document.getElementById(e)?.append(t);this.#o.clear(),this.#o=null}if(this.#s){for(let e of this.#s){let t=document.getElementById(e);t&&(t.ariaHidden=!0)}this.#s.length=0,this.#s=null}if(this.#a){for(let e=0,t=this.#a.length;e<t;e+=2){let i=this.#a[e],r=this.#a[e+1],s="";for(let o of r){let a=document.getElementById(o);a&&(s+=a.textContent.trim()||"",a.ariaHidden="true")}s&&(i.textContent=s)}this.#a.length=0,this.#a=null}}#h(e,t=[]){if(!e)return null;let i;if("role"in e){let{role:r}=e;if(BM.has(r)){i=document.createElementNS(Tm,r);let o=[];(this.#a||=[]).push(i,o);for(let{type:a,id:u}of e.children||[])a==="content"&&u&&o.push(u)}else i=document.createElement("span");let s=r.match(sne);if(s?(i.setAttribute("role","heading"),i.setAttribute("aria-level",s[1])):wM[r]&&i.setAttribute("role",r==="TH"&&t.at(-1)?.role==="TR"&&t.at(-2)?.role==="TBody"?"rowheader":wM[r]),r==="Figure"&&this.#u(e,i))return i;if(r==="Formula"){if(e.mathML&&Im.sanitizer){i.setHTML(e.mathML,{sanitizer:Im.sanitizer});for(let{id:o}of e.children||[])o&&(this.#s||=[]).push(o);delete e.alt}!e.mathML&&e.children.length===1&&e.children[0].role!=="math"&&(i=document.createElementNS(Tm,"math"),delete e.alt)}}if(i||=document.createElement("span"),this.#l(e,i),e.children)if(e.children.length===1&&"id"in e.children[0])this.#l(e.children[0],i);else{t.push(e);for(let r of e.children)i.append(this.#h(r,t));t.pop()}return i}},N4=class n{#e=!1;#t=null;#n=new Map;#i=new Map;setTextMapping(e){this.#t=e}static#r(e,t){let i=e.getBoundingClientRect(),r=t.getBoundingClientRect();if(i.width===0&&i.height===0)return 1;if(r.width===0&&r.height===0)return-1;let s=i.y,o=i.y+i.height,a=i.y+i.height/2,u=r.y,l=r.y+r.height,c=r.y+r.height/2;if(a<=u&&c>=o)return-1;if(c<=s&&a>=l)return 1;let d=i.x+i.width/2,f=r.x+r.width/2;return d-f}enable(){if(this.#e)throw new Error("TextAccessibilityManager is already enabled.");if(!this.#t)throw new Error("Text divs and strings have not been set.");if(this.#e=!0,this.#t=this.#t.slice(),this.#t.sort(n.#r),this.#n.size>0){let e=this.#t;for(let[t,i]of this.#n){if(!document.getElementById(t)){this.#n.delete(t);continue}this.#o(t,e[i])}}for(let[e,t]of this.#i)this.addPointerInTextLayer(e,t);this.#i.clear()}disable(){this.#e&&(this.#i.clear(),this.#t=null,this.#e=!1)}removePointerInTextLayer(e){if(!this.#e){this.#i.delete(e);return}let t=this.#t;if(!t||t.length===0)return;let{id:i}=e,r=this.#n.get(i);if(r===void 0)return;let s=t[r];this.#n.delete(i);let o=s.getAttribute("aria-owns");o?.includes(i)&&(o=o.split(" ").filter(a=>a!==i).join(" "),o?s.setAttribute("aria-owns",o):(s.removeAttribute("aria-owns"),s.setAttribute("role","presentation")))}#o(e,t){let i=t.getAttribute("aria-owns");i?.includes(e)||t.setAttribute("aria-owns",i?`${i} ${e}`:e),t.removeAttribute("role")}addPointerInTextLayer(e,t){let{id:i}=e;if(!i)return null;if(!this.#e)return this.#i.set(e,t),null;t&&this.removePointerInTextLayer(e);let r=this.#t;if(!r||r.length===0)return null;let s=jh(r,l=>n.#r(e,l)<0),o=Math.max(0,s-1),a=r[o];this.#o(i,a),this.#n.set(i,o);let u=a.parentNode;return u?.classList.contains("markedContent")?u.id:null}moveElementInDOM(e,t,i,r){let s=this.addPointerInTextLayer(i,r);if(!e.hasChildNodes())return e.append(t),s;let o=Array.from(e.childNodes).filter(u=>u!==t);if(o.length===0)return s;let a=jh(o,u=>n.#r(t,u)<0);return a===0?o[0].before(t):o[a-1].after(t),s}},B4=class{#e=null;constructor({findController:e,eventBus:t,pageIndex:i}){this.findController=e,this.matches=[],this.eventBus=t,this.pageIdx=i,this.textDivs=null,this.textContentItemsStr=null,this.enabled=!1}setTextMapping(e,t){this.textDivs=e,this.textContentItemsStr=t}enable(){if(!this.textDivs||!this.textContentItemsStr)throw new Error("Text divs and strings have not been set.");if(this.enabled)throw new Error("TextHighlighter is already enabled.");this.enabled=!0,this.#e||(this.#e=new AbortController,this.eventBus._on("updatetextlayermatches",e=>{(e.pageIndex===this.pageIdx||e.pageIndex===-1)&&this._updateMatches()},{signal:this.#e.signal})),this._updateMatches()}disable(){this.enabled&&(this.enabled=!1,this.#e?.abort(),this.#e=null,this._updateMatches(!0))}_convertMatches(e,t){if(!e)return[];let{textContentItemsStr:i}=this,r=0,s=0,o=i.length-1,a=[];for(let u=0,l=e.length;u<l;u++){let c=e[u];for(;r!==o&&c>=s+i[r].length;)s+=i[r].length,r++;r===i.length&&console.error("Could not find a matching mapping");let d={begin:{divIdx:r,offset:c-s}};for(c+=t[u];r!==o&&c>s+i[r].length;)s+=i[r].length,r++;d.end={divIdx:r,offset:c-s},a.push(d)}return a}_renderMatches(e){if(e.length===0)return;let{findController:t,pageIdx:i}=this,{textContentItemsStr:r,textDivs:s}=this,o=i===t.selected.pageIdx,a=t.selected.matchIdx,u=t.state.highlightAll,l=null,c={divIdx:-1,offset:void 0};function d(v,A){let w=v.divIdx;return s[w].textContent="",f(w,0,v.offset,A)}function f(v,A,w,S){let C=s[v];if(C.nodeType===Node.TEXT_NODE){let k=document.createElement("span");C.before(k),k.append(C),s[v]=k,C=k}let T=r[v].substring(A,w),_=document.createTextNode(T);if(S){let k=document.createElement("span");if(k.className=`${S} appended`,k.append(_),C.append(k),S.includes("selected")){let{left:L}=k.getClientRects()[0],M=C.getBoundingClientRect().left;return L-M}return 0}return C.append(_),0}let m=a,y=m+1;if(u)m=0,y=e.length;else if(!o)return;let g=-1,b=-1;for(let v=m;v<y;v++){let A=e[v],w=A.begin;if(w.divIdx===g&&w.offset===b)continue;g=w.divIdx,b=w.offset;let S=A.end,C=o&&v===a,T=C?" selected":"",_=0;if(!l||w.divIdx!==l.divIdx?(l!==null&&f(l.divIdx,l.offset,c.offset),d(w)):f(l.divIdx,l.offset,w.offset),w.divIdx===S.divIdx)_=f(w.divIdx,w.offset,S.offset,"highlight"+T);else{_=f(w.divIdx,w.offset,c.offset,"highlight begin"+T);for(let k=w.divIdx+1,L=S.divIdx;k<L;k++)s[k].className="highlight middle"+T;d(S,"highlight end"+T)}l=S,C&&t.scrollMatchIntoView({element:s[w.divIdx],selectedLeft:_,pageIndex:i,matchIndex:a})}l&&f(l.divIdx,l.offset,c.offset)}_updateMatches(e=!1){if(!this.enabled&&!e)return;let{findController:t,matches:i,pageIdx:r}=this,{textContentItemsStr:s,textDivs:o}=this,a=-1;for(let c of i){let d=Math.max(a,c.begin.divIdx);for(let f=d,m=c.end.divIdx;f<=m;f++){let y=o[f];y.textContent=s[f],y.className=""}a=c.end.divIdx+1}if(!t?.highlightMatches||e)return;let u=t.pageMatches[r]||null,l=t.pageMatchesLength[r]||null;this.matches=this._convertMatches(u,l),this._renderMatches(this.matches)}},_m=class n{#e=!1;#t=null;#n=!1;#i=null;static#r=new Map;static#o=null;constructor({pdfPage:e,highlighter:t=null,accessibilityManager:i=null,enablePermissions:r=!1,onAppend:s=null}){this.pdfPage=e,this.highlighter=t,this.accessibilityManager=i,this.#e=r===!0,this.#t=s,this.div=document.createElement("div"),this.div.tabIndex=0,this.div.className="textLayer"}async render({viewport:e,textContentParams:t=null}){if(this.#n&&this.#i){this.#i.update({viewport:e,onBefore:this.hide.bind(this)}),this.show();return}this.cancel(),this.#i=new Mte({textContentSource:this.pdfPage.streamTextContent(t||{includeMarkedContent:!0,disableNormalization:!0}),container:this.div,viewport:e});let{textDivs:i,textContentItemsStr:r}=this.#i;this.highlighter?.setTextMapping(i,r),this.accessibilityManager?.setTextMapping(i),await this.#i.render(),this.#n=!0;let s=document.createElement("div");s.className="endOfContent",this.div.append(s),this.#s(s),this.#t?.(this.div),this.highlighter?.enable(),this.accessibilityManager?.enable()}hide(){!this.div.hidden&&this.#n&&(this.highlighter?.disable(),this.div.hidden=!0)}show(){this.div.hidden&&this.#n&&(this.div.hidden=!1,this.highlighter?.enable())}cancel(){this.#i?.cancel(),this.#i=null,this.highlighter?.disable(),this.accessibilityManager?.disable(),n.#a(this.div)}#s(e){let{div:t}=this;t.addEventListener("mousedown",()=>{t.classList.add("selecting")}),t.addEventListener("copy",i=>{if(!this.#e){let r=document.getSelection();i.clipboardData.setData("text/plain",Fh(Lte(r.toString())))}p4(i)}),n.#r.set(t,e),n.#l()}static#a(e){this.#r.delete(e),this.#r.size===0&&(this.#o?.abort(),this.#o=null)}static#l(){if(this.#o)return;this.#o=new AbortController;let{signal:e}=this.#o,t=(o,a)=>{a.append(o),o.style.width="",o.style.height="",a.classList.remove("selecting")},i=!1;document.addEventListener("pointerdown",()=>{i=!0},{signal:e}),document.addEventListener("pointerup",()=>{i=!1,this.#r.forEach(t)},{signal:e}),window.addEventListener("blur",()=>{i=!1,this.#r.forEach(t)},{signal:e}),document.addEventListener("keyup",()=>{i||this.#r.forEach(t)},{signal:e});var r,s;document.addEventListener("selectionchange",()=>{let o=document.getSelection();if(o.rangeCount===0){this.#r.forEach(t);return}let a=new Set;for(let m=0;m<o.rangeCount;m++){let y=o.getRangeAt(m);for(let g of this.#r.keys())!a.has(g)&&y.intersectsNode(g)&&a.add(g)}for(let[m,y]of this.#r)a.has(m)?m.classList.add("selecting"):t(y,m);if(r??=getComputedStyle(this.#r.values().next().value).getPropertyValue("-moz-user-select")==="none",r)return;let u=o.getRangeAt(0),l=s&&(u.compareBoundaryPoints(Range.END_TO_END,s)===0||u.compareBoundaryPoints(Range.START_TO_END,s)===0),c=l?u.startContainer:u.endContainer;if(c.nodeType===Node.TEXT_NODE&&(c=c.parentNode),c.classList?.contains("highlight")&&(c=c.parentNode),!l&&u.endOffset===0)do{for(;!c.previousSibling;)c=c.parentNode;c=c.previousSibling}while(!c.childNodes.length);let d=c.parentElement?.closest(".textLayer"),f=this.#r.get(d);f&&(f.style.width=d.style.width,f.style.height=d.style.height,f.style.userSelect="text",c.parentElement.insertBefore(f,l?c:c.nextSibling)),s=u.cloneRange()},{signal:e})}},Pm=class{constructor({pdfPage:e,annotationStorage:t=null,linkService:i,xfaHtml:r=null}){this.pdfPage=e,this.annotationStorage=t,this.linkService=i,this.xfaHtml=r,this.div=null,this._cancelled=!1}async render({viewport:e,intent:t="display"}){if(t==="print"){let s={viewport:e.clone({dontFlip:!0}),div:this.div,xfaHtml:this.xfaHtml,annotationStorage:this.annotationStorage,linkService:this.linkService,intent:t};return this.div=document.createElement("div"),s.div=this.div,s4.render(s)}let i=await this.pdfPage.getXfa();if(this._cancelled||!i)return{textDivs:[]};let r={viewport:e.clone({dontFlip:!0}),div:this.div,xfaHtml:i,annotationStorage:this.annotationStorage,linkService:this.linkService,intent:t};return this.div?s4.update(r):(this.div=document.createElement("div"),r.div=this.div,s4.render(r))}cancel(){this._cancelled=!0}hide(){this.div&&(this.div.hidden=!0)}},one={annotationEditorUIManager:null,annotationStorage:null,downloadManager:null,enableScripting:!1,fieldObjectsPromise:null,findController:null,hasJSActionsPromise:null,get linkService(){return new Wh}},ane=new Map([["canvasWrapper",0],["textLayer",1],["annotationLayer",2],["annotationEditorLayer",3],["xfaLayer",3]]),Rm=class n extends xm{#e=_s.ENABLE_FORMS;#t=null;#n=null;#i=!0;#r=!1;#o=!1;#s=null;#a=!1;#l=null;#u=null;#h=1;#d=1;#f=ks.ENABLE;#m=1;#p={directDrawing:!0,initialOptionalContent:!0,regularAnnotations:!0};#c=[null,null,null,null];#g=null;constructor(e){super(e);let{container:t,defaultViewport:i}=e;this.renderingId="page"+this.id,this.#s=e.layerProperties||one,this.pdfPage=null,this.pageLabel=null,this.rotation=0,this.scale=e.scale||_M,this.viewport=i,this.pdfPageRotate=i.rotation,this._optionalContentConfigPromise=e.optionalContentConfigPromise||null,this.#f=e.textLayerMode??ks.ENABLE,this.#e=e.annotationMode??_s.ENABLE_FORMS,this.imageResourcesPath=e.imageResourcesPath||"",this.enableDetailCanvas=e.enableDetailCanvas??!0,this.maxCanvasPixels=e.maxCanvasPixels??Hh.get("maxCanvasPixels"),this.maxCanvasDim=e.maxCanvasDim||Hh.get("maxCanvasDim"),this.capCanvasAreaFactor=e.capCanvasAreaFactor??Hh.get("capCanvasAreaFactor"),this.#i=e.enableAutoLinking!==!1,this.#n=e.commentManager||null,this.#g=e.clonedFrom||null,this.l10n=e.l10n,this.l10n||=new uc,this._isStandalone=!this.renderingQueue?.hasViewer(),this._container=t,this._annotationCanvasMap=null,this.annotationLayer=null,this.annotationEditorLayer=null,this.textLayer=null,this.xfaLayer=null,this.structTreeLayer=null,this.drawLayer=null,this.detailView=null;let r=document.createElement("div");if(r.className="page",r.setAttribute("data-page-number",this.id),r.setAttribute("role","region"),r.setAttribute("data-l10n-id","pdfjs-page-landmark"),r.setAttribute("data-l10n-args",JSON.stringify({page:this.id})),this.div=r,this.#v(),t?.append(r),this._isStandalone){t?.style.setProperty("--scale-factor",this.scale*vo.PDF_TO_CSS_UNITS),this.pageColors?.background&&t?.style.setProperty("--page-bg-color",this.pageColors.background);let{optionalContentConfigPromise:s}=e;s&&s.then(o=>{s===this._optionalContentConfigPromise&&(this.#p.initialOptionalContent=o.hasInitialVisibility)}),e.l10n||this.l10n.translate(this.div)}}clone(e){let t=new n({container:null,eventBus:this.eventBus,pagesColors:this.pageColors,renderingQueue:this.renderingQueue,enableOptimizedPartialRendering:this.enableOptimizedPartialRendering,minDurationToUpdateCanvas:this.minDurationToUpdateCanvas,defaultViewport:this.viewport,id:e,layerProperties:this.#s,scale:this.scale,optionalContentConfigPromise:this._optionalContentConfigPromise,textLayerMode:this.#f,annotationMode:this.#e,imageResourcesPath:this.imageResourcesPath,enableDetailCanvas:this.enableDetailCanvas,maxCanvasPixels:this.maxCanvasPixels,maxCanvasDim:this.maxCanvasDim,capCanvasAreaFactor:this.capCanvasAreaFactor,enableAutoLinking:this.#i,commentManager:this.#n,l10n:this.l10n,clonedFrom:this});return t.setPdfPage(this.pdfPage),t}#y(e,t){let i=ane.get(t),r=this.#c[i];if(this.#c[i]=e,r){r.replaceWith(e);return}for(let s=i-1;s>=0;s--){let o=this.#c[s];if(o){o.after(e);return}}this.div.prepend(e)}#v(){let{div:e,viewport:t}=this;if(t.userUnit!==this.#m&&(t.userUnit!==1?e.style.setProperty("--user-unit",t.userUnit):e.style.removeProperty("--user-unit"),this.#m=t.userUnit),this.pdfPage){if(this.#u===t.rotation)return;this.#u=t.rotation}kM(e,t,!0,!1)}updatePageNumber(e){if(this.id===e)return;this.id=e,this.renderingId=`page${e}`,this.pdfPage&&(this.pdfPage.pageNumber=e),this.setPageLabel(this.pageLabel);let{div:t}=this;t.setAttribute("data-page-number",e),t.setAttribute("data-l10n-args",JSON.stringify({page:e})),this._textHighlighter.pageIdx=e-1,this.annotationEditorLayer?.updatePageIndex(e-1)}setPdfPage(e){this._isStandalone&&(this.pageColors?.foreground==="CanvasText"||this.pageColors?.background==="Canvas")&&(this._container?.style.setProperty("--hcm-highlight-filter",e.filterFactory.addHighlightHCMFilter("highlight","CanvasText","Canvas","HighlightText","Highlight")),this._container?.style.setProperty("--hcm-highlight-selected-filter",e.filterFactory.addHighlightHCMFilter("highlight_selected","CanvasText","Canvas","HighlightText","Highlight"))),this.pdfPage=e,this.pdfPageRotate=e.rotate;let t=(this.rotation+this.pdfPageRotate)%360;this.viewport=e.getViewport({scale:this.scale*vo.PDF_TO_CSS_UNITS,rotation:t}),this.#v(),this.reset()}destroy(){this.reset(),this.pdfPage?.cleanup()}deleteMe(e){if(e){this.div.remove();return}this.destroy(),this.#s.annotationEditorUIManager?.deletePage(this.id)}hasEditableAnnotations(){return!!this.annotationLayer?.hasEditableAnnotations()}get _textHighlighter(){return Uh(this,"_textHighlighter",new B4({pageIndex:this.id-1,eventBus:this.eventBus,findController:this.#s.findController}))}#b(e,t){this.eventBus.dispatch(e,{source:this,pageNumber:this.id,error:t})}async#C(){let e=null;try{await this.annotationLayer.render({viewport:this.viewport,intent:"display",structTreeLayer:this.structTreeLayer})}catch(t){console.error("#renderAnnotationLayer:",t),e=t}finally{this.#b("annotationlayerrendered",e)}}async#E(){let e=null;try{await this.annotationEditorLayer.render({viewport:this.viewport,intent:"display"})}catch(t){console.error("#renderAnnotationEditorLayer:",t),e=t}finally{this.#b("annotationeditorlayerrendered",e)}}async#A(){try{await this.drawLayer.render({intent:"display"})}catch(e){console.error("#renderDrawLayer:",e)}}async#x(){let e=null;try{let t=await this.xfaLayer.render({viewport:this.viewport,intent:"display"});t?.textDivs&&this._textHighlighter&&this.#P(t.textDivs)}catch(t){console.error("#renderXfaLayer:",t),e=t}finally{this.xfaLayer?.div&&(this.l10n.pause(),this.#y(this.xfaLayer.div,"xfaLayer"),this.l10n.resume()),this.#b("xfalayerrendered",e)}}async#w(){if(!this.textLayer)return;let e=null;try{await this.textLayer.render({viewport:this.viewport})}catch(t){if(t instanceof Ete)return;console.error("#renderTextLayer:",t),e=t}this.#b("textlayerrendered",e),this.#T()}async#T(){if(!this.textLayer)return;let e=await this.structTreeLayer?.render();e&&(this.l10n.pause(),this.structTreeLayer?.updateTextLayer(),this.canvas&&e.parentNode!==this.canvas&&this.canvas.append(e),this.l10n.resume()),this.structTreeLayer?.show()}async#P(e){let t=await this.pdfPage.getTextContent(),i=[];for(let r of t.items)i.push(r.str);this._textHighlighter.setTextMapping(e,i),this._textHighlighter.enable()}async#k(e){let t=null;try{if(await e,!this.annotationLayer)return;await this.annotationLayer.injectLinkAnnotations(R4.processLinks(this))}catch(i){console.error("#injectLinkAnnotations:",i),t=i}}_resetCanvas(){super._resetCanvas(),this.#l=null}reset({keepAnnotationLayer:e=!1,keepAnnotationEditorLayer:t=!1,keepXfaLayer:i=!1,keepTextLayer:r=!1,keepCanvasWrapper:s=!1,preserveDetailViewState:o=!1}={}){let a=this.pdfPage?._pdfBug??!1;this.cancelRendering({keepAnnotationLayer:e,keepAnnotationEditorLayer:t,keepXfaLayer:i,keepTextLayer:r}),this.renderingState=Tt.INITIAL;let u=this.div,l=u.childNodes,c=e&&this.annotationLayer?.div||null,d=t&&this.annotationEditorLayer?.div||null,f=i&&this.xfaLayer?.div||null,m=r&&this.textLayer?.div||null,y=s&&this.#t||null;for(let g=l.length-1;g>=0;g--){let b=l[g];switch(b){case c:case d:case f:case m:case y:continue}if(a&&b.classList.contains("pdfBugGroupsLayer"))continue;b.remove();let v=this.#c.indexOf(b);v>=0&&(this.#c[v]=null)}u.removeAttribute("data-loaded"),c&&this.annotationLayer.hide(),d&&this.annotationEditorLayer.hide(),f&&this.xfaLayer.hide(),m&&this.textLayer.hide(),this.structTreeLayer?.hide(),!s&&this.#t&&(this.#t=null,this._resetCanvas()),o||(this.detailView?.reset({keepCanvas:s}),s||(this.detailView=null))}toggleEditingMode(e){this.#o=e,this.hasEditableAnnotations()&&this.reset({keepAnnotationLayer:!0,keepAnnotationEditorLayer:!0,keepXfaLayer:!0,keepTextLayer:!0,keepCanvasWrapper:!0})}updateVisibleArea(e){this.enableDetailCanvas&&(this.#a&&this.maxCanvasPixels>0&&e?(this.detailView??=new O4({pageView:this,enableOptimizedPartialRendering:this.enableOptimizedPartialRendering}),this.detailView.update({visibleArea:e})):this.detailView&&(this.detailView.reset(),this.detailView=null))}update({scale:e=0,rotation:t=null,optionalContentConfigPromise:i=null,drawingDelay:r=-1}){this.scale=e||this.scale,typeof t=="number"&&(this.rotation=t),i instanceof Promise&&(this._optionalContentConfigPromise=i,i.then(o=>{i===this._optionalContentConfigPromise&&(this.#p.initialOptionalContent=o.hasInitialVisibility)})),this.#p.directDrawing=!0;let s=(this.rotation+this.pdfPageRotate)%360;if(this.viewport=this.viewport.clone({scale:this.scale*vo.PDF_TO_CSS_UNITS,rotation:s}),this.#v(),this._isStandalone&&this._container?.style.setProperty("--scale-factor",this.viewport.scale),this.#I(),this.canvas){let o=this.#r&&this.#a,a=r>=0&&r<1e3;if(a||o){a&&!o&&this.renderingState!==Tt.FINISHED&&(this.cancelRendering({keepAnnotationLayer:!0,keepAnnotationEditorLayer:!0,keepXfaLayer:!0,keepTextLayer:!0,cancelExtraDelay:r}),this.renderingState=Tt.FINISHED,this.#p.directDrawing=!1),this.cssTransform({redrawAnnotationLayer:!0,redrawAnnotationEditorLayer:!0,redrawXfaLayer:!0,redrawTextLayer:!a,hideTextLayer:a}),a||(this.detailView?.update({underlyingViewUpdated:!0}),this.dispatchPageRendered(!0,!1));return}}this.cssTransform({}),this.reset({keepAnnotationLayer:!0,keepAnnotationEditorLayer:!0,keepXfaLayer:!0,keepTextLayer:!0,keepCanvasWrapper:!0,preserveDetailViewState:!0}),this.detailView?.update({underlyingViewUpdated:!0})}#I(){let{width:e,height:t}=this.viewport,i=this.outputScale=new Am;if(this.maxCanvasPixels===0){let r=1/this.scale;i.sx*=r,i.sy*=r,this.#a=!0}else if(this.#a=i.limitCanvas(e,t,this.maxCanvasPixels,this.maxCanvasDim,this.capCanvasAreaFactor),this.#a&&this.enableDetailCanvas){let r=this.enableOptimizedPartialRendering?4:2;i.sx/=r,i.sy/=r}}cancelRendering({keepAnnotationLayer:e=!1,keepAnnotationEditorLayer:t=!1,keepXfaLayer:i=!1,keepTextLayer:r=!1,cancelExtraDelay:s=0}={}){super.cancelRendering({cancelExtraDelay:s}),this.textLayer&&(!r||!this.textLayer.div)&&(this.textLayer.cancel(),this.textLayer=null),this.annotationLayer&&(!e||!this.annotationLayer.div)&&(this.annotationLayer.cancel(),this.annotationLayer=null,this._annotationCanvasMap=null),this.structTreeLayer&&!this.textLayer&&(this.structTreeLayer=null),this.annotationEditorLayer&&(!t||!this.annotationEditorLayer.div)&&(this.drawLayer&&(this.drawLayer.cancel(),this.drawLayer=null),this.annotationEditorLayer.cancel(),this.annotationEditorLayer=null),this.xfaLayer&&(!i||!this.xfaLayer.div)&&(this.xfaLayer.cancel(),this.xfaLayer=null,this._textHighlighter?.disable())}cssTransform({redrawAnnotationLayer:e=!1,redrawAnnotationEditorLayer:t=!1,redrawXfaLayer:i=!1,redrawTextLayer:r=!1,hideTextLayer:s=!1}){let{canvas:o}=this;if(!o)return;let a=this.#l;if(this.viewport!==a){let u=(360+this.viewport.rotation-a.rotation)%360;if(u===90||u===270){let{width:l,height:c}=this.viewport,d=c/l,f=l/c;o.style.transform=`rotate(${u}deg) scale(${d},${f})`}else o.style.transform=u===0?"":`rotate(${u}deg)`}e&&this.annotationLayer&&this.#C(),t&&this.annotationEditorLayer&&(this.drawLayer&&this.#A(),this.#E()),i&&this.xfaLayer&&this.#x(),this.textLayer&&(s?(this.textLayer.hide(),this.structTreeLayer?.hide()):r&&this.#w())}get width(){return this.viewport.width}get height(){return this.viewport.height}getPagePoint(e,t){return this.viewport.convertToPdfPoint(e,t)}_ensureCanvasWrapper(){let e=this.#t;return e||(e=this.#t=document.createElement("div"),e.classList.add("canvasWrapper"),this.#y(e,"canvasWrapper")),e}_getRenderingContext(e,t,i){return{canvas:e,transform:t,viewport:this.viewport,annotationMode:this.#e,optionalContentConfigPromise:this._optionalContentConfigPromise,annotationCanvasMap:this._annotationCanvasMap,pageColors:this.pageColors,isEditing:this.#o,recordOperations:i}}async draw(){this.renderingState!==Tt.INITIAL&&(console.error("Must be in new state before drawing"),this.reset());let{div:e,l10n:t,pdfPage:i,viewport:r}=this;if(!i)throw this.renderingState=Tt.FINISHED,new Error("pdfPage is not loaded");this.renderingState=Tt.RUNNING;let s=this._ensureCanvasWrapper();if(!this.textLayer&&this.#f!==ks.DISABLE&&!i.isPureXfa&&(this._accessibilityManager||=new N4,this.textLayer=new _m({pdfPage:i,highlighter:this._textHighlighter,accessibilityManager:this._accessibilityManager,enablePermissions:this.#f===ks.ENABLE_PERMISSIONS,onAppend:S=>{this.l10n.pause(),this.#y(S,"textLayer"),this.l10n.resume()}})),!this.annotationLayer&&this.#e!==_s.DISABLE){let{annotationStorage:S,annotationEditorUIManager:C,downloadManager:T,enableComment:_,enableScripting:k,fieldObjectsPromise:L,hasJSActionsPromise:M,linkService:N}=this.#s;this._annotationCanvasMap||=new Map,this.annotationLayer=new Cm({pdfPage:i,annotationStorage:S,imageResourcesPath:this.imageResourcesPath,renderForms:this.#e===_s.ENABLE_FORMS,linkService:N,downloadManager:T,enableComment:_,enableScripting:k,hasJSActionsPromise:M,fieldObjectsPromise:L,annotationCanvasMap:this._annotationCanvasMap,accessibilityManager:this._accessibilityManager,annotationEditorUIManager:C,commentManager:this.#n,onAppend:O=>{this.#y(O,"annotationLayer")}})}let{width:o,height:a}=r;this.#l=r;let{canvas:u,prevCanvas:l}=this._createCanvas(S=>{s.prepend(S)});u.setAttribute("role","presentation"),this.outputScale||this.#I();let{outputScale:c}=this;this.#r=this.#a;let d=J9(c.sx),f=J9(c.sy),m=u.width=pm(gm(o*c.sx),d[0]),y=u.height=pm(gm(a*c.sy),f[0]),g=pm(gm(o),d[1]),b=pm(gm(a),f[1]);c.sx=m/g,c.sy=y/b,this.#h!==d[1]&&(e.style.setProperty("--scale-round-x",`${d[1]}px`),this.#h=d[1]),this.#d!==f[1]&&(e.style.setProperty("--scale-round-y",`${f[1]}px`),this.#d=f[1]);let v=this.enableOptimizedPartialRendering&&this.#r&&!this.recordedBBoxes,A=c.scaled?[c.sx,0,0,c.sy,0,0]:null,w=this._drawCanvas(this._getRenderingContext(u,A,v),()=>{l?.remove(),this._resetCanvas()},S=>{this.#p.regularAnnotations=!S.separateAnnots,this.dispatchPageRendered(!1,!1)}).then(async()=>{if(this.renderingState!==Tt.FINISHED)return;this.structTreeLayer||=new km(i,r.rawDims);let S=this.#w();this.annotationLayer&&(await this.#C(),this.#i&&this.annotationLayer&&this.textLayer&&await this.#k(S));let{annotationEditorUIManager:C}=this.#s;C&&(this.drawLayer||=new M4,await this.#A(),this.drawLayer.setParent(s),(this.annotationLayer||this.#e===_s.DISABLE)&&(this.annotationEditorLayer||=new _4({uiManager:C,pageIndex:this.id-1,l10n:t,structTreeLayer:this.structTreeLayer,accessibilityManager:this._accessibilityManager,annotationLayer:this.annotationLayer?.annotationLayer,textLayer:this.textLayer,drawLayer:this.drawLayer.getDrawLayer(),clonedFrom:this.#g?.annotationEditorLayer,onAppend:T=>{this.#y(T,"annotationEditorLayer")}}),this.#g=null,this.#E()))});if(i.isPureXfa){if(!this.xfaLayer){let{annotationStorage:S,linkService:C}=this.#s;this.xfaLayer=new Pm({pdfPage:i,annotationStorage:S,linkService:C})}this.#x()}return e.setAttribute("data-loaded",!0),this.dispatchPageRender(),w}setPageLabel(e){this.pageLabel=typeof e=="string"?e:null,this.div.setAttribute("data-l10n-args",JSON.stringify({page:this.pageLabel??this.id})),this.pageLabel!==null?this.div.setAttribute("data-page-label",this.pageLabel):this.div.removeAttribute("data-page-label")}get thumbnailCanvas(){let{directDrawing:e,initialOptionalContent:t,regularAnnotations:i}=this.#p;return e&&t&&i?this.canvas:null}};D4=class{constructor(e){this._ready=new Promise((t,i)=>{import(e).then(s=>{t(s.QuickJSSandbox())}).catch(i)})}async createSandbox(e){(await this._ready).create(e)}async dispatchEventInSandbox(e){let t=await this._ready;setTimeout(()=>t.dispatchEvent(e),0)}async destroySandbox(){(await this._ready).nukeSandbox()}},F4=class{#e=null;#t=null;#n=null;#i=null;#r=null;#o=null;#s=null;#a=null;#l=!1;#u=null;#h=null;constructor({eventBus:e,externalServices:t=null,docProperties:i=null}){this.#r=e,this.#o=t,this.#n=i}setViewer(e){this.#a=e}async setDocument(e){if(this.#s&&await this.#c(),this.#s=e,!e)return;let[t,i,r]=await Promise.all([e.getFieldObjects(),e.getCalculationOrderIds(),e.getJSActions()]);if(!t&&!r){await this.#c();return}if(e!==this.#s)return;try{this.#u=this.#p()}catch(a){console.error("setDocument:",a),await this.#c();return}let s=this.#r;this.#i=new AbortController;let{signal:o}=this.#i;s._on("updatefromsandbox",a=>{a?.source===window&&this.#d(a.detail)},{signal:o}),s._on("dispatcheventinsandbox",a=>{this.#u?.dispatchEventInSandbox(a.detail)},{signal:o}),s._on("pagechanging",({pageNumber:a,previous:u})=>{a!==u&&(this.#m(u),this.#f(a))},{signal:o}),s._on("pagerendered",({pageNumber:a})=>{this._pageOpenPending.has(a)&&a===this.#a.currentPageNumber&&this.#f(a)},{signal:o}),s._on("pagesdestroy",async()=>{await this.#m(this.#a.currentPageNumber),await this.#u?.dispatchEventInSandbox({id:"doc",name:"WillClose"}),this.#e?.resolve()},{signal:o});try{let a=await this.#n(e);if(e!==this.#s)return;await this.#u.createSandbox({objects:t,calculationOrder:i,appInfo:{platform:navigator.platform,language:navigator.language},docInfo:{...a,actions:r}}),s.dispatch("sandboxcreated",{source:this})}catch(a){console.error("setDocument:",a),await this.#c();return}await this.#u?.dispatchEventInSandbox({id:"doc",name:"Open"}),await this.#f(this.#a.currentPageNumber,!0),Promise.resolve().then(()=>{e===this.#s&&(this.#l=!0)})}async dispatchWillSave(){return this.#u?.dispatchEventInSandbox({id:"doc",name:"WillSave"})}async dispatchDidSave(){return this.#u?.dispatchEventInSandbox({id:"doc",name:"DidSave"})}async dispatchWillPrint(){if(this.#u){await this.#h?.promise,this.#h=Promise.withResolvers();try{await this.#u.dispatchEventInSandbox({id:"doc",name:"WillPrint"})}catch(e){throw this.#h.resolve(),this.#h=null,e}await this.#h.promise}}async dispatchDidPrint(){return this.#u?.dispatchEventInSandbox({id:"doc",name:"DidPrint"})}get destroyPromise(){return this.#t?.promise||null}get ready(){return this.#l}get _pageOpenPending(){return Uh(this,"_pageOpenPending",new Set)}get _visitedPages(){return Uh(this,"_visitedPages",new Map)}async#d(e){let t=this.#a,i=t.isInPresentationMode||t.isChangingPresentationMode,{id:r,siblings:s,command:o,value:a}=e;if(!r){switch(o){case"clear":console.clear();break;case"error":console.error(a);break;case"layout":if(!i){let l=Vte(a);t.spreadMode=l.spreadMode}break;case"page-num":t.currentPageNumber=a+1;break;case"print":await t.pagesPromise,this.#r.dispatch("print",{source:this});break;case"println":console.log(a);break;case"zoom":i||(t.currentScaleValue=a);break;case"SaveAs":this.#r.dispatch("download",{source:this});break;case"FirstPage":t.currentPageNumber=1;break;case"LastPage":t.currentPageNumber=t.pagesCount;break;case"NextPage":t.nextPage();break;case"PrevPage":t.previousPage();break;case"ZoomViewIn":i||t.increaseScale();break;case"ZoomViewOut":i||t.decreaseScale();break;case"WillPrintFinished":this.#h?.resolve(),this.#h=null;break}return}if(i&&e.focus)return;delete e.id,delete e.siblings;let u=s?[r,...s]:[r];for(let l of u){let c=document.querySelector(`[data-element-id="${l}"]`);c?c.dispatchEvent(new CustomEvent("updatefromsandbox",{detail:e})):this.#s?.annotationStorage.setValue(l,e)}}async#f(e,t=!1){let i=this.#s,r=this._visitedPages;if(t&&(this.#e=Promise.withResolvers()),!this.#e)return;let s=this.#a.getPageView(e-1);if(s?.renderingState!==Tt.FINISHED){this._pageOpenPending.add(e);return}this._pageOpenPending.delete(e);let o=(async()=>{let a=await(r.has(e)?null:s.pdfPage?.getJSActions());i===this.#s&&await this.#u?.dispatchEventInSandbox({id:"page",name:"PageOpen",pageNumber:e,actions:a})})();r.set(e,o)}async#m(e){let t=this.#s,i=this._visitedPages;if(!this.#e||this._pageOpenPending.has(e))return;let r=i.get(e);r&&(i.set(e,null),await r,t===this.#s&&await this.#u?.dispatchEventInSandbox({id:"page",name:"PageClose",pageNumber:e}))}#p(){if(this.#t=Promise.withResolvers(),this.#u)throw new Error("#initScripting: Scripting already exists.");return this.#o.createScripting()}async#c(){if(!this.#u){this.#s=null,this.#t?.resolve();return}this.#e&&(await Promise.race([this.#e.promise,new Promise(e=>{setTimeout(e,1e3)})]).catch(()=>{}),this.#e=null),this.#s=null;try{await this.#u.destroySandbox()}catch{}this.#h?.reject(new Error("Scripting destroyed.")),this.#h=null,this.#i?.abort(),this.#i=null,this._pageOpenPending.clear(),this._visitedPages.clear(),this.#u=null,this.#l=!1,this.#t?.resolve()}},H4=class extends F4{constructor(e){e.externalServices||window.addEventListener("updatefromsandbox",t=>{e.eventBus.dispatch("updatefromsandbox",{source:window,detail:t.detail})}),e.externalServices||={createScripting:()=>new D4(e.sandboxBundleSrc)},e.docProperties||=t=>une(t),super(e)}},lne=3e4,U4=class{#e=null;#t=null;#n=null;#i=null;isThumbnailViewEnabled=!1;onIdle=null;printing=!1;constructor(){Object.defineProperty(this,"hasViewer",{value:()=>!!this.#i})}setViewer(e){this.#i=e}setThumbnailViewer(e){this.#n=e}isHighestPriority(e){return this.#e===e.renderingId}renderHighestPriority(e){this.#t&&(clearTimeout(this.#t),this.#t=null),!this.#i.forceRendering(e)&&(this.isThumbnailViewEnabled&&this.#n?.forceRendering()||this.printing||this.onIdle&&(this.#t=setTimeout(this.onIdle.bind(this),lne)))}getHighestPriority(e,t,i,r=!1,s=!1){let o=e.views,a=o.length;if(a===0)return null;for(let f=0;f<a;f++){let m=o[f].view;if(!this.isViewFinished(m))return m}if(!s)for(let f=0;f<a;f++){let{detailView:m}=o[f].view;if(m&&!this.isViewFinished(m))return m}let u=e.first.id,l=e.last.id;if(l-u+1>a){let f=e.ids;for(let m=1,y=l-u;m<y;m++){let g=i?u+m:l-m;if(f.has(g))continue;let b=t[g-1];if(!this.isViewFinished(b))return b}}let c=i?l:u-2,d=t[c];return d&&!this.isViewFinished(d)||r&&(c+=i?1:-1,d=t[c],d&&!this.isViewFinished(d))?d:null}isViewFinished(e){return e.renderingState===Tt.FINISHED}renderView(e){switch(e.renderingState){case Tt.FINISHED:return!1;case Tt.PAUSED:this.#e=e.renderingId,e.resume();break;case Tt.RUNNING:this.#e=e.renderingId;break;case Tt.INITIAL:this.#e=e.renderingId,e.draw().finally(()=>{this.renderHighestPriority()}).catch(t=>{t instanceof f4||console.error("renderView:",t)});break}return!0}},EM=10,ym={FORCE_SCROLL_MODE_PAGE:1e4,FORCE_LAZY_PAGE_INIT:5e3,PAUSE_EAGER_PAGE_INIT:250};j4=class{#e=new Set;#t=0;constructor(e){this.#t=e}push(e){let t=this.#e;t.has(e)&&t.delete(e),t.add(e),t.size>this.#t&&this.#n()}resize(e,t=null){this.#t=e;let i=this.#e;if(t){let r=i.size,s=1;for(let o of i)if(t.has(o.id)&&(i.delete(o),i.add(o)),++s>r)break}for(;i.size>this.#t;)this.#n()}has(e){return this.#e.has(e)}[Symbol.iterator](){return this.#e.keys()}#n(){let e=this.#e.keys().next().value;e?.destroy(),this.#e.delete(e)}},lc=class{#e=null;#t=null;#n=null;#i=Kn.NONE;#r=null;#o=_s.ENABLE_FORMS;#s=null;#a=null;#l=null;#u=!1;#h=!1;#d=!1;#f=!1;#m=!1;#p=!0;#c=null;#g=0;#y=null;#v=!0;#b=null;#C=null;#E=null;#A=!1;#x=null;#w=!1;#T=0;#P=new ResizeObserver(this.#Q.bind(this));#k=null;#I=null;#N=null;#M=!0;#O=ks.ENABLE;#B=null;#L=null;constructor(e){let t="5.5.207";if(Y9!==t)throw new Error(`The API version "${Y9}" does not match the Viewer version "${t}".`);if(this.container=e.container,this.viewer=e.viewer||e.container.firstElementChild,this.#B=e.viewerAlert||null,this.container?.tagName!=="DIV"||this.viewer?.tagName!=="DIV")throw new Error("Invalid `container` and/or `viewer` option.");if(this.container.offsetParent&&getComputedStyle(this.container).position!=="absolute")throw new Error("The `container` must be absolutely positioned.");this.#P.observe(this.container),this.eventBus=e.eventBus,this.linkService=e.linkService||new Wh,this.downloadManager=e.downloadManager||null,this.findController=e.findController||null,this.#t=e.altTextManager||null,this.#s=e.commentManager||null,this.#N=e.signatureManager||null,this.#l=e.editorUndoBar||null,this.findController&&(this.findController.onIsPageVisible=r=>this._getVisiblePages().ids.has(r)),this._scriptingManager=e.scriptingManager||null,this.#O=e.textLayerMode??ks.ENABLE,this.#o=e.annotationMode??_s.ENABLE_FORMS,this.#i=e.annotationEditorMode??Kn.NONE,this.#n=e.annotationEditorHighlightColors||null,this.#h=e.enableHighlightFloatingButton===!0,this.#f=e.enableUpdatedAddImage===!0,this.#m=e.enableNewAltTextWhenAddingImage===!0,this.imageResourcesPath=e.imageResourcesPath||"",this.enablePrintAutoRotate=e.enablePrintAutoRotate||!1,this.removePageBorders=e.removePageBorders||!1,this.maxCanvasPixels=e.maxCanvasPixels,this.maxCanvasDim=e.maxCanvasDim,this.capCanvasAreaFactor=e.capCanvasAreaFactor,this.enableDetailCanvas=e.enableDetailCanvas??!0,this.enableOptimizedPartialRendering=e.enableOptimizedPartialRendering??!1,this.l10n=e.l10n,this.l10n||=new uc,this.#d=e.enablePermissions||!1,this.pageColors=e.pageColors||null,this.#y=e.mlManager||null,this.#u=e.enableHWA||!1,this.#M=e.supportsPinchToZoom!==!1,this.#p=e.enableAutoLinking!==!1,this.#g=e.minDurationToUpdateCanvas??500,this.defaultRenderingQueue=!e.renderingQueue,this.defaultRenderingQueue?(this.renderingQueue=new U4,this.renderingQueue.setViewer(this)):this.renderingQueue=e.renderingQueue;let{abortSignal:i}=e;i?.addEventListener("abort",()=>{this.#P.disconnect(),this.#P=null},{once:!0}),this.scroll=Hte(this.container,this._scrollUpdate.bind(this),i),this.presentationModeState=rc.UNKNOWN,this._resetView(),this.removePageBorders&&this.viewer.classList.add("removePageBorders"),this.#j(),this.eventBus._on("thumbnailrendered",({pageNumber:r,pdfPage:s})=>{let o=this._pages[r-1];this.#e.has(o)||s?.cleanup()}),e.l10n||this.l10n.translate(this.container)}get printingAllowed(){return this.#v}get pagesCount(){return this._pages.length}getPageView(e){return this._pages[e]}getCachedPageViews(){return new Set(this.#e)}get pageViewsReady(){return this._pages.every(e=>e?.pdfPage)}get renderForms(){return this.#o===_s.ENABLE_FORMS}get enableScripting(){return!!this._scriptingManager}get currentPageNumber(){return this._currentPageNumber}set currentPageNumber(e){if(!Number.isInteger(e))throw new Error("Invalid page number.");this.pdfDocument&&(this._setCurrentPageNumber(e,!0)||console.error(`currentPageNumber: "${e}" is not a valid page.`))}_setCurrentPageNumber(e,t=!1){if(this._currentPageNumber===e)return t&&this.#G(),!0;if(!(0<e&&e<=this.pagesCount))return!1;let i=this._currentPageNumber;return this._currentPageNumber=e,this.eventBus.dispatch("pagechanging",{source:this,pageNumber:e,pageLabel:this._pageLabels?.[e-1]??null,previous:i}),t&&this.#G(),!0}get currentPageLabel(){return this._pageLabels?.[this._currentPageNumber-1]??null}set currentPageLabel(e){if(!this.pdfDocument)return;let t=e|0;if(this._pageLabels){let i=this._pageLabels.indexOf(e);i>=0&&(t=i+1)}this._setCurrentPageNumber(t,!0)||console.error(`currentPageLabel: "${e}" is not a valid page.`)}get currentScale(){return this._currentScale!==o4?this._currentScale:_M}set currentScale(e){if(isNaN(e))throw new Error("Invalid numeric scale.");this.pdfDocument&&this.#U(e,{noScroll:!1})}get currentScaleValue(){return this._currentScaleValue}set currentScaleValue(e){this.pdfDocument&&this.#U(e,{noScroll:!1})}get pagesRotation(){return this._pagesRotation}set pagesRotation(e){if(!RM(e))throw new Error("Invalid pages rotation angle.");if(!this.pdfDocument||(e%=360,e<0&&(e+=360),this._pagesRotation===e))return;this._pagesRotation=e;let t=this._currentPageNumber;this.refresh(!0,{rotation:e}),this._currentScaleValue&&this.#U(this._currentScaleValue,{noScroll:!0}),this.eventBus.dispatch("rotationchanging",{source:this,pagesRotation:e,pageNumber:t}),this.defaultRenderingQueue&&this.update()}get firstPagePromise(){return this.pdfDocument?this._firstPageCapability.promise:null}get onePageRendered(){return this.pdfDocument?this._onePageRenderedCapability.promise:null}get pagesPromise(){return this.pdfDocument?this._pagesCapability.promise:null}get _layerProperties(){let e=this;return Uh(this,"_layerProperties",{get annotationEditorUIManager(){return e.#r},get annotationStorage(){return e.pdfDocument?.annotationStorage},get downloadManager(){return e.downloadManager},get enableComment(){return!!e.#s},get enableScripting(){return!!e._scriptingManager},get fieldObjectsPromise(){return e.pdfDocument?.getFieldObjects()},get findController(){return e.findController},get hasJSActionsPromise(){return e.pdfDocument?.hasJSActions()},get linkService(){return e.linkService}})}#z(e){let t={annotationEditorMode:this.#i,annotationMode:this.#o,textLayerMode:this.#O};return e?(this.#v=e.includes(nc.PRINT_HIGH_QUALITY)||e.includes(nc.PRINT),this.eventBus.dispatch("printingallowed",{source:this,isAllowed:this.#v}),!e.includes(nc.COPY)&&this.#O===ks.ENABLE&&(t.textLayerMode=ks.ENABLE_PERMISSIONS),e.includes(nc.MODIFY_CONTENTS)||(t.annotationEditorMode=Kn.DISABLE),!e.includes(nc.MODIFY_ANNOTATIONS)&&!e.includes(nc.FILL_INTERACTIVE_FORMS)&&this.#o===_s.ENABLE_FORMS&&(t.annotationMode=_s.ENABLE),t):(this.#v=!0,this.eventBus.dispatch("printingallowed",{source:this,isAllowed:this.#v}),t)}async#_(e){if(document.visibilityState==="hidden"||!this.container.offsetParent||this._getVisiblePages().views.length===0)return;let t=Promise.withResolvers(),i=new AbortController;document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&t.resolve()},{signal:AbortSignal.any([e,i.signal])}),await Promise.race([this._onePageRenderedCapability.promise,t.promise]),i.abort()}async getAllText(){let e=[],t=[];for(let i=1,r=this.pdfDocument.numPages;i<=r;++i){if(this.#w)return null;t.length=0;let s=await this.pdfDocument.getPage(i),{items:o}=await s.getTextContent();for(let a of o)a.str&&t.push(a.str),a.hasEOL&&t.push(`
|
|
603
603
|
`);e.push(Fh(t.join("")))}return e.join(`
|
|
604
|
-
`)}#S(e,t){let i=document.getSelection(),{focusNode:r,anchorNode:s}=i;if(s&&r&&i.containsNode(this.#x)){if(this.#A||e===ks.ENABLE_PERMISSIONS){p4(t);return}this.#A=!0;let{classList:o}=this.viewer;o.add("copyAll");let a=new AbortController;window.addEventListener("keydown",u=>this.#w=u.key==="Escape",{signal:a.signal}),this.getAllText().then(async u=>{u!==null&&await navigator.clipboard.writeText(u)}).catch(u=>{console.warn(`Something goes wrong when extracting the text: ${u.message}`)}).finally(()=>{this.#A=!1,this.#w=!1,a.abort(),o.remove("copyAll")}),p4(t)}}setDocument(e){if(this.pdfDocument&&(this.eventBus.dispatch("pagesdestroy",{source:this}),this._cancelRendering(),this._resetView(),this.findController?.setDocument(null),this._scriptingManager?.setDocument(null),this.#r?.destroy(),this.#r=null,this.#i=Kn.NONE,this.#v=!0),this.pdfDocument=e,!e)return;let t=e.numPages,i=e.getPage(1),r=e.getOptionalContentConfig({intent:"display"}),s=this.#d?e.getPermissions():Promise.resolve(),{eventBus:o,pageColors:a,viewer:u}=this;this.#c=new AbortController;let{signal:l}=this.#c;if(t>ym.FORCE_SCROLL_MODE_PAGE){console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document.");let f=this._scrollMode=ot.PAGE;o.dispatch("scrollmodechanged",{source:this,mode:f})}this._pagesCapability.promise.then(()=>{o.dispatch("pagesloaded",{source:this,pagesCount:t})},()=>{});let c=f=>{let m=this._pages[f.pageNumber-1];m&&this.#e.push(m)};o._on("pagerender",c,{signal:l});let d=f=>{f.cssTransform||f.isDetailView||(this._onePageRenderedCapability.resolve({timestamp:f.timestamp}),o._off("pagerendered",d))};o._on("pagerendered",d,{signal:l}),Promise.all([i,s]).then(([f,m])=>{if(e!==this.pdfDocument)return;this._firstPageCapability.resolve(f),this._optionalContentConfigPromise=r;let{annotationEditorMode:y,annotationMode:g,textLayerMode:b}=this.#z(m);if(b!==ks.DISABLE){let S=this.#x=document.createElement("div");S.id="hiddenCopyElement",u.before(S)}if(y!==Kn.DISABLE){let S=y;e.isPureXfa?console.warn("Warning: XFA-editing is not implemented."):CM(S)?(this.#r=new Ste(this.container,u,this.#B,this.#t,this.#s,this.#N,o,e,a,this.#n,this.#h,this.#f,this.#m,this.#y,this.#l,this.#M),o.dispatch("annotationeditoruimanager",{source:this,uiManager:this.#r}),S!==Kn.NONE&&(this.#ee(S),this.#r.updateMode(S))):console.error(`Invalid AnnotationEditor mode: ${S}`)}let v=this._scrollMode===ot.PAGE?null:u,A=this.currentScale,w=f.getViewport({scale:A*vo.PDF_TO_CSS_UNITS});u.style.setProperty("--scale-factor",w.scale),a?.background&&u.style.setProperty("--page-bg-color",a.background),(a?.foreground==="CanvasText"||a?.background==="Canvas")&&(u.style.setProperty("--hcm-highlight-filter",e.filterFactory.addHighlightHCMFilter("highlight","CanvasText","Canvas","HighlightText","Highlight")),u.style.setProperty("--hcm-highlight-selected-filter",e.filterFactory.addHighlightHCMFilter("highlight_selected","CanvasText","Canvas","HighlightText","ButtonText")));for(let S=1;S<=t;++S){let C=new Rm({container:v,eventBus:o,id:S,scale:A,defaultViewport:w.clone(),optionalContentConfigPromise:r,renderingQueue:this.renderingQueue,textLayerMode:b,annotationMode:g,imageResourcesPath:this.imageResourcesPath,maxCanvasPixels:this.maxCanvasPixels,maxCanvasDim:this.maxCanvasDim,capCanvasAreaFactor:this.capCanvasAreaFactor,enableDetailCanvas:this.enableDetailCanvas,enableOptimizedPartialRendering:this.enableOptimizedPartialRendering,pageColors:a,l10n:this.l10n,layerProperties:this._layerProperties,enableHWA:this.#u,enableAutoLinking:this.#p,minDurationToUpdateCanvas:this.#g,commentManager:this.#s});this._pages.push(C)}this._pages[0]?.setPdfPage(f),this._scrollMode===ot.PAGE?this.#R():this._spreadMode!==Fi.NONE&&this._updateSpreadMode(),o._on("annotationeditorlayerrendered",S=>{this.#r&&o.dispatch("annotationeditormodechanged",{source:this,mode:this.#i})},{once:!0,signal:l}),this.#_(l).then(async()=>{if(e!==this.pdfDocument)return;if(this.findController?.setDocument(e),this._scriptingManager?.setDocument(e),this.#x&&document.addEventListener("copy",this.#S.bind(this,b),{signal:l}),e.loadingParams.disableAutoFetch||t>ym.FORCE_LAZY_PAGE_INIT){this._pagesCapability.resolve();return}let S=t-1;if(S<=0){this._pagesCapability.resolve();return}for(let C=2;C<=t;++C){let T=e.getPage(C).then(_=>{let k=this._pages[C-1];k.pdfPage||k.setPdfPage(_),--S===0&&this._pagesCapability.resolve()},_=>{console.error(`Unable to get page ${C} to initialize viewer`,_),--S===0&&this._pagesCapability.resolve()});C%ym.PAUSE_EAGER_PAGE_INIT===0&&await T}}),o.dispatch("pagesinit",{source:this}),e.getMetadata().then(({info:S})=>{e===this.pdfDocument&&S.Language&&(u.lang=S.Language)}),this.defaultRenderingQueue&&this.update()}).catch(f=>{console.error("Unable to initialize viewer",f),this._pagesCapability.reject(f)})}onPagesEdited({pagesMapper:e,type:t,hasBeenCut:i,pageNumbers:r}){if(t==="copy"){this.#L=new Map;for(let l of r)this.#L.set(l,this._pages[l-1]);return}let s=t==="cut";if(s||t==="delete")for(let l of r)this._pages[l-1].deleteMe(s);this._currentPageNumber=0;let o=this._pages,a=this._pages=[];for(let l=1,c=e.pagesNumber;l<=c;l++){let d=e.getPrevPageNumber(l);if(d<0){let m=this.#L.get(-d);i?m.updatePageNumber(l):m=m.clone(l),a.push(m);continue}let f=o[d-1];a.push(f),f.updatePageNumber(l)}s||(this.#L=null);let u=this._scrollMode===ot.PAGE?null:this.viewer;if(u){u.replaceChildren();let l=document.createDocumentFragment();for(let c=0,d=e.pagesNumber;c<d;c++){let{div:f}=a[c];f.setAttribute("data-page-number",c+1),l.append(f)}u.append(l)}setTimeout(()=>{this.forceRendering()})}setPageLabels(e){if(this.pdfDocument){e?Array.isArray(e)&&this.pdfDocument.numPages===e.length?this._pageLabels=e:(this._pageLabels=null,console.error("setPageLabels: Invalid page labels.")):this._pageLabels=null;for(let t=0,i=this._pages.length;t<i;t++)this._pages[t].setPageLabel(this._pageLabels?.[t]??null)}}_resetView(){this._pages=[],this._currentPageNumber=1,this._currentScale=o4,this._currentScaleValue=null,this._pageLabels=null,this.#e=new j4(EM),this._location=null,this._pagesRotation=0,this._optionalContentConfigPromise=null,this._firstPageCapability=Promise.withResolvers(),this._onePageRenderedCapability=Promise.withResolvers(),this._pagesCapability=Promise.withResolvers(),this._scrollMode=ot.VERTICAL,this._previousScrollMode=ot.UNKNOWN,this._spreadMode=Fi.NONE,this.#k={previousPageNumber:1,scrollDown:!0,pages:[]},this.#c?.abort(),this.#c=null,this.viewer.textContent="",this._updateScrollMode(),this.viewer.removeAttribute("lang"),this.#x?.remove(),this.#x=null,this.#X(),this.#J()}#R(){if(this._scrollMode!==ot.PAGE)throw new Error("#ensurePageViewVisible: Invalid scrollMode value.");let e=this._currentPageNumber,t=this.#k,i=this.viewer;if(i.textContent="",t.pages.length=0,this._spreadMode===Fi.NONE&&!this.isInPresentationMode){let r=this._pages[e-1];i.append(r.div),t.pages.push(r)}else{let r=new Set,s=this._spreadMode-1;s===-1?r.add(e-1):e%2!==s?(r.add(e-1),r.add(e)):(r.add(e-2),r.add(e-1));let o=document.createElement("div");if(o.className="spread",this.isInPresentationMode){let a=document.createElement("div");a.className="dummyPage",o.append(a)}for(let a of r){let u=this._pages[a];u&&(o.append(u.div),t.pages.push(u))}i.append(o)}t.scrollDown=e>=t.previousPageNumber,t.previousPageNumber=e}_scrollUpdate(){this.pagesCount!==0&&(this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{this.#b=null,this.update()},100),this.update())}#D(e,t=null){let{div:i,id:r}=e;if(this._currentPageNumber!==r&&this._setCurrentPageNumber(r),this._scrollMode===ot.PAGE&&(this.#R(),this.update()),!t&&!this.isInPresentationMode){let s=i.offsetLeft+i.clientLeft,o=s+i.clientWidth,{scrollLeft:a,clientWidth:u}=this.container;(this._scrollMode===ot.HORIZONTAL||s<a||o>a+u)&&(t={left:0,top:0})}PM(i,t),!this._currentScaleValue&&this._location&&(this._location=null)}#W(e){return e===this._currentScale||Math.abs(e-this._currentScale)<1e-15}#Y(e,t,{noScroll:i=!1,preset:r=!1,drawingDelay:s=-1,origin:o=null}){if(this._currentScaleValue=t.toString(),this.#W(e)){r&&this.eventBus.dispatch("scalechanging",{source:this,scale:e,presetValue:t});return}this.viewer.style.setProperty("--scale-factor",e*vo.PDF_TO_CSS_UNITS);let a=s>=0&&s<1e3;this.refresh(!0,{scale:e,drawingDelay:a?s:-1}),a&&(this.#I=setTimeout(()=>{this.#I=null,this.refresh()},s));let u=this._currentScale;if(this._currentScale=e,!i){let l=this._currentPageNumber,c;if(this._location&&!(this.isInPresentationMode||this.isChangingPresentationMode)&&(l=this._location.pageNumber,c=[null,{name:"XYZ"},this._location.left,this._location.top,null]),this.scrollPageIntoView({pageNumber:l,destArray:c,allowNegativeOffset:!0}),Array.isArray(o)){let d=e/u-1,[f,m]=this.containerTopLeft;this.container.scrollLeft+=(o[0]-m)*d,this.container.scrollTop+=(o[1]-f)*d}}this.eventBus.dispatch("scalechanging",{source:this,scale:e,presetValue:r?t:void 0}),this.defaultRenderingQueue&&this.update()}get#q(){return this._spreadMode!==Fi.NONE&&this._scrollMode!==ot.HORIZONTAL?2:1}#U(e,t){let i=parseFloat(e);if(i>0)t.preset=!1,this.#Y(i,e,t);else{let r=this._pages[this._currentPageNumber-1];if(!r)return;let s=$9,o=Q9;this.isInPresentationMode?(s=o=4,this._spreadMode!==Fi.NONE&&(s*=2)):this.removePageBorders?s=o=0:this._scrollMode===ot.HORIZONTAL&&([s,o]=[o,s]);let a=(this.container.clientWidth-s)/r.width*r.scale/this.#q,u=(this.container.clientHeight-o)/r.height*r.scale;switch(e){case"page-actual":i=1;break;case"page-width":i=a;break;case"page-height":i=u;break;case"page-fit":i=Math.min(a,u);break;case"auto":let l=Z9(r)?a:Math.min(u,a);i=Math.min(Fte,l);break;default:console.error(`#setScale: "${e}" is an unknown zoom value.`);return}t.preset=!0,this.#Y(i,e,t)}}#G(){let e=this._pages[this._currentPageNumber-1];this.isInPresentationMode&&this.#U(this._currentScaleValue,{noScroll:!0}),this.#D(e)}pageLabelToPageNumber(e){if(!this._pageLabels)return null;let t=this._pageLabels.indexOf(e);return t<0?null:t+1}scrollPageIntoView({pageNumber:e,destArray:t=null,allowNegativeOffset:i=!1,ignoreDestinationZoom:r=!1,center:s=null}){if(!this.pdfDocument)return;let o=Number.isInteger(e)&&this._pages[e-1];if(!o){console.error(`scrollPageIntoView: "${e}" is not a valid pageNumber parameter.`);return}if(this.isInPresentationMode||!t){this._setCurrentPageNumber(e,!0);return}let a=0,u=0,l=0,c=0,d,f,m=o.rotation%180!==0,y=(m?o.height:o.width)/o.scale/vo.PDF_TO_CSS_UNITS,g=(m?o.width:o.height)/o.scale/vo.PDF_TO_CSS_UNITS,b=0;switch(t[1].name){case"XYZ":a=t[2],u=t[3],b=t[4],a=a!==null?a:0,u=u!==null?u:g;break;case"Fit":case"FitB":b="page-fit";break;case"FitH":case"FitBH":u=t[2],b="page-width",u===null&&this._location?(a=this._location.left,u=this._location.top):(typeof u!="number"||u<0)&&(u=g);break;case"FitV":case"FitBV":a=t[2],l=y,c=g,b="page-height";break;case"FitR":a=t[2],u=t[3],l=t[4]-a,c=t[5]-u;let S=$9,C=Q9;this.removePageBorders&&(S=C=0),d=(this.container.clientWidth-S)/l/vo.PDF_TO_CSS_UNITS,f=(this.container.clientHeight-C)/c/vo.PDF_TO_CSS_UNITS,b=Math.min(Math.abs(d),Math.abs(f));break;default:console.error(`scrollPageIntoView: "${t[1].name}" is not a valid destination type.`);return}if(r||(b&&b!==this._currentScale?this.currentScaleValue=b:this._currentScale===o4&&(this.currentScaleValue=Nte)),b==="page-fit"&&!t[4]){this.#D(o);return}let v=[o.viewport.convertToViewportPoint(a,u),o.viewport.convertToViewportPoint(a+l,u+c)],A=Math.min(v[0][0],v[1][0]),w=Math.min(v[0][1],v[1][1]);s?((s==="both"||s==="vertical")&&(w-=(this.container.clientHeight-Math.abs(v[1][1]-v[0][1]))/2),(s==="both"||s==="horizontal")&&(A-=(this.container.clientWidth-Math.abs(v[1][0]-v[0][0]))/2)):i||(A=Math.max(A,0),w=Math.max(w,0)),this.#D(o,{left:A,top:w})}_updateLocation(e){let t=this._currentScale,i=this._currentScaleValue,r=parseFloat(i)===t?Math.round(t*1e4)/100:i,s=e.id,o=this._pages[s-1],a=this.container,u=o.getPagePoint(a.scrollLeft-e.x,a.scrollTop-e.y),l=Math.round(u[0]),c=Math.round(u[1]),d=`#page=${s}`;this.isInPresentationMode||(d+=`&zoom=${r},${l},${c}`),this._location={pageNumber:s,scale:r,top:c,left:l,rotation:this._pagesRotation,pdfOpenParams:d}}update(){let e=this._getVisiblePages(),t=e.views,i=t.length;if(i===0)return;let r=Math.max(EM,2*i+1);this.#e.resize(r,e.ids);for(let{view:u,visibleArea:l}of t)u.updateVisibleArea(l);for(let u of this.#e)e.ids.has(u.id)||u.updateVisibleArea(null);this.renderingQueue.renderHighestPriority(e);let s=this._spreadMode===Fi.NONE&&(this._scrollMode===ot.PAGE||this._scrollMode===ot.VERTICAL),o=this._currentPageNumber,a=!1;for(let u of t){if(u.percent<100)break;if(u.id===o&&s){a=!0;break}}this._setCurrentPageNumber(a?this._currentPageNumber:t[0].id),this._updateLocation(e.first),this.eventBus.dispatch("updateviewarea",{source:this,location:this._location})}#F(){let e=this._getVisiblePages(),t=[],{ids:i,views:r}=e;for(let s of r){let{view:o}=s;if(!o.hasEditableAnnotations()){i.delete(o.id);continue}t.push(s)}return t.length===0?null:(this.renderingQueue.renderHighestPriority({first:t[0],last:t.at(-1),views:t,ids:i}),i)}containsElement(e){return this.container.contains(e)}focus(){this.container.focus()}get _isContainerRtl(){return getComputedStyle(this.container).direction==="rtl"}get isInPresentationMode(){return this.presentationModeState===rc.FULLSCREEN}get isChangingPresentationMode(){return this.presentationModeState===rc.CHANGING}get isHorizontalScrollbarEnabled(){return this.isInPresentationMode?!1:this.container.scrollWidth>this.container.clientWidth}get isVerticalScrollbarEnabled(){return this.isInPresentationMode?!1:this.container.scrollHeight>this.container.clientHeight}_getVisiblePages(){let e=this._scrollMode===ot.PAGE?this.#k.pages:this._pages,t=this._scrollMode===ot.HORIZONTAL,i=t&&this._isContainerRtl;return jte({scrollEl:this.container,views:e,sortByVisibility:!0,horizontal:t,rtl:i})}cleanup(){for(let e of this._pages)e.renderingState!==Tt.FINISHED&&e.reset()}_cancelRendering(){for(let e of this._pages)e.cancelRendering()}async#V(e){if(e.pdfPage)return e.pdfPage;try{let t=await this.pdfDocument.getPage(e.id);return e.pdfPage||e.setPdfPage(t),t}catch(t){return console.error("Unable to get page for page view",t),null}}#Z(e){if(e.first?.id===1)return!0;if(e.last?.id===this.pagesCount)return!1;switch(this._scrollMode){case ot.PAGE:return this.#k.scrollDown;case ot.HORIZONTAL:return this.scroll.right}return this.scroll.down}forceRendering(e){let t=e||this._getVisiblePages(),i=this.#Z(t),r=this._spreadMode!==Fi.NONE&&this._scrollMode!==ot.HORIZONTAL,s=this.#I!==null||this.#b!==null&&t.views.some(a=>a.detailView?.renderingCancelled),o=this.renderingQueue.getHighestPriority(t,this._pages,i,r,s);return o?(this.#V(o).then(()=>{this.renderingQueue.renderView(o)}),!0):!1}get hasEqualPageSizes(){let e=this._pages[0];for(let t=1,i=this._pages.length;t<i;++t){let r=this._pages[t];if(r.width!==e.width||r.height!==e.height)return!1}return!0}getPagesOverview(){let e;return this._pages.map(t=>{let i=t.pdfPage.getViewport({scale:1}),r=Z9(i);if(e===void 0)e=r;else if(this.enablePrintAutoRotate&&r!==e)return{width:i.height,height:i.width,rotation:(i.rotation-90)%360};return{width:i.width,height:i.height,rotation:i.rotation}})}get optionalContentConfigPromise(){return this.pdfDocument?this._optionalContentConfigPromise?this._optionalContentConfigPromise:(console.error("optionalContentConfigPromise: Not initialized yet."),this.pdfDocument.getOptionalContentConfig({intent:"display"})):Promise.resolve(null)}set optionalContentConfigPromise(e){if(!(e instanceof Promise))throw new Error(`Invalid optionalContentConfigPromise: ${e}`);this.pdfDocument&&this._optionalContentConfigPromise&&(this._optionalContentConfigPromise=e,this.refresh(!1,{optionalContentConfigPromise:e}),this.eventBus.dispatch("optionalcontentconfigchanged",{source:this,promise:e}))}get scrollMode(){return this._scrollMode}set scrollMode(e){if(this._scrollMode!==e){if(!Gte(e))throw new Error(`Invalid scroll mode: ${e}`);this.pagesCount>ym.FORCE_SCROLL_MODE_PAGE||(this._previousScrollMode=this._scrollMode,this._scrollMode=e,this.eventBus.dispatch("scrollmodechanged",{source:this,mode:e}),this._updateScrollMode(this._currentPageNumber))}}_updateScrollMode(e=null){let t=this._scrollMode,i=this.viewer;i.classList.toggle("scrollHorizontal",t===ot.HORIZONTAL),i.classList.toggle("scrollWrapped",t===ot.WRAPPED),!(!this.pdfDocument||!e)&&(t===ot.PAGE?this.#R():this._previousScrollMode===ot.PAGE&&this._updateSpreadMode(),this._currentScaleValue&&isNaN(this._currentScaleValue)&&this.#U(this._currentScaleValue,{noScroll:!0}),this._setCurrentPageNumber(e,!0),this.update())}get spreadMode(){return this._spreadMode}set spreadMode(e){if(this._spreadMode!==e){if(!Wte(e))throw new Error(`Invalid spread mode: ${e}`);this._spreadMode=e,this.eventBus.dispatch("spreadmodechanged",{source:this,mode:e}),this._updateSpreadMode(this._currentPageNumber)}}_updateSpreadMode(e=null){if(!this.pdfDocument)return;let t=this.viewer,i=this._pages;if(this._scrollMode===ot.PAGE)this.#R();else if(t.textContent="",this._spreadMode===Fi.NONE)for(let r of this._pages)t.append(r.div);else{let r=this._spreadMode-1,s=null;for(let o=0,a=i.length;o<a;++o)s===null?(s=document.createElement("div"),s.className="spread",t.append(s)):o%2===r&&(s=s.cloneNode(!1),t.append(s)),s.append(i[o].div)}e&&(this._currentScaleValue&&isNaN(this._currentScaleValue)&&this.#U(this._currentScaleValue,{noScroll:!0}),this._setCurrentPageNumber(e,!0),this.update())}#$(e,t=!1){switch(this._scrollMode){case ot.WRAPPED:{let{views:i}=this._getVisiblePages(),r=new Map;for(let{id:s,y:o,percent:a,widthPercent:u}of i)a===0||u<100||r.getOrInsertComputed(o,Pte).push(s);for(let s of r.values()){let o=s.indexOf(e);if(o===-1)continue;let a=s.length;if(a===1)break;if(t)for(let u=o-1,l=0;u>=l;u--){let c=s[u],d=s[u+1]-1;if(c<d)return e-d}else for(let u=o+1,l=a;u<l;u++){let c=s[u],d=s[u-1]+1;if(c>d)return d-e}if(t){let u=s[0];if(u<e)return e-u+1}else{let u=s[a-1];if(u>e)return u-e+1}break}break}case ot.HORIZONTAL:break;case ot.PAGE:case ot.VERTICAL:{if(this._spreadMode===Fi.NONE)break;let i=this._spreadMode-1;if(t&&e%2!==i)break;if(!t&&e%2===i)break;let{views:r}=this._getVisiblePages(),s=t?e-1:e+1;for(let{id:o,percent:a,widthPercent:u}of r)if(o===s){if(a>0&&u===100)return 2;break}break}}return 1}nextPage(){let e=this._currentPageNumber,t=this.pagesCount;if(e>=t)return!1;let i=this.#$(e,!1)||1;return this.currentPageNumber=Math.min(e+i,t),!0}previousPage(){let e=this._currentPageNumber;if(e<=1)return!1;let t=this.#$(e,!0)||1;return this.currentPageNumber=Math.max(e-t,1),!0}updateScale({drawingDelay:e,scaleFactor:t=null,steps:i=null,origin:r}){if(i===null&&t===null)throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided.");if(!this.pdfDocument)return;let s=this._currentScale;if(t>0&&t!==1)s=Math.round(s*t*100)/100;else if(i){let o=i>0?q9:1/q9,a=i>0?Math.ceil:Math.floor;i=Math.abs(i);do s=a((s*o).toFixed(2)*10)/10;while(--i>0)}s=IM(s,Bte,Dte),this.#U(s,{noScroll:!1,drawingDelay:e,origin:r})}increaseScale(e={}){this.updateScale({...e,steps:e.steps??1})}decreaseScale(e={}){this.updateScale({...e,steps:-(e.steps??1)})}#j(e=this.container.clientHeight){e!==this.#T&&(this.#T=e,zte.setProperty("--viewer-container-height",`${e}px`))}#Q(e){for(let t of e)if(t.target===this.container){this.#j(Math.floor(t.borderBoxSize[0].blockSize)),this.#a=null;break}}get containerTopLeft(){return this.#a||=[this.container.offsetTop,this.container.offsetLeft]}#X(){this.#I!==null&&(clearTimeout(this.#I),this.#I=null),this.#b!==null&&(clearTimeout(this.#b),this.#b=null)}#J(){this.#C?.abort(),this.#C=null,this.#E!==null&&(clearTimeout(this.#E),this.#E=null)}#ee(e){switch(e){case Kn.STAMP:this.#y?.loadModel("altText");break;case Kn.SIGNATURE:this.#N?.loadSignatures();break}}get annotationEditorMode(){return this.#r?this.#i:Kn.DISABLE}set annotationEditorMode({mode:e,editId:t=null,isFromKeyboard:i=!1,mustEnterInEditMode:r=!1,editComment:s=!1}){if(!this.#r)throw new Error("The AnnotationEditor is not enabled.");if(this.#i===e)return;if(!CM(e))throw new Error(`Invalid AnnotationEditor mode: ${e}`);if(!this.pdfDocument)return;this.#ee(e);let{eventBus:o,pdfDocument:a}=this,u=async()=>{this.#J(),this.#i=e,await this.#r.updateMode(e,t,!0,i,r,s),!(e!==this.#i||a!==this.pdfDocument)&&o.dispatch("annotationeditormodechanged",{source:this,mode:e})};if(e===Kn.NONE||this.#i===Kn.NONE){let l=e!==Kn.NONE;l||this.pdfDocument.annotationStorage.resetModifiedIds(),this.cleanup();for(let d of this._pages)d.toggleEditingMode(l);let c=this.#F();if(l&&c){this.#J(),this.#C=new AbortController;let d=AbortSignal.any([this.#c.signal,this.#C.signal]);o._on("pagerendered",({pageNumber:f})=>{c.delete(f),c.size===0&&(this.#E=setTimeout(u,0))},{signal:d});return}}u()}refresh(e=!1,t=Object.create(null)){if(this.pdfDocument){for(let i of this._pages)i.update(t);this.#X(),e||this.update()}}},G4=class extends lc{_resetView(){super._resetView(),this._scrollMode=ot.PAGE,this._spreadMode=Fi.NONE}set scrollMode(e){}_updateScrollMode(){}set spreadMode(e){}_updateSpreadMode(){}};globalThis.pdfjsViewer={AnnotationLayerBuilder:Cm,DownloadManager:b4,EventBus:oc,FindState:fa,GenericL10n:uc,LinkTarget:yu,parseQueryString:Lm,PDFFindController:Gh,PDFHistory:Vh,PDFLinkService:sc,PDFPageView:Rm,PDFScriptingManager:H4,PDFSinglePageViewer:G4,PDFViewer:lc,ProgressBar:g4,RenderingStates:Tt,ScrollMode:ot,SimpleLinkService:Wh,SpreadMode:Fi,StructTreeLayerBuilder:km,TextLayerBuilder:_m,XfaLayerBuilder:Pm}});function Mm(n,e){n.onSetModified=e}function DM(n){return n.onSetModified}function Om(n){return n.serializable}function V4(n){n.setDocument(null)}function FM(n){n.setDocument(null)}var K4=Me(()=>{x()});var HM={};jt(HM,{AnnotationEditorType:()=>Je,PDFNavigator:()=>Y4,ScrollMode:()=>ot,SpreadMode:()=>Fi});var Y4,UM=Me(()=>{x();zt();Ul();ei();cn();Nn();V9();z4();yn();$t();K4();h3();c3();Y4=class extends Zo{constructor(t){super();this.rights={};this.pageNum=1;this.resourceIndex=0;this.pdfDoc=null;this.numPages=0;this.positionRestored=!1;this.onResize=()=>{clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout(()=>{if(this.pdfViewer){let t=this.pdfViewer.currentScaleValue;this.pdfViewer.currentScaleValue=t}},200)};this.settings=t.settings,this.publication=t.publication,this.api=t.api,this.rights=t.rights??{},this.workerSrc=t.workerSrc??`https://unpkg.com/pdfjs-dist@${r4}/build/pdf.worker.min.mjs`,this.annotator=t.annotator,this.initialLastReadingPosition=t.initialLastReadingPosition,this.fetcher=new ho,this.registerModules(t.modules,Ve.PDF)}supports(t){return t===ye.Zoom?!0:this.registry.has(t)}get currentPage(){return this.pageNum}get totalPages(){return this.pdfDoc?.numPages??this.numPages??0}get fingerprint(){return this.pdfDoc?.fingerprints[0]??void 0}get currentResourceLink(){return this.resource}static async create(t){let i=new this(t);return await i.start(t.mainElement,t.headerMenu,t.footerMenu),i}async start(t,i,r){this.headerMenu=i,this.footerMenu=r,this.mainElement=t,this.resourceIndex=0,this.resource=this.publication.readingOrder[this.resourceIndex],mo.workerSrc=this.workerSrc,this.wrapper=yt(this.mainElement,"#iframe-wrapper"),this.pdfContainer=yt(this.mainElement,"#pdf-container"),this.wrapper.style.position="absolute",this.wrapper.style.overflow="auto",this.wrapper.style.top="0",this.wrapper.style.left="0",this.wrapper.style.right="0",this.wrapper.style.bottom="0",this.pdfContainer.classList.add("pdfViewer"),this.handTool=new Gl({element:this.wrapper}),this.eventBus=new oc,this.linkService=new sc({eventBus:this.eventBus}),this.findController=new Gh({linkService:this.linkService,eventBus:this.eventBus}),this.pdfViewer=new lc({container:this.wrapper,viewer:this.pdfContainer,eventBus:this.eventBus,linkService:this.linkService,findController:this.findController,textLayerMode:1,annotationMode:xs.ENABLE_STORAGE,annotationEditorMode:Je.NONE,annotationEditorHighlightColors:"Yellow=#FFFF98,Green=#53FFBC,Blue=#80EBFF,Pink=#FFCBE6,Red=#FF4F5F"}),this.linkService.setViewer(this.pdfViewer),this.pdfViewer.spreadMode=Fi.NONE,this.pdfHistory=new Vh({eventBus:this.eventBus,linkService:this.linkService}),this.linkService.setHistory(this.pdfHistory),this.eventBus.on("pagesinit",()=>{this.pdfViewer.currentPageNumber=this.pageNum}),this.eventBus.on("pagechanging",({pageNumber:s})=>{this.pageNum=s,this.saveLastReadingPosition(),this.emit(ce.PageChanged,{page:s,totalPages:this.pdfDoc?.numPages??this.numPages}),this.atStart()?(this.api?.resourceAtStart?.(),this.emit(ce.ResourceStart,{href:this.publication.readingOrder[0]?.href})):this.atEnd()&&(this.api?.resourceAtEnd?.(),this.emit(ce.ResourceEnd,{href:this.publication.readingOrder[0]?.href}))}),this.eventBus.on("pagesloaded",async({pagesCount:s})=>{this.numPages=s,this.hideLoading(),this.api?.resourceReady?.(),this.emit(ce.ResourceReady,{href:this.publication.readingOrder[0]?.href}),this.registry.notifyResourceReady(),this.positionRestored||(this.positionRestored=!0,await this.restoreLastReadingPosition())}),await this.registry.setupAll(),this.showLoading(),await this.loadDocument(this.publication.getAbsoluteHref(this.resource.href),1),ee(window,"resize",this.onResize)}showLoading(){let t=document.getElementById("loadingpdf");if(t){t.style.display="flex";return}t=document.createElement("div"),t.id="loadingpdf",t.innerHTML=Jg,Object.assign(t.style,{position:"absolute",inset:"0",display:"flex",zIndex:"100",alignItems:"center",justifyContent:"center",background:"white"}),t.className="dita-loading is-loading",(this.wrapper.parentElement??document.body).appendChild(t)}hideLoading(){let t=document.getElementById("loadingpdf");t&&(t.style.display="none")}async loadDocument(t,i){this.showLoading(),this.pageNum=i,this.pdfDoc&&(V4(this.pdfViewer),FM(this.linkService),await this.pdfDoc.destroy(),this.pdfDoc=null);try{let r;if("getBytes"in this.fetcher){let a=this.fetcher.getBytes(t);a?r=Bh({data:a}):r=Bh(t)}else r=Bh(t);let s=await r.promise;this.pdfDoc=s,this.pdfViewer.setDocument(s),this.linkService.setDocument(s),this.pdfHistory.initialize({fingerprint:s.fingerprints[0]??""})}catch(r){this.hideLoading();let s=r instanceof Error?r:new Error(String(r));console.error("PDFNavigator: failed to load document",t,s),this.api?.onError?.(s),this.emit(ce.ResourceError,s)}}atStart(){return this.pageNum<=1&&this.resourceIndex===0}atEnd(){return this.resourceIndex>=this.publication.readingOrder.length-1&&this.pageNum>=(this.pdfDoc?.numPages??1)}currentResource(){return this.resourceIndex}currentLocator(){let t=this.pdfDoc?.numPages??this.numPages??1,i=t>1?(this.pageNum-1)/(t-1):0;return{href:this.resource?this.publication.getAbsoluteHref(this.resource.href):"",title:`Page ${this.pageNum}`,locations:{page:this.pageNum,progression:i},type:"application/pdf"}}nextPage(){if(this.pageNum>=(this.pdfDoc?.numPages??1)){this.nextResource();return}this.pdfViewer.nextPage()}previousPage(){if(this.pageNum<=1){this.previousResource();return}this.pdfViewer.previousPage()}nextResource(){this.resourceIndex>=this.publication.readingOrder.length-1||(this.resourceIndex++,this.resource=this.publication.readingOrder[this.resourceIndex],this.loadDocument(this.publication.getAbsoluteHref(this.resource.href),1))}previousResource(){this.resourceIndex!==0&&(this.resourceIndex--,this.resource=this.publication.readingOrder[this.resourceIndex],this.loadDocument(this.publication.getAbsoluteHref(this.resource.href),this.pdfDoc?.numPages??1))}goTo(t){let i=Ur(t.locations);if(typeof i=="number"){this.pdfViewer.currentPageNumber=i;return}let r=t.href??"",s=this.pageFromHref(r)??1;if(r){let o=r.split("#")[0].split("?")[0],a=this.publication.readingOrder.findIndex(u=>{if(!u.href)return!1;let l=this.publication.getAbsoluteHref(u.href);return u.href===o||l===o||l===this.toAbsoluteHref(o)});if(a>=0&&a!==this.resourceIndex){this.resourceIndex=a,this.resource=this.publication.readingOrder[this.resourceIndex],this.loadDocument(this.publication.getAbsoluteHref(this.resource.href),s);return}}this.pdfViewer.currentPageNumber=s}pageFromHref(t){if(!t)return null;let i=t.match(/#page=(\d+)/i);if(i)return parseInt(i[1],10);try{let r=new URL(t,window.location.href);if(r.searchParams.has("start"))return parseInt(r.searchParams.get("start"),10);if(r.searchParams.has("page"))return parseInt(r.searchParams.get("page"),10)}catch{}return null}toAbsoluteHref(t){try{return new URL(t,window.location.href).href}catch{return t}}goToPosition(t){this.pdfViewer.currentPageNumber=t}async goToPage(t){this.pdfViewer.currentPageNumber=t}fitToWidth(){this.modules.viewSettings?.fitToWidth()}fitToPage(){this.modules.viewSettings?.fitToPage()}zoomIn(){this.modules.viewSettings?.zoomIn()}zoomOut(){this.modules.viewSettings?.zoomOut()}activateHand(){this.handTool.activate()}deactivateHand(){this.handTool.deactivate()}async scroll(t,i){this.modules.viewSettings?.setScrollMode(t,i)}saveLastReadingPosition(){if(!this.annotator||!this.resource)return;let t={href:this.publication.getAbsoluteHref(this.resource.href),locations:{page:this.pageNum},type:"application/pdf",created:new Date};this.api?.updateCurrentLocation?this.api.updateCurrentLocation(t).then(()=>{this.annotator.saveLastReadingPosition(t)}):this.annotator.saveLastReadingPosition(t),this.emit(ce.LocationChanged,t)}async restoreLastReadingPosition(){if(this.initialLastReadingPosition&&this.annotator?.initLastReadingPosition(this.initialLastReadingPosition),!this.annotator)return;let t=this.annotator.getLastReadingPosition();if(!t)return;let i=Ur(t.locations)??1,r=this.publication.readingOrder.findIndex(s=>s.href&&this.publication.getAbsoluteHref(s.href)===t.href);r>=0&&r!==this.resourceIndex?(this.resourceIndex=r,this.resource=this.publication.readingOrder[this.resourceIndex],await this.loadDocument(this.publication.getAbsoluteHref(this.resource.href),i)):this.pdfViewer.currentPageNumber=i}stop(){this.registry.stopAll(),we(window,"resize",this.onResize),this.pdfViewer&&V4(this.pdfViewer),this.pdfDoc?.destroy(),this.pdfDoc=null}}});var jM=Me(()=>{x()});function q4(n){return e=>({kind:"url",url:n.getAbsoluteHref(e.href)})}var GM,Nm,$4=Me(()=>{x();GM=1,Nm=class n{constructor(e){this.pool=new Map;this.destroyed=!1;this.engine=e.engine,this.publication=e.publication,this.resolveSource=e.resolveSource??q4(e.publication),this.supportedAudioTypes=n.detectSupportedAudioTypes(e.publication)}setCurrentAudio(e){if(this.destroyed)return;let t=this.publication.readingOrder;if(e<0||e>=t.length)return;let i=this.resolveSourceFor(t[e]);this.engine.changeSrc(i);let r=n.cacheKeyFor(i);r!==void 0&&this.releasePoolEntry(r),this.update(e)}prefetchAt(e){if(this.destroyed)return;let t=this.publication.readingOrder;if(e<0||e>=t.length)return;let i=this.resolveSourceFor(t[e]),r=n.cacheKeyFor(i);r!==void 0&&this.ensure(r)}get size(){return this.pool.size}destroy(){if(!this.destroyed){this.destroyed=!0;for(let[,e]of this.pool)n.releaseElement(e);this.pool.clear()}}ensure(e){let t=this.pool.get(e);if(t)return t;let i=document.createElement("audio");return i.preload="auto",this.engine.isWebAudioActive&&(i.crossOrigin="anonymous"),i.src=e,i.load(),this.pool.set(e,i),i}update(e){let t=this.publication.readingOrder,i=new Set;for(let r=0;r<t.length;r++){if(r===e||r<e-GM||r>e+GM)continue;let s=this.resolveSourceFor(t[r]),o=n.cacheKeyFor(s);o!==void 0&&(this.ensure(o),i.add(o))}for(let[r,s]of this.pool)i.has(r)||(n.releaseElement(s),this.pool.delete(r))}static cacheKeyFor(e){switch(e.kind){case"url":case"drm":return e.url;case"hls":case"vendor":return}}releasePoolEntry(e){let t=this.pool.get(e);t&&(n.releaseElement(t),this.pool.delete(e))}resolveSourceFor(e){let t=this.pickPlayableLink(e);return this.resolveSource(t)}static detectSupportedAudioTypes(e){let t=document.createElement("audio"),i=new Set;for(let s of e.readingOrder){s.type&&i.add(s.type);let o=s.alternates;if(o)for(let a of o.items)a.type&&i.add(a.type)}let r=new Map;for(let s of i){let o=t.canPlayType(s);(o==="probably"||o==="maybe")&&r.set(s,o)}return r}pickPlayableLink(e){let t=[e],i=e.alternates;if(i)for(let s of i.items)t.push(s);let r;for(let s of t){let o=s.type;if(!o)continue;let a=this.supportedAudioTypes.get(o);if(a==="probably")return s;a==="maybe"&&!r&&(r=s)}return r??e}static releaseElement(e){e.removeAttribute("src"),e.load()}}});var cne,dne,hne,Bm,WM=Me(()=>{x();$4();cne=262144,dne=3,hne=1,Bm=class n{constructor(e){this.attempted=new Set;this.badUrls=new Set;this.queue=[];this.inFlight=0;this.currentIndex=-1;this.started=!1;this.disposed=!1;this.abortController=new AbortController;this.publication=e.publication,this.engine=e.engine,this.resolveSource=e.resolveSource??q4(e.publication),this.bytes=e.bytes??cne,this.concurrency=e.concurrency??dne,this.enabled=e.enabled??!1}start(){this.disposed||this.enabled&&(this.started=!0,this.rebuildQueue(),this.pump())}setCurrentIndex(e){this.disposed||(this.currentIndex=e,this.started&&(this.rebuildQueue(),this.pump()))}dispose(){this.disposed||(this.disposed=!0,this.queue=[],this.abortController.abort())}rebuildQueue(){let e=this.publication.readingOrder,t=[];for(let r=0;r<e.length;r++)this.shouldPrefetch(r)&&t.push(r);let i=this.currentIndex>=0?this.currentIndex:0;t.sort((r,s)=>{let o=Math.abs(r-i),a=Math.abs(s-i);return o!==a?o-a:r-s}),this.queue=t}shouldPrefetch(e){if(e===this.currentIndex||this.currentIndex>=0&&Math.abs(e-this.currentIndex)<=hne)return!1;let t=this.publication.readingOrder[e];if(!t)return!1;let i=this.resolveSource(t),r=n.cacheKeyFor(i);return!(r===void 0||this.attempted.has(r)||this.badUrls.has(r))}pump(){if(!this.disposed)for(;this.inFlight<this.concurrency&&this.queue.length>0;){let e=this.queue.shift();if(e===void 0)return;this.fetchHead(e)}}async fetchHead(e){let t=this.publication.readingOrder[e];if(!t)return;let i=this.resolveSource(t),r=n.cacheKeyFor(i);if(r!==void 0&&!this.attempted.has(r)){this.attempted.add(r),this.inFlight++;try{let s=await fetch(r,{method:"GET",mode:"cors",credentials:"omit",signal:this.abortController.signal,headers:{Range:`bytes=0-${this.bytes-1}`}});s.status===200?this.badUrls.add(r):s.status!==206&&s.status!==0&&this.badUrls.add(r);try{await s.arrayBuffer()}catch{}}catch(s){if(s instanceof DOMException&&s.name==="AbortError")return;this.badUrls.add(r)}finally{this.inFlight--,this.pump()}}}static cacheKeyFor(e){switch(e.kind){case"url":case"drm":return e.url;case"hls":case"vendor":return}}}});var zM,VM=Me(()=>{x();zM="preserve-pitch-processor"});function fne(n){return new Promise((e,t)=>{let i=()=>{s(),e()},r=()=>{s(),t(new Error("WebAudioEngine: CORS reload failed \u2014 server may not send Access-Control-Allow-Origin"))},s=()=>{n.removeEventListener("canplaythrough",i),n.removeEventListener("error",r)};n.addEventListener("canplaythrough",i,{once:!0}),n.addEventListener("error",r,{once:!0})})}function pne(n){return new Promise(e=>{let t=()=>{n.removeEventListener("canplaythrough",t),e()};n.addEventListener("canplaythrough",t,{once:!0})})}var Q4,Dm,KM=Me(()=>{x();Uv();VM();Q4=class n{constructor(e={}){this.emitter=new $p;this.elementListeners=new Map;this.audioContext=null;this.sourceNode=null;this.gainNode=null;this.workletNode=null;this.workletReady=null;this.webAudioActive=!1;this.currentSrc="";this.destroyed=!1;this._preservesPitch=!0;this._muted=!1;this._volume=1;this.preservePitchWorkletUrl=e.preservePitchWorkletUrl,this.element=new Audio,this.element.preload="auto",this.wireElementEvents()}changeSrc(e){if(this.destroyed)return;if(e.kind!=="url")throw new Error(`WebAudioEngine: unsupported source kind "${e.kind}"; only "url" is handled. Register an EngineFactory for this kind.`);let t=e.url;if(t!==this.currentSrc)if(this.element.pause(),this.currentSrc=t,this.webAudioActive){this.element.crossOrigin="anonymous",this.element.src=t,this.element.load();let i=()=>s(),r=()=>{s(),console.warn("WebAudioEngine: CORS reload failed on changeSrc \u2014 tearing down Web Audio graph for this source"),this.tearDownWebAudio(),this.element.removeAttribute("crossorigin"),this.element.src=t,this.element.load()},s=()=>{this.element.removeEventListener("canplaythrough",i),this.element.removeEventListener("error",r)};this.element.addEventListener("canplaythrough",i,{once:!0}),this.element.addEventListener("error",r,{once:!0})}else this.element.src=t,this.element.load()}wireElementEvents(){let e=(i,r,s)=>{let o=()=>{this.destroyed||this.emitter.emit(r,s())};this.element.addEventListener(i,o),this.elementListeners.set(`${i}:${r}`,o)};e("loadedmetadata","loadedmetadata",()=>this.metadata),e("loadedmetadata","metadatachanged",()=>this.metadata),e("loadedmetadata","seekablechanged",()=>({ranges:this.seekable})),e("durationchange","metadatachanged",()=>this.metadata),e("canplay","canplay",()=>({duration:this.duration})),e("play","play",()=>({currentTime:this.currentTime})),e("playing","playing",()=>({currentTime:this.currentTime})),e("pause","pause",()=>({currentTime:this.currentTime})),e("ended","ended",()=>({currentTime:this.currentTime})),e("timeupdate","timeupdate",()=>({currentTime:this.currentTime,duration:this.duration})),e("seeking","seeking",()=>({currentTime:this.currentTime})),e("seeked","seeked",()=>({currentTime:this.currentTime})),e("stalled","stalled",()=>({currentTime:this.currentTime})),e("waiting","waiting",()=>({currentTime:this.currentTime})),e("progress","bufferedchanged",()=>({ranges:this.buffered}));let t=()=>{this.destroyed||this.emitter.emit("error",this.translateMediaError())};this.element.addEventListener("error",t),this.elementListeners.set("error:error",t)}translateMediaError(){let e=this.element.error;if(!e)return{message:"Unknown audio error",kind:"unknown",retryable:!1};switch(e.code){case 1:return{message:e.message||"Audio fetch aborted",kind:"network",cause:e,retryable:!0};case 2:return{message:e.message||"Audio network error",kind:"network",cause:e,retryable:!0};case 3:return{message:e.message||"Audio decode error",kind:"decode",cause:e,retryable:!1};case 4:return{message:e.message||"Audio source not supported",kind:"notfound",cause:e,retryable:!1};default:return{message:e.message||`Audio error code ${e.code}`,kind:"unknown",cause:e,retryable:!1}}}async play(){if(this.destroyed)throw new Error("WebAudioEngine: destroyed");this.audioContext&&this.audioContext.state==="suspended"&&await this.audioContext.resume();try{await this.element.play()}catch(e){if(e instanceof DOMException&&e.name==="AbortError")return;throw e}}pause(){this.destroyed||this.element.pause()}stop(){this.destroyed||(this.element.pause(),this.element.currentTime=0)}seek(e){this.destroyed||!Number.isFinite(e)||e<0||(this.element.currentTime=e)}get currentTime(){return this.element.currentTime}get duration(){let e=this.element.duration;return Number.isFinite(e)?e:0}get paused(){return this.element.paused}get ended(){return this.element.ended}get buffered(){return n.toTimeRanges(this.element.buffered)}get seekable(){return n.toTimeRanges(this.element.seekable)}get metadata(){return{duration:this.duration,textTracks:n.toAudioTextTracks(this.element.textTracks),readyState:this.element.readyState,networkState:this.element.networkState}}get isWebAudioActive(){return this.webAudioActive}getMediaElement(){return this.element}get playbackRate(){return this.element.playbackRate}set playbackRate(e){!Number.isFinite(e)||e<=0||(this.element.playbackRate=e,this.applyPitchHandling())}get preservesPitch(){return this._preservesPitch}set preservesPitch(e){this._preservesPitch!==e&&(this._preservesPitch=e,this.applyPitchHandling())}get volume(){return this._volume}set volume(e){Number.isFinite(e)&&(this._volume=Math.max(0,Math.min(1,e)),this.applyVolume())}get muted(){return this._muted}set muted(e){this._muted!==e&&(this._muted=e,this.applyVolume())}applyVolume(){let e=this._muted?0:this._volume;this.gainNode?(this.element.volume=1,this.gainNode.gain.value=e):this.element.volume=e}applyPitchHandling(){this._preservesPitch?"preservesPitch"in this.element?(this.element.preservesPitch=!0,this.sendPitchFactor()):this.activateWebAudio().then(()=>this.ensureWorklet()).then(()=>this.sendPitchFactor()).catch(e=>{console.warn("WebAudioEngine: pitch preservation unavailable \u2014 playing without:",e)}):("preservesPitch"in this.element&&(this.element.preservesPitch=!1),this.sendPitchFactor())}sendPitchFactor(){if(!this.workletNode)return;let t={type:"setPitchFactor",factor:this._preservesPitch?1/Math.max(.0625,this.element.playbackRate):1};this.workletNode.port.postMessage(t)}async activateWebAudio(){if(this.webAudioActive||!this.currentSrc)return;let e=!this.element.paused,t=this.element.currentTime;e&&this.element.pause(),this.element.crossOrigin="anonymous",this.element.src=this.currentSrc,this.element.load();try{await fne(this.element)}catch(i){if(this.element.removeAttribute("crossorigin"),this.element.src=this.currentSrc,this.element.load(),e){await pne(this.element),this.element.currentTime=t;try{await this.element.play()}catch{}}else this.element.currentTime=t;throw i}if(this.audioContext||(this.audioContext=new AudioContext),this.sourceNode=this.audioContext.createMediaElementSource(this.element),this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=this._muted?0:this._volume,this.element.volume=1,this.sourceNode.connect(this.gainNode),this.gainNode.connect(this.audioContext.destination),this.webAudioActive=!0,this.element.currentTime=t,e){this.audioContext.state==="suspended"&&await this.audioContext.resume();try{await this.element.play()}catch{}}}async ensureWorklet(){if(!this.workletNode){if(!this.webAudioActive||!this.audioContext)throw new Error("WebAudioEngine: activateWebAudio() must succeed before attaching the worklet");if(!this.preservePitchWorkletUrl)throw new Error("WebAudioEngine: preservePitchWorkletUrl was not supplied to the engine, so the worklet fallback is unavailable on this browser");if(!this.workletReady){let e=this.preservePitchWorkletUrl instanceof URL?this.preservePitchWorkletUrl.href:this.preservePitchWorkletUrl;this.workletReady=this.audioContext.audioWorklet.addModule(e)}if(await this.workletReady,!(!this.audioContext||!this.sourceNode||!this.gainNode)){this.workletNode=new AudioWorkletNode(this.audioContext,zM);try{this.sourceNode.disconnect()}catch{}this.sourceNode.connect(this.workletNode),this.workletNode.connect(this.gainNode)}}}tearDownWebAudio(){if(this.workletNode){try{this.workletNode.port.close()}catch{}try{this.workletNode.disconnect()}catch{}this.workletNode=null}if(this.sourceNode){try{this.sourceNode.disconnect()}catch{}this.sourceNode=null}if(this.gainNode){let e=this.gainNode.gain.value;try{this.gainNode.disconnect()}catch{}this.gainNode=null,this.element.volume=this._muted?0:e}this.webAudioActive=!1}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}destroy(){if(!this.destroyed){this.destroyed=!0,this.element.pause();for(let[e,t]of this.elementListeners){let i=e.split(":")[0];this.element.removeEventListener(i,t)}if(this.elementListeners.clear(),this.emitter.removeAllListeners(),this.tearDownWebAudio(),this.audioContext){try{this.audioContext.close()}catch{}this.audioContext=null}this.element.removeAttribute("src"),this.element.load()}}static toTimeRanges(e){let t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static toAudioTextTracks(e){let t=[];for(let i=0;i<e.length;i++){let r=e[i];t.push({src:"",kind:r.kind,label:r.label,language:r.language,mode:r.mode})}return t}};Dm=class{constructor(e={}){this.config=e}create(){return new Q4(this.config)}}});var Fm,YM=Me(()=>{x();Fm=class{constructor(e){this.kind=null;this.deadline=0;this.totalMs=0;this.interval=null;this.timeout=null;this.callbacks=e}get isActive(){return this.kind!==null}snapshot(){return this.kind===null?null:this.kind==="endOfChapter"?{kind:"endOfChapter",remainingMs:0,totalMs:0}:{kind:"minutes",remainingMs:Math.max(0,this.deadline-Date.now()),totalMs:this.totalMs}}startMinutes(e){if(!Number.isFinite(e)||e<=0)return;this.clearInternalTimers();let t=Math.round(e*6e4);this.kind="minutes",this.totalMs=t,this.deadline=Date.now()+t,this.interval=setInterval(()=>this.handleTick(),1e3),this.timeout=setTimeout(()=>this.fire(),t),this.callbacks.onStart(this.snapshot())}startEndOfChapter(){this.clearInternalTimers(),this.kind="endOfChapter",this.totalMs=0,this.deadline=0,this.callbacks.onStart(this.snapshot())}notifyChapterEnded(){return this.kind!=="endOfChapter"?!1:(this.fire(),!0)}cancel(){this.kind!==null&&(this.clearInternalTimers(),this.kind=null,this.callbacks.onCancel())}dispose(){this.clearInternalTimers(),this.kind=null}handleTick(){let e=this.snapshot();if(e){if(e.kind==="minutes"&&e.remainingMs<=0){this.fire();return}this.callbacks.onTick(e)}}fire(){if(this.kind===null)return;let e={kind:this.kind,remainingMs:0,totalMs:this.totalMs};this.clearInternalTimers(),this.kind=null,this.totalMs=0,this.deadline=0,this.callbacks.onExpire(e)}clearInternalTimers(){this.interval!==null&&(clearInterval(this.interval),this.interval=null),this.timeout!==null&&(clearTimeout(this.timeout),this.timeout=null)}}});function mne(n){let e=[n.readingOrder??[],n.resources??[],n.links??[]];for(let t of e)for(let i of t)if(i.rels?.has("cover"))return i}var Hm,gne,qM=Me(()=>{x();Hm=class n{constructor(e){this.destroyed=!1;this.hooks=e,this.installActionHandlers(),this.refreshMetadata()}static create(e){return typeof navigator>"u"||!("mediaSession"in navigator)?null:new n(e)}refreshMetadata(){if(!this.destroyed)try{let e=this.hooks.publication,t=this.hooks.currentIndex(),r=e.readingOrder[t]?.title||`Track ${t+1}`,s=e.metadata?.authors?.items?.map(u=>u.name?.getTranslation?.()??"")?.filter(u=>u.length>0)?.join(", "),o=e.metadata?.title?.getTranslation?.(),a=this.resolveArtwork();if(typeof MediaMetadata>"u")return;navigator.mediaSession.metadata=new MediaMetadata({title:r,artist:s||void 0,album:o||void 0,artwork:a})}catch{}}refreshPositionState(){if(!this.destroyed&&"setPositionState"in navigator.mediaSession)try{let e=this.hooks.duration(),t=this.hooks.currentTime(),i=this.hooks.playbackRate();if(!Number.isFinite(e)||e<=0){navigator.mediaSession.setPositionState();return}navigator.mediaSession.setPositionState({duration:e,position:Math.min(Math.max(0,t),e),playbackRate:Number.isFinite(i)&&i>0?i:1})}catch{}}setPlaying(){this.destroyed||(navigator.mediaSession.playbackState="playing",this.refreshPositionState())}setPaused(){this.destroyed||(navigator.mediaSession.playbackState="paused",this.refreshPositionState())}setIdle(){this.destroyed||(navigator.mediaSession.playbackState="none")}destroy(){if(!this.destroyed){if(this.destroyed=!0,navigator.mediaSession.metadata=null,navigator.mediaSession.playbackState="none","setPositionState"in navigator.mediaSession)try{navigator.mediaSession.setPositionState()}catch{}for(let e of gne)try{navigator.mediaSession.setActionHandler(e,null)}catch{}}}installActionHandlers(){let e=navigator.mediaSession;this.safeSet("play",()=>this.hooks.play()),this.safeSet("pause",()=>this.hooks.pause()),this.safeSet("previoustrack",()=>this.hooks.previousChapter()),this.safeSet("nexttrack",()=>this.hooks.nextChapter()),this.safeSet("seekbackward",t=>{let i=t.seekOffset??this.hooks.skipBackwardInterval();this.hooks.jump(-i)}),this.safeSet("seekforward",t=>{let i=t.seekOffset??this.hooks.skipForwardInterval();this.hooks.jump(i)}),this.safeSet("seekto",t=>{let i=t.seekTime;i!=null&&this.hooks.seek(i)})}safeSet(e,t){try{navigator.mediaSession.setActionHandler(e,t)}catch{}}resolveArtwork(){let e=mne(this.hooks.publication);if(!e?.href)return;let t=this.hooks.publication.manifestUrl,i;try{i=new URL(e.href,t).href}catch{i=e.href}return[{src:i,type:e.type}]}},gne=["play","pause","previoustrack","nexttrack","seekbackward","seekforward","seekto"]});var $M={};jt($M,{AudiobookNavigator:()=>X4});var X4,QM=Me(()=>{x();zv();Nn();cn();jM();$4();WM();KM();zt();Il();YM();qM();X4=class n extends Xp{constructor(t){super();this.settingsUnsubscribe=null;this.lrpTimer=null;this.mediaSession=null;this.currentIndex=-1;this.navigationId=0;this.isNavigating=!1;this._isWaiting=!1;this.stopped=!1;this.publication=t.publication,this.rights=t.rights??{},this.settings=t.settings,this.api=t.api,this.annotator=t.annotator,this.chapterListContainer=t.chapterListContainer,this.applyColors(t.colors),this.settingsUnsubscribe=this.settings.onChange(i=>{i==="enableMediaSession"?this.applyMediaSessionSetting():this.applySettingToEngine(i)}),this.sleepTimer=new Fm({onStart:i=>this.emit(ce.SleepTimerStarted,i),onTick:i=>this.emit(ce.SleepTimerTick,i),onCancel:()=>this.emit(ce.SleepTimerCancelled,void 0),onExpire:i=>{this.pause(),this.emit(ce.SleepTimerExpired,i)}}),this.engineFactory=t.engineFactory??new Dm({preservePitchWorkletUrl:t.preservePitchWorkletUrl}),this.engine=this.engineFactory.create(),this.attachEngineListeners(),this.pool=new Nm({engine:this.engine,publication:this.publication,resolveSource:t.resolveSource}),this.prefetcher=new Bm({publication:this.publication,engine:this.engine,resolveSource:t.resolveSource,bytes:t.prefetch?.bytes,concurrency:t.prefetch?.concurrency,enabled:t.prefetch?.enabled}),this.visibilityHandler=()=>{typeof document<"u"&&document.hidden&&this.flushReadingPositionSave()},typeof document<"u"&&document.addEventListener("visibilitychange",this.visibilityHandler),this.registerModules(t.modules,Ve.Audiobook),this.applyMediaSessionSetting(),this.on(ce.BookmarkCreated,()=>this.getTimelineModule()?.onBookmarkChanged()),this.on(ce.BookmarkDeleted,()=>this.getTimelineModule()?.onBookmarkChanged()),this.on(ce.CommentCreated,()=>this.getTimelineModule()?.onCommentChanged()),this.on(ce.CommentDeleted,()=>this.getTimelineModule()?.onCommentChanged()),this.chapterListContainer&&(this.renderChapterList(),this.on(ce.TrackChanged,()=>this.refreshChapterHighlight()))}applyColors(t){if(!t||typeof document>"u")return;let i=document.documentElement,r=(s,o)=>{o!==void 0&&i.style.setProperty(s,o)};r("--dita-audiobook-track",t.track),r("--dita-audiobook-accent",t.accent),r("--dita-audiobook-accent-fade",t.accentFade),r("--dita-audiobook-comment",t.comment),r("--dita-audiobook-boundary",t.boundary)}getTimelineModule(){return this.getModule(ye.Timeline)}getCommentsModule(){return this.getModule(ye.Comments)}renderChapterList(){let t=this.chapterListContainer;if(!t)return;t.innerHTML="";let i=document.createElement("ol");i.className="dita-audiobook-chapters";let r=this.publication.tableOfContents,s=r.length>0?r:this.publication.readingOrder;for(let o of s)this.appendChapterRow(i,o,0);t.appendChild(i),this.refreshChapterHighlight()}appendChapterRow(t,i,r){let s=document.createElement("li");s.className=r===0?"dita-audiobook-chapters-chapter":"dita-audiobook-chapters-section";let o=this.indexForHref(i.href);o>=0&&(s.dataset.chapterIndex=String(o)),s.tabIndex=0,s.setAttribute("role","button");let a=document.createElement("span");a.className="dita-audiobook-chapters-title",a.textContent=i.title||(o>=0?`Track ${o+1}`:i.href),s.appendChild(a);let u=this.locatorForTocLink(i);if(u){let c=d=>{d.preventDefault(),this.goTo(u)};s.addEventListener("click",c),s.addEventListener("keydown",d=>{(d.key==="Enter"||d.key===" ")&&c(d)})}t.appendChild(s);let l=i.children?.items;if(l&&l.length>0){let c=document.createElement("ol");c.className="dita-audiobook-chapters-sub";for(let d of l)this.appendChapterRow(c,d,r+1);t.appendChild(c)}}indexForHref(t){if(!t)return-1;let i=t.split("#")[0],r=this.publication.getAbsoluteHref(i);return this.publication.readingOrder.findIndex(o=>this.publication.getAbsoluteHref(o.href)===r)}locatorForTocLink(t){if(!t.href)return;let[i,r]=t.href.split("#"),s=this.indexForHref(i);if(s<0)return;let o=this.publication.readingOrder[s],a;if(r){let u=/(?:^|&)t=([0-9.]+)/.exec(r);u&&(a=Number(u[1]))}return{href:o.href,type:o.type,title:o.title,locations:a!==void 0?{time:a}:{}}}refreshChapterHighlight(){let t=this.chapterListContainer;if(!t)return;let i=String(this.currentIndex);for(let r of t.querySelectorAll("[data-chapter-index]"))r.dataset.chapterIndex===i?r.dataset.current="true":delete r.dataset.current}static async create(t,i=0){let r=new n(t),s=r.publication.readingOrder;if(s.length===0)return r;let o=t.initialLastReadingPosition??void 0;if(o){let l={...o,created:new Date};r.annotator?.initLastReadingPosition(l)}else{let l=r.annotator?.getLastReadingPosition();l?.href&&(o=l)}let a=i,u;if(o?.href){let l=s.findIndex(c=>c.href===o.href);if(l>=0){a=l;let c=o.locations?.time;typeof c=="number"&&c>0&&(u=c)}}return await r.goTrack(a,u),r.prefetcher.start(),r}async play(){this.engine.metadata.readyState<3&&this.setWaiting(!0),await this.engine.play()}pause(){this.engine.pause(),this.flushReadingPositionSave()}seek(t){!Number.isFinite(t)||t<0||(this.engine.seek(t),this.mediaSession?.refreshPositionState())}jump(t){let i=Math.max(0,this.engine.currentTime+t);this.engine.seek(Math.min(i,this.engine.duration||i)),this.mediaSession?.refreshPositionState()}skipForward(){this.jump(this.settings.skipForwardInterval)}skipBackward(){this.jump(-this.settings.skipBackwardInterval)}async goForward(){this.canGoForward&&await this.goTrack(this.currentIndex+1,void 0)}async goBackward(){this.canGoBackward&&await this.goTrack(this.currentIndex-1,void 0)}get currentTime(){return this.engine?.currentTime??0}get duration(){return this.engine?.duration??0}get isPlaying(){return!(this.engine?.paused??!0)}get isPaused(){return this.engine?.paused??!0}get isWaiting(){return this._isWaiting}get canGoForward(){return this.currentIndex<this.publication.readingOrder.length-1}get canGoBackward(){return this.currentIndex>0}get isTrackStart(){return this.currentTime===0}get isTrackEnd(){return this.engine.duration<=0?!1:this.engine.currentTime>=this.engine.duration||this.engine.ended}get playbackRate(){return this.settings.playbackRate}setPlaybackRate(t){!Number.isFinite(t)||t<=0||(this.settings.playbackRate=t)}get volume(){return this.settings.volume}setVolume(t){this.settings.volume=t}get muted(){return this.engine?.muted??!1}setMuted(t){this.engine&&(this.engine.muted=t)}startSleepTimerMinutes(t){this.sleepTimer.startMinutes(t)}startSleepTimerAtChapterEnd(){this.sleepTimer.startEndOfChapter()}cancelSleepTimer(){this.sleepTimer.cancel()}sleepTimerState(){return this.sleepTimer.snapshot()}currentResource(){return this.currentIndex>=0?this.currentIndex:void 0}currentLocator(){let t=this.currentLink;if(!t)return{href:"",locations:{}};let i=this.currentTime,r=this.duration||t.duration||0;return{href:t.href,type:t.type,title:t.title,locations:gy(i,{position:this.currentIndex>=0?this.currentIndex+1:void 0,progression:r>0?Math.min(1,i/r):0})}}async goTo(t){let i=this.publication.readingOrder.findIndex(s=>s.href===t.href);if(i<0)return;let r=typeof t.locations?.time=="number"&&t.locations.time>=0?t.locations.time:void 0;await this.goTrack(i,r)}async goToPosition(t){let i=t-1;i<0||i>=this.publication.readingOrder.length||await this.goTrack(i,0)}async nextResource(){return this.goForward()}async previousResource(){return this.goBackward()}atStart(){return this.currentIndex<=0&&this.currentTime<=0}atEnd(){return this.currentIndex>=this.publication.readingOrder.length-1&&this.isTrackEnd}stop(){if(!this.stopped){if(this.stopped=!0,this.flushReadingPositionSave(),typeof document<"u"&&document.removeEventListener("visibilitychange",this.visibilityHandler),this.settingsUnsubscribe&&(this.settingsUnsubscribe(),this.settingsUnsubscribe=null),this.sleepTimer.dispose(),this.mediaSession&&(this.mediaSession.destroy(),this.mediaSession=null),this.prefetcher.dispose(),this.pool.destroy(),Promise.resolve(this.engine.destroy()).catch(t=>{console.warn("AudiobookNavigator: engine destroy failed",t)}),this.engineFactory.destroy)try{let t=this.engineFactory.destroy();t&&typeof t.catch=="function"&&t.catch(i=>{console.warn("AudiobookNavigator: engineFactory destroy failed",i)})}catch(t){console.warn("AudiobookNavigator: engineFactory destroy threw",t)}this.currentIndex=-1}}scheduleReadingPositionSave(){!this.api?.updateCurrentLocation&&!this.annotator||(this.lrpTimer!==null&&clearTimeout(this.lrpTimer),this.lrpTimer=setTimeout(()=>{this.lrpTimer=null,this.persistReadingPosition()},this.settings.pollInterval))}flushReadingPositionSave(){this.lrpTimer!==null&&(clearTimeout(this.lrpTimer),this.lrpTimer=null),this.persistReadingPosition()}persistReadingPosition(){let t=this.currentLocator();if(!t.href)return;let i={...t,created:new Date},r=this.api?.updateCurrentLocation;r?r(i).then(()=>{this.annotator?.saveLastReadingPosition(i)}):this.annotator?.saveLastReadingPosition(i),this.emit(ce.LocationChanged,i)}get currentLink(){if(!(this.currentIndex<0))return this.publication.readingOrder[this.currentIndex]}async goTrack(t,i){if(this.stopped||t<0||t>=this.publication.readingOrder.length)return;if(t===this.currentIndex){typeof i=="number"&&i>=0&&(this.engine.seek(i),this.mediaSession?.refreshPositionState());return}let r=++this.navigationId,s=!this.engine.paused,o=this.currentIndex>=0?this.currentLocator():null;this.isNavigating=!0,this.setWaiting(s),this.engine.pause(),this.currentIndex=t,this.pool.setCurrentAudio(t),this.prefetcher.setCurrentIndex(t),this.engine.playbackRate=this.settings.playbackRate;try{await this.waitForCanPlay(r)}catch(u){r===this.navigationId&&(this.isNavigating=!1,this.setWaiting(!1),this.emit(ce.PlaybackError,{error:u,locator:this.currentLocator()}));return}if(this.stopped||r!==this.navigationId)return;typeof i=="number"&&i>=0&&this.engine.seek(i),this.isNavigating=!1;let a=this.currentLocator();this.emit(ce.TrackChanged,{previous:o,current:a}),this.getTimelineModule()?.onTrackChanged(),this.emit(ce.DurationChanged,{duration:this.engine.duration,locator:a}),this.getTimelineModule()?.onDurationChanged(),this.mediaSession&&(this.mediaSession.refreshMetadata(),this.mediaSession.refreshPositionState()),this.flushReadingPositionSave(),s&&await this.play()}waitForCanPlay(t){return new Promise((i,r)=>{if(this.engine.metadata.readyState>=3){i();return}let s=()=>{clearInterval(u),this.engine.off("canplay",o),this.engine.off("error",a)},o=()=>{s(),i()},a=l=>{s(),r(l)},u=setInterval(()=>{(t!==this.navigationId||this.stopped)&&(s(),i())},100);this.engine.on("canplay",o),this.engine.on("error",a)})}prefetchResource(t){this.stopped||this.pool.prefetchAt(t)}applySettingToEngine(t){t==="volume"?this.engine.volume=this.settings.volume:t==="playbackRate"?(this.engine.playbackRate=this.settings.playbackRate,this.emit(ce.PlaybackRateChanged,{rate:this.settings.playbackRate}),this.mediaSession?.refreshPositionState()):t==="preservePitch"&&(this.engine.preservesPitch=this.settings.preservePitch)}applyMediaSessionSetting(){let t=this.settings.enableMediaSession;t&&!this.mediaSession?(this.mediaSession=Hm.create({publication:this.publication,currentIndex:()=>this.currentIndex,currentTime:()=>this.currentTime,duration:()=>this.duration,playbackRate:()=>this.settings.playbackRate,skipBackwardInterval:()=>this.settings.skipBackwardInterval,skipForwardInterval:()=>this.settings.skipForwardInterval,play:()=>{this.play()},pause:()=>this.pause(),previousChapter:()=>{this.goBackward()},nextChapter:()=>{this.goForward()},seek:i=>this.seek(i),jump:i=>this.jump(i)}),this.mediaSession&&(this.isPlaying?this.mediaSession.setPlaying():this.mediaSession.setPaused())):!t&&this.mediaSession&&(this.mediaSession.destroy(),this.mediaSession=null)}setWaiting(t){this._isWaiting!==t&&(this._isWaiting=t,this.emit(ce.PlaybackWaiting,{waiting:t,locator:this.currentLocator()}))}attachEngineListeners(){let t=this.engine;t.volume=this.settings.volume,t.playbackRate=this.settings.playbackRate,t.preservesPitch=this.settings.preservePitch,t.on("play",i=>{this.isNavigating||(this.emit(ce.PlaybackStarted,{locator:this.currentLocator(),currentTime:i.currentTime}),this.mediaSession?.setPlaying())}),t.on("playing",()=>{this.isNavigating||this.setWaiting(!1)}),t.on("waiting",()=>{this.isNavigating||t.paused||this.setWaiting(!0)}),t.on("canplay",()=>{this.isNavigating||this.setWaiting(!1)}),t.on("pause",i=>{this.isNavigating||(this.setWaiting(!1),this.emit(ce.PlaybackPaused,{locator:this.currentLocator(),currentTime:i.currentTime}),this.mediaSession?.setPaused())}),t.on("ended",()=>{this.isNavigating||(this.setWaiting(!1),this.emit(ce.PlaybackEnded,{locator:this.currentLocator()}),!this.sleepTimer.notifyChapterEnded()&&this.canGoForward&&(async()=>(await this.goTrack(this.currentIndex+1,0),this.settings.autoPlay&&await this.play()))())}),t.on("timeupdate",i=>{if(this.isNavigating)return;let r={locator:this.currentLocator(),currentTime:i.currentTime,duration:i.duration};this.emit(ce.TimeUpdated,r),this.getTimelineModule()?.onTimeUpdate(),this.getCommentsModule()?.onTimeUpdate(r),this.scheduleReadingPositionSave()}),t.on("stalled",i=>{this.isNavigating||this.emit(ce.PlaybackStalled,{locator:this.currentLocator(),currentTime:i.currentTime})}),t.on("error",i=>{this.isNavigating||(this.setWaiting(!1),this.emit(ce.PlaybackError,{error:i,locator:this.currentLocator()}))})}}});function Ine(n,e){return xne(n,{i:2},e&&e.out,e&&e.dictionary)}function rE(n,e){if(e){for(var t="",i=0;i<n.length;i+=16384)t+=String.fromCharCode.apply(null,n.subarray(i,i+16384));return t}else{if(iE)return iE.decode(n);var r=_ne(n),s=r.s,t=r.r;return t.length&&Mr(8),s}}function rO(n,e){for(var t={},i=n.length-22;es(n,i)!=101010256;--i)(!i||n.length-i>65558)&&Mr(13);var r=Ps(n,i+8);if(!r)return{};var s=es(n,i+16),o=s==4294967295||r==65535;if(o){var a=es(n,i-12);o=es(n,a)==101075792,o&&(r=es(n,a+32),s=es(n,a+48))}for(var u=e&&e.filter,l=0;l<r;++l){var c=Rne(n,s,o),d=c[0],f=c[1],m=c[2],y=c[3],g=c[4],b=c[5],v=Pne(n,b);s=g,(!u||u({name:y,size:f,originalSize:m,compression:d}))&&(d?d==8?t[y]=Ine(n.subarray(v,v+f),{out:new fr(m)}):Mr(14,"unknown compression type "+d):t[y]=nE(n,v,v+f))}return t}var fr,cc,bne,XM,JM,yne,ZM,eO,tO,vne,iO,Ane,Zbe,tE,wo,Pt,Kh,Yh,Pt,Pt,Pt,Pt,nO,Pt,wne,Ene,J4,Zr,Z4,Cne,nE,Sne,Mr,xne,Tne,Ps,es,eE,iE,kne,_ne,Pne,Rne,Lne,sE=Me(()=>{x();fr=Uint8Array,cc=Uint16Array,bne=Int32Array,XM=new fr([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),JM=new fr([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),yne=new fr([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ZM=function(n,e){for(var t=new cc(31),i=0;i<31;++i)t[i]=e+=1<<n[i-1];for(var r=new bne(t[30]),i=1;i<30;++i)for(var s=t[i];s<t[i+1];++s)r[s]=s-t[i]<<5|i;return{b:t,r}},eO=ZM(XM,2),tO=eO.b,vne=eO.r;tO[28]=258,vne[258]=28;iO=ZM(JM,0),Ane=iO.b,Zbe=iO.r,tE=new cc(32768);for(Pt=0;Pt<32768;++Pt)wo=(Pt&43690)>>1|(Pt&21845)<<1,wo=(wo&52428)>>2|(wo&13107)<<2,wo=(wo&61680)>>4|(wo&3855)<<4,tE[Pt]=((wo&65280)>>8|(wo&255)<<8)>>1;Kh=(function(n,e,t){for(var i=n.length,r=0,s=new cc(e);r<i;++r)n[r]&&++s[n[r]-1];var o=new cc(e);for(r=1;r<e;++r)o[r]=o[r-1]+s[r-1]<<1;var a;if(t){a=new cc(1<<e);var u=15-e;for(r=0;r<i;++r)if(n[r])for(var l=r<<4|n[r],c=e-n[r],d=o[n[r]-1]++<<c,f=d|(1<<c)-1;d<=f;++d)a[tE[d]>>u]=l}else for(a=new cc(i),r=0;r<i;++r)n[r]&&(a[r]=tE[o[n[r]-1]++]>>15-n[r]);return a}),Yh=new fr(288);for(Pt=0;Pt<144;++Pt)Yh[Pt]=8;for(Pt=144;Pt<256;++Pt)Yh[Pt]=9;for(Pt=256;Pt<280;++Pt)Yh[Pt]=7;for(Pt=280;Pt<288;++Pt)Yh[Pt]=8;nO=new fr(32);for(Pt=0;Pt<32;++Pt)nO[Pt]=5;wne=Kh(Yh,9,1),Ene=Kh(nO,5,1),J4=function(n){for(var e=n[0],t=1;t<n.length;++t)n[t]>e&&(e=n[t]);return e},Zr=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},Z4=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},Cne=function(n){return(n+7)/8|0},nE=function(n,e,t){return(e==null||e<0)&&(e=0),(t==null||t>n.length)&&(t=n.length),new fr(n.subarray(e,t))},Sne=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Mr=function(n,e,t){var i=new Error(e||Sne[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,Mr),!t)throw i;return i},xne=function(n,e,t,i){var r=n.length,s=i?i.length:0;if(!r||e.f&&!e.l)return t||new fr(0);var o=!t,a=o||e.i!=2,u=e.i;o&&(t=new fr(r*3));var l=function(St){var $e=t.length;if(St>$e){var Bt=new fr(Math.max($e*2,St));Bt.set(t),t=Bt}},c=e.f||0,d=e.p||0,f=e.b||0,m=e.l,y=e.d,g=e.m,b=e.n,v=r*8;do{if(!m){c=Zr(n,d,1);var A=Zr(n,d+1,3);if(d+=3,A)if(A==1)m=wne,y=Ene,g=9,b=5;else if(A==2){var T=Zr(n,d,31)+257,_=Zr(n,d+10,15)+4,k=T+Zr(n,d+5,31)+1;d+=14;for(var L=new fr(k),M=new fr(19),N=0;N<_;++N)M[yne[N]]=Zr(n,d+N*3,7);d+=_*3;for(var O=J4(M),U=(1<<O)-1,G=Kh(M,O,1),N=0;N<k;){var j=G[Zr(n,d,U)];d+=j&15;var w=j>>4;if(w<16)L[N++]=w;else{var z=0,W=0;for(w==16?(W=3+Zr(n,d,3),d+=2,z=L[N-1]):w==17?(W=3+Zr(n,d,7),d+=3):w==18&&(W=11+Zr(n,d,127),d+=7);W--;)L[N++]=z}}var $=L.subarray(0,T),re=L.subarray(T);g=J4($),b=J4(re),m=Kh($,g,1),y=Kh(re,b,1)}else Mr(1);else{var w=Cne(d)+4,S=n[w-4]|n[w-3]<<8,C=w+S;if(C>r){u&&Mr(0);break}a&&l(f+S),t.set(n.subarray(w,C),f),e.b=f+=S,e.p=d=C*8,e.f=c;continue}if(d>v){u&&Mr(0);break}}a&&l(f+131072);for(var ae=(1<<g)-1,fe=(1<<b)-1,ge=d;;ge=d){var z=m[Z4(n,d)&ae],se=z>>4;if(d+=z&15,d>v){u&&Mr(0);break}if(z||Mr(2),se<256)t[f++]=se;else if(se==256){ge=d,m=null;break}else{var de=se-254;if(se>264){var N=se-257,Y=XM[N];de=Zr(n,d,(1<<Y)-1)+tO[N],d+=Y}var J=y[Z4(n,d)&fe],Q=J>>4;J||Mr(3),d+=J&15;var re=Ane[Q];if(Q>3){var Y=JM[Q];re+=Z4(n,d)&(1<<Y)-1,d+=Y}if(d>v){u&&Mr(0);break}a&&l(f+131072);var ie=f+de;if(f<re){var He=s-re,Ze=Math.min(re,ie);for(He+f<0&&Mr(3);f<Ze;++f)t[f]=i[He+f]}for(;f<ie;++f)t[f]=t[f-re]}}e.l=m,e.p=ge,e.b=f,e.f=c,m&&(c=1,e.m=g,e.d=y,e.n=b)}while(!c);return f!=t.length&&o?nE(t,0,f):t.subarray(0,f)},Tne=new fr(0),Ps=function(n,e){return n[e]|n[e+1]<<8},es=function(n,e){return(n[e]|n[e+1]<<8|n[e+2]<<16|n[e+3]<<24)>>>0},eE=function(n,e){return es(n,e)+es(n,e+4)*4294967296};iE=typeof TextDecoder<"u"&&new TextDecoder,kne=0;try{iE.decode(Tne,{stream:!0}),kne=1}catch{}_ne=function(n){for(var e="",t=0;;){var i=n[t++],r=(i>127)+(i>223)+(i>239);if(t+r>n.length)return{s:e,r:nE(n,t-1)};r?r==3?(i=((i&15)<<18|(n[t++]&63)<<12|(n[t++]&63)<<6|n[t++]&63)-65536,e+=String.fromCharCode(55296|i>>10,56320|i&1023)):r&1?e+=String.fromCharCode((i&31)<<6|n[t++]&63):e+=String.fromCharCode((i&15)<<12|(n[t++]&63)<<6|n[t++]&63):e+=String.fromCharCode(i)}};Pne=function(n,e){return e+30+Ps(n,e+26)+Ps(n,e+28)},Rne=function(n,e,t){var i=Ps(n,e+28),r=rE(n.subarray(e+46,e+46+i),!(Ps(n,e+8)&2048)),s=e+46+i,o=es(n,e+20),a=t&&o==4294967295?Lne(n,s):[o,es(n,e+24),es(n,e+42)],u=a[0],l=a[1],c=a[2];return[Ps(n,e+10),u,l,r,s+Ps(n,e+30)+Ps(n,e+32),c]},Lne=function(n,e){for(;Ps(n,e)!=1;e+=4+Ps(n,e+2));return[eE(n,e+12),eE(n,e+4),eE(n,e+20)]}});var dc,oE=Me(()=>{x();sE();dc=class{constructor(e){let t=e instanceof Uint8Array?e:new Uint8Array(e);this.data=rO(t)}entries(){return Object.keys(this.data)}get(e){return this.data[e]}has(e){return e in this.data}destroy(){this.data={}}}});var sO={};jt(sO,{ZipFetcher:()=>qh});var qh,aE=Me(()=>{x();sE();oE();Zg();th();qh=class{setBasePath(e){this.basePath=e}setEncryptionMap(e){this.encryptionMap=e}constructor(e,t=""){e instanceof ArrayBuffer||e instanceof Uint8Array?this.container=new dc(e):this.container=e,this.basePath=t}async get(e){let t=await this.getByHref(e.href);return e.type?{...t,mediaType:e.type}:t}async getByHref(e){let t=this.resolvePath(e),i=this.container.get(t);if(!i)throw Es.access(e,`Not found in archive: ${t}`);let r=fo(t),o=r.startsWith("text/")||r.includes("xml")||r.includes("json")||r.includes("javascript")?rE(i):"",a=this.encryptionMap?.get(t),u=a?{encrypted:a}:void 0;return{text:o,bytes:new Uint8Array(i).buffer,headers:{},mediaType:r,href:e,properties:u}}async has(e){let t=this.resolvePath(e.href);return this.container.has(t)}list(){return this.container.entries()}getBytes(e){return this.container.get(this.resolvePath(e))}destroy(){this.container.destroy()}resolvePath(e){let t=e,i=t.indexOf("?");i>=0&&(t=t.substring(0,i));let r=t.indexOf("#");r>=0&&(t=t.substring(0,r)),this.basePath&&t.startsWith(this.basePath)&&(t=t.substring(this.basePath.length)),t.startsWith("/")&&(t=t.substring(1));try{t=decodeURIComponent(t)}catch{}if(!this.container.has(t)){for(let s of this.container.entries())if(s.endsWith("/"+t)||s===t)return s}return t}static guessMediaType(e){return fo(e)}}});var oO={};jt(oO,{EpubParser:()=>$h});var $h,uE=Me(()=>{x();py();$h=class n{static async extractIdentifier(e){try{let t=await e.getByHref("META-INF/container.xml"),r=new DOMParser().parseFromString(t.text,"application/xml").querySelector("rootfile[full-path]")?.getAttribute("full-path")??"";if(!r)return"unknown";let s=await e.getByHref(r);return(new DOMParser().parseFromString(s.text,"application/xml").querySelector("metadata identifier")?.textContent?.trim()??"")||"unknown"}catch{return"unknown"}}static async parse(e,t){let i=await e.getByHref("META-INF/container.xml"),o=new DOMParser().parseFromString(i.text,"application/xml").querySelector("rootfile[full-path]")?.getAttribute("full-path");if(!o)throw new Error("EpubParser: no rootfile found in container.xml");let a=o.includes("/")?o.substring(0,o.lastIndexOf("/")+1):"",u=await e.getByHref(o),l=new DOMParser().parseFromString(u.text,"application/xml"),c=l.querySelector("metadata"),d=l.querySelector("manifest"),f=l.querySelector("spine"),m=c?.querySelector("title")?.textContent?.trim()??"",y=c?.querySelector("language")?.textContent?.trim()??"en",g=c?.querySelector("identifier")?.textContent?.trim()??"",b=c?.querySelectorAll("creator")??[],v=[];b.forEach(Ue=>{let lt=Ue.textContent?.trim();lt&&v.push({name:lt})});let A=c?.querySelector("publisher")?.textContent?.trim()??void 0,w=c?.querySelector("description")?.textContent?.trim()??void 0,S=c?.querySelectorAll("subject")??[],C=[];S.forEach(Ue=>{let lt=Ue.textContent?.trim();lt&&C.push(lt)});let T=c?.querySelector("date")?.textContent?.trim()??void 0,k=c?.querySelector('meta[property="dcterms:modified"]')?.textContent?.trim()??void 0,L=c?.querySelector('meta[property="schema:numberOfPages"]'),M=L&&parseInt(L.textContent?.trim()??"",10)||void 0,O=c?.querySelector('meta[property="rendition:layout"]')?.textContent?.trim()??"";O||c?.querySelector('meta[name="fixed-layout"]')?.getAttribute("content")==="true"&&(O="pre-paginated"),O||(O="reflowable");let U=f?.getAttribute("page-progression-direction"),G=U==="rtl"?"rtl":U==="ltr"?"ltr":void 0,z=c?.querySelector('meta[property="rendition:spread"]')?.textContent?.trim()??void 0,$=c?.querySelector('meta[property="rendition:orientation"]')?.textContent?.trim()??void 0,re=d?.querySelectorAll("item")??[],ae=new Map;re.forEach(Ue=>{let lt=Ue.getAttribute("id"),Kt=Ue.getAttribute("href"),hi=Ue.getAttribute("media-type")??"",Se=Ue.getAttribute("properties")??void 0;lt&&Kt&&ae.set(lt,{href:a+Kt,type:hi,properties:Se})});let fe=f?.querySelectorAll("itemref")??[],ge=[],se=[],de=new Set;fe.forEach(Ue=>{let lt=Ue.getAttribute("idref");if(!lt)return;let Kt=ae.get(lt);if(!Kt)return;if(de.add(lt),Ue.getAttribute("linear")==="no"){se.push({href:Kt.href,type:Kt.type});return}let Se={href:Kt.href,type:Kt.type},ve=Ue.getAttribute("properties");ve&&(Se.properties={page:ve}),ge.push(Se)});let Y=[...se],J=c?.querySelector('meta[name="cover"]')?.getAttribute("content")??void 0;ae.forEach((Ue,lt)=>{if(!de.has(lt)){let Kt={href:Ue.href,type:Ue.type};(Ue.properties?.includes("cover-image")||lt===J)&&(Kt.rel="cover"),Y.push(Kt)}});let Q=[],ie=[...ae.values()].find(Ue=>Ue.properties?.includes("nav"));if(ie)try{let Ue=await e.getByHref(ie.href);Q=n.parseNavToc(Ue.text,a)}catch{}if(Q.length===0){let Ue=f?.getAttribute("toc"),lt=Ue?ae.get(Ue):void 0;if(lt)try{let Kt=await e.getByHref(lt.href);Q=n.parseNcxToc(Kt.text,a)}catch{}}let He=c?.querySelector('meta[property="media:active-class"]')?.textContent?.trim(),Ze=c?.querySelector('meta[property="media:playback-active-class"]')?.textContent?.trim(),St={title:m,language:y,identifier:g,author:v.length>0?v:void 0,...A?{publisher:{name:A}}:{},...w?{description:w}:{},...C.length>0?{subject:C}:{},...T?{published:T}:{},...k?{modified:k}:{},...M?{numberOfPages:M}:{},...G?{readingProgression:G}:{},...O==="pre-paginated"?{layout:"fixed"}:{}},$e={};z&&($e["rendition:spread"]=z),$&&($e["rendition:orientation"]=$),He&&($e["media:active-class"]=He),Ze&&($e["media:playback-active-class"]=Ze),Object.keys($e).length>0&&(St.otherMetadata=$e);let Bt={metadata:St,readingOrder:ge,resources:Y,toc:Q,links:[]},Si=Ks.fromJSON(Bt,t);if(!Si)throw new Error("EpubParser: failed to create Publication from OPF");return Si}static parseNavToc(e,t){let i=new DOMParser().parseFromString(e,"application/xhtml+xml"),r=i.querySelector('nav[epub\\:type="toc"]')??i.querySelector('nav[role="doc-toc"]')??i.querySelector("nav");if(!r)return[];let s=a=>{let u=[];return a.querySelectorAll(":scope > li").forEach(c=>{let d=c.querySelector(":scope > a");if(!d)return;let f=d.getAttribute("href"),m=d.textContent?.trim();if(!f)return;let y={href:t+f,title:m},g=c.querySelector(":scope > ol");g&&(y.children=s(g)),u.push(y)}),u},o=r.querySelector("ol");return o?s(o):[]}static parseNcxToc(e,t){let i=new DOMParser().parseFromString(e,"application/xml"),r=o=>{let a=[];return o.querySelectorAll(":scope > navPoint").forEach(l=>{let c=l.querySelector("navLabel text")?.textContent?.trim(),d=l.querySelector("content")?.getAttribute("src");if(!d)return;let f={href:t+d,title:c};l.querySelectorAll(":scope > navPoint").length>0&&(f.children=r(l)),a.push(f)}),a},s=i.querySelector("navMap");return s?r(s):[]}}});var aO={};jt(aO,{BlobUrlManager:()=>Qh});var Qh,lE=Me(()=>{x();th();Qh=class{constructor(e){this.blobUrls=new Map;this.transforms=[];this.container="container"in e?e.container:e}setEncryptionMap(e){this.encryptionMap=e}addTransform(e){this.transforms.push(e)}async initialize(){let e=[];for(let t of this.container.entries()){if(t.endsWith("/"))continue;let i=this.container.get(t);if(!i)continue;let r=fo(t);if(r==="text/css"){e.push({path:t,bytes:i});continue}let s=i;if(this.transforms.length>0){let a=this.encryptionMap?.get(t),u={text:"",bytes:new Uint8Array(i).buffer,headers:{},mediaType:r,href:t,properties:a?{encrypted:a}:void 0};for(let l of this.transforms)u=await l(u);u.bytes&&(s=new Uint8Array(u.bytes))}let o=new Blob([new Uint8Array(s)],{type:r});this.blobUrls.set(t,URL.createObjectURL(o))}for(let{path:t,bytes:i}of e){let r=new TextDecoder().decode(i),s=t.includes("/")?t.substring(0,t.lastIndexOf("/")+1):"";r=this.rewriteCssUrls(r,s);let o=new Blob([r],{type:"text/css"});this.blobUrls.set(t,URL.createObjectURL(o))}}rewriteDom(e,t){let i=t.includes("/")?t.substring(0,t.lastIndexOf("/")+1):"";e.querySelectorAll("script").forEach(d=>{d.setAttribute("defer","")}),e.querySelectorAll("img, script, audio, video, source, input[type=image]").forEach(d=>{let f=d.getAttribute("src");if(f&&!this.isAbsolute(f)){let m=this.resolve(i,f),y=this.blobUrls.get(m);y&&d.setAttribute("src",y)}}),e.querySelectorAll("link[href], a[href]").forEach(d=>{let f=d.getAttribute("href");if(f&&!this.isAbsolute(f)&&!f.startsWith("#")){let m=this.resolve(i,f),y=this.blobUrls.get(m);y&&d.setAttribute("href",y)}}),e.querySelectorAll("[*|href]").forEach(d=>{let f=d.getAttributeNS("http://www.w3.org/1999/xlink","href")??d.getAttribute("xlink:href");if(f&&!this.isAbsolute(f)&&!f.startsWith("#")){let m=this.resolve(i,f),y=this.blobUrls.get(m);y&&d.setAttributeNS("http://www.w3.org/1999/xlink","href",y)}}),e.querySelectorAll("style").forEach(d=>{d.textContent&&(d.textContent=this.rewriteCssUrls(d.textContent,i))}),e.querySelectorAll("[style]").forEach(d=>{let f=d.getAttribute("style");f&&f.includes("url(")&&d.setAttribute("style",this.rewriteCssUrls(f,i))}),e.querySelectorAll('meta[http-equiv="Content-Security-Policy"]').forEach(d=>d.remove())}rewriteCssUrls(e,t){let i=e.replace(/url\(\s*["']?([^"')]+)["']?\s*\)/gi,(r,s)=>{if(this.isAbsolute(s)||s.startsWith("data:"))return r;let o=this.resolve(t,s),a=this.blobUrls.get(o);return a?`url("${a}")`:r});return i=i.replace(/@import\s+["']([^"']+)["']/gi,(r,s)=>{if(this.isAbsolute(s)||s.startsWith("data:"))return r;let o=this.resolve(t,s),a=this.blobUrls.get(o);return a?`@import "${a}"`:r}),i}isAbsolute(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("javascript:")||e.startsWith("mailto:")}resolve(e,t){let i=t.split("?")[0].split("#")[0],r=(e+i).split("/"),s=[];for(let o of r)o===".."?s.pop():o!=="."&&o!==""&&s.push(o);return s.join("/")}destroy(){for(let e of this.blobUrls.values())URL.revokeObjectURL(e);this.blobUrls.clear()}}});var uO={};jt(uO,{ALGORITHM_ADOBE:()=>dE,ALGORITHM_IDPF:()=>cE,createDeobfuscationTransform:()=>fE,deobfuscateAdobe:()=>jm,deobfuscateIdpf:()=>Um,parseEncryptionXml:()=>hE});function hE(n){let e=new Map;return new DOMParser().parseFromString(n,"application/xml").querySelectorAll("EncryptedData").forEach(r=>{let s=r.querySelector("EncryptionMethod")?.getAttribute("Algorithm")??"";if(s!==cE&&s!==dE)return;let o=r.querySelector("CipherData CipherReference")?.getAttribute("URI")??"";if(!o)return;let a;try{a=decodeURIComponent(o)}catch{a=o}let u={algorithm:s},l=r.querySelector("EncryptionProperties EncryptionProperty Compression");if(l){let c=parseInt(l.getAttribute("OriginalLength")??"",10);isNaN(c)||(u.originalLength=c)}e.set(a,u)}),e}async function Um(n,e){let t=e.replace(/\s+/g,""),i=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-1",i),s=new Uint8Array(r),o=new Uint8Array(n),a=Math.min(1040,o.length);for(let u=0;u<a;u++)o[u]=o[u]^s[u%s.length];return o}function jm(n,e){let t=e.replace(/^urn:uuid:/i,"").replace(/[- \t\r\n]/g,"");if(t.length<32)return n;t=t.substring(0,32);let i=new Uint8Array(16);for(let o=0;o<16;o++)i[o]=parseInt(t.substring(o*2,o*2+2),16);let r=new Uint8Array(n),s=Math.min(1024,r.length);for(let o=0;o<s;o++)r[o]=r[o]^i[o%i.length];return r}function fE(n){return async e=>{let t=e.properties?.encrypted;if(!t||!e.bytes)return e;let i;if(t.algorithm===cE)i=await Um(new Uint8Array(e.bytes),n);else if(t.algorithm===dE)i=jm(new Uint8Array(e.bytes),n);else return e;return{...e,bytes:i.buffer,text:e.text?new TextDecoder().decode(i):e.text}}}var cE,dE,pE=Me(()=>{x();cE="http://www.idpf.org/2008/embedding",dE="http://ns.adobe.com/pdf/enc#RC"});var lO={};jt(lO,{TransformingFetcher:()=>Xh});var Xh,gE=Me(()=>{x();Xh=class{constructor(e,...t){this.inner=e;this.transforms=t}async get(e){let t=await this.inner.get(e);for(let i of this.transforms)t=await i(t);return t}async getByHref(e){let t=await this.inner.getByHref(e);for(let i of this.transforms)t=await i(t);return t}cancel(e){this.inner.cancel?.(e)}destroy(){this.inner.destroy?.()}}});var dO={};jt(dO,{AudiobookSettings:()=>mE});function hc(n,e,t){return Math.max(e,Math.min(t,n))}var qi,cO,xn,Gm,mE,hO=Me(()=>{x();qi={volume:1,playbackRate:1,preservePitch:!0,skipBackwardInterval:10,skipForwardInterval:30,pollInterval:1e3,autoPlay:!0,enableMediaSession:!0,timelineMode:"chapter"},cO=new Set(["chapter","book","both"]),xn={volume:[0,1],playbackRate:[.5,4],skipBackwardInterval:[5,60],skipForwardInterval:[5,60],pollInterval:[0,Number.MAX_SAFE_INTEGER]},Gm="audiobook-",mE=class n{constructor(e){this.listeners=new Set;this._volume=qi.volume;this._playbackRate=qi.playbackRate;this._preservePitch=qi.preservePitch;this._skipBackwardInterval=qi.skipBackwardInterval;this._skipForwardInterval=qi.skipForwardInterval;this._pollInterval=qi.pollInterval;this._autoPlay=qi.autoPlay;this._enableMediaSession=qi.enableMediaSession;this._timelineMode=qi.timelineMode;this.store=e}static async create(e){let t=new n(e.store);return t.loadFromStore(),e.initialAudiobookSettings&&t.apply(e.initialAudiobookSettings),t}loadFromStore(){this._volume=this.readNumber("volume",qi.volume,xn.volume),this._playbackRate=this.readNumber("playbackRate",qi.playbackRate,xn.playbackRate),this._preservePitch=this.readBoolean("preservePitch",qi.preservePitch),this._skipBackwardInterval=this.readNumber("skipBackwardInterval",qi.skipBackwardInterval,xn.skipBackwardInterval),this._skipForwardInterval=this.readNumber("skipForwardInterval",qi.skipForwardInterval,xn.skipForwardInterval),this._pollInterval=this.readNumber("pollInterval",qi.pollInterval,xn.pollInterval),this._autoPlay=this.readBoolean("autoPlay",qi.autoPlay),this._enableMediaSession=this.readBoolean("enableMediaSession",qi.enableMediaSession),this._timelineMode=this.readEnum("timelineMode",qi.timelineMode,cO)}apply(e){e.volume!==void 0&&(this.volume=e.volume),e.playbackRate!==void 0&&(this.playbackRate=e.playbackRate),e.preservePitch!==void 0&&(this.preservePitch=e.preservePitch),e.skipBackwardInterval!==void 0&&(this.skipBackwardInterval=e.skipBackwardInterval),e.skipForwardInterval!==void 0&&(this.skipForwardInterval=e.skipForwardInterval),e.pollInterval!==void 0&&(this.pollInterval=e.pollInterval),e.autoPlay!==void 0&&(this.autoPlay=e.autoPlay),e.enableMediaSession!==void 0&&(this.enableMediaSession=e.enableMediaSession),e.timelineMode!==void 0&&(this.timelineMode=e.timelineMode)}toJSON(){return{volume:this._volume,playbackRate:this._playbackRate,preservePitch:this._preservePitch,skipBackwardInterval:this._skipBackwardInterval,skipForwardInterval:this._skipForwardInterval,pollInterval:this._pollInterval,autoPlay:this._autoPlay,enableMediaSession:this._enableMediaSession,timelineMode:this._timelineMode}}onChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}get volume(){return this._volume}set volume(e){let t=hc(e,xn.volume[0],xn.volume[1]);t!==this._volume&&(this._volume=t,this.persist("volume",t))}get playbackRate(){return this._playbackRate}set playbackRate(e){let t=hc(e,xn.playbackRate[0],xn.playbackRate[1]);t!==this._playbackRate&&(this._playbackRate=t,this.persist("playbackRate",t))}get preservePitch(){return this._preservePitch}set preservePitch(e){e!==this._preservePitch&&(this._preservePitch=e,this.persist("preservePitch",e))}get skipBackwardInterval(){return this._skipBackwardInterval}set skipBackwardInterval(e){let t=hc(e,xn.skipBackwardInterval[0],xn.skipBackwardInterval[1]);t!==this._skipBackwardInterval&&(this._skipBackwardInterval=t,this.persist("skipBackwardInterval",t))}get skipForwardInterval(){return this._skipForwardInterval}set skipForwardInterval(e){let t=hc(e,xn.skipForwardInterval[0],xn.skipForwardInterval[1]);t!==this._skipForwardInterval&&(this._skipForwardInterval=t,this.persist("skipForwardInterval",t))}get pollInterval(){return this._pollInterval}set pollInterval(e){let t=hc(e,xn.pollInterval[0],xn.pollInterval[1]);t!==this._pollInterval&&(this._pollInterval=t,this.persist("pollInterval",t))}get autoPlay(){return this._autoPlay}set autoPlay(e){e!==this._autoPlay&&(this._autoPlay=e,this.persist("autoPlay",e))}get enableMediaSession(){return this._enableMediaSession}set enableMediaSession(e){e!==this._enableMediaSession&&(this._enableMediaSession=e,this.persist("enableMediaSession",e))}get timelineMode(){return this._timelineMode}set timelineMode(e){cO.has(e)&&e!==this._timelineMode&&(this._timelineMode=e,this.persist("timelineMode",e))}readNumber(e,t,i){let r=this.store.get(Gm+e);if(r==null)return t;let s=Number(r);return Number.isFinite(s)?hc(s,i[0],i[1]):t}readBoolean(e,t){let i=this.store.get(Gm+e);return i==null?t:typeof i=="boolean"?i:i==="true"||i==="1"}readEnum(e,t,i){let r=this.store.get(Gm+e);return r==null||typeof r!="string"?t:i.has(r)?r:t}persist(e,t){this.store.set(Gm+e,String(t));for(let i of this.listeners)i(e)}}});var fO={};jt(fO,{AudiobookBookmarkModule:()=>bE});function Mne(n){(!Number.isFinite(n)||n<0)&&(n=0);let e=Math.floor(n/3600),t=Math.floor(n%3600/60),i=Math.floor(n%60),r=String(t).padStart(e>0?2:1,"0"),s=String(i).padStart(2,"0");return e>0?`${e}:${r}:${s}`:`${r}:${s}`}var Jh,bE,pO=Me(()=>{x();zt();Il();cn();Jh=class Jh{constructor(e){this.name=ye.Bookmarks;this.hostType=Ve.Audiobook;this.rightsKey=st.Bookmarks;this.annotator=e.annotator,this.publication=e.publication,this.listContainer=e.listContainer}static async create(e){return new Jh(e)}attach(e){this.host=e,this.listContainer&&this.renderList()}save(){if(this.hasBookmarkAt())return null;let e=this.makeBookmark();if(!e)return null;let t=this.annotator.saveBookmark(e)??null;return t&&(this.host.emit(ce.BookmarkCreated,t),this.listContainer&&this.renderList()),t}delete(e){this.annotator.deleteBookmark(e),this.host.emit(ce.BookmarkDeleted,e),this.listContainer&&this.renderList()}list(){return this.annotator.getBookmarks()}hasBookmarkAt(e){return this.findBookmarkAt(e)!==null}findBookmarkAt(e){let t=e??this.host.currentLocator(),i=t.href,r=t.locations?.time;if(!i||typeof r!="number")return null;let s=Jh.MATCH_TOLERANCE_SECONDS;return this.annotator.getBookmarks(this.publication.getAbsoluteHref(i)).find(a=>{let u=a.locations?.time;return typeof u=="number"&&Math.abs(u-r)<=s})??null}stop(){this.listContainer&&(this.listContainer.innerHTML="")}renderList(){let e=this.listContainer;if(!e)return;e.innerHTML="";let t=this.list();if(t.length===0)return;let i=this.publication.readingOrder,r=document.createElement("ol");r.className="dita-audiobook-bookmarks",i.forEach((s,o)=>{let a=this.publication.getAbsoluteHref(s.href),u=t.filter(c=>c.href===a).sort((c,d)=>(c.locations?.time??0)-(d.locations?.time??0));if(u.length===0)return;let l=document.createElement("li");l.className="dita-audiobook-bookmarks-heading",l.textContent=s.title||`Track ${o+1}`,r.appendChild(l);for(let c of u)r.appendChild(this.buildRow(c,s.href))}),e.appendChild(r)}buildRow(e,t){let i=document.createElement("li");i.className="dita-audiobook-bookmarks-row",i.tabIndex=0,i.setAttribute("role","button");let r=document.createElement("span");r.className="dita-audiobook-bookmarks-time",r.textContent=Mne(e.locations?.time??0),i.appendChild(r);let s=document.createElement("button");s.type="button",s.className="dita-audiobook-bookmarks-delete",s.setAttribute("aria-label","Delete bookmark"),s.textContent="\u2715",s.addEventListener("click",a=>{a.stopPropagation(),this.delete(e)}),i.appendChild(s);let o=a=>{a.target?.closest("button")||this.host.goTo({href:t,locations:{time:e.locations?.time??0}})};return i.addEventListener("click",o),i.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),o(a))}),i}makeBookmark(){let e=this.host.currentLocator();return e.href?{id:crypto.randomUUID(),href:this.publication.getAbsoluteHref(e.href),type:e.type??"audio/*",title:e.title,locations:e.locations,created:new Date}:null}};Jh.MATCH_TOLERANCE_SECONDS=1;bE=Jh});var gO={};jt(gO,{AudiobookCommentsModule:()=>yE});function One(n){(!Number.isFinite(n)||n<0)&&(n=0);let e=Math.floor(n/3600),t=Math.floor(n%3600/60),i=Math.floor(n%60),r=String(t).padStart(e>0?2:1,"0"),s=String(i).padStart(2,"0");return e>0?`${e}:${r}:${s}`:`${r}:${s}`}var wu,yE,mO=Me(()=>{x();zt();Il();cn();wu=class wu{constructor(e){this.name=ye.Comments;this.hostType=Ve.Audiobook;this.rightsKey=st.Comments;this.lastActiveIds="";this.annotator=e.annotator,this.publication=e.publication,this.listContainer=e.listContainer,this.onEdit=e.onEdit}static async create(e){return new wu(e)}attach(e){this.host=e,this.listContainer&&this.renderList()}onTimeUpdate(e){this.recomputeActive(e.locator,e.currentTime)}add(e,t){let i=t??this.host.currentLocator();if(!i.href)return null;let r={id:crypto.randomUUID(),href:this.publication.getAbsoluteHref(i.href),type:i.type??"audio/*",title:i.title,locations:i.locations,created:new Date,body:e},s=this.annotator.saveComment(r)??null;return s&&(this.host.emit(ce.CommentCreated,s),this.recomputeActive(this.host.currentLocator(),this.currentTime()),this.listContainer&&this.renderList()),s}update(e,t){let i=this.annotator.updateComment(e,t);return i&&(this.host.emit(ce.CommentUpdated,i),this.listContainer&&this.renderList()),i}delete(e){this.annotator.deleteComment(e.id),this.host.emit(ce.CommentDeleted,{id:e.id}),this.recomputeActive(this.host.currentLocator(),this.currentTime()),this.listContainer&&this.renderList()}list(){return this.annotator.getComments()}findAt(e){let t=e??this.host.currentLocator(),i=t.href,r=t.locations?.time;return!i||typeof r!="number"?[]:this.annotator.getComments(this.publication.getAbsoluteHref(i)).filter(o=>this.isWithinWindow(o,r))}stop(){this.listContainer&&(this.listContainer.innerHTML="")}renderList(){let e=this.listContainer;if(!e)return;e.innerHTML="";let t=this.list();if(t.length===0)return;let i=this.publication.readingOrder,r=document.createElement("ol");r.className="dita-audiobook-comments",i.forEach((s,o)=>{let a=this.publication.getAbsoluteHref(s.href),u=t.filter(c=>c.href===a).sort((c,d)=>(c.locations?.time??0)-(d.locations?.time??0));if(u.length===0)return;let l=document.createElement("li");l.className="dita-audiobook-comments-heading",l.textContent=s.title||`Track ${o+1}`,r.appendChild(l);for(let c of u)r.appendChild(this.buildRow(c,s.href))}),e.appendChild(r)}buildRow(e,t){let i=document.createElement("li");i.className="dita-audiobook-comments-row",i.tabIndex=0,i.setAttribute("role","button");let r=document.createElement("span");r.className="dita-audiobook-comments-body",r.textContent=e.body??"",i.appendChild(r);let s=document.createElement("span");if(s.className="dita-audiobook-comments-time",s.textContent=One(e.locations?.time??0),i.appendChild(s),this.onEdit){let u=document.createElement("button");u.type="button",u.className="dita-audiobook-comments-edit",u.setAttribute("aria-label","Edit comment"),u.textContent="\u270E",u.addEventListener("click",l=>{l.stopPropagation(),this.onEdit?.(e)}),i.appendChild(u)}let o=document.createElement("button");o.type="button",o.className="dita-audiobook-comments-delete",o.setAttribute("aria-label","Delete comment"),o.textContent="\u2715",o.addEventListener("click",u=>{u.stopPropagation(),this.delete(e)}),i.appendChild(o);let a=u=>{u.target?.closest("button")||this.host.goTo({href:t,locations:{time:e.locations?.time??0}})};return i.addEventListener("click",a),i.addEventListener("keydown",u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),a(u))}),i}isWithinWindow(e,t){let i=e.locations?.time;if(typeof i!="number")return!1;let r=e.displayBefore??wu.DEFAULT_DISPLAY_BEFORE_SECONDS,s=e.displayAfter??wu.DEFAULT_DISPLAY_AFTER_SECONDS;return t>=i-r&&t<=i+s}recomputeActive(e,t){let i=e.href;if(!i)return;let s=this.annotator.getComments(this.publication.getAbsoluteHref(i)).filter(a=>this.isWithinWindow(a,t)),o=s.map(a=>a.id).join(",");o!==this.lastActiveIds&&(this.lastActiveIds=o,this.host.emit(ce.CommentsActive,{active:s,currentTime:t}))}currentTime(){return this.host.currentLocator().locations?.time??0}};wu.DEFAULT_DISPLAY_BEFORE_SECONDS=5,wu.DEFAULT_DISPLAY_AFTER_SECONDS=10;yE=wu});var vO={};jt(vO,{AudiobookTimelineModule:()=>vE});function fc(n){(!Number.isFinite(n)||n<0)&&(n=0);let e=Math.floor(n/3600),t=Math.floor(n%3600/60),i=Math.floor(n%60),r=t.toString().padStart(e>0?2:1,"0"),s=i.toString().padStart(2,"0");return e>0?`${e}:${r}:${s}`:`${r}:${s}`}function yO(n){let e=document.createElement("div");return e.textContent=n,e.innerHTML}function Wm(n,e){let t=n.reduce((l,c)=>l+c,0);if(t<=0||e<0||e>=n.length){let l=0;return n.map(c=>{let d=t>0?l/t*100:0;return l+=c,{startPct:d,widthPct:t>0?c/t*100:0}})}let i=n[e]/t*100,r=Math.min(100,Math.max(Bne,Math.min(i*Dne,Nne))),s=Math.max(0,100-r),o=t-n[e],a=[],u=0;for(let l=0;l<n.length;l++){let c=l===e?r:o>0?n[l]/o*s:0;a.push({startPct:u,widthPct:c}),u+=c}return a}function Fne(n,e){for(let t=0;t<n.length;t++)if(e>=n[t].startPct&&e<n[t].startPct+n[t].widthPct)return t;return Math.max(0,n.length-1)}function Hne(n,e,t){for(let i=0;i<e.length;i++){let{startPct:r,widthPct:s}=e[i];if(t>=r&&t<r+s){let o=(t-r)/s,a=0;for(let u=0;u<i;u++)a+=n[u];return a+o*n[i]}}return n.reduce((i,r)=>i+r,0)}var Nne,Bne,Dne,bO,vE,AO=Me(()=>{x();zt();Il();Nne=28,Bne=8,Dne=5,bO=5;vE=class n{constructor(e){this.name=ye.Timeline;this.hostType=Ve.Audiobook;this.rightsKey=st.Timeline;this.bars=[];this.settingsUnsubscribe=null;this._chapterStarts=[];this._bookDuration=0;this.publication=e.publication,this.settings=e.settings,this.chapterScrubberContainer=e.chapterScrubberContainer,this.bookScrubberContainer=e.bookScrubberContainer}static async create(e){let t=new n(e);return t.rebuild(),t}attach(e){this.host=e,this.chapterScrubberContainer&&this.bars.push(this.buildBar(this.chapterScrubberContainer,"auto")),this.bookScrubberContainer&&this.bars.push(this.buildBar(this.bookScrubberContainer,"book")),this.settings&&(this.settingsUnsubscribe=this.settings.onChange(t=>{t==="timelineMode"&&this.redraw()})),this.redraw()}stop(){this.settingsUnsubscribe&&(this.settingsUnsubscribe(),this.settingsUnsubscribe=null);for(let e of this.bars)e.boundPointerMove&&window.removeEventListener("pointermove",e.boundPointerMove),e.boundPointerUp&&window.removeEventListener("pointerup",e.boundPointerUp),e.container.innerHTML="";this.bars=[]}rebuild(){let e=this.publication.readingOrder??[];this._chapterStarts=[];let t=0;for(let i of e)this._chapterStarts.push(t),t+=i.duration??0;this._bookDuration=t}get chapterStarts(){return this._chapterStarts}get bookDuration(){return this._bookDuration}get isUsable(){return this._bookDuration>0}toBookTime(e,t){if(this._chapterStarts.length===0)return 0;let i=Math.max(0,Math.min(this._chapterStarts.length-1,e|0)),r=Math.max(0,t||0);return this._chapterStarts[i]+r}fromBookTime(e){let t=this.publication.readingOrder??[];if(t.length===0)return{chapterIndex:0,timeInChapter:0,href:""};let i=Math.max(0,Math.min(this._bookDuration,e)),r=t.length-1;for(let s=0;s<t.length;s++){let a=this._chapterStarts[s]+(t[s].duration??0);if(i<a){r=s;break}}return{chapterIndex:r,timeInChapter:i-(this._chapterStarts[r]??0),href:t[r].href}}currentBookTime(){if(!this.host)return 0;let e=this.host.currentLocator();if(!e?.href)return 0;let i=(this.publication.readingOrder??[]).findIndex(s=>s.href===e.href);if(i<0)return 0;let r=e.locations?.time??0;return this.toBookTime(i,r)}onTimeUpdate(){for(let e of this.bars)this.renderPlayhead(e)}onTrackChanged(){this.redraw()}onDurationChanged(){this.rebuild(),this.redraw()}onBookmarkChanged(){for(let e of this.bars)this.renderMarkers(e)}onCommentChanged(){for(let e of this.bars)this.renderMarkers(e)}resolveScope(e){if((e.modeKind==="book"||this.timelineModeSetting()==="book")&&this.isUsable)return{scope:"book",duration:this._bookDuration,position:this.currentBookTime()};let i=this.host?.currentResource()??0,s=this.publication.readingOrder?.[i]?.duration??0,o=this.host?.currentLocator()?.locations?.time??0;return{scope:"chapter",duration:s,position:o}}timelineModeSetting(){return this.settings?.timelineMode??"chapter"}currentChapterIndex(){return this.host?.currentResource()??0}bookmarks(){return this.host?.getModule(ye.Bookmarks)?.list()??[]}comments(){return this.host?.getModule(ye.Comments)?.list()??[]}redraw(){for(let e of this.bars)this.renderMarkers(e),this.renderPlayhead(e)}buildBar(e,t){let i=document.createElement("div");i.className="dita-audiobook-timeline",i.setAttribute("role","slider"),i.tabIndex=0,i.setAttribute("aria-valuemin","0"),i.setAttribute("aria-valuemax","0"),i.setAttribute("aria-valuenow","0");let r=document.createElement("div");r.className="dita-audiobook-timeline-fill",i.appendChild(r);let s=document.createElement("div");s.className="dita-audiobook-timeline-markers",i.appendChild(s);let o=document.createElement("div");o.className="dita-audiobook-timeline-thumb",i.appendChild(o);let a=document.createElement("div");a.className="dita-audiobook-timeline-tooltip",a.setAttribute("aria-hidden","true"),i.appendChild(a),e.innerHTML="",e.appendChild(i);let u={container:e,modeKind:t,root:i,fill:r,thumb:o,markersHost:s,tooltip:a,isDragging:!1,dragValue:0,fisheye:null};return i.addEventListener("pointerdown",l=>this.beginDrag(u,l)),i.addEventListener("pointermove",l=>this.onHover(u,l)),i.addEventListener("pointerleave",()=>this.onHoverEnd(u)),i.addEventListener("keydown",l=>this.onKeyDown(u,l)),u}renderPlayhead(e){if(e.isDragging)return;let{duration:t,position:i}=this.resolveScope(e),r=t>0?Math.min(100,i/t*100):0;e.fill.style.width=r+"%",e.thumb.style.left=r+"%",e.root.setAttribute("aria-valuemin","0"),e.root.setAttribute("aria-valuemax",String(Math.round(t))),e.root.setAttribute("aria-valuenow",String(Math.round(i))),e.root.setAttribute("aria-valuetext",`${fc(i)} of ${fc(t)}`)}renderMarkers(e){e.markersHost.innerHTML="";let{scope:t,duration:i}=this.resolveScope(e);if(i<=0)return;let r=this.publication.readingOrder??[],s=this.bookmarks(),o=this.comments(),a=(u,l,c,d)=>{let f=Math.min(100,Math.max(0,u/i*100)),m=document.createElement("div");m.className=`dita-audiobook-timeline-marker ${l}`,m.style.left=f+"%",t==="book"&&(m.dataset.bookTime=String(u)),m.addEventListener("click",y=>{y.stopPropagation(),d()}),m.addEventListener("pointerenter",()=>{e.tooltip.innerHTML=c,e.tooltip.style.left=m.style.left,e.tooltip.dataset.visible="true"}),m.addEventListener("pointerleave",()=>{delete e.tooltip.dataset.visible}),e.markersHost.appendChild(m)};if(t==="book")r.forEach((u,l)=>{let c=this._chapterStarts[l]??0,d=u.duration??0,f=Math.min(100,Math.max(0,c/i*100)),m=Math.min(100,Math.max(0,d/i*100)),y=document.createElement("div");if(y.className="dita-audiobook-timeline-chapter",y.style.left=f+"%",y.style.width=m+"%",y.dataset.chapterIndex=String(l),y.dataset.chapterBand="true",e.markersHost.appendChild(y),l>0){let b=document.createElement("div");b.className="dita-audiobook-timeline-boundary",b.style.left=f+"%",b.dataset.chapterIndex=String(l);let v=u.title||`Track ${l+1}`;b.title=`${v} \u2014 ${fc(c)}`,b.setAttribute("aria-label",`Jump to ${v}`),b.addEventListener("click",A=>{A.stopPropagation(),this.seekToBookTime(c)}),e.markersHost.appendChild(b)}let g=this.publication.getAbsoluteHref(u.href);for(let b of s){if(b.href!==g)continue;let v=b.locations?.time;typeof v=="number"&&a(c+v,"bookmark",this.bookmarkTooltipHTML(v),()=>this.seekToBookTime(c+v))}for(let b of o){if(b.href!==g)continue;let v=b.locations?.time;typeof v=="number"&&a(c+v,"comment",this.commentTooltipHTML(b.body??"",v),()=>this.seekToBookTime(c+v))}});else{let u=this.currentChapterIndex(),l=r[u];if(!l)return;let c=this.publication.getAbsoluteHref(l.href);for(let d of s){if(d.href!==c)continue;let f=d.locations?.time;typeof f=="number"&&a(f,"bookmark",this.bookmarkTooltipHTML(f),()=>this.seekToChapterTime(f))}for(let d of o){if(d.href!==c)continue;let f=d.locations?.time;typeof f=="number"&&a(f,"comment",this.commentTooltipHTML(d.body??"",f),()=>this.seekToChapterTime(f))}}}bookmarkTooltipHTML(e){return`Bookmark<span class="dita-audiobook-timeline-tooltip-time">${fc(e)}</span>`}commentTooltipHTML(e,t){let i=e.length>60?e.slice(0,57)+"\u2026":e;return`${yO(i)}<span class="dita-audiobook-timeline-tooltip-time">${fc(t)}</span>`}onHover(e,t){let{scope:i}=this.resolveScope(e);i==="book"&&this.isUsable&&this.updateFisheye(e,t),this.updateTooltip(e,t)}onHoverEnd(e){e.fisheye&&(e.fisheye=null,this.applyFisheyeVisuals(e,-1)),delete e.tooltip.dataset.visible}updateFisheye(e,t){let r=(this.publication.readingOrder??[]).map(l=>l.duration??0);if(r.length<2)return;let s=this.cursorPercent(e,t),o=e.fisheye?.layout??Wm(r,-1),a=Fne(o,s),u=Wm(r,a);e.fisheye={layout:u,hoveredIdx:a},this.applyFisheyeVisuals(e,a)}applyFisheyeVisuals(e,t){let r=(this.publication.readingOrder??[]).map(o=>o.duration??0),s=Wm(r,t);for(let o of e.markersHost.querySelectorAll("[data-chapter-band]")){let a=Number(o.dataset.chapterIndex);!Number.isFinite(a)||!s[a]||(o.style.left=s[a].startPct+"%",o.style.width=s[a].widthPct+"%",a===t?o.dataset.hovered="true":delete o.dataset.hovered)}for(let o of e.markersHost.querySelectorAll("[data-chapter-index]:not([data-chapter-band])")){let a=Number(o.dataset.chapterIndex);Number.isFinite(a)&&s[a]&&(o.style.left=s[a].startPct+"%")}for(let o of e.markersHost.querySelectorAll("[data-book-time]")){let a=Number(o.dataset.bookTime);if(!Number.isFinite(a))continue;let u=this.fromBookTime(a),l=u.chapterIndex,c=r[l]>0?u.timeInChapter/r[l]:0,d=s[l];d&&(o.style.left=d.startPct+c*d.widthPct+"%")}}updateTooltip(e,t){if(t.target?.closest(".dita-audiobook-timeline-marker, .dita-audiobook-timeline-boundary"))return;let r=this.cursorPercent(e,t),{scope:s,duration:o}=this.resolveScope(e);if(o<=0){delete e.tooltip.dataset.visible;return}let a=this.publication.readingOrder??[],u="",l=0;if(s==="book"){let c=this.cursorBookTime(e,t),d=this.fromBookTime(c);u=a[d.chapterIndex]?.title||`Track ${d.chapterIndex+1}`,l=d.timeInChapter}else{let c=this.currentChapterIndex();u=a[c]?.title||`Track ${c+1}`,l=r/100*o}e.tooltip.innerHTML=`${yO(u)}<span class="dita-audiobook-timeline-tooltip-time">${fc(l)}</span>`,e.tooltip.style.left=r+"%",e.tooltip.dataset.visible="true"}cursorPercent(e,t){let i=e.root.getBoundingClientRect();return Math.max(0,Math.min(100,(t.clientX-i.left)/i.width*100))}cursorBookTime(e,t){let r=(this.publication.readingOrder??[]).map(o=>o.duration??0),s=e.fisheye?.layout??Wm(r,-1);return Hne(r,s,this.cursorPercent(e,t))}beginDrag(e,t){let{duration:i}=this.resolveScope(e);i<=0||(e.isDragging=!0,e.root.classList.add("dragging"),this.updateDrag(e,t),e.boundPointerMove=r=>this.updateDrag(e,r),e.boundPointerUp=()=>this.endDrag(e),window.addEventListener("pointermove",e.boundPointerMove),window.addEventListener("pointerup",e.boundPointerUp,{once:!0}))}updateDrag(e,t){if(!e.isDragging)return;let{scope:i,duration:r}=this.resolveScope(e),s=this.cursorPercent(e,t);if(i==="book"){this.updateFisheye(e,t),e.dragValue=this.cursorBookTime(e,t);let o=this.fromBookTime(e.dragValue);this.host.prefetchResource(o.chapterIndex)}else e.dragValue=s/100*r;e.fill.style.width=s+"%",e.thumb.style.left=s+"%",e.root.setAttribute("aria-valuenow",String(Math.round(e.dragValue)))}endDrag(e){if(!e.isDragging)return;e.isDragging=!1,e.root.classList.remove("dragging"),e.boundPointerMove&&(window.removeEventListener("pointermove",e.boundPointerMove),e.boundPointerMove=void 0),e.boundPointerUp=void 0;let{scope:t}=this.resolveScope(e);t==="book"?this.seekToBookTime(e.dragValue):this.seekToChapterTime(e.dragValue)}onKeyDown(e,t){let{scope:i,duration:r,position:s}=this.resolveScope(e);if(r<=0)return;let o=null;switch(t.key){case"ArrowLeft":t.preventDefault(),o=Math.max(0,s-bO);break;case"ArrowRight":t.preventDefault(),o=Math.min(r,s+bO);break;case"Home":t.preventDefault(),o=0;break;case"End":t.preventDefault(),o=Math.max(0,r-1);break}o!==null&&(i==="book"?this.seekToBookTime(o):this.seekToChapterTime(o))}seekToChapterTime(e){let t=this.currentChapterIndex(),i=this.publication.readingOrder?.[t];i&&this.host.goTo({href:i.href,locations:{time:e}})}seekToBookTime(e){let t=this.fromBookTime(e);this.host.goTo({href:t.href,locations:{time:t.timeInChapter}})}}});var wO={};jt(wO,{PdfBookmarkModule:()=>AE});var AE,EO=Me(()=>{x();zt();ei();Nn();AE=class{constructor(e){this.name=ye.Bookmarks;this.hostType=Ve.PDF;this.rightsKey=st.Bookmarks;this.annotator=e.annotator,this.publication=e.publication}attach(e){this.host=e}save(){return this.hasBookmarkAt()?null:this.annotator.saveBookmark(this.makeBookmark())??null}delete(e){this.annotator.deleteBookmark(e)}list(){return this.host.currentResourceLink?this.annotator.getBookmarks(this.publication.getAbsoluteHref(this.host.currentResourceLink.href)):[]}hasBookmarkAt(e){return this.findBookmarkAt(e)!==null}findBookmarkAt(e){let t=(e?Ur(e.locations):void 0)??this.host.currentPage;return this.list().find(i=>Ur(i.locations)===t)??null}stop(){}makeBookmark(){return{id:crypto.randomUUID(),href:this.host.currentResourceLink?this.publication.getAbsoluteHref(this.host.currentResourceLink.href):"",locations:{page:this.host.currentPage},type:"application/pdf",title:`Page ${this.host.currentPage}`,created:new Date}}}});var CO={};jt(CO,{PdfSearchModule:()=>wE});var wE,SO=Me(()=>{x();zt();ei();cn();wE=class{constructor(){this.name=ye.Search;this.hostType=Ve.PDF;this.rightsKey=st.Search;this._query="";this._caseSensitive=!1;this._highlightAll=!0;this._entireWord=!1;this._matchCount=0;this._currentMatch=0;this.onMatchesUpdate=e=>{e?.matchesCount&&(this._currentMatch=e.matchesCount.current??0,this._matchCount=e.matchesCount.total??0,this.host.emit(ce.PdfMatchesUpdated,{current:this._currentMatch,total:this._matchCount}))}}attach(e){this.host=e}setup(){this.host.eventBus.on("updatefindmatchescount",this.onMatchesUpdate),this.host.eventBus.on("updatefindcontrolstate",this.onMatchesUpdate)}search(e,t){this._query=e,this._caseSensitive=t?.caseSensitive??!1,this._highlightAll=t?.highlightAll??!0,this._entireWord=t?.entireWord??!1,this.host.eventBus.dispatch("find",{query:e,caseSensitive:this._caseSensitive,highlightAll:this._highlightAll,entireWord:this._entireWord,findPrevious:!1,type:""})}next(){this._query&&this.host.eventBus.dispatch("find",{query:this._query,caseSensitive:this._caseSensitive,highlightAll:this._highlightAll,entireWord:this._entireWord,findPrevious:!1,type:"again"})}previous(){this._query&&this.host.eventBus.dispatch("find",{query:this._query,caseSensitive:this._caseSensitive,highlightAll:this._highlightAll,entireWord:this._entireWord,findPrevious:!0,type:"again"})}clear(){this._query="",this._matchCount=0,this._currentMatch=0,this.host.eventBus.dispatch("find",{query:"",caseSensitive:!1,highlightAll:!0,entireWord:!1,findPrevious:!1,type:""})}matchCount(){return this._matchCount}currentMatch(){return this._currentMatch}stop(){this.host?.eventBus.off("updatefindmatchescount",this.onMatchesUpdate),this.host?.eventBus.off("updatefindcontrolstate",this.onMatchesUpdate)}}});var TO={};jt(TO,{PdfAnnotationModule:()=>EE});function Une(n){return typeof n=="object"&&n!==null&&"bitmap"in n&&n.bitmap!==void 0}function jne(n){return typeof n=="object"&&n!==null&&"pageIndex"in n&&typeof n.pageIndex=="number"?n.pageIndex:0}var xO,EE,IO=Me(()=>{x();xO=Xe(to());zt();ei();K4();EE=class n{constructor(e){this.name=ye.Annotations;this.hostType=Ve.PDF;this.rightsKey=st.Annotations;this.pendingAnnotations=null;this.onLayerRendered=async e=>{if(e.error||!this.pendingAnnotations)return;let t=e.pageNumber-1,i=this.pendingAnnotations.get(t);if(!i||i.length===0)return;this.pendingAnnotations.delete(t);let r=e.source?.annotationEditorLayer?.annotationEditorLayer;if(!r||!this.host.pdfDoc)return;let s=this.host.pdfDoc.annotationStorage,o=DM(s);Mm(s,null);for(let a of i)try{let u=await r.deserialize(a);u&&r.addOrRebuild(u)}catch(u){console.warn("PdfAnnotationModule: failed to restore annotation",a,u)}Mm(s,o),this.save()};this.viewStore=e.viewStore}attach(e){this.host=e}setup(){this.debouncedSave=(0,xO.default)(()=>{this.host.pdfDoc&&this.save()},200),this.host.eventBus.on("annotationeditorlayerrendered",this.onLayerRendered),this.host.eventBus.on("annotationeditorstateschanged",this.debouncedSave)}onResourceReady(){let e=this.host.fingerprint??"";!e||e===this.lastFingerprint||(this.lastFingerprint=e,this.pendingAnnotations=null,this.restore(e),this.host.pdfDoc&&Mm(this.host.pdfDoc.annotationStorage,()=>{this.save()}))}stop(){this.host?.eventBus.off("annotationeditorlayerrendered",this.onLayerRendered),this.host?.eventBus.off("annotationeditorstateschanged",this.debouncedSave)}getAll(){let e=[];if(this.host.pdfDoc){let{map:t}=Om(this.host.pdfDoc.annotationStorage);if(t)for(let i of t.values())e.push(n.toJsonSafe(i))}if(this.pendingAnnotations)for(let t of this.pendingAnnotations.values())for(let i of t)e.push(i);return e.sort((t,i)=>(t.pageIndex??0)-(i.pageIndex??0)),e}clear(){if(!this.host.pdfDoc)return;let e=this.host.pdfDoc.annotationStorage,{map:t}=Om(e);if(t)for(let r of t.keys())e.remove(r);let i=this.host.fingerprint;this.viewStore&&i&&this.viewStore.remove(this.storageKey(i)),this.pendingAnnotations=null}setEditorMode(e){this.host.pdfViewer.annotationEditorMode={mode:e}}save(){if(!this.viewStore||!this.host.pdfDoc)return;let e=this.host.fingerprint??"",t=this.storageKey(e),i={},{map:r}=Om(this.host.pdfDoc.annotationStorage);if(r)for(let[s,o]of r)Une(o)||(i[s]=n.toJsonSafe(o));if(this.pendingAnnotations){let s=0;for(let[o,a]of this.pendingAnnotations)for(let u of a)i[`_pending_p${o}_${s++}`]=u}Object.keys(i).length===0?this.viewStore.remove(t):this.viewStore.set(t,JSON.stringify(i))}restore(e){if(this.pendingAnnotations=null,!this.viewStore)return;let t=this.storageKey(e),i=this.viewStore.get(t);if(i)try{let r=JSON.parse(i),s=new Map;for(let o of Object.values(r)){let a=jne(o);s.has(a)||s.set(a,[]),s.get(a).push(o)}this.pendingAnnotations=s}catch{}}storageKey(e){return`pdf-ann-${e}`}static toJsonSafe(e){if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Array.from(e);if(Array.isArray(e))return e.map(n.toJsonSafe);if(e!==null&&typeof e=="object"){let t={};for(let[i,r]of Object.entries(e))t[i]=n.toJsonSafe(r);return t}return e}}});var kO={};jt(kO,{PdfHistoryModule:()=>CE});var CE,_O=Me(()=>{x();zt();ei();Nn();CE=class{constructor(){this.name=ye.History;this.hostType=Ve.PDF;this.rightsKey=st.History;this.stack=[];this.cursor=-1}attach(e){this.host=e}setup(){}push(e){let t=Ur(e.locations);t!==void 0&&(this.cursor<this.stack.length-1&&(this.stack=this.stack.slice(0,this.cursor+1)),this.stack[this.stack.length-1]!==t&&(this.stack.push(t),this.cursor=this.stack.length-1))}back(){this.canGoBack()&&(this.cursor-=1,this.host.goToPage(this.stack[this.cursor]))}forward(){this.canGoForward()&&(this.cursor+=1,this.host.goToPage(this.stack[this.cursor]))}canGoBack(){return this.cursor>0}canGoForward(){return this.cursor<this.stack.length-1}stop(){}}});var PO={};jt(PO,{PdfViewSettingsModule:()=>SE});var $i,SE,RO=Me(()=>{x();zt();ei();z4();$i=class $i{constructor(e){this.name=ye.ViewSettings;this.hostType=Ve.PDF;this.onPagesInit=()=>{this.restore()};this.viewStore=e.viewStore}attach(e){this.host=e}setup(){this.host.eventBus.on("pagesinit",this.onPagesInit)}fitToWidth(){this.host.pdfViewer.currentScaleValue="page-width",this.saveSetting($i.KEY_SCALE,"page-width")}fitToPage(){this.host.pdfViewer.currentScaleValue="page-fit",this.saveSetting($i.KEY_SCALE,"page-fit")}zoomIn(){this.host.pdfViewer.increaseScale(),this.saveSetting($i.KEY_SCALE,this.host.pdfViewer.currentScaleValue)}zoomOut(){this.host.pdfViewer.decreaseScale(),this.saveSetting($i.KEY_SCALE,this.host.pdfViewer.currentScaleValue)}rotateCw(){this.host.pdfViewer.pagesRotation=(this.host.pdfViewer.pagesRotation+90)%360,this.saveSetting($i.KEY_ROTATE,this.host.pdfViewer.pagesRotation)}rotateCcw(){this.host.pdfViewer.pagesRotation=(this.host.pdfViewer.pagesRotation+270)%360,this.saveSetting($i.KEY_ROTATE,this.host.pdfViewer.pagesRotation)}setSpreadMode(e){this.host.pdfViewer.spreadMode=e,this.saveSetting($i.KEY_SPREAD,e)}setScrollMode(e,t){let i=e?t==="horizontal"?ot.HORIZONTAL:t==="wrapped"?ot.WRAPPED:ot.VERTICAL:ot.PAGE;this.host.pdfViewer.scrollMode=i,this.saveSetting($i.KEY_SCROLL,i)}stop(){this.host?.eventBus.off("pagesinit",this.onPagesInit)}saveSetting(e,t){this.viewStore.set(e,String(t))}restore(){let e=this.viewStore,t=e.get($i.KEY_SCROLL),i=e.get($i.KEY_SPREAD),r=e.get($i.KEY_SCALE),s=e.get($i.KEY_ROTATE);this.host.pdfViewer.currentScaleValue=r??"page-fit",t!=null&&(this.host.pdfViewer.scrollMode=Number(t)),i!=null&&(this.host.pdfViewer.spreadMode=Number(i)),s!=null&&(this.host.pdfViewer.pagesRotation=Number(s))}};$i.KEY_SCROLL="pdf-scroll-mode",$i.KEY_SPREAD="pdf-spread-mode",$i.KEY_SCALE="pdf-scale-value",$i.KEY_ROTATE="pdf-rotation";SE=$i});var XO={};jt(XO,{AntiAutomation:()=>VO,BrowserEnforcement:()=>UO,ContentExpiration:()=>YO,ContentProtection:()=>Gne,ContextMenuProtection:()=>NO,CopyProtection:()=>OO,DevToolsDetection:()=>DO,DragPrevention:()=>LO,ImageProtection:()=>zO,KeyboardProtection:()=>BO,LinkUrlHiding:()=>HO,MediaProtection:()=>qO,MediaStreamProtection:()=>$O,PrintProtection:()=>MO,ScreenshotDetection:()=>jO,SelectionLimiting:()=>WO,SpeechSynthesisBlocking:()=>KO,TamperDetection:()=>QO,TextObfuscation:()=>FO,Watermarking:()=>GO});function xE(){return typeof navigator<"u"&&(/Mac/.test(navigator.platform)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1)}function di(n,e,t,i){if(!n)return null;try{return n.addEventListener(e,t,i),{target:n,type:e,handler:t,options:i}}catch{return null}}function Eo(n){for(let{target:e,type:t,handler:i,options:r}of n)try{e.removeEventListener(t,i,r)}catch{}n.length=0}function zm(n,e,t){let i=[n,window,document];if(e&&i.push(...e),t)for(let r of t)try{i.push(r),r.ownerDocument&&i.push(r.ownerDocument),r.contentDocument&&(i.push(r.contentDocument),r.contentDocument.body&&i.push(r.contentDocument.body)),r.contentWindow&&(i.push(r.contentWindow),r.contentWindow.document&&i.push(r.contentWindow.document))}catch{}return i}var LO,MO,OO,NO,BO,DO,FO,HO,UO,jO,GO,WO,zO,VO,KO,YO,qO,$O,QO,Gne,JO=Me(()=>{x();LO=class{constructor(n){this.listeners=[],this.styledElements=[],this.config=n}activate(){let n=t=>(t.preventDefault(),t.stopPropagation(),this.config.onEvent?.({type:"drag_blocked",timestamp:Date.now()}),!1),e=zm(this.config.contentElement,this.config.additionalElements,this.config.contentIframes);for(let t of e)for(let i of["dragstart","drag","drop"]){let r=di(t,i,n,!0);r&&this.listeners.push(r)}if(this.applyCss(this.config.contentElement),this.config.contentIframes)for(let t of this.config.contentIframes)try{let i=t.contentDocument?.body;i&&this.applyCss(i)}catch{}}deactivate(){Eo(this.listeners);for(let n of this.styledElements)n.style.removeProperty("-webkit-user-drag"),n.style.removeProperty("user-drag");this.styledElements=[]}applyCss(n){n.style.setProperty("-webkit-user-drag","none"),n.style.setProperty("user-drag","none"),this.styledElements.push(n),n.querySelectorAll("img").forEach(e=>{e.setAttribute("draggable","false")})}},MO=class{constructor(n){this.listeners=[],this.styleElements=[],this.config=n}activate(){if(this.styleElements.push(this.injectPrintCss(document)),this.config.contentIframes)for(let s of this.config.contentIframes)try{let o=s.contentDocument;o&&this.styleElements.push(this.injectPrintCss(o))}catch{}let n=s=>(this.onBeforePrint(),s.preventDefault?.(),s.stopPropagation?.(),this.config.onEvent?.({type:"print_blocked",timestamp:Date.now()}),!1),e=()=>this.onAfterPrint(),t=[window];if(this.config.contentIframes)for(let s of this.config.contentIframes)try{s.contentWindow&&t.push(s.contentWindow)}catch{}for(let s of t){let o=di(s,"beforeprint",n),a=di(s,"afterprint",e);o&&this.listeners.push(o),a&&this.listeners.push(a)}let i=s=>{let o=s;(xE()?o.metaKey:o.ctrlKey)&&o.key==="p"&&(o.preventDefault(),o.stopPropagation(),this.config.onEvent?.({type:"print_blocked",timestamp:Date.now(),detail:"keyboard"}))},r=di(document,"keydown",i,!0);if(r&&this.listeners.push(r),this.config.contentIframes)for(let s of this.config.contentIframes)try{let o=s.contentDocument;if(o){let a=di(o,"keydown",i,!0);a&&this.listeners.push(a)}}catch{}}deactivate(){Eo(this.listeners);for(let n of this.styleElements)n.remove();this.styleElements=[]}injectPrintCss(n){let e=n.createElement("style");return e.setAttribute("data-protection","print"),e.textContent=`
|
|
604
|
+
`)}#S(e,t){let i=document.getSelection(),{focusNode:r,anchorNode:s}=i;if(s&&r&&i.containsNode(this.#x)){if(this.#A||e===ks.ENABLE_PERMISSIONS){p4(t);return}this.#A=!0;let{classList:o}=this.viewer;o.add("copyAll");let a=new AbortController;window.addEventListener("keydown",u=>this.#w=u.key==="Escape",{signal:a.signal}),this.getAllText().then(async u=>{u!==null&&await navigator.clipboard.writeText(u)}).catch(u=>{console.warn(`Something goes wrong when extracting the text: ${u.message}`)}).finally(()=>{this.#A=!1,this.#w=!1,a.abort(),o.remove("copyAll")}),p4(t)}}setDocument(e){if(this.pdfDocument&&(this.eventBus.dispatch("pagesdestroy",{source:this}),this._cancelRendering(),this._resetView(),this.findController?.setDocument(null),this._scriptingManager?.setDocument(null),this.#r?.destroy(),this.#r=null,this.#i=Kn.NONE,this.#v=!0),this.pdfDocument=e,!e)return;let t=e.numPages,i=e.getPage(1),r=e.getOptionalContentConfig({intent:"display"}),s=this.#d?e.getPermissions():Promise.resolve(),{eventBus:o,pageColors:a,viewer:u}=this;this.#c=new AbortController;let{signal:l}=this.#c;if(t>ym.FORCE_SCROLL_MODE_PAGE){console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document.");let f=this._scrollMode=ot.PAGE;o.dispatch("scrollmodechanged",{source:this,mode:f})}this._pagesCapability.promise.then(()=>{o.dispatch("pagesloaded",{source:this,pagesCount:t})},()=>{});let c=f=>{let m=this._pages[f.pageNumber-1];m&&this.#e.push(m)};o._on("pagerender",c,{signal:l});let d=f=>{f.cssTransform||f.isDetailView||(this._onePageRenderedCapability.resolve({timestamp:f.timestamp}),o._off("pagerendered",d))};o._on("pagerendered",d,{signal:l}),Promise.all([i,s]).then(([f,m])=>{if(e!==this.pdfDocument)return;this._firstPageCapability.resolve(f),this._optionalContentConfigPromise=r;let{annotationEditorMode:y,annotationMode:g,textLayerMode:b}=this.#z(m);if(b!==ks.DISABLE){let S=this.#x=document.createElement("div");S.id="hiddenCopyElement",u.before(S)}if(y!==Kn.DISABLE){let S=y;e.isPureXfa?console.warn("Warning: XFA-editing is not implemented."):CM(S)?(this.#r=new Ste(this.container,u,this.#B,this.#t,this.#s,this.#N,o,e,a,this.#n,this.#h,this.#f,this.#m,this.#y,this.#l,this.#M),o.dispatch("annotationeditoruimanager",{source:this,uiManager:this.#r}),S!==Kn.NONE&&(this.#ee(S),this.#r.updateMode(S))):console.error(`Invalid AnnotationEditor mode: ${S}`)}let v=this._scrollMode===ot.PAGE?null:u,A=this.currentScale,w=f.getViewport({scale:A*vo.PDF_TO_CSS_UNITS});u.style.setProperty("--scale-factor",w.scale),a?.background&&u.style.setProperty("--page-bg-color",a.background),(a?.foreground==="CanvasText"||a?.background==="Canvas")&&(u.style.setProperty("--hcm-highlight-filter",e.filterFactory.addHighlightHCMFilter("highlight","CanvasText","Canvas","HighlightText","Highlight")),u.style.setProperty("--hcm-highlight-selected-filter",e.filterFactory.addHighlightHCMFilter("highlight_selected","CanvasText","Canvas","HighlightText","ButtonText")));for(let S=1;S<=t;++S){let C=new Rm({container:v,eventBus:o,id:S,scale:A,defaultViewport:w.clone(),optionalContentConfigPromise:r,renderingQueue:this.renderingQueue,textLayerMode:b,annotationMode:g,imageResourcesPath:this.imageResourcesPath,maxCanvasPixels:this.maxCanvasPixels,maxCanvasDim:this.maxCanvasDim,capCanvasAreaFactor:this.capCanvasAreaFactor,enableDetailCanvas:this.enableDetailCanvas,enableOptimizedPartialRendering:this.enableOptimizedPartialRendering,pageColors:a,l10n:this.l10n,layerProperties:this._layerProperties,enableHWA:this.#u,enableAutoLinking:this.#p,minDurationToUpdateCanvas:this.#g,commentManager:this.#s});this._pages.push(C)}this._pages[0]?.setPdfPage(f),this._scrollMode===ot.PAGE?this.#R():this._spreadMode!==Fi.NONE&&this._updateSpreadMode(),o._on("annotationeditorlayerrendered",S=>{this.#r&&o.dispatch("annotationeditormodechanged",{source:this,mode:this.#i})},{once:!0,signal:l}),this.#_(l).then(async()=>{if(e!==this.pdfDocument)return;if(this.findController?.setDocument(e),this._scriptingManager?.setDocument(e),this.#x&&document.addEventListener("copy",this.#S.bind(this,b),{signal:l}),e.loadingParams.disableAutoFetch||t>ym.FORCE_LAZY_PAGE_INIT){this._pagesCapability.resolve();return}let S=t-1;if(S<=0){this._pagesCapability.resolve();return}for(let C=2;C<=t;++C){let T=e.getPage(C).then(_=>{let k=this._pages[C-1];k.pdfPage||k.setPdfPage(_),--S===0&&this._pagesCapability.resolve()},_=>{console.error(`Unable to get page ${C} to initialize viewer`,_),--S===0&&this._pagesCapability.resolve()});C%ym.PAUSE_EAGER_PAGE_INIT===0&&await T}}),o.dispatch("pagesinit",{source:this}),e.getMetadata().then(({info:S})=>{e===this.pdfDocument&&S.Language&&(u.lang=S.Language)}),this.defaultRenderingQueue&&this.update()}).catch(f=>{console.error("Unable to initialize viewer",f),this._pagesCapability.reject(f)})}onPagesEdited({pagesMapper:e,type:t,hasBeenCut:i,pageNumbers:r}){if(t==="copy"){this.#L=new Map;for(let l of r)this.#L.set(l,this._pages[l-1]);return}let s=t==="cut";if(s||t==="delete")for(let l of r)this._pages[l-1].deleteMe(s);this._currentPageNumber=0;let o=this._pages,a=this._pages=[];for(let l=1,c=e.pagesNumber;l<=c;l++){let d=e.getPrevPageNumber(l);if(d<0){let m=this.#L.get(-d);i?m.updatePageNumber(l):m=m.clone(l),a.push(m);continue}let f=o[d-1];a.push(f),f.updatePageNumber(l)}s||(this.#L=null);let u=this._scrollMode===ot.PAGE?null:this.viewer;if(u){u.replaceChildren();let l=document.createDocumentFragment();for(let c=0,d=e.pagesNumber;c<d;c++){let{div:f}=a[c];f.setAttribute("data-page-number",c+1),l.append(f)}u.append(l)}setTimeout(()=>{this.forceRendering()})}setPageLabels(e){if(this.pdfDocument){e?Array.isArray(e)&&this.pdfDocument.numPages===e.length?this._pageLabels=e:(this._pageLabels=null,console.error("setPageLabels: Invalid page labels.")):this._pageLabels=null;for(let t=0,i=this._pages.length;t<i;t++)this._pages[t].setPageLabel(this._pageLabels?.[t]??null)}}_resetView(){this._pages=[],this._currentPageNumber=1,this._currentScale=o4,this._currentScaleValue=null,this._pageLabels=null,this.#e=new j4(EM),this._location=null,this._pagesRotation=0,this._optionalContentConfigPromise=null,this._firstPageCapability=Promise.withResolvers(),this._onePageRenderedCapability=Promise.withResolvers(),this._pagesCapability=Promise.withResolvers(),this._scrollMode=ot.VERTICAL,this._previousScrollMode=ot.UNKNOWN,this._spreadMode=Fi.NONE,this.#k={previousPageNumber:1,scrollDown:!0,pages:[]},this.#c?.abort(),this.#c=null,this.viewer.textContent="",this._updateScrollMode(),this.viewer.removeAttribute("lang"),this.#x?.remove(),this.#x=null,this.#X(),this.#J()}#R(){if(this._scrollMode!==ot.PAGE)throw new Error("#ensurePageViewVisible: Invalid scrollMode value.");let e=this._currentPageNumber,t=this.#k,i=this.viewer;if(i.textContent="",t.pages.length=0,this._spreadMode===Fi.NONE&&!this.isInPresentationMode){let r=this._pages[e-1];i.append(r.div),t.pages.push(r)}else{let r=new Set,s=this._spreadMode-1;s===-1?r.add(e-1):e%2!==s?(r.add(e-1),r.add(e)):(r.add(e-2),r.add(e-1));let o=document.createElement("div");if(o.className="spread",this.isInPresentationMode){let a=document.createElement("div");a.className="dummyPage",o.append(a)}for(let a of r){let u=this._pages[a];u&&(o.append(u.div),t.pages.push(u))}i.append(o)}t.scrollDown=e>=t.previousPageNumber,t.previousPageNumber=e}_scrollUpdate(){this.pagesCount!==0&&(this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{this.#b=null,this.update()},100),this.update())}#D(e,t=null){let{div:i,id:r}=e;if(this._currentPageNumber!==r&&this._setCurrentPageNumber(r),this._scrollMode===ot.PAGE&&(this.#R(),this.update()),!t&&!this.isInPresentationMode){let s=i.offsetLeft+i.clientLeft,o=s+i.clientWidth,{scrollLeft:a,clientWidth:u}=this.container;(this._scrollMode===ot.HORIZONTAL||s<a||o>a+u)&&(t={left:0,top:0})}PM(i,t),!this._currentScaleValue&&this._location&&(this._location=null)}#W(e){return e===this._currentScale||Math.abs(e-this._currentScale)<1e-15}#Y(e,t,{noScroll:i=!1,preset:r=!1,drawingDelay:s=-1,origin:o=null}){if(this._currentScaleValue=t.toString(),this.#W(e)){r&&this.eventBus.dispatch("scalechanging",{source:this,scale:e,presetValue:t});return}this.viewer.style.setProperty("--scale-factor",e*vo.PDF_TO_CSS_UNITS);let a=s>=0&&s<1e3;this.refresh(!0,{scale:e,drawingDelay:a?s:-1}),a&&(this.#I=setTimeout(()=>{this.#I=null,this.refresh()},s));let u=this._currentScale;if(this._currentScale=e,!i){let l=this._currentPageNumber,c;if(this._location&&!(this.isInPresentationMode||this.isChangingPresentationMode)&&(l=this._location.pageNumber,c=[null,{name:"XYZ"},this._location.left,this._location.top,null]),this.scrollPageIntoView({pageNumber:l,destArray:c,allowNegativeOffset:!0}),Array.isArray(o)){let d=e/u-1,[f,m]=this.containerTopLeft;this.container.scrollLeft+=(o[0]-m)*d,this.container.scrollTop+=(o[1]-f)*d}}this.eventBus.dispatch("scalechanging",{source:this,scale:e,presetValue:r?t:void 0}),this.defaultRenderingQueue&&this.update()}get#q(){return this._spreadMode!==Fi.NONE&&this._scrollMode!==ot.HORIZONTAL?2:1}#U(e,t){let i=parseFloat(e);if(i>0)t.preset=!1,this.#Y(i,e,t);else{let r=this._pages[this._currentPageNumber-1];if(!r)return;let s=$9,o=Q9;this.isInPresentationMode?(s=o=4,this._spreadMode!==Fi.NONE&&(s*=2)):this.removePageBorders?s=o=0:this._scrollMode===ot.HORIZONTAL&&([s,o]=[o,s]);let a=(this.container.clientWidth-s)/r.width*r.scale/this.#q,u=(this.container.clientHeight-o)/r.height*r.scale;switch(e){case"page-actual":i=1;break;case"page-width":i=a;break;case"page-height":i=u;break;case"page-fit":i=Math.min(a,u);break;case"auto":let l=Z9(r)?a:Math.min(u,a);i=Math.min(Fte,l);break;default:console.error(`#setScale: "${e}" is an unknown zoom value.`);return}t.preset=!0,this.#Y(i,e,t)}}#G(){let e=this._pages[this._currentPageNumber-1];this.isInPresentationMode&&this.#U(this._currentScaleValue,{noScroll:!0}),this.#D(e)}pageLabelToPageNumber(e){if(!this._pageLabels)return null;let t=this._pageLabels.indexOf(e);return t<0?null:t+1}scrollPageIntoView({pageNumber:e,destArray:t=null,allowNegativeOffset:i=!1,ignoreDestinationZoom:r=!1,center:s=null}){if(!this.pdfDocument)return;let o=Number.isInteger(e)&&this._pages[e-1];if(!o){console.error(`scrollPageIntoView: "${e}" is not a valid pageNumber parameter.`);return}if(this.isInPresentationMode||!t){this._setCurrentPageNumber(e,!0);return}let a=0,u=0,l=0,c=0,d,f,m=o.rotation%180!==0,y=(m?o.height:o.width)/o.scale/vo.PDF_TO_CSS_UNITS,g=(m?o.width:o.height)/o.scale/vo.PDF_TO_CSS_UNITS,b=0;switch(t[1].name){case"XYZ":a=t[2],u=t[3],b=t[4],a=a!==null?a:0,u=u!==null?u:g;break;case"Fit":case"FitB":b="page-fit";break;case"FitH":case"FitBH":u=t[2],b="page-width",u===null&&this._location?(a=this._location.left,u=this._location.top):(typeof u!="number"||u<0)&&(u=g);break;case"FitV":case"FitBV":a=t[2],l=y,c=g,b="page-height";break;case"FitR":a=t[2],u=t[3],l=t[4]-a,c=t[5]-u;let S=$9,C=Q9;this.removePageBorders&&(S=C=0),d=(this.container.clientWidth-S)/l/vo.PDF_TO_CSS_UNITS,f=(this.container.clientHeight-C)/c/vo.PDF_TO_CSS_UNITS,b=Math.min(Math.abs(d),Math.abs(f));break;default:console.error(`scrollPageIntoView: "${t[1].name}" is not a valid destination type.`);return}if(r||(b&&b!==this._currentScale?this.currentScaleValue=b:this._currentScale===o4&&(this.currentScaleValue=Nte)),b==="page-fit"&&!t[4]){this.#D(o);return}let v=[o.viewport.convertToViewportPoint(a,u),o.viewport.convertToViewportPoint(a+l,u+c)],A=Math.min(v[0][0],v[1][0]),w=Math.min(v[0][1],v[1][1]);s?((s==="both"||s==="vertical")&&(w-=(this.container.clientHeight-Math.abs(v[1][1]-v[0][1]))/2),(s==="both"||s==="horizontal")&&(A-=(this.container.clientWidth-Math.abs(v[1][0]-v[0][0]))/2)):i||(A=Math.max(A,0),w=Math.max(w,0)),this.#D(o,{left:A,top:w})}_updateLocation(e){let t=this._currentScale,i=this._currentScaleValue,r=parseFloat(i)===t?Math.round(t*1e4)/100:i,s=e.id,o=this._pages[s-1],a=this.container,u=o.getPagePoint(a.scrollLeft-e.x,a.scrollTop-e.y),l=Math.round(u[0]),c=Math.round(u[1]),d=`#page=${s}`;this.isInPresentationMode||(d+=`&zoom=${r},${l},${c}`),this._location={pageNumber:s,scale:r,top:c,left:l,rotation:this._pagesRotation,pdfOpenParams:d}}update(){let e=this._getVisiblePages(),t=e.views,i=t.length;if(i===0)return;let r=Math.max(EM,2*i+1);this.#e.resize(r,e.ids);for(let{view:u,visibleArea:l}of t)u.updateVisibleArea(l);for(let u of this.#e)e.ids.has(u.id)||u.updateVisibleArea(null);this.renderingQueue.renderHighestPriority(e);let s=this._spreadMode===Fi.NONE&&(this._scrollMode===ot.PAGE||this._scrollMode===ot.VERTICAL),o=this._currentPageNumber,a=!1;for(let u of t){if(u.percent<100)break;if(u.id===o&&s){a=!0;break}}this._setCurrentPageNumber(a?this._currentPageNumber:t[0].id),this._updateLocation(e.first),this.eventBus.dispatch("updateviewarea",{source:this,location:this._location})}#F(){let e=this._getVisiblePages(),t=[],{ids:i,views:r}=e;for(let s of r){let{view:o}=s;if(!o.hasEditableAnnotations()){i.delete(o.id);continue}t.push(s)}return t.length===0?null:(this.renderingQueue.renderHighestPriority({first:t[0],last:t.at(-1),views:t,ids:i}),i)}containsElement(e){return this.container.contains(e)}focus(){this.container.focus()}get _isContainerRtl(){return getComputedStyle(this.container).direction==="rtl"}get isInPresentationMode(){return this.presentationModeState===rc.FULLSCREEN}get isChangingPresentationMode(){return this.presentationModeState===rc.CHANGING}get isHorizontalScrollbarEnabled(){return this.isInPresentationMode?!1:this.container.scrollWidth>this.container.clientWidth}get isVerticalScrollbarEnabled(){return this.isInPresentationMode?!1:this.container.scrollHeight>this.container.clientHeight}_getVisiblePages(){let e=this._scrollMode===ot.PAGE?this.#k.pages:this._pages,t=this._scrollMode===ot.HORIZONTAL,i=t&&this._isContainerRtl;return jte({scrollEl:this.container,views:e,sortByVisibility:!0,horizontal:t,rtl:i})}cleanup(){for(let e of this._pages)e.renderingState!==Tt.FINISHED&&e.reset()}_cancelRendering(){for(let e of this._pages)e.cancelRendering()}async#V(e){if(e.pdfPage)return e.pdfPage;try{let t=await this.pdfDocument.getPage(e.id);return e.pdfPage||e.setPdfPage(t),t}catch(t){return console.error("Unable to get page for page view",t),null}}#Z(e){if(e.first?.id===1)return!0;if(e.last?.id===this.pagesCount)return!1;switch(this._scrollMode){case ot.PAGE:return this.#k.scrollDown;case ot.HORIZONTAL:return this.scroll.right}return this.scroll.down}forceRendering(e){let t=e||this._getVisiblePages(),i=this.#Z(t),r=this._spreadMode!==Fi.NONE&&this._scrollMode!==ot.HORIZONTAL,s=this.#I!==null||this.#b!==null&&t.views.some(a=>a.detailView?.renderingCancelled),o=this.renderingQueue.getHighestPriority(t,this._pages,i,r,s);return o?(this.#V(o).then(()=>{this.renderingQueue.renderView(o)}),!0):!1}get hasEqualPageSizes(){let e=this._pages[0];for(let t=1,i=this._pages.length;t<i;++t){let r=this._pages[t];if(r.width!==e.width||r.height!==e.height)return!1}return!0}getPagesOverview(){let e;return this._pages.map(t=>{let i=t.pdfPage.getViewport({scale:1}),r=Z9(i);if(e===void 0)e=r;else if(this.enablePrintAutoRotate&&r!==e)return{width:i.height,height:i.width,rotation:(i.rotation-90)%360};return{width:i.width,height:i.height,rotation:i.rotation}})}get optionalContentConfigPromise(){return this.pdfDocument?this._optionalContentConfigPromise?this._optionalContentConfigPromise:(console.error("optionalContentConfigPromise: Not initialized yet."),this.pdfDocument.getOptionalContentConfig({intent:"display"})):Promise.resolve(null)}set optionalContentConfigPromise(e){if(!(e instanceof Promise))throw new Error(`Invalid optionalContentConfigPromise: ${e}`);this.pdfDocument&&this._optionalContentConfigPromise&&(this._optionalContentConfigPromise=e,this.refresh(!1,{optionalContentConfigPromise:e}),this.eventBus.dispatch("optionalcontentconfigchanged",{source:this,promise:e}))}get scrollMode(){return this._scrollMode}set scrollMode(e){if(this._scrollMode!==e){if(!Gte(e))throw new Error(`Invalid scroll mode: ${e}`);this.pagesCount>ym.FORCE_SCROLL_MODE_PAGE||(this._previousScrollMode=this._scrollMode,this._scrollMode=e,this.eventBus.dispatch("scrollmodechanged",{source:this,mode:e}),this._updateScrollMode(this._currentPageNumber))}}_updateScrollMode(e=null){let t=this._scrollMode,i=this.viewer;i.classList.toggle("scrollHorizontal",t===ot.HORIZONTAL),i.classList.toggle("scrollWrapped",t===ot.WRAPPED),!(!this.pdfDocument||!e)&&(t===ot.PAGE?this.#R():this._previousScrollMode===ot.PAGE&&this._updateSpreadMode(),this._currentScaleValue&&isNaN(this._currentScaleValue)&&this.#U(this._currentScaleValue,{noScroll:!0}),this._setCurrentPageNumber(e,!0),this.update())}get spreadMode(){return this._spreadMode}set spreadMode(e){if(this._spreadMode!==e){if(!Wte(e))throw new Error(`Invalid spread mode: ${e}`);this._spreadMode=e,this.eventBus.dispatch("spreadmodechanged",{source:this,mode:e}),this._updateSpreadMode(this._currentPageNumber)}}_updateSpreadMode(e=null){if(!this.pdfDocument)return;let t=this.viewer,i=this._pages;if(this._scrollMode===ot.PAGE)this.#R();else if(t.textContent="",this._spreadMode===Fi.NONE)for(let r of this._pages)t.append(r.div);else{let r=this._spreadMode-1,s=null;for(let o=0,a=i.length;o<a;++o)s===null?(s=document.createElement("div"),s.className="spread",t.append(s)):o%2===r&&(s=s.cloneNode(!1),t.append(s)),s.append(i[o].div)}e&&(this._currentScaleValue&&isNaN(this._currentScaleValue)&&this.#U(this._currentScaleValue,{noScroll:!0}),this._setCurrentPageNumber(e,!0),this.update())}#$(e,t=!1){switch(this._scrollMode){case ot.WRAPPED:{let{views:i}=this._getVisiblePages(),r=new Map;for(let{id:s,y:o,percent:a,widthPercent:u}of i)a===0||u<100||r.getOrInsertComputed(o,Pte).push(s);for(let s of r.values()){let o=s.indexOf(e);if(o===-1)continue;let a=s.length;if(a===1)break;if(t)for(let u=o-1,l=0;u>=l;u--){let c=s[u],d=s[u+1]-1;if(c<d)return e-d}else for(let u=o+1,l=a;u<l;u++){let c=s[u],d=s[u-1]+1;if(c>d)return d-e}if(t){let u=s[0];if(u<e)return e-u+1}else{let u=s[a-1];if(u>e)return u-e+1}break}break}case ot.HORIZONTAL:break;case ot.PAGE:case ot.VERTICAL:{if(this._spreadMode===Fi.NONE)break;let i=this._spreadMode-1;if(t&&e%2!==i)break;if(!t&&e%2===i)break;let{views:r}=this._getVisiblePages(),s=t?e-1:e+1;for(let{id:o,percent:a,widthPercent:u}of r)if(o===s){if(a>0&&u===100)return 2;break}break}}return 1}nextPage(){let e=this._currentPageNumber,t=this.pagesCount;if(e>=t)return!1;let i=this.#$(e,!1)||1;return this.currentPageNumber=Math.min(e+i,t),!0}previousPage(){let e=this._currentPageNumber;if(e<=1)return!1;let t=this.#$(e,!0)||1;return this.currentPageNumber=Math.max(e-t,1),!0}updateScale({drawingDelay:e,scaleFactor:t=null,steps:i=null,origin:r}){if(i===null&&t===null)throw new Error("Invalid updateScale options: either `steps` or `scaleFactor` must be provided.");if(!this.pdfDocument)return;let s=this._currentScale;if(t>0&&t!==1)s=Math.round(s*t*100)/100;else if(i){let o=i>0?q9:1/q9,a=i>0?Math.ceil:Math.floor;i=Math.abs(i);do s=a((s*o).toFixed(2)*10)/10;while(--i>0)}s=IM(s,Bte,Dte),this.#U(s,{noScroll:!1,drawingDelay:e,origin:r})}increaseScale(e={}){this.updateScale({...e,steps:e.steps??1})}decreaseScale(e={}){this.updateScale({...e,steps:-(e.steps??1)})}#j(e=this.container.clientHeight){e!==this.#T&&(this.#T=e,zte.setProperty("--viewer-container-height",`${e}px`))}#Q(e){for(let t of e)if(t.target===this.container){this.#j(Math.floor(t.borderBoxSize[0].blockSize)),this.#a=null;break}}get containerTopLeft(){return this.#a||=[this.container.offsetTop,this.container.offsetLeft]}#X(){this.#I!==null&&(clearTimeout(this.#I),this.#I=null),this.#b!==null&&(clearTimeout(this.#b),this.#b=null)}#J(){this.#C?.abort(),this.#C=null,this.#E!==null&&(clearTimeout(this.#E),this.#E=null)}#ee(e){switch(e){case Kn.STAMP:this.#y?.loadModel("altText");break;case Kn.SIGNATURE:this.#N?.loadSignatures();break}}get annotationEditorMode(){return this.#r?this.#i:Kn.DISABLE}set annotationEditorMode({mode:e,editId:t=null,isFromKeyboard:i=!1,mustEnterInEditMode:r=!1,editComment:s=!1}){if(!this.#r)throw new Error("The AnnotationEditor is not enabled.");if(this.#i===e)return;if(!CM(e))throw new Error(`Invalid AnnotationEditor mode: ${e}`);if(!this.pdfDocument)return;this.#ee(e);let{eventBus:o,pdfDocument:a}=this,u=async()=>{this.#J(),this.#i=e,await this.#r.updateMode(e,t,!0,i,r,s),!(e!==this.#i||a!==this.pdfDocument)&&o.dispatch("annotationeditormodechanged",{source:this,mode:e})};if(e===Kn.NONE||this.#i===Kn.NONE){let l=e!==Kn.NONE;l||this.pdfDocument.annotationStorage.resetModifiedIds(),this.cleanup();for(let d of this._pages)d.toggleEditingMode(l);let c=this.#F();if(l&&c){this.#J(),this.#C=new AbortController;let d=AbortSignal.any([this.#c.signal,this.#C.signal]);o._on("pagerendered",({pageNumber:f})=>{c.delete(f),c.size===0&&(this.#E=setTimeout(u,0))},{signal:d});return}}u()}refresh(e=!1,t=Object.create(null)){if(this.pdfDocument){for(let i of this._pages)i.update(t);this.#X(),e||this.update()}}},G4=class extends lc{_resetView(){super._resetView(),this._scrollMode=ot.PAGE,this._spreadMode=Fi.NONE}set scrollMode(e){}_updateScrollMode(){}set spreadMode(e){}_updateSpreadMode(){}};globalThis.pdfjsViewer={AnnotationLayerBuilder:Cm,DownloadManager:b4,EventBus:oc,FindState:fa,GenericL10n:uc,LinkTarget:yu,parseQueryString:Lm,PDFFindController:Gh,PDFHistory:Vh,PDFLinkService:sc,PDFPageView:Rm,PDFScriptingManager:H4,PDFSinglePageViewer:G4,PDFViewer:lc,ProgressBar:g4,RenderingStates:Tt,ScrollMode:ot,SimpleLinkService:Wh,SpreadMode:Fi,StructTreeLayerBuilder:km,TextLayerBuilder:_m,XfaLayerBuilder:Pm}});function Mm(n,e){n.onSetModified=e}function DM(n){return n.onSetModified}function Om(n){return n.serializable}function V4(n){n.setDocument(null)}function FM(n){n.setDocument(null)}var K4=Me(()=>{x()});var HM={};jt(HM,{AnnotationEditorType:()=>Je,PDFNavigator:()=>Y4,ScrollMode:()=>ot,SpreadMode:()=>Fi});var Y4,UM=Me(()=>{x();zt();Ul();ei();cn();Nn();V9();z4();yn();$t();K4();h3();c3();Y4=class extends Zo{constructor(t){super();this.rights={};this.pageNum=1;this.resourceIndex=0;this.pdfDoc=null;this.numPages=0;this.positionRestored=!1;this.onResize=()=>{clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout(()=>{if(this.pdfViewer){let t=this.pdfViewer.currentScaleValue;this.pdfViewer.currentScaleValue=t}},200)};this.settings=t.settings,this.publication=t.publication,this.api=t.api,this.rights=t.rights??{},this.workerSrc=t.workerSrc??`https://unpkg.com/pdfjs-dist@${r4}/build/pdf.worker.min.mjs`,this.annotator=t.annotator,this.initialLastReadingPosition=t.initialLastReadingPosition,this.fetcher=new ho,this.registerModules(t.modules,Ve.PDF)}supports(t){return t===ye.Zoom?!0:this.registry.has(t)}get currentPage(){return this.pageNum}get totalPages(){return this.pdfDoc?.numPages??this.numPages??0}get fingerprint(){return this.pdfDoc?.fingerprints[0]??void 0}get currentResourceLink(){return this.resource}static async create(t){let i=new this(t);return await i.start(t.mainElement,t.headerMenu,t.footerMenu),i}async start(t,i,r){this.headerMenu=i,this.footerMenu=r,this.mainElement=t,this.resourceIndex=0,this.resource=this.publication.readingOrder[this.resourceIndex],mo.workerSrc=this.workerSrc,this.wrapper=yt(this.mainElement,"#iframe-wrapper"),this.pdfContainer=yt(this.mainElement,"#pdf-container"),this.wrapper.style.position="absolute",this.wrapper.style.overflow="auto",this.wrapper.style.top="0",this.wrapper.style.left="0",this.wrapper.style.right="0",this.wrapper.style.bottom="0",this.pdfContainer.classList.add("pdfViewer"),this.handTool=new Gl({element:this.wrapper}),this.eventBus=new oc,this.linkService=new sc({eventBus:this.eventBus}),this.findController=new Gh({linkService:this.linkService,eventBus:this.eventBus}),this.pdfViewer=new lc({container:this.wrapper,viewer:this.pdfContainer,eventBus:this.eventBus,linkService:this.linkService,findController:this.findController,textLayerMode:1,annotationMode:xs.ENABLE_STORAGE,annotationEditorMode:Je.NONE,annotationEditorHighlightColors:"Yellow=#FFFF98,Green=#53FFBC,Blue=#80EBFF,Pink=#FFCBE6,Red=#FF4F5F"}),this.linkService.setViewer(this.pdfViewer),this.pdfViewer.spreadMode=Fi.NONE,this.pdfHistory=new Vh({eventBus:this.eventBus,linkService:this.linkService}),this.linkService.setHistory(this.pdfHistory),this.eventBus.on("pagesinit",()=>{this.pdfViewer.currentPageNumber=this.pageNum}),this.eventBus.on("pagechanging",({pageNumber:s})=>{this.pageNum=s,this.saveLastReadingPosition(),this.emit(ce.PageChanged,{page:s,totalPages:this.pdfDoc?.numPages??this.numPages}),this.atStart()?(this.api?.resourceAtStart?.(),this.emit(ce.ResourceStart,{href:this.publication.readingOrder[0]?.href})):this.atEnd()&&(this.api?.resourceAtEnd?.(),this.emit(ce.ResourceEnd,{href:this.publication.readingOrder[0]?.href}))}),this.eventBus.on("pagesloaded",async({pagesCount:s})=>{this.numPages=s,this.hideLoading(),this.api?.resourceReady?.(),this.emit(ce.ResourceReady,{href:this.publication.readingOrder[0]?.href}),this.registry.notifyResourceReady(),this.positionRestored||(this.positionRestored=!0,await this.restoreLastReadingPosition())}),await this.registry.setupAll(),this.showLoading(),await this.loadDocument(this.publication.getAbsoluteHref(this.resource.href),1),ee(window,"resize",this.onResize)}showLoading(){let t=document.getElementById("loadingpdf");if(t){t.style.display="flex";return}t=document.createElement("div"),t.id="loadingpdf",t.innerHTML=Jg,Object.assign(t.style,{position:"absolute",inset:"0",display:"flex",zIndex:"100",alignItems:"center",justifyContent:"center",background:"white"}),t.className="dita-loading is-loading",(this.wrapper.parentElement??document.body).appendChild(t)}hideLoading(){let t=document.getElementById("loadingpdf");t&&(t.style.display="none")}async loadDocument(t,i){this.showLoading(),this.pageNum=i,this.pdfDoc&&(V4(this.pdfViewer),FM(this.linkService),await this.pdfDoc.destroy(),this.pdfDoc=null);try{let r;if("getBytes"in this.fetcher){let a=this.fetcher.getBytes(t);a?r=Bh({data:a}):r=Bh(t)}else r=Bh(t);let s=await r.promise;this.pdfDoc=s,this.pdfViewer.setDocument(s),this.linkService.setDocument(s),this.pdfHistory.initialize({fingerprint:s.fingerprints[0]??""})}catch(r){this.hideLoading();let s=r instanceof Error?r:new Error(String(r));console.error("PDFNavigator: failed to load document",t,s),this.api?.onError?.(s),this.emit(ce.ResourceError,s)}}atStart(){return this.pageNum<=1&&this.resourceIndex===0}atEnd(){return this.resourceIndex>=this.publication.readingOrder.length-1&&this.pageNum>=(this.pdfDoc?.numPages??1)}currentResource(){return this.resourceIndex}currentLocator(){let t=this.pdfDoc?.numPages??this.numPages??1,i=t>1?(this.pageNum-1)/(t-1):0;return{href:this.resource?this.publication.getAbsoluteHref(this.resource.href):"",title:`Page ${this.pageNum}`,locations:{page:this.pageNum,progression:i},type:"application/pdf"}}nextPage(){if(this.pageNum>=(this.pdfDoc?.numPages??1)){this.nextResource();return}this.pdfViewer.nextPage()}previousPage(){if(this.pageNum<=1){this.previousResource();return}this.pdfViewer.previousPage()}nextResource(){this.resourceIndex>=this.publication.readingOrder.length-1||(this.resourceIndex++,this.resource=this.publication.readingOrder[this.resourceIndex],this.loadDocument(this.publication.getAbsoluteHref(this.resource.href),1))}previousResource(){this.resourceIndex!==0&&(this.resourceIndex--,this.resource=this.publication.readingOrder[this.resourceIndex],this.loadDocument(this.publication.getAbsoluteHref(this.resource.href),this.pdfDoc?.numPages??1))}goTo(t){let i=Ur(t.locations);if(typeof i=="number"){this.pdfViewer.currentPageNumber=i;return}let r=t.href??"",s=this.pageFromHref(r)??1;if(r){let o=r.split("#")[0].split("?")[0],a=this.publication.readingOrder.findIndex(u=>{if(!u.href)return!1;let l=this.publication.getAbsoluteHref(u.href);return u.href===o||l===o||l===this.toAbsoluteHref(o)});if(a>=0&&a!==this.resourceIndex){this.resourceIndex=a,this.resource=this.publication.readingOrder[this.resourceIndex],this.loadDocument(this.publication.getAbsoluteHref(this.resource.href),s);return}}this.pdfViewer.currentPageNumber=s}pageFromHref(t){if(!t)return null;let i=t.match(/#page=(\d+)/i);if(i)return parseInt(i[1],10);try{let r=new URL(t,window.location.href);if(r.searchParams.has("start"))return parseInt(r.searchParams.get("start"),10);if(r.searchParams.has("page"))return parseInt(r.searchParams.get("page"),10)}catch{}return null}toAbsoluteHref(t){try{return new URL(t,window.location.href).href}catch{return t}}goToPosition(t){this.pdfViewer.currentPageNumber=t}async goToPage(t){this.pdfViewer.currentPageNumber=t}fitToWidth(){this.modules.viewSettings?.fitToWidth()}fitToPage(){this.modules.viewSettings?.fitToPage()}zoomIn(){this.modules.viewSettings?.zoomIn()}zoomOut(){this.modules.viewSettings?.zoomOut()}activateHand(){this.handTool.activate()}deactivateHand(){this.handTool.deactivate()}async scroll(t,i){this.modules.viewSettings?.setScrollMode(t,i)}saveLastReadingPosition(){if(!this.annotator||!this.resource)return;let t={href:this.publication.getAbsoluteHref(this.resource.href),locations:{page:this.pageNum},type:"application/pdf",created:new Date};this.api?.updateCurrentLocation?this.api.updateCurrentLocation(t).then(()=>{this.annotator.saveLastReadingPosition(t)}):this.annotator.saveLastReadingPosition(t),this.emit(ce.LocationChanged,t)}async restoreLastReadingPosition(){if(this.initialLastReadingPosition&&this.annotator?.initLastReadingPosition(this.initialLastReadingPosition),!this.annotator)return;let t=this.annotator.getLastReadingPosition();if(!t)return;let i=Ur(t.locations)??1,r=this.publication.readingOrder.findIndex(s=>s.href&&this.publication.getAbsoluteHref(s.href)===t.href);r>=0&&r!==this.resourceIndex?(this.resourceIndex=r,this.resource=this.publication.readingOrder[this.resourceIndex],await this.loadDocument(this.publication.getAbsoluteHref(this.resource.href),i)):this.pdfViewer.currentPageNumber=i}stop(){this.registry.stopAll(),we(window,"resize",this.onResize),this.pdfViewer&&V4(this.pdfViewer),this.pdfDoc?.destroy(),this.pdfDoc=null}}});var jM=Me(()=>{x()});function q4(n){return e=>({kind:"url",url:n.getAbsoluteHref(e.href)})}var GM,Nm,$4=Me(()=>{x();GM=1,Nm=class n{constructor(e){this.pool=new Map;this.destroyed=!1;this.engine=e.engine,this.publication=e.publication,this.resolveSource=e.resolveSource??q4(e.publication),this.supportedAudioTypes=n.detectSupportedAudioTypes(e.publication)}setCurrentAudio(e){if(this.destroyed)return;let t=this.publication.readingOrder;if(e<0||e>=t.length)return;let i=this.resolveSourceFor(t[e]);this.engine.changeSrc(i);let r=n.cacheKeyFor(i);r!==void 0&&this.releasePoolEntry(r),this.update(e)}prefetchAt(e){if(this.destroyed)return;let t=this.publication.readingOrder;if(e<0||e>=t.length)return;let i=this.resolveSourceFor(t[e]),r=n.cacheKeyFor(i);r!==void 0&&this.ensure(r)}get size(){return this.pool.size}destroy(){if(!this.destroyed){this.destroyed=!0;for(let[,e]of this.pool)n.releaseElement(e);this.pool.clear()}}ensure(e){let t=this.pool.get(e);if(t)return t;let i=document.createElement("audio");return i.preload="auto",this.engine.isWebAudioActive&&(i.crossOrigin="anonymous"),i.src=e,i.load(),this.pool.set(e,i),i}update(e){let t=this.publication.readingOrder,i=new Set;for(let r=0;r<t.length;r++){if(r===e||r<e-GM||r>e+GM)continue;let s=this.resolveSourceFor(t[r]),o=n.cacheKeyFor(s);o!==void 0&&(this.ensure(o),i.add(o))}for(let[r,s]of this.pool)i.has(r)||(n.releaseElement(s),this.pool.delete(r))}static cacheKeyFor(e){switch(e.kind){case"url":case"drm":return e.url;case"hls":case"vendor":return}}releasePoolEntry(e){let t=this.pool.get(e);t&&(n.releaseElement(t),this.pool.delete(e))}resolveSourceFor(e){let t=this.pickPlayableLink(e);return this.resolveSource(t)}static detectSupportedAudioTypes(e){let t=document.createElement("audio"),i=new Set;for(let s of e.readingOrder){s.type&&i.add(s.type);let o=s.alternates;if(o)for(let a of o.items)a.type&&i.add(a.type)}let r=new Map;for(let s of i){let o=t.canPlayType(s);(o==="probably"||o==="maybe")&&r.set(s,o)}return r}pickPlayableLink(e){let t=[e],i=e.alternates;if(i)for(let s of i.items)t.push(s);let r;for(let s of t){let o=s.type;if(!o)continue;let a=this.supportedAudioTypes.get(o);if(a==="probably")return s;a==="maybe"&&!r&&(r=s)}return r??e}static releaseElement(e){e.removeAttribute("src"),e.load()}}});var cne,dne,hne,Bm,WM=Me(()=>{x();$4();cne=262144,dne=3,hne=1,Bm=class n{constructor(e){this.attempted=new Set;this.badUrls=new Set;this.queue=[];this.inFlight=0;this.currentIndex=-1;this.started=!1;this.disposed=!1;this.abortController=new AbortController;this.publication=e.publication,this.engine=e.engine,this.resolveSource=e.resolveSource??q4(e.publication),this.bytes=e.bytes??cne,this.concurrency=e.concurrency??dne,this.enabled=e.enabled??!1}start(){this.disposed||this.enabled&&(this.started=!0,this.rebuildQueue(),this.pump())}setCurrentIndex(e){this.disposed||(this.currentIndex=e,this.started&&(this.rebuildQueue(),this.pump()))}dispose(){this.disposed||(this.disposed=!0,this.queue=[],this.abortController.abort())}rebuildQueue(){let e=this.publication.readingOrder,t=[];for(let r=0;r<e.length;r++)this.shouldPrefetch(r)&&t.push(r);let i=this.currentIndex>=0?this.currentIndex:0;t.sort((r,s)=>{let o=Math.abs(r-i),a=Math.abs(s-i);return o!==a?o-a:r-s}),this.queue=t}shouldPrefetch(e){if(e===this.currentIndex||this.currentIndex>=0&&Math.abs(e-this.currentIndex)<=hne)return!1;let t=this.publication.readingOrder[e];if(!t)return!1;let i=this.resolveSource(t),r=n.cacheKeyFor(i);return!(r===void 0||this.attempted.has(r)||this.badUrls.has(r))}pump(){if(!this.disposed)for(;this.inFlight<this.concurrency&&this.queue.length>0;){let e=this.queue.shift();if(e===void 0)return;this.fetchHead(e)}}async fetchHead(e){let t=this.publication.readingOrder[e];if(!t)return;let i=this.resolveSource(t),r=n.cacheKeyFor(i);if(r!==void 0&&!this.attempted.has(r)){this.attempted.add(r),this.inFlight++;try{let s=await fetch(r,{method:"GET",mode:"cors",credentials:"omit",signal:this.abortController.signal,headers:{Range:`bytes=0-${this.bytes-1}`}});s.status===200?this.badUrls.add(r):s.status!==206&&s.status!==0&&this.badUrls.add(r);try{await s.arrayBuffer()}catch{}}catch(s){if(s instanceof DOMException&&s.name==="AbortError")return;this.badUrls.add(r)}finally{this.inFlight--,this.pump()}}}static cacheKeyFor(e){switch(e.kind){case"url":case"drm":return e.url;case"hls":case"vendor":return}}}});var zM,VM=Me(()=>{x();zM="preserve-pitch-processor"});function fne(n){return new Promise((e,t)=>{let i=()=>{s(),e()},r=()=>{s(),t(new Error("WebAudioEngine: CORS reload failed \u2014 server may not send Access-Control-Allow-Origin"))},s=()=>{n.removeEventListener("canplaythrough",i),n.removeEventListener("error",r)};n.addEventListener("canplaythrough",i,{once:!0}),n.addEventListener("error",r,{once:!0})})}function pne(n){return new Promise(e=>{let t=()=>{n.removeEventListener("canplaythrough",t),e()};n.addEventListener("canplaythrough",t,{once:!0})})}var Q4,Dm,KM=Me(()=>{x();Uv();VM();Q4=class n{constructor(e={}){this.emitter=new $p;this.elementListeners=new Map;this.audioContext=null;this.sourceNode=null;this.gainNode=null;this.workletNode=null;this.workletReady=null;this.webAudioActive=!1;this.currentSrc="";this.destroyed=!1;this._preservesPitch=!0;this._muted=!1;this._volume=1;this.preservePitchWorkletUrl=e.preservePitchWorkletUrl,this.element=new Audio,this.element.preload="auto",this.wireElementEvents()}changeSrc(e){if(this.destroyed)return;if(e.kind!=="url")throw new Error(`WebAudioEngine: unsupported source kind "${e.kind}"; only "url" is handled. Register an EngineFactory for this kind.`);let t=e.url;if(t!==this.currentSrc)if(this.element.pause(),this.currentSrc=t,this.webAudioActive){this.element.crossOrigin="anonymous",this.element.src=t,this.element.load();let i=()=>s(),r=()=>{s(),console.warn("WebAudioEngine: CORS reload failed on changeSrc \u2014 tearing down Web Audio graph for this source"),this.tearDownWebAudio(),this.element.removeAttribute("crossorigin"),this.element.src=t,this.element.load()},s=()=>{this.element.removeEventListener("canplaythrough",i),this.element.removeEventListener("error",r)};this.element.addEventListener("canplaythrough",i,{once:!0}),this.element.addEventListener("error",r,{once:!0})}else this.element.src=t,this.element.load()}wireElementEvents(){let e=(i,r,s)=>{let o=()=>{this.destroyed||this.emitter.emit(r,s())};this.element.addEventListener(i,o),this.elementListeners.set(`${i}:${r}`,o)};e("loadedmetadata","loadedmetadata",()=>this.metadata),e("loadedmetadata","metadatachanged",()=>this.metadata),e("loadedmetadata","seekablechanged",()=>({ranges:this.seekable})),e("durationchange","metadatachanged",()=>this.metadata),e("canplay","canplay",()=>({duration:this.duration})),e("play","play",()=>({currentTime:this.currentTime})),e("playing","playing",()=>({currentTime:this.currentTime})),e("pause","pause",()=>({currentTime:this.currentTime})),e("ended","ended",()=>({currentTime:this.currentTime})),e("timeupdate","timeupdate",()=>({currentTime:this.currentTime,duration:this.duration})),e("seeking","seeking",()=>({currentTime:this.currentTime})),e("seeked","seeked",()=>({currentTime:this.currentTime})),e("stalled","stalled",()=>({currentTime:this.currentTime})),e("waiting","waiting",()=>({currentTime:this.currentTime})),e("progress","bufferedchanged",()=>({ranges:this.buffered}));let t=()=>{this.destroyed||this.emitter.emit("error",this.translateMediaError())};this.element.addEventListener("error",t),this.elementListeners.set("error:error",t)}translateMediaError(){let e=this.element.error;if(!e)return{message:"Unknown audio error",kind:"unknown",retryable:!1};switch(e.code){case 1:return{message:e.message||"Audio fetch aborted",kind:"network",cause:e,retryable:!0};case 2:return{message:e.message||"Audio network error",kind:"network",cause:e,retryable:!0};case 3:return{message:e.message||"Audio decode error",kind:"decode",cause:e,retryable:!1};case 4:return{message:e.message||"Audio source not supported",kind:"notfound",cause:e,retryable:!1};default:return{message:e.message||`Audio error code ${e.code}`,kind:"unknown",cause:e,retryable:!1}}}async play(){if(this.destroyed)throw new Error("WebAudioEngine: destroyed");this.audioContext&&this.audioContext.state==="suspended"&&await this.audioContext.resume();try{await this.element.play()}catch(e){if(e instanceof DOMException&&e.name==="AbortError")return;throw e}}pause(){this.destroyed||this.element.pause()}stop(){this.destroyed||(this.element.pause(),this.element.currentTime=0)}seek(e){this.destroyed||!Number.isFinite(e)||e<0||(this.element.currentTime=e)}get currentTime(){return this.element.currentTime}get duration(){let e=this.element.duration;return Number.isFinite(e)?e:0}get paused(){return this.element.paused}get ended(){return this.element.ended}get buffered(){return n.toTimeRanges(this.element.buffered)}get seekable(){return n.toTimeRanges(this.element.seekable)}get metadata(){return{duration:this.duration,textTracks:n.toAudioTextTracks(this.element.textTracks),readyState:this.element.readyState,networkState:this.element.networkState}}get isWebAudioActive(){return this.webAudioActive}getMediaElement(){return this.element}get playbackRate(){return this.element.playbackRate}set playbackRate(e){!Number.isFinite(e)||e<=0||(this.element.playbackRate=e,this.applyPitchHandling())}get preservesPitch(){return this._preservesPitch}set preservesPitch(e){this._preservesPitch!==e&&(this._preservesPitch=e,this.applyPitchHandling())}get volume(){return this._volume}set volume(e){Number.isFinite(e)&&(this._volume=Math.max(0,Math.min(1,e)),this.applyVolume())}get muted(){return this._muted}set muted(e){this._muted!==e&&(this._muted=e,this.applyVolume())}applyVolume(){let e=this._muted?0:this._volume;this.gainNode?(this.element.volume=1,this.gainNode.gain.value=e):this.element.volume=e}applyPitchHandling(){this._preservesPitch?"preservesPitch"in this.element?(this.element.preservesPitch=!0,this.sendPitchFactor()):this.activateWebAudio().then(()=>this.ensureWorklet()).then(()=>this.sendPitchFactor()).catch(e=>{console.warn("WebAudioEngine: pitch preservation unavailable \u2014 playing without:",e)}):("preservesPitch"in this.element&&(this.element.preservesPitch=!1),this.sendPitchFactor())}sendPitchFactor(){if(!this.workletNode)return;let t={type:"setPitchFactor",factor:this._preservesPitch?1/Math.max(.0625,this.element.playbackRate):1};this.workletNode.port.postMessage(t)}async activateWebAudio(){if(this.webAudioActive||!this.currentSrc)return;let e=!this.element.paused,t=this.element.currentTime;e&&this.element.pause(),this.element.crossOrigin="anonymous",this.element.src=this.currentSrc,this.element.load();try{await fne(this.element)}catch(i){if(this.element.removeAttribute("crossorigin"),this.element.src=this.currentSrc,this.element.load(),e){await pne(this.element),this.element.currentTime=t;try{await this.element.play()}catch{}}else this.element.currentTime=t;throw i}if(this.audioContext||(this.audioContext=new AudioContext),this.sourceNode=this.audioContext.createMediaElementSource(this.element),this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=this._muted?0:this._volume,this.element.volume=1,this.sourceNode.connect(this.gainNode),this.gainNode.connect(this.audioContext.destination),this.webAudioActive=!0,this.element.currentTime=t,e){this.audioContext.state==="suspended"&&await this.audioContext.resume();try{await this.element.play()}catch{}}}async ensureWorklet(){if(!this.workletNode){if(!this.webAudioActive||!this.audioContext)throw new Error("WebAudioEngine: activateWebAudio() must succeed before attaching the worklet");if(!this.preservePitchWorkletUrl)throw new Error("WebAudioEngine: preservePitchWorkletUrl was not supplied to the engine, so the worklet fallback is unavailable on this browser");if(!this.workletReady){let e=this.preservePitchWorkletUrl instanceof URL?this.preservePitchWorkletUrl.href:this.preservePitchWorkletUrl;this.workletReady=this.audioContext.audioWorklet.addModule(e)}if(await this.workletReady,!(!this.audioContext||!this.sourceNode||!this.gainNode)){this.workletNode=new AudioWorkletNode(this.audioContext,zM);try{this.sourceNode.disconnect()}catch{}this.sourceNode.connect(this.workletNode),this.workletNode.connect(this.gainNode)}}}tearDownWebAudio(){if(this.workletNode){try{this.workletNode.port.close()}catch{}try{this.workletNode.disconnect()}catch{}this.workletNode=null}if(this.sourceNode){try{this.sourceNode.disconnect()}catch{}this.sourceNode=null}if(this.gainNode){let e=this.gainNode.gain.value;try{this.gainNode.disconnect()}catch{}this.gainNode=null,this.element.volume=this._muted?0:e}this.webAudioActive=!1}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}destroy(){if(!this.destroyed){this.destroyed=!0,this.element.pause();for(let[e,t]of this.elementListeners){let i=e.split(":")[0];this.element.removeEventListener(i,t)}if(this.elementListeners.clear(),this.emitter.removeAllListeners(),this.tearDownWebAudio(),this.audioContext){try{this.audioContext.close()}catch{}this.audioContext=null}this.element.removeAttribute("src"),this.element.load()}}static toTimeRanges(e){let t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static toAudioTextTracks(e){let t=[];for(let i=0;i<e.length;i++){let r=e[i];t.push({src:"",kind:r.kind,label:r.label,language:r.language,mode:r.mode})}return t}};Dm=class{constructor(e={}){this.config=e}create(){return new Q4(this.config)}}});var Fm,YM=Me(()=>{x();Fm=class{constructor(e){this.kind=null;this.deadline=0;this.totalMs=0;this.interval=null;this.timeout=null;this.callbacks=e}get isActive(){return this.kind!==null}snapshot(){return this.kind===null?null:this.kind==="endOfChapter"?{kind:"endOfChapter",remainingMs:0,totalMs:0}:{kind:"minutes",remainingMs:Math.max(0,this.deadline-Date.now()),totalMs:this.totalMs}}startMinutes(e){if(!Number.isFinite(e)||e<=0)return;this.clearInternalTimers();let t=Math.round(e*6e4);this.kind="minutes",this.totalMs=t,this.deadline=Date.now()+t,this.interval=setInterval(()=>this.handleTick(),1e3),this.timeout=setTimeout(()=>this.fire(),t),this.callbacks.onStart(this.snapshot())}startEndOfChapter(){this.clearInternalTimers(),this.kind="endOfChapter",this.totalMs=0,this.deadline=0,this.callbacks.onStart(this.snapshot())}notifyChapterEnded(){return this.kind!=="endOfChapter"?!1:(this.fire(),!0)}cancel(){this.kind!==null&&(this.clearInternalTimers(),this.kind=null,this.callbacks.onCancel())}dispose(){this.clearInternalTimers(),this.kind=null}handleTick(){let e=this.snapshot();if(e){if(e.kind==="minutes"&&e.remainingMs<=0){this.fire();return}this.callbacks.onTick(e)}}fire(){if(this.kind===null)return;let e={kind:this.kind,remainingMs:0,totalMs:this.totalMs};this.clearInternalTimers(),this.kind=null,this.totalMs=0,this.deadline=0,this.callbacks.onExpire(e)}clearInternalTimers(){this.interval!==null&&(clearInterval(this.interval),this.interval=null),this.timeout!==null&&(clearTimeout(this.timeout),this.timeout=null)}}});function mne(n){let e=[n.readingOrder??[],n.resources??[],n.links??[]];for(let t of e)for(let i of t)if(i.rels?.has("cover"))return i}var Hm,gne,qM=Me(()=>{x();Hm=class n{constructor(e){this.destroyed=!1;this.hooks=e,this.installActionHandlers(),this.refreshMetadata()}static create(e){return typeof navigator>"u"||!("mediaSession"in navigator)?null:new n(e)}refreshMetadata(){if(!this.destroyed)try{let e=this.hooks.publication,t=this.hooks.currentIndex(),r=e.readingOrder[t]?.title||`Track ${t+1}`,s=e.metadata?.authors?.items?.map(u=>u.name?.getTranslation?.()??"")?.filter(u=>u.length>0)?.join(", "),o=e.metadata?.title?.getTranslation?.(),a=this.resolveArtwork();if(typeof MediaMetadata>"u")return;navigator.mediaSession.metadata=new MediaMetadata({title:r,artist:s||void 0,album:o||void 0,artwork:a})}catch{}}refreshPositionState(){if(!this.destroyed&&"setPositionState"in navigator.mediaSession)try{let e=this.hooks.duration(),t=this.hooks.currentTime(),i=this.hooks.playbackRate();if(!Number.isFinite(e)||e<=0){navigator.mediaSession.setPositionState();return}navigator.mediaSession.setPositionState({duration:e,position:Math.min(Math.max(0,t),e),playbackRate:Number.isFinite(i)&&i>0?i:1})}catch{}}setPlaying(){this.destroyed||(navigator.mediaSession.playbackState="playing",this.refreshPositionState())}setPaused(){this.destroyed||(navigator.mediaSession.playbackState="paused",this.refreshPositionState())}setIdle(){this.destroyed||(navigator.mediaSession.playbackState="none")}destroy(){if(!this.destroyed){if(this.destroyed=!0,navigator.mediaSession.metadata=null,navigator.mediaSession.playbackState="none","setPositionState"in navigator.mediaSession)try{navigator.mediaSession.setPositionState()}catch{}for(let e of gne)try{navigator.mediaSession.setActionHandler(e,null)}catch{}}}installActionHandlers(){let e=navigator.mediaSession;this.safeSet("play",()=>this.hooks.play()),this.safeSet("pause",()=>this.hooks.pause()),this.safeSet("previoustrack",()=>this.hooks.previousChapter()),this.safeSet("nexttrack",()=>this.hooks.nextChapter()),this.safeSet("seekbackward",t=>{let i=t.seekOffset??this.hooks.skipBackwardInterval();this.hooks.jump(-i)}),this.safeSet("seekforward",t=>{let i=t.seekOffset??this.hooks.skipForwardInterval();this.hooks.jump(i)}),this.safeSet("seekto",t=>{let i=t.seekTime;i!=null&&this.hooks.seek(i)})}safeSet(e,t){try{navigator.mediaSession.setActionHandler(e,t)}catch{}}resolveArtwork(){let e=mne(this.hooks.publication);if(!e?.href)return;let t=this.hooks.publication.manifestUrl,i;try{i=new URL(e.href,t).href}catch{i=e.href}return[{src:i,type:e.type}]}},gne=["play","pause","previoustrack","nexttrack","seekbackward","seekforward","seekto"]});var $M={};jt($M,{AudiobookNavigator:()=>X4});var X4,QM=Me(()=>{x();zv();Nn();cn();jM();$4();WM();KM();zt();Il();YM();qM();X4=class n extends Xp{constructor(t){super();this.settingsUnsubscribe=null;this.lrpTimer=null;this.mediaSession=null;this.currentIndex=-1;this.navigationId=0;this.isNavigating=!1;this._isWaiting=!1;this.stopped=!1;this.publication=t.publication,this.rights=t.rights??{},this.settings=t.settings,this.api=t.api,this.annotator=t.annotator,this.chapterListContainer=t.chapterListContainer,this.applyColors(t.colors),this.settingsUnsubscribe=this.settings.onChange(i=>{i==="enableMediaSession"?this.applyMediaSessionSetting():this.applySettingToEngine(i)}),this.sleepTimer=new Fm({onStart:i=>this.emit(ce.SleepTimerStarted,i),onTick:i=>this.emit(ce.SleepTimerTick,i),onCancel:()=>this.emit(ce.SleepTimerCancelled,void 0),onExpire:i=>{this.pause(),this.emit(ce.SleepTimerExpired,i)}}),this.engineFactory=t.engineFactory??new Dm({preservePitchWorkletUrl:t.preservePitchWorkletUrl}),this.engine=this.engineFactory.create(),this.attachEngineListeners(),this.pool=new Nm({engine:this.engine,publication:this.publication,resolveSource:t.resolveSource}),this.prefetcher=new Bm({publication:this.publication,engine:this.engine,resolveSource:t.resolveSource,bytes:t.prefetch?.bytes,concurrency:t.prefetch?.concurrency,enabled:t.prefetch?.enabled}),this.visibilityHandler=()=>{typeof document<"u"&&document.hidden&&this.flushReadingPositionSave()},typeof document<"u"&&document.addEventListener("visibilitychange",this.visibilityHandler),this.registerModules(t.modules,Ve.Audiobook),this.applyMediaSessionSetting(),this.on(ce.BookmarkCreated,()=>this.getTimelineModule()?.onBookmarkChanged()),this.on(ce.BookmarkDeleted,()=>this.getTimelineModule()?.onBookmarkChanged()),this.on(ce.CommentCreated,()=>this.getTimelineModule()?.onCommentChanged()),this.on(ce.CommentDeleted,()=>this.getTimelineModule()?.onCommentChanged()),this.chapterListContainer&&(this.renderChapterList(),this.on(ce.TrackChanged,()=>this.refreshChapterHighlight()))}applyColors(t){if(!t||typeof document>"u")return;let i=document.documentElement,r=(s,o)=>{o!==void 0&&i.style.setProperty(s,o)};r("--dita-audiobook-track",t.track),r("--dita-audiobook-accent",t.accent),r("--dita-audiobook-accent-fade",t.accentFade),r("--dita-audiobook-comment",t.comment),r("--dita-audiobook-boundary",t.boundary)}getTimelineModule(){return this.getModule(ye.Timeline)}getCommentsModule(){return this.getModule(ye.Comments)}renderChapterList(){let t=this.chapterListContainer;if(!t)return;t.innerHTML="";let i=document.createElement("ol");i.className="dita-audiobook-chapters";let r=this.publication.tableOfContents,s=r.length>0?r:this.publication.readingOrder;for(let o of s)this.appendChapterRow(i,o,0);t.appendChild(i),this.refreshChapterHighlight()}appendChapterRow(t,i,r){let s=document.createElement("li");s.className=r===0?"dita-audiobook-chapters-chapter":"dita-audiobook-chapters-section";let o=this.indexForHref(i.href);o>=0&&(s.dataset.chapterIndex=String(o)),s.tabIndex=0,s.setAttribute("role","button");let a=document.createElement("span");a.className="dita-audiobook-chapters-title",a.textContent=i.title||(o>=0?`Track ${o+1}`:i.href),s.appendChild(a);let u=this.locatorForTocLink(i);if(u){let c=d=>{d.preventDefault(),this.goTo(u)};s.addEventListener("click",c),s.addEventListener("keydown",d=>{(d.key==="Enter"||d.key===" ")&&c(d)})}t.appendChild(s);let l=i.children?.items;if(l&&l.length>0){let c=document.createElement("ol");c.className="dita-audiobook-chapters-sub";for(let d of l)this.appendChapterRow(c,d,r+1);t.appendChild(c)}}indexForHref(t){if(!t)return-1;let i=t.split("#")[0],r=this.publication.getAbsoluteHref(i);return this.publication.readingOrder.findIndex(o=>this.publication.getAbsoluteHref(o.href)===r)}locatorForTocLink(t){if(!t.href)return;let[i,r]=t.href.split("#"),s=this.indexForHref(i);if(s<0)return;let o=this.publication.readingOrder[s],a;if(r){let u=/(?:^|&)t=([0-9.]+)/.exec(r);u&&(a=Number(u[1]))}return{href:o.href,type:o.type,title:o.title,locations:a!==void 0?{time:a}:{}}}refreshChapterHighlight(){let t=this.chapterListContainer;if(!t)return;let i=String(this.currentIndex);for(let r of t.querySelectorAll("[data-chapter-index]"))r.dataset.chapterIndex===i?r.dataset.current="true":delete r.dataset.current}static async create(t,i=0){let r=new n(t),s=r.publication.readingOrder;if(s.length===0)return r;let o=t.initialLastReadingPosition??void 0;if(o){let l={...o,created:new Date};r.annotator?.initLastReadingPosition(l)}else{let l=r.annotator?.getLastReadingPosition();l?.href&&(o=l)}let a=i,u;if(o?.href){let l=s.findIndex(c=>c.href===o.href);if(l>=0){a=l;let c=o.locations?.time;typeof c=="number"&&c>0&&(u=c)}}return await r.goTrack(a,u),r.prefetcher.start(),r}async play(){this.engine.metadata.readyState<3&&this.setWaiting(!0),await this.engine.play()}pause(){this.engine.pause(),this.flushReadingPositionSave()}seek(t){!Number.isFinite(t)||t<0||(this.engine.seek(t),this.mediaSession?.refreshPositionState())}jump(t){let i=Math.max(0,this.engine.currentTime+t);this.engine.seek(Math.min(i,this.engine.duration||i)),this.mediaSession?.refreshPositionState()}skipForward(){this.jump(this.settings.skipForwardInterval)}skipBackward(){this.jump(-this.settings.skipBackwardInterval)}async goForward(){this.canGoForward&&await this.goTrack(this.currentIndex+1,void 0)}async goBackward(){this.canGoBackward&&await this.goTrack(this.currentIndex-1,void 0)}get currentTime(){return this.engine?.currentTime??0}get duration(){return this.engine?.duration??0}get isPlaying(){return!(this.engine?.paused??!0)}get isPaused(){return this.engine?.paused??!0}get isWaiting(){return this._isWaiting}get canGoForward(){return this.currentIndex<this.publication.readingOrder.length-1}get canGoBackward(){return this.currentIndex>0}get isTrackStart(){return this.currentTime===0}get isTrackEnd(){return this.engine.duration<=0?!1:this.engine.currentTime>=this.engine.duration||this.engine.ended}get playbackRate(){return this.settings.playbackRate}setPlaybackRate(t){!Number.isFinite(t)||t<=0||(this.settings.playbackRate=t)}get volume(){return this.settings.volume}setVolume(t){this.settings.volume=t}get muted(){return this.engine?.muted??!1}setMuted(t){this.engine&&(this.engine.muted=t)}startSleepTimerMinutes(t){this.sleepTimer.startMinutes(t)}startSleepTimerAtChapterEnd(){this.sleepTimer.startEndOfChapter()}cancelSleepTimer(){this.sleepTimer.cancel()}sleepTimerState(){return this.sleepTimer.snapshot()}currentResource(){return this.currentIndex>=0?this.currentIndex:void 0}currentLocator(){let t=this.currentLink;if(!t)return{href:"",locations:{}};let i=this.currentTime,r=this.duration||t.duration||0;return{href:t.href,type:t.type,title:t.title,locations:gy(i,{position:this.currentIndex>=0?this.currentIndex+1:void 0,progression:r>0?Math.min(1,i/r):0})}}async goTo(t){let i=this.publication.readingOrder.findIndex(s=>s.href===t.href);if(i<0)return;let r=typeof t.locations?.time=="number"&&t.locations.time>=0?t.locations.time:void 0;await this.goTrack(i,r)}async goToPosition(t){let i=t-1;i<0||i>=this.publication.readingOrder.length||await this.goTrack(i,0)}async nextResource(){return this.goForward()}async previousResource(){return this.goBackward()}atStart(){return this.currentIndex<=0&&this.currentTime<=0}atEnd(){return this.currentIndex>=this.publication.readingOrder.length-1&&this.isTrackEnd}stop(){if(!this.stopped){if(this.stopped=!0,this.flushReadingPositionSave(),typeof document<"u"&&document.removeEventListener("visibilitychange",this.visibilityHandler),this.settingsUnsubscribe&&(this.settingsUnsubscribe(),this.settingsUnsubscribe=null),this.sleepTimer.dispose(),this.mediaSession&&(this.mediaSession.destroy(),this.mediaSession=null),this.prefetcher.dispose(),this.pool.destroy(),Promise.resolve(this.engine.destroy()).catch(t=>{console.warn("AudiobookNavigator: engine destroy failed",t)}),this.engineFactory.destroy)try{let t=this.engineFactory.destroy();t&&typeof t.catch=="function"&&t.catch(i=>{console.warn("AudiobookNavigator: engineFactory destroy failed",i)})}catch(t){console.warn("AudiobookNavigator: engineFactory destroy threw",t)}this.currentIndex=-1}}scheduleReadingPositionSave(){!this.api?.updateCurrentLocation&&!this.annotator||(this.lrpTimer!==null&&clearTimeout(this.lrpTimer),this.lrpTimer=setTimeout(()=>{this.lrpTimer=null,this.persistReadingPosition()},this.settings.pollInterval))}flushReadingPositionSave(){this.lrpTimer!==null&&(clearTimeout(this.lrpTimer),this.lrpTimer=null),this.persistReadingPosition()}persistReadingPosition(){let t=this.currentLocator();if(!t.href)return;let i={...t,created:new Date},r=this.api?.updateCurrentLocation;r?r(i).then(()=>{this.annotator?.saveLastReadingPosition(i)}):this.annotator?.saveLastReadingPosition(i),this.emit(ce.LocationChanged,i)}get currentLink(){if(!(this.currentIndex<0))return this.publication.readingOrder[this.currentIndex]}async goTrack(t,i){if(this.stopped||t<0||t>=this.publication.readingOrder.length)return;if(t===this.currentIndex){typeof i=="number"&&i>=0&&(this.engine.seek(i),this.mediaSession?.refreshPositionState());return}let r=++this.navigationId,s=!this.engine.paused,o=this.currentIndex>=0?this.currentLocator():null;this.isNavigating=!0,this.setWaiting(s),this.engine.pause(),this.currentIndex=t,this.pool.setCurrentAudio(t),this.prefetcher.setCurrentIndex(t),this.engine.playbackRate=this.settings.playbackRate;try{await this.waitForCanPlay(r)}catch(u){r===this.navigationId&&(this.isNavigating=!1,this.setWaiting(!1),this.emit(ce.PlaybackError,{error:u,locator:this.currentLocator()}));return}if(this.stopped||r!==this.navigationId)return;typeof i=="number"&&i>=0&&this.engine.seek(i),this.isNavigating=!1;let a=this.currentLocator();this.emit(ce.TrackChanged,{previous:o,current:a}),this.getTimelineModule()?.onTrackChanged(),this.emit(ce.DurationChanged,{duration:this.engine.duration,locator:a}),this.getTimelineModule()?.onDurationChanged(),this.mediaSession&&(this.mediaSession.refreshMetadata(),this.mediaSession.refreshPositionState()),this.flushReadingPositionSave(),s&&await this.play()}waitForCanPlay(t){return new Promise((i,r)=>{if(this.engine.metadata.readyState>=3){i();return}let s=()=>{clearInterval(u),this.engine.off("canplay",o),this.engine.off("error",a)},o=()=>{s(),i()},a=l=>{s(),r(l)},u=setInterval(()=>{(t!==this.navigationId||this.stopped)&&(s(),i())},100);this.engine.on("canplay",o),this.engine.on("error",a)})}prefetchResource(t){this.stopped||this.pool.prefetchAt(t)}applySettingToEngine(t){t==="volume"?this.engine.volume=this.settings.volume:t==="playbackRate"?(this.engine.playbackRate=this.settings.playbackRate,this.emit(ce.PlaybackRateChanged,{rate:this.settings.playbackRate}),this.mediaSession?.refreshPositionState()):t==="preservePitch"&&(this.engine.preservesPitch=this.settings.preservePitch)}applyMediaSessionSetting(){let t=this.settings.enableMediaSession;t&&!this.mediaSession?(this.mediaSession=Hm.create({publication:this.publication,currentIndex:()=>this.currentIndex,currentTime:()=>this.currentTime,duration:()=>this.duration,playbackRate:()=>this.settings.playbackRate,skipBackwardInterval:()=>this.settings.skipBackwardInterval,skipForwardInterval:()=>this.settings.skipForwardInterval,play:()=>{this.play()},pause:()=>this.pause(),previousChapter:()=>{this.goBackward()},nextChapter:()=>{this.goForward()},seek:i=>this.seek(i),jump:i=>this.jump(i)}),this.mediaSession&&(this.isPlaying?this.mediaSession.setPlaying():this.mediaSession.setPaused())):!t&&this.mediaSession&&(this.mediaSession.destroy(),this.mediaSession=null)}setWaiting(t){this._isWaiting!==t&&(this._isWaiting=t,this.emit(ce.PlaybackWaiting,{waiting:t,locator:this.currentLocator()}))}attachEngineListeners(){let t=this.engine;t.volume=this.settings.volume,t.playbackRate=this.settings.playbackRate,t.preservesPitch=this.settings.preservePitch,t.on("play",i=>{this.isNavigating||(this.emit(ce.PlaybackStarted,{locator:this.currentLocator(),currentTime:i.currentTime}),this.mediaSession?.setPlaying())}),t.on("playing",()=>{this.isNavigating||this.setWaiting(!1)}),t.on("waiting",()=>{this.isNavigating||t.paused||this.setWaiting(!0)}),t.on("canplay",()=>{this.isNavigating||this.setWaiting(!1)}),t.on("pause",i=>{this.isNavigating||(this.setWaiting(!1),this.emit(ce.PlaybackPaused,{locator:this.currentLocator(),currentTime:i.currentTime}),this.mediaSession?.setPaused())}),t.on("ended",()=>{this.isNavigating||(this.setWaiting(!1),this.emit(ce.PlaybackEnded,{locator:this.currentLocator()}),!this.sleepTimer.notifyChapterEnded()&&this.canGoForward&&(async()=>(await this.goTrack(this.currentIndex+1,0),this.settings.autoPlay&&await this.play()))())}),t.on("timeupdate",i=>{if(this.isNavigating)return;let r={locator:this.currentLocator(),currentTime:i.currentTime,duration:i.duration};this.emit(ce.TimeUpdated,r),this.getTimelineModule()?.onTimeUpdate(),this.getCommentsModule()?.onTimeUpdate(r),this.scheduleReadingPositionSave()}),t.on("stalled",i=>{this.isNavigating||this.emit(ce.PlaybackStalled,{locator:this.currentLocator(),currentTime:i.currentTime})}),t.on("error",i=>{this.isNavigating||(this.setWaiting(!1),this.emit(ce.PlaybackError,{error:i,locator:this.currentLocator()}))})}}});function Ine(n,e){return xne(n,{i:2},e&&e.out,e&&e.dictionary)}function rE(n,e){if(e){for(var t="",i=0;i<n.length;i+=16384)t+=String.fromCharCode.apply(null,n.subarray(i,i+16384));return t}else{if(iE)return iE.decode(n);var r=_ne(n),s=r.s,t=r.r;return t.length&&Mr(8),s}}function rO(n,e){for(var t={},i=n.length-22;es(n,i)!=101010256;--i)(!i||n.length-i>65558)&&Mr(13);var r=Ps(n,i+8);if(!r)return{};var s=es(n,i+16),o=s==4294967295||r==65535;if(o){var a=es(n,i-12);o=es(n,a)==101075792,o&&(r=es(n,a+32),s=es(n,a+48))}for(var u=e&&e.filter,l=0;l<r;++l){var c=Rne(n,s,o),d=c[0],f=c[1],m=c[2],y=c[3],g=c[4],b=c[5],v=Pne(n,b);s=g,(!u||u({name:y,size:f,originalSize:m,compression:d}))&&(d?d==8?t[y]=Ine(n.subarray(v,v+f),{out:new fr(m)}):Mr(14,"unknown compression type "+d):t[y]=nE(n,v,v+f))}return t}var fr,cc,bne,XM,JM,yne,ZM,eO,tO,vne,iO,Ane,Zbe,tE,wo,Pt,Kh,Yh,Pt,Pt,Pt,Pt,nO,Pt,wne,Ene,J4,Zr,Z4,Cne,nE,Sne,Mr,xne,Tne,Ps,es,eE,iE,kne,_ne,Pne,Rne,Lne,sE=Me(()=>{x();fr=Uint8Array,cc=Uint16Array,bne=Int32Array,XM=new fr([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),JM=new fr([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),yne=new fr([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ZM=function(n,e){for(var t=new cc(31),i=0;i<31;++i)t[i]=e+=1<<n[i-1];for(var r=new bne(t[30]),i=1;i<30;++i)for(var s=t[i];s<t[i+1];++s)r[s]=s-t[i]<<5|i;return{b:t,r}},eO=ZM(XM,2),tO=eO.b,vne=eO.r;tO[28]=258,vne[258]=28;iO=ZM(JM,0),Ane=iO.b,Zbe=iO.r,tE=new cc(32768);for(Pt=0;Pt<32768;++Pt)wo=(Pt&43690)>>1|(Pt&21845)<<1,wo=(wo&52428)>>2|(wo&13107)<<2,wo=(wo&61680)>>4|(wo&3855)<<4,tE[Pt]=((wo&65280)>>8|(wo&255)<<8)>>1;Kh=(function(n,e,t){for(var i=n.length,r=0,s=new cc(e);r<i;++r)n[r]&&++s[n[r]-1];var o=new cc(e);for(r=1;r<e;++r)o[r]=o[r-1]+s[r-1]<<1;var a;if(t){a=new cc(1<<e);var u=15-e;for(r=0;r<i;++r)if(n[r])for(var l=r<<4|n[r],c=e-n[r],d=o[n[r]-1]++<<c,f=d|(1<<c)-1;d<=f;++d)a[tE[d]>>u]=l}else for(a=new cc(i),r=0;r<i;++r)n[r]&&(a[r]=tE[o[n[r]-1]++]>>15-n[r]);return a}),Yh=new fr(288);for(Pt=0;Pt<144;++Pt)Yh[Pt]=8;for(Pt=144;Pt<256;++Pt)Yh[Pt]=9;for(Pt=256;Pt<280;++Pt)Yh[Pt]=7;for(Pt=280;Pt<288;++Pt)Yh[Pt]=8;nO=new fr(32);for(Pt=0;Pt<32;++Pt)nO[Pt]=5;wne=Kh(Yh,9,1),Ene=Kh(nO,5,1),J4=function(n){for(var e=n[0],t=1;t<n.length;++t)n[t]>e&&(e=n[t]);return e},Zr=function(n,e,t){var i=e/8|0;return(n[i]|n[i+1]<<8)>>(e&7)&t},Z4=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},Cne=function(n){return(n+7)/8|0},nE=function(n,e,t){return(e==null||e<0)&&(e=0),(t==null||t>n.length)&&(t=n.length),new fr(n.subarray(e,t))},Sne=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Mr=function(n,e,t){var i=new Error(e||Sne[n]);if(i.code=n,Error.captureStackTrace&&Error.captureStackTrace(i,Mr),!t)throw i;return i},xne=function(n,e,t,i){var r=n.length,s=i?i.length:0;if(!r||e.f&&!e.l)return t||new fr(0);var o=!t,a=o||e.i!=2,u=e.i;o&&(t=new fr(r*3));var l=function(St){var $e=t.length;if(St>$e){var Bt=new fr(Math.max($e*2,St));Bt.set(t),t=Bt}},c=e.f||0,d=e.p||0,f=e.b||0,m=e.l,y=e.d,g=e.m,b=e.n,v=r*8;do{if(!m){c=Zr(n,d,1);var A=Zr(n,d+1,3);if(d+=3,A)if(A==1)m=wne,y=Ene,g=9,b=5;else if(A==2){var T=Zr(n,d,31)+257,_=Zr(n,d+10,15)+4,k=T+Zr(n,d+5,31)+1;d+=14;for(var L=new fr(k),M=new fr(19),N=0;N<_;++N)M[yne[N]]=Zr(n,d+N*3,7);d+=_*3;for(var O=J4(M),U=(1<<O)-1,G=Kh(M,O,1),N=0;N<k;){var j=G[Zr(n,d,U)];d+=j&15;var w=j>>4;if(w<16)L[N++]=w;else{var z=0,W=0;for(w==16?(W=3+Zr(n,d,3),d+=2,z=L[N-1]):w==17?(W=3+Zr(n,d,7),d+=3):w==18&&(W=11+Zr(n,d,127),d+=7);W--;)L[N++]=z}}var $=L.subarray(0,T),re=L.subarray(T);g=J4($),b=J4(re),m=Kh($,g,1),y=Kh(re,b,1)}else Mr(1);else{var w=Cne(d)+4,S=n[w-4]|n[w-3]<<8,C=w+S;if(C>r){u&&Mr(0);break}a&&l(f+S),t.set(n.subarray(w,C),f),e.b=f+=S,e.p=d=C*8,e.f=c;continue}if(d>v){u&&Mr(0);break}}a&&l(f+131072);for(var ae=(1<<g)-1,fe=(1<<b)-1,ge=d;;ge=d){var z=m[Z4(n,d)&ae],se=z>>4;if(d+=z&15,d>v){u&&Mr(0);break}if(z||Mr(2),se<256)t[f++]=se;else if(se==256){ge=d,m=null;break}else{var de=se-254;if(se>264){var N=se-257,Y=XM[N];de=Zr(n,d,(1<<Y)-1)+tO[N],d+=Y}var J=y[Z4(n,d)&fe],Q=J>>4;J||Mr(3),d+=J&15;var re=Ane[Q];if(Q>3){var Y=JM[Q];re+=Z4(n,d)&(1<<Y)-1,d+=Y}if(d>v){u&&Mr(0);break}a&&l(f+131072);var ie=f+de;if(f<re){var He=s-re,Ze=Math.min(re,ie);for(He+f<0&&Mr(3);f<Ze;++f)t[f]=i[He+f]}for(;f<ie;++f)t[f]=t[f-re]}}e.l=m,e.p=ge,e.b=f,e.f=c,m&&(c=1,e.m=g,e.d=y,e.n=b)}while(!c);return f!=t.length&&o?nE(t,0,f):t.subarray(0,f)},Tne=new fr(0),Ps=function(n,e){return n[e]|n[e+1]<<8},es=function(n,e){return(n[e]|n[e+1]<<8|n[e+2]<<16|n[e+3]<<24)>>>0},eE=function(n,e){return es(n,e)+es(n,e+4)*4294967296};iE=typeof TextDecoder<"u"&&new TextDecoder,kne=0;try{iE.decode(Tne,{stream:!0}),kne=1}catch{}_ne=function(n){for(var e="",t=0;;){var i=n[t++],r=(i>127)+(i>223)+(i>239);if(t+r>n.length)return{s:e,r:nE(n,t-1)};r?r==3?(i=((i&15)<<18|(n[t++]&63)<<12|(n[t++]&63)<<6|n[t++]&63)-65536,e+=String.fromCharCode(55296|i>>10,56320|i&1023)):r&1?e+=String.fromCharCode((i&31)<<6|n[t++]&63):e+=String.fromCharCode((i&15)<<12|(n[t++]&63)<<6|n[t++]&63):e+=String.fromCharCode(i)}};Pne=function(n,e){return e+30+Ps(n,e+26)+Ps(n,e+28)},Rne=function(n,e,t){var i=Ps(n,e+28),r=rE(n.subarray(e+46,e+46+i),!(Ps(n,e+8)&2048)),s=e+46+i,o=es(n,e+20),a=t&&o==4294967295?Lne(n,s):[o,es(n,e+24),es(n,e+42)],u=a[0],l=a[1],c=a[2];return[Ps(n,e+10),u,l,r,s+Ps(n,e+30)+Ps(n,e+32),c]},Lne=function(n,e){for(;Ps(n,e)!=1;e+=4+Ps(n,e+2));return[eE(n,e+12),eE(n,e+4),eE(n,e+20)]}});var dc,oE=Me(()=>{x();sE();dc=class{constructor(e){let t=e instanceof Uint8Array?e:new Uint8Array(e);this.data=rO(t)}entries(){return Object.keys(this.data)}get(e){return this.data[e]}has(e){return e in this.data}destroy(){this.data={}}}});var sO={};jt(sO,{ZipFetcher:()=>qh});var qh,aE=Me(()=>{x();sE();oE();Zg();th();qh=class{setBasePath(e){this.basePath=e}setEncryptionMap(e){this.encryptionMap=e}constructor(e,t=""){e instanceof ArrayBuffer||e instanceof Uint8Array?this.container=new dc(e):this.container=e,this.basePath=t}async get(e){let t=await this.getByHref(e.href);return e.type?{...t,mediaType:e.type}:t}async getByHref(e){let t=this.resolvePath(e),i=this.container.get(t);if(!i)throw Es.access(e,`Not found in archive: ${t}`);let r=fo(t),o=r.startsWith("text/")||r.includes("xml")||r.includes("json")||r.includes("javascript")?rE(i):"",a=this.encryptionMap?.get(t),u=a?{encrypted:a}:void 0;return{text:o,bytes:new Uint8Array(i).buffer,headers:{},mediaType:r,href:e,properties:u}}async has(e){let t=this.resolvePath(e.href);return this.container.has(t)}list(){return this.container.entries()}getBytes(e){return this.container.get(this.resolvePath(e))}destroy(){this.container.destroy()}resolvePath(e){let t=e,i=t.indexOf("?");i>=0&&(t=t.substring(0,i));let r=t.indexOf("#");r>=0&&(t=t.substring(0,r)),this.basePath&&t.startsWith(this.basePath)&&(t=t.substring(this.basePath.length)),t.startsWith("/")&&(t=t.substring(1));try{t=decodeURIComponent(t)}catch{}if(!this.container.has(t)){for(let s of this.container.entries())if(s.endsWith("/"+t)||s===t)return s}return t}static guessMediaType(e){return fo(e)}}});var oO={};jt(oO,{EpubParser:()=>$h});var $h,uE=Me(()=>{x();py();$h=class n{static async extractIdentifier(e){try{let t=await e.getByHref("META-INF/container.xml"),r=new DOMParser().parseFromString(t.text,"application/xml").querySelector("rootfile[full-path]")?.getAttribute("full-path")??"";if(!r)return"unknown";let s=await e.getByHref(r);return(new DOMParser().parseFromString(s.text,"application/xml").querySelector("metadata identifier")?.textContent?.trim()??"")||"unknown"}catch{return"unknown"}}static async parse(e,t){let i=await e.getByHref("META-INF/container.xml"),o=new DOMParser().parseFromString(i.text,"application/xml").querySelector("rootfile[full-path]")?.getAttribute("full-path");if(!o)throw new Error("EpubParser: no rootfile found in container.xml");let a=o.includes("/")?o.substring(0,o.lastIndexOf("/")+1):"",u=await e.getByHref(o),l=new DOMParser().parseFromString(u.text,"application/xml"),c=l.querySelector("metadata"),d=l.querySelector("manifest"),f=l.querySelector("spine"),m=c?.querySelector("title")?.textContent?.trim()??"",y=c?.querySelector("language")?.textContent?.trim()??"en",g=c?.querySelector("identifier")?.textContent?.trim()??"",b=c?.querySelectorAll("creator")??[],v=[];b.forEach(Ue=>{let lt=Ue.textContent?.trim();lt&&v.push({name:lt})});let A=c?.querySelector("publisher")?.textContent?.trim()??void 0,w=c?.querySelector("description")?.textContent?.trim()??void 0,S=c?.querySelectorAll("subject")??[],C=[];S.forEach(Ue=>{let lt=Ue.textContent?.trim();lt&&C.push(lt)});let T=c?.querySelector("date")?.textContent?.trim()??void 0,k=c?.querySelector('meta[property="dcterms:modified"]')?.textContent?.trim()??void 0,L=c?.querySelector('meta[property="schema:numberOfPages"]'),M=L&&parseInt(L.textContent?.trim()??"",10)||void 0,O=c?.querySelector('meta[property="rendition:layout"]')?.textContent?.trim()??"";O||c?.querySelector('meta[name="fixed-layout"]')?.getAttribute("content")==="true"&&(O="pre-paginated"),O||(O="reflowable");let U=f?.getAttribute("page-progression-direction"),G=U==="rtl"?"rtl":U==="ltr"?"ltr":void 0,z=c?.querySelector('meta[property="rendition:spread"]')?.textContent?.trim()??void 0,$=c?.querySelector('meta[property="rendition:orientation"]')?.textContent?.trim()??void 0,re=d?.querySelectorAll("item")??[],ae=new Map;re.forEach(Ue=>{let lt=Ue.getAttribute("id"),Kt=Ue.getAttribute("href"),hi=Ue.getAttribute("media-type")??"",Se=Ue.getAttribute("properties")??void 0;lt&&Kt&&ae.set(lt,{href:a+Kt,type:hi,properties:Se})});let fe=f?.querySelectorAll("itemref")??[],ge=[],se=[],de=new Set;fe.forEach(Ue=>{let lt=Ue.getAttribute("idref");if(!lt)return;let Kt=ae.get(lt);if(!Kt)return;if(de.add(lt),Ue.getAttribute("linear")==="no"){se.push({href:Kt.href,type:Kt.type});return}let Se={href:Kt.href,type:Kt.type},ve=Ue.getAttribute("properties");ve&&(Se.properties={page:ve}),ge.push(Se)});let Y=[...se],J=c?.querySelector('meta[name="cover"]')?.getAttribute("content")??void 0;ae.forEach((Ue,lt)=>{if(!de.has(lt)){let Kt={href:Ue.href,type:Ue.type};(Ue.properties?.includes("cover-image")||lt===J)&&(Kt.rel="cover"),Y.push(Kt)}});let Q=[],ie=[...ae.values()].find(Ue=>Ue.properties?.includes("nav"));if(ie)try{let Ue=await e.getByHref(ie.href);Q=n.parseNavToc(Ue.text,a)}catch{}if(Q.length===0){let Ue=f?.getAttribute("toc"),lt=Ue?ae.get(Ue):void 0;if(lt)try{let Kt=await e.getByHref(lt.href);Q=n.parseNcxToc(Kt.text,a)}catch{}}let He=c?.querySelector('meta[property="media:active-class"]')?.textContent?.trim(),Ze=c?.querySelector('meta[property="media:playback-active-class"]')?.textContent?.trim(),St={title:m,language:y,identifier:g,author:v.length>0?v:void 0,...A?{publisher:{name:A}}:{},...w?{description:w}:{},...C.length>0?{subject:C}:{},...T?{published:T}:{},...k?{modified:k}:{},...M?{numberOfPages:M}:{},...G?{readingProgression:G}:{},...O==="pre-paginated"?{layout:"fixed"}:{}},$e={};z&&($e["rendition:spread"]=z),$&&($e["rendition:orientation"]=$),He&&($e["media:active-class"]=He),Ze&&($e["media:playback-active-class"]=Ze),Object.keys($e).length>0&&(St.otherMetadata=$e);let Bt={metadata:St,readingOrder:ge,resources:Y,toc:Q,links:[]},Si=Ks.fromJSON(Bt,t);if(!Si)throw new Error("EpubParser: failed to create Publication from OPF");return Si}static parseNavToc(e,t){let i=new DOMParser().parseFromString(e,"application/xhtml+xml"),r=i.querySelector('nav[epub\\:type="toc"]')??i.querySelector('nav[role="doc-toc"]')??i.querySelector("nav");if(!r)return[];let s=a=>{let u=[];return a.querySelectorAll(":scope > li").forEach(c=>{let d=c.querySelector(":scope > a");if(!d)return;let f=d.getAttribute("href"),m=d.textContent?.trim();if(!f)return;let y={href:t+f,title:m},g=c.querySelector(":scope > ol");g&&(y.children=s(g)),u.push(y)}),u},o=r.querySelector("ol");return o?s(o):[]}static parseNcxToc(e,t){let i=new DOMParser().parseFromString(e,"application/xml"),r=o=>{let a=[];return o.querySelectorAll(":scope > navPoint").forEach(l=>{let c=l.querySelector("navLabel text")?.textContent?.trim(),d=l.querySelector("content")?.getAttribute("src");if(!d)return;let f={href:t+d,title:c};l.querySelectorAll(":scope > navPoint").length>0&&(f.children=r(l)),a.push(f)}),a},s=i.querySelector("navMap");return s?r(s):[]}}});var aO={};jt(aO,{BlobUrlManager:()=>Qh});var Qh,lE=Me(()=>{x();th();Qh=class{constructor(e){this.blobUrls=new Map;this.transforms=[];this.container="container"in e?e.container:e}setEncryptionMap(e){this.encryptionMap=e}addTransform(e){this.transforms.push(e)}async initialize(){let e=[];for(let t of this.container.entries()){if(t.endsWith("/"))continue;let i=this.container.get(t);if(!i)continue;let r=fo(t);if(r==="text/css"){e.push({path:t,bytes:i});continue}let s=i;if(this.transforms.length>0){let a=this.encryptionMap?.get(t),u={text:"",bytes:new Uint8Array(i).buffer,headers:{},mediaType:r,href:t,properties:a?{encrypted:a}:void 0};for(let l of this.transforms)u=await l(u);u.bytes&&(s=new Uint8Array(u.bytes))}let o=new Blob([new Uint8Array(s)],{type:r});this.blobUrls.set(t,URL.createObjectURL(o))}for(let{path:t,bytes:i}of e){let r=new TextDecoder().decode(i),s=t.includes("/")?t.substring(0,t.lastIndexOf("/")+1):"";r=this.rewriteCssUrls(r,s);let o=new Blob([r],{type:"text/css"});this.blobUrls.set(t,URL.createObjectURL(o))}}rewriteDom(e,t){let i=t.includes("/")?t.substring(0,t.lastIndexOf("/")+1):"";e.querySelectorAll("script").forEach(d=>{d.setAttribute("defer","")}),e.querySelectorAll("img, script, audio, video, source, input[type=image]").forEach(d=>{let f=d.getAttribute("src");if(f&&!this.isAbsolute(f)){let m=this.resolve(i,f),y=this.blobUrls.get(m);y&&d.setAttribute("src",y)}}),e.querySelectorAll("link[href], a[href]").forEach(d=>{let f=d.getAttribute("href");if(f&&!this.isAbsolute(f)&&!f.startsWith("#")){let m=this.resolve(i,f),y=this.blobUrls.get(m);y&&d.setAttribute("href",y)}}),e.querySelectorAll("[*|href]").forEach(d=>{let f=d.getAttributeNS("http://www.w3.org/1999/xlink","href")??d.getAttribute("xlink:href");if(f&&!this.isAbsolute(f)&&!f.startsWith("#")){let m=this.resolve(i,f),y=this.blobUrls.get(m);y&&d.setAttributeNS("http://www.w3.org/1999/xlink","href",y)}}),e.querySelectorAll("style").forEach(d=>{d.textContent&&(d.textContent=this.rewriteCssUrls(d.textContent,i))}),e.querySelectorAll("[style]").forEach(d=>{let f=d.getAttribute("style");f&&f.includes("url(")&&d.setAttribute("style",this.rewriteCssUrls(f,i))}),e.querySelectorAll('meta[http-equiv="Content-Security-Policy"]').forEach(d=>d.remove())}rewriteCssUrls(e,t){let i=e.replace(/url\(\s*["']?([^"')]+)["']?\s*\)/gi,(r,s)=>{if(this.isAbsolute(s)||s.startsWith("data:"))return r;let o=this.resolve(t,s),a=this.blobUrls.get(o);return a?`url("${a}")`:r});return i=i.replace(/@import\s+["']([^"']+)["']/gi,(r,s)=>{if(this.isAbsolute(s)||s.startsWith("data:"))return r;let o=this.resolve(t,s),a=this.blobUrls.get(o);return a?`@import "${a}"`:r}),i}isAbsolute(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("javascript:")||e.startsWith("vbscript:")||e.startsWith("mailto:")}resolve(e,t){let i=t.split("?")[0].split("#")[0],r=(e+i).split("/"),s=[];for(let o of r)o===".."?s.pop():o!=="."&&o!==""&&s.push(o);return s.join("/")}destroy(){for(let e of this.blobUrls.values())URL.revokeObjectURL(e);this.blobUrls.clear()}}});var uO={};jt(uO,{ALGORITHM_ADOBE:()=>dE,ALGORITHM_IDPF:()=>cE,createDeobfuscationTransform:()=>fE,deobfuscateAdobe:()=>jm,deobfuscateIdpf:()=>Um,parseEncryptionXml:()=>hE});function hE(n){let e=new Map;return new DOMParser().parseFromString(n,"application/xml").querySelectorAll("EncryptedData").forEach(r=>{let s=r.querySelector("EncryptionMethod")?.getAttribute("Algorithm")??"";if(s!==cE&&s!==dE)return;let o=r.querySelector("CipherData CipherReference")?.getAttribute("URI")??"";if(!o)return;let a;try{a=decodeURIComponent(o)}catch{a=o}let u={algorithm:s},l=r.querySelector("EncryptionProperties EncryptionProperty Compression");if(l){let c=parseInt(l.getAttribute("OriginalLength")??"",10);isNaN(c)||(u.originalLength=c)}e.set(a,u)}),e}async function Um(n,e){let t=e.replace(/\s+/g,""),i=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-1",i),s=new Uint8Array(r),o=new Uint8Array(n),a=Math.min(1040,o.length);for(let u=0;u<a;u++)o[u]=o[u]^s[u%s.length];return o}function jm(n,e){let t=e.replace(/^urn:uuid:/i,"").replace(/[- \t\r\n]/g,"");if(t.length<32)return n;t=t.substring(0,32);let i=new Uint8Array(16);for(let o=0;o<16;o++)i[o]=parseInt(t.substring(o*2,o*2+2),16);let r=new Uint8Array(n),s=Math.min(1024,r.length);for(let o=0;o<s;o++)r[o]=r[o]^i[o%i.length];return r}function fE(n){return async e=>{let t=e.properties?.encrypted;if(!t||!e.bytes)return e;let i;if(t.algorithm===cE)i=await Um(new Uint8Array(e.bytes),n);else if(t.algorithm===dE)i=jm(new Uint8Array(e.bytes),n);else return e;return{...e,bytes:i.buffer,text:e.text?new TextDecoder().decode(i):e.text}}}var cE,dE,pE=Me(()=>{x();cE="http://www.idpf.org/2008/embedding",dE="http://ns.adobe.com/pdf/enc#RC"});var lO={};jt(lO,{TransformingFetcher:()=>Xh});var Xh,gE=Me(()=>{x();Xh=class{constructor(e,...t){this.inner=e;this.transforms=t}async get(e){let t=await this.inner.get(e);for(let i of this.transforms)t=await i(t);return t}async getByHref(e){let t=await this.inner.getByHref(e);for(let i of this.transforms)t=await i(t);return t}cancel(e){this.inner.cancel?.(e)}destroy(){this.inner.destroy?.()}}});var dO={};jt(dO,{AudiobookSettings:()=>mE});function hc(n,e,t){return Math.max(e,Math.min(t,n))}var qi,cO,xn,Gm,mE,hO=Me(()=>{x();qi={volume:1,playbackRate:1,preservePitch:!0,skipBackwardInterval:10,skipForwardInterval:30,pollInterval:1e3,autoPlay:!0,enableMediaSession:!0,timelineMode:"chapter"},cO=new Set(["chapter","book","both"]),xn={volume:[0,1],playbackRate:[.5,4],skipBackwardInterval:[5,60],skipForwardInterval:[5,60],pollInterval:[0,Number.MAX_SAFE_INTEGER]},Gm="audiobook-",mE=class n{constructor(e){this.listeners=new Set;this._volume=qi.volume;this._playbackRate=qi.playbackRate;this._preservePitch=qi.preservePitch;this._skipBackwardInterval=qi.skipBackwardInterval;this._skipForwardInterval=qi.skipForwardInterval;this._pollInterval=qi.pollInterval;this._autoPlay=qi.autoPlay;this._enableMediaSession=qi.enableMediaSession;this._timelineMode=qi.timelineMode;this.store=e}static async create(e){let t=new n(e.store);return t.loadFromStore(),e.initialAudiobookSettings&&t.apply(e.initialAudiobookSettings),t}loadFromStore(){this._volume=this.readNumber("volume",qi.volume,xn.volume),this._playbackRate=this.readNumber("playbackRate",qi.playbackRate,xn.playbackRate),this._preservePitch=this.readBoolean("preservePitch",qi.preservePitch),this._skipBackwardInterval=this.readNumber("skipBackwardInterval",qi.skipBackwardInterval,xn.skipBackwardInterval),this._skipForwardInterval=this.readNumber("skipForwardInterval",qi.skipForwardInterval,xn.skipForwardInterval),this._pollInterval=this.readNumber("pollInterval",qi.pollInterval,xn.pollInterval),this._autoPlay=this.readBoolean("autoPlay",qi.autoPlay),this._enableMediaSession=this.readBoolean("enableMediaSession",qi.enableMediaSession),this._timelineMode=this.readEnum("timelineMode",qi.timelineMode,cO)}apply(e){e.volume!==void 0&&(this.volume=e.volume),e.playbackRate!==void 0&&(this.playbackRate=e.playbackRate),e.preservePitch!==void 0&&(this.preservePitch=e.preservePitch),e.skipBackwardInterval!==void 0&&(this.skipBackwardInterval=e.skipBackwardInterval),e.skipForwardInterval!==void 0&&(this.skipForwardInterval=e.skipForwardInterval),e.pollInterval!==void 0&&(this.pollInterval=e.pollInterval),e.autoPlay!==void 0&&(this.autoPlay=e.autoPlay),e.enableMediaSession!==void 0&&(this.enableMediaSession=e.enableMediaSession),e.timelineMode!==void 0&&(this.timelineMode=e.timelineMode)}toJSON(){return{volume:this._volume,playbackRate:this._playbackRate,preservePitch:this._preservePitch,skipBackwardInterval:this._skipBackwardInterval,skipForwardInterval:this._skipForwardInterval,pollInterval:this._pollInterval,autoPlay:this._autoPlay,enableMediaSession:this._enableMediaSession,timelineMode:this._timelineMode}}onChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}get volume(){return this._volume}set volume(e){let t=hc(e,xn.volume[0],xn.volume[1]);t!==this._volume&&(this._volume=t,this.persist("volume",t))}get playbackRate(){return this._playbackRate}set playbackRate(e){let t=hc(e,xn.playbackRate[0],xn.playbackRate[1]);t!==this._playbackRate&&(this._playbackRate=t,this.persist("playbackRate",t))}get preservePitch(){return this._preservePitch}set preservePitch(e){e!==this._preservePitch&&(this._preservePitch=e,this.persist("preservePitch",e))}get skipBackwardInterval(){return this._skipBackwardInterval}set skipBackwardInterval(e){let t=hc(e,xn.skipBackwardInterval[0],xn.skipBackwardInterval[1]);t!==this._skipBackwardInterval&&(this._skipBackwardInterval=t,this.persist("skipBackwardInterval",t))}get skipForwardInterval(){return this._skipForwardInterval}set skipForwardInterval(e){let t=hc(e,xn.skipForwardInterval[0],xn.skipForwardInterval[1]);t!==this._skipForwardInterval&&(this._skipForwardInterval=t,this.persist("skipForwardInterval",t))}get pollInterval(){return this._pollInterval}set pollInterval(e){let t=hc(e,xn.pollInterval[0],xn.pollInterval[1]);t!==this._pollInterval&&(this._pollInterval=t,this.persist("pollInterval",t))}get autoPlay(){return this._autoPlay}set autoPlay(e){e!==this._autoPlay&&(this._autoPlay=e,this.persist("autoPlay",e))}get enableMediaSession(){return this._enableMediaSession}set enableMediaSession(e){e!==this._enableMediaSession&&(this._enableMediaSession=e,this.persist("enableMediaSession",e))}get timelineMode(){return this._timelineMode}set timelineMode(e){cO.has(e)&&e!==this._timelineMode&&(this._timelineMode=e,this.persist("timelineMode",e))}readNumber(e,t,i){let r=this.store.get(Gm+e);if(r==null)return t;let s=Number(r);return Number.isFinite(s)?hc(s,i[0],i[1]):t}readBoolean(e,t){let i=this.store.get(Gm+e);return i==null?t:typeof i=="boolean"?i:i==="true"||i==="1"}readEnum(e,t,i){let r=this.store.get(Gm+e);return r==null||typeof r!="string"?t:i.has(r)?r:t}persist(e,t){this.store.set(Gm+e,String(t));for(let i of this.listeners)i(e)}}});var fO={};jt(fO,{AudiobookBookmarkModule:()=>bE});function Mne(n){(!Number.isFinite(n)||n<0)&&(n=0);let e=Math.floor(n/3600),t=Math.floor(n%3600/60),i=Math.floor(n%60),r=String(t).padStart(e>0?2:1,"0"),s=String(i).padStart(2,"0");return e>0?`${e}:${r}:${s}`:`${r}:${s}`}var Jh,bE,pO=Me(()=>{x();zt();Il();cn();Jh=class Jh{constructor(e){this.name=ye.Bookmarks;this.hostType=Ve.Audiobook;this.rightsKey=st.Bookmarks;this.annotator=e.annotator,this.publication=e.publication,this.listContainer=e.listContainer}static async create(e){return new Jh(e)}attach(e){this.host=e,this.listContainer&&this.renderList()}save(){if(this.hasBookmarkAt())return null;let e=this.makeBookmark();if(!e)return null;let t=this.annotator.saveBookmark(e)??null;return t&&(this.host.emit(ce.BookmarkCreated,t),this.listContainer&&this.renderList()),t}delete(e){this.annotator.deleteBookmark(e),this.host.emit(ce.BookmarkDeleted,e),this.listContainer&&this.renderList()}list(){return this.annotator.getBookmarks()}hasBookmarkAt(e){return this.findBookmarkAt(e)!==null}findBookmarkAt(e){let t=e??this.host.currentLocator(),i=t.href,r=t.locations?.time;if(!i||typeof r!="number")return null;let s=Jh.MATCH_TOLERANCE_SECONDS;return this.annotator.getBookmarks(this.publication.getAbsoluteHref(i)).find(a=>{let u=a.locations?.time;return typeof u=="number"&&Math.abs(u-r)<=s})??null}stop(){this.listContainer&&(this.listContainer.innerHTML="")}renderList(){let e=this.listContainer;if(!e)return;e.innerHTML="";let t=this.list();if(t.length===0)return;let i=this.publication.readingOrder,r=document.createElement("ol");r.className="dita-audiobook-bookmarks",i.forEach((s,o)=>{let a=this.publication.getAbsoluteHref(s.href),u=t.filter(c=>c.href===a).sort((c,d)=>(c.locations?.time??0)-(d.locations?.time??0));if(u.length===0)return;let l=document.createElement("li");l.className="dita-audiobook-bookmarks-heading",l.textContent=s.title||`Track ${o+1}`,r.appendChild(l);for(let c of u)r.appendChild(this.buildRow(c,s.href))}),e.appendChild(r)}buildRow(e,t){let i=document.createElement("li");i.className="dita-audiobook-bookmarks-row",i.tabIndex=0,i.setAttribute("role","button");let r=document.createElement("span");r.className="dita-audiobook-bookmarks-time",r.textContent=Mne(e.locations?.time??0),i.appendChild(r);let s=document.createElement("button");s.type="button",s.className="dita-audiobook-bookmarks-delete",s.setAttribute("aria-label","Delete bookmark"),s.textContent="\u2715",s.addEventListener("click",a=>{a.stopPropagation(),this.delete(e)}),i.appendChild(s);let o=a=>{a.target?.closest("button")||this.host.goTo({href:t,locations:{time:e.locations?.time??0}})};return i.addEventListener("click",o),i.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),o(a))}),i}makeBookmark(){let e=this.host.currentLocator();return e.href?{id:crypto.randomUUID(),href:this.publication.getAbsoluteHref(e.href),type:e.type??"audio/*",title:e.title,locations:e.locations,created:new Date}:null}};Jh.MATCH_TOLERANCE_SECONDS=1;bE=Jh});var gO={};jt(gO,{AudiobookCommentsModule:()=>yE});function One(n){(!Number.isFinite(n)||n<0)&&(n=0);let e=Math.floor(n/3600),t=Math.floor(n%3600/60),i=Math.floor(n%60),r=String(t).padStart(e>0?2:1,"0"),s=String(i).padStart(2,"0");return e>0?`${e}:${r}:${s}`:`${r}:${s}`}var wu,yE,mO=Me(()=>{x();zt();Il();cn();wu=class wu{constructor(e){this.name=ye.Comments;this.hostType=Ve.Audiobook;this.rightsKey=st.Comments;this.lastActiveIds="";this.annotator=e.annotator,this.publication=e.publication,this.listContainer=e.listContainer,this.onEdit=e.onEdit}static async create(e){return new wu(e)}attach(e){this.host=e,this.listContainer&&this.renderList()}onTimeUpdate(e){this.recomputeActive(e.locator,e.currentTime)}add(e,t){let i=t??this.host.currentLocator();if(!i.href)return null;let r={id:crypto.randomUUID(),href:this.publication.getAbsoluteHref(i.href),type:i.type??"audio/*",title:i.title,locations:i.locations,created:new Date,body:e},s=this.annotator.saveComment(r)??null;return s&&(this.host.emit(ce.CommentCreated,s),this.recomputeActive(this.host.currentLocator(),this.currentTime()),this.listContainer&&this.renderList()),s}update(e,t){let i=this.annotator.updateComment(e,t);return i&&(this.host.emit(ce.CommentUpdated,i),this.listContainer&&this.renderList()),i}delete(e){this.annotator.deleteComment(e.id),this.host.emit(ce.CommentDeleted,{id:e.id}),this.recomputeActive(this.host.currentLocator(),this.currentTime()),this.listContainer&&this.renderList()}list(){return this.annotator.getComments()}findAt(e){let t=e??this.host.currentLocator(),i=t.href,r=t.locations?.time;return!i||typeof r!="number"?[]:this.annotator.getComments(this.publication.getAbsoluteHref(i)).filter(o=>this.isWithinWindow(o,r))}stop(){this.listContainer&&(this.listContainer.innerHTML="")}renderList(){let e=this.listContainer;if(!e)return;e.innerHTML="";let t=this.list();if(t.length===0)return;let i=this.publication.readingOrder,r=document.createElement("ol");r.className="dita-audiobook-comments",i.forEach((s,o)=>{let a=this.publication.getAbsoluteHref(s.href),u=t.filter(c=>c.href===a).sort((c,d)=>(c.locations?.time??0)-(d.locations?.time??0));if(u.length===0)return;let l=document.createElement("li");l.className="dita-audiobook-comments-heading",l.textContent=s.title||`Track ${o+1}`,r.appendChild(l);for(let c of u)r.appendChild(this.buildRow(c,s.href))}),e.appendChild(r)}buildRow(e,t){let i=document.createElement("li");i.className="dita-audiobook-comments-row",i.tabIndex=0,i.setAttribute("role","button");let r=document.createElement("span");r.className="dita-audiobook-comments-body",r.textContent=e.body??"",i.appendChild(r);let s=document.createElement("span");if(s.className="dita-audiobook-comments-time",s.textContent=One(e.locations?.time??0),i.appendChild(s),this.onEdit){let u=document.createElement("button");u.type="button",u.className="dita-audiobook-comments-edit",u.setAttribute("aria-label","Edit comment"),u.textContent="\u270E",u.addEventListener("click",l=>{l.stopPropagation(),this.onEdit?.(e)}),i.appendChild(u)}let o=document.createElement("button");o.type="button",o.className="dita-audiobook-comments-delete",o.setAttribute("aria-label","Delete comment"),o.textContent="\u2715",o.addEventListener("click",u=>{u.stopPropagation(),this.delete(e)}),i.appendChild(o);let a=u=>{u.target?.closest("button")||this.host.goTo({href:t,locations:{time:e.locations?.time??0}})};return i.addEventListener("click",a),i.addEventListener("keydown",u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),a(u))}),i}isWithinWindow(e,t){let i=e.locations?.time;if(typeof i!="number")return!1;let r=e.displayBefore??wu.DEFAULT_DISPLAY_BEFORE_SECONDS,s=e.displayAfter??wu.DEFAULT_DISPLAY_AFTER_SECONDS;return t>=i-r&&t<=i+s}recomputeActive(e,t){let i=e.href;if(!i)return;let s=this.annotator.getComments(this.publication.getAbsoluteHref(i)).filter(a=>this.isWithinWindow(a,t)),o=s.map(a=>a.id).join(",");o!==this.lastActiveIds&&(this.lastActiveIds=o,this.host.emit(ce.CommentsActive,{active:s,currentTime:t}))}currentTime(){return this.host.currentLocator().locations?.time??0}};wu.DEFAULT_DISPLAY_BEFORE_SECONDS=5,wu.DEFAULT_DISPLAY_AFTER_SECONDS=10;yE=wu});var vO={};jt(vO,{AudiobookTimelineModule:()=>vE});function fc(n){(!Number.isFinite(n)||n<0)&&(n=0);let e=Math.floor(n/3600),t=Math.floor(n%3600/60),i=Math.floor(n%60),r=t.toString().padStart(e>0?2:1,"0"),s=i.toString().padStart(2,"0");return e>0?`${e}:${r}:${s}`:`${r}:${s}`}function yO(n){let e=document.createElement("div");return e.textContent=n,e.innerHTML}function Wm(n,e){let t=n.reduce((l,c)=>l+c,0);if(t<=0||e<0||e>=n.length){let l=0;return n.map(c=>{let d=t>0?l/t*100:0;return l+=c,{startPct:d,widthPct:t>0?c/t*100:0}})}let i=n[e]/t*100,r=Math.min(100,Math.max(Bne,Math.min(i*Dne,Nne))),s=Math.max(0,100-r),o=t-n[e],a=[],u=0;for(let l=0;l<n.length;l++){let c=l===e?r:o>0?n[l]/o*s:0;a.push({startPct:u,widthPct:c}),u+=c}return a}function Fne(n,e){for(let t=0;t<n.length;t++)if(e>=n[t].startPct&&e<n[t].startPct+n[t].widthPct)return t;return Math.max(0,n.length-1)}function Hne(n,e,t){for(let i=0;i<e.length;i++){let{startPct:r,widthPct:s}=e[i];if(t>=r&&t<r+s){let o=(t-r)/s,a=0;for(let u=0;u<i;u++)a+=n[u];return a+o*n[i]}}return n.reduce((i,r)=>i+r,0)}var Nne,Bne,Dne,bO,vE,AO=Me(()=>{x();zt();Il();Nne=28,Bne=8,Dne=5,bO=5;vE=class n{constructor(e){this.name=ye.Timeline;this.hostType=Ve.Audiobook;this.rightsKey=st.Timeline;this.bars=[];this.settingsUnsubscribe=null;this._chapterStarts=[];this._bookDuration=0;this.publication=e.publication,this.settings=e.settings,this.chapterScrubberContainer=e.chapterScrubberContainer,this.bookScrubberContainer=e.bookScrubberContainer}static async create(e){let t=new n(e);return t.rebuild(),t}attach(e){this.host=e,this.chapterScrubberContainer&&this.bars.push(this.buildBar(this.chapterScrubberContainer,"auto")),this.bookScrubberContainer&&this.bars.push(this.buildBar(this.bookScrubberContainer,"book")),this.settings&&(this.settingsUnsubscribe=this.settings.onChange(t=>{t==="timelineMode"&&this.redraw()})),this.redraw()}stop(){this.settingsUnsubscribe&&(this.settingsUnsubscribe(),this.settingsUnsubscribe=null);for(let e of this.bars)e.boundPointerMove&&window.removeEventListener("pointermove",e.boundPointerMove),e.boundPointerUp&&window.removeEventListener("pointerup",e.boundPointerUp),e.container.innerHTML="";this.bars=[]}rebuild(){let e=this.publication.readingOrder??[];this._chapterStarts=[];let t=0;for(let i of e)this._chapterStarts.push(t),t+=i.duration??0;this._bookDuration=t}get chapterStarts(){return this._chapterStarts}get bookDuration(){return this._bookDuration}get isUsable(){return this._bookDuration>0}toBookTime(e,t){if(this._chapterStarts.length===0)return 0;let i=Math.max(0,Math.min(this._chapterStarts.length-1,e|0)),r=Math.max(0,t||0);return this._chapterStarts[i]+r}fromBookTime(e){let t=this.publication.readingOrder??[];if(t.length===0)return{chapterIndex:0,timeInChapter:0,href:""};let i=Math.max(0,Math.min(this._bookDuration,e)),r=t.length-1;for(let s=0;s<t.length;s++){let a=this._chapterStarts[s]+(t[s].duration??0);if(i<a){r=s;break}}return{chapterIndex:r,timeInChapter:i-(this._chapterStarts[r]??0),href:t[r].href}}currentBookTime(){if(!this.host)return 0;let e=this.host.currentLocator();if(!e?.href)return 0;let i=(this.publication.readingOrder??[]).findIndex(s=>s.href===e.href);if(i<0)return 0;let r=e.locations?.time??0;return this.toBookTime(i,r)}onTimeUpdate(){for(let e of this.bars)this.renderPlayhead(e)}onTrackChanged(){this.redraw()}onDurationChanged(){this.rebuild(),this.redraw()}onBookmarkChanged(){for(let e of this.bars)this.renderMarkers(e)}onCommentChanged(){for(let e of this.bars)this.renderMarkers(e)}resolveScope(e){if((e.modeKind==="book"||this.timelineModeSetting()==="book")&&this.isUsable)return{scope:"book",duration:this._bookDuration,position:this.currentBookTime()};let i=this.host?.currentResource()??0,s=this.publication.readingOrder?.[i]?.duration??0,o=this.host?.currentLocator()?.locations?.time??0;return{scope:"chapter",duration:s,position:o}}timelineModeSetting(){return this.settings?.timelineMode??"chapter"}currentChapterIndex(){return this.host?.currentResource()??0}bookmarks(){return this.host?.getModule(ye.Bookmarks)?.list()??[]}comments(){return this.host?.getModule(ye.Comments)?.list()??[]}redraw(){for(let e of this.bars)this.renderMarkers(e),this.renderPlayhead(e)}buildBar(e,t){let i=document.createElement("div");i.className="dita-audiobook-timeline",i.setAttribute("role","slider"),i.tabIndex=0,i.setAttribute("aria-valuemin","0"),i.setAttribute("aria-valuemax","0"),i.setAttribute("aria-valuenow","0");let r=document.createElement("div");r.className="dita-audiobook-timeline-fill",i.appendChild(r);let s=document.createElement("div");s.className="dita-audiobook-timeline-markers",i.appendChild(s);let o=document.createElement("div");o.className="dita-audiobook-timeline-thumb",i.appendChild(o);let a=document.createElement("div");a.className="dita-audiobook-timeline-tooltip",a.setAttribute("aria-hidden","true"),i.appendChild(a),e.innerHTML="",e.appendChild(i);let u={container:e,modeKind:t,root:i,fill:r,thumb:o,markersHost:s,tooltip:a,isDragging:!1,dragValue:0,fisheye:null};return i.addEventListener("pointerdown",l=>this.beginDrag(u,l)),i.addEventListener("pointermove",l=>this.onHover(u,l)),i.addEventListener("pointerleave",()=>this.onHoverEnd(u)),i.addEventListener("keydown",l=>this.onKeyDown(u,l)),u}renderPlayhead(e){if(e.isDragging)return;let{duration:t,position:i}=this.resolveScope(e),r=t>0?Math.min(100,i/t*100):0;e.fill.style.width=r+"%",e.thumb.style.left=r+"%",e.root.setAttribute("aria-valuemin","0"),e.root.setAttribute("aria-valuemax",String(Math.round(t))),e.root.setAttribute("aria-valuenow",String(Math.round(i))),e.root.setAttribute("aria-valuetext",`${fc(i)} of ${fc(t)}`)}renderMarkers(e){e.markersHost.innerHTML="";let{scope:t,duration:i}=this.resolveScope(e);if(i<=0)return;let r=this.publication.readingOrder??[],s=this.bookmarks(),o=this.comments(),a=(u,l,c,d)=>{let f=Math.min(100,Math.max(0,u/i*100)),m=document.createElement("div");m.className=`dita-audiobook-timeline-marker ${l}`,m.style.left=f+"%",t==="book"&&(m.dataset.bookTime=String(u)),m.addEventListener("click",y=>{y.stopPropagation(),d()}),m.addEventListener("pointerenter",()=>{e.tooltip.innerHTML=c,e.tooltip.style.left=m.style.left,e.tooltip.dataset.visible="true"}),m.addEventListener("pointerleave",()=>{delete e.tooltip.dataset.visible}),e.markersHost.appendChild(m)};if(t==="book")r.forEach((u,l)=>{let c=this._chapterStarts[l]??0,d=u.duration??0,f=Math.min(100,Math.max(0,c/i*100)),m=Math.min(100,Math.max(0,d/i*100)),y=document.createElement("div");if(y.className="dita-audiobook-timeline-chapter",y.style.left=f+"%",y.style.width=m+"%",y.dataset.chapterIndex=String(l),y.dataset.chapterBand="true",e.markersHost.appendChild(y),l>0){let b=document.createElement("div");b.className="dita-audiobook-timeline-boundary",b.style.left=f+"%",b.dataset.chapterIndex=String(l);let v=u.title||`Track ${l+1}`;b.title=`${v} \u2014 ${fc(c)}`,b.setAttribute("aria-label",`Jump to ${v}`),b.addEventListener("click",A=>{A.stopPropagation(),this.seekToBookTime(c)}),e.markersHost.appendChild(b)}let g=this.publication.getAbsoluteHref(u.href);for(let b of s){if(b.href!==g)continue;let v=b.locations?.time;typeof v=="number"&&a(c+v,"bookmark",this.bookmarkTooltipHTML(v),()=>this.seekToBookTime(c+v))}for(let b of o){if(b.href!==g)continue;let v=b.locations?.time;typeof v=="number"&&a(c+v,"comment",this.commentTooltipHTML(b.body??"",v),()=>this.seekToBookTime(c+v))}});else{let u=this.currentChapterIndex(),l=r[u];if(!l)return;let c=this.publication.getAbsoluteHref(l.href);for(let d of s){if(d.href!==c)continue;let f=d.locations?.time;typeof f=="number"&&a(f,"bookmark",this.bookmarkTooltipHTML(f),()=>this.seekToChapterTime(f))}for(let d of o){if(d.href!==c)continue;let f=d.locations?.time;typeof f=="number"&&a(f,"comment",this.commentTooltipHTML(d.body??"",f),()=>this.seekToChapterTime(f))}}}bookmarkTooltipHTML(e){return`Bookmark<span class="dita-audiobook-timeline-tooltip-time">${fc(e)}</span>`}commentTooltipHTML(e,t){let i=e.length>60?e.slice(0,57)+"\u2026":e;return`${yO(i)}<span class="dita-audiobook-timeline-tooltip-time">${fc(t)}</span>`}onHover(e,t){let{scope:i}=this.resolveScope(e);i==="book"&&this.isUsable&&this.updateFisheye(e,t),this.updateTooltip(e,t)}onHoverEnd(e){e.fisheye&&(e.fisheye=null,this.applyFisheyeVisuals(e,-1)),delete e.tooltip.dataset.visible}updateFisheye(e,t){let r=(this.publication.readingOrder??[]).map(l=>l.duration??0);if(r.length<2)return;let s=this.cursorPercent(e,t),o=e.fisheye?.layout??Wm(r,-1),a=Fne(o,s),u=Wm(r,a);e.fisheye={layout:u,hoveredIdx:a},this.applyFisheyeVisuals(e,a)}applyFisheyeVisuals(e,t){let r=(this.publication.readingOrder??[]).map(o=>o.duration??0),s=Wm(r,t);for(let o of e.markersHost.querySelectorAll("[data-chapter-band]")){let a=Number(o.dataset.chapterIndex);!Number.isFinite(a)||!s[a]||(o.style.left=s[a].startPct+"%",o.style.width=s[a].widthPct+"%",a===t?o.dataset.hovered="true":delete o.dataset.hovered)}for(let o of e.markersHost.querySelectorAll("[data-chapter-index]:not([data-chapter-band])")){let a=Number(o.dataset.chapterIndex);Number.isFinite(a)&&s[a]&&(o.style.left=s[a].startPct+"%")}for(let o of e.markersHost.querySelectorAll("[data-book-time]")){let a=Number(o.dataset.bookTime);if(!Number.isFinite(a))continue;let u=this.fromBookTime(a),l=u.chapterIndex,c=r[l]>0?u.timeInChapter/r[l]:0,d=s[l];d&&(o.style.left=d.startPct+c*d.widthPct+"%")}}updateTooltip(e,t){if(t.target?.closest(".dita-audiobook-timeline-marker, .dita-audiobook-timeline-boundary"))return;let r=this.cursorPercent(e,t),{scope:s,duration:o}=this.resolveScope(e);if(o<=0){delete e.tooltip.dataset.visible;return}let a=this.publication.readingOrder??[],u="",l=0;if(s==="book"){let c=this.cursorBookTime(e,t),d=this.fromBookTime(c);u=a[d.chapterIndex]?.title||`Track ${d.chapterIndex+1}`,l=d.timeInChapter}else{let c=this.currentChapterIndex();u=a[c]?.title||`Track ${c+1}`,l=r/100*o}e.tooltip.innerHTML=`${yO(u)}<span class="dita-audiobook-timeline-tooltip-time">${fc(l)}</span>`,e.tooltip.style.left=r+"%",e.tooltip.dataset.visible="true"}cursorPercent(e,t){let i=e.root.getBoundingClientRect();return Math.max(0,Math.min(100,(t.clientX-i.left)/i.width*100))}cursorBookTime(e,t){let r=(this.publication.readingOrder??[]).map(o=>o.duration??0),s=e.fisheye?.layout??Wm(r,-1);return Hne(r,s,this.cursorPercent(e,t))}beginDrag(e,t){let{duration:i}=this.resolveScope(e);i<=0||(e.isDragging=!0,e.root.classList.add("dragging"),this.updateDrag(e,t),e.boundPointerMove=r=>this.updateDrag(e,r),e.boundPointerUp=()=>this.endDrag(e),window.addEventListener("pointermove",e.boundPointerMove),window.addEventListener("pointerup",e.boundPointerUp,{once:!0}))}updateDrag(e,t){if(!e.isDragging)return;let{scope:i,duration:r}=this.resolveScope(e),s=this.cursorPercent(e,t);if(i==="book"){this.updateFisheye(e,t),e.dragValue=this.cursorBookTime(e,t);let o=this.fromBookTime(e.dragValue);this.host.prefetchResource(o.chapterIndex)}else e.dragValue=s/100*r;e.fill.style.width=s+"%",e.thumb.style.left=s+"%",e.root.setAttribute("aria-valuenow",String(Math.round(e.dragValue)))}endDrag(e){if(!e.isDragging)return;e.isDragging=!1,e.root.classList.remove("dragging"),e.boundPointerMove&&(window.removeEventListener("pointermove",e.boundPointerMove),e.boundPointerMove=void 0),e.boundPointerUp=void 0;let{scope:t}=this.resolveScope(e);t==="book"?this.seekToBookTime(e.dragValue):this.seekToChapterTime(e.dragValue)}onKeyDown(e,t){let{scope:i,duration:r,position:s}=this.resolveScope(e);if(r<=0)return;let o=null;switch(t.key){case"ArrowLeft":t.preventDefault(),o=Math.max(0,s-bO);break;case"ArrowRight":t.preventDefault(),o=Math.min(r,s+bO);break;case"Home":t.preventDefault(),o=0;break;case"End":t.preventDefault(),o=Math.max(0,r-1);break}o!==null&&(i==="book"?this.seekToBookTime(o):this.seekToChapterTime(o))}seekToChapterTime(e){let t=this.currentChapterIndex(),i=this.publication.readingOrder?.[t];i&&this.host.goTo({href:i.href,locations:{time:e}})}seekToBookTime(e){let t=this.fromBookTime(e);this.host.goTo({href:t.href,locations:{time:t.timeInChapter}})}}});var wO={};jt(wO,{PdfBookmarkModule:()=>AE});var AE,EO=Me(()=>{x();zt();ei();Nn();AE=class{constructor(e){this.name=ye.Bookmarks;this.hostType=Ve.PDF;this.rightsKey=st.Bookmarks;this.annotator=e.annotator,this.publication=e.publication}attach(e){this.host=e}save(){return this.hasBookmarkAt()?null:this.annotator.saveBookmark(this.makeBookmark())??null}delete(e){this.annotator.deleteBookmark(e)}list(){return this.host.currentResourceLink?this.annotator.getBookmarks(this.publication.getAbsoluteHref(this.host.currentResourceLink.href)):[]}hasBookmarkAt(e){return this.findBookmarkAt(e)!==null}findBookmarkAt(e){let t=(e?Ur(e.locations):void 0)??this.host.currentPage;return this.list().find(i=>Ur(i.locations)===t)??null}stop(){}makeBookmark(){return{id:crypto.randomUUID(),href:this.host.currentResourceLink?this.publication.getAbsoluteHref(this.host.currentResourceLink.href):"",locations:{page:this.host.currentPage},type:"application/pdf",title:`Page ${this.host.currentPage}`,created:new Date}}}});var CO={};jt(CO,{PdfSearchModule:()=>wE});var wE,SO=Me(()=>{x();zt();ei();cn();wE=class{constructor(){this.name=ye.Search;this.hostType=Ve.PDF;this.rightsKey=st.Search;this._query="";this._caseSensitive=!1;this._highlightAll=!0;this._entireWord=!1;this._matchCount=0;this._currentMatch=0;this.onMatchesUpdate=e=>{e?.matchesCount&&(this._currentMatch=e.matchesCount.current??0,this._matchCount=e.matchesCount.total??0,this.host.emit(ce.PdfMatchesUpdated,{current:this._currentMatch,total:this._matchCount}))}}attach(e){this.host=e}setup(){this.host.eventBus.on("updatefindmatchescount",this.onMatchesUpdate),this.host.eventBus.on("updatefindcontrolstate",this.onMatchesUpdate)}search(e,t){this._query=e,this._caseSensitive=t?.caseSensitive??!1,this._highlightAll=t?.highlightAll??!0,this._entireWord=t?.entireWord??!1,this.host.eventBus.dispatch("find",{query:e,caseSensitive:this._caseSensitive,highlightAll:this._highlightAll,entireWord:this._entireWord,findPrevious:!1,type:""})}next(){this._query&&this.host.eventBus.dispatch("find",{query:this._query,caseSensitive:this._caseSensitive,highlightAll:this._highlightAll,entireWord:this._entireWord,findPrevious:!1,type:"again"})}previous(){this._query&&this.host.eventBus.dispatch("find",{query:this._query,caseSensitive:this._caseSensitive,highlightAll:this._highlightAll,entireWord:this._entireWord,findPrevious:!0,type:"again"})}clear(){this._query="",this._matchCount=0,this._currentMatch=0,this.host.eventBus.dispatch("find",{query:"",caseSensitive:!1,highlightAll:!0,entireWord:!1,findPrevious:!1,type:""})}matchCount(){return this._matchCount}currentMatch(){return this._currentMatch}stop(){this.host?.eventBus.off("updatefindmatchescount",this.onMatchesUpdate),this.host?.eventBus.off("updatefindcontrolstate",this.onMatchesUpdate)}}});var TO={};jt(TO,{PdfAnnotationModule:()=>EE});function Une(n){return typeof n=="object"&&n!==null&&"bitmap"in n&&n.bitmap!==void 0}function jne(n){return typeof n=="object"&&n!==null&&"pageIndex"in n&&typeof n.pageIndex=="number"?n.pageIndex:0}var xO,EE,IO=Me(()=>{x();xO=Xe(to());zt();ei();K4();EE=class n{constructor(e){this.name=ye.Annotations;this.hostType=Ve.PDF;this.rightsKey=st.Annotations;this.pendingAnnotations=null;this.onLayerRendered=async e=>{if(e.error||!this.pendingAnnotations)return;let t=e.pageNumber-1,i=this.pendingAnnotations.get(t);if(!i||i.length===0)return;this.pendingAnnotations.delete(t);let r=e.source?.annotationEditorLayer?.annotationEditorLayer;if(!r||!this.host.pdfDoc)return;let s=this.host.pdfDoc.annotationStorage,o=DM(s);Mm(s,null);for(let a of i)try{let u=await r.deserialize(a);u&&r.addOrRebuild(u)}catch(u){console.warn("PdfAnnotationModule: failed to restore annotation",a,u)}Mm(s,o),this.save()};this.viewStore=e.viewStore}attach(e){this.host=e}setup(){this.debouncedSave=(0,xO.default)(()=>{this.host.pdfDoc&&this.save()},200),this.host.eventBus.on("annotationeditorlayerrendered",this.onLayerRendered),this.host.eventBus.on("annotationeditorstateschanged",this.debouncedSave)}onResourceReady(){let e=this.host.fingerprint??"";!e||e===this.lastFingerprint||(this.lastFingerprint=e,this.pendingAnnotations=null,this.restore(e),this.host.pdfDoc&&Mm(this.host.pdfDoc.annotationStorage,()=>{this.save()}))}stop(){this.host?.eventBus.off("annotationeditorlayerrendered",this.onLayerRendered),this.host?.eventBus.off("annotationeditorstateschanged",this.debouncedSave)}getAll(){let e=[];if(this.host.pdfDoc){let{map:t}=Om(this.host.pdfDoc.annotationStorage);if(t)for(let i of t.values())e.push(n.toJsonSafe(i))}if(this.pendingAnnotations)for(let t of this.pendingAnnotations.values())for(let i of t)e.push(i);return e.sort((t,i)=>(t.pageIndex??0)-(i.pageIndex??0)),e}clear(){if(!this.host.pdfDoc)return;let e=this.host.pdfDoc.annotationStorage,{map:t}=Om(e);if(t)for(let r of t.keys())e.remove(r);let i=this.host.fingerprint;this.viewStore&&i&&this.viewStore.remove(this.storageKey(i)),this.pendingAnnotations=null}setEditorMode(e){this.host.pdfViewer.annotationEditorMode={mode:e}}save(){if(!this.viewStore||!this.host.pdfDoc)return;let e=this.host.fingerprint??"",t=this.storageKey(e),i={},{map:r}=Om(this.host.pdfDoc.annotationStorage);if(r)for(let[s,o]of r)Une(o)||(i[s]=n.toJsonSafe(o));if(this.pendingAnnotations){let s=0;for(let[o,a]of this.pendingAnnotations)for(let u of a)i[`_pending_p${o}_${s++}`]=u}Object.keys(i).length===0?this.viewStore.remove(t):this.viewStore.set(t,JSON.stringify(i))}restore(e){if(this.pendingAnnotations=null,!this.viewStore)return;let t=this.storageKey(e),i=this.viewStore.get(t);if(i)try{let r=JSON.parse(i),s=new Map;for(let o of Object.values(r)){let a=jne(o);s.has(a)||s.set(a,[]),s.get(a).push(o)}this.pendingAnnotations=s}catch{}}storageKey(e){return`pdf-ann-${e}`}static toJsonSafe(e){if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Array.from(e);if(Array.isArray(e))return e.map(n.toJsonSafe);if(e!==null&&typeof e=="object"){let t={};for(let[i,r]of Object.entries(e))t[i]=n.toJsonSafe(r);return t}return e}}});var kO={};jt(kO,{PdfHistoryModule:()=>CE});var CE,_O=Me(()=>{x();zt();ei();Nn();CE=class{constructor(){this.name=ye.History;this.hostType=Ve.PDF;this.rightsKey=st.History;this.stack=[];this.cursor=-1}attach(e){this.host=e}setup(){}push(e){let t=Ur(e.locations);t!==void 0&&(this.cursor<this.stack.length-1&&(this.stack=this.stack.slice(0,this.cursor+1)),this.stack[this.stack.length-1]!==t&&(this.stack.push(t),this.cursor=this.stack.length-1))}back(){this.canGoBack()&&(this.cursor-=1,this.host.goToPage(this.stack[this.cursor]))}forward(){this.canGoForward()&&(this.cursor+=1,this.host.goToPage(this.stack[this.cursor]))}canGoBack(){return this.cursor>0}canGoForward(){return this.cursor<this.stack.length-1}stop(){}}});var PO={};jt(PO,{PdfViewSettingsModule:()=>SE});var $i,SE,RO=Me(()=>{x();zt();ei();z4();$i=class $i{constructor(e){this.name=ye.ViewSettings;this.hostType=Ve.PDF;this.onPagesInit=()=>{this.restore()};this.viewStore=e.viewStore}attach(e){this.host=e}setup(){this.host.eventBus.on("pagesinit",this.onPagesInit)}fitToWidth(){this.host.pdfViewer.currentScaleValue="page-width",this.saveSetting($i.KEY_SCALE,"page-width")}fitToPage(){this.host.pdfViewer.currentScaleValue="page-fit",this.saveSetting($i.KEY_SCALE,"page-fit")}zoomIn(){this.host.pdfViewer.increaseScale(),this.saveSetting($i.KEY_SCALE,this.host.pdfViewer.currentScaleValue)}zoomOut(){this.host.pdfViewer.decreaseScale(),this.saveSetting($i.KEY_SCALE,this.host.pdfViewer.currentScaleValue)}rotateCw(){this.host.pdfViewer.pagesRotation=(this.host.pdfViewer.pagesRotation+90)%360,this.saveSetting($i.KEY_ROTATE,this.host.pdfViewer.pagesRotation)}rotateCcw(){this.host.pdfViewer.pagesRotation=(this.host.pdfViewer.pagesRotation+270)%360,this.saveSetting($i.KEY_ROTATE,this.host.pdfViewer.pagesRotation)}setSpreadMode(e){this.host.pdfViewer.spreadMode=e,this.saveSetting($i.KEY_SPREAD,e)}setScrollMode(e,t){let i=e?t==="horizontal"?ot.HORIZONTAL:t==="wrapped"?ot.WRAPPED:ot.VERTICAL:ot.PAGE;this.host.pdfViewer.scrollMode=i,this.saveSetting($i.KEY_SCROLL,i)}stop(){this.host?.eventBus.off("pagesinit",this.onPagesInit)}saveSetting(e,t){this.viewStore.set(e,String(t))}restore(){let e=this.viewStore,t=e.get($i.KEY_SCROLL),i=e.get($i.KEY_SPREAD),r=e.get($i.KEY_SCALE),s=e.get($i.KEY_ROTATE);this.host.pdfViewer.currentScaleValue=r??"page-fit",t!=null&&(this.host.pdfViewer.scrollMode=Number(t)),i!=null&&(this.host.pdfViewer.spreadMode=Number(i)),s!=null&&(this.host.pdfViewer.pagesRotation=Number(s))}};$i.KEY_SCROLL="pdf-scroll-mode",$i.KEY_SPREAD="pdf-spread-mode",$i.KEY_SCALE="pdf-scale-value",$i.KEY_ROTATE="pdf-rotation";SE=$i});var XO={};jt(XO,{AntiAutomation:()=>VO,BrowserEnforcement:()=>UO,ContentExpiration:()=>YO,ContentProtection:()=>Gne,ContextMenuProtection:()=>NO,CopyProtection:()=>OO,DevToolsDetection:()=>DO,DragPrevention:()=>LO,ImageProtection:()=>zO,KeyboardProtection:()=>BO,LinkUrlHiding:()=>HO,MediaProtection:()=>qO,MediaStreamProtection:()=>$O,PrintProtection:()=>MO,ScreenshotDetection:()=>jO,SelectionLimiting:()=>WO,SpeechSynthesisBlocking:()=>KO,TamperDetection:()=>QO,TextObfuscation:()=>FO,Watermarking:()=>GO});function xE(){return typeof navigator<"u"&&(/Mac/.test(navigator.platform)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1)}function di(n,e,t,i){if(!n)return null;try{return n.addEventListener(e,t,i),{target:n,type:e,handler:t,options:i}}catch{return null}}function Eo(n){for(let{target:e,type:t,handler:i,options:r}of n)try{e.removeEventListener(t,i,r)}catch{}n.length=0}function zm(n,e,t){let i=[n,window,document];if(e&&i.push(...e),t)for(let r of t)try{i.push(r),r.ownerDocument&&i.push(r.ownerDocument),r.contentDocument&&(i.push(r.contentDocument),r.contentDocument.body&&i.push(r.contentDocument.body)),r.contentWindow&&(i.push(r.contentWindow),r.contentWindow.document&&i.push(r.contentWindow.document))}catch{}return i}var LO,MO,OO,NO,BO,DO,FO,HO,UO,jO,GO,WO,zO,VO,KO,YO,qO,$O,QO,Gne,JO=Me(()=>{x();LO=class{constructor(n){this.listeners=[],this.styledElements=[],this.config=n}activate(){let n=t=>(t.preventDefault(),t.stopPropagation(),this.config.onEvent?.({type:"drag_blocked",timestamp:Date.now()}),!1),e=zm(this.config.contentElement,this.config.additionalElements,this.config.contentIframes);for(let t of e)for(let i of["dragstart","drag","drop"]){let r=di(t,i,n,!0);r&&this.listeners.push(r)}if(this.applyCss(this.config.contentElement),this.config.contentIframes)for(let t of this.config.contentIframes)try{let i=t.contentDocument?.body;i&&this.applyCss(i)}catch{}}deactivate(){Eo(this.listeners);for(let n of this.styledElements)n.style.removeProperty("-webkit-user-drag"),n.style.removeProperty("user-drag");this.styledElements=[]}applyCss(n){n.style.setProperty("-webkit-user-drag","none"),n.style.setProperty("user-drag","none"),this.styledElements.push(n),n.querySelectorAll("img").forEach(e=>{e.setAttribute("draggable","false")})}},MO=class{constructor(n){this.listeners=[],this.styleElements=[],this.config=n}activate(){if(this.styleElements.push(this.injectPrintCss(document)),this.config.contentIframes)for(let s of this.config.contentIframes)try{let o=s.contentDocument;o&&this.styleElements.push(this.injectPrintCss(o))}catch{}let n=s=>(this.onBeforePrint(),s.preventDefault?.(),s.stopPropagation?.(),this.config.onEvent?.({type:"print_blocked",timestamp:Date.now()}),!1),e=()=>this.onAfterPrint(),t=[window];if(this.config.contentIframes)for(let s of this.config.contentIframes)try{s.contentWindow&&t.push(s.contentWindow)}catch{}for(let s of t){let o=di(s,"beforeprint",n),a=di(s,"afterprint",e);o&&this.listeners.push(o),a&&this.listeners.push(a)}let i=s=>{let o=s;(xE()?o.metaKey:o.ctrlKey)&&o.key==="p"&&(o.preventDefault(),o.stopPropagation(),this.config.onEvent?.({type:"print_blocked",timestamp:Date.now(),detail:"keyboard"}))},r=di(document,"keydown",i,!0);if(r&&this.listeners.push(r),this.config.contentIframes)for(let s of this.config.contentIframes)try{let o=s.contentDocument;if(o){let a=di(o,"keydown",i,!0);a&&this.listeners.push(a)}}catch{}}deactivate(){Eo(this.listeners);for(let n of this.styleElements)n.remove();this.styleElements=[]}injectPrintCss(n){let e=n.createElement("style");return e.setAttribute("data-protection","print"),e.textContent=`
|
|
605
605
|
@media print {
|
|
606
606
|
body, body * {
|
|
607
607
|
visibility: hidden !important;
|