@likecoin/epub-ts 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/epub.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const ne=require("jszip");function I(l){const t=typeof l=="function"?l.prototype:l;return t.on=function(e,i){return this.__listeners||(this.__listeners={}),this.__listeners[e]||(this.__listeners[e]=[]),this.__listeners[e].push(i),this},t.off=function(e,i){return!this.__listeners||!this.__listeners[e]?this:(i?this.__listeners[e]=this.__listeners[e].filter(function(s){return s!==i}):delete this.__listeners[e],this)},t.emit=function(e,...i){if(!this.__listeners||!this.__listeners[e])return;const s=this.__listeners[e].slice();for(let n=0;n<s.length;n++)s[n](...i)},l}const _t=typeof window<"u"?window.requestAnimationFrame.bind(window):!1,re=1,oe=3,zt=typeof URL<"u"?URL:window.URL;function dt(){let l=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const i=(l+Math.random()*16)%16|0;return l=Math.floor(l/16),(e=="x"?i:i&7|8).toString(16)})}function he(){return Math.max(document.documentElement.clientHeight,document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight)}function Dt(l){return!!(l&&l.nodeType==1)}function x(l){return!isNaN(parseFloat(l))&&isFinite(l)}function Bt(l){const t=parseFloat(l);return x(l)===!1?!1:typeof l=="string"&&l.indexOf(".")>-1?!0:Math.floor(t)!==t}function U(l){const t=["Webkit","webkit","Moz","O","ms"],e=["-webkit-","-webkit-","-moz-","-o-","-ms-"],i=l.toLowerCase(),s=t.length;if(typeof document>"u"||typeof document.body.style[i]<"u")return l;for(let n=0;n<s;n++)if(typeof document.body.style[e[n]+i]<"u")return e[n]+i;return l}function Mt(l,...t){for(let e=0;e<t.length;e++){const i=t[e];for(const s in i)l[s]===void 0&&(l[s]=i[s])}return l}function _(l,...t){return t.forEach(function(e){e&&Object.getOwnPropertyNames(e).forEach(function(i){Object.defineProperty(l,i,Object.getOwnPropertyDescriptor(e,i))})}),l}function le(l,t,e){const i=V(l,t,e);return t.splice(i,0,l),i}function V(l,t,e,i,s){const n=i||0,r=s||t.length,o=parseInt(n+(r-n)/2);if(e||(e=function(a,c){return a>c?1:a<c?-1:0}),r-n<=0)return o;const h=e(t[o],l);return r-n===1?h>=0?o:o+1:h===0?o:h===-1?V(l,t,e,o,r):V(l,t,e,n,o)}function st(l,t,e,i,s){const n=i||0,r=s||t.length,o=parseInt(n+(r-n)/2);if(e||(e=function(a,c){return a>c?1:a<c?-1:0}),r-n<=0)return-1;const h=e(t[o],l);return r-n===1?h===0?o:-1:h===0?o:h===-1?st(l,t,e,o,r):st(l,t,e,n,o)}function J(l){const t=window.getComputedStyle(l),e=["width","paddingRight","paddingLeft","marginRight","marginLeft","borderRightWidth","borderLeftWidth"],i=["height","paddingTop","paddingBottom","marginTop","marginBottom","borderTopWidth","borderBottomWidth"];let s=0,n=0;return e.forEach(function(r){s+=parseFloat(t[r])||0}),i.forEach(function(r){n+=parseFloat(t[r])||0}),{height:n,width:s}}function nt(l){const t=window.getComputedStyle(l),e=["paddingRight","paddingLeft","marginRight","marginLeft","borderRightWidth","borderLeftWidth"],i=["paddingTop","paddingBottom","marginTop","marginBottom","borderTopWidth","borderBottomWidth"];let s=0,n=0;return e.forEach(function(r){s+=parseFloat(t[r])||0}),i.forEach(function(r){n+=parseFloat(t[r])||0}),{height:n,width:s}}function yt(l){let t;const e=l.ownerDocument;if(l.nodeType==Node.TEXT_NODE){const i=e.createRange();i.selectNodeContents(l),t=i.getBoundingClientRect()}else t=l.getBoundingClientRect();return t}function rt(){const l=window.innerWidth,t=window.innerHeight;return{top:0,left:0,right:l,bottom:t,width:l,height:t}}function Tt(l,t){const i=l.parentNode.childNodes;let s,n=-1;for(let r=0;r<i.length&&(s=i[r],s.nodeType===t&&n++,s!=l);r++);return n}function ae(l){return Tt(l,oe)}function Wt(l){return Tt(l,re)}function G(l){return["xml","opf","ncx"].indexOf(l)>-1}function qt(l,t){return new Blob([l],{type:t})}function ot(l,t){const e=qt(l,t);return zt.createObjectURL(e)}function Ut(l){return zt.revokeObjectURL(l)}function wt(l,t){if(typeof l!="string")return;const e=btoa(l);return"data:"+t+";base64,"+e}function jt(l){return Object.prototype.toString.call(l).slice(8,-1)}function A(l,t){return l.charCodeAt(0)===65279&&(l=l.slice(1)),new DOMParser().parseFromString(l,t)}function w(l,t){if(!l)throw new Error("No Element Provided");return l.querySelector(t)??void 0}function B(l,t){return l.querySelectorAll(t)}function j(l,t,e){t+="[";for(const i in e)t+=i+"~='"+e[i]+"'";return t+="]",l.querySelector(t)??void 0}function ht(l,t){Ft(l,t,NodeFilter.SHOW_TEXT)}function Ft(l,t,e){const i=document.createTreeWalker(l,e,null);let s;for(;s=i.nextNode();)t(s)}function Ht(l,t,e){if(t(l))return!0;let i=l.firstChild;if(i)do{if(Ht(i,t))return!0;i=i.nextSibling}while(i)}function Vt(l){return new Promise(function(t,e){const i=new FileReader;i.readAsDataURL(l),i.onloadend=function(){t(i.result)}})}class v{constructor(){this.id=dt(),this.promise=new Promise((t,e)=>{this.resolve=t,this.reject=e}),Object.freeze(this)}}function lt(l,t,e){const i=l.querySelector(`${t}[*|type="${e}"]`);if(i)return i;const s=l.querySelectorAll(t);for(let n=0;n<s.length;n++)if(s[n].getAttributeNS("http://www.idpf.org/2007/ops","type")===e||s[n].getAttribute("epub:type")===e)return s[n]}function bt(l){const t=[],e=l.childNodes;for(let i=0;i<e.length;i++){const s=e[i];s.nodeType===1&&t.push(s)}return t}function xt(l){const t=[];for(let e=l??null;e;e=e.parentNode)t.unshift(e);return t}function F(l,t,e){const i=[],s=l.childNodes;for(let n=0;n<s.length;n++){const r=s[n];if(r.nodeType===1&&r.nodeName.toLowerCase()===t){if(e)return r;i.push(r)}}if(!e)return i}function ce(l,t){let e;if(!(l===null||t===""))for(e=l.parentNode;e&&e.nodeType===1;){if(e.tagName.toLowerCase()===t)return e;e=e.parentNode}}class Xt{constructor(){this.collapsed=!1,this.commonAncestorContainer=void 0,this.endContainer=void 0,this.endOffset=void 0,this.startContainer=void 0,this.startOffset=void 0}setStart(t,e){this.startContainer=t,this.startOffset=e,this.endContainer?this.commonAncestorContainer=this._commonAncestorContainer():this.collapse(!0),this._checkCollapsed()}setEnd(t,e){this.endContainer=t,this.endOffset=e,this.startContainer?(this.collapsed=!1,this.commonAncestorContainer=this._commonAncestorContainer()):this.collapse(!1),this._checkCollapsed()}collapse(t){var e,i;this.collapsed=!0,t?(this.endContainer=this.startContainer,this.endOffset=this.startOffset,this.commonAncestorContainer=((e=this.startContainer)==null?void 0:e.parentNode)??void 0):(this.startContainer=this.endContainer,this.startOffset=this.endOffset,this.commonAncestorContainer=((i=this.endContainer)==null?void 0:i.parentNode)??void 0)}selectNode(t){const e=t.parentNode,i=Array.from(e.childNodes).indexOf(t);this.setStart(e,i),this.setEnd(e,i+1)}selectNodeContents(t){const e=t.nodeType===3?(t.textContent??"").length:t.childNodes.length;this.setStart(t,0),this.setEnd(t,e)}_commonAncestorContainer(t,e){const i=xt(t??this.startContainer),s=xt(e??this.endContainer);if(i[0]==s[0]){for(let n=0;n<i.length;n++)if(i[n]!=s[n])return i[n-1]}}_checkCollapsed(){this.startContainer===this.endContainer&&this.startOffset===this.endOffset?this.collapsed=!0:this.collapsed=!1}toString(){return""}}const de=Object.freeze(Object.defineProperty({__proto__:null,RangeObject:Xt,blob2base64:Vt,borders:nt,bounds:J,createBase64Url:wt,createBlob:qt,createBlobUrl:ot,defaults:Mt,defer:v,documentHeight:he,extend:_,filterChildren:F,findChildren:bt,getParentByTagName:ce,indexOfElementNode:Wt,indexOfNode:Tt,indexOfSorted:st,indexOfTextNode:ae,insert:le,isElement:Dt,isFloat:Bt,isNumber:x,isXml:G,locationOf:V,nodeBounds:yt,parents:xt,parse:A,prefixed:U,qs:w,qsa:B,qsp:j,querySelectorByType:lt,requestAnimationFrame:_t,revokeBlobUrl:Ut,sprint:ht,treeWalker:Ft,type:jt,uuid:dt,walk:Ht,windowBounds:rt},Symbol.toStringTag,{value:"Module"}));function X(l){if(typeof l!="string")throw new TypeError("Path must be a string. Received "+l)}function ue(l,t){let e="",i=-1,s=0,n;for(let r=0;r<=l.length;++r){if(r<l.length)n=l.charCodeAt(r);else{if(n===47)break;n=47}if(n===47){if(!(i===r-1||s===1))if(i!==r-1&&s===2){if(e.length<2||e.charCodeAt(e.length-1)!==46||e.charCodeAt(e.length-2)!==46){if(e.length>2){const o=e.length-1;let h=o;for(;h>=0&&e.charCodeAt(h)!==47;--h);if(h!==o){h===-1?e="":e=e.slice(0,h),i=r,s=0;continue}}else if(e.length===2||e.length===1){e="",i=r,s=0;continue}}t&&(e.length>0?e+="/..":e="..")}else e.length>0?e+="/"+l.slice(i+1,r):e=l.slice(i+1,r);i=r,s=0}else n===46&&s!==-1?++s:s=-1}return e}function Et(...l){let t="",e=!1;for(let i=l.length-1;i>=-1&&!e;i--){const s=i>=0?l[i]:"/";X(s),s.length!==0&&(t=s+"/"+t,e=s.charCodeAt(0)===47)}return t=ue(t,!e),e?t.length>0?"/"+t:"/":t.length>0?t:"."}function fe(l,t){if(X(l),X(t),l===t||(l=Et(l),t=Et(t),l===t))return"";let e=1;for(;e<l.length&&l.charCodeAt(e)===47;++e);const i=l.length,s=i-e;let n=1;for(;n<t.length&&t.charCodeAt(n)===47;++n);const o=t.length-n,h=s<o?s:o;let a=-1,c=0;for(;c<=h;++c){if(c===h){if(o>h){if(t.charCodeAt(n+c)===47)return t.slice(n+c+1);if(c===0)return t.slice(n+c)}else s>h&&(l.charCodeAt(e+c)===47?a=c:c===0&&(a=0));break}const u=l.charCodeAt(e+c),p=t.charCodeAt(n+c);if(u!==p)break;u===47&&(a=c)}let d="";for(c=e+a+1;c<=i;++c)(c===i||l.charCodeAt(c)===47)&&(d.length===0?d+="..":d+="/..");return d.length>0?d+t.slice(n+a):(n+=a,t.charCodeAt(n)===47&&++n,t.slice(n))}function pe(l){if(X(l),l.length===0)return".";let t=l.charCodeAt(0);const e=t===47;let i=-1,s=!0;for(let n=l.length-1;n>=1;--n)if(t=l.charCodeAt(n),t===47){if(!s){i=n;break}}else s=!1;return i===-1?e?"/":".":e&&i===1?"//":l.slice(0,i)}function ge(l){return X(l),l.length>0&&l.charCodeAt(0)===47}function me(l){X(l);const t={root:"",dir:"",base:"",ext:"",name:""};if(l.length===0)return t;let e=l.charCodeAt(0);const i=e===47;let s;i?(t.root="/",s=1):s=0;let n=-1,r=0,o=-1,h=!0,a=l.length-1,c=0;for(;a>=s;--a){if(e=l.charCodeAt(a),e===47){if(!h){r=a+1;break}continue}o===-1&&(h=!1,o=a+1),e===46?n===-1?n=a:c!==1&&(c=1):n!==-1&&(c=-1)}return n===-1||o===-1||c===0||c===1&&n===o-1&&n===r+1?o!==-1&&(r===0&&i?t.base=t.name=l.slice(1,o):t.base=t.name=l.slice(r,o)):(r===0&&i?(t.name=l.slice(1,n),t.base=l.slice(1,o)):(t.name=l.slice(r,n),t.base=l.slice(r,o)),t.ext=l.slice(n,o)),r>0?t.dir=l.slice(0,r-1):i&&(t.dir="/"),t}const D={resolve:Et,relative:fe,dirname:pe,isAbsolute:ge,parse:me};class P{constructor(t){t.indexOf("://")>-1&&(t=new URL(t).pathname);const i=this.parse(t);this.path=t,this.isDirectory(t)?(this.directory=t,this.filename="",this.extension=""):(this.directory=i.dir+"/",this.filename=i.base,this.extension=i.ext.slice(1))}parse(t){return D.parse(t)}isAbsolute(t){return D.isAbsolute(t||this.path)}isDirectory(t){return t.charAt(t.length-1)==="/"}resolve(t){return D.resolve(this.directory,t)}relative(t){return t&&t.indexOf("://")>-1?t:D.relative(this.directory,t)}splitPath(t){return this.splitPathRe.exec(t).slice(1)}toString(){return this.path}}class R{constructor(t,e){const i=t.indexOf("://")>-1;let s=t,n;if(this.Url=void 0,this.href=t,this.protocol="",this.origin="",this.hash="",this.hash="",this.search="",this.base=e,!i&&e!==!1&&typeof e!="string"&&window&&window.location&&(this.base=window.location.href),i||this.base)try{this.base?this.Url=new URL(t,this.base):this.Url=new URL(t),this.href=this.Url.href,this.protocol=this.Url.protocol,this.origin=this.Url.origin,this.origin==="null"&&this.protocol==="file:"&&(this.origin="file://"),this.hash=this.Url.hash,this.search=this.Url.search,s=this.Url.pathname+(this.Url.search?this.Url.search:"")}catch{this.Url=void 0,this.base&&(n=new P(this.base),s=n.resolve(s))}this.Path=new P(s),this.directory=this.Path.directory,this.filename=this.Path.filename,this.extension=this.Path.extension}path(){return this.Path}resolve(t){if(t.indexOf("://")>-1)return t;const i=D.resolve(this.directory,t);return this.origin+i}relative(t){return D.relative(t,this.directory)}toString(){return this.href}}const q=1,L=3,ve=9;class g{constructor(t,e,i){if(this.str="",this.base={},this.spinePos=0,this.range=!1,this.path={},this.start=null,this.end=null,!(this instanceof g))return new g(t,e,i);typeof e=="string"?this.base=this.parseComponent(e):typeof e=="object"&&e.steps&&(this.base=e);const s=this.checkType(t);if(s==="string")return this.str=t,_(this,this.parse(t));if(s==="range")return _(this,this.fromRange(t,this.base,i));if(s==="node")return _(this,this.fromNode(t,this.base,i));if(s==="EpubCFI"&&t.path)return t;if(t)throw new TypeError("not a valid argument for EpubCFI");return this}checkType(t){return this.isCfiString(t)?"string":t&&typeof t=="object"&&(jt(t)==="Range"||typeof t.startContainer<"u")?"range":t&&typeof t=="object"&&typeof t.nodeType<"u"?"node":t&&typeof t=="object"&&t instanceof g?"EpubCFI":!1}parse(t){const e={spinePos:-1,range:!1,base:{},path:{},start:null,end:null};if(typeof t!="string")return{spinePos:-1};t.indexOf("epubcfi(")===0&&t[t.length-1]===")"&&(t=t.slice(8,t.length-1));const i=this.getChapterComponent(t);if(!i)return{spinePos:-1};e.base=this.parseComponent(i);const s=this.getPathComponent(t);e.path=this.parseComponent(s);const n=this.getRange(t);return n&&(e.range=!0,e.start=this.parseComponent(n[0]),e.end=this.parseComponent(n[1])),e.base.steps.length<2?{spinePos:-1}:(e.spinePos=e.base.steps[1].index,e)}parseComponent(t){const e={steps:[],terminal:{offset:null,assertion:null}},i=t.split(":"),s=i[0].split("/");let n;return i.length>1&&(n=i[1],e.terminal=this.parseTerminal(n)),s[0]===""&&s.shift(),e.steps=s.map(r=>this.parseStep(r)).filter(r=>r!==void 0),e}parseStep(t){let e,i,s;const n=t.match(/\[(.*)\]/);n&&n[1]&&(s=n[1]);const r=parseInt(t);if(!isNaN(r))return r%2===0?(e="element",i=r/2-1):(e="text",i=(r-1)/2),{type:e,index:i,id:s||null,tagName:""}}parseTerminal(t){let e,i=null;const s=t.match(/\[(.*)\]/);return s&&s[1]?(e=parseInt(t.split("[")[0]),i=s[1]):e=parseInt(t),x(e)||(e=null),{offset:e,assertion:i}}getChapterComponent(t){return t.split("!")[0]}getPathComponent(t){const e=t.split("!");if(e[1])return e[1].split(",")[0]}getRange(t){const e=t.split(",");return e.length===3?[e[1],e[2]]:!1}getCharecterOffsetComponent(t){return t.split(":")[1]||""}joinSteps(t){return t?t.map(function(e){let i="";return e.type==="element"&&(i+=(e.index+1)*2),e.type==="text"&&(i+=1+2*e.index),e.id&&(i+="["+e.id+"]"),i}).join("/"):""}segmentString(t){let e="/";return e+=this.joinSteps(t.steps),t.terminal&&t.terminal.offset!=null&&(e+=":"+t.terminal.offset),t.terminal&&t.terminal.assertion!=null&&(e+="["+t.terminal.assertion+"]"),e}toString(){let t="epubcfi(";return t+=this.segmentString(this.base),t+="!",t+=this.segmentString(this.path),this.range&&this.start&&(t+=",",t+=this.segmentString(this.start)),this.range&&this.end&&(t+=",",t+=this.segmentString(this.end)),t+=")",t}compare(t,e){let i,s,n,r;if(typeof t=="string"&&(t=new g(t)),typeof e=="string"&&(e=new g(e)),t.spinePos>e.spinePos)return 1;if(t.spinePos<e.spinePos)return-1;t.range?(i=t.path.steps.concat(t.start.steps),n=t.start.terminal):(i=t.path.steps,n=t.path.terminal),e.range?(s=e.path.steps.concat(e.start.steps),r=e.start.terminal):(s=e.path.steps,r=e.path.terminal);for(let o=0;o<i.length;o++){if(!i[o])return-1;if(!s[o]||i[o].index>s[o].index)return 1;if(i[o].index<s[o].index)return-1}if(i.length<s.length)return-1;if(n.offset!=null&&r.offset!=null){if(n.offset>r.offset)return 1;if(n.offset<r.offset)return-1}return 0}step(t){const e=t.nodeType===L?"text":"element";return{id:t.id,tagName:t.tagName,type:e,index:this.position(t)}}filteredStep(t,e){const i=this.filter(t,e);if(!i)return;const s=i.nodeType===L?"text":"element";return{id:i.id,tagName:i.tagName,type:s,index:this.filteredPosition(i,e)}}pathTo(t,e,i){const s={steps:[],terminal:{offset:null,assertion:null}};let n=t,r;for(;n&&n.parentNode&&n.parentNode.nodeType!=ve;)i?r=this.filteredStep(n,i):r=this.step(n),r&&s.steps.unshift(r),n=n.parentNode;return e!=null&&e>=0&&(s.terminal.offset=e,s.steps.length>0&&s.steps[s.steps.length-1].type!="text"&&s.steps.push({type:"text",index:0,id:null,tagName:""})),s}equalStep(t,e){return!t||!e?!1:t.index===e.index&&t.id===e.id&&t.type===e.type}fromRange(t,e,i){const s={range:!1,base:{},path:{},start:null,end:null,spinePos:0},n=t.startContainer,r=t.endContainer;let o=t.startOffset,h=t.endOffset,a=!1;if(i&&(a=n.ownerDocument.querySelector("."+i)!=null),typeof e=="string"?(s.base=this.parseComponent(e),s.spinePos=s.base.steps[1].index):typeof e=="object"&&(s.base=e),t.collapsed)a&&(o=this.patchOffset(n,o,i)),s.path=this.pathTo(n,o,i);else{s.range=!0,a&&(o=this.patchOffset(n,o,i)),s.start=this.pathTo(n,o,i),a&&(h=this.patchOffset(r,h,i)),s.end=this.pathTo(r,h,i),s.path={steps:[],terminal:{offset:null,assertion:null}};const c=s.start.steps.length;let d;for(d=0;d<c&&this.equalStep(s.start.steps[d],s.end.steps[d]);d++)d===c-1?s.start.terminal===s.end.terminal&&(s.path.steps.push(s.start.steps[d]),s.range=!1):s.path.steps.push(s.start.steps[d]);s.start.steps=s.start.steps.slice(s.path.steps.length),s.end.steps=s.end.steps.slice(s.path.steps.length)}return s}fromNode(t,e,i){const s={range:!1,base:{},path:{},start:null,end:null,spinePos:0};return typeof e=="string"?(s.base=this.parseComponent(e),s.spinePos=s.base.steps[1].index):typeof e=="object"&&(s.base=e),s.path=this.pathTo(t,null,i),s}filter(t,e){let i,s,n,r,o,h=!1;return t.nodeType===L?(h=!0,n=t.parentNode,i=t.parentNode.classList.contains(e)):(h=!1,i=t.classList.contains(e)),i&&h?(r=n.previousSibling,o=n.nextSibling,r&&r.nodeType===L?s=r:o&&o.nodeType===L&&(s=o),s||t):i&&!h?!1:t}patchOffset(t,e,i){if(t.nodeType!=L)throw new Error("Anchor must be a text node");let s=t,n=e;for(t.parentNode.classList.contains(i)&&(s=t.parentNode);s.previousSibling;){if(s.previousSibling.nodeType===q)if(s.previousSibling.classList.contains(i))n+=(s.previousSibling.textContent??"").length;else break;else n+=(s.previousSibling.textContent??"").length;s=s.previousSibling}return n}normalizedMap(t,e,i){const s={};let n=-1,r;const o=t.length;let h,a;for(r=0;r<o;r++)h=t[r].nodeType,h===q&&t[r].classList.contains(i)&&(h=L),r>0&&h===L&&a===L?s[r]=n:e===h&&(n=n+1,s[r]=n),a=h;return s}position(t){let e,i;return t.nodeType===q?(e=t.parentNode.children,e||(e=bt(t.parentNode)),i=Array.from(e).indexOf(t)):(e=this.textNodes(t.parentNode),i=e.indexOf(t)),i}filteredPosition(t,e){let i,s;t.nodeType===q?(i=t.parentNode.children,s=this.normalizedMap(i,q,e)):(i=t.parentNode.childNodes,t.parentNode.classList.contains(e)&&(t=t.parentNode,i=t.parentNode.childNodes),s=this.normalizedMap(i,L,e));const n=Array.from(i).indexOf(t);return s[n]}stepsToXpath(t){const e=[".","*"];return t.forEach(function(i){const s=i.index+1;i.id?e.push("*[position()="+s+" and @id='"+i.id+"']"):i.type==="text"?e.push("text()["+s+"]"):e.push("*["+s+"]")}),e.join("/")}stepsToQuerySelector(t){const e=["html"];return t.forEach(function(i){const s=i.index+1;i.id?e.push("#"+i.id):i.type==="text"||e.push("*:nth-child("+s+")")}),e.join(">")}textNodes(t,e){return Array.from(t.childNodes).filter(function(i){return i.nodeType===L?!0:!!(e&&i.classList.contains(e))})}walkToNode(t,e,i){const s=e||document;let n=s.documentElement,r,o;const h=t.length;let a;for(a=0;a<h&&(o=t[a],o.type==="element"?o.id?n=s.getElementById(o.id):(r=n.children||bt(n),n=r[o.index]):o.type==="text"&&(n=this.textNodes(n,i)[o.index]),!!n);a++);return n}findNode(t,e,i){const s=e||document;let n,r;return!i&&typeof s.evaluate<"u"?(r=this.stepsToXpath(t),n=s.evaluate(r,s,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue??void 0):i?n=this.walkToNode(t,s,i):n=this.walkToNode(t,s),n}fixMiss(t,e,i,s){let n=this.findNode(t.slice(0,-1),i,s);if(!n)return{container:(i??document).documentElement,offset:0};const r=n.childNodes,o=this.normalizedMap(r,L,s);let h,a;const c=t[t.length-1].index;for(const d in o)if(o.hasOwnProperty(d)&&o[d]===c)if(h=r[d],a=(h.textContent??"").length,e>a)e=e-a;else{h.nodeType===q?n=h.childNodes[0]??h:n=h;break}return{container:n,offset:e}}toRange(t,e){const i=t||document;let s,n,r,o,h;const a=this;let c,d;const u=e?i.querySelector("."+e)!=null:!1;let p;if(typeof i.createRange<"u"?s=i.createRange():s=new Xt,a.range?(n=a.start,c=a.path.steps.concat(n.steps),o=this.findNode(c,i,u?e:void 0),r=a.end,d=a.path.steps.concat(r.steps),h=this.findNode(d,i,u?e:void 0)):(n=a.path,c=a.path.steps,o=this.findNode(a.path.steps,i,u?e:void 0)),o)try{n.terminal.offset!=null?s.setStart(o,n.terminal.offset):s.setStart(o,0)}catch{p=this.fixMiss(c,n.terminal.offset,i,u?e:void 0),s.setStart(p.container,p.offset)}else return console.log("No startContainer found for",this.toString()),null;if(h)try{r.terminal.offset!=null?s.setEnd(h,r.terminal.offset):s.setEnd(h,0)}catch{p=this.fixMiss(d,a.end.terminal.offset,i,u?e:void 0),s.setEnd(p.container,p.offset)}return s}isCfiString(t){return typeof t=="string"&&t.indexOf("epubcfi(")===0&&t[t.length-1]===")"}generateChapterComponent(t,e,i){const s=parseInt(e);let r="/"+(t+1)*2+"/";return r+=(s+1)*2,i&&(r+="["+i+"]"),r}collapse(t){this.range&&(this.range=!1,t?(this.path.steps=this.path.steps.concat(this.start.steps),this.path.terminal=this.start.terminal):(this.path.steps=this.path.steps.concat(this.end.steps),this.path.terminal=this.end.terminal))}}class N{constructor(t){this.context=t||this,this.hooks=[]}register(...t){for(let e=0;e<t.length;++e)if(typeof t[e]=="function")this.hooks.push(t[e]);else for(let i=0;i<t[e].length;++i)this.hooks.push(t[e][i])}deregister(t){let e;for(let i=0;i<this.hooks.length;i++)if(e=this.hooks[i],e===t){this.hooks.splice(i,1);break}}trigger(...t){const e=this.context,i=[];return this.hooks.forEach(function(s){let n;try{n=s.call(e,...t)}catch(r){console.log(r)}n&&typeof n.then=="function"&&i.push(n)}),Promise.all(i)}list(){return this.hooks}clear(){return this.hooks=[]}}function Yt(l,t){let e,i=t.url;const s=i.indexOf("://")>-1;if(!l)return;const n=w(l,"head");e=w(n,"base"),e||(e=l.createElement("base"),n.insertBefore(e,n.firstChild)),!s&&window&&window.location&&(i=window.location.origin+i),e.setAttribute("href",i)}function ye(l,t){let e;const i=t.canonical;if(!l)return;const s=w(l,"head");e=w(s,"link[rel='canonical']"),e?e.setAttribute("href",i):(e=l.createElement("link"),e.setAttribute("rel","canonical"),e.setAttribute("href",i),s.appendChild(e))}function we(l,t){let e;const i=t.idref;if(!l)return;const s=w(l,"head");e=w(s,"link[property='dc.identifier']"),e?e.setAttribute("content",i):(e=l.createElement("meta"),e.setAttribute("name","dc.identifier"),e.setAttribute("content",i),s.appendChild(e))}function be(l,t){const e=l.querySelectorAll("a[href]");if(!e.length)return;const i=w(l.ownerDocument,"base"),s=i?i.getAttribute("href")??void 0:void 0,n=function(r){const o=r.getAttribute("href")??"";if(o.indexOf("mailto:")===0)return;if(o.indexOf("://")>-1)r.setAttribute("target","_blank");else{let a;try{a=new R(o,s)}catch{}r.onclick=function(){return a&&a.hash?t(a.Path.path+a.hash):t(a?a.Path.path:o),!1}}};for(let r=0;r<e.length;r++)n(e[r])}function At(l,t,e){return t.forEach(function(i,s){if(i&&e[s]){try{const n=decodeURIComponent(i);if(n!==i){const r=n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");l=l.replace(new RegExp(r,"g"),e[s])}}catch{}i=i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),l=l.replace(new RegExp(i,"g"),e[s])}}),l}function $(l,t,e,i){const s=typeof window<"u"?window.URL:!1,n=s?"blob":"arraybuffer",r=new v,o=new XMLHttpRequest;let h;e&&(o.withCredentials=!0),o.onreadystatechange=c,o.onerror=a,o.open("GET",l,!0);for(h in i)o.setRequestHeader(h,i[h]);t=="json"&&o.setRequestHeader("Accept","application/json"),t||(t=new P(l).extension),t=="blob"&&(o.responseType=n),G(t)&&o.overrideMimeType("text/xml"),t=="binary"&&(o.responseType="arraybuffer"),o.send();function a(d){r.reject(d)}function c(){if(o.readyState===XMLHttpRequest.DONE){let d=!1;if((o.responseType===""||o.responseType==="document")&&(d=o.responseXML),o.status===200||o.status===0||d){let u;if(!o.response&&!d)return r.reject({status:o.status,message:"Empty Response",stack:new Error().stack}),r.promise;if(o.status===403)return r.reject({status:o.status,response:o.response,message:"Forbidden",stack:new Error().stack}),r.promise;d?u=o.responseXML:G(t)?u=A(o.response,"text/xml"):t=="xhtml"?u=A(o.response,"application/xhtml+xml"):t=="html"||t=="htm"?u=A(o.response,"text/html"):t=="json"?u=JSON.parse(o.response):t=="blob"?s?u=o.response:u=new Blob([o.response]):u=o.response,r.resolve(u)}else r.reject({status:o.status,message:o.response,stack:new Error().stack})}}return r.promise}class Gt{constructor(t,e){this.idref=t.idref,this.linear=t.linear==="yes",this.properties=t.properties,this.index=t.index,this.href=t.href,this.url=t.url,this.canonical=t.canonical,this.next=t.next,this.prev=t.prev,this.cfiBase=t.cfiBase,e?this.hooks=e:(this.hooks={},this.hooks.serialize=new N(this),this.hooks.content=new N(this)),this.document=void 0,this.contents=void 0,this.output=void 0}load(t){const e=t||this.request||$,i=new v,s=i.promise;return this.contents?i.resolve(this.contents):e(this.url).then(n=>(this.document=n,this.contents=n.documentElement,this.hooks.content.trigger(this.document,this))).then(()=>{i.resolve(this.contents)}).catch(function(n){i.reject(n)}),s}base(){return Yt(this.document,this)}render(t){const e=new v,i=e.promise;return this.load(t).then(s=>{const n=new XMLSerializer;return this.output=n.serializeToString(s),this.output}).then(()=>this.hooks.serialize.trigger(this.output,this)).then(()=>{e.resolve(this.output)}).catch(function(s){e.reject(s)}),i}find(t){const e=this,i=[],s=t.toLowerCase(),n=function(r){const o=r.textContent.toLowerCase();let h,a,c,d=-1,u;const p=150;for(;c!=-1;)c=o.indexOf(s,d+1),c!=-1&&(h=e.document.createRange(),h.setStart(r,c),h.setEnd(r,c+s.length),a=e.cfiFromRange(h),r.textContent.length<p?u=r.textContent:(u=r.textContent.substring(c-p/2,c+p/2),u="..."+u+"..."),i.push({cfi:a,excerpt:u})),d=c};return ht(e.document,function(r){n(r)}),i}search(t,e=5){const i=[],n=this,r=t.toLowerCase(),o=function(d){const m=d.reduce((y,b)=>y+(b.textContent??""),"").toLowerCase().indexOf(r);if(m!=-1){const b=m+r.length;let E=0,T=0;if(m<d[0].length){for(;E<d.length-1&&(T+=d[E].length,!(b<=T));)E+=1;const S=d[0],C=d[E],O=n.document.createRange();O.setStart(S,m);const Z=d.slice(0,E).reduce((mt,vt)=>mt+(vt.textContent??"").length,0);O.setEnd(C,Z>b?b:b-Z);const M=n.cfiFromRange(O);let z=d.slice(0,E+1).reduce((mt,vt)=>mt+(vt.textContent??""),"");z.length>150&&(z=z.substring(m-150/2,m+150/2),z="..."+z+"..."),i.push({cfi:M,excerpt:z})}}},h=document.createTreeWalker(n.document,NodeFilter.SHOW_TEXT,null);let a,c=[];for(;a=h.nextNode();)c.push(a),c.length==e&&(o(c.slice(0,e)),c=c.slice(1,e));return c.length>0&&o(c),i}reconcileLayoutSettings(t){const e={layout:t.layout,spread:t.spread,orientation:t.orientation};return this.properties.forEach(function(i){const s=i.replace("rendition:",""),n=s.indexOf("-");let r,o;n!=-1&&(r=s.slice(0,n),o=s.slice(n+1),e[r]=o)}),e}cfiFromRange(t){return new g(t,this.cfiBase).toString()}cfiFromElement(t){return new g(t,this.cfiBase).toString()}unload(){this.document=void 0,this.contents=void 0,this.output=void 0}destroy(){this.unload(),this.hooks.serialize.clear(),this.hooks.content.clear(),this.hooks=void 0,this.idref=void 0,this.linear=void 0,this.properties=void 0,this.index=void 0,this.href=void 0,this.url=void 0,this.next=void 0,this.prev=void 0,this.cfiBase=void 0}}class $t{constructor(){this.spineItems=[],this.spineByHref={},this.spineById={},this.hooks={},this.hooks.serialize=new N,this.hooks.content=new N,this.hooks.content.register(Yt),this.hooks.content.register(ye),this.hooks.content.register(we),this.epubcfi=new g,this.loaded=!1,this.items=[],this.manifest={},this.spineNodeIndex=0,this.baseUrl="",this.length=0}unpack(t,e,i){this.items=t.spine,this.manifest=t.manifest,this.spineNodeIndex=t.spineNodeIndex,this.baseUrl=t.baseUrl||t.basePath||"",this.length=this.items.length,this.items.forEach((s,n)=>{const r=this.manifest[s.idref];s.index=n,s.cfiBase=this.epubcfi.generateChapterComponent(this.spineNodeIndex,s.index,s.id),s.href&&(s.url=e(s.href,!0),s.canonical=i(s.href)),r&&(s.href=r.href,s.url=e(s.href,!0),s.canonical=i(s.href),r.properties.length&&s.properties.push(...r.properties)),s.linear==="yes"?(s.prev=()=>{let h=s.index;for(;h>0;){const a=this.get(h-1);if(a&&a.linear)return a;h-=1}},s.next=()=>{let h=s.index;for(;h<this.spineItems.length-1;){const a=this.get(h+1);if(a&&a.linear)return a;h+=1}}):(s.prev=function(){},s.next=function(){});const o=new Gt(s,this.hooks);this.append(o)}),this.loaded=!0}get(t){let e=0;if(typeof t>"u")for(;e<this.spineItems.length;){const i=this.spineItems[e];if(i&&i.linear)break;e+=1}else this.epubcfi.isCfiString(t)?e=new g(t).spinePos:typeof t=="number"||isNaN(Number(t))===!1?e=Number(t):typeof t=="string"&&t.indexOf("#")===0?e=this.spineById[t.substring(1)]??-1:typeof t=="string"&&(t=t.split("#")[0],e=this.spineByHref[t]??this.spineByHref[encodeURI(t)]??-1);return this.spineItems[e]??null}append(t){const e=this.spineItems.length;return t.index=e,this.spineItems.push(t),this.spineByHref[decodeURI(t.href)]=e,this.spineByHref[encodeURI(t.href)]=e,this.spineByHref[t.href]=e,this.spineById[t.idref]=e,e}prepend(t){return this.spineByHref[t.href]=0,this.spineById[t.idref]=0,this.spineItems.forEach(function(e,i){e.index=i}),0}remove(t){const e=this.spineItems.indexOf(t);if(e>-1)return delete this.spineByHref[t.href],delete this.spineById[t.idref],this.spineItems.splice(e,1)}each(t){return this.spineItems.forEach(t)}first(){let t=0;do{const e=this.get(t);if(e&&e.linear)return e;t+=1}while(t<this.spineItems.length)}last(){let t=this.spineItems.length-1;do{const e=this.get(t);if(e&&e.linear)return e;t-=1}while(t>=0)}destroy(){this.each(t=>t.destroy()),this.spineItems=void 0,this.spineByHref=void 0,this.spineById=void 0,this.hooks.serialize.clear(),this.hooks.content.clear(),this.hooks=void 0,this.epubcfi=void 0,this.loaded=!1,this.items=void 0,this.manifest=void 0,this.spineNodeIndex=void 0,this.baseUrl=void 0,this.length=void 0}}class Lt{constructor(t){this._q=[],this.context=t,this.tick=_t,this.running=!1,this.paused=!1}enqueue(...t){let e,i,s;const[n,...r]=t;if(!n)throw new Error("No Task Provided");return typeof n=="function"?(e=new v,i=e.promise,s={task:n,args:r,deferred:e,promise:i}):s={promise:n},this._q.push(s),this.paused==!1&&!this.running&&this.run(),s.promise}dequeue(){let t,e,i;if(this._q.length&&!this.paused){if(t=this._q.shift(),e=t.task,e)return i=e.call(this.context,...t.args),i&&typeof i.then=="function"?i.then((...s)=>{t.deferred.resolve(...s)},(...s)=>{t.deferred.reject(...s)}):(t.deferred.resolve(i),t.promise);if(t.promise)return t.promise}else return t=new v,t.resolve(),t.promise}dump(){for(;this._q.length;)this.dequeue()}run(){return this.running||(this.running=!0,this.defered=new v),this.tick(()=>{this._q.length?this.dequeue().then(()=>{this.run()}):(this.defered.resolve(),this.running=void 0)}),this.paused==!0&&(this.paused=!1),this.defered.promise}flush(){if(this.running)return this.running;if(this._q.length)return this.running=this.dequeue().then(()=>(this.running=void 0,this.flush())),this.running}clear(){this._q=[]}length(){return this._q.length}pause(){this.paused=!0}stop(){this._q=[],this.running=!1,this.paused=!0}}const ut="0.3",Q=["keydown","keyup","keypress","mouseup","mousedown","mousemove","click","dblclick","touchend","touchstart","touchmove"],f={BOOK:{OPEN_FAILED:"openFailed"},CONTENTS:{EXPAND:"expand",RESIZE:"resize",SELECTED:"selected",SELECTED_RANGE:"selectedRange",LINK_CLICKED:"linkClicked"},LOCATIONS:{CHANGED:"changed"},MANAGERS:{RESIZE:"resize",RESIZED:"resized",ORIENTATION_CHANGE:"orientationchange",ADDED:"added",SCROLL:"scroll",SCROLLED:"scrolled",REMOVED:"removed"},VIEWS:{AXIS:"axis",WRITING_MODE:"writingMode",LOAD_ERROR:"loaderror",RENDERED:"rendered",RESIZED:"resized",DISPLAYED:"displayed",SHOWN:"shown",HIDDEN:"hidden",MARK_CLICKED:"markClicked"},RENDITION:{STARTED:"started",ATTACHED:"attached",DISPLAYED:"displayed",DISPLAY_ERROR:"displayerror",RENDERED:"rendered",REMOVED:"removed",RESIZED:"resized",ORIENTATION_CHANGE:"orientationchange",LOCATION_CHANGED:"locationChanged",RELOCATED:"relocated",MARK_CLICKED:"markClicked",SELECTED:"selected",LAYOUT:"layout"},LAYOUT:{UPDATED:"updated"},ANNOTATION:{ATTACH:"attach",DETACH:"detach"}};class kt{constructor(t,e,i){this.spine=t,this.request=e,this.pause=i||100,this.q=new Lt(this),this.epubcfi=new g,this._locations=[],this._locationsWords=[],this.total=0,this.break=150,this._current=0,this._wordCounter=0,this._currentCfi="",this.processingTimeout=void 0}generate(t){return t&&(this.break=t),this.q.pause(),this.spine.each(e=>{e.linear&&this.q.enqueue(i=>this.process(i),e)}),this.q.run().then(()=>(this.total=this._locations.length-1,this._currentCfi&&(this.currentLocation=this._currentCfi),this._locations))}createRange(){return{startContainer:void 0,startOffset:void 0,endContainer:void 0,endOffset:void 0}}process(t){return t.load(this.request).then(e=>{const i=new v,s=this.parse(e,t.cfiBase);return this._locations=this._locations.concat(s),t.unload(),this.processingTimeout=setTimeout(()=>i.resolve(s),this.pause),i.promise})}parse(t,e,i){const s=[];let n;const r=t.ownerDocument,o=w(r,"body");let h=0,a;const c=i||this.break;if(ht(o,u=>{const p=u.length;let m,y=0;if(h===0&&n===void 0&&(n=this.createRange(),n.startContainer=u,n.startOffset=0),(u.textContent??"").trim().length===0)return a=u,!1;for(m=c-h,m>p&&(h+=p,y=p);y<p;)if(m=c-h,h===0&&(y+=1,n=this.createRange(),n.startContainer=u,n.startOffset=y),y+m>=p)h+=p-y,y=p;else{y+=m,n.endContainer=u,n.endOffset=y;const b=new g(n,e).toString();s.push(b),h=0}return a=u,!1}),n&&n.startContainer&&a){n.endContainer=a,n.endOffset=a.length;const u=new g(n,e).toString();s.push(u),h=0}return s}generateFromWords(t,e,i){const s=t?new g(t):void 0;return this.q.pause(),this._locationsWords=[],this._wordCounter=0,this.spine.each(n=>{n.linear&&(s?n.index>=s.spinePos&&this.q.enqueue((r,o,h,a)=>this.processWords(r,o,h,a),n,e,s,i):this.q.enqueue((r,o,h,a)=>this.processWords(r,o,h,a),n,e,s,i))}),this.q.run().then(()=>(this._currentCfi&&(this.currentLocation=this._currentCfi),this._locationsWords))}processWords(t,e,i,s){return s&&this._locationsWords.length>=s?Promise.resolve([]):t.load(this.request).then(n=>{const r=new v,o=this.parseWords(n,t,e,i),h=s-this._locationsWords.length;return this._locationsWords=this._locationsWords.concat(o.length>=s?o.slice(0,h):o),t.unload(),this.processingTimeout=setTimeout(()=>r.resolve(o),this.pause),r.promise})}countWords(t){return t=t.replace(/(^\s*)|(\s*$)/gi,""),t=t.replace(/[ ]{2,}/gi," "),t=t.replace(/\n /,`
2
- `),t.split(" ").length}parseWords(t,e,i,s){const n=e.cfiBase,r=[],o=t.ownerDocument,h=w(o,"body"),a=i;let c=s?s.spinePos!==e.index:!0,d;return s&&e.index===s.spinePos&&(d=s.findNode(s.range?s.path.steps.concat(s.start.steps):s.path.steps,t.ownerDocument)),ht(h,p=>{if(!c)if(p===d)c=!0;else return!1;if((p.textContent??"").length<10&&(p.textContent??"").trim().length===0)return!1;const m=this.countWords(p.textContent??"");let y,b=0;if(m===0)return!1;for(y=a-this._wordCounter,y>m&&(this._wordCounter+=m,b=m);b<m;)if(y=a-this._wordCounter,b+y>=m)this._wordCounter+=m-b,b=m;else{b+=y;const E=new g(p,n);r.push({cfi:E.toString(),wordCount:this._wordCounter}),this._wordCounter=0}return!1}),r}locationFromCfi(t){if(g.prototype.isCfiString(t)&&(t=new g(t)),this._locations.length===0)return-1;const e=V(t,this._locations,this.epubcfi.compare);return e>this.total?this.total:e}percentageFromCfi(t){if(this._locations.length===0)return null;const e=this.locationFromCfi(t);return this.percentageFromLocation(e)}percentageFromLocation(t){return!t||!this.total?0:t/this.total}cfiFromLocation(t){let e=-1;return typeof t!="number"&&(t=parseInt(t)),t>=0&&t<this._locations.length&&(e=this._locations[t]),e}cfiFromPercentage(t){if(t>1&&console.warn("Normalize cfiFromPercentage value to between 0 - 1"),t>=1){const i=new g(this._locations[this.total]);return i.collapse(),i.toString()}const e=Math.ceil(this.total*t);return this.cfiFromLocation(e)}load(t){return typeof t=="string"?this._locations=JSON.parse(t):this._locations=t,this.total=this._locations.length-1,this._locations}save(){return JSON.stringify(this._locations)}getCurrent(){return this._current}setCurrent(t){let e;if(typeof t=="string")this._currentCfi=t;else if(typeof t=="number")this._current=t;else return;this._locations.length!==0&&(typeof t=="string"?(e=this.locationFromCfi(t),this._current=e):e=t,this.emit(f.LOCATIONS.CHANGED,{percentage:this.percentageFromLocation(e)}))}get currentLocation(){return this._current}set currentLocation(t){this.setCurrent(t)}length(){return this._locations.length}destroy(){this.spine=void 0,this.request=void 0,this.pause=void 0,this.q.stop(),this.q=void 0,this.epubcfi=void 0,this._locations=void 0,this.total=void 0,this.break=void 0,this._current=void 0,this.currentLocation=void 0,this._currentCfi=void 0,clearTimeout(this.processingTimeout)}}I(kt.prototype);class xe{constructor(t){this.packagePath="",this.directory="",this.encoding="",t&&this.parse(t)}parse(t){if(!t)throw new Error("Container File Not Found");const e=w(t,"rootfile");if(!e)throw new Error("No RootFile Found");this.packagePath=e.getAttribute("full-path")??"",this.directory=D.dirname(this.packagePath),this.encoding=t.xmlEncoding}destroy(){this.packagePath=void 0,this.directory=void 0,this.encoding=void 0}}class St{constructor(t){this.manifest={},this.navPath="",this.ncxPath="",this.coverPath="",this.spineNodeIndex=0,this.spine=[],this.metadata={},t&&this.parse(t)}parse(t){if(!t)throw new Error("Package File Not Found");const e=w(t,"metadata");if(!e)throw new Error("No Metadata Found");const i=w(t,"manifest");if(!i)throw new Error("No Manifest Found");const s=w(t,"spine");if(!s)throw new Error("No Spine Found");return this.manifest=this.parseManifest(i),this.navPath=this.findNavPath(i),this.ncxPath=this.findNcxPath(i,s),this.coverPath=this.findCoverPath(t),this.spineNodeIndex=Wt(s),this.spine=this.parseSpine(s,this.manifest),this.uniqueIdentifier=this.findUniqueIdentifier(t),this.metadata=this.parseMetadata(e),this.metadata.direction=s.getAttribute("page-progression-direction")??"",{metadata:this.metadata,spine:this.spine,manifest:this.manifest,navPath:this.navPath,ncxPath:this.ncxPath,coverPath:this.coverPath,spineNodeIndex:this.spineNodeIndex}}parseMetadata(t){const e={};return e.title=this.getElementText(t,"title"),e.creator=this.getElementText(t,"creator"),e.description=this.getElementText(t,"description"),e.pubdate=this.getElementText(t,"date"),e.publisher=this.getElementText(t,"publisher"),e.identifier=this.getElementText(t,"identifier"),e.language=this.getElementText(t,"language"),e.rights=this.getElementText(t,"rights"),e.modified_date=this.getPropertyText(t,"dcterms:modified"),e.layout=this.getPropertyText(t,"rendition:layout"),e.orientation=this.getPropertyText(t,"rendition:orientation"),e.flow=this.getPropertyText(t,"rendition:flow"),e.viewport=this.getPropertyText(t,"rendition:viewport"),e.media_active_class=this.getPropertyText(t,"media:active-class"),e.spread=this.getPropertyText(t,"rendition:spread"),e}parseManifest(t){const e={},i=B(t,"item");return Array.from(i).forEach(function(n){const r=n.getAttribute("id")??"",o=n.getAttribute("href")||"",h=n.getAttribute("media-type")||"",a=n.getAttribute("media-overlay")||"",c=n.getAttribute("properties")||"",d=n.getAttribute("fallback")||"";e[r]={href:o,type:h,overlay:a,properties:c.length?c.split(" "):[],fallback:d}}),e}parseSpine(t,e){const i=[],s=B(t,"itemref");return Array.from(s).forEach(function(r,o){const h=r.getAttribute("idref"),a=r.getAttribute("properties")||"",c=a.length?a.split(" "):[],d={id:r.getAttribute("id")??void 0,idref:h,linear:r.getAttribute("linear")||"yes",properties:c,index:o};i.push(d)}),i}findUniqueIdentifier(t){const e=t.documentElement.getAttribute("unique-identifier");if(!e)return"";const i=t.getElementById(e);return i&&i.localName==="identifier"&&i.namespaceURI==="http://purl.org/dc/elements/1.1/"&&i.childNodes.length>0?(i.childNodes[0].nodeValue??"").trim():""}findNavPath(t){const e=j(t,"item",{properties:"nav"});return e&&e.getAttribute("href")||""}findNcxPath(t,e){let i=j(t,"item",{"media-type":"application/x-dtbncx+xml"}),s;return i||(s=e.getAttribute("toc"),s&&(i=t.querySelector(`#${s}`)??void 0)),i&&i.getAttribute("href")||""}findCoverPath(t){const e=w(t,"package");e==null||e.getAttribute("version");const i=j(t,"item",{properties:"cover-image"});if(i)return i.getAttribute("href")??"";const s=j(t,"meta",{name:"cover"});if(s){const n=s.getAttribute("content"),r=t.getElementById(n);return r?r.getAttribute("href")??"":""}else return""}getElementText(t,e){const i=t.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/",e);if(!i||i.length===0)return"";const s=i[0];return s.childNodes.length?s.childNodes[0].nodeValue??"":""}getPropertyText(t,e){const i=j(t,"meta",{property:e});return i&&i.childNodes.length?i.childNodes[0].nodeValue??"":""}load(t){this.metadata=t.metadata;const e=t.readingOrder||t.spine;return this.spine=e.map((i,s)=>(i.index=s,i.linear=i.linear||"yes",i)),t.resources.forEach((i,s)=>{this.manifest[s]=i,i.rel&&i.rel[0]==="cover"&&(this.coverPath=i.href)}),this.spineNodeIndex=0,this.toc=t.toc.map(i=>(i.label=i.title||i.label,i)),{metadata:this.metadata,spine:this.spine,manifest:this.manifest,navPath:this.navPath,ncxPath:this.ncxPath,coverPath:this.coverPath,spineNodeIndex:this.spineNodeIndex,toc:this.toc}}destroy(){this.manifest=void 0,this.navPath=void 0,this.ncxPath=void 0,this.coverPath=void 0,this.spineNodeIndex=void 0,this.spine=void 0,this.metadata=void 0}}class tt{constructor(t){this.toc=[],this.tocByHref={},this.tocById={},this.landmarks=[],this.landmarksByType={},this.length=0,t&&this.parse(t)}parse(t){const e=t.nodeType;let i,s;e&&(i=w(t,"html"),s=w(t,"ncx")),e?i?(this.toc=this.parseNav(t),this.landmarks=this.parseLandmarks(t)):s&&(this.toc=this.parseNcx(t)):this.toc=this.load(t),this.length=0,this.unpack(this.toc)}unpack(t){let e;for(let i=0;i<t.length;i++)e=t[i],e.href&&(this.tocByHref[e.href]=i),e.id&&(this.tocById[e.id]=i),this.length++,e.subitems&&e.subitems.length&&this.unpack(e.subitems)}get(t){let e;return t?(t.indexOf("#")===0?(t=t.substring(1),e=this.tocById[t]):t in this.tocByHref&&(e=this.tocByHref[t]),this.getByIndex(t,e,this.toc)):this.toc}getByIndex(t,e,i){if(i.length===0)return;const s=e!==void 0?i[e]:void 0;if(s&&(t===s.id||t===s.href))return s;{let n;for(let r=0;r<i.length&&(n=this.getByIndex(t,e,i[r].subitems??[]),!n);++r);return n}}landmark(t){if(!t)return this.landmarks;const e=this.landmarksByType[t];return e!==void 0?this.landmarks[e]:void 0}parseNav(t){const e=lt(t,"nav","toc");let i=[];if(!e)return i;const s=F(e,"ol",!0);return s&&(i=this.parseNavList(s)),i}parseNavList(t,e){const i=[];if(!t||!t.children)return i;for(let s=0;s<t.children.length;s++){const n=this.navItem(t.children[s],e);n&&i.push(n)}return i}navItem(t,e){let i=t.getAttribute("id")||void 0;const s=F(t,"a",!0)||F(t,"span",!0);if(!s)return;const n=s.getAttribute("href")||"";i||(i=n);const r=s.textContent||"";let o=[];const h=F(t,"ol",!0);return h&&(o=this.parseNavList(h,i)),{id:i,href:n,label:r,subitems:o,parent:e}}parseLandmarks(t){const e=lt(t,"nav","landmarks"),i=e?Array.from(B(e,"li")):[],s=i.length;let n;const r=[];let o;if(!i||s===0)return r;for(n=0;n<s;++n)o=this.landmarkItem(i[n]),o&&(r.push(o),this.landmarksByType[o.type]=n);return r}landmarkItem(t){const e=F(t,"a",!0);if(!e)return;const i=e.getAttributeNS("http://www.idpf.org/2007/ops","type")||void 0,s=e.getAttribute("href")||"",n=e.textContent||"";return{href:s,label:n,type:i}}parseNcx(t){const e=B(t,"navPoint"),i=e.length;let s;const n={},r=[];let o,h;if(!e||i===0)return r;for(s=0;s<i;++s)o=this.ncxItem(e[s]),n[o.id]=o,o.parent?(h=n[o.parent],h?h.subitems.push(o):r.push(o)):r.push(o);return r}ncxItem(t){const e=t.getAttribute("id")||"",i=w(t,"content"),s=i?i.getAttribute("src")??"":"",n=w(t,"navLabel"),r=n!=null&&n.textContent?n.textContent:"",o=[],h=t.parentNode;let a;return h&&(h.nodeName==="navPoint"||h.nodeName.split(":").slice(-1)[0]==="navPoint")&&(a=h.getAttribute("id")??void 0),{id:e,href:s,label:r,subitems:o,parent:a}}load(t){return t.map(e=>(e.label=e.title,e.subitems=e.children?this.load(e.children):[],e))}forEach(t){return this.toc.forEach(t)}}const Y={application:{ecmascript:["es","ecma"],javascript:"js",ogg:"ogx",pdf:"pdf",postscript:["ps","ai","eps","epsi","epsf","eps2","eps3"],"rdf+xml":"rdf",smil:["smi","smil"],"xhtml+xml":["xhtml","xht"],xml:["xml","xsl","xsd","opf","ncx"],zip:"zip","x-httpd-eruby":"rhtml","x-latex":"latex","x-maker":["frm","maker","frame","fm","fb","book","fbdoc"],"x-object":"o","x-shockwave-flash":["swf","swfl"],"x-silverlight":"scr","epub+zip":"epub","font-tdpfr":"pfr","inkml+xml":["ink","inkml"],json:"json","jsonml+json":"jsonml","mathml+xml":"mathml","metalink+xml":"metalink",mp4:"mp4s","omdoc+xml":"omdoc",oxps:"oxps","vnd.amazon.ebook":"azw",widget:"wgt","x-dtbook+xml":"dtb","x-dtbresource+xml":"res","x-font-bdf":"bdf","x-font-ghostscript":"gsf","x-font-linux-psf":"psf","x-font-otf":"otf","x-font-pcf":"pcf","x-font-snf":"snf","x-font-ttf":["ttf","ttc"],"x-font-type1":["pfa","pfb","pfm","afm"],"x-font-woff":"woff","x-mobipocket-ebook":["prc","mobi"],"x-mspublisher":"pub","x-nzb":"nzb","x-tgif":"obj","xaml+xml":"xaml","xml-dtd":"dtd","xproc+xml":"xpl","xslt+xml":"xslt","internet-property-stream":"acx","x-compress":"z","x-compressed":"tgz","x-gzip":"gz"},audio:{flac:"flac",midi:["mid","midi","kar","rmi"],mpeg:["mpga","mpega","mp2","mp3","m4a","mp2a","m2a","m3a"],mpegurl:"m3u",ogg:["oga","ogg","spx"],"x-aiff":["aif","aiff","aifc"],"x-ms-wma":"wma","x-wav":"wav",adpcm:"adp",mp4:"mp4a",webm:"weba","x-aac":"aac","x-caf":"caf","x-matroska":"mka","x-pn-realaudio-plugin":"rmp",xm:"xm",mid:["mid","rmi"]},image:{gif:"gif",ief:"ief",jpeg:["jpeg","jpg","jpe"],pcx:"pcx",png:"png","svg+xml":["svg","svgz"],tiff:["tiff","tif"],"x-icon":"ico",bmp:"bmp",webp:"webp","x-pict":["pic","pct"],"x-tga":"tga","cis-cod":"cod"},text:{"cache-manifest":["manifest","appcache"],css:"css",csv:"csv",html:["html","htm","shtml","stm"],mathml:"mml",plain:["txt","text","brf","conf","def","list","log","in","bas"],richtext:"rtx","tab-separated-values":"tsv","x-bibtex":"bib"},video:{mpeg:["mpeg","mpg","mpe","m1v","m2v","mp2","mpa","mpv2"],mp4:["mp4","mp4v","mpg4"],quicktime:["qt","mov"],ogg:"ogv","vnd.mpegurl":["mxu","m4u"],"x-flv":"flv","x-la-asf":["lsf","lsx"],"x-mng":"mng","x-ms-asf":["asf","asx","asr"],"x-ms-wm":"wm","x-ms-wmv":"wmv","x-ms-wmx":"wmx","x-ms-wvx":"wvx","x-msvideo":"avi","x-sgi-movie":"movie","x-matroska":["mpv","mkv","mk3d","mks"],"3gpp2":"3g2",h261:"h261",h263:"h263",h264:"h264",jpeg:"jpgv",jpm:["jpm","jpgm"],mj2:["mj2","mjp2"],"vnd.ms-playready.media.pyv":"pyv","vnd.uvvu.mp4":["uvu","uvvu"],"vnd.vivo":"viv",webm:"webm","x-f4v":"f4v","x-m4v":"m4v","x-ms-vob":"vob","x-smv":"smv"}},Ee=(function(){let l,t,e,i;const s={};for(l in Y)if(Y.hasOwnProperty(l)){for(t in Y[l])if(Y[l].hasOwnProperty(t))if(e=Y[l][t],typeof e=="string")s[e]=l+"/"+t;else for(i=0;i<e.length;i++)s[e[i]]=l+"/"+t}return s})(),Se="text/plain";function Ce(l){return l&&Ee[l.split(".").pop().toLowerCase()]||Se}const H={lookup:Ce};class Kt{constructor(t,e){this.settings={replacements:e&&e.replacements||"base64",archive:e&&e.archive,resolver:e&&e.resolver,request:e&&e.request},this.process(t)}process(t){this.manifest=t,this.resources=Object.keys(t).map(function(e){return t[e]}),this.replacementUrls=[],this.html=[],this.assets=[],this.css=[],this.urls=[],this.cssUrls=[],this.split(),this.splitUrls()}split(){this.html=this.resources.filter(function(t){return t.type==="application/xhtml+xml"||t.type==="text/html"}),this.assets=this.resources.filter(function(t){return t.type!=="application/xhtml+xml"&&t.type!=="text/html"}),this.css=this.resources.filter(function(t){return t.type==="text/css"})}splitUrls(){this.urls=this.assets.map(t=>t.href),this.cssUrls=this.css.map(function(t){return t.href})}createUrl(t){const e=new R(t),i=H.lookup(e.filename);return this.settings.archive?this.settings.archive.createUrl(t,{base64:this.settings.replacements==="base64"}):this.settings.replacements==="base64"?this.settings.request(t,"blob").then(s=>Vt(s)).then(s=>wt(s,i)):this.settings.request(t,"blob").then(s=>ot(s,i))}replacements(){if(this.settings.replacements==="none")return new Promise(e=>{e(this.urls)});const t=this.urls.map(e=>{const i=this.settings.resolver(e);return this.createUrl(i).catch(s=>(console.error(s),null))});return Promise.all(t).then(e=>(this.replacementUrls=e.filter(i=>typeof i=="string"),e))}replaceCss(t,e){const i=[];return this.cssUrls.forEach(s=>{const n=this.createCssFile(s).then(r=>{const o=this.urls.indexOf(s);r&&o>-1&&(this.replacementUrls[o]=r)});i.push(n)}),Promise.all(i)}createCssFile(t){let e;if(D.isAbsolute(t))return new Promise(function(r){r()});const i=this.settings.resolver(t);let s;this.settings.archive?s=this.settings.archive.getText(i):s=this.settings.request(i,"text");const n=this.urls.map(r=>{const o=this.settings.resolver(r);return new P(i).relative(o)});return s?s.then(r=>(r=At(r,n,this.replacementUrls),this.settings.replacements==="base64"?e=wt(r,"text/css"):e=ot(r,"text/css"),e),r=>new Promise(function(o){o()})):new Promise(function(r){r()})}relativeTo(t,e){return e=e||this.settings.resolver,this.urls.map(i=>{const s=e(i);return new P(t).relative(s)})}get(t){const e=this.urls.indexOf(t);if(e!==-1)return this.replacementUrls.length?new Promise((i,s)=>{i(this.replacementUrls[e])}):this.createUrl(t)}substitute(t,e){let i;return e?i=this.relativeTo(e):i=this.urls,At(t,i,this.replacementUrls)}destroy(){this.settings=void 0,this.manifest=void 0,this.resources=void 0,this.replacementUrls=void 0,this.html=void 0,this.assets=void 0,this.css=void 0,this.urls=void 0,this.cssUrls=void 0}}class et{constructor(t){this.pages=[],this.locations=[],this.epubcfi=new g,this.firstPage=0,this.lastPage=0,this.totalPages=0,this.toc=void 0,this.ncx=void 0,t&&(this.pageList=this.parse(t)),this.pageList&&this.pageList.length&&this.process(this.pageList)}parse(t){const e=w(t,"html"),i=w(t,"ncx");return e?this.parseNav(t):i?this.parseNcx(t):[]}parseNav(t){const e=lt(t,"nav","page-list"),i=e?Array.from(B(e,"li")):[],s=i.length;let n;const r=[];let o;if(!i||s===0)return r;for(n=0;n<s;++n)o=this.item(i[n]),r.push(o);return r}parseNcx(t){const e=[];let i=0,s,n=0;const r=w(t,"pageList");if(!r)return e;const o=B(r,"pageTarget");if(n=o.length,!o||o.length===0)return e;for(i=0;i<n;++i)s=this.ncxItem(o[i]),e.push(s);return e}ncxItem(t){const e=w(t,"navLabel"),s=w(e,"text").textContent??"",r=w(t,"content").getAttribute("src")??"",o=parseInt(s,10);return{href:r,page:o}}item(t){const e=w(t,"a"),i=e.getAttribute("href")||"",s=e.textContent||"",n=parseInt(s),r=i.indexOf("epubcfi");let o,h,a;return r!=-1?(o=i.split("#"),h=o[0],a=o.length>1?o[1]:void 0,{cfi:a,href:i,packageUrl:h,page:n}):{href:i,page:n}}process(t){t.forEach(e=>{this.pages.push(e.page),e.cfi&&this.locations.push(e.cfi)}),this.firstPage=this.pages[0],this.lastPage=this.pages[this.pages.length-1],this.totalPages=this.lastPage-this.firstPage}pageFromCfi(t){let e=-1;if(this.locations.length===0)return-1;let i=st(t,this.locations,this.epubcfi.compare);return i!=-1?e=this.pages[i]:(i=V(t,this.locations,this.epubcfi.compare),e=i-1>=0?this.pages[i-1]:this.pages[0],e!==void 0||(e=-1)),e}cfiFromPage(t){let e=-1;typeof t!="number"&&(t=parseInt(t));const i=this.pages.indexOf(t);return i!=-1&&i<this.locations.length&&(e=this.locations[i]),e}pageFromPercentage(t){return Math.round(this.totalPages*t)}percentageFromPage(t){const e=(t-this.firstPage)/this.totalPages;return Math.round(e*1e3)/1e3}percentageFromCfi(t){const e=this.pageFromCfi(t);return this.percentageFromPage(e)}destroy(){this.pages=void 0,this.locations=void 0,this.epubcfi=void 0,this.pageList=void 0,this.toc=void 0,this.ncx=void 0}}class Rt{constructor(t){this.settings=t,this.name=t.layout||"reflowable",this._spread=t.spread!=="none",this._minSpreadWidth=t.minSpreadWidth||800,this._evenSpreads=t.evenSpreads||!1,t.flow==="scrolled"||t.flow==="scrolled-continuous"||t.flow==="scrolled-doc"?this._flow="scrolled":this._flow="paginated",this.width=0,this.height=0,this.spreadWidth=0,this.delta=0,this.columnWidth=0,this.gap=0,this.divisor=1,this.props={name:this.name,spread:this._spread,flow:this._flow,width:0,height:0,spreadWidth:0,delta:0,columnWidth:0,gap:0,divisor:1}}flow(t){return typeof t<"u"&&(t==="scrolled"||t==="scrolled-continuous"||t==="scrolled-doc"?this._flow="scrolled":this._flow="paginated",this.update({flow:this._flow})),this._flow}spread(t,e){return t&&(this._spread=t!=="none",this.update({spread:this._spread})),e!==void 0&&e>=0&&(this._minSpreadWidth=e),this._spread}calculate(t,e,i){let s=1,n=i||0,r=t;const o=e,h=Math.floor(r/12);let a,c;this._spread&&r>=this._minSpreadWidth?s=2:s=1,this.name==="reflowable"&&this._flow==="paginated"&&!(i!==void 0&&i>=0)&&(n=h%2===0?h:h-1),this.name==="pre-paginated"&&(n=0),s>1?(a=r/s-n,c=a+n):(a=r,c=r),this.name==="pre-paginated"&&s>1&&(r=a);const d=a*s+n,u=r;this.width=r,this.height=o,this.spreadWidth=d,this.pageWidth=c,this.delta=u,this.columnWidth=a,this.gap=n,this.divisor=s,this.update({width:r,height:o,spreadWidth:d,pageWidth:c,delta:u,columnWidth:a,gap:n,divisor:s})}format(t,e,i){let s;return this.name==="pre-paginated"?s=t.fit(this.columnWidth,this.height,e):this._flow==="paginated"?s=t.columns(this.width,this.height,this.columnWidth,this.gap,this.settings.direction):i&&i==="horizontal"?s=t.size(void 0,this.height):s=t.size(this.width,void 0),s}count(t,e){let i,s;return this.name==="pre-paginated"?(i=1,s=1):this._flow==="paginated"?(e=e||this.delta,i=Math.ceil(t/e),s=i*this.divisor):(e=e||this.height,i=Math.ceil(t/e),s=i),{spreads:i,pages:s}}update(t){const e=t,i=this.props;if(Object.keys(e).forEach(s=>{i[s]===e[s]&&delete e[s]}),Object.keys(e).length>0){const s=_(this.props,t);this.emit(f.LAYOUT.UPDATED,s,t)}}}I(Rt.prototype);class Zt{constructor(t){this.rendition=t,this._themes={default:{rules:{},url:"",serialized:""}},this._overrides={},this._current="default",this._injected=[],this.rendition.hooks.content.register(e=>this.inject(e)),this.rendition.hooks.content.register(e=>this.overrides(e))}register(...t){if(t.length!==0){if(t.length===1&&typeof t[0]=="object")return this.registerThemes(t[0]);if(t.length===1&&typeof t[0]=="string")return this.default(t[0]);if(t.length===2&&typeof t[1]=="string")return this.registerUrl(t[0],t[1]);if(t.length===2&&typeof t[1]=="object")return this.registerRules(t[0],t[1])}}default(t){if(t){if(typeof t=="string")return this.registerUrl("default",t);if(typeof t=="object")return this.registerRules("default",t)}}registerThemes(t){for(const e in t)if(t.hasOwnProperty(e)){const i=t[e];typeof i=="string"?this.registerUrl(e,i):this.registerRules(e,i)}}registerCss(t,e){this._themes[t]={serialized:e},(this._injected[t]||t=="default")&&this.update(t)}registerUrl(t,e){const i=new R(e);this._themes[t]={url:i.toString()},(this._injected[t]||t=="default")&&this.update(t)}registerRules(t,e){this._themes[t]={rules:e},(this._injected[t]||t=="default")&&this.update(t)}select(t){const e=this._current;this._current=t,this.update(t),this.rendition.getContents().forEach(s=>{s.removeClass(e),s.addClass(t)})}update(t){this.rendition.getContents().forEach(i=>{this.add(t,i)})}inject(t){const e=[],i=this._themes;let s;for(const n in i)i.hasOwnProperty(n)&&(n===this._current||n==="default")&&(s=i[n],(s.rules&&Object.keys(s.rules).length>0||s.url&&e.indexOf(s.url)===-1||s.serialized)&&this.add(n,t),this._injected.push(n));this._current!="default"&&t.addClass(this._current)}add(t,e){const i=this._themes[t];!i||!e||(i.url?e.addStylesheet(i.url):i.serialized?(e.addStylesheetCss(i.serialized,t),i.injected=!0):i.rules&&(e.addStylesheetRules(i.rules,t),i.injected=!0))}override(t,e,i){const s=this.rendition.getContents();this._overrides[t]={value:e,priority:i===!0},s.forEach(n=>{n.css(t,this._overrides[t].value,this._overrides[t].priority)})}removeOverride(t){const e=this.rendition.getContents();delete this._overrides[t],e.forEach(i=>{i.css(t)})}overrides(t){const e=this._overrides;for(const i in e)e.hasOwnProperty(i)&&t.css(i,e[i].value,e[i].priority)}fontSize(t){this.override("font-size",t)}font(t){this.override("font-family",t,!0)}destroy(){this.rendition=void 0,this._themes=void 0,this._overrides=void 0,this._current=void 0,this._injected=void 0}}class Jt{constructor(t){this.rendition=t,this.highlights=[],this.underlines=[],this.marks=[],this._annotations={},this._annotationsBySectionIndex={},this.rendition.hooks.render.register(e=>this.inject(e)),this.rendition.hooks.unloaded.register(e=>this.clear(e))}add(t,e,i,s,n,r){const o=encodeURI(e+t),a=new g(e).spinePos,c=new Qt({type:t,cfiRange:e,data:i,sectionIndex:a,cb:s,className:n,styles:r});return this._annotations[o]=c,a in this._annotationsBySectionIndex?this._annotationsBySectionIndex[a].push(o):this._annotationsBySectionIndex[a]=[o],this.rendition.views().forEach(u=>{c.sectionIndex===u.index&&c.attach(u)}),c}remove(t,e){const i=encodeURI(t+e);if(i in this._annotations){const s=this._annotations[i];if(e&&s.type!==e)return;this.rendition.views().forEach(r=>{this._removeFromAnnotationBySectionIndex(s.sectionIndex,i),s.sectionIndex===r.index&&s.detach(r)}),delete this._annotations[i]}}_removeFromAnnotationBySectionIndex(t,e){this._annotationsBySectionIndex[t]=this._annotationsAt(t).filter(i=>i!==e)}_annotationsAt(t){return this._annotationsBySectionIndex[t]??[]}highlight(t,e,i,s,n){return this.add("highlight",t,e,i,s,n)}underline(t,e,i,s,n){return this.add("underline",t,e,i,s,n)}mark(t,e,i){return this.add("mark",t,e,i)}each(t){Object.keys(this._annotations).forEach(e=>{t(this._annotations[e],e)})}inject(t){const e=t.index;e in this._annotationsBySectionIndex&&this._annotationsBySectionIndex[e].forEach(s=>{const n=this._annotations[s];n&&n.attach(t)})}clear(t){const e=t.index;e in this._annotationsBySectionIndex&&this._annotationsBySectionIndex[e].forEach(s=>{const n=this._annotations[s];n&&n.detach(t)})}show(){}hide(){}}class Qt{constructor({type:t,cfiRange:e,data:i,sectionIndex:s,cb:n,className:r,styles:o}){this.type=t,this.cfiRange=e,this.data=i??{},this.sectionIndex=s??0,this.mark=void 0,this.cb=n,this.className=r??"",this.styles=o??{}}update(t){this.data=t}attach(t){const{cfiRange:e,data:i,type:s,mark:n,cb:r,className:o,styles:h}=this;let a;return s==="highlight"?a=t.highlight(e,i,r,o,h):s==="underline"?a=t.underline(e,i,r,o,h):s==="mark"&&(a=t.mark(e,i,r)),this.mark=a,this.emit(f.ANNOTATION.ATTACH,a),a}detach(t){const{cfiRange:e,type:i}=this;let s;return t&&(i==="highlight"?s=t.unhighlight(e):i==="underline"?s=t.ununderline(e):i==="mark"&&(s=t.unmark(e))),this.mark=void 0,this.emit(f.ANNOTATION.DETACH,s),s}text(){}}I(Qt.prototype);class at{constructor(t,e,i,s=!1){this.layout=t,this.horizontal=i==="horizontal",this.direction=e||"ltr",this._dev=s}section(t){const e=this.findRanges(t);return this.rangeListToCfiList(t.section.cfiBase,e)}page(t,e,i,s){const n=t&&t.document?t.document.body:!1;if(!n)return;const r=this.rangePairToCfiPair(e,{start:this.findStart(n,i,s),end:this.findEnd(n,i,s)});if(this._dev===!0){const o=t.document,h=new g(r.start).toRange(o),a=new g(r.end).toRange(o),c=o.defaultView.getSelection(),d=o.createRange();c.removeAllRanges(),d.setStart(h.startContainer,h.startOffset),d.setEnd(a.endContainer,a.endOffset),c.addRange(d)}return r}walk(t,e){const i={acceptNode(o){return o.data.trim().length>0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}},s=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,i);let n,r;for(;(n=s.nextNode())&&(r=e(n),!r););return r}findRanges(t){const e=[],i=t.contents.scrollWidth(),n=Math.ceil(i/this.layout.spreadWidth)*this.layout.divisor,r=this.layout.columnWidth,o=this.layout.gap;let h,a;for(let c=0;c<n;c++)h=(r+o)*c,a=r*(c+1)+o*c,e.push({start:this.findStart(t.document.body,h,a),end:this.findEnd(t.document.body,h,a)});return e}findStart(t,e,i){const s=[t];let n,r,o=t;for(;s.length;)if(n=s.shift(),r=this.walk(n,h=>{let a,c,d,u;const p=yt(h);if(this.horizontal&&this.direction==="ltr"){if(a=this.horizontal?p.left:p.top,c=this.horizontal?p.right:p.bottom,a>=e&&a<=i)return h;if(c>e)return h;o=h,s.push(h)}else if(this.horizontal&&this.direction==="rtl"){if(a=p.left,c=p.right,c<=i&&c>=e)return h;if(a<i)return h;o=h,s.push(h)}else{if(d=p.top,u=p.bottom,d>=e&&d<=i)return h;if(u>e)return h;o=h,s.push(h)}}),r)return this.findTextStartRange(r,e,i);return this.findTextStartRange(o,e,i)}findEnd(t,e,i){const s=[t];let n,r=t,o;for(;s.length;)if(n=s.shift(),o=this.walk(n,h=>{let a,c,d,u;const p=yt(h);if(this.horizontal&&this.direction==="ltr"){if(a=Math.round(p.left),c=Math.round(p.right),a>i&&r)return r;if(c>i)return h;r=h,s.push(h)}else if(this.horizontal&&this.direction==="rtl"){if(a=Math.round(this.horizontal?p.left:p.top),c=Math.round(this.horizontal?p.right:p.bottom),c<e&&r)return r;if(a<e)return h;r=h,s.push(h)}else{if(d=Math.round(p.top),u=Math.round(p.bottom),d>i&&r)return r;if(u>i)return h;r=h,s.push(h)}}),o)return this.findTextEndRange(o,e,i);return this.findTextEndRange(r,e,i)}findTextStartRange(t,e,i){const s=this.splitTextNodeIntoRanges(t);let n,r,o,h,a;for(let c=0;c<s.length;c++)if(n=s[c],r=n.getBoundingClientRect(),this.horizontal&&this.direction==="ltr"){if(o=r.left,o>=e)return n}else if(this.horizontal&&this.direction==="rtl"){if(a=r.right,a<=i)return n}else if(h=r.top,h>=e)return n;return s[0]}findTextEndRange(t,e,i){const s=this.splitTextNodeIntoRanges(t);let n,r,o,h,a,c,d;for(let u=0;u<s.length;u++){if(r=s[u],o=r.getBoundingClientRect(),this.horizontal&&this.direction==="ltr"){if(h=o.left,a=o.right,h>i&&n)return n;if(a>i)return r}else if(this.horizontal&&this.direction==="rtl"){if(h=o.left,a=o.right,a<e&&n)return n;if(h<e)return r}else{if(c=o.top,d=o.bottom,c>i&&n)return n;if(d>i)return r}n=r}return s[s.length-1]}splitTextNodeIntoRanges(t,e){const i=[],n=(t.textContent||"").trim();let r;const o=t.ownerDocument,h=e||" ";let a=n.indexOf(h);if(a===-1||t.nodeType!=Node.TEXT_NODE)return r=o.createRange(),r.selectNodeContents(t),[r];for(r=o.createRange(),r.setStart(t,0),r.setEnd(t,a),i.push(r),r=null;a!=-1;)a=n.indexOf(h,a+1),a>0&&(r&&(r.setEnd(t,a),i.push(r)),r=o.createRange(),r.setStart(t,a+1));return r&&(r.setEnd(t,n.length),i.push(r)),i}rangePairToCfiPair(t,e){const i=e.start,s=e.end;i.collapse(!0),s.collapse(!1);const n=new g(i,t).toString(),r=new g(s,t).toString();return{start:n,end:r}}rangeListToCfiList(t,e){const i=[];let s;for(let n=0;n<e.length;n++)s=this.rangePairToCfiPair(t,e[n]),i.push(s);return i}axis(t){return t&&(this.horizontal=t==="horizontal"),this.horizontal}}const te=typeof navigator<"u",_e=te&&/Chrome/.test(navigator.userAgent),It=te&&!_e&&/AppleWebKit/.test(navigator.userAgent),Te=1;class ft{constructor(t,e,i,s){this.epubcfi=new g,this.document=t,this.documentElement=this.document.documentElement,this.content=e||this.document.body,this.window=this.document.defaultView,this._size={width:0,height:0},this.sectionIndex=s||0,this.cfiBase=i||"",this._mediaQueryHandlers=[],this.epubReadingSystem("epub.js",ut),this.called=0,this.active=!0,this.listeners()}static get listenedEvents(){return Q}width(t){const e=this.content;return t&&x(t)&&(t=t+"px"),t&&(e.style.width=t),parseInt(this.window.getComputedStyle(e).width)}height(t){const e=this.content;return t&&x(t)&&(t=t+"px"),t&&(e.style.height=t),parseInt(this.window.getComputedStyle(e).height)}contentWidth(t){const e=this.content||this.document.body;return t&&x(t)&&(t=t+"px"),t&&(e.style.width=t),parseInt(this.window.getComputedStyle(e).width)}contentHeight(t){const e=this.content||this.document.body;return t&&x(t)&&(t=t+"px"),t&&(e.style.height=t),parseInt(this.window.getComputedStyle(e).height)}textWidth(){let t;const e=this.document.createRange(),i=this.content||this.document.body,s=nt(i);return e.selectNodeContents(i),t=e.getBoundingClientRect().width,s&&s.width&&(t+=s.width),Math.round(t)}textHeight(){const t=this.document.createRange(),e=this.content||this.document.body;t.selectNodeContents(e);const s=t.getBoundingClientRect().bottom;return Math.round(s)}scrollWidth(){return this.documentElement.scrollWidth}scrollHeight(){return this.documentElement.scrollHeight}overflow(t){return t&&(this.documentElement.style.overflow=t),this.window.getComputedStyle(this.documentElement).overflow}overflowX(t){return t&&(this.documentElement.style.overflowX=t),this.window.getComputedStyle(this.documentElement).overflowX}overflowY(t){return t&&(this.documentElement.style.overflowY=t),this.window.getComputedStyle(this.documentElement).overflowY}css(t,e,i){const s=this.content||this.document.body;return e?s.style.setProperty(t,e,i?"important":""):s.style.removeProperty(t),this.window.getComputedStyle(s)[t]}viewport(t){let e=this.document.querySelector("meta[name='viewport']");const i={width:void 0,height:void 0,scale:void 0,minimum:void 0,maximum:void 0,scalable:void 0},s=[];let n={};if(e&&e.hasAttribute("content")){const r=e.getAttribute("content")??"",o=r.match(/width\s*=\s*([^,]*)/),h=r.match(/height\s*=\s*([^,]*)/),a=r.match(/initial-scale\s*=\s*([^,]*)/),c=r.match(/minimum-scale\s*=\s*([^,]*)/),d=r.match(/maximum-scale\s*=\s*([^,]*)/),u=r.match(/user-scalable\s*=\s*([^,]*)/);o&&o.length&&typeof o[1]<"u"&&(i.width=o[1]),h&&h.length&&typeof h[1]<"u"&&(i.height=h[1]),a&&a.length&&typeof a[1]<"u"&&(i.scale=a[1]),c&&c.length&&typeof c[1]<"u"&&(i.minimum=c[1]),d&&d.length&&typeof d[1]<"u"&&(i.maximum=d[1]),u&&u.length&&typeof u[1]<"u"&&(i.scalable=u[1])}return n=Mt(t||{},i),t&&(n.width&&s.push("width="+n.width),n.height&&s.push("height="+n.height),n.scale&&s.push("initial-scale="+n.scale),n.scalable==="no"?(s.push("minimum-scale="+n.scale),s.push("maximum-scale="+n.scale),s.push("user-scalable="+n.scalable)):(n.scalable&&s.push("user-scalable="+n.scalable),n.minimum&&s.push("minimum-scale="+n.minimum),n.maximum&&s.push("minimum-scale="+n.maximum)),e||(e=this.document.createElement("meta"),e.setAttribute("name","viewport"),this.document.querySelector("head").appendChild(e)),e.setAttribute("content",s.join(", ")),this.window.scrollTo(0,0)),n}expand(){this.emit(f.CONTENTS.EXPAND)}listeners(){this.imageLoadListeners(),this.mediaQueryListeners(),this.addEventListeners(),this.addSelectionListeners(),typeof ResizeObserver>"u"?(this.resizeListeners(),this.visibilityListeners()):this.resizeObservers(),this.linksHandler()}removeListeners(){this.removeEventListeners(),this.removeSelectionListeners(),this._onVisibilityChange&&(document.removeEventListener("visibilitychange",this._onVisibilityChange),this._onVisibilityChange=void 0),this._resizeCheck&&(this.document.removeEventListener("transitionend",this._resizeCheck),this._resizeCheck=void 0);for(const{mql:t,handler:e}of this._mediaQueryHandlers)t.removeEventListener("change",e);this._mediaQueryHandlers=[],this.observer&&this.observer.disconnect(),clearTimeout(this.expanding)}resizeCheck(){const t=this.textWidth(),e=this.textHeight();(t!=this._size.width||e!=this._size.height)&&(this._size={width:t,height:e},this.onResize&&this.onResize(this._size),this.emit(f.CONTENTS.RESIZE,this._size))}resizeListeners(){clearTimeout(this.expanding),requestAnimationFrame(this.resizeCheck.bind(this)),this.expanding=setTimeout(this.resizeListeners.bind(this),350)}visibilityListeners(){this._onVisibilityChange=()=>{document.visibilityState==="visible"&&this.active===!1?(this.active=!0,this.resizeListeners()):(this.active=!1,clearTimeout(this.expanding))},document.addEventListener("visibilitychange",this._onVisibilityChange)}transitionListeners(){const t=this.content;t.style.transitionProperty="font, font-size, font-size-adjust, font-stretch, font-variation-settings, font-weight, width, height",t.style.transitionDuration="0.001ms",t.style.transitionTimingFunction="linear",t.style.transitionDelay="0",this._resizeCheck=this.resizeCheck.bind(this),this.document.addEventListener("transitionend",this._resizeCheck)}mediaQueryListeners(){const t=this.document.styleSheets,e=i=>{i.matches&&!this._expanding&&setTimeout(this.expand.bind(this),1)};for(let i=0;i<t.length;i+=1){let s;try{s=t[i].cssRules}catch{return}if(!s)return;for(let n=0;n<s.length;n+=1)if(s[n].media){const r=this.window.matchMedia(s[n].media.mediaText);r.addEventListener("change",e),this._mediaQueryHandlers.push({mql:r,handler:e})}}}resizeObservers(){this.observer=new ResizeObserver(t=>{requestAnimationFrame(this.resizeCheck.bind(this))}),this.observer.observe(this.document.documentElement)}mutationObservers(){this.observer=new MutationObserver(e=>{this.resizeCheck()});const t={attributes:!0,childList:!0,characterData:!0,subtree:!0};this.observer.observe(this.document,t)}imageLoadListeners(){const t=this.document.querySelectorAll("img");let e;for(let i=0;i<t.length;i++)e=t[i],typeof e.naturalWidth<"u"&&e.naturalWidth===0&&(e.onload=this.expand.bind(this))}fontLoadListeners(){!this.document||!this.document.fonts||this.document.fonts.ready.then(()=>{this.resizeCheck()})}root(){return this.document?this.document.documentElement:null}locationOf(t,e){let i;const s={left:0,top:0};if(!this.document)return s;if(this.epubcfi.isCfiString(t)){const n=new g(t).toRange(this.document,e);if(n){try{if(!n.endContainer||n.startContainer==n.endContainer&&n.startOffset==n.endOffset){let r=(n.startContainer.textContent??"").indexOf(" ",n.startOffset);r==-1&&(r=(n.startContainer.textContent??"").length),n.setEnd(n.startContainer,r)}}catch(r){console.error("setting end offset to start container length failed",r)}if(n.startContainer.nodeType===Node.ELEMENT_NODE)i=n.startContainer.getBoundingClientRect(),s.left=i.left,s.top=i.top;else if(It){const r=n.startContainer,o=new Range;try{r.nodeType===Te?i=r.getBoundingClientRect():n.startOffset+2<r.length?(o.setStart(r,n.startOffset),o.setEnd(r,n.startOffset+2),i=o.getBoundingClientRect()):n.startOffset-2>0?(o.setStart(r,n.startOffset-2),o.setEnd(r,n.startOffset),i=o.getBoundingClientRect()):i=r.parentNode.getBoundingClientRect()}catch(h){console.error(h,h instanceof Error?h.stack:void 0)}}else i=n.getBoundingClientRect()}}else if(typeof t=="string"&&t.indexOf("#")>-1){const n=t.substring(t.indexOf("#")+1),r=this.document.getElementById(n);if(r)if(It){const o=new Range;o.selectNode(r),i=o.getBoundingClientRect()}else i=r.getBoundingClientRect()}return i&&(s.left=i.left,s.top=i.top),s}addStylesheet(t){return new Promise((e,i)=>{let s,n=!1;if(!this.document){e(!1);return}if(s=this.document.querySelector("link[href='"+t+"']"),s){e(!0);return}s=this.document.createElement("link"),s.type="text/css",s.rel="stylesheet",s.href=t,s.onload=s.onreadystatechange=function(){!n&&(!this.readyState||this.readyState=="complete")&&(n=!0,setTimeout(()=>{e(!0)},1))},this.document.head.appendChild(s)})}_getStylesheetNode(t){let e;return t="epubjs-inserted-css-"+(t||""),this.document?(e=this.document.getElementById(t),e||(e=this.document.createElement("style"),e.id=t,this.document.head.appendChild(e)),e):!1}addStylesheetCss(t,e){if(!this.document||!t)return!1;const i=this._getStylesheetNode(e);return i?(i.innerHTML=t,!0):!1}addStylesheetRules(t,e){var s;if(!this.document||!t||Array.isArray(t)&&t.length===0)return;const i=this._getStylesheetNode(e).sheet;if(Array.isArray(t))for(let n=0,r=t.length;n<r;n++){let o=1,h=t[n],a="";const c=t[n][0];Array.isArray((s=h[1])==null?void 0:s[0])&&(h=h[1],o=0);for(let d=h.length;o<d;o++){const u=h[o];a+=u[0]+":"+u[1]+(u[2]?" !important":"")+`;
3
- `}i.insertRule(c+"{"+a+"}",i.cssRules.length)}else Object.keys(t).forEach(r=>{const o=t[r];if(Array.isArray(o))o.forEach(h=>{const c=Object.keys(h).map(d=>`${d}:${h[d]}`).join(";");i.insertRule(`${r}{${c}}`,i.cssRules.length)});else{const a=Object.keys(o).map(c=>`${c}:${o[c]}`).join(";");i.insertRule(`${r}{${a}}`,i.cssRules.length)}})}addScript(t){return new Promise((e,i)=>{let s=!1;if(!this.document){e(!1);return}const n=this.document.createElement("script");n.type="text/javascript",n.async=!0,n.src=t,n.onload=n.onreadystatechange=function(){!s&&(!this.readyState||this.readyState=="complete")&&(s=!0,setTimeout(function(){e(!0)},1))},this.document.head.appendChild(n)})}addClass(t){if(!this.document)return;const e=this.content||this.document.body;e&&e.classList.add(t)}removeClass(t){if(!this.document)return;const e=this.content||this.document.body;e&&e.classList.remove(t)}addEventListeners(){this.document&&(this._triggerEvent=this.triggerEvent.bind(this),Q.forEach(t=>{this.document.addEventListener(t,this._triggerEvent,{passive:!0})}))}removeEventListeners(){this.document&&(Q.forEach(t=>{this.document.removeEventListener(t,this._triggerEvent)}),this._triggerEvent=void 0)}triggerEvent(t){this.emit(t.type,t)}addSelectionListeners(){this.document&&(this._onSelectionChange=this.onSelectionChange.bind(this),this.document.addEventListener("selectionchange",this._onSelectionChange,{passive:!0}))}removeSelectionListeners(){this.document&&(this.document.removeEventListener("selectionchange",this._onSelectionChange),this._onSelectionChange=void 0)}onSelectionChange(t){this.selectionEndTimeout&&clearTimeout(this.selectionEndTimeout),this.selectionEndTimeout=setTimeout(()=>{const e=this.window.getSelection();e&&this.triggerSelectedEvent(e)},250)}triggerSelectedEvent(t){let e,i;t&&t.rangeCount>0&&(e=t.getRangeAt(0),e.collapsed||(i=new g(e,this.cfiBase).toString(),this.emit(f.CONTENTS.SELECTED,i),this.emit(f.CONTENTS.SELECTED_RANGE,e)))}range(t,e){return new g(t).toRange(this.document,e)}cfiFromRange(t,e){return new g(t,this.cfiBase,e).toString()}cfiFromNode(t,e){return new g(t,this.cfiBase,e).toString()}size(t,e){const i={scale:1,scalable:"no"};this.layoutStyle("scrolling"),t!==void 0&&t>=0&&(this.width(t),i.width=t,this.css("padding","0 "+t/12+"px")),e!==void 0&&e>=0&&(this.height(e),i.height=e),this.css("margin","0"),this.css("box-sizing","border-box"),this.viewport(i)}columns(t,e,i,s,n){const r=U("column-axis"),o=U("column-gap"),h=U("column-width"),a=U("column-fill"),d=this.writingMode().indexOf("vertical")===0?"vertical":"horizontal";this.layoutStyle("paginated"),n==="rtl"&&d==="horizontal"&&this.direction(n),this.width(t),this.height(e),this.viewport({width:t,height:e,scale:1,scalable:"no"}),this.css("display","inline-block"),this.css("overflow-y","hidden"),this.css("margin","0",!0),d==="vertical"?(this.css("padding-top",s/2+"px",!0),this.css("padding-bottom",s/2+"px",!0),this.css("padding-left","20px"),this.css("padding-right","20px"),this.css(r,"vertical")):(this.css("padding-top","20px"),this.css("padding-bottom","20px"),this.css("padding-left",s/2+"px",!0),this.css("padding-right",s/2+"px",!0),this.css(r,"horizontal")),this.css("box-sizing","border-box"),this.css("max-width","inherit"),this.css(a,"auto"),this.css(o,s+"px"),this.css(h,i+"px")}scaler(t,e,i){const s="scale("+t+")";let n="";this.css("transform-origin","top left"),(e!==void 0&&e>=0||i!==void 0&&i>=0)&&(n=" translate("+(e||0)+"px, "+(i||0)+"px )"),this.css("transform",s+n)}fit(t,e,i){const s=this.viewport(),n=parseInt(s.width),r=parseInt(s.height),o=t/n,h=e/r,a=o<h?o:h;if(this.layoutStyle("paginated"),this.width(n),this.height(r),this.overflow("hidden"),this.scaler(a,0,0),this.css("background-size",n*a+"px "+r*a+"px"),this.css("background-color","transparent"),i&&i.properties.includes("page-spread-left")){const c=t-n*a;this.css("margin-left",c+"px")}}direction(t){this.documentElement&&(this.documentElement.style.direction=t)}mapPage(t,e,i,s,n){return new at(e,void 0,void 0,n).page(this,t,i,s)}linksHandler(){be(this.content,t=>{this.emit(f.CONTENTS.LINK_CLICKED,t)})}writingMode(t){const e=U("writing-mode");return t&&this.documentElement&&(this.documentElement.style[e]=t),this.window.getComputedStyle(this.documentElement)[e]||""}layoutStyle(t){return t&&(this._layoutStyle=t,navigator.epubReadingSystem.layoutStyle=this._layoutStyle),this._layoutStyle||"paginated"}epubReadingSystem(t,e){return navigator.epubReadingSystem={name:t,version:e,layoutStyle:this.layoutStyle(),hasFeature:function(i){switch(i){case"dom-manipulation":return!0;case"layout-changes":return!0;case"touch-events":return!0;case"mouse-events":return!0;case"keyboard-events":return!0;case"spine-scripting":return!1;default:return!1}}},navigator.epubReadingSystem}destroy(){this.removeListeners()}}I(ft.prototype);function K(l){return document.createElementNS("http://www.w3.org/2000/svg",l)}function Le(l,t){function e(s){for(let n=t.length-1;n>=0;n--){const r=t[n];let o=s.clientX,h=s.clientY;if(s.touches&&s.touches.length&&(o=s.touches[0].clientX,h=s.touches[0].clientY),!!Re(r,l,o,h)){r.dispatchEvent(ke(s));break}}}let i;if(l.nodeName==="iframe"||l.nodeName==="IFRAME")try{i=l.contentDocument}catch{i=l}else i=l;for(const s of["mouseup","mousedown","click","touchstart"])i.addEventListener(s,n=>e(n),!1)}function ke(l){const t=Object.assign({},l,{bubbles:!1});try{return new MouseEvent(l.type,t)}catch{const i=document.createEvent("MouseEvents");return i.initMouseEvent(l.type,!1,t.cancelable,t.view,t.detail,t.screenX,t.screenY,t.clientX,t.clientY,t.ctrlKey,t.altKey,t.shiftKey,t.metaKey,t.button,t.relatedTarget),i}}function Re(l,t,e,i){const s=t.getBoundingClientRect();function n(h,a,c){const d=h.top-s.top,u=h.left-s.left,p=d+h.height,m=u+h.width;return d<=c&&u<=a&&p>c&&m>a}const r=l.getBoundingClientRect();if(!n(r,e,i))return!1;const o=l.getClientRects();for(let h=0,a=o.length;h<a;h++)if(n(o[h],e,i))return!0;return!1}function Ne(l,t){const e=t.getBoundingClientRect(),i=l.getBoundingClientRect();return{top:i.top-e.top,left:i.left-e.left,height:l.scrollHeight,width:l.scrollWidth}}function Ae(l,t){l.style.setProperty("top",`${t.top}px`,"important"),l.style.setProperty("left",`${t.left}px`,"important"),l.style.setProperty("height",`${t.height}px`,"important"),l.style.setProperty("width",`${t.width}px`,"important")}function Ie(l,t){return t.right<=l.right&&t.left>=l.left&&t.top>=l.top&&t.bottom<=l.bottom}class Ot{constructor(t,e=document.body){this.target=t,this.element=K("svg"),this.marks=[],this.element.style.position="absolute",this.element.setAttribute("pointer-events","none"),Le(this.target,this.marks),this.container=e,this.container.appendChild(this.element),this.render()}addMark(t){const e=K("g");return this.element.appendChild(e),t.bind(e,this.container),this.marks.push(t),t.render(),t}removeMark(t){const e=this.marks.indexOf(t);if(e===-1)return;const i=t.unbind();this.element.removeChild(i),this.marks.splice(e,1)}render(){Ae(this.element,Ne(this.target,this.container));for(const t of this.marks)t.render()}}class Oe{constructor(){this.element=null}bind(t,e){this.element=t,this.container=e}unbind(){const t=this.element;return this.element=null,t}render(){}dispatchEvent(t){this.element&&this.element.dispatchEvent(t)}getBoundingClientRect(){return this.element.getBoundingClientRect()}getClientRects(){const t=[];let e=this.element.firstChild;for(;e;)t.push(e.getBoundingClientRect()),e=e.nextSibling;return t}filteredRanges(){const t=Array.from(this.range.getClientRects());return t.filter(e=>{for(let i=0;i<t.length;i++){if(t[i]===e)return!0;if(Ie(t[i],e))return!1}return!0})}}class ee extends Oe{constructor(t,e,i,s){super(),this.range=t,this.className=e,this.data=i||{},this.attributes=s||{}}bind(t,e){super.bind(t,e);for(const i in this.data)this.data.hasOwnProperty(i)&&(this.element.dataset[i]=this.data[i]);for(const i in this.attributes)this.attributes.hasOwnProperty(i)&&this.element.setAttribute(i,this.attributes[i]);this.className&&this.element.classList.add(this.className)}render(){for(;this.element.firstChild;)this.element.removeChild(this.element.firstChild);const t=this.element.ownerDocument.createDocumentFragment(),e=this.filteredRanges(),i=this.element.getBoundingClientRect(),s=this.container.getBoundingClientRect();for(let n=0,r=e.length;n<r;n++){const o=e[n],h=K("rect");h.setAttribute("x",o.left-i.left+s.left),h.setAttribute("y",o.top-i.top+s.top),h.setAttribute("height",o.height),h.setAttribute("width",o.width),t.appendChild(h)}this.element.appendChild(t)}}class Pe extends ee{constructor(t,e,i,s){super(t,e,i,s)}render(){for(;this.element.firstChild;)this.element.removeChild(this.element.firstChild);const t=this.element.ownerDocument.createDocumentFragment(),e=this.filteredRanges(),i=this.element.getBoundingClientRect(),s=this.container.getBoundingClientRect();for(let n=0,r=e.length;n<r;n++){const o=e[n],h=K("rect");h.setAttribute("x",o.left-i.left+s.left),h.setAttribute("y",o.top-i.top+s.top),h.setAttribute("height",o.height),h.setAttribute("width",o.width),h.setAttribute("fill","none");const a=K("line");a.setAttribute("x1",o.left-i.left+s.left),a.setAttribute("x2",o.left-i.left+s.left+o.width),a.setAttribute("y1",o.top-i.top+s.top+o.height-1),a.setAttribute("y2",o.top-i.top+s.top+o.height-1),a.setAttribute("stroke-width",1),a.setAttribute("stroke","black"),a.setAttribute("stroke-linecap","square"),t.appendChild(h),t.appendChild(a)}this.element.appendChild(t)}}class ie{constructor(t,e){this.settings=_({ignoreClass:"",axis:void 0,direction:void 0,width:0,height:0,layout:void 0,globalLayoutProperties:{},method:void 0,forceRight:!1,allowScriptedContent:!1,allowPopups:!1},e||{}),this.id="epubjs-view-"+dt(),this.section=t,this.index=t.index,this.element=this.container(this.settings.axis),this.added=!1,this.displayed=!1,this.rendered=!1,this.fixedWidth=0,this.fixedHeight=0,this.epubcfi=new g,this.layout=this.settings.layout,this.pane=void 0,this.highlights={},this.underlines={},this.marks={}}container(t){const e=document.createElement("div");return e.classList.add("epub-view"),e.style.height="0px",e.style.width="0px",e.style.overflow="hidden",e.style.position="relative",e.style.display="block",t&&t=="horizontal"?e.style.flex="none":e.style.flex="initial",e}create(){return this.iframe?this.iframe:(this.element||(this.element=this.container()),this.iframe=document.createElement("iframe"),this.iframe.id=this.id,this.iframe.scrolling="no",this.iframe.style.overflow="hidden",this.iframe.seamless="seamless",this.iframe.style.border="none",this.iframe.sandbox="allow-same-origin",this.settings.allowScriptedContent&&(this.iframe.sandbox+=" allow-scripts"),this.settings.allowPopups&&(this.iframe.sandbox+=" allow-popups"),this.iframe.setAttribute("enable-annotation","true"),this.resizing=!0,this.element.style.visibility="hidden",this.iframe.style.visibility="hidden",this.iframe.style.width="0",this.iframe.style.height="0",this._width=0,this._height=0,this.element.setAttribute("ref",String(this.index)),this.added=!0,this.elementBounds=J(this.element),"srcdoc"in this.iframe?this.supportsSrcdoc=!0:this.supportsSrcdoc=!1,this.settings.method||(this.settings.method=this.supportsSrcdoc?"srcdoc":"write"),this.iframe)}render(t,e){return this.create(),this.size(),this.sectionRender||(this.sectionRender=this.section.render(t)),this.sectionRender.then(i=>this.load(i)).then(()=>{const i=this.contents.writingMode();let s;return this.settings.flow==="scrolled"?s=i.indexOf("vertical")===0?"horizontal":"vertical":s=i.indexOf("vertical")===0?"vertical":"horizontal",i.indexOf("vertical")===0&&this.settings.flow==="paginated"&&(this.layout.delta=this.layout.height),this.setAxis(s),this.emit(f.VIEWS.AXIS,s),this.setWritingMode(i),this.emit(f.VIEWS.WRITING_MODE,i),this.layout.format(this.contents,this.section,this.axis),this.addListeners(),new Promise((n,r)=>{this.expand(),this.settings.forceRight&&(this.element.style.marginLeft=this.width()+"px"),n()})},i=>(this.emit(f.VIEWS.LOAD_ERROR,i),new Promise((s,n)=>{n(i)}))).then(()=>{this.emit(f.VIEWS.RENDERED,this.section)})}reset(){this.iframe&&(this.iframe.style.width="0",this.iframe.style.height="0",this._width=0,this._height=0,this._textWidth=void 0,this._contentWidth=void 0,this._textHeight=void 0,this._contentHeight=void 0),this._needsReframe=!0}size(t,e){const i=t||this.settings.width,s=e||this.settings.height;this.layout.name==="pre-paginated"?this.lock("both",i,s):this.settings.axis==="horizontal"?this.lock("height",i,s):this.lock("width",i,s),this.settings.width=i,this.settings.height=s}lock(t,e,i){const s=nt(this.element);let n;this.iframe?n=nt(this.iframe):n={width:0,height:0},t=="width"&&x(e)&&(this.lockedWidth=e-s.width-n.width),t=="height"&&x(i)&&(this.lockedHeight=i-s.height-n.height),t==="both"&&x(e)&&x(i)&&(this.lockedWidth=e-s.width-n.width,this.lockedHeight=i-s.height-n.height),this.displayed&&this.iframe&&this.expand()}expand(t){let e=this.lockedWidth,i=this.lockedHeight,s;!this.iframe||this._expanding||(this._expanding=!0,this.layout.name==="pre-paginated"?(e=this.layout.columnWidth,i=this.layout.height):this.settings.axis==="horizontal"?(e=this.contents.textWidth(),e%this.layout.pageWidth>0&&(e=Math.ceil(e/this.layout.pageWidth)*this.layout.pageWidth),this.settings.forceEvenPages&&(s=e/this.layout.pageWidth,this.layout.divisor>1&&this.layout.name==="reflowable"&&s%2>0&&(e+=this.layout.pageWidth))):this.settings.axis==="vertical"&&(i=this.contents.textHeight(),this.settings.flow==="paginated"&&i%this.layout.height>0&&(i=Math.ceil(i/this.layout.height)*this.layout.height)),(this._needsReframe||e!=this._width||i!=this._height)&&this.reframe(e,i),this._expanding=!1)}reframe(t,e){x(t)&&(this.element.style.width=t+"px",this.iframe.style.width=t+"px",this._width=t),x(e)&&(this.element.style.height=e+"px",this.iframe.style.height=e+"px",this._height=e);const i=this.prevBounds?t-this.prevBounds.width:t,s=this.prevBounds?e-this.prevBounds.height:e,n={width:t,height:e,widthDelta:i,heightDelta:s};this.pane&&this.pane.render(),requestAnimationFrame(()=>{let r;for(const o in this.marks)this.marks.hasOwnProperty(o)&&(r=this.marks[o],this.placeMark(r.element,r.range))}),this.onResize(this,n),this.emit(f.VIEWS.RESIZED,n),this.prevBounds=n,this.elementBounds=J(this.element)}load(t){const e=new v,i=e.promise;if(!this.iframe)return e.reject(new Error("No Iframe Available")),i;if(this.iframe.onload=s=>{this.onLoad(s,e)},this.settings.method==="blobUrl")this.blobUrl=ot(t,"application/xhtml+xml"),this.iframe.src=this.blobUrl,this.element.appendChild(this.iframe);else if(this.settings.method==="srcdoc")this.iframe.srcdoc=t,this.element.appendChild(this.iframe);else{if(this.element.appendChild(this.iframe),this.document=this.iframe.contentDocument,!this.document)return e.reject(new Error("No Document Available")),i;if(this.document.open(),window.MSApp&&window.MSApp.execUnsafeLocalFunction){const s=this;window.MSApp.execUnsafeLocalFunction(function(){s.document.write(t)})}else this.document.write(t);this.document.close()}return i}onLoad(t,e){this.window=this.iframe.contentWindow,this.document=this.iframe.contentDocument,this.contents=new ft(this.document,this.document.body,this.section.cfiBase,this.section.index),this.rendering=!1;let i=this.document.querySelector("link[rel='canonical']");i?i.setAttribute("href",this.section.canonical):(i=this.document.createElement("link"),i.setAttribute("rel","canonical"),i.setAttribute("href",this.section.canonical),this.document.querySelector("head").appendChild(i)),this.contents.on(f.CONTENTS.EXPAND,()=>{this.displayed&&this.iframe&&(this.expand(),this.contents&&this.layout.format(this.contents))}),this.contents.on(f.CONTENTS.RESIZE,s=>{this.displayed&&this.iframe&&(this.expand(),this.contents&&this.layout.format(this.contents))}),e.resolve(this.contents)}setLayout(t){this.layout=t,this.contents&&(this.layout.format(this.contents),this.expand())}setAxis(t){this.settings.axis=t,t=="horizontal"?this.element.style.flex="none":this.element.style.flex="initial",this.size()}setWritingMode(t){this.writingMode=t}addListeners(){}removeListeners(t){}display(t){const e=new v;return this.displayed?e.resolve(this):this.render(t).then(()=>{this.emit(f.VIEWS.DISPLAYED,this),this.onDisplayed(this),this.displayed=!0,e.resolve(this)},i=>{e.reject(i)}),e.promise}show(){this.element.style.visibility="visible",this.iframe&&(this.iframe.style.visibility="visible",this.iframe.style.transform="translateZ(0)",this.iframe.offsetWidth,this.iframe.style.transform=""),this.emit(f.VIEWS.SHOWN,this)}hide(){this.element.style.visibility="hidden",this.iframe.style.visibility="hidden",this.stopExpanding=!0,this.emit(f.VIEWS.HIDDEN,this)}offset(){return{top:this.element.offsetTop,left:this.element.offsetLeft}}width(){return this._width}height(){return this._height}position(){return this.element.getBoundingClientRect()}locationOf(t){this.iframe.getBoundingClientRect();const e=this.contents.locationOf(t,this.settings.ignoreClass);return{left:e.left,top:e.top}}onDisplayed(t){}onResize(t,e){}bounds(t){return(t||!this.elementBounds)&&(this.elementBounds=J(this.element)),this.elementBounds}highlight(t,e={},i,s="epubjs-hl",n={}){if(!this.contents)return;const r=Object.assign({fill:"yellow","fill-opacity":"0.3","mix-blend-mode":"multiply"},n),o=this.contents.range(t),h=()=>{this.emit(f.VIEWS.MARK_CLICKED,t,e)};e.epubcfi=t,this.pane||(this.pane=new Ot(this.iframe,this.element));const a=new ee(o,s,e,r);let c;try{c=this.pane.addMark(a)}catch(d){console.error("Failed to add highlight for",t,d);return}return this.highlights[t]={mark:c,element:c.element,listeners:[h,i]},c.element.setAttribute("ref",s),c.element.addEventListener("click",h),c.element.addEventListener("touchstart",h),i&&(c.element.addEventListener("click",i),c.element.addEventListener("touchstart",i)),c}underline(t,e={},i,s="epubjs-ul",n={}){if(!this.contents)return;const r=Object.assign({stroke:"black","stroke-opacity":"0.3","mix-blend-mode":"multiply"},n),o=this.contents.range(t),h=()=>{this.emit(f.VIEWS.MARK_CLICKED,t,e)};e.epubcfi=t,this.pane||(this.pane=new Ot(this.iframe,this.element));const a=new Pe(o,s,e,r);let c;try{c=this.pane.addMark(a)}catch(d){console.error("Failed to add underline for",t,d);return}return this.underlines[t]={mark:c,element:c.element,listeners:[h,i]},c.element.setAttribute("ref",s),c.element.addEventListener("click",h),c.element.addEventListener("touchstart",h),i&&(c.element.addEventListener("click",i),c.element.addEventListener("touchstart",i)),c}mark(t,e={},i){if(!this.contents)return;if(t in this.marks)return this.marks[t];let s=this.contents.range(t);if(!s)return;const n=s.commonAncestorContainer,r=n.nodeType===1?n:n.parentNode,o=a=>{this.emit(f.VIEWS.MARK_CLICKED,t,e)};s.collapsed&&n.nodeType===1?(s=new Range,s.selectNodeContents(n)):s.collapsed&&(s=new Range,s.selectNodeContents(r));const h=this.document.createElement("a");return h.setAttribute("ref","epubjs-mk"),h.style.position="absolute",h.dataset.epubcfi=t,e&&Object.keys(e).forEach(a=>{h.dataset[a]=e[a]}),i&&(h.addEventListener("click",i),h.addEventListener("touchstart",i)),h.addEventListener("click",o),h.addEventListener("touchstart",o),this.placeMark(h,s),this.element.appendChild(h),this.marks[t]={element:h,range:s,listeners:[o,i]},r}placeMark(t,e){let i,s,n;if(this.layout.name==="pre-paginated"||this.settings.axis!=="horizontal"){const r=e.getBoundingClientRect();i=r.top,s=r.right}else{const r=e.getClientRects();let o;for(let h=0;h!=r.length;h++)o=r[h],(!n||o.left<n)&&(n=o.left,s=Math.ceil(n/this.layout.props.pageWidth)*this.layout.props.pageWidth-this.layout.gap/2,i=o.top)}t.style.top=`${i}px`,t.style.left=`${s}px`}unhighlight(t){if(t in this.highlights){const e=this.highlights[t];this.pane.removeMark(e.mark),e.listeners.forEach(i=>{i&&(e.element.removeEventListener("click",i),e.element.removeEventListener("touchstart",i))}),delete this.highlights[t]}}ununderline(t){if(t in this.underlines){const e=this.underlines[t];this.pane.removeMark(e.mark),e.listeners.forEach(i=>{i&&(e.element.removeEventListener("click",i),e.element.removeEventListener("touchstart",i))}),delete this.underlines[t]}}unmark(t){if(t in this.marks){const e=this.marks[t];this.element.removeChild(e.element),e.listeners.forEach(i=>{i&&(e.element.removeEventListener("click",i),e.element.removeEventListener("touchstart",i))}),delete this.marks[t]}}destroy(){for(const t in this.highlights)this.unhighlight(t);for(const t in this.underlines)this.ununderline(t);for(const t in this.marks)this.unmark(t);this.blobUrl&&Ut(this.blobUrl),this.displayed&&(this.displayed=!1,this.removeListeners(),this.contents.destroy(),this.stopExpanding=!0,this.element.removeChild(this.iframe),this.pane&&(this.pane.element.remove(),this.pane=void 0),this.iframe=void 0,this.contents=void 0,this._textWidth=null,this._textHeight=null,this._width=null,this._height=null)}}I(ie.prototype);function ze(){let l="reverse";const t=De();return document.body.appendChild(t),t.scrollLeft>0?l="default":typeof Element<"u"&&typeof Element.prototype.scrollIntoView=="function"?(t.children[0].children[1].scrollIntoView(),t.scrollLeft<0&&(l="negative")):(t.scrollLeft=1,t.scrollLeft===0&&(l="negative")),document.body.removeChild(t),l}function De(){const l=document.createElement("div");l.dir="rtl",l.style.position="fixed",l.style.width="1px",l.style.height="1px",l.style.top="0px",l.style.left="0px",l.style.overflow="hidden";const t=document.createElement("div");t.style.width="2px";const e=document.createElement("span");e.style.width="1px",e.style.display="inline-block";const i=document.createElement("span");return i.style.width="1px",i.style.display="inline-block",t.appendChild(e),t.appendChild(i),l.appendChild(t),l}function Be(l,t){let e=null,i=0;return function(...s){const n=Date.now(),r=t-(n-i);r<=0||r>t?(e&&(clearTimeout(e),e=null),i=n,l.call(this,...s)):e||(e=setTimeout(()=>{i=Date.now(),e=null,l.call(this,...s)},r))}}class Me{constructor(t){this.settings=t||{},this.id="epubjs-container-"+dt(),this.container=this.create(this.settings),this.settings.hidden&&(this.wrapper=this.wrap(this.container))}create(t){let e=t.height,i=t.width;const s=t.overflow||!1,n=t.axis||"vertical",r=t.direction;_(this.settings,t),t.height&&x(t.height)&&(e=t.height+"px"),t.width&&x(t.width)&&(i=t.width+"px");const o=document.createElement("div");return o.id=this.id,o.classList.add("epub-container"),o.style.wordSpacing="0",o.style.lineHeight="0",o.style.verticalAlign="top",o.style.position="relative",o.style.overflowAnchor="none",n==="horizontal"&&(o.style.display="flex",o.style.flexDirection="row",o.style.flexWrap="nowrap"),i&&(o.style.width=i),e&&(o.style.height=e),s&&(s==="scroll"&&n==="vertical"?(o.style.overflowY=s,o.style.overflowX="hidden"):s==="scroll"&&n==="horizontal"?(o.style.overflowY="hidden",o.style.overflowX=s):o.style.overflow=s),r&&(o.dir=r,o.style.direction=r),r&&this.settings.fullsize&&(document.body.style.direction=r),o}wrap(t){const e=document.createElement("div");return e.style.visibility="hidden",e.style.overflow="hidden",e.style.width="0",e.style.height="0",e.appendChild(t),e}getElement(t){let e=null;if(Dt(t)?e=t:typeof t=="string"&&(e=document.getElementById(t)),!e)throw new Error("Not an Element");return e}attachTo(t){const e=this.getElement(t);let i;if(e)return this.settings.hidden?i=this.wrapper:i=this.container,e.appendChild(i),this.element=e,e}getContainer(){return this.container}onResize(t){(!x(this.settings.width)||!x(this.settings.height))&&(this.resizeFunc=Be(t,50),window.addEventListener("resize",this.resizeFunc,!1))}onOrientationChange(t){this.orientationChangeFunc=t,window.addEventListener("orientationchange",this.orientationChangeFunc,!1)}size(t,e){let i;const s=t||this.settings.width,n=e||this.settings.height;t===null?(i=this.element.getBoundingClientRect(),i.width&&(t=Math.floor(i.width),this.container.style.width=t+"px")):x(t)?this.container.style.width=t+"px":t&&(this.container.style.width=t),e===null?(i=i||this.element.getBoundingClientRect(),i.height&&(e=i.height,this.container.style.height=e+"px")):x(e)?this.container.style.height=e+"px":e&&(this.container.style.height=e),x(t)||(t=this.container.clientWidth),x(e)||(e=this.container.clientHeight),this.containerStyles=window.getComputedStyle(this.container),this.containerPadding={left:parseFloat(this.containerStyles.paddingLeft)||0,right:parseFloat(this.containerStyles.paddingRight)||0,top:parseFloat(this.containerStyles.paddingTop)||0,bottom:parseFloat(this.containerStyles.paddingBottom)||0};const r=rt(),o=window.getComputedStyle(document.body),h={left:parseFloat(o.paddingLeft)||0,right:parseFloat(o.paddingRight)||0,top:parseFloat(o.paddingTop)||0,bottom:parseFloat(o.paddingBottom)||0};return s||(t=r.width-h.left-h.right),(this.settings.fullsize&&!n||!n)&&(e=r.height-h.top-h.bottom),{width:t-this.containerPadding.left-this.containerPadding.right,height:e-this.containerPadding.top-this.containerPadding.bottom}}bounds(){let t;return this.container.style.overflow!=="visible"&&(t=this.container&&this.container.getBoundingClientRect()),!t||!t.width||!t.height?rt():t}getSheet(){const t=document.createElement("style");return t.appendChild(document.createTextNode("")),document.head.appendChild(t),t.sheet}addStyleRules(t,e){const i="#"+this.id+" ";let s="";this.sheet||(this.sheet=this.getSheet()),e.forEach(function(n){for(const r in n)n.hasOwnProperty(r)&&(s+=r+":"+n[r]+";")}),this.sheet.insertRule(i+t+" {"+s+"}",0)}axis(t){t==="horizontal"?(this.container.style.display="flex",this.container.style.flexDirection="row",this.container.style.flexWrap="nowrap"):this.container.style.display="block",this.settings.axis=t}direction(t){this.container&&(this.container.dir=t,this.container.style.direction=t),this.settings.fullsize&&(document.body.style.direction=t),this.settings.dir=t}overflow(t){this.container&&(t==="scroll"&&this.settings.axis==="vertical"?(this.container.style.overflowY=t,this.container.style.overflowX="hidden"):t==="scroll"&&this.settings.axis==="horizontal"?(this.container.style.overflowY="hidden",this.container.style.overflowX=t):this.container.style.overflow=t),this.settings.overflow=t}destroy(){this.element&&(this.settings.hidden?this.wrapper:this.container,this.element.contains(this.container)&&this.element.removeChild(this.container),window.removeEventListener("resize",this.resizeFunc),window.removeEventListener("orientationchange",this.orientationChangeFunc))}}class We{constructor(t){this.container=t,this._views=[],this.length=0,this.hidden=!1}all(){return this._views}first(){return this._views[0]}last(){return this._views[this._views.length-1]}indexOf(t){return this._views.indexOf(t)}slice(...t){return this._views.slice(...t)}get(t){return this._views[t]}append(t){return this._views.push(t),this.container&&this.container.appendChild(t.element),this.length++,t}prepend(t){return this._views.unshift(t),this.container&&this.container.insertBefore(t.element,this.container.firstChild),this.length++,t}insert(t,e){return this._views.splice(e,0,t),this.container&&(e<this.container.children.length?this.container.insertBefore(t.element,this.container.children[e]):this.container.appendChild(t.element)),this.length++,t}remove(t){const e=this._views.indexOf(t);e>-1&&this._views.splice(e,1),this.destroy(t),this.length--}destroy(t){t.displayed&&t.destroy(),this.container&&this.container.removeChild(t.element)}forEach(t){return this._views.forEach(t)}clear(){let t;const e=this.length;if(this.length){for(let i=0;i<e;i++)t=this._views[i],this.destroy(t);this._views=[],this.length=0}}find(t){let e;const i=this.length;for(let s=0;s<i;s++)if(e=this._views[s],e.displayed&&e.section.index==t.index)return e}displayed(){const t=[];let e;const i=this.length;for(let s=0;s<i;s++)e=this._views[s],e.displayed&&t.push(e);return t}show(){let t;const e=this.length;for(let i=0;i<e;i++)t=this._views[i],t.displayed&&t.show();this.hidden=!1}hide(){let t;const e=this.length;for(let i=0;i<e;i++)t=this._views[i],t.displayed&&t.hide();this.hidden=!0}}class ct{constructor(t){this.name="default",this.optsSettings=t.settings,this.View=t.view,this.request=t.request,this.renditionQueue=t.queue,this.q=new Lt(this),this.settings=_({},{infinite:!0,hidden:!1,width:void 0,height:void 0,axis:void 0,writingMode:void 0,flow:"scrolled",ignoreClass:"",fullsize:void 0,allowScriptedContent:!1,allowPopups:!1}),_(this.settings,t.settings||{}),this.viewSettings={ignoreClass:this.settings.ignoreClass,axis:this.settings.axis,flow:this.settings.flow,layout:this.layout,method:this.settings.method,width:0,height:0,forceEvenPages:!0,allowScriptedContent:this.settings.allowScriptedContent,allowPopups:this.settings.allowPopups},this.rendered=!1}render(t,e){const i=t.tagName;typeof this.settings.fullsize>"u"&&i&&(i.toLowerCase()=="body"||i.toLowerCase()=="html")&&(this.settings.fullsize=!0),this.settings.fullsize&&(this.settings.overflow="visible",this.overflow=this.settings.overflow),this.settings.size=e,this.settings.rtlScrollType=ze(),this.stage=new Me({width:e.width,height:e.height,overflow:this.overflow,hidden:this.settings.hidden,axis:this.settings.axis,fullsize:this.settings.fullsize,direction:this.settings.direction}),this.stage.attachTo(t),this.container=this.stage.getContainer(),this.views=new We(this.container),this._bounds=this.bounds(),this._stageSize=this.stage.size(),this.viewSettings.width=this._stageSize.width,this.viewSettings.height=this._stageSize.height,this.stage.onResize(()=>this.onResized()),this.stage.onOrientationChange(s=>this.onOrientationChange(s)),this.addEventListeners(),this.layout&&this.updateLayout(),this.rendered=!0}addEventListeners(){let t;this._onUnload=e=>{this.destroy()},window.addEventListener("unload",this._onUnload),this.settings.fullsize?t=window:t=this.container,this._onScroll=this.onScroll.bind(this),t.addEventListener("scroll",this._onScroll)}removeEventListeners(){let t;this.settings.fullsize?t=window:t=this.container,t.removeEventListener("scroll",this._onScroll),this._onScroll=void 0,window.removeEventListener("unload",this._onUnload),this._onUnload=void 0}destroy(){clearTimeout(this.orientationTimeout),clearTimeout(this.resizeTimeout),clearTimeout(this.afterScrolled),this.clear(),this.removeEventListeners(),this.stage.destroy(),this.rendered=!1}onOrientationChange(t){const{orientation:e}=window;this.optsSettings.resizeOnOrientationChange&&this.resize(),clearTimeout(this.orientationTimeout),this.orientationTimeout=setTimeout(()=>{this.orientationTimeout=void 0,this.optsSettings.resizeOnOrientationChange&&this.resize(),this.emit(f.MANAGERS.ORIENTATION_CHANGE,e)},500)}onResized(t){this.resize()}resize(t,e,i){const s=this.stage.size(t,e);if(this.winBounds=rt(),this.orientationTimeout&&this.winBounds.width===this.winBounds.height){this._stageSize=void 0;return}this._stageSize&&this._stageSize.width===s.width&&this._stageSize.height===s.height||(this._stageSize=s,this._bounds=this.bounds(),this.clear(),this.viewSettings.width=this._stageSize.width,this.viewSettings.height=this._stageSize.height,this.updateLayout(),this.emit(f.MANAGERS.RESIZED,{width:this._stageSize.width,height:this._stageSize.height},i))}createView(t,e){return new this.View(t,_(this.viewSettings,{forceRight:e}))}handleNextPrePaginated(t,e,i){let s;if(this.layout.name==="pre-paginated"&&this.layout.divisor>1){if(t||e.index===0)return;if(s=e.next(),s&&!s.properties.includes("page-spread-left"))return i.call(this,s)}}display(t,e){const i=new v,s=i.promise;(e===t.href||x(e))&&(e=void 0);const n=this.views.find(t);if(n&&t&&this.layout.name!=="pre-paginated"){const o=n.offset();if(this.settings.direction==="ltr")this.scrollTo(o.left,o.top,!0);else{const h=n.width();this.scrollTo(o.left+h,o.top,!0)}if(e){const h=n.locationOf(e),a=n.width();this.moveTo(h,a)}return i.resolve(),s}this.clear();let r=!1;return this.layout.name==="pre-paginated"&&this.layout.divisor===2&&t.properties.includes("page-spread-right")&&(r=!0),this.add(t,r).then(o=>{if(e){const h=o.locationOf(e),a=o.width();this.moveTo(h,a)}},o=>{i.reject(o)}).then(()=>this.handleNextPrePaginated(r,t,this.add)).then(()=>{this.views.show(),i.resolve()}),s}afterDisplayed(t){this.emit(f.MANAGERS.ADDED,t)}afterResized(t){this.emit(f.MANAGERS.RESIZE,t.section)}moveTo(t,e){let i=0,s=0;this.isPaginated?(i=Math.floor(t.left/this.layout.delta)*this.layout.delta,i+this.layout.delta>this.container.scrollWidth&&(i=this.container.scrollWidth-this.layout.delta),s=Math.floor(t.top/this.layout.height)*this.layout.height,s+this.layout.height>this.container.scrollHeight&&(s=this.container.scrollHeight-this.layout.height)):s=t.top,this.settings.direction==="rtl"&&(i=i+this.layout.delta,i=i-e),this.scrollTo(i,s,!0)}add(t,e){const i=this.createView(t,e);return this.views.append(i),i.onDisplayed=s=>this.afterDisplayed(s),i.onResize=s=>this.afterResized(s),i.on(f.VIEWS.AXIS,s=>{this.updateAxis(s)}),i.on(f.VIEWS.WRITING_MODE,s=>{this.updateWritingMode(s)}),i.display(this.request)}append(t,e){const i=this.createView(t,e);return this.views.append(i),i.onDisplayed=s=>this.afterDisplayed(s),i.onResize=s=>this.afterResized(s),i.on(f.VIEWS.AXIS,s=>{this.updateAxis(s)}),i.on(f.VIEWS.WRITING_MODE,s=>{this.updateWritingMode(s)}),i.display(this.request)}prepend(t,e){const i=this.createView(t,e);return i.on(f.VIEWS.RESIZED,s=>{this.counter(s)}),this.views.prepend(i),i.onDisplayed=s=>this.afterDisplayed(s),i.onResize=s=>this.afterResized(s),i.on(f.VIEWS.AXIS,s=>{this.updateAxis(s)}),i.on(f.VIEWS.WRITING_MODE,s=>{this.updateWritingMode(s)}),i.display(this.request)}counter(t){this.settings.axis==="vertical"?this.scrollBy(0,t.heightDelta,!0):this.scrollBy(t.widthDelta,0,!0)}next(){let t,e;const i=this.settings.direction;if(this.views.length&&(this.isPaginated&&this.settings.axis==="horizontal"&&(!i||i==="ltr")?(this.scrollLeft=this.container.scrollLeft,e=this.container.scrollLeft+this.container.offsetWidth+this.layout.delta,e<=this.container.scrollWidth?this.scrollBy(this.layout.delta,0,!0):t=this.views.last().section.next()):this.isPaginated&&this.settings.axis==="horizontal"&&i==="rtl"?(this.scrollLeft=this.container.scrollLeft,this.settings.rtlScrollType==="default"?(e=this.container.scrollLeft,e>0?this.scrollBy(this.layout.delta,0,!0):t=this.views.last().section.next()):(e=this.container.scrollLeft+this.layout.delta*-1,e>this.container.scrollWidth*-1?this.scrollBy(this.layout.delta,0,!0):t=this.views.last().section.next())):this.isPaginated&&this.settings.axis==="vertical"?(this.scrollTop=this.container.scrollTop,Math.abs(this.container.scrollHeight-this.container.clientHeight-this.container.scrollTop)<1?t=this.views.last().section.next():this.scrollBy(0,this.layout.height,!0)):t=this.views.last().section.next(),t)){this.clear(),this.updateLayout();let s=!1;return this.layout.name==="pre-paginated"&&this.layout.divisor===2&&t.properties.includes("page-spread-right")&&(s=!0),this.append(t,s).then(()=>this.handleNextPrePaginated(s,t,this.append),n=>n).then(()=>{!this.isPaginated&&this.settings.axis==="horizontal"&&this.settings.direction==="rtl"&&this.settings.rtlScrollType==="default"&&this.scrollTo(this.container.scrollWidth,0,!0),this.views.show()})}}prev(){let t,e;const i=this.settings.direction;if(this.views.length&&(this.isPaginated&&this.settings.axis==="horizontal"&&(!i||i==="ltr")?(this.scrollLeft=this.container.scrollLeft,e=this.container.scrollLeft,e>0?this.scrollBy(-this.layout.delta,0,!0):t=this.views.first().section.prev()):this.isPaginated&&this.settings.axis==="horizontal"&&i==="rtl"?(this.scrollLeft=this.container.scrollLeft,this.settings.rtlScrollType==="default"?(e=this.container.scrollLeft+this.container.offsetWidth,e<this.container.scrollWidth?this.scrollBy(-this.layout.delta,0,!0):t=this.views.first().section.prev()):(e=this.container.scrollLeft,e<0?this.scrollBy(-this.layout.delta,0,!0):t=this.views.first().section.prev())):this.isPaginated&&this.settings.axis==="vertical"?(this.scrollTop=this.container.scrollTop,this.container.scrollTop>0?this.scrollBy(0,-this.layout.height,!0):t=this.views.first().section.prev()):t=this.views.first().section.prev(),t)){this.clear(),this.updateLayout();let s=!1;return this.layout.name==="pre-paginated"&&this.layout.divisor===2&&typeof t.prev()!="object"&&(s=!0),this.prepend(t,s).then(()=>{if(this.layout.name==="pre-paginated"&&this.layout.divisor>1){const n=t.prev();if(n)return this.prepend(n)}},n=>n).then(()=>{this.isPaginated&&this.settings.axis==="horizontal"&&(this.settings.direction==="rtl"?this.settings.rtlScrollType==="default"?this.scrollTo(0,0,!0):this.scrollTo(this.container.scrollWidth*-1+this.layout.delta,0,!0):this.scrollTo(this.container.scrollWidth-this.layout.delta,0,!0)),this.views.show()})}}current(){const t=this.visible();return t.length?t[t.length-1]:null}clear(){this.views&&(this.views.hide(),this.scrollTo(0,0,!0),this.views.clear())}currentLocation(){return this.updateLayout(),this.isPaginated&&this.settings.axis==="horizontal"?this.location=this.paginatedLocation():this.location=this.scrolledLocation(),this.location}scrolledLocation(){const t=this.visible(),e=this.container.getBoundingClientRect(),i=e.height<window.innerHeight?e.height:window.innerHeight,s=e.width<window.innerWidth?e.width:window.innerWidth,n=this.settings.axis==="vertical";this.settings.direction;let r=0;const o=0;return this.settings.fullsize&&(r=n?window.scrollY:window.scrollX),t.map(a=>{const{index:c,href:d}=a.section,u=a.position(),p=a.width(),m=a.height();let y,b,E,T;n?(y=r+e.top-u.top+o,b=y+i-o,T=this.layout.count(m,i).pages,E=i):(y=r+e.left-u.left+o,b=y+s-o,T=this.layout.count(p,s).pages,E=s);let S=Math.ceil(y/E),C=[],O=Math.ceil(b/E);if(this.settings.direction==="rtl"&&!n){const M=S;S=T-O,O=T-M}C=[];for(let M=S;M<=O;M++){const z=M+1;C.push(z)}const Z=this.mapping.page(a.contents,a.section.cfiBase,y,b);return{index:c,href:d,pages:C,totalPages:T,mapping:Z}})}paginatedLocation(){const t=this.visible(),e=this.container.getBoundingClientRect();let i=0,s=0;return this.settings.fullsize&&(i=window.scrollX),t.map(r=>{const{index:o,href:h}=r.section;let a;const c=r.position(),d=r.width();let u,p,m;this.settings.direction==="rtl"?(a=e.right-i,m=Math.min(Math.abs(a-c.left),this.layout.width)-s,p=c.width-(c.right-a)-s,u=p-m):(a=e.left+i,m=Math.min(c.right-a,this.layout.width)-s,u=a-c.left+s,p=u+m),s+=m;const y=this.mapping.page(r.contents,r.section.cfiBase,u,p),b=this.layout.count(d).pages;let E=Math.floor(u/this.layout.pageWidth);const T=[];let S=Math.floor(p/this.layout.pageWidth);if(E<0&&(E=0,S=S+1),this.settings.direction==="rtl"){const C=E;E=b-S,S=b-C}for(let C=E+1;C<=S;C++){const O=C;T.push(O)}return{index:o,href:h,pages:T,totalPages:b,mapping:y}})}isVisible(t,e,i,s){const n=t.position(),r=s||this.bounds();return this.settings.axis==="horizontal"&&n.right>r.left-e&&n.left<r.right+i?!0:this.settings.axis==="vertical"&&n.bottom>r.top-e&&n.top<r.bottom+i}visible(){const t=this.bounds(),e=this.views.displayed(),i=e.length,s=[];let n,r;for(let o=0;o<i;o++)r=e[o],n=this.isVisible(r,0,0,t),n===!0&&s.push(r);return s}scrollBy(t,e,i){const s=this.settings.direction==="rtl"?-1:1;i&&(this.ignore=!0),this.settings.fullsize?window.scrollBy(t*s,e*s):(t&&(this.container.scrollLeft+=t*s),e&&(this.container.scrollTop+=e)),this._hasScrolled=!0}scrollTo(t,e,i){i&&(this.ignore=!0),this.settings.fullsize?window.scrollTo(t,e):(this.container.scrollLeft=t,this.container.scrollTop=e),this._hasScrolled=!0}onScroll(){let t,e;this.settings.fullsize?(t=window.scrollY,e=window.scrollX):(t=this.container.scrollTop,e=this.container.scrollLeft),this.scrollTop=t,this.scrollLeft=e,this.ignore?this.ignore=!1:(this.emit(f.MANAGERS.SCROLL,{top:t,left:e}),clearTimeout(this.afterScrolled),this.afterScrolled=setTimeout(()=>{this.emit(f.MANAGERS.SCROLLED,{top:this.scrollTop,left:this.scrollLeft})},20))}bounds(){return this.stage.bounds()}applyLayout(t){this.layout=t,this.updateLayout(),this.views&&this.views.length>0&&this.layout.name==="pre-paginated"&&this.display(this.views.first().section)}updateLayout(){this.stage&&(this._stageSize=this.stage.size(),this.isPaginated?(this.layout.calculate(this._stageSize.width,this._stageSize.height,this.settings.gap),this.settings.offset=this.layout.delta/this.layout.divisor):this.layout.calculate(this._stageSize.width,this._stageSize.height),this.viewSettings.width=this.layout.width,this.viewSettings.height=this.layout.height,this.setLayout(this.layout))}setLayout(t){this.viewSettings.layout=t,this.mapping=new at(t.props,this.settings.direction,this.settings.axis),this.views&&this.views.forEach(e=>{e&&e.setLayout(t)})}updateWritingMode(t){this.writingMode=t}updateAxis(t,e){!e&&t===this.settings.axis||(this.settings.axis=t,this.stage&&this.stage.axis(t),this.viewSettings.axis=t,this.mapping&&(this.mapping=new at(this.layout.props,this.settings.direction,this.settings.axis)),this.layout&&(t==="vertical"?this.layout.spread("none"):this.layout.spread(this.layout.settings.spread)))}updateFlow(t,e="auto"){const i=t==="paginated"||t==="auto";this.isPaginated=i,t==="scrolled-doc"||t==="scrolled-continuous"||t==="scrolled"?this.updateAxis("vertical"):this.updateAxis("horizontal"),this.viewSettings.flow=t,this.settings.overflow?this.overflow=this.settings.overflow:this.overflow=i?"hidden":e,this.stage&&this.stage.overflow(this.overflow),this.updateLayout()}getContents(){const t=[];return this.views&&this.views.forEach(e=>{const i=e&&e.contents;i&&t.push(i)}),t}direction(t="ltr"){this.settings.direction=t,this.stage&&this.stage.direction(t),this.viewSettings.direction=t,this.updateLayout()}isRendered(){return this.rendered}}I(ct.prototype);const qe={easeInCubic:function(l){return Math.pow(l,3)}};class Ct{constructor(t,e){this.settings=_({duration:80,minVelocity:.2,minDistance:10,easing:qe.easeInCubic},e||{}),this.supportsTouch=this.supportsTouch(),this.supportsTouch&&this.setup(t)}setup(t){this.manager=t,this.layout=this.manager.layout,this.fullsize=this.manager.settings.fullsize??!1,this.fullsize?(this.element=this.manager.stage.element,this.scroller=window,this.disableScroll()):(this.element=this.manager.stage.container,this.scroller=this.element,this.element.style.WebkitOverflowScrolling="touch"),this.manager.settings.offset=this.layout.width,this.manager.settings.afterScrolledTimeout=this.settings.duration*2,this.isVertical=this.manager.settings.axis==="vertical",!(!this.manager.isPaginated||this.isVertical)&&(this.touchCanceler=!1,this.resizeCanceler=!1,this.snapping=!1,this.scrollLeft,this.scrollTop,this.startTouchX=void 0,this.startTouchY=void 0,this.startTime=void 0,this.endTouchX=void 0,this.endTouchY=void 0,this.endTime=void 0,this.addListeners())}supportsTouch(){return!!("ontouchstart"in window||window.DocumentTouch&&document instanceof window.DocumentTouch)}disableScroll(){this.element.style.overflow="hidden"}enableScroll(){this.element.style.overflow=""}addListeners(){this._onResize=this.onResize.bind(this),window.addEventListener("resize",this._onResize),this._onScroll=this.onScroll.bind(this),this.scroller.addEventListener("scroll",this._onScroll),this._onTouchStart=this.onTouchStart.bind(this),this.scroller.addEventListener("touchstart",this._onTouchStart,{passive:!0}),this.on("touchstart",this._onTouchStart),this._onTouchMove=this.onTouchMove.bind(this),this.scroller.addEventListener("touchmove",this._onTouchMove,{passive:!0}),this.on("touchmove",this._onTouchMove),this._onTouchEnd=this.onTouchEnd.bind(this),this.scroller.addEventListener("touchend",this._onTouchEnd,{passive:!0}),this.on("touchend",this._onTouchEnd),this._afterDisplayed=this.afterDisplayed.bind(this),this.manager.on(f.MANAGERS.ADDED,this._afterDisplayed)}removeListeners(){window.removeEventListener("resize",this._onResize),this._onResize=void 0,this.scroller.removeEventListener("scroll",this._onScroll),this._onScroll=void 0,this.scroller.removeEventListener("touchstart",this._onTouchStart,{passive:!0}),this.off("touchstart",this._onTouchStart),this._onTouchStart=void 0,this.scroller.removeEventListener("touchmove",this._onTouchMove,{passive:!0}),this.off("touchmove",this._onTouchMove),this._onTouchMove=void 0,this.scroller.removeEventListener("touchend",this._onTouchEnd,{passive:!0}),this.off("touchend",this._onTouchEnd),this._onTouchEnd=void 0,this.manager.off(f.MANAGERS.ADDED,this._afterDisplayed),this._afterDisplayed=void 0}afterDisplayed(t){const e=t.contents;["touchstart","touchmove","touchend"].forEach(i=>{e.on(i,s=>this.triggerViewEvent(s,e))})}triggerViewEvent(t,e){this.emit(t.type,t,e)}onScroll(t){this.scrollLeft=this.fullsize?window.scrollX:this.scroller.scrollLeft,this.scrollTop=this.fullsize?window.scrollY:this.scroller.scrollTop}onResize(t){this.resizeCanceler=!0}onTouchStart(t){const{screenX:e,screenY:i}=t.touches[0];this.fullsize&&this.enableScroll(),this.touchCanceler=!0,this.startTouchX||(this.startTouchX=e,this.startTouchY=i,this.startTime=this.now()),this.endTouchX=e,this.endTouchY=i,this.endTime=this.now()}onTouchMove(t){const{screenX:e,screenY:i}=t.touches[0],s=Math.abs(i-this.endTouchY);this.touchCanceler=!0,!this.fullsize&&s<10&&(this.element.scrollLeft-=e-this.endTouchX),this.endTouchX=e,this.endTouchY=i,this.endTime=this.now()}onTouchEnd(t){this.fullsize&&this.disableScroll(),this.touchCanceler=!1;const e=this.wasSwiped();e!==0?this.snap(e):this.snap(),this.startTouchX=void 0,this.startTouchY=void 0,this.startTime=void 0,this.endTouchX=void 0,this.endTouchY=void 0,this.endTime=void 0}wasSwiped(){const t=this.layout.pageWidth*this.layout.divisor,e=this.endTouchX-this.startTouchX,i=Math.abs(e),s=this.endTime-this.startTime,n=e/s,r=this.settings.minVelocity;return i<=this.settings.minDistance||i>=t?0:n>r?-1:n<-r?1:0}needsSnap(){const t=this.scrollLeft,e=this.layout.pageWidth*this.layout.divisor;return t%e!==0}snap(t=0){const e=this.scrollLeft,i=this.layout.pageWidth*this.layout.divisor;let s=Math.round(e/i)*i;return t&&(s+=t*i),this.smoothScrollTo(s)}smoothScrollTo(t){const e=new v,i=this.scrollLeft,s=this.now(),n=this.settings.duration,r=this.settings.easing;this.snapping=!0;const o=()=>{const h=this.now(),a=Math.min(1,(h-s)/n);if(r(a),this.touchCanceler||this.resizeCanceler){this.resizeCanceler=!1,this.snapping=!1,e.resolve();return}a<1?(window.requestAnimationFrame(o),this.scrollTo(i+(t-i)*a,0)):(this.scrollTo(t,0),this.snapping=!1,e.resolve())};return o(),e.promise}scrollTo(t=0,e=0){this.fullsize?window.scroll(t,e):(this.scroller.scrollLeft=t,this.scroller.scrollTop=e)}now(){return"now"in window.performance?performance.now():new Date().getTime()}destroy(){this.scroller&&(this.fullsize&&this.enableScroll(),this.removeListeners(),this.scroller=void 0)}}I(Ct.prototype);function Ue(l,t){let e;return function(...i){clearTimeout(e),e=setTimeout(()=>{l.call(this,...i)},t)}}class je extends ct{constructor(t){super(t),this.name="continuous",this.settings=_({},{infinite:!0,overflow:void 0,axis:void 0,writingMode:void 0,flow:"scrolled",offset:500,offsetDelta:250,width:void 0,height:void 0,snap:!1,afterScrolledTimeout:10,allowScriptedContent:!1,allowPopups:!1}),_(this.settings,t.settings||{}),t.settings.gap!="undefined"&&t.settings.gap===0&&(this.settings.gap=t.settings.gap),this.viewSettings={ignoreClass:this.settings.ignoreClass,axis:this.settings.axis,flow:this.settings.flow,layout:this.layout,width:0,height:0,forceEvenPages:!1,allowScriptedContent:this.settings.allowScriptedContent,allowPopups:this.settings.allowPopups},this.scrollTop=0,this.scrollLeft=0}display(t,e){return ct.prototype.display.call(this,t,e).then(()=>this.fill())}fill(t){const e=t||new v;return this.q.enqueue(()=>this.check()).then(i=>{i?this.fill(e):e.resolve()}),e.promise}moveTo(t){let e=0,i=0;this.isPaginated?(e=Math.floor(t.left/this.layout.delta)*this.layout.delta,e+this.settings.offsetDelta):(i=t.top,t.top+this.settings.offsetDelta),(e>0||i>0)&&this.scrollBy(e,i,!0)}afterResized(t){this.emit(f.MANAGERS.RESIZE,t.section)}removeShownListeners(t){t.onDisplayed=function(){}}add(t){const e=this.createView(t);return this.views.append(e),e.on(f.VIEWS.RESIZED,i=>{e.expanded=!0}),e.on(f.VIEWS.AXIS,i=>{this.updateAxis(i)}),e.on(f.VIEWS.WRITING_MODE,i=>{this.updateWritingMode(i)}),e.onDisplayed=i=>this.afterDisplayed(i),e.onResize=i=>this.afterResized(i),e.display(this.request)}append(t){const e=this.createView(t);return e.on(f.VIEWS.RESIZED,i=>{e.expanded=!0}),e.on(f.VIEWS.AXIS,i=>{this.updateAxis(i)}),e.on(f.VIEWS.WRITING_MODE,i=>{this.updateWritingMode(i)}),this.views.append(e),e.onDisplayed=i=>this.afterDisplayed(i),e}prepend(t){const e=this.createView(t);return e.on(f.VIEWS.RESIZED,i=>{this.counter(i),e.expanded=!0}),e.on(f.VIEWS.AXIS,i=>{this.updateAxis(i)}),e.on(f.VIEWS.WRITING_MODE,i=>{this.updateWritingMode(i)}),this.views.prepend(e),e.onDisplayed=i=>this.afterDisplayed(i),e}counter(t){this.settings.axis==="vertical"?this.scrollBy(0,t.heightDelta,!0):this.scrollBy(t.widthDelta,0,!0)}update(t){const e=this.bounds(),i=this.views.all(),s=i.length,n=typeof t<"u"?t:this.settings.offset||0;let r,o;const h=new v,a=[];for(let c=0;c<s;c++)if(o=i[c],r=this.isVisible(o,n,n,e),r===!0)if(o.displayed)o.show();else{const d=o.display(this.request).then(function(u){u.show()},u=>{o.hide()});a.push(d)}else this.q.enqueue(()=>o.destroy()),clearTimeout(this.trimTimeout),this.trimTimeout=setTimeout(()=>{this.q.enqueue(()=>this.trim())},250);return a.length?Promise.all(a).catch(c=>{h.reject(c)}):(h.resolve(),h.promise)}check(t,e){const i=new v,s=[],n=this.settings.axis==="horizontal";let r=this.settings.offset||0;t&&n&&(r=t),e&&!n&&(r=e);const o=this._bounds;let h=n?this.scrollLeft:this.scrollTop;const a=n?Math.floor(o.width):o.height,c=n?this.container.scrollWidth:this.container.scrollHeight,d=this.writingMode&&this.writingMode.indexOf("vertical")===0?"vertical":"horizontal",u=this.settings.rtlScrollType,p=this.settings.direction==="rtl";this.settings.fullsize?(n&&p&&u==="negative"||!n&&p&&u==="default")&&(h=h*-1):(p&&u==="default"&&d==="horizontal"&&(h=c-a-h),p&&u==="negative"&&d==="horizontal"&&(h=h*-1));const m=()=>{const S=this.views.first(),C=S&&S.section.prev();C&&s.push(this.prepend(C))},y=()=>{const S=this.views.last(),C=S&&S.section.next();C&&s.push(this.append(C))},b=h+a+r,E=h-r;b>=c&&y(),E<0&&m();const T=s.map(S=>S.display(this.request));return s.length?Promise.all(T).then(()=>this.check()).then(()=>this.update(r),S=>S):(this.q.enqueue(()=>{this.update()}),i.resolve(!1),i.promise)}trim(){const t=new v,e=this.views.displayed();if(!e.length)return t.resolve(),t.promise;const i=e[0],s=e[e.length-1],n=this.views.indexOf(i),r=this.views.indexOf(s),o=this.views.slice(0,n),h=this.views.slice(r+1);for(let a=0;a<o.length-1;a++)this.erase(o[a],o);for(let a=1;a<h.length;a++)this.erase(h[a]);return t.resolve(),t.promise}erase(t,e){let i,s;this.settings.fullsize?(i=window.scrollY,s=window.scrollX):(i=this.container.scrollTop,s=this.container.scrollLeft);const n=t.bounds();this.views.remove(t),e&&(this.settings.axis==="vertical"?this.scrollTo(0,i-n.height,!0):this.settings.direction==="rtl"?this.settings.fullsize?this.scrollTo(s+Math.floor(n.width),0,!0):this.scrollTo(s,0,!0):this.scrollTo(s-Math.floor(n.width),0,!0))}addEventListeners(t){this._onUnload=e=>{this.ignore=!0,this.destroy()},window.addEventListener("unload",this._onUnload),this.addScrollListeners(),this.isPaginated&&this.settings.snap&&(this.snapper=new Ct(this,typeof this.settings.snap=="object"?this.settings.snap:void 0))}addScrollListeners(){let t;this.tick=_t;const e=this.settings.direction==="rtl"&&this.settings.rtlScrollType==="default"?-1:1;this.scrollDeltaVert=0,this.scrollDeltaHorz=0,this.settings.fullsize?(t=window,this.scrollTop=window.scrollY*e,this.scrollLeft=window.scrollX*e):(t=this.container,this.scrollTop=this.container.scrollTop,this.scrollLeft=this.container.scrollLeft),this._onScroll=this.onScroll.bind(this),t.addEventListener("scroll",this._onScroll),this._scrolled=Ue(()=>this.scrolled(),30),this.didScroll=!1}removeEventListeners(){let t;this.settings.fullsize?t=window:t=this.container,t.removeEventListener("scroll",this._onScroll),this._onScroll=void 0,window.removeEventListener("unload",this._onUnload),this._onUnload=void 0}onScroll(){let t,e;const i=this.settings.direction==="rtl"&&this.settings.rtlScrollType==="default"?-1:1;this.settings.fullsize?(t=window.scrollY*i,e=window.scrollX*i):(t=this.container.scrollTop,e=this.container.scrollLeft),this.scrollTop=t,this.scrollLeft=e,this.ignore?this.ignore=!1:this._scrolled(),this.scrollDeltaVert+=Math.abs(t-this.prevScrollTop),this.scrollDeltaHorz+=Math.abs(e-this.prevScrollLeft),this.prevScrollTop=t,this.prevScrollLeft=e,clearTimeout(this.scrollTimeout),this.scrollTimeout=setTimeout(()=>{this.scrollDeltaVert=0,this.scrollDeltaHorz=0},150),clearTimeout(this.afterScrolled),this.didScroll=!1}scrolled(){this.q.enqueue(()=>this.check()),this.emit(f.MANAGERS.SCROLL,{top:this.scrollTop,left:this.scrollLeft}),clearTimeout(this.afterScrolled),this.afterScrolled=setTimeout(()=>{this.snapper&&this.snapper.supportsTouch()&&this.snapper.needsSnap()||this.emit(f.MANAGERS.SCROLLED,{top:this.scrollTop,left:this.scrollLeft})},this.settings.afterScrolledTimeout)}next(){const t=this.layout.props.name==="pre-paginated"&&this.layout.props.spread?this.layout.props.delta*2:this.layout.props.delta;this.views.length&&(this.isPaginated&&this.settings.axis==="horizontal"?this.scrollBy(t,0,!0):this.scrollBy(0,this.layout.height,!0),this.q.enqueue(()=>this.check()))}prev(){const t=this.layout.props.name==="pre-paginated"&&this.layout.props.spread?this.layout.props.delta*2:this.layout.props.delta;this.views.length&&(this.isPaginated&&this.settings.axis==="horizontal"?this.scrollBy(-t,0,!0):this.scrollBy(0,-this.layout.height,!0),this.q.enqueue(()=>this.check()))}updateFlow(t){this.rendered&&this.snapper&&(this.snapper.destroy(),this.snapper=void 0),super.updateFlow(t,"scroll"),this.rendered&&this.isPaginated&&this.settings.snap&&(this.snapper=new Ct(this,typeof this.settings.snap=="object"?this.settings.snap:void 0))}destroy(){super.destroy(),this.snapper&&this.snapper.destroy()}}class pt{constructor(t,e){this.settings=_({},{width:null,height:null,ignoreClass:"",manager:"default",view:"iframe",flow:null,layout:null,spread:null,minSpreadWidth:800,stylesheet:null,resizeOnOrientationChange:!0,script:null,snap:!1,defaultDirection:"ltr",allowScriptedContent:!1,allowPopups:!1}),_(this.settings,e),typeof this.settings.manager=="object"&&(this.manager=this.settings.manager),this.book=t,this.hooks={},this.hooks.display=new N(this),this.hooks.serialize=new N(this),this.hooks.content=new N(this),this.hooks.unloaded=new N(this),this.hooks.layout=new N(this),this.hooks.render=new N(this),this.hooks.show=new N(this),this.hooks.content.register(i=>this.handleLinks(i)),this.hooks.content.register(i=>this.passEvents(i)),this.hooks.content.register(i=>this.adjustImages(i)),this.book.spine.hooks.content.register((i,s)=>this.injectIdentifier(i,s)),this.settings.stylesheet&&this.book.spine.hooks.content.register((i,s)=>this.injectStylesheet(i,s)),this.settings.script&&this.book.spine.hooks.content.register((i,s)=>this.injectScript(i,s)),this.themes=new Zt(this),this.annotations=new Jt(this),this.epubcfi=new g,this.q=new Lt(this),this.location=void 0,this.q.enqueue(this.book.opened),this.starting=new v,this.started=this.starting.promise,this.q.enqueue(this.start)}setManager(t){this.manager=t}requireManager(t){let e;return typeof t=="string"&&t==="default"?e=ct:typeof t=="string"&&t==="continuous"?e=je:e=t,e}requireView(t){let e;return typeof t=="string"&&t==="iframe"?e=ie:e=t,e}start(){switch(!this.settings.layout&&(this.book.package.metadata.layout==="pre-paginated"||this.book.displayOptions.fixedLayout==="true")&&(this.settings.layout="pre-paginated"),this.book.package.metadata.spread){case"none":this.settings.spread="none";break;case"both":this.settings.spread=!0;break}this.manager||(this.ViewManager=this.requireManager(this.settings.manager),this.View=this.requireView(this.settings.view),this.manager=new this.ViewManager({view:this.View,queue:this.q,request:this.book.load.bind(this.book),settings:this.settings})),this.direction(this.book.package.metadata.direction||this.settings.defaultDirection),this.settings.globalLayoutProperties=this.determineLayoutProperties(this.book.package.metadata),this.flow(this.settings.globalLayoutProperties.flow),this.layout(this.settings.globalLayoutProperties),this.manager.on(f.MANAGERS.ADDED,t=>this.afterDisplayed(t)),this.manager.on(f.MANAGERS.REMOVED,t=>this.afterRemoved(t)),this.manager.on(f.MANAGERS.RESIZED,(t,e)=>this.onResized(t,e)),this.manager.on(f.MANAGERS.ORIENTATION_CHANGE,t=>this.onOrientationChange(t)),this.manager.on(f.MANAGERS.SCROLLED,()=>this.reportLocation()),this.emit(f.RENDITION.STARTED),this.starting.resolve()}attachTo(t){return this.q.enqueue(()=>{this.manager.render(t,{width:this.settings.width,height:this.settings.height}),this.emit(f.RENDITION.ATTACHED)})}display(t){return this.displaying&&this.displaying.resolve(),this.q.enqueue(this._display,t)}_display(t){if(!this.book)return;this.epubcfi.isCfiString(t);const e=new v,i=e.promise;this.displaying=e,this.book.locations.length()&&Bt(t)&&(t=this.book.locations.cfiFromPercentage(parseFloat(t)));const s=this.book.spine.get(t);return s?(this.manager.display(s,t).then(()=>{e.resolve(s),this.displaying=void 0,this.emit(f.RENDITION.DISPLAYED,s),this.reportLocation()},n=>{this.emit(f.RENDITION.DISPLAY_ERROR,n)}),i):(e.reject(new Error("No Section Found")),i)}afterDisplayed(t){t.on(f.VIEWS.MARK_CLICKED,(e,i)=>{t.contents&&this.triggerMarkEvent(e,i,t.contents)}),this.hooks.render.trigger(t,this).then(()=>{t.contents?this.hooks.content.trigger(t.contents,this).then(()=>{this.emit(f.RENDITION.RENDERED,t.section,t)}):this.emit(f.RENDITION.RENDERED,t.section,t)})}afterRemoved(t){this.hooks.unloaded.trigger(t,this).then(()=>{this.emit(f.RENDITION.REMOVED,t.section,t)})}onResized(t,e){this.emit(f.RENDITION.RESIZED,{width:t.width,height:t.height},e),this.location&&this.location.start&&this.display(e||this.location.start.cfi)}onOrientationChange(t){this.emit(f.RENDITION.ORIENTATION_CHANGE,t)}moveTo(t){this.manager.moveTo(t)}resize(t,e,i){t&&(this.settings.width=t),e&&(this.settings.height=e),this.manager.resize(t,e,i)}clear(){this.manager.clear()}next(){return this.q.enqueue(()=>this.manager.next()).then(()=>this.reportLocation())}prev(){return this.q.enqueue(()=>this.manager.prev()).then(()=>this.reportLocation())}determineLayoutProperties(t){const e=this.settings.layout||t.layout||"reflowable",i=this.settings.spread||t.spread||"auto",s=this.settings.orientation||t.orientation||"auto",n=this.settings.flow||t.flow||"auto",r=t.viewport||"",o=this.settings.minSpreadWidth||t.minSpreadWidth||800,h=this.settings.direction||t.direction||"ltr";return(this.settings.width===0||this.settings.width>0)&&(this.settings.height===0||this.settings.height>0),{layout:e,spread:i,orientation:s,flow:n,viewport:r,minSpreadWidth:o,direction:h}}flow(t){let e=t;(t==="scrolled"||t==="scrolled-doc"||t==="scrolled-continuous")&&(e="scrolled"),(t==="auto"||t==="paginated")&&(e="paginated"),this.settings.flow=t,this._layout&&this._layout.flow(e),this.manager&&this._layout&&this.manager.applyLayout(this._layout),this.manager&&this.manager.updateFlow(e),this.manager&&this.manager.isRendered()&&this.location&&(this.manager.clear(),this.display(this.location.start.cfi))}layout(t){return t&&(this._layout=new Rt(t),this._layout.spread(t.spread,this.settings.minSpreadWidth),this._layout.on(f.LAYOUT.UPDATED,(e,i)=>{this.emit(f.RENDITION.LAYOUT,e,i)})),this.manager&&this._layout&&this.manager.applyLayout(this._layout),this._layout}spread(t,e){this.settings.spread=t,e&&(this.settings.minSpreadWidth=e),this._layout&&this._layout.spread(t,e),this.manager&&this.manager.isRendered()&&this.manager.updateLayout()}direction(t){this.settings.direction=t||"ltr",this.manager&&this.manager.direction(this.settings.direction),this.manager&&this.manager.isRendered()&&this.location&&(this.manager.clear(),this.display(this.location.start.cfi))}reportLocation(){return this.q.enqueue(()=>{requestAnimationFrame(()=>{const t=this.manager.currentLocation();if(t&&t.then&&typeof t.then=="function")t.then(e=>{const i=this.located(e);!i||!i.start||!i.end||(this.location=i,this.emit(f.RENDITION.LOCATION_CHANGED,{index:this.location.start.index,href:this.location.start.href,start:this.location.start.cfi,end:this.location.end.cfi,percentage:this.location.start.percentage}),this.emit(f.RENDITION.RELOCATED,this.location))});else if(t){const e=this.located(t);if(!e||!e.start||!e.end)return;this.location=e,this.emit(f.RENDITION.LOCATION_CHANGED,{index:this.location.start.index,href:this.location.start.href,start:this.location.start.cfi,end:this.location.end.cfi,percentage:this.location.start.percentage}),this.emit(f.RENDITION.RELOCATED,this.location)}})})}currentLocation(){const t=this.manager.currentLocation();if(t&&t.then&&typeof t.then=="function")t.then(e=>this.located(e));else if(t)return this.located(t)}located(t){if(!t.length)return;const e=t[0],i=t[t.length-1],s={start:{index:e.index,href:e.href,cfi:e.mapping.start,displayed:{page:e.pages[0]||1,total:e.totalPages}},end:{index:i.index,href:i.href,cfi:i.mapping.end,displayed:{page:i.pages[i.pages.length-1]||1,total:i.totalPages}}},n=this.book.locations.locationFromCfi(e.mapping.start),r=this.book.locations.locationFromCfi(i.mapping.end);n!=null&&(s.start.location=n,s.start.percentage=this.book.locations.percentageFromLocation(n)),r!=null&&(s.end.location=r,s.end.percentage=this.book.locations.percentageFromLocation(r));const o=this.book.pageList.pageFromCfi(e.mapping.start),h=this.book.pageList.pageFromCfi(i.mapping.end);return o!=-1&&(s.start.page=o),h!=-1&&(s.end.page=h),i.index===this.book.spine.last().index&&s.end.displayed.page>=s.end.displayed.total&&(s.atEnd=!0),e.index===this.book.spine.first().index&&s.start.displayed.page===1&&(s.atStart=!0),s}destroy(){this.q.clear(),this.manager&&(this.manager.destroy(),this.manager=void 0),this.book=void 0,this.hooks.display.clear(),this.hooks.serialize.clear(),this.hooks.content.clear(),this.hooks.unloaded.clear(),this.hooks.layout.clear(),this.hooks.render.clear(),this.hooks.show.clear(),this.themes.destroy(),this._layout=void 0,this.location=void 0}passEvents(t){Q.forEach(e=>{t.on(e,i=>this.triggerViewEvent(i,t))}),t.on(f.CONTENTS.SELECTED,e=>this.triggerSelectedEvent(e,t))}triggerViewEvent(t,e){this.emit(t.type,t,e)}triggerSelectedEvent(t,e){this.emit(f.RENDITION.SELECTED,t,e)}triggerMarkEvent(t,e,i){this.emit(f.RENDITION.MARK_CLICKED,t,e,i)}getRange(t,e){const i=new g(t),s=this.manager.visible().filter(function(n){return i.spinePos===n.index});if(s.length)return s[0].contents.range(i,e)}adjustImages(t){if(this._layout.name==="pre-paginated")return new Promise(function(n){n()});const e=t.window.getComputedStyle(t.content,null),i=(t.content.offsetHeight-(parseFloat(e.paddingTop)+parseFloat(e.paddingBottom)))*.95,s=parseFloat(e.paddingLeft)+parseFloat(e.paddingRight);return t.addStylesheetRules({img:{"max-width":(this._layout.columnWidth?this._layout.columnWidth-s+"px":"100%")+"!important","max-height":i+"px!important","object-fit":"contain","page-break-inside":"avoid","break-inside":"avoid","box-sizing":"border-box"},svg:{"max-width":(this._layout.columnWidth?this._layout.columnWidth-s+"px":"100%")+"!important","max-height":i+"px!important","page-break-inside":"avoid","break-inside":"avoid"}}),new Promise(function(n,r){setTimeout(function(){n()},1)})}getContents(){return this.manager?this.manager.getContents():[]}views(){return(this.manager?this.manager.views:void 0)||[]}handleLinks(t){t&&t.on(f.CONTENTS.LINK_CLICKED,e=>{const i=this.book.path.relative(e);this.display(i)})}injectStylesheet(t,e){const i=t.createElement("link");i.setAttribute("type","text/css"),i.setAttribute("rel","stylesheet"),i.setAttribute("href",this.settings.stylesheet),t.getElementsByTagName("head")[0].appendChild(i)}injectScript(t,e){const i=t.createElement("script");i.setAttribute("type","text/javascript"),i.setAttribute("src",this.settings.script),i.textContent=" ",t.getElementsByTagName("head")[0].appendChild(i)}injectIdentifier(t,e){const i=this.book.packaging.metadata.identifier,s=t.createElement("meta");s.setAttribute("name","dc.relation.ispartof"),i&&s.setAttribute("content",i),t.getElementsByTagName("head")[0].appendChild(s)}}I(pt.prototype);class se{constructor(){this.zip=void 0,this.urlCache={},this.checkRequirements()}checkRequirements(){try{this.zip=new ne}catch{throw new Error("JSZip lib not loaded")}}open(t,e){return this.zip.loadAsync(t,{base64:e})}openUrl(t,e){return $(t,"binary").then(i=>this.zip.loadAsync(i,{base64:e}))}request(t,e){const i=new v;let s;const n=new P(t);return e||(e=n.extension),e=="blob"?s=this.getBlob(t):s=this.getText(t),s?s.then(r=>{const o=this.handleResponse(r,e);i.resolve(o)}):i.reject({message:"File not found in the epub: "+t,stack:new Error().stack}),i.promise}handleResponse(t,e){let i;return e=="json"?i=JSON.parse(t):G(e)?i=A(t,"text/xml"):e=="xhtml"?i=A(t,"application/xhtml+xml"):e=="html"||e=="htm"?i=A(t,"text/html"):i=t,i}getBlob(t,e){const i=window.decodeURIComponent(t.substr(1)),s=this.zip.file(i);if(s)return e=e||H.lookup(s.name),s.async("uint8array").then(function(n){return new Blob([n],{type:e})})}getText(t,e){const i=window.decodeURIComponent(t.substr(1)),s=this.zip.file(i);if(s)return s.async("string").then(function(n){return n})}getBase64(t,e){const i=window.decodeURIComponent(t.substr(1)),s=this.zip.file(i);if(s)return e=e||H.lookup(s.name),s.async("base64").then(function(n){return"data:"+e+";base64,"+n})}createUrl(t,e){const i=new v,s=window.URL||window.webkitURL||window.mozURL;let n,r;const o=e&&e.base64;return t in this.urlCache?(i.resolve(this.urlCache[t]),i.promise):(o?(r=this.getBase64(t),r&&r.then(h=>{this.urlCache[t]=h,i.resolve(h)})):(r=this.getBlob(t),r&&r.then(h=>{n=s.createObjectURL(h),this.urlCache[t]=n,i.resolve(n)})),r||i.reject({message:"File not found in the epub: "+t,stack:new Error().stack}),i.promise)}revokeUrl(t){const e=window.URL||window.webkitURL||window.mozURL,i=this.urlCache[t];i&&e.revokeObjectURL(i)}destroy(){const t=window.URL||window.webkitURL||window.mozURL;for(const e in this.urlCache)t.revokeObjectURL(e);this.zip=void 0,this.urlCache={}}}function Fe(l){return new Promise((t,e)=>{const i=indexedDB.open(l,1);i.onupgradeneeded=()=>{i.result.createObjectStore("data")},i.onsuccess=()=>t(i.result),i.onerror=()=>e(i.error)})}function He(l){const t=Fe(l);return{getItem(e){return t.then(i=>new Promise((s,n)=>{const o=i.transaction("data","readonly").objectStore("data").get(e);o.onsuccess=()=>s(o.result??null),o.onerror=()=>n(o.error)}))},setItem(e,i){return t.then(s=>new Promise((n,r)=>{const h=s.transaction("data","readwrite").objectStore("data").put(i,e);h.onsuccess=()=>n(i),h.onerror=()=>r(h.error)}))}}}class Nt{constructor(t,e,i){this.urlCache={},this.name=t,this.requester=e||$,this.resolver=i,this.online=!0,this.checkRequirements(),this.addListeners()}checkRequirements(){try{if(typeof indexedDB>"u")throw new Error("IndexedDB not available");this.storage=He(this.name)}catch{throw new Error("IndexedDB not available")}}addListeners(){this._status=this.status.bind(this),window.addEventListener("online",this._status),window.addEventListener("offline",this._status)}removeListeners(){window.removeEventListener("online",this._status),window.removeEventListener("offline",this._status),this._status=void 0}status(t){const e=navigator.onLine;this.online=e,e?this.emit("online",this):this.emit("offline",this)}add(t,e){const i=t.resources.map(s=>{const{href:n}=s,r=this.resolver(n),o=window.encodeURIComponent(r);return this.storage.getItem(o).then(h=>!h||e?this.requester(r,"binary").then(a=>this.storage.setItem(o,a)):h)});return Promise.all(i)}put(t,e,i){const s=window.encodeURIComponent(t);return this.storage.getItem(s).then(n=>n||this.requester(t,"binary",e,i).then(r=>this.storage.setItem(s,r)))}request(t,e,i,s){return this.online?this.requester(t,e,i,s).then(n=>(this.put(t),n)):this.retrieve(t,e)}retrieve(t,e){let i;const s=new P(t);return e||(e=s.extension),e=="blob"?i=this.getBlob(t):i=this.getText(t),i.then(n=>{const r=new v;let o;return n?(o=this.handleResponse(n,e),r.resolve(o)):r.reject({message:"File not found in storage: "+t,stack:new Error().stack}),r.promise})}handleResponse(t,e){let i;return e=="json"?i=JSON.parse(t):G(e)?i=A(t,"text/xml"):e=="xhtml"?i=A(t,"application/xhtml+xml"):e=="html"||e=="htm"?i=A(t,"text/html"):i=t,i}getBlob(t,e){const i=window.encodeURIComponent(t);return this.storage.getItem(i).then(function(s){if(s)return e=e||H.lookup(t),new Blob([s],{type:e})})}getText(t,e){const i=window.encodeURIComponent(t);return e=e||H.lookup(t),this.storage.getItem(i).then(function(s){const n=new v,r=new FileReader;if(!s)return;const o=new Blob([s],{type:e});return r.addEventListener("loadend",()=>{n.resolve(r.result)}),r.readAsText(o,e),n.promise})}getBase64(t,e){const i=window.encodeURIComponent(t);return e=e||H.lookup(t),this.storage.getItem(i).then(s=>{const n=new v,r=new FileReader;if(!s)return;const o=new Blob([s],{type:e});return r.addEventListener("loadend",()=>{n.resolve(r.result)}),r.readAsDataURL(o),n.promise})}createUrl(t,e){const i=new v,s=window.URL||window.webkitURL||window.mozURL;let n,r;const o=e&&e.base64;return t in this.urlCache?(i.resolve(this.urlCache[t]),i.promise):(o?(r=this.getBase64(t),r&&r.then(h=>{h&&(this.urlCache[t]=h,i.resolve(h))})):(r=this.getBlob(t),r&&r.then(h=>{h&&(n=s.createObjectURL(h),this.urlCache[t]=n,i.resolve(n))})),r||i.reject({message:"File not found in storage: "+t,stack:new Error().stack}),i.promise)}revokeUrl(t){const e=window.URL||window.webkitURL||window.mozURL,i=this.urlCache[t];i&&e.revokeObjectURL(i)}destroy(){const t=window.URL||window.webkitURL||window.mozURL;for(const e in this.urlCache)t.revokeObjectURL(e);this.urlCache={},this.removeListeners()}}I(Nt.prototype);class it{constructor(t){this.interactive="",this.fixedLayout="",this.openToSpread="",this.orientationLock="",t&&this.parse(t)}parse(t){if(!t)return this;const e=w(t,"display_options");return e?(B(e,"option").forEach(s=>{let n="";switch(s.childNodes.length&&(n=s.childNodes[0].nodeValue??""),s.attributes.name.value){case"interactive":this.interactive=n;break;case"fixed-layout":this.fixedLayout=n;break;case"open-to-spread":this.openToSpread=n;break;case"orientation-lock":this.orientationLock=n;break}}),this):this}destroy(){this.interactive=void 0,this.fixedLayout=void 0,this.openToSpread=void 0,this.orientationLock=void 0}}const Pt="META-INF/container.xml",Ve="META-INF/com.apple.ibooks.display-options.xml",k={BINARY:"binary",BASE64:"base64",EPUB:"epub",OPF:"opf",MANIFEST:"json",DIRECTORY:"directory"};class gt{constructor(t,e){typeof e>"u"&&typeof t!="string"&&!(t instanceof Blob)&&!(t instanceof ArrayBuffer)&&(e=t,t=void 0),this.settings=_({},{requestMethod:void 0,requestCredentials:void 0,requestHeaders:void 0,encoding:void 0,replacements:void 0,canonical:void 0,openAs:void 0,store:void 0}),_(this.settings,e),this.opening=new v,this.opened=this.opening.promise,this.isOpen=!1,this.loading={manifest:new v,spine:new v,metadata:new v,cover:new v,navigation:new v,pageList:new v,resources:new v,displayOptions:new v},this.loaded={manifest:this.loading.manifest.promise,spine:this.loading.spine.promise,metadata:this.loading.metadata.promise,cover:this.loading.cover.promise,navigation:this.loading.navigation.promise,pageList:this.loading.pageList.promise,resources:this.loading.resources.promise,displayOptions:this.loading.displayOptions.promise},this.ready=Promise.all([this.loaded.manifest,this.loaded.spine,this.loaded.metadata,this.loaded.cover,this.loaded.navigation,this.loaded.resources,this.loaded.displayOptions]),this.isRendered=!1,this.request=this.settings.requestMethod||$,this.spine=new $t,this.locations=new kt(this.spine,i=>this.load(i)),this.navigation=void 0,this.pageList=void 0,this.url=void 0,this.path=void 0,this.archived=!1,this.archive=void 0,this.storage=void 0,this.resources=void 0,this.rendition=void 0,this.container=void 0,this.packaging=void 0,this.displayOptions=void 0,this.settings.store&&this.store(this.settings.store),t&&this.open(t,this.settings.openAs).catch(i=>{const s=new Error("Cannot load book at "+t);this.emit(f.BOOK.OPEN_FAILED,s)})}open(t,e){let i;const s=e||this.determineType(t);return s===k.BINARY?(this.archived=!0,this.url=new R("/",""),i=this.openEpub(t)):s===k.BASE64?(this.archived=!0,this.url=new R("/",""),i=this.openEpub(t,s)):s===k.EPUB?(this.archived=!0,this.url=new R("/",""),i=this.request(t,"binary",this.settings.requestCredentials,this.settings.requestHeaders).then(n=>this.openEpub(n))):s==k.OPF?(this.url=new R(t),i=this.openPackaging(this.url.Path.toString())):s==k.MANIFEST?(this.url=new R(t),i=this.openManifest(this.url.Path.toString())):(this.url=new R(t),i=this.openContainer(Pt).then(n=>this.openPackaging(n))),i}openEpub(t,e){return this.unarchive(t,e||this.settings.encoding).then(()=>this.openContainer(Pt)).then(i=>this.openPackaging(i))}openContainer(t){return this.load(t).then(e=>(this.container=new xe(e),this.resolve(this.container.packagePath)))}openPackaging(t){return this.path=new P(t),this.load(t).then(e=>(this.packaging=new St(e),this.unpack(this.packaging)))}openManifest(t){return this.path=new P(t),this.load(t).then(e=>(this.packaging=new St,this.packaging.load(e),this.unpack(this.packaging)))}load(t,e){const i=this.resolve(t);return this.archived?this.archive.request(i):this.request(i,void 0,this.settings.requestCredentials,this.settings.requestHeaders)}resolve(t,e){if(!t)return"";let i=t;return t.indexOf("://")>-1?t:(this.path&&(i=this.path.resolve(t)),e!=!1&&this.url&&(i=this.url.resolve(i)),i)}canonical(t){let e=t;return t?(this.settings.canonical?e=this.settings.canonical(t):e=this.resolve(t,!0),e):""}determineType(t){let e;return this.settings.encoding==="base64"?k.BASE64:typeof t!="string"?k.BINARY:(e=new R(t).path().extension,e&&(e=e.replace(/\?.*$/,"")),e?e==="epub"?k.EPUB:e==="opf"?k.OPF:e==="json"?k.MANIFEST:k.BINARY:k.DIRECTORY)}unpack(t){this.package=t,this.packaging.metadata.layout===""?this.load(this.url.resolve(Ve)).then(e=>{this.displayOptions=new it(e),this.loading.displayOptions.resolve(this.displayOptions)}).catch(e=>{this.displayOptions=new it,this.loading.displayOptions.resolve(this.displayOptions)}):(this.displayOptions=new it,this.loading.displayOptions.resolve(this.displayOptions)),this.spine.unpack(this.packaging,(e,i)=>this.resolve(e,i),e=>this.canonical(e)),this.resources=new Kt(this.packaging.manifest,{archive:this.archive,resolver:(e,i)=>this.resolve(e,i),request:(e,i)=>this.request(e,i),replacements:this.settings.replacements||(this.archived?"blobUrl":"base64")}),this.loadNavigation(this.packaging).then(()=>{this.loading.navigation.resolve(this.navigation)}),this.packaging.coverPath&&(this.cover=this.resolve(this.packaging.coverPath)),this.loading.manifest.resolve(this.packaging.manifest),this.loading.metadata.resolve(this.packaging.metadata),this.loading.spine.resolve(this.spine),this.loading.cover.resolve(this.cover),this.loading.resources.resolve(this.resources),this.loading.pageList.resolve(this.pageList),this.isOpen=!0,this.archived||this.settings.replacements&&this.settings.replacements!="none"?this.replacements().then(()=>{this.loaded.displayOptions.then(()=>{this.opening.resolve(this)})}).catch(e=>{console.error(e)}):this.loaded.displayOptions.then(()=>{this.opening.resolve(this)})}loadNavigation(t){const e=t.navPath||t.ncxPath,i=t.toc;return i?new Promise((s,n)=>{this.navigation=new tt(i),t.pageList&&(this.pageList=new et(t.pageList)),s(this.navigation)}):e?this.load(e,"xml").then(s=>(this.navigation=new tt(s),this.pageList=new et(s),this.navigation)):new Promise((s,n)=>{this.navigation=new tt,this.pageList=new et,s(this.navigation)})}section(t){return this.spine.get(t)}renderTo(t,e){return this.rendition=new pt(this,e),this.rendition.attachTo(t),this.rendition}setRequestCredentials(t){this.settings.requestCredentials=t}setRequestHeaders(t){this.settings.requestHeaders=t}unarchive(t,e){return this.archive=new se,this.archive.open(t,e==="base64")}store(t){const e=this.settings.replacements&&this.settings.replacements!=="none",i=this.url,s=this.settings.requestMethod||((n,r)=>$(n,r));return this.storage=new Nt(t,s,(n,r)=>this.resolve(n,r)),this.request=(n,r)=>this.storage.request(n,r),this.opened.then(()=>{this.archived&&(this.storage.requester=(r,o)=>this.archive.request(r,o));const n=(r,o)=>{o.output=this.resources.substitute(r,o.url)};this.resources.settings.replacements=e||"blobUrl",this.resources.replacements().then(()=>this.resources.replaceCss()),this.storage.on("offline",()=>{this.url=new R("/",""),this.spine.hooks.serialize.register(n)}),this.storage.on("online",()=>{this.url=i,this.spine.hooks.serialize.deregister(n)})}),this.storage}coverUrl(){return this.loaded.cover.then(()=>this.cover?this.archived?this.archive.createUrl(this.cover):this.cover:null)}replacements(){return this.spine.hooks.serialize.register((t,e)=>{e.output=this.resources.substitute(t,e.url)}),this.resources.replacements().then(()=>this.resources.replaceCss()).then(()=>{})}getRange(t){const e=new g(t),i=this.spine.get(e.spinePos),s=n=>this.load(n);return i?i.load(s).then(function(n){return e.toRange(i.document)}):new Promise((n,r)=>{r("CFI could not be found")})}key(t){const e=t||this.packaging.metadata.identifier||this.url.filename;return`epubjs:${ut}:${e}`}destroy(){this.opened=void 0,this.loading=void 0,this.loaded=void 0,this.ready=void 0,this.isOpen=!1,this.isRendered=!1,this.spine&&this.spine.destroy(),this.locations&&this.locations.destroy(),this.pageList&&this.pageList.destroy(),this.archive&&this.archive.destroy(),this.resources&&this.resources.destroy(),this.container&&this.container.destroy(),this.packaging&&this.packaging.destroy(),this.rendition&&this.rendition.destroy(),this.displayOptions&&this.displayOptions.destroy(),this.spine=void 0,this.locations=void 0,this.pageList=void 0,this.archive=void 0,this.resources=void 0,this.container=void 0,this.packaging=void 0,this.rendition=void 0,this.navigation=void 0,this.url=void 0,this.path=void 0,this.archived=!1}}I(gt.prototype);function W(l,t){return new gt(l,t)}W.VERSION=ut;typeof global<"u"&&(globalThis.EPUBJS_VERSION=ut);W.Book=gt;W.Rendition=pt;W.Contents=ft;W.CFI=g;W.utils=de;exports.Annotations=Jt;exports.Archive=se;exports.Book=gt;exports.Contents=ft;exports.DisplayOptions=it;exports.EpubCFI=g;exports.Layout=Rt;exports.Locations=kt;exports.Mapping=at;exports.Navigation=tt;exports.Packaging=St;exports.PageList=et;exports.Rendition=pt;exports.Resources=Kt;exports.Section=Gt;exports.Spine=$t;exports.Store=Nt;exports.Themes=Zt;exports.default=W;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const re=require("jszip");function P(l){const t=typeof l=="function"?l.prototype:l;return t.on=function(e,i){return this.__listeners||(this.__listeners={}),this.__listeners[e]||(this.__listeners[e]=[]),this.__listeners[e].push(i),this},t.off=function(e,i){return!this.__listeners||!this.__listeners[e]?this:(i?this.__listeners[e]=this.__listeners[e].filter(function(s){return s!==i}):delete this.__listeners[e],this)},t.emit=function(e,...i){if(!this.__listeners||!this.__listeners[e])return;const s=this.__listeners[e].slice();for(let n=0;n<s.length;n++)s[n](...i)},l}const Tt=typeof window<"u"?window.requestAnimationFrame.bind(window):!1,oe=1,he=3,Dt=typeof URL<"u"?URL:typeof window<"u"?window.URL:void 0;function dt(){let l=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const i=(l+Math.random()*16)%16|0;return l=Math.floor(l/16),(e=="x"?i:i&7|8).toString(16)})}function le(){return Math.max(document.documentElement.clientHeight,document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight)}function Bt(l){return!!(l&&l.nodeType==1)}function E(l){return!isNaN(parseFloat(l))&&isFinite(l)}function Mt(l){const t=parseFloat(l);return E(l)===!1?!1:typeof l=="string"&&l.indexOf(".")>-1?!0:Math.floor(t)!==t}function j(l){const t=["Webkit","webkit","Moz","O","ms"],e=["-webkit-","-webkit-","-moz-","-o-","-ms-"],i=l.toLowerCase(),s=t.length;if(typeof document>"u"||i in document.body.style)return l;for(let n=0;n<s;n++)if(e[n]+i in document.body.style)return e[n]+i;return l}function qt(l,...t){for(let e=0;e<t.length;e++){const i=t[e];for(const s in i)l[s]===void 0&&(l[s]=i[s])}return l}function _(l,...t){return t.forEach(function(e){e&&Object.getOwnPropertyNames(e).forEach(function(i){Object.defineProperty(l,i,Object.getOwnPropertyDescriptor(e,i))})}),l}function ae(l,t,e){const i=X(l,t,e);return t.splice(i,0,l),i}function X(l,t,e,i,s){const n=i||0,r=s||t.length,o=Math.floor(n+(r-n)/2);if(e||(e=function(a,c){return a>c?1:a<c?-1:0}),r-n<=0)return o;const h=e(t[o],l);return r-n===1?h>=0?o:o+1:h===0?o:h===-1?X(l,t,e,o,r):X(l,t,e,n,o)}function st(l,t,e,i,s){const n=i||0,r=s||t.length,o=Math.floor(n+(r-n)/2);if(e||(e=function(a,c){return a>c?1:a<c?-1:0}),r-n<=0)return-1;const h=e(t[o],l);return r-n===1?h===0?o:-1:h===0?o:h===-1?st(l,t,e,o,r):st(l,t,e,n,o)}function J(l){const t=window.getComputedStyle(l),e=["width","padding-right","padding-left","margin-right","margin-left","border-right-width","border-left-width"],i=["height","padding-top","padding-bottom","margin-top","margin-bottom","border-top-width","border-bottom-width"];let s=0,n=0;return e.forEach(function(r){s+=parseFloat(t.getPropertyValue(r))||0}),i.forEach(function(r){n+=parseFloat(t.getPropertyValue(r))||0}),{height:n,width:s}}function nt(l){const t=window.getComputedStyle(l),e=["padding-right","padding-left","margin-right","margin-left","border-right-width","border-left-width"],i=["padding-top","padding-bottom","margin-top","margin-bottom","border-top-width","border-bottom-width"];let s=0,n=0;return e.forEach(function(r){s+=parseFloat(t.getPropertyValue(r))||0}),i.forEach(function(r){n+=parseFloat(t.getPropertyValue(r))||0}),{height:n,width:s}}function wt(l){let t;const e=l.ownerDocument;if(l.nodeType==Node.TEXT_NODE){const i=e.createRange();i.selectNodeContents(l),t=i.getBoundingClientRect()}else t=l.getBoundingClientRect();return t}function rt(){const l=window.innerWidth,t=window.innerHeight;return{top:0,left:0,right:l,bottom:t,width:l,height:t}}function kt(l,t){const i=l.parentNode.childNodes;let s,n=-1;for(let r=0;r<i.length&&(s=i[r],s.nodeType===t&&n++,s!=l);r++);return n}function ce(l){return kt(l,he)}function Wt(l){return kt(l,oe)}function $(l){return["xml","opf","ncx"].indexOf(l)>-1}function Ut(l,t){return new Blob([l],{type:t})}function ot(l,t){const e=Ut(l,t);return Dt.createObjectURL(e)}function jt(l){return Dt.revokeObjectURL(l)}function bt(l,t){if(typeof l!="string")return;const e=btoa(l);return"data:"+t+";base64,"+e}function Ft(l){return Object.prototype.toString.call(l).slice(8,-1)}function O(l,t){return l.charCodeAt(0)===65279&&(l=l.slice(1)),new DOMParser().parseFromString(l,t)}function b(l,t){if(!l)throw new Error("No Element Provided");return l.querySelector(t)}function M(l,t){return l.querySelectorAll(t)}function F(l,t,e){t+="[";for(const i in e)t+=i+"~='"+e[i]+"'";return t+="]",l.querySelector(t)??void 0}function ht(l,t){Vt(l,t,NodeFilter.SHOW_TEXT)}function Vt(l,t,e){const i=document.createTreeWalker(l,e,null);let s;for(;s=i.nextNode();)t(s)}function Ht(l,t,e){if(t(l))return!0;let i=l.firstChild;if(i)do{if(Ht(i,t))return!0;i=i.nextSibling}while(i)}function Xt(l){return new Promise(function(t,e){const i=new FileReader;i.readAsDataURL(l),i.onloadend=function(){t(i.result)}})}class y{constructor(){this.id=dt(),this.promise=new Promise((t,e)=>{this.resolve=t,this.reject=e}),Object.freeze(this)}}function lt(l,t,e){const i=l.querySelector(`${t}[*|type="${e}"]`);if(i)return i;const s=l.querySelectorAll(t);for(let n=0;n<s.length;n++)if(s[n].getAttributeNS("http://www.idpf.org/2007/ops","type")===e||s[n].getAttribute("epub:type")===e)return s[n]}function xt(l){const t=[],e=l.childNodes;for(let i=0;i<e.length;i++){const s=e[i];s.nodeType===1&&t.push(s)}return t}function Et(l){const t=[];for(let e=l??null;e;e=e.parentNode)t.unshift(e);return t}function V(l,t,e){const i=[],s=l.childNodes;for(let n=0;n<s.length;n++){const r=s[n];if(r.nodeType===1&&r.nodeName.toLowerCase()===t){if(e)return r;i.push(r)}}if(!e)return i}function de(l,t){let e;if(!(l===null||t===""))for(e=l.parentNode;e&&e.nodeType===1;){if(e.tagName.toLowerCase()===t)return e;e=e.parentNode}}class Gt{constructor(){this.collapsed=!1,this.commonAncestorContainer=void 0,this.endContainer=void 0,this.endOffset=void 0,this.startContainer=void 0,this.startOffset=void 0}setStart(t,e){this.startContainer=t,this.startOffset=e,this.endContainer?this.commonAncestorContainer=this._commonAncestorContainer():this.collapse(!0),this._checkCollapsed()}setEnd(t,e){this.endContainer=t,this.endOffset=e,this.startContainer?(this.collapsed=!1,this.commonAncestorContainer=this._commonAncestorContainer()):this.collapse(!1),this._checkCollapsed()}collapse(t){var e,i;this.collapsed=!0,t?(this.endContainer=this.startContainer,this.endOffset=this.startOffset,this.commonAncestorContainer=((e=this.startContainer)==null?void 0:e.parentNode)??void 0):(this.startContainer=this.endContainer,this.startOffset=this.endOffset,this.commonAncestorContainer=((i=this.endContainer)==null?void 0:i.parentNode)??void 0)}selectNode(t){const e=t.parentNode,i=Array.from(e.childNodes).indexOf(t);this.setStart(e,i),this.setEnd(e,i+1)}selectNodeContents(t){const e=t.nodeType===3?(t.textContent??"").length:t.childNodes.length;this.setStart(t,0),this.setEnd(t,e)}_commonAncestorContainer(t,e){const i=Et(t??this.startContainer),s=Et(e??this.endContainer);if(i[0]==s[0]){for(let n=0;n<i.length;n++)if(i[n]!=s[n])return i[n-1]}}_checkCollapsed(){this.startContainer===this.endContainer&&this.startOffset===this.endOffset?this.collapsed=!0:this.collapsed=!1}toString(){return""}}const ue=Object.freeze(Object.defineProperty({__proto__:null,RangeObject:Gt,blob2base64:Xt,borders:nt,bounds:J,createBase64Url:bt,createBlob:Ut,createBlobUrl:ot,defaults:qt,defer:y,documentHeight:le,extend:_,filterChildren:V,findChildren:xt,getParentByTagName:de,indexOfElementNode:Wt,indexOfNode:kt,indexOfSorted:st,indexOfTextNode:ce,insert:ae,isElement:Bt,isFloat:Mt,isNumber:E,isXml:$,locationOf:X,nodeBounds:wt,parents:Et,parse:O,prefixed:j,qs:b,qsa:M,qsp:F,querySelectorByType:lt,requestAnimationFrame:Tt,revokeBlobUrl:jt,sprint:ht,treeWalker:Vt,type:Ft,uuid:dt,walk:Ht,windowBounds:rt},Symbol.toStringTag,{value:"Module"}));function G(l){if(typeof l!="string")throw new TypeError("Path must be a string. Received "+l)}function fe(l,t){let e="",i=-1,s=0,n;for(let r=0;r<=l.length;++r){if(r<l.length)n=l.charCodeAt(r);else{if(n===47)break;n=47}if(n===47){if(!(i===r-1||s===1))if(i!==r-1&&s===2){if(e.length<2||e.charCodeAt(e.length-1)!==46||e.charCodeAt(e.length-2)!==46){if(e.length>2){const o=e.length-1;let h=o;for(;h>=0&&e.charCodeAt(h)!==47;--h);if(h!==o){h===-1?e="":e=e.slice(0,h),i=r,s=0;continue}}else if(e.length===2||e.length===1){e="",i=r,s=0;continue}}t&&(e.length>0?e+="/..":e="..")}else e.length>0?e+="/"+l.slice(i+1,r):e=l.slice(i+1,r);i=r,s=0}else n===46&&s!==-1?++s:s=-1}return e}function St(...l){let t="",e=!1;for(let i=l.length-1;i>=-1&&!e;i--){const s=i>=0?l[i]:"/";G(s),s.length!==0&&(t=s+"/"+t,e=s.charCodeAt(0)===47)}return t=fe(t,!e),e?t.length>0?"/"+t:"/":t.length>0?t:"."}function pe(l,t){if(G(l),G(t),l===t||(l=St(l),t=St(t),l===t))return"";let e=1;for(;e<l.length&&l.charCodeAt(e)===47;++e);const i=l.length,s=i-e;let n=1;for(;n<t.length&&t.charCodeAt(n)===47;++n);const o=t.length-n,h=s<o?s:o;let a=-1,c=0;for(;c<=h;++c){if(c===h){if(o>h){if(t.charCodeAt(n+c)===47)return t.slice(n+c+1);if(c===0)return t.slice(n+c)}else s>h&&(l.charCodeAt(e+c)===47?a=c:c===0&&(a=0));break}const u=l.charCodeAt(e+c),p=t.charCodeAt(n+c);if(u!==p)break;u===47&&(a=c)}let d="";for(c=e+a+1;c<=i;++c)(c===i||l.charCodeAt(c)===47)&&(d.length===0?d+="..":d+="/..");return d.length>0?d+t.slice(n+a):(n+=a,t.charCodeAt(n)===47&&++n,t.slice(n))}function ge(l){if(G(l),l.length===0)return".";let t=l.charCodeAt(0);const e=t===47;let i=-1,s=!0;for(let n=l.length-1;n>=1;--n)if(t=l.charCodeAt(n),t===47){if(!s){i=n;break}}else s=!1;return i===-1?e?"/":".":e&&i===1?"//":l.slice(0,i)}function me(l){return G(l),l.length>0&&l.charCodeAt(0)===47}function ve(l){G(l);const t={root:"",dir:"",base:"",ext:"",name:""};if(l.length===0)return t;let e=l.charCodeAt(0);const i=e===47;let s;i?(t.root="/",s=1):s=0;let n=-1,r=0,o=-1,h=!0,a=l.length-1,c=0;for(;a>=s;--a){if(e=l.charCodeAt(a),e===47){if(!h){r=a+1;break}continue}o===-1&&(h=!1,o=a+1),e===46?n===-1?n=a:c!==1&&(c=1):n!==-1&&(c=-1)}return n===-1||o===-1||c===0||c===1&&n===o-1&&n===r+1?o!==-1&&(r===0&&i?t.base=t.name=l.slice(1,o):t.base=t.name=l.slice(r,o)):(r===0&&i?(t.name=l.slice(1,n),t.base=l.slice(1,o)):(t.name=l.slice(r,n),t.base=l.slice(r,o)),t.ext=l.slice(n,o)),r>0?t.dir=l.slice(0,r-1):i&&(t.dir="/"),t}const B={resolve:St,relative:pe,dirname:ge,isAbsolute:me,parse:ve};class z{constructor(t){t.indexOf("://")>-1&&(t=new URL(t).pathname);const i=this.parse(t);this.path=t,this.isDirectory(t)?(this.directory=t,this.filename="",this.extension=""):(this.directory=i.dir+"/",this.filename=i.base,this.extension=i.ext.slice(1))}parse(t){return B.parse(t)}isAbsolute(t){return B.isAbsolute(t||this.path)}isDirectory(t){return t.charAt(t.length-1)==="/"}resolve(t){return B.resolve(this.directory,t)}relative(t){return t&&t.indexOf("://")>-1?t:B.relative(this.directory,t)}splitPath(t){return this.splitPathRe.exec(t).slice(1)}toString(){return this.path}}class N{constructor(t,e){const i=t.indexOf("://")>-1;let s=t,n;if(this.Url=void 0,this.href=t,this.protocol="",this.origin="",this.hash="",this.hash="",this.search="",this.base=e,!i&&e!==!1&&typeof e!="string"&&window&&window.location&&(this.base=window.location.href),i||this.base)try{this.base?this.Url=new URL(t,this.base):this.Url=new URL(t),this.href=this.Url.href,this.protocol=this.Url.protocol,this.origin=this.Url.origin,this.origin==="null"&&this.protocol==="file:"&&(this.origin="file://"),this.hash=this.Url.hash,this.search=this.Url.search,s=this.Url.pathname+(this.Url.search?this.Url.search:"")}catch{this.Url=void 0,this.base&&(n=new z(this.base),s=n.resolve(s))}this.Path=new z(s),this.directory=this.Path.directory,this.filename=this.Path.filename,this.extension=this.Path.extension}path(){return this.Path}resolve(t){if(t.indexOf("://")>-1)return t;const i=B.resolve(this.directory,t);return this.origin+i}relative(t){return B.relative(t,this.directory)}toString(){return this.href}}const U=1,L=3,ye=9;class m{constructor(t,e,i){if(this.str="",this.base={},this.spinePos=0,this.range=!1,this.path={},this.start=null,this.end=null,!(this instanceof m))return new m(t,e,i);typeof e=="string"?this.base=this.parseComponent(e):typeof e=="object"&&e.steps&&(this.base=e);const s=this.checkType(t);if(s==="string")return this.str=t,_(this,this.parse(t));if(s==="range")return _(this,this.fromRange(t,this.base,i));if(s==="node")return _(this,this.fromNode(t,this.base,i));if(s==="EpubCFI"&&t.path)return t;if(t)throw new TypeError("not a valid argument for EpubCFI");return this}checkType(t){return this.isCfiString(t)?"string":t&&typeof t=="object"&&(Ft(t)==="Range"||typeof t.startContainer<"u")?"range":t&&typeof t=="object"&&typeof t.nodeType<"u"?"node":t&&typeof t=="object"&&t instanceof m?"EpubCFI":!1}parse(t){const e={spinePos:-1,range:!1,base:{},path:{},start:null,end:null};if(typeof t!="string")return{spinePos:-1};t.indexOf("epubcfi(")===0&&t[t.length-1]===")"&&(t=t.slice(8,t.length-1));const i=this.getChapterComponent(t);if(!i)return{spinePos:-1};e.base=this.parseComponent(i);const s=this.getPathComponent(t);e.path=this.parseComponent(s);const n=this.getRange(t);return n&&(e.range=!0,e.start=this.parseComponent(n[0]),e.end=this.parseComponent(n[1])),e.base.steps.length<2?{spinePos:-1}:(e.spinePos=e.base.steps[1].index,e)}parseComponent(t){const e={steps:[],terminal:{offset:null,assertion:null}},i=t.split(":"),s=i[0].split("/");let n;return i.length>1&&(n=i[1],e.terminal=this.parseTerminal(n)),s[0]===""&&s.shift(),e.steps=s.map(r=>this.parseStep(r)),e}parseStep(t){let e,i,s;const n=t.match(/\[(.*)\]/);n&&n[1]&&(s=n[1]);const r=parseInt(t);if(!isNaN(r))return r%2===0?(e="element",i=r/2-1):(e="text",i=(r-1)/2),{type:e,index:i,id:s||null,tagName:""}}parseTerminal(t){let e,i=null;const s=t.match(/\[(.*)\]/);return s&&s[1]?(e=parseInt(t.split("[")[0]),i=s[1]):e=parseInt(t),E(e)||(e=null),{offset:e,assertion:i}}getChapterComponent(t){return t.split("!")[0]}getPathComponent(t){const e=t.split("!");if(e[1])return e[1].split(",")[0]}getRange(t){const e=t.split(",");return e.length===3?[e[1],e[2]]:!1}getCharecterOffsetComponent(t){return t.split(":")[1]||""}joinSteps(t){return t?t.map(function(e){let i="";return e.type==="element"&&(i+=(e.index+1)*2),e.type==="text"&&(i+=1+2*e.index),e.id&&(i+="["+e.id+"]"),i}).join("/"):""}segmentString(t){let e="/";return e+=this.joinSteps(t.steps),t.terminal&&t.terminal.offset!=null&&(e+=":"+t.terminal.offset),t.terminal&&t.terminal.assertion!=null&&(e+="["+t.terminal.assertion+"]"),e}toString(){let t="epubcfi(";return t+=this.segmentString(this.base),t+="!",t+=this.segmentString(this.path),this.range&&this.start&&(t+=",",t+=this.segmentString(this.start)),this.range&&this.end&&(t+=",",t+=this.segmentString(this.end)),t+=")",t}compare(t,e){let i,s,n,r;if(typeof t=="string"&&(t=new m(t)),typeof e=="string"&&(e=new m(e)),t.spinePos>e.spinePos)return 1;if(t.spinePos<e.spinePos)return-1;t.range?(i=t.path.steps.concat(t.start.steps),n=t.start.terminal):(i=t.path.steps,n=t.path.terminal),e.range?(s=e.path.steps.concat(e.start.steps),r=e.start.terminal):(s=e.path.steps,r=e.path.terminal);for(let a=0;a<i.length;a++){if(!i[a])return-1;if(!s[a]||i[a].index>s[a].index)return 1;if(i[a].index<s[a].index)return-1}if(i.length<s.length)return-1;const o=n.offset??0,h=r.offset??0;return o>h?1:o<h?-1:0}step(t){const e=t.nodeType===L?"text":"element";return{id:t.id,tagName:t.tagName,type:e,index:this.position(t)}}filteredStep(t,e){const i=this.filter(t,e);if(!i)return;const s=i.nodeType===L?"text":"element";return{id:i.id,tagName:i.tagName,type:s,index:this.filteredPosition(i,e)}}pathTo(t,e,i){const s={steps:[],terminal:{offset:null,assertion:null}};let n=t,r;for(;n&&n.parentNode&&n.parentNode.nodeType!=ye;)i?r=this.filteredStep(n,i):r=this.step(n),r&&s.steps.unshift(r),n=n.parentNode;return e!=null&&e>=0&&(s.terminal.offset=e,s.steps.length>0&&s.steps[s.steps.length-1].type!="text"&&s.steps.push({type:"text",index:0,id:null,tagName:""})),s}equalStep(t,e){return!t||!e?!1:t.index===e.index&&t.id===e.id&&t.type===e.type}fromRange(t,e,i){const s={range:!1,base:{},path:{},start:null,end:null,spinePos:0},n=t.startContainer,r=t.endContainer;let o=t.startOffset,h=t.endOffset,a=!1;if(i&&(a=n.ownerDocument.querySelector("."+i)!=null),typeof e=="string"?(s.base=this.parseComponent(e),s.spinePos=s.base.steps[1].index):typeof e=="object"&&(s.base=e),t.collapsed)a&&(o=this.patchOffset(n,o,i)),s.path=this.pathTo(n,o,i);else{s.range=!0,a&&(o=this.patchOffset(n,o,i)),s.start=this.pathTo(n,o,i),a&&(h=this.patchOffset(r,h,i)),s.end=this.pathTo(r,h,i),s.path={steps:[],terminal:{offset:null,assertion:null}};const c=s.start.steps.length;let d;for(d=0;d<c&&this.equalStep(s.start.steps[d],s.end.steps[d]);d++)d===c-1?s.start.terminal===s.end.terminal&&(s.path.steps.push(s.start.steps[d]),s.range=!1):s.path.steps.push(s.start.steps[d]);s.start.steps=s.start.steps.slice(s.path.steps.length),s.end.steps=s.end.steps.slice(s.path.steps.length)}return s}fromNode(t,e,i){const s={range:!1,base:{},path:{},start:null,end:null,spinePos:0};return typeof e=="string"?(s.base=this.parseComponent(e),s.spinePos=s.base.steps[1].index):typeof e=="object"&&(s.base=e),s.path=this.pathTo(t,null,i),s}filter(t,e){let i,s,n,r,o,h=!1;return t.nodeType===L?(h=!0,n=t.parentNode,i=t.parentNode.classList.contains(e)):(h=!1,i=t.classList.contains(e)),i&&h?(r=n.previousSibling,o=n.nextSibling,r&&r.nodeType===L?s=r:o&&o.nodeType===L&&(s=o),s||t):i&&!h?!1:t}patchOffset(t,e,i){if(t.nodeType!=L)throw new Error("Anchor must be a text node");let s=t,n=e;for(t.parentNode.classList.contains(i)&&(s=t.parentNode);s.previousSibling;){if(s.previousSibling.nodeType===U)if(s.previousSibling.classList.contains(i))n+=(s.previousSibling.textContent??"").length;else break;else n+=(s.previousSibling.textContent??"").length;s=s.previousSibling}return n}normalizedMap(t,e,i){const s={};let n=-1,r;const o=t.length;let h,a;for(r=0;r<o;r++)h=t[r].nodeType,h===U&&t[r].classList.contains(i)&&(h=L),r>0&&h===L&&a===L?s[r]=n:e===h&&(n=n+1,s[r]=n),a=h;return s}position(t){let e,i;return t.nodeType===U?(e=t.parentNode.children,e||(e=xt(t.parentNode)),i=Array.from(e).indexOf(t)):(e=this.textNodes(t.parentNode),i=e.indexOf(t)),i}filteredPosition(t,e){let i,s;t.nodeType===U?(i=t.parentNode.children,s=this.normalizedMap(i,U,e)):(i=t.parentNode.childNodes,t.parentNode.classList.contains(e)&&(t=t.parentNode,i=t.parentNode.childNodes),s=this.normalizedMap(i,L,e));const n=Array.from(i).indexOf(t);return s[n]}stepsToXpath(t){const e=[".","*"];return t.forEach(function(i){const s=i.index+1;i.id?e.push("*[position()="+s+" and @id='"+i.id+"']"):i.type==="text"?e.push("text()["+s+"]"):e.push("*["+s+"]")}),e.join("/")}stepsToQuerySelector(t){const e=["html"];return t.forEach(function(i){const s=i.index+1;i.id?e.push("#"+i.id):i.type==="text"||e.push("*:nth-child("+s+")")}),e.join(">")}textNodes(t,e){return Array.from(t.childNodes).filter(function(i){return i.nodeType===L?!0:!!(e&&i.classList.contains(e))})}walkToNode(t,e,i){const s=e||document;let n=s.documentElement,r,o;const h=t.length;let a;for(a=0;a<h&&(o=t[a],o.type==="element"?o.id?n=s.getElementById(o.id):(r=n.children||xt(n),n=r[o.index]):o.type==="text"&&(n=this.textNodes(n,i)[o.index]),!!n);a++);return n}findNode(t,e,i){const s=e||document;let n,r;return!i&&typeof s.evaluate<"u"?(r=this.stepsToXpath(t),n=s.evaluate(r,s,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue??void 0):i?n=this.walkToNode(t,s,i):n=this.walkToNode(t,s),n}fixMiss(t,e,i,s){let n=this.findNode(t.slice(0,-1),i,s);if(!n)return{container:(i??document).documentElement,offset:0};const r=n.childNodes,o=this.normalizedMap(r,L,s);let h,a;const c=t[t.length-1].index;for(const d in o)if(o.hasOwnProperty(d)&&o[d]===c)if(h=r[d],a=(h.textContent??"").length,e>a)e=e-a;else{h.nodeType===U?n=h.childNodes[0]??h:n=h;break}return{container:n,offset:e}}toRange(t,e){const i=t||document;let s,n,r,o,h;const a=this;let c,d;const u=e?i.querySelector("."+e)!=null:!1;let p;if(typeof i.createRange<"u"?s=i.createRange():s=new Gt,a.range?(n=a.start,c=a.path.steps.concat(n.steps),o=this.findNode(c,i,u?e:void 0),r=a.end,d=a.path.steps.concat(r.steps),h=this.findNode(d,i,u?e:void 0)):(n=a.path,c=a.path.steps,o=this.findNode(a.path.steps,i,u?e:void 0)),o)try{n.terminal.offset!=null?s.setStart(o,n.terminal.offset):s.setStart(o,0)}catch{p=this.fixMiss(c,n.terminal.offset,i,u?e:void 0),s.setStart(p.container,p.offset)}else return console.log("No startContainer found for",this.toString()),null;if(h)try{r.terminal.offset!=null?s.setEnd(h,r.terminal.offset):s.setEnd(h,0)}catch{p=this.fixMiss(d,a.end.terminal.offset,i,u?e:void 0),s.setEnd(p.container,p.offset)}return s}isCfiString(t){return typeof t=="string"&&t.indexOf("epubcfi(")===0&&t[t.length-1]===")"}generateChapterComponent(t,e,i){const s=parseInt(e);let r="/"+(t+1)*2+"/";return r+=(s+1)*2,i&&(r+="["+i+"]"),r}collapse(t){this.range&&(this.range=!1,t?(this.path.steps=this.path.steps.concat(this.start.steps),this.path.terminal=this.start.terminal):(this.path.steps=this.path.steps.concat(this.end.steps),this.path.terminal=this.end.terminal))}}class A{constructor(t){this.context=t||this,this.hooks=[]}register(...t){for(let e=0;e<t.length;++e){const i=t[e];if(typeof i=="function")this.hooks.push(i);else for(let s=0;s<i.length;++s)this.hooks.push(i[s])}}deregister(t){let e;for(let i=0;i<this.hooks.length;i++)if(e=this.hooks[i],e===t){this.hooks.splice(i,1);break}}trigger(...t){const e=this.context,i=[];return this.hooks.forEach(function(s){let n;try{n=s.call(e,...t)}catch(r){console.log(r)}n&&typeof n.then=="function"&&i.push(n)}),Promise.all(i)}list(){return this.hooks}clear(){return this.hooks=[]}}function Yt(l,t){let e,i=t.url;const s=i.indexOf("://")>-1;if(!l)return;const n=b(l,"head");e=b(n,"base"),e||(e=l.createElement("base"),n.insertBefore(e,n.firstChild)),!s&&window&&window.location&&(i=window.location.origin+i),e.setAttribute("href",i)}function we(l,t){let e;const i=t.canonical;if(!l)return;const s=b(l,"head");e=b(s,"link[rel='canonical']"),e?e.setAttribute("href",i):(e=l.createElement("link"),e.setAttribute("rel","canonical"),e.setAttribute("href",i),s.appendChild(e))}function be(l,t){let e;const i=t.idref;if(!l)return;const s=b(l,"head");e=b(s,"link[property='dc.identifier']"),e?e.setAttribute("content",i):(e=l.createElement("meta"),e.setAttribute("name","dc.identifier"),e.setAttribute("content",i),s.appendChild(e))}function xe(l,t){const e=l.querySelectorAll("a[href]");if(!e.length)return;const i=b(l.ownerDocument,"base"),s=i?i.getAttribute("href")??void 0:void 0,n=function(r){const o=r.getAttribute("href")??"";if(o.indexOf("mailto:")===0)return;const h=o.trimStart().toLowerCase();if(h.startsWith("javascript:")||h.startsWith("data:text/html")){r.removeAttribute("href");return}if(o.indexOf("://")>-1)r.setAttribute("target","_blank");else{let c;try{c=new N(o,s)}catch{}r.onclick=function(){return c&&c.hash?t(c.Path.path+c.hash):t(c?c.Path.path:o),!1}}};for(let r=0;r<e.length;r++)n(e[r])}function It(l,t,e){return t.forEach(function(i,s){if(i&&e[s]){try{const n=decodeURIComponent(i);if(n!==i){const r=n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");l=l.replace(new RegExp(r,"g"),e[s])}}catch{}i=i.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),l=l.replace(new RegExp(i,"g"),e[s])}}),l}function K(l,t,e,i){const s=typeof window<"u"?window.URL:!1,n=s?"blob":"arraybuffer",r=new y,o=new XMLHttpRequest;let h;e&&(o.withCredentials=!0),o.onreadystatechange=c,o.onerror=a,o.open("GET",l,!0);for(h in i)o.setRequestHeader(h,i[h]);t=="json"&&o.setRequestHeader("Accept","application/json"),t||(t=new z(l).extension),t=="blob"&&(o.responseType=n),$(t)&&o.overrideMimeType("text/xml"),t=="binary"&&(o.responseType="arraybuffer"),o.send();function a(d){r.reject(d)}function c(){if(o.readyState===XMLHttpRequest.DONE){let d=!1;if((o.responseType===""||o.responseType==="document")&&(d=o.responseXML),o.status===200||o.status===0||d){let u;if(!o.response&&!d)return r.reject({status:o.status,message:"Empty Response",stack:new Error().stack}),r.promise;if(o.status===403)return r.reject({status:o.status,response:o.response,message:"Forbidden",stack:new Error().stack}),r.promise;d?u=o.responseXML:$(t)?u=O(o.response,"text/xml"):t=="xhtml"?u=O(o.response,"application/xhtml+xml"):t=="html"||t=="htm"?u=O(o.response,"text/html"):t=="json"?u=JSON.parse(o.response):t=="blob"?s?u=o.response:u=new Blob([o.response]):u=o.response,r.resolve(u)}else r.reject({status:o.status,message:o.response,stack:new Error().stack})}}return r.promise}class $t{constructor(t,e){this.idref=t.idref,this.linear=t.linear==="yes",this.properties=t.properties,this.index=t.index,this.href=t.href,this.url=t.url,this.canonical=t.canonical,this.next=t.next,this.prev=t.prev,this.cfiBase=t.cfiBase,e?this.hooks=e:(this.hooks={},this.hooks.serialize=new A(this),this.hooks.content=new A(this)),this.document=void 0,this.contents=void 0,this.output=void 0}load(t){const e=t||this.request||K,i=new y,s=i.promise;return this.contents?i.resolve(this.contents):e(this.url).then(n=>(this.document=n,this.contents=n.documentElement,this.hooks.content.trigger(this.document,this))).then(()=>{i.resolve(this.contents)}).catch(function(n){i.reject(n)}),s}base(){return Yt(this.document,this)}render(t){const e=new y,i=e.promise;return this.load(t).then(s=>{const n=new XMLSerializer;return this.output=n.serializeToString(s),this.output}).then(()=>this.hooks.serialize.trigger(this.output,this)).then(()=>{e.resolve(this.output)}).catch(function(s){e.reject(s)}),i}find(t){const e=this,i=[],s=t.toLowerCase(),n=function(r){const o=r.textContent.toLowerCase();let h,a,c,d=-1,u;const p=150;for(;c!=-1;)c=o.indexOf(s,d+1),c!=-1&&(h=e.document.createRange(),h.setStart(r,c),h.setEnd(r,c+s.length),a=e.cfiFromRange(h),r.textContent.length<p?u=r.textContent:(u=r.textContent.substring(c-p/2,c+p/2),u="..."+u+"..."),i.push({cfi:a,excerpt:u})),d=c};return ht(e.document,function(r){n(r)}),i}search(t,e=5){const i=[],n=this,r=t.toLowerCase(),o=function(d){const g=d.reduce((v,w)=>v+(w.textContent??""),"").toLowerCase().indexOf(r);if(g!=-1){const w=g+r.length;let x=0,k=0;if(g<d[0].length){for(;x<d.length-1&&(k+=d[x].length,!(w<=k));)x+=1;const S=d[0],C=d[x],T=n.document.createRange();T.setStart(S,g);const I=d.slice(0,x).reduce((mt,vt)=>mt+(vt.textContent??"").length,0);T.setEnd(C,I>w?w:w-I);const q=n.cfiFromRange(T);let D=d.slice(0,x+1).reduce((mt,vt)=>mt+(vt.textContent??""),"");D.length>150&&(D=D.substring(g-150/2,g+150/2),D="..."+D+"..."),i.push({cfi:q,excerpt:D})}}},h=document.createTreeWalker(n.document,NodeFilter.SHOW_TEXT,null);let a,c=[];for(;a=h.nextNode();)c.push(a),c.length==e&&(o(c.slice(0,e)),c=c.slice(1,e));return c.length>0&&o(c),i}reconcileLayoutSettings(t){const e={layout:t.layout,spread:t.spread,orientation:t.orientation};return this.properties.forEach(function(i){const s=i.replace("rendition:",""),n=s.indexOf("-");let r,o;n!=-1&&(r=s.slice(0,n),o=s.slice(n+1),e[r]=o)}),e}cfiFromRange(t){return new m(t,this.cfiBase).toString()}cfiFromElement(t){return new m(t,this.cfiBase).toString()}unload(){this.document=void 0,this.contents=void 0,this.output=void 0}destroy(){this.unload(),this.hooks.serialize.clear(),this.hooks.content.clear(),this.hooks=void 0,this.idref=void 0,this.linear=void 0,this.properties=void 0,this.index=void 0,this.href=void 0,this.url=void 0,this.next=void 0,this.prev=void 0,this.cfiBase=void 0}}class Kt{constructor(){this.spineItems=[],this.spineByHref={},this.spineById={},this.hooks={},this.hooks.serialize=new A,this.hooks.content=new A,this.hooks.content.register(Yt),this.hooks.content.register(we),this.hooks.content.register(be),this.epubcfi=new m,this.loaded=!1,this.items=[],this.manifest={},this.spineNodeIndex=0,this.baseUrl="",this.length=0}unpack(t,e,i){this.items=t.spine,this.manifest=t.manifest,this.spineNodeIndex=t.spineNodeIndex,this.baseUrl=t.baseUrl||t.basePath||"",this.length=this.items.length,this.items.forEach((s,n)=>{const r=this.manifest[s.idref];s.index=n,s.cfiBase=this.epubcfi.generateChapterComponent(this.spineNodeIndex,s.index,s.id),s.href&&(s.url=e(s.href,!0),s.canonical=i(s.href)),r&&(s.href=r.href,s.url=e(s.href,!0),s.canonical=i(s.href),r.properties.length&&s.properties.push(...r.properties)),s.linear==="yes"?(s.prev=()=>{let h=s.index;for(;h>0;){const a=this.get(h-1);if(a&&a.linear)return a;h-=1}},s.next=()=>{let h=s.index;for(;h<this.spineItems.length-1;){const a=this.get(h+1);if(a&&a.linear)return a;h+=1}}):(s.prev=function(){},s.next=function(){});const o=new $t(s,this.hooks);this.append(o)}),this.loaded=!0}get(t){let e=0;if(typeof t>"u")for(;e<this.spineItems.length;){const i=this.spineItems[e];if(i&&i.linear)break;e+=1}else this.epubcfi.isCfiString(t)?e=new m(t).spinePos:typeof t=="number"||isNaN(Number(t))===!1?e=Number(t):typeof t=="string"&&t.indexOf("#")===0?e=this.spineById[t.substring(1)]??-1:typeof t=="string"&&(t=t.split("#")[0],e=this.spineByHref[t]??this.spineByHref[encodeURI(t)]??-1);return this.spineItems[e]??null}append(t){const e=this.spineItems.length;return t.index=e,this.spineItems.push(t),this.spineByHref[decodeURI(t.href)]=e,this.spineByHref[encodeURI(t.href)]=e,this.spineByHref[t.href]=e,this.spineById[t.idref]=e,e}prepend(t){return this.spineByHref[t.href]=0,this.spineById[t.idref]=0,this.spineItems.forEach(function(e,i){e.index=i}),0}remove(t){const e=this.spineItems.indexOf(t);if(e>-1)return delete this.spineByHref[t.href],delete this.spineById[t.idref],this.spineItems.splice(e,1)}each(t){return this.spineItems.forEach(t)}first(){let t=0;do{const e=this.get(t);if(e&&e.linear)return e;t+=1}while(t<this.spineItems.length)}last(){let t=this.spineItems.length-1;do{const e=this.get(t);if(e&&e.linear)return e;t-=1}while(t>=0)}destroy(){this.each(t=>t.destroy()),this.spineItems=void 0,this.spineByHref=void 0,this.spineById=void 0,this.hooks.serialize.clear(),this.hooks.content.clear(),this.hooks=void 0,this.epubcfi=void 0,this.loaded=!1,this.items=void 0,this.manifest=void 0,this.spineNodeIndex=void 0,this.baseUrl=void 0,this.length=void 0}}class Lt{constructor(t){this._q=[],this.context=t,this.tick=Tt,this.running=!1,this.paused=!1}enqueue(...t){let e,i,s;const[n,...r]=t;if(!n)throw new Error("No Task Provided");return typeof n=="function"?(e=new y,i=e.promise,s={task:n,args:r,deferred:e,promise:i}):s={args:[],promise:n},this._q.push(s),this.paused==!1&&!this.running&&this.run(),s.promise}dequeue(){let t,e,i;return this._q.length&&!this.paused?(t=this._q.shift(),e=t.task,e?(i=e.call(this.context,...t.args),i&&typeof i.then=="function"?i.then(s=>{t.deferred.resolve(s)},s=>{t.deferred.reject(s)}):(t.deferred.resolve(i),t.promise)):t.promise):Promise.resolve()}dump(){for(;this._q.length;)this.dequeue()}run(){return this.running||(this.running=!0,this.defered=new y),this.tick&&this.tick(()=>{var t;this._q.length?(t=this.dequeue())==null||t.then(()=>{this.run()}):(this.defered.resolve(),this.running=void 0)}),this.paused==!0&&(this.paused=!1),this.defered.promise}flush(){var t;if(this.running)return this.running;if(this._q.length)return this.running=(t=this.dequeue())==null?void 0:t.then(()=>(this.running=void 0,this.flush())),this.running}clear(){this._q=[]}length(){return this._q.length}pause(){this.paused=!0}stop(){this._q=[],this.running=!1,this.paused=!0}}const ut="0.3",Q=["keydown","keyup","keypress","mouseup","mousedown","mousemove","click","dblclick","touchend","touchstart","touchmove"],f={BOOK:{OPEN_FAILED:"openFailed"},CONTENTS:{EXPAND:"expand",RESIZE:"resize",SELECTED:"selected",SELECTED_RANGE:"selectedRange",LINK_CLICKED:"linkClicked"},LOCATIONS:{CHANGED:"changed"},MANAGERS:{RESIZE:"resize",RESIZED:"resized",ORIENTATION_CHANGE:"orientationchange",ADDED:"added",SCROLL:"scroll",SCROLLED:"scrolled",REMOVED:"removed"},VIEWS:{AXIS:"axis",WRITING_MODE:"writingMode",LOAD_ERROR:"loaderror",RENDERED:"rendered",RESIZED:"resized",DISPLAYED:"displayed",SHOWN:"shown",HIDDEN:"hidden",MARK_CLICKED:"markClicked"},RENDITION:{STARTED:"started",ATTACHED:"attached",DISPLAYED:"displayed",DISPLAY_ERROR:"displayerror",RENDERED:"rendered",REMOVED:"removed",RESIZED:"resized",ORIENTATION_CHANGE:"orientationchange",LOCATION_CHANGED:"locationChanged",RELOCATED:"relocated",MARK_CLICKED:"markClicked",SELECTED:"selected",LAYOUT:"layout"},LAYOUT:{UPDATED:"updated"},ANNOTATION:{ATTACH:"attach",DETACH:"detach"}};class Rt{constructor(t,e,i){this.spine=t,this.request=e,this.pause=i||100,this.q=new Lt(this),this.epubcfi=new m,this._locations=[],this._locationsWords=[],this.total=0,this.break=150,this._current=0,this._wordCounter=0,this._currentCfi="",this.processingTimeout=void 0}generate(t){return t&&(this.break=t),this.q.pause(),this.spine.each(e=>{e.linear&&this.q.enqueue(i=>this.process(i),e)}),this.q.run().then(()=>(this.total=this._locations.length-1,this._currentCfi&&(this.currentLocation=this._currentCfi),this._locations))}createRange(){return{startContainer:void 0,startOffset:void 0,endContainer:void 0,endOffset:void 0}}process(t){return t.load(this.request).then(e=>{const i=new y,s=this.parse(e,t.cfiBase);return this._locations=this._locations.concat(s),t.unload(),this.processingTimeout=setTimeout(()=>i.resolve(s),this.pause),i.promise})}parse(t,e,i){const s=[];let n;const r=t.ownerDocument,o=b(r,"body");let h=0,a;const c=i||this.break;if(ht(o,u=>{const p=u.length;let g,v=0;if((u.textContent??"").trim().length===0)return a=u,!1;for(h===0&&(n=this.createRange(),n.startContainer=u,n.startOffset=0),g=c-h,g>p&&(h+=p,v=p);v<p;)if(g=c-h,h===0&&(v+=1,n=this.createRange(),n.startContainer=u,n.startOffset=v),v+g>=p)h+=p-v,v=p;else{v+=g,n.endContainer=u,n.endOffset=v;const w=new m(n,e).toString();s.push(w),h=0}return a=u,!1}),n&&n.startContainer&&a){n.endContainer=a,n.endOffset=a.length;const u=new m(n,e).toString();s.push(u),h=0}return s}generateFromWords(t,e,i){const s=t?new m(t):void 0;return this.q.pause(),this._locationsWords=[],this._wordCounter=0,this.spine.each(n=>{n.linear&&(s?n.index>=s.spinePos&&this.q.enqueue((r,o,h,a)=>this.processWords(r,o,h,a),n,e,s,i):this.q.enqueue((r,o,h,a)=>this.processWords(r,o,h,a),n,e,s,i))}),this.q.run().then(()=>(this._currentCfi&&(this.currentLocation=this._currentCfi),this._locationsWords))}processWords(t,e,i,s){return s&&this._locationsWords.length>=s?Promise.resolve([]):t.load(this.request).then(n=>{const r=new y,o=this.parseWords(n,t,e,i),h=s-this._locationsWords.length;return this._locationsWords=this._locationsWords.concat(o.length>=s?o.slice(0,h):o),t.unload(),this.processingTimeout=setTimeout(()=>r.resolve(o),this.pause),r.promise})}countWords(t){return t=t.replace(/(^\s*)|(\s*$)/gi,""),t=t.replace(/[ ]{2,}/gi," "),t=t.replace(/\n /,`
2
+ `),t.split(" ").length}parseWords(t,e,i,s){const n=e.cfiBase,r=[],o=t.ownerDocument,h=b(o,"body"),a=i;let c=s?s.spinePos!==e.index:!0,d;return s&&e.index===s.spinePos&&(d=s.findNode(s.range?s.path.steps.concat(s.start.steps):s.path.steps,t.ownerDocument)),ht(h,p=>{if(!c)if(p===d)c=!0;else return!1;if((p.textContent??"").length<10&&(p.textContent??"").trim().length===0)return!1;const g=this.countWords(p.textContent??"");let v,w=0;if(g===0)return!1;for(v=a-this._wordCounter,v>g&&(this._wordCounter+=g,w=g);w<g;)if(v=a-this._wordCounter,w+v>=g)this._wordCounter+=g-w,w=g;else{w+=v;const x=new m(p,n);r.push({cfi:x.toString(),wordCount:this._wordCounter}),this._wordCounter=0}return!1}),r}locationFromCfi(t){if(m.prototype.isCfiString(t)&&(t=new m(t)),this._locations.length===0)return-1;const e=X(t,this._locations,this.epubcfi.compare);return e>this.total?this.total:e}percentageFromCfi(t){if(this._locations.length===0)return null;const e=this.locationFromCfi(t);return this.percentageFromLocation(e)}percentageFromLocation(t){return!t||!this.total?0:t/this.total}cfiFromLocation(t){let e=-1;return typeof t!="number"&&(t=parseInt(t)),t>=0&&t<this._locations.length&&(e=this._locations[t]),e}cfiFromPercentage(t){if(t>1&&console.warn("Normalize cfiFromPercentage value to between 0 - 1"),t>=1){const i=new m(this._locations[this.total]);return i.collapse(),i.toString()}const e=Math.ceil(this.total*t);return this.cfiFromLocation(e)}load(t){return typeof t=="string"?this._locations=JSON.parse(t):this._locations=t,this.total=this._locations.length-1,this._locations}save(){return JSON.stringify(this._locations)}getCurrent(){return this._current}setCurrent(t){let e;if(typeof t=="string")this._currentCfi=t;else if(typeof t=="number")this._current=t;else return;this._locations.length!==0&&(typeof t=="string"?(e=this.locationFromCfi(t),this._current=e):e=t,this.emit(f.LOCATIONS.CHANGED,{percentage:this.percentageFromLocation(e)}))}get currentLocation(){return this._current}set currentLocation(t){this.setCurrent(t)}length(){return this._locations.length}destroy(){var t;this.spine=void 0,this.request=void 0,this.pause=void 0,(t=this.q)==null||t.stop(),this.q=void 0,this.epubcfi=void 0,this._locations=void 0,this.total=void 0,this.break=void 0,this._current=void 0,this.currentLocation=void 0,this._currentCfi=void 0,clearTimeout(this.processingTimeout)}}P(Rt.prototype);class Ee{constructor(t){this.packagePath="",this.directory="",this.encoding="",t&&this.parse(t)}parse(t){if(!t)throw new Error("Container File Not Found");const e=b(t,"rootfile");if(!e)throw new Error("No RootFile Found");this.packagePath=e.getAttribute("full-path")??"",this.directory=B.dirname(this.packagePath),this.encoding=t.xmlEncoding}destroy(){this.packagePath=void 0,this.directory=void 0,this.encoding=void 0}}class Ct{constructor(t){this.manifest={},this.navPath="",this.ncxPath="",this.coverPath="",this.spineNodeIndex=0,this.spine=[],this.metadata={},t&&this.parse(t)}parse(t){if(!t)throw new Error("Package File Not Found");const e=b(t,"metadata");if(!e)throw new Error("No Metadata Found");const i=b(t,"manifest");if(!i)throw new Error("No Manifest Found");const s=b(t,"spine");if(!s)throw new Error("No Spine Found");return this.manifest=this.parseManifest(i),this.navPath=this.findNavPath(i),this.ncxPath=this.findNcxPath(i,s),this.coverPath=this.findCoverPath(t),this.spineNodeIndex=Wt(s),this.spine=this.parseSpine(s,this.manifest),this.uniqueIdentifier=this.findUniqueIdentifier(t),this.metadata=this.parseMetadata(e),this.metadata.direction=s.getAttribute("page-progression-direction")??"",{metadata:this.metadata,spine:this.spine,manifest:this.manifest,navPath:this.navPath,ncxPath:this.ncxPath,coverPath:this.coverPath,spineNodeIndex:this.spineNodeIndex}}parseMetadata(t){const e={};return e.title=this.getElementText(t,"title"),e.creator=this.getElementText(t,"creator"),e.description=this.getElementText(t,"description"),e.pubdate=this.getElementText(t,"date"),e.publisher=this.getElementText(t,"publisher"),e.identifier=this.getElementText(t,"identifier"),e.language=this.getElementText(t,"language"),e.rights=this.getElementText(t,"rights"),e.modified_date=this.getPropertyText(t,"dcterms:modified"),e.layout=this.getPropertyText(t,"rendition:layout"),e.orientation=this.getPropertyText(t,"rendition:orientation"),e.flow=this.getPropertyText(t,"rendition:flow"),e.viewport=this.getPropertyText(t,"rendition:viewport"),e.media_active_class=this.getPropertyText(t,"media:active-class"),e.spread=this.getPropertyText(t,"rendition:spread"),e}parseManifest(t){const e={},i=M(t,"item");return Array.from(i).forEach(function(n){const r=n.getAttribute("id")??"",o=n.getAttribute("href")||"",h=n.getAttribute("media-type")||"",a=n.getAttribute("media-overlay")||"",c=n.getAttribute("properties")||"",d=n.getAttribute("fallback")||"";e[r]={href:o,type:h,overlay:a,properties:c.length?c.split(" "):[],fallback:d}}),e}parseSpine(t,e){const i=[],s=M(t,"itemref");return Array.from(s).forEach(function(r,o){const h=r.getAttribute("idref"),a=r.getAttribute("properties")||"",c=a.length?a.split(" "):[],d={id:r.getAttribute("id")??void 0,idref:h,linear:r.getAttribute("linear")||"yes",properties:c,index:o};i.push(d)}),i}findUniqueIdentifier(t){const e=t.documentElement.getAttribute("unique-identifier");if(!e)return"";const i=t.getElementById(e);return i&&i.localName==="identifier"&&i.namespaceURI==="http://purl.org/dc/elements/1.1/"&&i.childNodes.length>0?(i.childNodes[0].nodeValue??"").trim():""}findNavPath(t){const e=F(t,"item",{properties:"nav"});return e&&e.getAttribute("href")||""}findNcxPath(t,e){let i=F(t,"item",{"media-type":"application/x-dtbncx+xml"}),s;return i||(s=e.getAttribute("toc"),s&&(i=t.querySelector(`#${s}`)??void 0)),i&&i.getAttribute("href")||""}findCoverPath(t){const e=b(t,"package");e==null||e.getAttribute("version");const i=F(t,"item",{properties:"cover-image"});if(i)return i.getAttribute("href")??"";const s=F(t,"meta",{name:"cover"});if(s){const n=s.getAttribute("content"),r=t.getElementById(n);return r?r.getAttribute("href")??"":""}else return""}getElementText(t,e){const i=t.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/",e);if(!i||i.length===0)return"";const s=i[0];return s.childNodes.length?s.childNodes[0].nodeValue??"":""}getPropertyText(t,e){const i=F(t,"meta",{property:e});return i&&i.childNodes.length?i.childNodes[0].nodeValue??"":""}load(t){this.metadata=t.metadata;const e=t.readingOrder||t.spine;return this.spine=e.map((i,s)=>(i.index=s,i.linear=i.linear||"yes",i)),t.resources.forEach((i,s)=>{this.manifest[s]=i,i.rel&&i.rel[0]==="cover"&&(this.coverPath=i.href)}),this.spineNodeIndex=0,this.toc=t.toc.map(i=>(i.label=i.title||i.label,i)),{metadata:this.metadata,spine:this.spine,manifest:this.manifest,navPath:this.navPath,ncxPath:this.ncxPath,coverPath:this.coverPath,spineNodeIndex:this.spineNodeIndex,toc:this.toc}}destroy(){this.manifest=void 0,this.navPath=void 0,this.ncxPath=void 0,this.coverPath=void 0,this.spineNodeIndex=void 0,this.spine=void 0,this.metadata=void 0}}class tt{constructor(t){this.toc=[],this.tocByHref={},this.tocById={},this.landmarks=[],this.landmarksByType={},this.length=0,t&&this.parse(t)}parse(t){const e=t.nodeType;let i,s;e&&(i=b(t,"html"),s=b(t,"ncx")),e?i?(this.toc=this.parseNav(t),this.landmarks=this.parseLandmarks(t)):s&&(this.toc=this.parseNcx(t)):this.toc=this.load(t),this.length=0,this.unpack(this.toc)}unpack(t){let e;for(let i=0;i<t.length;i++)e=t[i],e.href&&(this.tocByHref[e.href]=i),e.id&&(this.tocById[e.id]=i),this.length++,e.subitems&&e.subitems.length&&this.unpack(e.subitems)}get(t){let e;return t?(t.indexOf("#")===0?(t=t.substring(1),e=this.tocById[t]):t in this.tocByHref&&(e=this.tocByHref[t]),this.getByIndex(t,e,this.toc)):this.toc}getByIndex(t,e,i){if(i.length===0)return;const s=e!==void 0?i[e]:void 0;if(s&&(t===s.id||t===s.href))return s;{let n;for(let r=0;r<i.length&&(n=this.getByIndex(t,e,i[r].subitems??[]),!n);++r);return n}}landmark(t){if(!t)return this.landmarks;const e=this.landmarksByType[t];return e!==void 0?this.landmarks[e]:void 0}parseNav(t){const e=lt(t,"nav","toc");let i=[];if(!e)return i;const s=V(e,"ol",!0);return s&&(i=this.parseNavList(s)),i}parseNavList(t,e){const i=[];if(!t||!t.children)return i;for(let s=0;s<t.children.length;s++){const n=this.navItem(t.children[s],e);n&&i.push(n)}return i}navItem(t,e){let i=t.getAttribute("id")||void 0;const s=V(t,"a",!0)||V(t,"span",!0);if(!s)return;const n=s.getAttribute("href")||"";i||(i=n);const r=s.textContent||"";let o=[];const h=V(t,"ol",!0);return h&&(o=this.parseNavList(h,i)),{id:i,href:n,label:r,subitems:o,parent:e}}parseLandmarks(t){const e=lt(t,"nav","landmarks"),i=e?Array.from(M(e,"li")):[],s=i.length;let n;const r=[];let o;if(!i||s===0)return r;for(n=0;n<s;++n)o=this.landmarkItem(i[n]),o&&(r.push(o),this.landmarksByType[o.type]=n);return r}landmarkItem(t){const e=V(t,"a",!0);if(!e)return;const i=e.getAttributeNS("http://www.idpf.org/2007/ops","type")||void 0,s=e.getAttribute("href")||"",n=e.textContent||"";return{href:s,label:n,type:i}}parseNcx(t){const e=M(t,"navPoint"),i=e.length;let s;const n={},r=[];let o,h;if(!e||i===0)return r;for(s=0;s<i;++s)o=this.ncxItem(e[s]),n[o.id]=o,o.parent?(h=n[o.parent],h?h.subitems.push(o):r.push(o)):r.push(o);return r}ncxItem(t){const e=t.getAttribute("id")||"",i=b(t,"content"),s=i?i.getAttribute("src")??"":"",n=b(t,"navLabel"),r=n!=null&&n.textContent?n.textContent:"",o=[],h=t.parentNode;let a;return h&&(h.nodeName==="navPoint"||h.nodeName.split(":").slice(-1)[0]==="navPoint")&&(a=h.getAttribute("id")??void 0),{id:e,href:s,label:r,subitems:o,parent:a}}load(t){return t.map(e=>(e.label=e.title,e.subitems=e.children?this.load(e.children):[],e))}forEach(t){return this.toc.forEach(t)}}const Y={application:{ecmascript:["es","ecma"],javascript:"js",ogg:"ogx",pdf:"pdf",postscript:["ps","ai","eps","epsi","epsf","eps2","eps3"],"rdf+xml":"rdf",smil:["smi","smil"],"xhtml+xml":["xhtml","xht"],xml:["xml","xsl","xsd","opf","ncx"],zip:"zip","x-httpd-eruby":"rhtml","x-latex":"latex","x-maker":["frm","maker","frame","fm","fb","book","fbdoc"],"x-object":"o","x-shockwave-flash":["swf","swfl"],"x-silverlight":"scr","epub+zip":"epub","font-tdpfr":"pfr","inkml+xml":["ink","inkml"],json:"json","jsonml+json":"jsonml","mathml+xml":"mathml","metalink+xml":"metalink",mp4:"mp4s","omdoc+xml":"omdoc",oxps:"oxps","vnd.amazon.ebook":"azw",widget:"wgt","x-dtbook+xml":"dtb","x-dtbresource+xml":"res","x-font-bdf":"bdf","x-font-ghostscript":"gsf","x-font-linux-psf":"psf","x-font-otf":"otf","x-font-pcf":"pcf","x-font-snf":"snf","x-font-ttf":["ttf","ttc"],"x-font-type1":["pfa","pfb","pfm","afm"],"x-font-woff":"woff","x-mobipocket-ebook":["prc","mobi"],"x-mspublisher":"pub","x-nzb":"nzb","x-tgif":"obj","xaml+xml":"xaml","xml-dtd":"dtd","xproc+xml":"xpl","xslt+xml":"xslt","internet-property-stream":"acx","x-compress":"z","x-compressed":"tgz","x-gzip":"gz"},audio:{flac:"flac",midi:["mid","midi","kar","rmi"],mpeg:["mpga","mpega","mp2","mp3","m4a","mp2a","m2a","m3a"],mpegurl:"m3u",ogg:["oga","ogg","spx"],"x-aiff":["aif","aiff","aifc"],"x-ms-wma":"wma","x-wav":"wav",adpcm:"adp",mp4:"mp4a",webm:"weba","x-aac":"aac","x-caf":"caf","x-matroska":"mka","x-pn-realaudio-plugin":"rmp",xm:"xm",mid:["mid","rmi"]},image:{gif:"gif",ief:"ief",jpeg:["jpeg","jpg","jpe"],pcx:"pcx",png:"png","svg+xml":["svg","svgz"],tiff:["tiff","tif"],"x-icon":"ico",bmp:"bmp",webp:"webp","x-pict":["pic","pct"],"x-tga":"tga","cis-cod":"cod"},text:{"cache-manifest":["manifest","appcache"],css:"css",csv:"csv",html:["html","htm","shtml","stm"],mathml:"mml",plain:["txt","text","brf","conf","def","list","log","in","bas"],richtext:"rtx","tab-separated-values":"tsv","x-bibtex":"bib"},video:{mpeg:["mpeg","mpg","mpe","m1v","m2v","mp2","mpa","mpv2"],mp4:["mp4","mp4v","mpg4"],quicktime:["qt","mov"],ogg:"ogv","vnd.mpegurl":["mxu","m4u"],"x-flv":"flv","x-la-asf":["lsf","lsx"],"x-mng":"mng","x-ms-asf":["asf","asx","asr"],"x-ms-wm":"wm","x-ms-wmv":"wmv","x-ms-wmx":"wmx","x-ms-wvx":"wvx","x-msvideo":"avi","x-sgi-movie":"movie","x-matroska":["mpv","mkv","mk3d","mks"],"3gpp2":"3g2",h261:"h261",h263:"h263",h264:"h264",jpeg:"jpgv",jpm:["jpm","jpgm"],mj2:["mj2","mjp2"],"vnd.ms-playready.media.pyv":"pyv","vnd.uvvu.mp4":["uvu","uvvu"],"vnd.vivo":"viv",webm:"webm","x-f4v":"f4v","x-m4v":"m4v","x-ms-vob":"vob","x-smv":"smv"}},Se=(function(){let l,t,e,i;const s={};for(l in Y)if(Y.hasOwnProperty(l)){for(t in Y[l])if(Y[l].hasOwnProperty(t))if(e=Y[l][t],typeof e=="string")s[e]=l+"/"+t;else for(i=0;i<e.length;i++)s[e[i]]=l+"/"+t}return s})(),Ce="text/plain";function _e(l){return l&&Se[l.split(".").pop().toLowerCase()]||Ce}const H={lookup:_e};class Zt{constructor(t,e){this.settings={replacements:e&&e.replacements||"base64",archive:e&&e.archive,resolver:e&&e.resolver,request:e&&e.request},this.process(t)}process(t){this.manifest=t,this.resources=Object.keys(t).map(function(e){return t[e]}),this.replacementUrls=[],this.html=[],this.assets=[],this.css=[],this.urls=[],this.cssUrls=[],this.split(),this.splitUrls()}split(){this.html=this.resources.filter(function(t){return t.type==="application/xhtml+xml"||t.type==="text/html"}),this.assets=this.resources.filter(function(t){return t.type!=="application/xhtml+xml"&&t.type!=="text/html"}),this.css=this.resources.filter(function(t){return t.type==="text/css"})}splitUrls(){this.urls=this.assets.map(t=>t.href),this.cssUrls=this.css.map(function(t){return t.href})}createUrl(t){const e=new N(t),i=H.lookup(e.filename);return this.settings.archive?this.settings.archive.createUrl(t,{base64:this.settings.replacements==="base64"}):this.settings.replacements==="base64"?this.settings.request(t,"blob").then(s=>Xt(s)).then(s=>bt(s,i)):this.settings.request(t,"blob").then(s=>ot(s,i))}replacements(){if(this.settings.replacements==="none")return new Promise(e=>{e(this.urls)});const t=this.urls.map(e=>{const i=this.settings.resolver(e);return this.createUrl(i).catch(s=>(console.error(s),null))});return Promise.all(t).then(e=>(this.replacementUrls=e.filter(i=>typeof i=="string"),e))}replaceCss(t,e){const i=[];return this.cssUrls.forEach(s=>{const n=this.createCssFile(s).then(r=>{const o=this.urls.indexOf(s);r&&o>-1&&(this.replacementUrls[o]=r)});i.push(n)}),Promise.all(i)}createCssFile(t){let e;if(B.isAbsolute(t))return new Promise(function(r){r()});const i=this.settings.resolver(t);let s;this.settings.archive?s=this.settings.archive.getText(i):s=this.settings.request(i,"text");const n=this.urls.map(r=>{const o=this.settings.resolver(r);return new z(i).relative(o)});return s?s.then(r=>{const o=It(r,n,this.replacementUrls);return this.settings.replacements==="base64"?e=bt(o,"text/css"):e=ot(o,"text/css"),e},r=>new Promise(function(o){o()})):new Promise(function(r){r()})}relativeTo(t,e){return e=e||this.settings.resolver,this.urls.map(i=>{const s=e(i);return new z(t).relative(s)})}get(t){const e=this.urls.indexOf(t);if(e!==-1)return this.replacementUrls.length?new Promise((i,s)=>{i(this.replacementUrls[e])}):this.createUrl(t)}substitute(t,e){let i;return e?i=this.relativeTo(e):i=this.urls,It(t,i,this.replacementUrls)}destroy(){this.settings=void 0,this.manifest=void 0,this.resources=void 0,this.replacementUrls=void 0,this.html=void 0,this.assets=void 0,this.css=void 0,this.urls=void 0,this.cssUrls=void 0}}class et{constructor(t){this.pages=[],this.locations=[],this.epubcfi=new m,this.firstPage=0,this.lastPage=0,this.totalPages=0,this.toc=void 0,this.ncx=void 0,t&&(this.pageList=this.parse(t)),this.pageList&&this.pageList.length&&this.process(this.pageList)}parse(t){const e=b(t,"html"),i=b(t,"ncx");return e?this.parseNav(t):i?this.parseNcx(t):[]}parseNav(t){const e=lt(t,"nav","page-list"),i=e?Array.from(M(e,"li")):[],s=i.length;let n;const r=[];let o;if(!i||s===0)return r;for(n=0;n<s;++n)o=this.item(i[n]),r.push(o);return r}parseNcx(t){const e=[];let i=0,s,n=0;const r=b(t,"pageList");if(!r)return e;const o=M(r,"pageTarget");if(n=o.length,!o||o.length===0)return e;for(i=0;i<n;++i)s=this.ncxItem(o[i]),e.push(s);return e}ncxItem(t){const e=b(t,"navLabel"),s=b(e,"text").textContent??"",r=b(t,"content").getAttribute("src")??"",o=parseInt(s,10);return{href:r,page:o}}item(t){const e=b(t,"a"),i=e.getAttribute("href")||"",s=e.textContent||"",n=parseInt(s),r=i.indexOf("epubcfi");let o,h,a;return r!=-1?(o=i.split("#"),h=o[0],a=o.length>1?o[1]:void 0,{cfi:a,href:i,packageUrl:h,page:n}):{href:i,page:n}}process(t){t.forEach(e=>{this.pages.push(e.page),e.cfi&&this.locations.push(e.cfi)}),this.firstPage=this.pages[0],this.lastPage=this.pages[this.pages.length-1],this.totalPages=this.lastPage-this.firstPage}pageFromCfi(t){let e=-1;if(this.locations.length===0)return-1;let i=st(t,this.locations,this.epubcfi.compare);return i!=-1?e=this.pages[i]:(i=X(t,this.locations,this.epubcfi.compare),e=i-1>=0?this.pages[i-1]:this.pages[0],e!==void 0||(e=-1)),e}cfiFromPage(t){let e=-1;typeof t!="number"&&(t=parseInt(t));const i=this.pages.indexOf(t);return i!=-1&&i<this.locations.length&&(e=this.locations[i]),e}pageFromPercentage(t){return Math.round(this.totalPages*t)}percentageFromPage(t){const e=(t-this.firstPage)/this.totalPages;return Math.round(e*1e3)/1e3}percentageFromCfi(t){const e=this.pageFromCfi(t);return this.percentageFromPage(e)}destroy(){this.pages=void 0,this.locations=void 0,this.epubcfi=void 0,this.pageList=void 0,this.toc=void 0,this.ncx=void 0}}class Nt{constructor(t){this.settings=t,this.name=t.layout||"reflowable",this._spread=t.spread!=="none",this._minSpreadWidth=t.minSpreadWidth||800,this._evenSpreads=t.evenSpreads||!1,t.flow==="scrolled"||t.flow==="scrolled-continuous"||t.flow==="scrolled-doc"?this._flow="scrolled":this._flow="paginated",this.width=0,this.height=0,this.spreadWidth=0,this.delta=0,this.columnWidth=0,this.gap=0,this.divisor=1,this.props={name:this.name,spread:this._spread,flow:this._flow,width:0,height:0,spreadWidth:0,delta:0,columnWidth:0,gap:0,divisor:1}}flow(t){return typeof t<"u"&&(t==="scrolled"||t==="scrolled-continuous"||t==="scrolled-doc"?this._flow="scrolled":this._flow="paginated",this.update({flow:this._flow})),this._flow}spread(t,e){return t&&(this._spread=t!=="none",this.update({spread:this._spread})),e!==void 0&&e>=0&&(this._minSpreadWidth=e),this._spread}calculate(t,e,i){let s=1,n=i||0,r=t;const o=e,h=Math.floor(r/12);let a,c;this._spread&&r>=this._minSpreadWidth?s=2:s=1,this.name==="reflowable"&&this._flow==="paginated"&&!(i!==void 0&&i>=0)&&(n=h%2===0?h:h-1),this.name==="pre-paginated"&&(n=0),s>1?(a=r/s-n,c=a+n):(a=r,c=r),this.name==="pre-paginated"&&s>1&&(r=a);const d=a*s+n,u=r;this.width=r,this.height=o,this.spreadWidth=d,this.pageWidth=c,this.delta=u,this.columnWidth=a,this.gap=n,this.divisor=s,this.update({width:r,height:o,spreadWidth:d,pageWidth:c,delta:u,columnWidth:a,gap:n,divisor:s})}format(t,e,i){let s;return this.name==="pre-paginated"?s=t.fit(this.columnWidth,this.height,e):this._flow==="paginated"?s=t.columns(this.width,this.height,this.columnWidth,this.gap,this.settings.direction):i&&i==="horizontal"?s=t.size(void 0,this.height):s=t.size(this.width,void 0),s}count(t,e){let i,s;return this.name==="pre-paginated"?(i=1,s=1):this._flow==="paginated"?(e=e||this.delta,i=Math.ceil(t/e),s=i*this.divisor):(e=e||this.height,i=Math.ceil(t/e),s=i),{spreads:i,pages:s}}update(t){const e=t,i=this.props;if(Object.keys(e).forEach(s=>{i[s]===e[s]&&delete e[s]}),Object.keys(e).length>0){const s=_(this.props,t);this.emit(f.LAYOUT.UPDATED,s,t)}}}P(Nt.prototype);class Jt{constructor(t){this.rendition=t,this._themes={default:{rules:{},url:"",serialized:""}},this._overrides={},this._current="default",this._injected=[],this.rendition.hooks.content.register(e=>this.inject(e)),this.rendition.hooks.content.register(e=>this.overrides(e))}register(...t){if(t.length!==0){if(t.length===1&&typeof t[0]=="object")return this.registerThemes(t[0]);if(t.length===1&&typeof t[0]=="string")return this.default(t[0]);if(t.length===2&&typeof t[1]=="string")return this.registerUrl(t[0],t[1]);if(t.length===2&&typeof t[1]=="object")return this.registerRules(t[0],t[1])}}default(t){if(t){if(typeof t=="string")return this.registerUrl("default",t);if(typeof t=="object")return this.registerRules("default",t)}}registerThemes(t){for(const e in t)if(t.hasOwnProperty(e)){const i=t[e];typeof i=="string"?this.registerUrl(e,i):this.registerRules(e,i)}}registerCss(t,e){this._themes[t]={serialized:e},(this._injected[t]||t=="default")&&this.update(t)}registerUrl(t,e){const i=new N(e);this._themes[t]={url:i.toString()},(this._injected[t]||t=="default")&&this.update(t)}registerRules(t,e){this._themes[t]={rules:e},(this._injected[t]||t=="default")&&this.update(t)}select(t){const e=this._current;this._current=t,this.update(t),this.rendition.getContents().forEach(s=>{s.removeClass(e),s.addClass(t)})}update(t){this.rendition.getContents().forEach(i=>{this.add(t,i)})}inject(t){const e=[],i=this._themes;let s;for(const n in i)i.hasOwnProperty(n)&&(n===this._current||n==="default")&&(s=i[n],(s.rules&&Object.keys(s.rules).length>0||s.url&&e.indexOf(s.url)===-1||s.serialized)&&this.add(n,t),this._injected.push(n));this._current!="default"&&t.addClass(this._current)}add(t,e){const i=this._themes[t];!i||!e||(i.url?e.addStylesheet(i.url):i.serialized?(e.addStylesheetCss(i.serialized,t),i.injected=!0):i.rules&&(e.addStylesheetRules(i.rules,t),i.injected=!0))}override(t,e,i){const s=this.rendition.getContents();this._overrides[t]={value:e,priority:i===!0},s.forEach(n=>{n.css(t,this._overrides[t].value,this._overrides[t].priority)})}removeOverride(t){const e=this.rendition.getContents();delete this._overrides[t],e.forEach(i=>{i.css(t)})}overrides(t){const e=this._overrides;for(const i in e)e.hasOwnProperty(i)&&t.css(i,e[i].value,e[i].priority)}fontSize(t){this.override("font-size",t)}font(t){this.override("font-family",t,!0)}destroy(){this.rendition=void 0,this._themes=void 0,this._overrides=void 0,this._current=void 0,this._injected=void 0}}class Qt{constructor(t){this.rendition=t,this.highlights=[],this.underlines=[],this.marks=[],this._annotations={},this._annotationsBySectionIndex={},this.rendition.hooks.render.register(e=>this.inject(e)),this.rendition.hooks.unloaded.register(e=>this.clear(e))}add(t,e,i,s,n,r){const o=encodeURI(e+t),a=new m(e).spinePos,c=new te({type:t,cfiRange:e,data:i,sectionIndex:a,cb:s,className:n,styles:r});return this._annotations[o]=c,a in this._annotationsBySectionIndex?this._annotationsBySectionIndex[a].push(o):this._annotationsBySectionIndex[a]=[o],this.rendition.views().forEach(u=>{c.sectionIndex===u.index&&c.attach(u)}),c}remove(t,e){const i=encodeURI(t+e);if(i in this._annotations){const s=this._annotations[i];if(e&&s.type!==e)return;this.rendition.views().forEach(r=>{this._removeFromAnnotationBySectionIndex(s.sectionIndex,i),s.sectionIndex===r.index&&s.detach(r)}),delete this._annotations[i]}}_removeFromAnnotationBySectionIndex(t,e){this._annotationsBySectionIndex[t]=this._annotationsAt(t).filter(i=>i!==e)}_annotationsAt(t){return this._annotationsBySectionIndex[t]??[]}highlight(t,e,i,s,n){return this.add("highlight",t,e,i,s,n)}underline(t,e,i,s,n){return this.add("underline",t,e,i,s,n)}mark(t,e,i){return this.add("mark",t,e,i)}each(t){Object.keys(this._annotations).forEach(e=>{t(this._annotations[e],e)})}inject(t){const e=t.index;e in this._annotationsBySectionIndex&&this._annotationsBySectionIndex[e].forEach(s=>{const n=this._annotations[s];n&&n.attach(t)})}clear(t){const e=t.index;e in this._annotationsBySectionIndex&&this._annotationsBySectionIndex[e].forEach(s=>{const n=this._annotations[s];n&&n.detach(t)})}show(){}hide(){}}class te{constructor({type:t,cfiRange:e,data:i,sectionIndex:s,cb:n,className:r,styles:o}){this.type=t,this.cfiRange=e,this.data=i??{},this.sectionIndex=s??0,this.mark=void 0,this.cb=n,this.className=r??"",this.styles=o??{}}update(t){this.data=t}attach(t){const{cfiRange:e,data:i,type:s,mark:n,cb:r,className:o,styles:h}=this;let a;return s==="highlight"?a=t.highlight(e,i,r,o,h):s==="underline"?a=t.underline(e,i,r,o,h):s==="mark"&&(a=t.mark(e,i,r)),this.mark=a,this.emit(f.ANNOTATION.ATTACH,a),a}detach(t){const{cfiRange:e,type:i}=this;let s;return t&&(i==="highlight"?s=t.unhighlight(e):i==="underline"?s=t.ununderline(e):i==="mark"&&(s=t.unmark(e))),this.mark=void 0,this.emit(f.ANNOTATION.DETACH,s),s}text(){}}P(te.prototype);class at{constructor(t,e,i,s=!1){this.layout=t,this.horizontal=i==="horizontal",this.direction=e||"ltr",this._dev=s}section(t){const e=this.findRanges(t);return this.rangeListToCfiList(t.section.cfiBase,e)}page(t,e,i,s){const n=t&&t.document?t.document.body:!1;if(!n)return;const r=this.rangePairToCfiPair(e,{start:this.findStart(n,i,s),end:this.findEnd(n,i,s)});if(this._dev===!0){const o=t.document,h=new m(r.start).toRange(o),a=new m(r.end).toRange(o),c=o.defaultView.getSelection(),d=o.createRange();c.removeAllRanges(),d.setStart(h.startContainer,h.startOffset),d.setEnd(a.endContainer,a.endOffset),c.addRange(d)}return r}walk(t,e){const i={acceptNode(o){return o.data.trim().length>0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}},s=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,i);let n,r;for(;(n=s.nextNode())&&(r=e(n),!r););return r}findRanges(t){const e=[],i=t.contents.scrollWidth(),n=Math.ceil(i/this.layout.spreadWidth)*this.layout.divisor,r=this.layout.columnWidth,o=this.layout.gap;let h,a;for(let c=0;c<n;c++)h=(r+o)*c,a=r*(c+1)+o*c,e.push({start:this.findStart(t.document.body,h,a),end:this.findEnd(t.document.body,h,a)});return e}findStart(t,e,i){const s=[t];let n,r,o=t;for(;s.length;)if(n=s.shift(),r=this.walk(n,h=>{let a,c,d,u;const p=wt(h);if(this.horizontal&&this.direction==="ltr"){if(a=this.horizontal?p.left:p.top,c=this.horizontal?p.right:p.bottom,a>=e&&a<=i)return h;if(c>e)return h;o=h,s.push(h)}else if(this.horizontal&&this.direction==="rtl"){if(a=p.left,c=p.right,c<=i&&c>=e)return h;if(a<i)return h;o=h,s.push(h)}else{if(d=p.top,u=p.bottom,d>=e&&d<=i)return h;if(u>e)return h;o=h,s.push(h)}}),r)return this.findTextStartRange(r,e,i);return this.findTextStartRange(o,e,i)}findEnd(t,e,i){const s=[t];let n,r=t,o;for(;s.length;)if(n=s.shift(),o=this.walk(n,h=>{let a,c,d,u;const p=wt(h);if(this.horizontal&&this.direction==="ltr"){if(a=Math.round(p.left),c=Math.round(p.right),a>i&&r)return r;if(c>i)return h;r=h,s.push(h)}else if(this.horizontal&&this.direction==="rtl"){if(a=Math.round(this.horizontal?p.left:p.top),c=Math.round(this.horizontal?p.right:p.bottom),c<e&&r)return r;if(a<e)return h;r=h,s.push(h)}else{if(d=Math.round(p.top),u=Math.round(p.bottom),d>i&&r)return r;if(u>i)return h;r=h,s.push(h)}}),o)return this.findTextEndRange(o,e,i);return this.findTextEndRange(r,e,i)}findTextStartRange(t,e,i){const s=this.splitTextNodeIntoRanges(t);let n,r,o,h,a;for(let c=0;c<s.length;c++)if(n=s[c],r=n.getBoundingClientRect(),this.horizontal&&this.direction==="ltr"){if(o=r.left,o>=e)return n}else if(this.horizontal&&this.direction==="rtl"){if(a=r.right,a<=i)return n}else if(h=r.top,h>=e)return n;return s[0]}findTextEndRange(t,e,i){const s=this.splitTextNodeIntoRanges(t);let n,r,o,h,a,c,d;for(let u=0;u<s.length;u++){if(r=s[u],o=r.getBoundingClientRect(),this.horizontal&&this.direction==="ltr"){if(h=o.left,a=o.right,h>i&&n)return n;if(a>i)return r}else if(this.horizontal&&this.direction==="rtl"){if(h=o.left,a=o.right,a<e&&n)return n;if(h<e)return r}else{if(c=o.top,d=o.bottom,c>i&&n)return n;if(d>i)return r}n=r}return s[s.length-1]}splitTextNodeIntoRanges(t,e){const i=[],n=(t.textContent||"").trim();let r;const o=t.ownerDocument,h=e||" ";let a=n.indexOf(h);if(a===-1||t.nodeType!=Node.TEXT_NODE)return r=o.createRange(),r.selectNodeContents(t),[r];for(r=o.createRange(),r.setStart(t,0),r.setEnd(t,a),i.push(r),r=null;a!=-1;)a=n.indexOf(h,a+1),a>0&&(r&&(r.setEnd(t,a),i.push(r)),r=o.createRange(),r.setStart(t,a+1));return r&&(r.setEnd(t,n.length),i.push(r)),i}rangePairToCfiPair(t,e){const i=e.start,s=e.end;i.collapse(!0),s.collapse(!1);const n=new m(i,t).toString(),r=new m(s,t).toString();return{start:n,end:r}}rangeListToCfiList(t,e){const i=[];let s;for(let n=0;n<e.length;n++)s=this.rangePairToCfiPair(t,e[n]),i.push(s);return i}axis(t){return t&&(this.horizontal=t==="horizontal"),this.horizontal}}const ee=typeof navigator<"u",Te=ee&&/Chrome/.test(navigator.userAgent),Ot=ee&&!Te&&/AppleWebKit/.test(navigator.userAgent),ke=1;class ft{constructor(t,e,i,s){this.epubcfi=new m,this.document=t,this.documentElement=this.document.documentElement,this.content=e||this.document.body,this.window=this.document.defaultView,this._size={width:0,height:0},this.sectionIndex=s||0,this.cfiBase=i||"",this._mediaQueryHandlers=[],this.epubReadingSystem("epub.js",ut),this.called=0,this.active=!0,this.listeners()}static get listenedEvents(){return Q}width(t){const e=this.content;return t&&E(t)&&(t=t+"px"),t&&(e.style.width=t),parseInt(this.window.getComputedStyle(e).width)}height(t){const e=this.content;return t&&E(t)&&(t=t+"px"),t&&(e.style.height=t),parseInt(this.window.getComputedStyle(e).height)}contentWidth(t){const e=this.content||this.document.body;return t&&E(t)&&(t=t+"px"),t&&(e.style.width=t),parseInt(this.window.getComputedStyle(e).width)}contentHeight(t){const e=this.content||this.document.body;return t&&E(t)&&(t=t+"px"),t&&(e.style.height=t),parseInt(this.window.getComputedStyle(e).height)}textWidth(){let t;const e=this.document.createRange(),i=this.content||this.document.body,s=nt(i);return e.selectNodeContents(i),t=e.getBoundingClientRect().width,s&&s.width&&(t+=s.width),Math.round(t)}textHeight(){const t=this.document.createRange(),e=this.content||this.document.body;t.selectNodeContents(e);const s=t.getBoundingClientRect().bottom;return Math.round(s)}scrollWidth(){return this.documentElement.scrollWidth}scrollHeight(){return this.documentElement.scrollHeight}overflow(t){return t&&(this.documentElement.style.overflow=t),this.window.getComputedStyle(this.documentElement).overflow}overflowX(t){return t&&(this.documentElement.style.overflowX=t),this.window.getComputedStyle(this.documentElement).overflowX}overflowY(t){return t&&(this.documentElement.style.overflowY=t),this.window.getComputedStyle(this.documentElement).overflowY}css(t,e,i){const s=this.content||this.document.body;return e?s.style.setProperty(t,e,i?"important":""):s.style.removeProperty(t),this.window.getComputedStyle(s)[t]}viewport(t){let e=this.document.querySelector("meta[name='viewport']");const i={width:void 0,height:void 0,scale:void 0,minimum:void 0,maximum:void 0,scalable:void 0},s=[];let n={};if(e&&e.hasAttribute("content")){const r=e.getAttribute("content")??"",o=r.match(/width\s*=\s*([^,]*)/),h=r.match(/height\s*=\s*([^,]*)/),a=r.match(/initial-scale\s*=\s*([^,]*)/),c=r.match(/minimum-scale\s*=\s*([^,]*)/),d=r.match(/maximum-scale\s*=\s*([^,]*)/),u=r.match(/user-scalable\s*=\s*([^,]*)/);o&&o.length&&typeof o[1]<"u"&&(i.width=o[1]),h&&h.length&&typeof h[1]<"u"&&(i.height=h[1]),a&&a.length&&typeof a[1]<"u"&&(i.scale=a[1]),c&&c.length&&typeof c[1]<"u"&&(i.minimum=c[1]),d&&d.length&&typeof d[1]<"u"&&(i.maximum=d[1]),u&&u.length&&typeof u[1]<"u"&&(i.scalable=u[1])}return n=qt(t??{},i),t&&(n.width&&s.push("width="+n.width),n.height&&s.push("height="+n.height),n.scale&&s.push("initial-scale="+n.scale),n.scalable==="no"?(s.push("minimum-scale="+n.scale),s.push("maximum-scale="+n.scale),s.push("user-scalable="+n.scalable)):(n.scalable&&s.push("user-scalable="+n.scalable),n.minimum&&s.push("minimum-scale="+n.minimum),n.maximum&&s.push("minimum-scale="+n.maximum)),e||(e=this.document.createElement("meta"),e.setAttribute("name","viewport"),this.document.querySelector("head").appendChild(e)),e.setAttribute("content",s.join(", ")),this.window.scrollTo(0,0)),n}expand(){this.emit(f.CONTENTS.EXPAND)}listeners(){this.imageLoadListeners(),this.mediaQueryListeners(),this.addEventListeners(),this.addSelectionListeners(),typeof ResizeObserver>"u"?(this.resizeListeners(),this.visibilityListeners()):this.resizeObservers(),this.linksHandler()}removeListeners(){this.removeEventListeners(),this.removeSelectionListeners(),this._onVisibilityChange&&(document.removeEventListener("visibilitychange",this._onVisibilityChange),this._onVisibilityChange=void 0),this._resizeCheck&&(this.document.removeEventListener("transitionend",this._resizeCheck),this._resizeCheck=void 0);for(const{mql:e,handler:i}of this._mediaQueryHandlers)e.removeEventListener("change",i);this._mediaQueryHandlers=[],this.observer&&this.observer.disconnect(),clearTimeout(this.expanding);const t=this.document.querySelectorAll("img");for(let e=0;e<t.length;e++)t[e].onload=null}resizeCheck(){const t=this.textWidth(),e=this.textHeight();(t!=this._size.width||e!=this._size.height)&&(this._size={width:t,height:e},this.onResize&&this.onResize(this._size),this.emit(f.CONTENTS.RESIZE,this._size))}resizeListeners(){clearTimeout(this.expanding),requestAnimationFrame(this.resizeCheck.bind(this)),this.expanding=setTimeout(this.resizeListeners.bind(this),350)}visibilityListeners(){this._onVisibilityChange=()=>{document.visibilityState==="visible"&&this.active===!1?(this.active=!0,this.resizeListeners()):(this.active=!1,clearTimeout(this.expanding))},document.addEventListener("visibilitychange",this._onVisibilityChange)}transitionListeners(){const t=this.content;t.style.transitionProperty="font, font-size, font-size-adjust, font-stretch, font-variation-settings, font-weight, width, height",t.style.transitionDuration="0.001ms",t.style.transitionTimingFunction="linear",t.style.transitionDelay="0",this._resizeCheck=this.resizeCheck.bind(this),this.document.addEventListener("transitionend",this._resizeCheck)}mediaQueryListeners(){const t=this.document.styleSheets,e=i=>{i.matches&&!this._expanding&&setTimeout(this.expand.bind(this),1)};for(let i=0;i<t.length;i+=1){let s;try{s=t[i].cssRules}catch{return}if(!s)return;for(let n=0;n<s.length;n+=1)if(s[n].media){const r=this.window.matchMedia(s[n].media.mediaText);r.addEventListener("change",e),this._mediaQueryHandlers.push({mql:r,handler:e})}}}resizeObservers(){this.observer=new ResizeObserver(t=>{requestAnimationFrame(this.resizeCheck.bind(this))}),this.observer.observe(this.document.documentElement)}mutationObservers(){this.observer=new MutationObserver(e=>{this.resizeCheck()});const t={attributes:!0,childList:!0,characterData:!0,subtree:!0};this.observer.observe(this.document,t)}imageLoadListeners(){const t=this.document.querySelectorAll("img");let e;for(let i=0;i<t.length;i++)e=t[i],typeof e.naturalWidth<"u"&&e.naturalWidth===0&&(e.onload=this.expand.bind(this))}fontLoadListeners(){!this.document||!this.document.fonts||this.document.fonts.ready.then(()=>{this.resizeCheck()})}root(){return this.document?this.document.documentElement:null}locationOf(t,e){let i;const s={left:0,top:0};if(!this.document)return s;if(this.epubcfi.isCfiString(t)){const n=new m(t).toRange(this.document,e);if(n){try{if(!n.endContainer||n.startContainer==n.endContainer&&n.startOffset==n.endOffset){let r=(n.startContainer.textContent??"").indexOf(" ",n.startOffset);r==-1&&(r=(n.startContainer.textContent??"").length),n.setEnd(n.startContainer,r)}}catch(r){console.error("setting end offset to start container length failed",r)}if(n.startContainer.nodeType===Node.ELEMENT_NODE)i=n.startContainer.getBoundingClientRect(),s.left=i.left,s.top=i.top;else if(Ot){const r=n.startContainer,o=new Range;try{r.nodeType===ke?i=r.getBoundingClientRect():n.startOffset+2<r.length?(o.setStart(r,n.startOffset),o.setEnd(r,n.startOffset+2),i=o.getBoundingClientRect()):n.startOffset-2>0?(o.setStart(r,n.startOffset-2),o.setEnd(r,n.startOffset),i=o.getBoundingClientRect()):i=r.parentNode.getBoundingClientRect()}catch(h){console.error(h,h instanceof Error?h.stack:void 0)}}else i=n.getBoundingClientRect()}}else if(typeof t=="string"&&t.indexOf("#")>-1){const n=t.substring(t.indexOf("#")+1),r=this.document.getElementById(n);if(r)if(Ot){const o=new Range;o.selectNode(r),i=o.getBoundingClientRect()}else i=r.getBoundingClientRect()}return i&&(s.left=i.left,s.top=i.top),s}addStylesheet(t){return new Promise((e,i)=>{let s,n=!1;if(!this.document){e(!1);return}if(s=this.document.querySelector("link[href='"+t+"']"),s){e(!0);return}s=this.document.createElement("link"),s.type="text/css",s.rel="stylesheet",s.href=t,s.onload=()=>{n||(n=!0,setTimeout(()=>{e(!0)},1))},this.document.head.appendChild(s)})}_getStylesheetNode(t){let e;return t="epubjs-inserted-css-"+(t||""),this.document?(e=this.document.getElementById(t),e||(e=this.document.createElement("style"),e.id=t,this.document.head.appendChild(e)),e):!1}addStylesheetCss(t,e){if(!this.document||!t)return!1;const i=this._getStylesheetNode(e);return i?(i.textContent=t,!0):!1}addStylesheetRules(t,e){var s;if(!this.document||!t||Array.isArray(t)&&t.length===0)return;const i=this._getStylesheetNode(e).sheet;if(Array.isArray(t))for(let n=0,r=t.length;n<r;n++){let o=1,h=t[n],a="";const c=t[n][0];Array.isArray((s=h[1])==null?void 0:s[0])&&(h=h[1],o=0);for(let d=h.length;o<d;o++){const u=h[o];a+=u[0]+":"+u[1]+(u[2]?" !important":"")+`;
3
+ `}i.insertRule(c+"{"+a+"}",i.cssRules.length)}else Object.keys(t).forEach(r=>{const o=t[r];if(Array.isArray(o))o.forEach(h=>{const c=Object.keys(h).map(d=>`${d}:${h[d]}`).join(";");i.insertRule(`${r}{${c}}`,i.cssRules.length)});else{const a=Object.keys(o).map(c=>`${c}:${o[c]}`).join(";");i.insertRule(`${r}{${a}}`,i.cssRules.length)}})}addScript(t){return new Promise((e,i)=>{let s=!1;if(!this.document){e(!1);return}const n=this.document.createElement("script");n.type="text/javascript",n.async=!0,n.src=t,n.onload=()=>{s||(s=!0,setTimeout(()=>{e(!0)},1))},this.document.head.appendChild(n)})}addClass(t){if(!this.document)return;const e=this.content||this.document.body;e&&e.classList.add(t)}removeClass(t){if(!this.document)return;const e=this.content||this.document.body;e&&e.classList.remove(t)}addEventListeners(){this.document&&(this._triggerEvent=this.triggerEvent.bind(this),Q.forEach(t=>{this.document.addEventListener(t,this._triggerEvent,{passive:!0})}))}removeEventListeners(){this.document&&(Q.forEach(t=>{this.document.removeEventListener(t,this._triggerEvent)}),this._triggerEvent=void 0)}triggerEvent(t){this.emit(t.type,t)}addSelectionListeners(){this.document&&(this._onSelectionChange=this.onSelectionChange.bind(this),this.document.addEventListener("selectionchange",this._onSelectionChange,{passive:!0}))}removeSelectionListeners(){this.document&&(this.document.removeEventListener("selectionchange",this._onSelectionChange),this._onSelectionChange=void 0)}onSelectionChange(t){this.selectionEndTimeout&&clearTimeout(this.selectionEndTimeout),this.selectionEndTimeout=setTimeout(()=>{const e=this.window.getSelection();e&&this.triggerSelectedEvent(e)},250)}triggerSelectedEvent(t){let e,i;t&&t.rangeCount>0&&(e=t.getRangeAt(0),e.collapsed||(i=new m(e,this.cfiBase).toString(),this.emit(f.CONTENTS.SELECTED,i),this.emit(f.CONTENTS.SELECTED_RANGE,e)))}range(t,e){return new m(t).toRange(this.document,e)}cfiFromRange(t,e){return new m(t,this.cfiBase,e).toString()}cfiFromNode(t,e){return new m(t,this.cfiBase,e).toString()}size(t,e){const i={scale:1,scalable:"no"};this.layoutStyle("scrolling"),t!==void 0&&t>=0&&(this.width(t),i.width=t,this.css("padding","0 "+t/12+"px")),e!==void 0&&e>=0&&(this.height(e),i.height=e),this.css("margin","0"),this.css("box-sizing","border-box"),this.viewport(i)}columns(t,e,i,s,n){const r=j("column-axis"),o=j("column-gap"),h=j("column-width"),a=j("column-fill"),d=this.writingMode().indexOf("vertical")===0?"vertical":"horizontal";this.layoutStyle("paginated"),n==="rtl"&&d==="horizontal"&&this.direction(n),this.width(t),this.height(e),this.viewport({width:t,height:e,scale:1,scalable:"no"}),this.css("display","inline-block"),this.css("overflow-y","hidden"),this.css("margin","0",!0),d==="vertical"?(this.css("padding-top",s/2+"px",!0),this.css("padding-bottom",s/2+"px",!0),this.css("padding-left","20px"),this.css("padding-right","20px"),this.css(r,"vertical")):(this.css("padding-top","20px"),this.css("padding-bottom","20px"),this.css("padding-left",s/2+"px",!0),this.css("padding-right",s/2+"px",!0),this.css(r,"horizontal")),this.css("box-sizing","border-box"),this.css("max-width","inherit"),this.css(a,"auto"),this.css(o,s+"px"),this.css(h,i+"px")}scaler(t,e,i){const s="scale("+t+")";let n="";this.css("transform-origin","top left"),(e!==void 0&&e>=0||i!==void 0&&i>=0)&&(n=" translate("+(e||0)+"px, "+(i||0)+"px )"),this.css("transform",s+n)}fit(t,e,i){const s=this.viewport(),n=parseInt(s.width),r=parseInt(s.height),o=t/n,h=e/r,a=o<h?o:h;if(this.layoutStyle("paginated"),this.width(n),this.height(r),this.overflow("hidden"),this.scaler(a,0,0),this.css("background-size",n*a+"px "+r*a+"px"),this.css("background-color","transparent"),i&&i.properties.includes("page-spread-left")){const c=t-n*a;this.css("margin-left",c+"px")}}direction(t){this.documentElement&&(this.documentElement.style.direction=t)}mapPage(t,e,i,s,n){return new at(e,void 0,void 0,n).page(this,t,i,s)}linksHandler(){xe(this.content,t=>{this.emit(f.CONTENTS.LINK_CLICKED,t)})}writingMode(t){const e=j("writing-mode");return t&&this.documentElement&&(this.documentElement.style[e]=t),this.window.getComputedStyle(this.documentElement)[e]||""}layoutStyle(t){return t&&(this._layoutStyle=t,navigator.epubReadingSystem.layoutStyle=this._layoutStyle),this._layoutStyle||"paginated"}epubReadingSystem(t,e){return navigator.epubReadingSystem={name:t,version:e,layoutStyle:this.layoutStyle(),hasFeature:function(i){switch(i){case"dom-manipulation":return!0;case"layout-changes":return!0;case"touch-events":return!0;case"mouse-events":return!0;case"keyboard-events":return!0;case"spine-scripting":return!1;default:return!1}}},navigator.epubReadingSystem}destroy(){this.removeListeners(),this.__listeners={}}}P(ft.prototype);function Z(l){return document.createElementNS("http://www.w3.org/2000/svg",l)}function Le(l,t){function e(s){for(let n=t.length-1;n>=0;n--){const r=t[n];let o,h;if("touches"in s&&s.touches.length?(o=s.touches[0].clientX,h=s.touches[0].clientY):(o=s.clientX,h=s.clientY),!!Ne(r,l,o,h)){r.dispatchEvent(Re(s));break}}}let i;if(l.nodeName==="iframe"||l.nodeName==="IFRAME")try{i=l.contentDocument}catch{i=l}else i=l;for(const s of["mouseup","mousedown","click","touchstart"])i.addEventListener(s,n=>e(n),!1)}function Re(l){const t=Object.assign({},l,{bubbles:!1});try{return new MouseEvent(l.type,t)}catch{const i=l,s=document.createEvent("MouseEvents");return s.initMouseEvent(l.type,!1,i.cancelable,i.view,i.detail,i.screenX,i.screenY,i.clientX,i.clientY,i.ctrlKey,i.altKey,i.shiftKey,i.metaKey,i.button,i.relatedTarget),s}}function Ne(l,t,e,i){const s=t.getBoundingClientRect();function n(h,a,c){const d=h.top-s.top,u=h.left-s.left,p=d+h.height,g=u+h.width;return d<=c&&u<=a&&p>c&&g>a}const r=l.getBoundingClientRect();if(!n(r,e,i))return!1;const o=l.getClientRects();for(let h=0,a=o.length;h<a;h++)if(n(o[h],e,i))return!0;return!1}function Ae(l,t){const e=t.getBoundingClientRect(),i=l.getBoundingClientRect();return{top:i.top-e.top,left:i.left-e.left,height:l.scrollHeight,width:l.scrollWidth}}function Ie(l,t){l.style.setProperty("top",`${t.top}px`,"important"),l.style.setProperty("left",`${t.left}px`,"important"),l.style.setProperty("height",`${t.height}px`,"important"),l.style.setProperty("width",`${t.width}px`,"important")}function Oe(l,t){return t.right<=l.right&&t.left>=l.left&&t.top>=l.top&&t.bottom<=l.bottom}class Pt{constructor(t,e=document.body){this.target=t,this.element=Z("svg"),this.marks=[],this.element.style.position="absolute",this.element.setAttribute("pointer-events","none"),Le(this.target,this.marks),this.container=e,this.container.appendChild(this.element),this.render()}addMark(t){const e=Z("g");return this.element.appendChild(e),t.bind(e,this.container),this.marks.push(t),t.render(),t}removeMark(t){const e=this.marks.indexOf(t);if(e===-1)return;const i=t.unbind();this.element.removeChild(i),this.marks.splice(e,1)}render(){Ie(this.element,Ae(this.target,this.container));for(const t of this.marks)t.render()}}class Pe{constructor(){this.element=null}bind(t,e){this.element=t,this.container=e}unbind(){const t=this.element;return this.element=null,t}render(){}dispatchEvent(t){this.element&&this.element.dispatchEvent(t)}getBoundingClientRect(){return this.element.getBoundingClientRect()}getClientRects(){const t=[];let e=this.element.firstChild;for(;e;)t.push(e.getBoundingClientRect()),e=e.nextSibling;return t}filteredRanges(){const t=Array.from(this.range.getClientRects());return t.filter(e=>{for(let i=0;i<t.length;i++){if(t[i]===e)return!0;if(Oe(t[i],e))return!1}return!0})}}class ie extends Pe{constructor(t,e,i,s){super(),this.range=t,this.className=e,this.data=i||{},this.attributes=s||{}}bind(t,e){super.bind(t,e);for(const i in this.data)this.data.hasOwnProperty(i)&&(this.element.dataset[i]=this.data[i]);for(const i in this.attributes)this.attributes.hasOwnProperty(i)&&this.element.setAttribute(i,this.attributes[i]);this.className&&this.element.classList.add(this.className)}render(){for(;this.element.firstChild;)this.element.removeChild(this.element.firstChild);const t=this.element.ownerDocument.createDocumentFragment(),e=this.filteredRanges(),i=this.element.getBoundingClientRect(),s=this.container.getBoundingClientRect();for(let n=0,r=e.length;n<r;n++){const o=e[n],h=Z("rect");h.setAttribute("x",String(o.left-i.left+s.left)),h.setAttribute("y",String(o.top-i.top+s.top)),h.setAttribute("height",String(o.height)),h.setAttribute("width",String(o.width)),t.appendChild(h)}this.element.appendChild(t)}}class ze extends ie{constructor(t,e,i,s){super(t,e,i,s)}render(){for(;this.element.firstChild;)this.element.removeChild(this.element.firstChild);const t=this.element.ownerDocument.createDocumentFragment(),e=this.filteredRanges(),i=this.element.getBoundingClientRect(),s=this.container.getBoundingClientRect();for(let n=0,r=e.length;n<r;n++){const o=e[n],h=Z("rect");h.setAttribute("x",String(o.left-i.left+s.left)),h.setAttribute("y",String(o.top-i.top+s.top)),h.setAttribute("height",String(o.height)),h.setAttribute("width",String(o.width)),h.setAttribute("fill","none");const a=Z("line");a.setAttribute("x1",String(o.left-i.left+s.left)),a.setAttribute("x2",String(o.left-i.left+s.left+o.width)),a.setAttribute("y1",String(o.top-i.top+s.top+o.height-1)),a.setAttribute("y2",String(o.top-i.top+s.top+o.height-1)),a.setAttribute("stroke-width","1"),a.setAttribute("stroke","black"),a.setAttribute("stroke-linecap","square"),t.appendChild(h),t.appendChild(a)}this.element.appendChild(t)}}class se{constructor(t,e){this.settings=_({ignoreClass:"",axis:void 0,direction:void 0,width:0,height:0,layout:void 0,globalLayoutProperties:{},method:void 0,forceRight:!1,allowScriptedContent:!1,allowPopups:!1},e||{}),this.id="epubjs-view-"+dt(),this.section=t,this.index=t.index,this.element=this.container(this.settings.axis),this.added=!1,this.displayed=!1,this.rendered=!1,this.fixedWidth=0,this.fixedHeight=0,this.epubcfi=new m,this.layout=this.settings.layout,this.pane=void 0,this.highlights={},this.underlines={},this.marks={}}container(t){const e=document.createElement("div");return e.classList.add("epub-view"),e.style.height="0px",e.style.width="0px",e.style.overflow="hidden",e.style.position="relative",e.style.display="block",t&&t=="horizontal"?e.style.flex="none":e.style.flex="initial",e}create(){return this.iframe?this.iframe:(this.element||(this.element=this.container()),this.iframe=document.createElement("iframe"),this.iframe.id=this.id,this.iframe.scrolling="no",this.iframe.style.overflow="hidden",this.iframe.seamless="seamless",this.iframe.style.border="none",this.iframe.sandbox="allow-same-origin",this.settings.allowScriptedContent&&(this.iframe.sandbox+=" allow-scripts"),this.settings.allowPopups&&(this.iframe.sandbox+=" allow-popups"),this.iframe.setAttribute("enable-annotation","true"),this.resizing=!0,this.element.style.visibility="hidden",this.iframe.style.visibility="hidden",this.iframe.style.width="0",this.iframe.style.height="0",this._width=0,this._height=0,this.element.setAttribute("ref",String(this.index)),this.added=!0,this.elementBounds=J(this.element),"srcdoc"in this.iframe?this.supportsSrcdoc=!0:this.supportsSrcdoc=!1,this.settings.method||(this.settings.method=this.supportsSrcdoc?"srcdoc":"write"),this.iframe)}render(t,e){return this.create(),this.size(),this.sectionRender||(this.sectionRender=this.section.render(t)),this.sectionRender.then(i=>this.load(i)).then(()=>{const i=this.contents.writingMode();let s;return this.settings.flow==="scrolled"?s=i.indexOf("vertical")===0?"horizontal":"vertical":s=i.indexOf("vertical")===0?"vertical":"horizontal",i.indexOf("vertical")===0&&this.settings.flow==="paginated"&&(this.layout.delta=this.layout.height),this.setAxis(s),this.emit(f.VIEWS.AXIS,s),this.setWritingMode(i),this.emit(f.VIEWS.WRITING_MODE,i),this.layout.format(this.contents,this.section,this.axis),this.addListeners(),new Promise((n,r)=>{this.expand(),this.settings.forceRight&&(this.element.style.marginLeft=this.width()+"px"),n()})},i=>(this.emit(f.VIEWS.LOAD_ERROR,i),new Promise((s,n)=>{n(i)}))).then(()=>{this.emit(f.VIEWS.RENDERED,this.section)})}reset(){this.iframe&&(this.iframe.style.width="0",this.iframe.style.height="0",this._width=0,this._height=0,this._textWidth=void 0,this._contentWidth=void 0,this._textHeight=void 0,this._contentHeight=void 0),this._needsReframe=!0}size(t,e){const i=t||this.settings.width,s=e||this.settings.height;this.layout.name==="pre-paginated"?this.lock("both",i,s):this.settings.axis==="horizontal"?this.lock("height",i,s):this.lock("width",i,s),this.settings.width=i,this.settings.height=s}lock(t,e,i){const s=nt(this.element);let n;this.iframe?n=nt(this.iframe):n={width:0,height:0},t=="width"&&E(e)&&(this.lockedWidth=e-s.width-n.width),t=="height"&&E(i)&&(this.lockedHeight=i-s.height-n.height),t==="both"&&E(e)&&E(i)&&(this.lockedWidth=e-s.width-n.width,this.lockedHeight=i-s.height-n.height),this.displayed&&this.iframe&&this.expand()}expand(t){let e=this.lockedWidth,i=this.lockedHeight,s;!this.iframe||this._expanding||(this._expanding=!0,this.layout.name==="pre-paginated"?(e=this.layout.columnWidth,i=this.layout.height):this.settings.axis==="horizontal"?(e=this.contents.textWidth(),e%this.layout.pageWidth>0&&(e=Math.ceil(e/this.layout.pageWidth)*this.layout.pageWidth),this.settings.forceEvenPages&&(s=e/this.layout.pageWidth,this.layout.divisor>1&&this.layout.name==="reflowable"&&s%2>0&&(e+=this.layout.pageWidth))):this.settings.axis==="vertical"&&(i=this.contents.textHeight(),this.settings.flow==="paginated"&&i%this.layout.height>0&&(i=Math.ceil(i/this.layout.height)*this.layout.height)),(this._needsReframe||e!=this._width||i!=this._height)&&this.reframe(e,i),this._expanding=!1)}reframe(t,e){E(t)&&(this.element.style.width=t+"px",this.iframe.style.width=t+"px",this._width=t),E(e)&&(this.element.style.height=e+"px",this.iframe.style.height=e+"px",this._height=e);const i=this.prevBounds?t-this.prevBounds.width:t,s=this.prevBounds?e-this.prevBounds.height:e,n={width:t,height:e,widthDelta:i,heightDelta:s};this.pane&&this.pane.render(),requestAnimationFrame(()=>{let r;for(const o in this.marks)this.marks.hasOwnProperty(o)&&(r=this.marks[o],this.placeMark(r.element,r.range))}),this.onResize(this,n),this.emit(f.VIEWS.RESIZED,n),this.prevBounds=n,this.elementBounds=J(this.element)}load(t){const e=new y,i=e.promise;if(!this.iframe)return e.reject(new Error("No Iframe Available")),i;if(this.iframe.onload=s=>{this.onLoad(s,e)},this.settings.method==="blobUrl")this.blobUrl=ot(t,"application/xhtml+xml"),this.iframe.src=this.blobUrl,this.element.appendChild(this.iframe);else if(this.settings.method==="srcdoc")this.iframe.srcdoc=t,this.element.appendChild(this.iframe);else{if(this.element.appendChild(this.iframe),this.document=this.iframe.contentDocument,!this.document)return e.reject(new Error("No Document Available")),i;this.document.open(),this.document.write(t),this.document.close()}return i}onLoad(t,e){this.window=this.iframe.contentWindow,this.document=this.iframe.contentDocument,this.contents=new ft(this.document,this.document.body,this.section.cfiBase,this.section.index),this.rendering=!1;let i=this.document.querySelector("link[rel='canonical']");i?i.setAttribute("href",this.section.canonical):(i=this.document.createElement("link"),i.setAttribute("rel","canonical"),i.setAttribute("href",this.section.canonical),this.document.querySelector("head").appendChild(i)),this.contents.on(f.CONTENTS.EXPAND,()=>{this.displayed&&this.iframe&&(this.expand(),this.contents&&this.layout.format(this.contents))}),this.contents.on(f.CONTENTS.RESIZE,s=>{this.displayed&&this.iframe&&(this.expand(),this.contents&&this.layout.format(this.contents))}),e.resolve(this.contents)}setLayout(t){this.layout=t,this.contents&&(this.layout.format(this.contents),this.expand())}setAxis(t){this.settings.axis=t,t=="horizontal"?this.element.style.flex="none":this.element.style.flex="initial",this.size()}setWritingMode(t){this.writingMode=t}addListeners(){}removeListeners(t){this.contents&&(this.contents.off(f.CONTENTS.EXPAND),this.contents.off(f.CONTENTS.RESIZE))}display(t){const e=new y;return this.displayed?e.resolve(this):this.render(t).then(()=>{this.emit(f.VIEWS.DISPLAYED,this),this.onDisplayed(this),this.displayed=!0,e.resolve(this)},i=>{e.reject(i)}),e.promise}show(){this.element.style.visibility="visible",this.iframe&&(this.iframe.style.visibility="visible",this.iframe.style.transform="translateZ(0)",this.iframe.offsetWidth,this.iframe.style.transform=""),this.emit(f.VIEWS.SHOWN,this)}hide(){this.element.style.visibility="hidden",this.iframe.style.visibility="hidden",this.stopExpanding=!0,this.emit(f.VIEWS.HIDDEN,this)}offset(){return{top:this.element.offsetTop,left:this.element.offsetLeft}}width(){return this._width}height(){return this._height}position(){return this.element.getBoundingClientRect()}locationOf(t){this.iframe.getBoundingClientRect();const e=this.contents.locationOf(t,this.settings.ignoreClass);return{left:e.left,top:e.top}}onDisplayed(t){}onResize(t,e){}bounds(t){return(t||!this.elementBounds)&&(this.elementBounds=J(this.element)),this.elementBounds}highlight(t,e={},i,s="epubjs-hl",n={}){if(!this.contents)return;const r=Object.assign({fill:"yellow","fill-opacity":"0.3","mix-blend-mode":"multiply"},n),o=this.contents.range(t),h=()=>{this.emit(f.VIEWS.MARK_CLICKED,t,e)};e.epubcfi=t,this.pane||(this.pane=new Pt(this.iframe,this.element));const a=new ie(o,s,e,r);let c;try{c=this.pane.addMark(a)}catch(d){console.error("Failed to add highlight for",t,d);return}return this.highlights[t]={mark:c,element:c.element,listeners:[h,i]},c.element.setAttribute("ref",s),c.element.addEventListener("click",h),c.element.addEventListener("touchstart",h),i&&(c.element.addEventListener("click",i),c.element.addEventListener("touchstart",i)),c}underline(t,e={},i,s="epubjs-ul",n={}){if(!this.contents)return;const r=Object.assign({stroke:"black","stroke-opacity":"0.3","mix-blend-mode":"multiply"},n),o=this.contents.range(t),h=()=>{this.emit(f.VIEWS.MARK_CLICKED,t,e)};e.epubcfi=t,this.pane||(this.pane=new Pt(this.iframe,this.element));const a=new ze(o,s,e,r);let c;try{c=this.pane.addMark(a)}catch(d){console.error("Failed to add underline for",t,d);return}return this.underlines[t]={mark:c,element:c.element,listeners:[h,i]},c.element.setAttribute("ref",s),c.element.addEventListener("click",h),c.element.addEventListener("touchstart",h),i&&(c.element.addEventListener("click",i),c.element.addEventListener("touchstart",i)),c}mark(t,e={},i){if(!this.contents)return;if(t in this.marks)return this.marks[t];let s=this.contents.range(t);if(!s)return;const n=s.commonAncestorContainer,r=n.nodeType===1?n:n.parentNode,o=a=>{this.emit(f.VIEWS.MARK_CLICKED,t,e)};s.collapsed&&n.nodeType===1?(s=new Range,s.selectNodeContents(n)):s.collapsed&&(s=new Range,s.selectNodeContents(r));const h=this.document.createElement("a");return h.setAttribute("ref","epubjs-mk"),h.style.position="absolute",h.dataset.epubcfi=t,e&&Object.keys(e).forEach(a=>{h.dataset[a]=e[a]}),i&&(h.addEventListener("click",i),h.addEventListener("touchstart",i)),h.addEventListener("click",o),h.addEventListener("touchstart",o),this.placeMark(h,s),this.element.appendChild(h),this.marks[t]={element:h,range:s,listeners:[o,i]},r}placeMark(t,e){let i,s,n;if(this.layout.name==="pre-paginated"||this.settings.axis!=="horizontal"){const r=e.getBoundingClientRect();i=r.top,s=r.right}else{const r=e.getClientRects();let o;for(let h=0;h!=r.length;h++)o=r[h],(!n||o.left<n)&&(n=o.left,s=Math.ceil(n/this.layout.props.pageWidth)*this.layout.props.pageWidth-this.layout.gap/2,i=o.top)}t.style.top=`${i}px`,t.style.left=`${s}px`}unhighlight(t){if(t in this.highlights){const e=this.highlights[t];this.pane.removeMark(e.mark),e.listeners.forEach(i=>{i&&(e.element.removeEventListener("click",i),e.element.removeEventListener("touchstart",i))}),delete this.highlights[t]}}ununderline(t){if(t in this.underlines){const e=this.underlines[t];this.pane.removeMark(e.mark),e.listeners.forEach(i=>{i&&(e.element.removeEventListener("click",i),e.element.removeEventListener("touchstart",i))}),delete this.underlines[t]}}unmark(t){if(t in this.marks){const e=this.marks[t];this.element.removeChild(e.element),e.listeners.forEach(i=>{i&&(e.element.removeEventListener("click",i),e.element.removeEventListener("touchstart",i))}),delete this.marks[t]}}destroy(){for(const t in this.highlights)this.unhighlight(t);for(const t in this.underlines)this.ununderline(t);for(const t in this.marks)this.unmark(t);this.blobUrl&&jt(this.blobUrl),this.displayed&&(this.displayed=!1,this.removeListeners(),this.contents.destroy(),this.stopExpanding=!0,this.iframe&&(this.iframe.onload=null),this.element.removeChild(this.iframe),this.pane&&(this.pane.element.remove(),this.pane=void 0),this.iframe=void 0,this.contents=void 0,this._textWidth=void 0,this._textHeight=void 0,this._width=void 0,this._height=void 0),this.__listeners={}}}P(se.prototype);function De(){let l="reverse";const t=Be();return document.body.appendChild(t),t.scrollLeft>0?l="default":typeof Element<"u"&&typeof Element.prototype.scrollIntoView=="function"?(t.children[0].children[1].scrollIntoView(),t.scrollLeft<0&&(l="negative")):(t.scrollLeft=1,t.scrollLeft===0&&(l="negative")),document.body.removeChild(t),l}function Be(){const l=document.createElement("div");l.dir="rtl",l.style.position="fixed",l.style.width="1px",l.style.height="1px",l.style.top="0px",l.style.left="0px",l.style.overflow="hidden";const t=document.createElement("div");t.style.width="2px";const e=document.createElement("span");e.style.width="1px",e.style.display="inline-block";const i=document.createElement("span");return i.style.width="1px",i.style.display="inline-block",t.appendChild(e),t.appendChild(i),l.appendChild(t),l}function Me(l,t){let e=null,i=0;return function(...s){const n=Date.now(),r=t-(n-i);r<=0||r>t?(e&&(clearTimeout(e),e=null),i=n,l.call(this,...s)):e||(e=setTimeout(()=>{i=Date.now(),e=null,l.call(this,...s)},r))}}class qe{constructor(t){this.settings=t||{},this.id="epubjs-container-"+dt(),this.container=this.create(this.settings),this.settings.hidden&&(this.wrapper=this.wrap(this.container))}create(t){let e=t.height,i=t.width;const s=t.overflow||!1,n=t.axis||"vertical",r=t.direction;_(this.settings,t),t.height&&E(t.height)&&(e=t.height+"px"),t.width&&E(t.width)&&(i=t.width+"px");const o=document.createElement("div");return o.id=this.id,o.classList.add("epub-container"),o.style.wordSpacing="0",o.style.lineHeight="0",o.style.verticalAlign="top",o.style.position="relative",o.style.overflowAnchor="none",n==="horizontal"&&(o.style.display="flex",o.style.flexDirection="row",o.style.flexWrap="nowrap"),i&&(o.style.width=i),e&&(o.style.height=e),s&&(s==="scroll"&&n==="vertical"?(o.style.overflowY=s,o.style.overflowX="hidden"):s==="scroll"&&n==="horizontal"?(o.style.overflowY="hidden",o.style.overflowX=s):o.style.overflow=s),r&&(o.dir=r,o.style.direction=r),r&&this.settings.fullsize&&(document.body.style.direction=r),o}wrap(t){const e=document.createElement("div");return e.style.visibility="hidden",e.style.overflow="hidden",e.style.width="0",e.style.height="0",e.appendChild(t),e}getElement(t){let e=null;if(Bt(t)?e=t:typeof t=="string"&&(e=document.getElementById(t)),!e)throw new Error("Not an Element");return e}attachTo(t){const e=this.getElement(t);let i;if(e)return this.settings.hidden?i=this.wrapper:i=this.container,e.appendChild(i),this.element=e,e}getContainer(){return this.container}onResize(t){(!E(this.settings.width)||!E(this.settings.height))&&(this.resizeFunc=Me(t,50),window.addEventListener("resize",this.resizeFunc,!1))}onOrientationChange(t){this.orientationChangeFunc=t,window.addEventListener("orientationchange",this.orientationChangeFunc,!1)}size(t,e){let i;const s=t||this.settings.width,n=e||this.settings.height;t===null?(i=this.element.getBoundingClientRect(),i.width&&(t=Math.floor(i.width),this.container.style.width=t+"px")):E(t)?this.container.style.width=t+"px":t&&(this.container.style.width=t),e===null?(i=i||this.element.getBoundingClientRect(),i.height&&(e=i.height,this.container.style.height=e+"px")):E(e)?this.container.style.height=e+"px":e&&(this.container.style.height=e),E(t)||(t=this.container.clientWidth),E(e)||(e=this.container.clientHeight),this.containerStyles=window.getComputedStyle(this.container),this.containerPadding={left:parseFloat(this.containerStyles.paddingLeft)||0,right:parseFloat(this.containerStyles.paddingRight)||0,top:parseFloat(this.containerStyles.paddingTop)||0,bottom:parseFloat(this.containerStyles.paddingBottom)||0};const r=rt(),o=window.getComputedStyle(document.body),h={left:parseFloat(o.paddingLeft)||0,right:parseFloat(o.paddingRight)||0,top:parseFloat(o.paddingTop)||0,bottom:parseFloat(o.paddingBottom)||0};return s||(t=r.width-h.left-h.right),(this.settings.fullsize&&!n||!n)&&(e=r.height-h.top-h.bottom),{width:t-this.containerPadding.left-this.containerPadding.right,height:e-this.containerPadding.top-this.containerPadding.bottom}}bounds(){let t;return this.container.style.overflow!=="visible"&&(t=this.container&&this.container.getBoundingClientRect()),!t||!t.width||!t.height?rt():t}getSheet(){const t=document.createElement("style");return t.appendChild(document.createTextNode("")),document.head.appendChild(t),t.sheet}addStyleRules(t,e){const i="#"+this.id+" ";let s="";this.sheet||(this.sheet=this.getSheet()),e.forEach(function(n){for(const r in n)n.hasOwnProperty(r)&&(s+=r+":"+n[r]+";")}),this.sheet.insertRule(i+t+" {"+s+"}",0)}axis(t){t==="horizontal"?(this.container.style.display="flex",this.container.style.flexDirection="row",this.container.style.flexWrap="nowrap"):this.container.style.display="block",this.settings.axis=t}direction(t){this.container&&(this.container.dir=t,this.container.style.direction=t),this.settings.fullsize&&(document.body.style.direction=t),this.settings.dir=t}overflow(t){this.container&&(t==="scroll"&&this.settings.axis==="vertical"?(this.container.style.overflowY=t,this.container.style.overflowX="hidden"):t==="scroll"&&this.settings.axis==="horizontal"?(this.container.style.overflowY="hidden",this.container.style.overflowX=t):this.container.style.overflow=t),this.settings.overflow=t}destroy(){this.element&&(this.settings.hidden?this.wrapper:this.container,this.element.contains(this.container)&&this.element.removeChild(this.container),window.removeEventListener("resize",this.resizeFunc),window.removeEventListener("orientationchange",this.orientationChangeFunc))}}class We{constructor(t){this.container=t,this._views=[],this.length=0,this.hidden=!1}all(){return this._views}first(){return this._views[0]}last(){return this._views[this._views.length-1]}indexOf(t){return this._views.indexOf(t)}slice(...t){return this._views.slice(...t)}get(t){return this._views[t]}append(t){return this._views.push(t),this.container&&this.container.appendChild(t.element),this.length++,t}prepend(t){return this._views.unshift(t),this.container&&this.container.insertBefore(t.element,this.container.firstChild),this.length++,t}insert(t,e){return this._views.splice(e,0,t),this.container&&(e<this.container.children.length?this.container.insertBefore(t.element,this.container.children[e]):this.container.appendChild(t.element)),this.length++,t}remove(t){const e=this._views.indexOf(t);e>-1&&this._views.splice(e,1),this.destroy(t),this.length--}destroy(t){t.displayed&&t.destroy(),this.container&&this.container.removeChild(t.element)}forEach(t){return this._views.forEach(t)}clear(){let t;const e=this.length;if(this.length){for(let i=0;i<e;i++)t=this._views[i],this.destroy(t);this._views=[],this.length=0}}find(t){let e;const i=this.length;for(let s=0;s<i;s++)if(e=this._views[s],e.displayed&&e.section.index==t.index)return e}displayed(){const t=[];let e;const i=this.length;for(let s=0;s<i;s++)e=this._views[s],e.displayed&&t.push(e);return t}show(){let t;const e=this.length;for(let i=0;i<e;i++)t=this._views[i],t.displayed&&t.show();this.hidden=!1}hide(){let t;const e=this.length;for(let i=0;i<e;i++)t=this._views[i],t.displayed&&t.hide();this.hidden=!0}}class ct{constructor(t){this.name="default",this.optsSettings=t.settings,this.View=t.view,this.request=t.request,this.renditionQueue=t.queue,this.q=new Lt(this),this.settings=_({},{infinite:!0,hidden:!1,width:void 0,height:void 0,axis:void 0,writingMode:void 0,flow:"scrolled",ignoreClass:"",fullsize:void 0,allowScriptedContent:!1,allowPopups:!1}),_(this.settings,t.settings||{}),this.viewSettings={ignoreClass:this.settings.ignoreClass,axis:this.settings.axis,flow:this.settings.flow,layout:this.layout,method:this.settings.method,width:0,height:0,forceEvenPages:!0,allowScriptedContent:this.settings.allowScriptedContent,allowPopups:this.settings.allowPopups},this.rendered=!1}render(t,e){const i=t.tagName;typeof this.settings.fullsize>"u"&&i&&(i.toLowerCase()=="body"||i.toLowerCase()=="html")&&(this.settings.fullsize=!0),this.settings.fullsize&&(this.settings.overflow="visible",this.overflow=this.settings.overflow),this.settings.size=e,this.settings.rtlScrollType=De(),this.stage=new qe({width:e.width,height:e.height,overflow:this.overflow,hidden:this.settings.hidden,axis:this.settings.axis,fullsize:this.settings.fullsize,direction:this.settings.direction}),this.stage.attachTo(t),this.container=this.stage.getContainer(),this.views=new We(this.container),this._bounds=this.bounds(),this._stageSize=this.stage.size(),this.viewSettings.width=this._stageSize.width,this.viewSettings.height=this._stageSize.height,this.stage.onResize(()=>this.onResized()),this.stage.onOrientationChange(s=>this.onOrientationChange(s)),this.addEventListeners(),this.layout&&this.updateLayout(),this.rendered=!0}addEventListeners(){let t;this._onUnload=e=>{this.destroy()},window.addEventListener("unload",this._onUnload),this.settings.fullsize?t=window:t=this.container,this._onScroll=this.onScroll.bind(this),t.addEventListener("scroll",this._onScroll)}removeEventListeners(){let t;this.settings.fullsize?t=window:t=this.container,t.removeEventListener("scroll",this._onScroll),this._onScroll=void 0,window.removeEventListener("unload",this._onUnload),this._onUnload=void 0}destroy(){clearTimeout(this.orientationTimeout),clearTimeout(this.resizeTimeout),clearTimeout(this.afterScrolled),this.clear(),this.removeEventListeners(),this.stage.destroy(),this.rendered=!1,this.__listeners={}}onOrientationChange(t){var i;const{orientation:e}=window;(i=this.optsSettings)!=null&&i.resizeOnOrientationChange&&this.resize(),clearTimeout(this.orientationTimeout),this.orientationTimeout=setTimeout(()=>{var s;this.orientationTimeout=void 0,(s=this.optsSettings)!=null&&s.resizeOnOrientationChange&&this.resize(),this.emit(f.MANAGERS.ORIENTATION_CHANGE,e)},500)}onResized(t){this.resize()}resize(t,e,i){const s=this.stage.size(t,e);if(this.winBounds=rt(),this.orientationTimeout&&this.winBounds.width===this.winBounds.height){this._stageSize=void 0;return}this._stageSize&&this._stageSize.width===s.width&&this._stageSize.height===s.height||(this._stageSize=s,this._bounds=this.bounds(),this.clear(),this.viewSettings.width=this._stageSize.width,this.viewSettings.height=this._stageSize.height,this.updateLayout(),this.emit(f.MANAGERS.RESIZED,{width:this._stageSize.width,height:this._stageSize.height},i))}createView(t,e){return new this.View(t,_(this.viewSettings,{forceRight:e}))}handleNextPrePaginated(t,e,i){var n;let s;if(this.layout.name==="pre-paginated"&&this.layout.divisor>1){if(t||e.index===0)return;if(s=(n=e.next)==null?void 0:n.call(e),s&&!s.properties.includes("page-spread-left"))return i.call(this,s)}}display(t,e){const i=new y,s=i.promise;(e===t.href||E(e))&&(e=void 0);const n=this.views.find(t);if(n&&t&&this.layout.name!=="pre-paginated"){const o=n.offset();if(this.settings.direction==="ltr")this.scrollTo(o.left,o.top,!0);else{const h=n.width();this.scrollTo(o.left+h,o.top,!0)}if(e){const h=n.locationOf(e),a=n.width();this.moveTo(h,a)}return i.resolve(),s}this.clear();let r=!1;return this.layout.name==="pre-paginated"&&this.layout.divisor===2&&t.properties.includes("page-spread-right")&&(r=!0),this.add(t,r).then(o=>{if(e){const h=o.locationOf(e),a=o.width();this.moveTo(h,a)}},o=>{i.reject(o)}).then(()=>this.handleNextPrePaginated(r,t,this.add)).then(()=>{this.views.show(),i.resolve()}),s}afterDisplayed(t){this.emit(f.MANAGERS.ADDED,t)}afterResized(t){this.emit(f.MANAGERS.RESIZE,t.section)}moveTo(t,e){let i=0,s=0;this.isPaginated?(i=Math.floor(t.left/this.layout.delta)*this.layout.delta,i+this.layout.delta>this.container.scrollWidth&&(i=this.container.scrollWidth-this.layout.delta),s=Math.floor(t.top/this.layout.height)*this.layout.height,s+this.layout.height>this.container.scrollHeight&&(s=this.container.scrollHeight-this.layout.height)):s=t.top,this.settings.direction==="rtl"&&(i=i+this.layout.delta,i=i-e),this.scrollTo(i,s,!0)}add(t,e){const i=this.createView(t,e);return this.views.append(i),i.onDisplayed=s=>this.afterDisplayed(s),i.onResize=s=>this.afterResized(s),i.on(f.VIEWS.AXIS,s=>{this.updateAxis(s)}),i.on(f.VIEWS.WRITING_MODE,s=>{this.updateWritingMode(s)}),i.display(this.request)}append(t,e){const i=this.createView(t,e);return this.views.append(i),i.onDisplayed=s=>this.afterDisplayed(s),i.onResize=s=>this.afterResized(s),i.on(f.VIEWS.AXIS,s=>{this.updateAxis(s)}),i.on(f.VIEWS.WRITING_MODE,s=>{this.updateWritingMode(s)}),i.display(this.request)}prepend(t,e){const i=this.createView(t,e);return i.on(f.VIEWS.RESIZED,s=>{this.counter(s)}),this.views.prepend(i),i.onDisplayed=s=>this.afterDisplayed(s),i.onResize=s=>this.afterResized(s),i.on(f.VIEWS.AXIS,s=>{this.updateAxis(s)}),i.on(f.VIEWS.WRITING_MODE,s=>{this.updateWritingMode(s)}),i.display(this.request)}counter(t){this.settings.axis==="vertical"?this.scrollBy(0,t.heightDelta,!0):this.scrollBy(t.widthDelta,0,!0)}next(){var s,n,r,o,h,a,c,d,u,p;let t,e;const i=this.settings.direction;if(this.views.length&&(this.isPaginated&&this.settings.axis==="horizontal"&&(!i||i==="ltr")?(this.scrollLeft=this.container.scrollLeft,e=this.container.scrollLeft+this.container.offsetWidth+this.layout.delta,e<=this.container.scrollWidth?this.scrollBy(this.layout.delta,0,!0):t=(n=(s=this.views.last().section).next)==null?void 0:n.call(s)):this.isPaginated&&this.settings.axis==="horizontal"&&i==="rtl"?(this.scrollLeft=this.container.scrollLeft,this.settings.rtlScrollType==="default"?(e=this.container.scrollLeft,e>0?this.scrollBy(this.layout.delta,0,!0):t=(o=(r=this.views.last().section).next)==null?void 0:o.call(r)):(e=this.container.scrollLeft+this.layout.delta*-1,e>this.container.scrollWidth*-1?this.scrollBy(this.layout.delta,0,!0):t=(a=(h=this.views.last().section).next)==null?void 0:a.call(h))):this.isPaginated&&this.settings.axis==="vertical"?(this.scrollTop=this.container.scrollTop,Math.abs(this.container.scrollHeight-this.container.clientHeight-this.container.scrollTop)<1?t=(d=(c=this.views.last().section).next)==null?void 0:d.call(c):this.scrollBy(0,this.layout.height,!0)):t=(p=(u=this.views.last().section).next)==null?void 0:p.call(u),t)){this.clear(),this.updateLayout();let g=!1;return this.layout.name==="pre-paginated"&&this.layout.divisor===2&&t.properties.includes("page-spread-right")&&(g=!0),this.append(t,g).then(()=>this.handleNextPrePaginated(g,t,this.append),v=>v).then(()=>{!this.isPaginated&&this.settings.axis==="horizontal"&&this.settings.direction==="rtl"&&this.settings.rtlScrollType==="default"&&this.scrollTo(this.container.scrollWidth,0,!0),this.views.show()})}}prev(){var s,n,r,o,h,a,c,d,u,p,g;let t,e;const i=this.settings.direction;if(this.views.length&&(this.isPaginated&&this.settings.axis==="horizontal"&&(!i||i==="ltr")?(this.scrollLeft=this.container.scrollLeft,e=this.container.scrollLeft,e>0?this.scrollBy(-this.layout.delta,0,!0):t=(n=(s=this.views.first().section).prev)==null?void 0:n.call(s)):this.isPaginated&&this.settings.axis==="horizontal"&&i==="rtl"?(this.scrollLeft=this.container.scrollLeft,this.settings.rtlScrollType==="default"?(e=this.container.scrollLeft+this.container.offsetWidth,e<this.container.scrollWidth?this.scrollBy(-this.layout.delta,0,!0):t=(o=(r=this.views.first().section).prev)==null?void 0:o.call(r)):(e=this.container.scrollLeft,e<0?this.scrollBy(-this.layout.delta,0,!0):t=(a=(h=this.views.first().section).prev)==null?void 0:a.call(h))):this.isPaginated&&this.settings.axis==="vertical"?(this.scrollTop=this.container.scrollTop,this.container.scrollTop>0?this.scrollBy(0,-this.layout.height,!0):t=(d=(c=this.views.first().section).prev)==null?void 0:d.call(c)):t=(p=(u=this.views.first().section).prev)==null?void 0:p.call(u),t)){this.clear(),this.updateLayout();let v=!1;return this.layout.name==="pre-paginated"&&this.layout.divisor===2&&typeof((g=t.prev)==null?void 0:g.call(t))!="object"&&(v=!0),this.prepend(t,v).then(()=>{var w;if(this.layout.name==="pre-paginated"&&this.layout.divisor>1){const x=(w=t.prev)==null?void 0:w.call(t);if(x)return this.prepend(x)}},w=>w).then(()=>{this.isPaginated&&this.settings.axis==="horizontal"&&(this.settings.direction==="rtl"?this.settings.rtlScrollType==="default"?this.scrollTo(0,0,!0):this.scrollTo(this.container.scrollWidth*-1+this.layout.delta,0,!0):this.scrollTo(this.container.scrollWidth-this.layout.delta,0,!0)),this.views.show()})}}current(){const t=this.visible();return t.length?t[t.length-1]:null}clear(){this.views&&(this.views.hide(),this.scrollTo(0,0,!0),this.views.clear())}currentLocation(){return this.updateLayout(),this.isPaginated&&this.settings.axis==="horizontal"?this.location=this.paginatedLocation():this.location=this.scrolledLocation(),this.location}scrolledLocation(){const t=this.visible(),e=this.container.getBoundingClientRect(),i=e.height<window.innerHeight?e.height:window.innerHeight,s=e.width<window.innerWidth?e.width:window.innerWidth,n=this.settings.axis==="vertical";this.settings.direction;let r=0;const o=0;return this.settings.fullsize&&(r=n?window.scrollY:window.scrollX),t.map(a=>{const c=a.section.index,d=a.section.href,u=a.position(),p=a.width(),g=a.height();let v,w,x,k;n?(v=r+e.top-u.top+o,w=v+i-o,k=this.layout.count(g,i).pages,x=i):(v=r+e.left-u.left+o,w=v+s-o,k=this.layout.count(p,s).pages,x=s);let S=Math.ceil(v/x),C=[],T=Math.ceil(w/x);if(this.settings.direction==="rtl"&&!n){const q=S;S=k-T,T=k-q}C=[];for(let q=S;q<=T;q++){const D=q+1;C.push(D)}const I=this.mapping.page(a.contents,a.section.cfiBase,v,w);return{index:c,href:d,pages:C,totalPages:k,mapping:I}})}paginatedLocation(){const t=this.visible(),e=this.container.getBoundingClientRect();let i=0,s=0;return this.settings.fullsize&&(i=window.scrollX),t.map(r=>{const o=r.section.index,h=r.section.href;let a;const c=r.position(),d=r.width();let u,p,g;this.settings.direction==="rtl"?(a=e.right-i,g=Math.min(Math.abs(a-c.left),this.layout.width)-s,p=c.width-(c.right-a)-s,u=p-g):(a=e.left+i,g=Math.min(c.right-a,this.layout.width)-s,u=a-c.left+s,p=u+g),s+=g;const v=this.mapping.page(r.contents,r.section.cfiBase,u,p),w=this.layout.count(d).pages;let x=Math.floor(u/this.layout.pageWidth);const k=[];let S=Math.floor(p/this.layout.pageWidth);if(x<0&&(x=0,S=S+1),this.settings.direction==="rtl"){const C=x;x=w-S,S=w-C}for(let C=x+1;C<=S;C++){const T=C;k.push(T)}return{index:o,href:h,pages:k,totalPages:w,mapping:v}})}isVisible(t,e,i,s){const n=t.position(),r=s||this.bounds();return this.settings.axis==="horizontal"&&n.right>r.left-e&&n.left<r.right+i?!0:this.settings.axis==="vertical"&&n.bottom>r.top-e&&n.top<r.bottom+i}visible(){const t=this.bounds(),e=this.views.displayed(),i=e.length,s=[];let n,r;for(let o=0;o<i;o++)r=e[o],n=this.isVisible(r,0,0,t),n===!0&&s.push(r);return s}scrollBy(t,e,i){const s=this.settings.direction==="rtl"?-1:1;i&&(this.ignore=!0),this.settings.fullsize?window.scrollBy(t*s,e*s):(t&&(this.container.scrollLeft+=t*s),e&&(this.container.scrollTop+=e)),this._hasScrolled=!0}scrollTo(t,e,i){i&&(this.ignore=!0),this.settings.fullsize?window.scrollTo(t,e):(this.container.scrollLeft=t,this.container.scrollTop=e),this._hasScrolled=!0}onScroll(){let t,e;this.settings.fullsize?(t=window.scrollY,e=window.scrollX):(t=this.container.scrollTop,e=this.container.scrollLeft),this.scrollTop=t,this.scrollLeft=e,this.ignore?this.ignore=!1:(this.emit(f.MANAGERS.SCROLL,{top:t,left:e}),clearTimeout(this.afterScrolled),this.afterScrolled=setTimeout(()=>{this.emit(f.MANAGERS.SCROLLED,{top:this.scrollTop,left:this.scrollLeft})},20))}bounds(){return this.stage.bounds()}applyLayout(t){this.layout=t,this.updateLayout(),this.views&&this.views.length>0&&this.layout.name==="pre-paginated"&&this.display(this.views.first().section)}updateLayout(){this.stage&&(this._stageSize=this.stage.size(),this.isPaginated?(this.layout.calculate(this._stageSize.width,this._stageSize.height,this.settings.gap),this.settings.offset=this.layout.delta/this.layout.divisor):this.layout.calculate(this._stageSize.width,this._stageSize.height),this.viewSettings.width=this.layout.width,this.viewSettings.height=this.layout.height,this.setLayout(this.layout))}setLayout(t){this.viewSettings.layout=t,this.mapping=new at(t.props,this.settings.direction,this.settings.axis),this.views&&this.views.forEach(e=>{e&&e.setLayout(t)})}updateWritingMode(t){this.writingMode=t}updateAxis(t,e){!e&&t===this.settings.axis||(this.settings.axis=t,this.stage&&this.stage.axis(t),this.viewSettings.axis=t,this.mapping&&(this.mapping=new at(this.layout.props,this.settings.direction,this.settings.axis)),this.layout&&(t==="vertical"?this.layout.spread("none"):this.layout.spread(this.layout.settings.spread)))}updateFlow(t,e="auto"){const i=t==="paginated"||t==="auto";this.isPaginated=i,t==="scrolled-doc"||t==="scrolled-continuous"||t==="scrolled"?this.updateAxis("vertical"):this.updateAxis("horizontal"),this.viewSettings.flow=t,this.settings.overflow?this.overflow=this.settings.overflow:this.overflow=i?"hidden":e,this.stage&&this.stage.overflow(this.overflow),this.updateLayout()}getContents(){const t=[];return this.views&&this.views.forEach(e=>{const i=e&&e.contents;i&&t.push(i)}),t}direction(t="ltr"){this.settings.direction=t,this.stage&&this.stage.direction(t),this.viewSettings.direction=t,this.updateLayout()}isRendered(){return this.rendered}}P(ct.prototype);const Ue={easeInCubic:function(l){return Math.pow(l,3)}};class _t{constructor(t,e){this.settings=_({duration:80,minVelocity:.2,minDistance:10,easing:Ue.easeInCubic},e||{}),this._supportsTouch=this.supportsTouch(),this._supportsTouch&&this.setup(t)}setup(t){this.manager=t,this.layout=this.manager.layout,this.fullsize=this.manager.settings.fullsize??!1,this.fullsize?(this.element=this.manager.stage.element,this.scroller=window,this.disableScroll()):(this.element=this.manager.stage.container,this.scroller=this.element,this.element.style.WebkitOverflowScrolling="touch"),this.manager.settings.offset=this.layout.width,this.manager.settings.afterScrolledTimeout=this.settings.duration*2,this.isVertical=this.manager.settings.axis==="vertical",!(!this.manager.isPaginated||this.isVertical)&&(this.touchCanceler=!1,this.resizeCanceler=!1,this.snapping=!1,this.scrollLeft,this.scrollTop,this.startTouchX=void 0,this.startTouchY=void 0,this.startTime=void 0,this.endTouchX=void 0,this.endTouchY=void 0,this.endTime=void 0,this.addListeners())}supportsTouch(){return!!("ontouchstart"in window||window.DocumentTouch&&document instanceof window.DocumentTouch)}disableScroll(){this.element.style.overflow="hidden"}enableScroll(){this.element.style.overflow=""}addListeners(){this._onResize=this.onResize.bind(this),window.addEventListener("resize",this._onResize),this._onScroll=this.onScroll.bind(this),this.scroller.addEventListener("scroll",this._onScroll),this._onTouchStart=this.onTouchStart.bind(this),this.scroller.addEventListener("touchstart",this._onTouchStart,{passive:!0}),this.on("touchstart",this._onTouchStart),this._onTouchMove=this.onTouchMove.bind(this),this.scroller.addEventListener("touchmove",this._onTouchMove,{passive:!0}),this.on("touchmove",this._onTouchMove),this._onTouchEnd=this.onTouchEnd.bind(this),this.scroller.addEventListener("touchend",this._onTouchEnd,{passive:!0}),this.on("touchend",this._onTouchEnd),this._afterDisplayed=this.afterDisplayed.bind(this),this.manager.on(f.MANAGERS.ADDED,this._afterDisplayed)}removeListeners(){window.removeEventListener("resize",this._onResize),this._onResize=void 0,this.scroller.removeEventListener("scroll",this._onScroll),this._onScroll=void 0,this.scroller.removeEventListener("touchstart",this._onTouchStart,{passive:!0}),this.off("touchstart",this._onTouchStart),this._onTouchStart=void 0,this.scroller.removeEventListener("touchmove",this._onTouchMove,{passive:!0}),this.off("touchmove",this._onTouchMove),this._onTouchMove=void 0,this.scroller.removeEventListener("touchend",this._onTouchEnd,{passive:!0}),this.off("touchend",this._onTouchEnd),this._onTouchEnd=void 0,this.manager.off(f.MANAGERS.ADDED,this._afterDisplayed),this._afterDisplayed=void 0}afterDisplayed(t){const e=t.contents;["touchstart","touchmove","touchend"].forEach(i=>{e.on(i,s=>this.triggerViewEvent(s,e))})}triggerViewEvent(t,e){this.emit(t.type,t,e)}onScroll(t){this.scrollLeft=this.fullsize?window.scrollX:this.scroller.scrollLeft,this.scrollTop=this.fullsize?window.scrollY:this.scroller.scrollTop}onResize(t){this.resizeCanceler=!0}onTouchStart(t){const{screenX:e,screenY:i}=t.touches[0];this.fullsize&&this.enableScroll(),this.touchCanceler=!0,this.startTouchX||(this.startTouchX=e,this.startTouchY=i,this.startTime=this.now()),this.endTouchX=e,this.endTouchY=i,this.endTime=this.now()}onTouchMove(t){const{screenX:e,screenY:i}=t.touches[0],s=Math.abs(i-this.endTouchY);this.touchCanceler=!0,!this.fullsize&&s<10&&(this.element.scrollLeft-=e-this.endTouchX),this.endTouchX=e,this.endTouchY=i,this.endTime=this.now()}onTouchEnd(t){this.fullsize&&this.disableScroll(),this.touchCanceler=!1;const e=this.wasSwiped();e!==0?this.snap(e):this.snap(),this.startTouchX=void 0,this.startTouchY=void 0,this.startTime=void 0,this.endTouchX=void 0,this.endTouchY=void 0,this.endTime=void 0}wasSwiped(){const t=this.layout.pageWidth*this.layout.divisor,e=this.endTouchX-this.startTouchX,i=Math.abs(e),s=this.endTime-this.startTime,n=e/s,r=this.settings.minVelocity;return i<=this.settings.minDistance||i>=t?0:n>r?-1:n<-r?1:0}needsSnap(){const t=this.scrollLeft,e=this.layout.pageWidth*this.layout.divisor;return t%e!==0}snap(t=0){const e=this.scrollLeft,i=this.layout.pageWidth*this.layout.divisor;let s=Math.round(e/i)*i;return t&&(s+=t*i),this.smoothScrollTo(s)}smoothScrollTo(t){const e=new y,i=this.scrollLeft,s=this.now(),n=this.settings.duration,r=this.settings.easing;this.snapping=!0;const o=()=>{const h=this.now(),a=Math.min(1,(h-s)/n);if(r(a),this.touchCanceler||this.resizeCanceler){this.resizeCanceler=!1,this.snapping=!1,e.resolve();return}a<1?(window.requestAnimationFrame(o),this.scrollTo(i+(t-i)*a,0)):(this.scrollTo(t,0),this.snapping=!1,e.resolve())};return o(),e.promise}scrollTo(t=0,e=0){this.fullsize?window.scroll(t,e):(this.scroller.scrollLeft=t,this.scroller.scrollTop=e)}now(){return"now"in window.performance?performance.now():new Date().getTime()}destroy(){this.scroller&&(this.fullsize&&this.enableScroll(),this.removeListeners(),this.scroller=void 0)}}P(_t.prototype);function je(l,t){let e;return function(...i){clearTimeout(e),e=setTimeout(()=>{l.call(this,...i)},t)}}class Fe extends ct{constructor(t){var i;super(t),this.name="continuous",this.settings=_({},{infinite:!0,overflow:void 0,axis:void 0,writingMode:void 0,flow:"scrolled",offset:500,offsetDelta:250,width:void 0,height:void 0,snap:!1,afterScrolledTimeout:10,allowScriptedContent:!1,allowPopups:!1}),_(this.settings,t.settings||{});const e=(i=t.settings)==null?void 0:i.gap;e!==void 0&&e===0&&(this.settings.gap=e),this.viewSettings={ignoreClass:this.settings.ignoreClass,axis:this.settings.axis,flow:this.settings.flow,layout:this.layout,width:0,height:0,forceEvenPages:!1,allowScriptedContent:this.settings.allowScriptedContent,allowPopups:this.settings.allowPopups},this.scrollTop=0,this.scrollLeft=0}display(t,e){return ct.prototype.display.call(this,t,e).then(()=>this.fill())}fill(t){const e=t||new y;return this.q.enqueue(()=>this.check()).then(i=>{i?this.fill(e):e.resolve()}),e.promise}moveTo(t){let e=0,i=0;this.isPaginated?(e=Math.floor(t.left/this.layout.delta)*this.layout.delta,e+(this.settings.offsetDelta??0)):(i=t.top,t.top+(this.settings.offsetDelta??0)),(e>0||i>0)&&this.scrollBy(e,i,!0)}afterResized(t){this.emit(f.MANAGERS.RESIZE,t.section)}removeShownListeners(t){t.onDisplayed=function(){}}add(t){const e=this.createView(t);return this.views.append(e),e.on(f.VIEWS.RESIZED,i=>{e.expanded=!0}),e.on(f.VIEWS.AXIS,i=>{this.updateAxis(i)}),e.on(f.VIEWS.WRITING_MODE,i=>{this.updateWritingMode(i)}),e.onDisplayed=i=>this.afterDisplayed(i),e.onResize=i=>this.afterResized(i),e.display(this.request)}append(t){const e=this.createView(t);return e.on(f.VIEWS.RESIZED,i=>{e.expanded=!0}),e.on(f.VIEWS.AXIS,i=>{this.updateAxis(i)}),e.on(f.VIEWS.WRITING_MODE,i=>{this.updateWritingMode(i)}),this.views.append(e),e.onDisplayed=i=>this.afterDisplayed(i),e}prepend(t){const e=this.createView(t);return e.on(f.VIEWS.RESIZED,i=>{this.counter(i),e.expanded=!0}),e.on(f.VIEWS.AXIS,i=>{this.updateAxis(i)}),e.on(f.VIEWS.WRITING_MODE,i=>{this.updateWritingMode(i)}),this.views.prepend(e),e.onDisplayed=i=>this.afterDisplayed(i),e}counter(t){this.settings.axis==="vertical"?this.scrollBy(0,t.heightDelta,!0):this.scrollBy(t.widthDelta,0,!0)}update(t){const e=this.bounds(),i=this.views.all(),s=i.length,n=typeof t<"u"?t:this.settings.offset||0;let r,o;const h=new y,a=[];for(let c=0;c<s;c++)if(o=i[c],r=this.isVisible(o,n,n,e),r===!0)if(o.displayed)o.show();else{const d=o.display(this.request).then(function(u){u.show()},u=>{o.hide()});a.push(d)}else this.q.enqueue(()=>o.destroy()),clearTimeout(this.trimTimeout),this.trimTimeout=setTimeout(()=>{this.q.enqueue(()=>this.trim())},250);return a.length?Promise.all(a).catch(c=>{h.reject(c)}):(h.resolve(),h.promise)}check(t,e){const i=new y,s=[],n=this.settings.axis==="horizontal";let r=this.settings.offset||0;t&&n&&(r=t),e&&!n&&(r=e);const o=this._bounds;let h=n?this.scrollLeft:this.scrollTop;const a=n?Math.floor(o.width):o.height,c=n?this.container.scrollWidth:this.container.scrollHeight,d=this.writingMode&&this.writingMode.indexOf("vertical")===0?"vertical":"horizontal",u=this.settings.rtlScrollType,p=this.settings.direction==="rtl";this.settings.fullsize?(n&&p&&u==="negative"||!n&&p&&u==="default")&&(h=h*-1):(p&&u==="default"&&d==="horizontal"&&(h=c-a-h),p&&u==="negative"&&d==="horizontal"&&(h=h*-1));const g=()=>{var T,I;const S=this.views.first(),C=S&&((I=(T=S.section).prev)==null?void 0:I.call(T));C&&s.push(this.prepend(C))},v=()=>{var T,I;const S=this.views.last(),C=S&&((I=(T=S.section).next)==null?void 0:I.call(T));C&&s.push(this.append(C))},w=h+a+r,x=h-r;w>=c&&v(),x<0&&g();const k=s.map(S=>S.display(this.request));return s.length?Promise.all(k).then(()=>this.check()).then(()=>this.update(r),S=>S):(this.q.enqueue(()=>{this.update()}),i.resolve(!1),i.promise)}trim(){const t=new y,e=this.views.displayed();if(!e.length)return t.resolve(),t.promise;const i=e[0],s=e[e.length-1],n=this.views.indexOf(i),r=this.views.indexOf(s),o=this.views.slice(0,n),h=this.views.slice(r+1);for(let a=0;a<o.length-1;a++)this.erase(o[a],o);for(let a=1;a<h.length;a++)this.erase(h[a]);return t.resolve(),t.promise}erase(t,e){let i,s;this.settings.fullsize?(i=window.scrollY,s=window.scrollX):(i=this.container.scrollTop,s=this.container.scrollLeft);const n=t.bounds();this.views.remove(t),e&&(this.settings.axis==="vertical"?this.scrollTo(0,i-n.height,!0):this.settings.direction==="rtl"?this.settings.fullsize?this.scrollTo(s+Math.floor(n.width),0,!0):this.scrollTo(s,0,!0):this.scrollTo(s-Math.floor(n.width),0,!0))}addEventListeners(t){this._onUnload=e=>{this.ignore=!0,this.destroy()},window.addEventListener("unload",this._onUnload),this.addScrollListeners(),this.isPaginated&&this.settings.snap&&(this.snapper=new _t(this,typeof this.settings.snap=="object"?this.settings.snap:void 0))}addScrollListeners(){let t;this.tick=Tt;const e=this.settings.direction==="rtl"&&this.settings.rtlScrollType==="default"?-1:1;this.scrollDeltaVert=0,this.scrollDeltaHorz=0,this.settings.fullsize?(t=window,this.scrollTop=window.scrollY*e,this.scrollLeft=window.scrollX*e):(t=this.container,this.scrollTop=this.container.scrollTop,this.scrollLeft=this.container.scrollLeft),this._onScroll=this.onScroll.bind(this),t.addEventListener("scroll",this._onScroll),this._scrolled=je(()=>this.scrolled(),30),this.didScroll=!1}removeEventListeners(){let t;this.settings.fullsize?t=window:t=this.container,t.removeEventListener("scroll",this._onScroll),this._onScroll=void 0,window.removeEventListener("unload",this._onUnload),this._onUnload=void 0}onScroll(){let t,e;const i=this.settings.direction==="rtl"&&this.settings.rtlScrollType==="default"?-1:1;this.settings.fullsize?(t=window.scrollY*i,e=window.scrollX*i):(t=this.container.scrollTop,e=this.container.scrollLeft),this.scrollTop=t,this.scrollLeft=e,this.ignore?this.ignore=!1:this._scrolled(),this.scrollDeltaVert+=Math.abs(t-this.prevScrollTop),this.scrollDeltaHorz+=Math.abs(e-this.prevScrollLeft),this.prevScrollTop=t,this.prevScrollLeft=e,clearTimeout(this.scrollTimeout),this.scrollTimeout=setTimeout(()=>{this.scrollDeltaVert=0,this.scrollDeltaHorz=0},150),clearTimeout(this.afterScrolled),this.didScroll=!1}scrolled(){this.q.enqueue(()=>this.check()),this.emit(f.MANAGERS.SCROLL,{top:this.scrollTop,left:this.scrollLeft}),clearTimeout(this.afterScrolled),this.afterScrolled=setTimeout(()=>{this.snapper&&this.snapper.supportsTouch()&&this.snapper.needsSnap()||this.emit(f.MANAGERS.SCROLLED,{top:this.scrollTop,left:this.scrollLeft})},this.settings.afterScrolledTimeout)}next(){const t=this.layout.props.name==="pre-paginated"&&this.layout.props.spread?this.layout.props.delta*2:this.layout.props.delta;this.views.length&&(this.isPaginated&&this.settings.axis==="horizontal"?this.scrollBy(t,0,!0):this.scrollBy(0,this.layout.height,!0),this.q.enqueue(()=>this.check()))}prev(){const t=this.layout.props.name==="pre-paginated"&&this.layout.props.spread?this.layout.props.delta*2:this.layout.props.delta;this.views.length&&(this.isPaginated&&this.settings.axis==="horizontal"?this.scrollBy(-t,0,!0):this.scrollBy(0,-this.layout.height,!0),this.q.enqueue(()=>this.check()))}updateFlow(t){this.rendered&&this.snapper&&(this.snapper.destroy(),this.snapper=void 0),super.updateFlow(t,"scroll"),this.rendered&&this.isPaginated&&this.settings.snap&&(this.snapper=new _t(this,typeof this.settings.snap=="object"?this.settings.snap:void 0))}destroy(){clearTimeout(this.scrollTimeout),clearTimeout(this.trimTimeout),super.destroy(),this.snapper&&this.snapper.destroy()}}class pt{constructor(t,e){this.settings=_({},{width:null,height:null,ignoreClass:"",manager:"default",view:"iframe",flow:null,layout:null,spread:null,minSpreadWidth:800,stylesheet:null,resizeOnOrientationChange:!0,script:null,snap:!1,defaultDirection:"ltr",allowScriptedContent:!1,allowPopups:!1}),_(this.settings,e),typeof this.settings.manager=="object"&&(this.manager=this.settings.manager),this.book=t,this.hooks={},this.hooks.display=new A(this),this.hooks.serialize=new A(this),this.hooks.content=new A(this),this.hooks.unloaded=new A(this),this.hooks.layout=new A(this),this.hooks.render=new A(this),this.hooks.show=new A(this),this.hooks.content.register(i=>this.handleLinks(i)),this.hooks.content.register(i=>this.passEvents(i)),this.hooks.content.register(i=>this.adjustImages(i)),this.book.spine.hooks.content.register((i,s)=>this.injectIdentifier(i,s)),this.settings.stylesheet&&this.book.spine.hooks.content.register((i,s)=>this.injectStylesheet(i,s)),this.settings.script&&this.book.spine.hooks.content.register((i,s)=>this.injectScript(i,s)),this.themes=new Jt(this),this.annotations=new Qt(this),this.epubcfi=new m,this.q=new Lt(this),this.location=void 0,this.q.enqueue(this.book.opened),this.starting=new y,this.started=this.starting.promise,this.q.enqueue(this.start)}setManager(t){this.manager=t}requireManager(t){let e;return typeof t=="string"&&t==="default"?e=ct:typeof t=="string"&&t==="continuous"?e=Fe:e=t,e}requireView(t){let e;return typeof t=="string"&&t==="iframe"?e=se:e=t,e}start(){switch(!this.settings.layout&&(this.book.package.metadata.layout==="pre-paginated"||this.book.displayOptions.fixedLayout==="true")&&(this.settings.layout="pre-paginated"),this.book.package.metadata.spread){case"none":this.settings.spread="none";break;case"both":this.settings.spread=!0;break}this.manager||(this.ViewManager=this.requireManager(this.settings.manager),this.View=this.requireView(this.settings.view),this.manager=new this.ViewManager({view:this.View,queue:this.q,request:this.book.load.bind(this.book),settings:this.settings})),this.direction(this.book.package.metadata.direction||this.settings.defaultDirection),this.settings.globalLayoutProperties=this.determineLayoutProperties(this.book.package.metadata),this.flow(this.settings.globalLayoutProperties.flow),this.layout(this.settings.globalLayoutProperties),this.manager.on(f.MANAGERS.ADDED,t=>this.afterDisplayed(t)),this.manager.on(f.MANAGERS.REMOVED,t=>this.afterRemoved(t)),this.manager.on(f.MANAGERS.RESIZED,(t,e)=>this.onResized(t,e)),this.manager.on(f.MANAGERS.ORIENTATION_CHANGE,t=>this.onOrientationChange(t)),this.manager.on(f.MANAGERS.SCROLLED,()=>this.reportLocation()),this.emit(f.RENDITION.STARTED),this.starting.resolve()}attachTo(t){return this.q.enqueue(()=>{this.manager.render(t,{width:this.settings.width,height:this.settings.height}),this.emit(f.RENDITION.ATTACHED)})}display(t){return this.displaying&&this.displaying.resolve(void 0),this.q.enqueue(this._display,t)}_display(t){if(!this.book)return;this.epubcfi.isCfiString(t);const e=new y,i=e.promise;this.displaying=e,this.book.locations.length()&&Mt(t)&&(t=this.book.locations.cfiFromPercentage(parseFloat(t)));const s=this.book.spine.get(t);return s?(this.manager.display(s,t).then(()=>{e.resolve(s),this.displaying=void 0,this.emit(f.RENDITION.DISPLAYED,s),this.reportLocation()},n=>{this.emit(f.RENDITION.DISPLAY_ERROR,n)}),i):(e.reject(new Error("No Section Found")),i)}afterDisplayed(t){t.on(f.VIEWS.MARK_CLICKED,(e,i)=>{t.contents&&this.triggerMarkEvent(e,i,t.contents)}),this.hooks.render.trigger(t,this).then(()=>{t.contents?this.hooks.content.trigger(t.contents,this).then(()=>{this.emit(f.RENDITION.RENDERED,t.section,t)}):this.emit(f.RENDITION.RENDERED,t.section,t)})}afterRemoved(t){this.hooks.unloaded.trigger(t,this).then(()=>{this.emit(f.RENDITION.REMOVED,t.section,t)})}onResized(t,e){this.emit(f.RENDITION.RESIZED,{width:t.width,height:t.height},e),this.location&&this.location.start&&this.display(e||this.location.start.cfi)}onOrientationChange(t){this.emit(f.RENDITION.ORIENTATION_CHANGE,t)}moveTo(t){this.manager.moveTo(t)}resize(t,e,i){t&&(this.settings.width=t),e&&(this.settings.height=e),this.manager.resize(t,e,i)}clear(){this.manager.clear()}next(){return this.q.enqueue(()=>this.manager.next()).then(()=>this.reportLocation())}prev(){return this.q.enqueue(()=>this.manager.prev()).then(()=>this.reportLocation())}determineLayoutProperties(t){const e=this.settings.layout||t.layout||"reflowable",i=this.settings.spread||t.spread||"auto",s=this.settings.orientation||t.orientation||"auto",n=this.settings.flow||t.flow||"auto",r=t.viewport||"",o=this.settings.minSpreadWidth||t.minSpreadWidth||800,h=this.settings.direction||t.direction||"ltr";return(this.settings.width===0||this.settings.width>0)&&(this.settings.height===0||this.settings.height>0),{layout:e,spread:i,orientation:s,flow:n,viewport:r,minSpreadWidth:o,direction:h}}flow(t){let e=t;(t==="scrolled"||t==="scrolled-doc"||t==="scrolled-continuous")&&(e="scrolled"),(t==="auto"||t==="paginated")&&(e="paginated"),this.settings.flow=t,this._layout&&this._layout.flow(e),this.manager&&this._layout&&this.manager.applyLayout(this._layout),this.manager&&this.manager.updateFlow(e),this.manager&&this.manager.isRendered()&&this.location&&(this.manager.clear(),this.display(this.location.start.cfi))}layout(t){return t&&(this._layout=new Nt(t),this._layout.spread(t.spread,this.settings.minSpreadWidth),this._layout.on(f.LAYOUT.UPDATED,(e,i)=>{this.emit(f.RENDITION.LAYOUT,e,i)})),this.manager&&this._layout&&this.manager.applyLayout(this._layout),this._layout}spread(t,e){this.settings.spread=t,e&&(this.settings.minSpreadWidth=e),this._layout&&this._layout.spread(t,e),this.manager&&this.manager.isRendered()&&this.manager.updateLayout()}direction(t){this.settings.direction=t||"ltr",this.manager&&this.manager.direction(this.settings.direction),this.manager&&this.manager.isRendered()&&this.location&&(this.manager.clear(),this.display(this.location.start.cfi))}reportLocation(){return this.q.enqueue(()=>{requestAnimationFrame(()=>{const t=this.manager.currentLocation();if(t&&"then"in t&&typeof t.then=="function")t.then(e=>{const i=this.located(e);!i||!i.start||!i.end||(this.location=i,this.emit(f.RENDITION.LOCATION_CHANGED,{index:this.location.start.index,href:this.location.start.href,start:this.location.start.cfi,end:this.location.end.cfi,percentage:this.location.start.percentage}),this.emit(f.RENDITION.RELOCATED,this.location))});else if(t){const e=this.located(t);if(!e||!e.start||!e.end)return;this.location=e,this.emit(f.RENDITION.LOCATION_CHANGED,{index:this.location.start.index,href:this.location.start.href,start:this.location.start.cfi,end:this.location.end.cfi,percentage:this.location.start.percentage}),this.emit(f.RENDITION.RELOCATED,this.location)}})})}currentLocation(){const t=this.manager.currentLocation();if(t&&"then"in t&&typeof t.then=="function")t.then(e=>this.located(e));else if(t)return this.located(t)}located(t){if(!t.length)return;const e=t[0],i=t[t.length-1],s={start:{index:e.index,href:e.href,cfi:e.mapping.start,displayed:{page:e.pages[0]||1,total:e.totalPages}},end:{index:i.index,href:i.href,cfi:i.mapping.end,displayed:{page:i.pages[i.pages.length-1]||1,total:i.totalPages}}},n=this.book.locations.locationFromCfi(e.mapping.start),r=this.book.locations.locationFromCfi(i.mapping.end);n!=null&&(s.start.location=n,s.start.percentage=this.book.locations.percentageFromLocation(n)),r!=null&&(s.end.location=r,s.end.percentage=this.book.locations.percentageFromLocation(r));const o=this.book.pageList.pageFromCfi(e.mapping.start),h=this.book.pageList.pageFromCfi(i.mapping.end);return o!=-1&&(s.start.page=o),h!=-1&&(s.end.page=h),i.index===this.book.spine.last().index&&s.end.displayed.page>=s.end.displayed.total&&(s.atEnd=!0),e.index===this.book.spine.first().index&&s.start.displayed.page===1&&(s.atStart=!0),s}destroy(){this.q.clear(),this.manager&&(this.manager.off(f.MANAGERS.ADDED),this.manager.off(f.MANAGERS.REMOVED),this.manager.off(f.MANAGERS.RESIZED),this.manager.off(f.MANAGERS.ORIENTATION_CHANGE),this.manager.off(f.MANAGERS.SCROLLED),this.manager.destroy(),this.manager=void 0),this.book=void 0,this.hooks.display.clear(),this.hooks.serialize.clear(),this.hooks.content.clear(),this.hooks.unloaded.clear(),this.hooks.layout.clear(),this.hooks.render.clear(),this.hooks.show.clear(),this.themes.destroy(),this._layout&&this._layout.off(f.LAYOUT.UPDATED),this._layout=void 0,this.location=void 0}passEvents(t){Q.forEach(e=>{t.on(e,i=>this.triggerViewEvent(i,t))}),t.on(f.CONTENTS.SELECTED,e=>this.triggerSelectedEvent(e,t))}triggerViewEvent(t,e){this.emit(t.type,t,e)}triggerSelectedEvent(t,e){this.emit(f.RENDITION.SELECTED,t,e)}triggerMarkEvent(t,e,i){this.emit(f.RENDITION.MARK_CLICKED,t,e,i)}getRange(t,e){const i=new m(t),s=this.manager.visible().filter(function(n){return i.spinePos===n.index});if(s.length)return s[0].contents.range(i.toString(),e)}adjustImages(t){if(this._layout.name==="pre-paginated")return new Promise(function(n){n()});const e=t.window.getComputedStyle(t.content,null),i=(t.content.offsetHeight-(parseFloat(e.paddingTop)+parseFloat(e.paddingBottom)))*.95,s=parseFloat(e.paddingLeft)+parseFloat(e.paddingRight);return t.addStylesheetRules({img:{"max-width":(this._layout.columnWidth?this._layout.columnWidth-s+"px":"100%")+"!important","max-height":i+"px!important","object-fit":"contain","page-break-inside":"avoid","break-inside":"avoid","box-sizing":"border-box"},svg:{"max-width":(this._layout.columnWidth?this._layout.columnWidth-s+"px":"100%")+"!important","max-height":i+"px!important","page-break-inside":"avoid","break-inside":"avoid"}}),new Promise(function(n,r){setTimeout(function(){n()},1)})}getContents(){return this.manager?this.manager.getContents():[]}views(){return(this.manager?this.manager.views:void 0)||[]}handleLinks(t){t&&t.on(f.CONTENTS.LINK_CLICKED,e=>{const i=this.book.path.relative(e);this.display(i)})}injectStylesheet(t,e){const i=t.createElement("link");i.setAttribute("type","text/css"),i.setAttribute("rel","stylesheet"),i.setAttribute("href",this.settings.stylesheet),t.getElementsByTagName("head")[0].appendChild(i)}injectScript(t,e){const i=t.createElement("script");i.setAttribute("type","text/javascript"),i.setAttribute("src",this.settings.script),i.textContent=" ",t.getElementsByTagName("head")[0].appendChild(i)}injectIdentifier(t,e){const i=this.book.packaging.metadata.identifier,s=t.createElement("meta");s.setAttribute("name","dc.relation.ispartof"),i&&s.setAttribute("content",i),t.getElementsByTagName("head")[0].appendChild(s)}}P(pt.prototype);class ne{constructor(){this.zip=void 0,this.urlCache={},this.checkRequirements()}checkRequirements(){try{this.zip=new re}catch{throw new Error("JSZip lib not loaded")}}open(t,e){return this.zip.loadAsync(t,{base64:e})}openUrl(t,e){return K(t,"binary").then(i=>this.zip.loadAsync(i,{base64:e}))}request(t,e){const i=new y;let s;const n=new z(t);return e||(e=n.extension),e=="blob"?s=this.getBlob(t):s=this.getText(t),s?s.then(r=>{const o=this.handleResponse(r,e);i.resolve(o)}):i.reject({message:"File not found in the epub: "+t,stack:new Error().stack}),i.promise}handleResponse(t,e){let i;return e=="json"?i=JSON.parse(t):$(e)?i=O(t,"text/xml"):e=="xhtml"?i=O(t,"application/xhtml+xml"):e=="html"||e=="htm"?i=O(t,"text/html"):i=t,i}getBlob(t,e){const i=window.decodeURIComponent(t.substr(1)),s=this.zip.file(i);if(s)return e=e||H.lookup(s.name),s.async("uint8array").then(function(n){return new Blob([n],{type:e})})}getText(t,e){const i=window.decodeURIComponent(t.substr(1)),s=this.zip.file(i);if(s)return s.async("string").then(function(n){return n})}getBase64(t,e){const i=window.decodeURIComponent(t.substr(1)),s=this.zip.file(i);if(s)return e=e||H.lookup(s.name),s.async("base64").then(function(n){return"data:"+e+";base64,"+n})}createUrl(t,e){const i=new y,s=window.URL||window.webkitURL||window.mozURL;let n,r;const o=e&&e.base64;return t in this.urlCache?(i.resolve(this.urlCache[t]),i.promise):(o?(r=this.getBase64(t),r&&r.then(h=>{this.urlCache[t]=h,i.resolve(h)})):(r=this.getBlob(t),r&&r.then(h=>{n=s.createObjectURL(h),this.urlCache[t]=n,i.resolve(n)})),r||i.reject({message:"File not found in the epub: "+t,stack:new Error().stack}),i.promise)}revokeUrl(t){const e=window.URL||window.webkitURL||window.mozURL,i=this.urlCache[t];i&&e.revokeObjectURL(i)}destroy(){const t=window.URL||window.webkitURL||window.mozURL;for(const e in this.urlCache)t.revokeObjectURL(e);this.zip=void 0,this.urlCache={}}}function Ve(l){return new Promise((t,e)=>{const i=indexedDB.open(l,1);i.onupgradeneeded=()=>{i.result.createObjectStore("data")},i.onsuccess=()=>t(i.result),i.onerror=()=>e(i.error)})}function He(l){const t=Ve(l);return{getItem(e){return t.then(i=>new Promise((s,n)=>{const o=i.transaction("data","readonly").objectStore("data").get(e);o.onsuccess=()=>s(o.result??null),o.onerror=()=>n(o.error)}))},setItem(e,i){return t.then(s=>new Promise((n,r)=>{const h=s.transaction("data","readwrite").objectStore("data").put(i,e);h.onsuccess=()=>n(i),h.onerror=()=>r(h.error)}))}}}const yt=window.URL||window.webkitURL||window.mozURL;class At{constructor(t,e,i){this.urlCache={},this.name=t,this.requester=e||K,this.resolver=i,this.online=!0,this.checkRequirements(),this.addListeners()}checkRequirements(){try{if(typeof indexedDB>"u")throw new Error("IndexedDB not available");this.storage=He(this.name)}catch{throw new Error("IndexedDB not available")}}addListeners(){this._status=this.status.bind(this),window.addEventListener("online",this._status),window.addEventListener("offline",this._status)}removeListeners(){window.removeEventListener("online",this._status),window.removeEventListener("offline",this._status),this._status=void 0}status(t){const e=navigator.onLine;this.online=e,e?this.emit("online",this):this.emit("offline",this)}add(t,e){const i=t.resources.map(s=>{const{href:n}=s,r=this.resolver(n),o=window.encodeURIComponent(r);return this.storage.getItem(o).then(h=>!h||e?this.requester(r,"binary").then(a=>this.storage.setItem(o,a)):h)});return Promise.all(i)}put(t,e,i){const s=window.encodeURIComponent(t);return this.storage.getItem(s).then(n=>n||this.requester(t,"binary",e,i).then(r=>this.storage.setItem(s,r)))}request(t,e,i,s){return this.online?this.requester(t,e,i,s).then(n=>(this.put(t),n)):this.retrieve(t,e)}retrieve(t,e){let i;const s=new z(t);return e||(e=s.extension),e=="blob"?i=this.getBlob(t):i=this.getText(t),i.then(n=>{const r=new y;let o;return n?(o=this.handleResponse(n,e),r.resolve(o)):r.reject({message:"File not found in storage: "+t,stack:new Error().stack}),r.promise})}handleResponse(t,e){let i;return e=="json"?i=JSON.parse(t):$(e)?i=O(t,"text/xml"):e=="xhtml"?i=O(t,"application/xhtml+xml"):e=="html"||e=="htm"?i=O(t,"text/html"):i=t,i}getBlob(t,e){const i=window.encodeURIComponent(t);return this.storage.getItem(i).then(function(s){if(s)return e=e||H.lookup(t),new Blob([s],{type:e})})}getText(t,e){const i=window.encodeURIComponent(t);return e=e||H.lookup(t),this.storage.getItem(i).then(function(s){const n=new y,r=new FileReader;if(!s)return;const o=new Blob([s],{type:e});return r.addEventListener("loadend",()=>{n.resolve(r.result)}),r.readAsText(o,e),n.promise})}getBase64(t,e){const i=window.encodeURIComponent(t);return e=e||H.lookup(t),this.storage.getItem(i).then(s=>{const n=new y,r=new FileReader;if(!s)return;const o=new Blob([s],{type:e});return r.addEventListener("loadend",()=>{n.resolve(r.result)}),r.readAsDataURL(o),n.promise})}createUrl(t,e){const i=new y;let s,n;const r=e&&e.base64;return t in this.urlCache?(i.resolve(this.urlCache[t]),i.promise):(r?(n=this.getBase64(t),n&&n.then(o=>{this.urlCache[t]=o,i.resolve(o)})):(n=this.getBlob(t),n&&n.then(o=>{s=o?yt.createObjectURL(o):void 0,this.urlCache[t]=s,i.resolve(s)})),n||i.reject({message:"File not found in storage: "+t,stack:new Error().stack}),i.promise)}revokeUrl(t){const e=this.urlCache[t];e&&yt.revokeObjectURL(e)}destroy(){for(const t in this.urlCache)yt.revokeObjectURL(t);this.urlCache={},this.removeListeners()}}P(At.prototype);class it{constructor(t){this.interactive="",this.fixedLayout="",this.openToSpread="",this.orientationLock="",t&&this.parse(t)}parse(t){if(!t)return this;const e=b(t,"display_options");return e?(M(e,"option").forEach(s=>{let n="";switch(s.childNodes.length&&(n=s.childNodes[0].nodeValue??""),s.getAttribute("name")??""){case"interactive":this.interactive=n;break;case"fixed-layout":this.fixedLayout=n;break;case"open-to-spread":this.openToSpread=n;break;case"orientation-lock":this.orientationLock=n;break}}),this):this}destroy(){this.interactive=void 0,this.fixedLayout=void 0,this.openToSpread=void 0,this.orientationLock=void 0}}const zt="META-INF/container.xml",Xe="META-INF/com.apple.ibooks.display-options.xml",R={BINARY:"binary",BASE64:"base64",EPUB:"epub",OPF:"opf",MANIFEST:"json",DIRECTORY:"directory"};class gt{constructor(t,e){typeof e>"u"&&typeof t!="string"&&!(t instanceof Blob)&&!(t instanceof ArrayBuffer)&&(e=t,t=void 0),this.settings=_({},{requestMethod:void 0,requestCredentials:void 0,requestHeaders:void 0,encoding:void 0,replacements:void 0,canonical:void 0,openAs:void 0,store:void 0}),_(this.settings,e),this.opening=new y,this.opened=this.opening.promise,this.isOpen=!1,this.loading={manifest:new y,spine:new y,metadata:new y,cover:new y,navigation:new y,pageList:new y,resources:new y,displayOptions:new y},this.loaded={manifest:this.loading.manifest.promise,spine:this.loading.spine.promise,metadata:this.loading.metadata.promise,cover:this.loading.cover.promise,navigation:this.loading.navigation.promise,pageList:this.loading.pageList.promise,resources:this.loading.resources.promise,displayOptions:this.loading.displayOptions.promise},this.ready=Promise.all([this.loaded.manifest,this.loaded.spine,this.loaded.metadata,this.loaded.cover,this.loaded.navigation,this.loaded.resources,this.loaded.displayOptions]),this.isRendered=!1,this.request=this.settings.requestMethod||K,this.spine=new Kt,this.locations=new Rt(this.spine,i=>this.load(i)),this.navigation=void 0,this.pageList=void 0,this.url=void 0,this.path=void 0,this.archived=!1,this.archive=void 0,this.storage=void 0,this.resources=void 0,this.rendition=void 0,this.container=void 0,this.packaging=void 0,this.displayOptions=void 0,this.settings.store&&this.store(this.settings.store),t&&this.open(t,this.settings.openAs).catch(i=>{const s=new Error("Cannot load book at "+t);this.emit(f.BOOK.OPEN_FAILED,s)})}open(t,e){let i;const s=e||this.determineType(t);return s===R.BINARY?(this.archived=!0,this.url=new N("/",""),i=this.openEpub(t)):s===R.BASE64?(this.archived=!0,this.url=new N("/",""),i=this.openEpub(t,s)):s===R.EPUB?(this.archived=!0,this.url=new N("/",""),i=this.request(t,"binary",this.settings.requestCredentials,this.settings.requestHeaders).then(n=>this.openEpub(n))):s==R.OPF?(this.url=new N(t),i=this.openPackaging(this.url.Path.toString())):s==R.MANIFEST?(this.url=new N(t),i=this.openManifest(this.url.Path.toString())):(this.url=new N(t),i=this.openContainer(zt).then(n=>this.openPackaging(n))),i}openEpub(t,e){return this.unarchive(t,e||this.settings.encoding).then(()=>this.openContainer(zt)).then(i=>this.openPackaging(i))}openContainer(t){return this.load(t).then(e=>(this.container=new Ee(e),this.resolve(this.container.packagePath)))}openPackaging(t){return this.path=new z(t),this.load(t).then(e=>(this.packaging=new Ct(e),this.unpack(this.packaging)))}openManifest(t){return this.path=new z(t),this.load(t).then(e=>(this.packaging=new Ct,this.packaging.load(e),this.unpack(this.packaging)))}load(t,e){const i=this.resolve(t);return this.archived?this.archive.request(i):this.request(i,void 0,this.settings.requestCredentials,this.settings.requestHeaders)}resolve(t,e){if(!t)return"";let i=t;return t.indexOf("://")>-1?t:(this.path&&(i=this.path.resolve(t)),e!=!1&&this.url&&(i=this.url.resolve(i)),i)}canonical(t){let e=t;return t?(this.settings.canonical?e=this.settings.canonical(t):e=this.resolve(t,!0),e):""}determineType(t){let e;if(this.settings.encoding==="base64")return R.BASE64;if(typeof t!="string")return R.BINARY;if(e=new N(t).path().extension,e&&(e=e.replace(/\?.*$/,"")),!e)return R.DIRECTORY;if(e==="epub")return R.EPUB;if(e==="opf")return R.OPF;if(e==="json")return R.MANIFEST}unpack(t){this.package=t,this.packaging.metadata.layout===""?this.load(this.url.resolve(Xe)).then(e=>{this.displayOptions=new it(e),this.loading.displayOptions.resolve(this.displayOptions)}).catch(e=>{this.displayOptions=new it,this.loading.displayOptions.resolve(this.displayOptions)}):(this.displayOptions=new it,this.loading.displayOptions.resolve(this.displayOptions)),this.spine.unpack(this.packaging,(e,i)=>this.resolve(e,i),e=>this.canonical(e)),this.resources=new Zt(this.packaging.manifest,{archive:this.archive,resolver:(e,i)=>this.resolve(e,i),request:(e,i)=>this.request(e,i),replacements:this.settings.replacements||(this.archived?"blobUrl":"base64")}),this.loadNavigation(this.packaging).then(()=>{this.loading.navigation.resolve(this.navigation)}),this.packaging.coverPath&&(this.cover=this.resolve(this.packaging.coverPath)),this.loading.manifest.resolve(this.packaging.manifest),this.loading.metadata.resolve(this.packaging.metadata),this.loading.spine.resolve(this.spine),this.loading.cover.resolve(this.cover),this.loading.resources.resolve(this.resources),this.loading.pageList.resolve(this.pageList),this.isOpen=!0,this.archived||this.settings.replacements&&this.settings.replacements!="none"?this.replacements().then(()=>{this.loaded.displayOptions.then(()=>{this.opening.resolve(this)})}).catch(e=>{console.error(e)}):this.loaded.displayOptions.then(()=>{this.opening.resolve(this)})}loadNavigation(t){const e=t.navPath||t.ncxPath,i=t.toc;return i?new Promise((s,n)=>{this.navigation=new tt(i),"pageList"in t&&t.pageList&&(this.pageList=new et(t.pageList)),s(this.navigation)}):e?this.load(e,"xml").then(s=>(this.navigation=new tt(s),this.pageList=new et(s),this.navigation)):new Promise((s,n)=>{this.navigation=new tt,this.pageList=new et,s(this.navigation)})}section(t){return this.spine.get(t)}renderTo(t,e){return this.rendition=new pt(this,e),this.rendition.attachTo(t),this.rendition}setRequestCredentials(t){this.settings.requestCredentials=t}setRequestHeaders(t){this.settings.requestHeaders=t}unarchive(t,e){return this.archive=new ne,this.archive.open(t,e==="base64")}store(t){const e=this.settings.replacements&&this.settings.replacements!=="none"?this.settings.replacements:void 0,i=this.url,s=this.settings.requestMethod||((n,r)=>K(n,r));return this.storage=new At(t,s,(n,r)=>this.resolve(n,r)),this.request=(n,r)=>this.storage.request(n,r),this.opened.then(()=>{this.archived&&(this.storage.requester=(r,o)=>this.archive.request(r,o));const n=(r,o)=>{o.output=this.resources.substitute(r,o.url)};this.resources.settings.replacements=e||"blobUrl",this.resources.replacements().then(()=>this.resources.replaceCss()),this.storage.on("offline",()=>{this.url=new N("/",""),this.spine.hooks.serialize.register(n)}),this.storage.on("online",()=>{this.url=i,this.spine.hooks.serialize.deregister(n)})}),this.storage}coverUrl(){return this.loaded.cover.then(()=>this.cover?this.archived?this.archive.createUrl(this.cover):this.cover:null)}replacements(){return this.spine.hooks.serialize.register((t,e)=>{e.output=this.resources.substitute(t,e.url)}),this.resources.replacements().then(()=>this.resources.replaceCss()).then(()=>{})}getRange(t){const e=new m(t),i=this.spine.get(e.spinePos),s=n=>this.load(n);return i?i.load(s).then(function(n){return e.toRange(i.document)}):new Promise((n,r)=>{r("CFI could not be found")})}key(t){const e=t||this.packaging.metadata.identifier||this.url.filename;return`epubjs:${ut}:${e}`}destroy(){this.opened=void 0,this.loading=void 0,this.loaded=void 0,this.ready=void 0,this.isOpen=!1,this.isRendered=!1,this.spine&&this.spine.destroy(),this.locations&&this.locations.destroy(),this.pageList&&this.pageList.destroy(),this.archive&&this.archive.destroy(),this.resources&&this.resources.destroy(),this.container&&this.container.destroy(),this.packaging&&this.packaging.destroy(),this.rendition&&this.rendition.destroy(),this.displayOptions&&this.displayOptions.destroy(),this.storage&&(this.storage.destroy(),this.storage=void 0),this.spine=void 0,this.locations=void 0,this.pageList=void 0,this.archive=void 0,this.resources=void 0,this.container=void 0,this.packaging=void 0,this.rendition=void 0,this.navigation=void 0,this.url=void 0,this.path=void 0,this.archived=!1}}P(gt.prototype);function W(l,t){return new gt(l,t)}W.VERSION=ut;typeof global<"u"&&(globalThis.EPUBJS_VERSION=ut);W.Book=gt;W.Rendition=pt;W.Contents=ft;W.CFI=m;W.utils=ue;exports.Annotations=Qt;exports.Archive=ne;exports.Book=gt;exports.Contents=ft;exports.DisplayOptions=it;exports.EpubCFI=m;exports.Layout=Nt;exports.Locations=Rt;exports.Mapping=at;exports.Navigation=tt;exports.Packaging=Ct;exports.PageList=et;exports.Rendition=pt;exports.Resources=Zt;exports.Section=$t;exports.Spine=Kt;exports.Store=At;exports.Themes=Jt;exports.default=W;
4
4
  //# sourceMappingURL=epub.cjs.map