@readium/navigator 1.3.4 → 2.0.0-beta.10

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.
Files changed (57) hide show
  1. package/dist/index.js +3974 -2928
  2. package/dist/index.umd.cjs +16 -16
  3. package/package.json +10 -9
  4. package/src/Navigator.ts +11 -0
  5. package/src/epub/EpubNavigator.ts +250 -24
  6. package/src/epub/css/Properties.ts +396 -0
  7. package/src/epub/css/ReadiumCSS.ts +339 -0
  8. package/src/epub/css/index.ts +2 -0
  9. package/src/epub/frame/FrameBlobBuilder.ts +59 -9
  10. package/src/epub/frame/FrameManager.ts +23 -1
  11. package/src/epub/frame/FramePoolManager.ts +62 -4
  12. package/src/epub/fxl/FXLFramePoolManager.ts +23 -16
  13. package/src/epub/index.ts +3 -1
  14. package/src/epub/preferences/EpubDefaults.ts +165 -0
  15. package/src/epub/preferences/EpubPreferences.ts +192 -0
  16. package/src/epub/preferences/EpubPreferencesEditor.ts +534 -0
  17. package/src/epub/preferences/EpubSettings.ts +239 -0
  18. package/src/epub/preferences/guards.ts +86 -0
  19. package/src/epub/preferences/index.ts +4 -0
  20. package/src/helpers/dimensions.ts +13 -0
  21. package/src/helpers/index.ts +1 -0
  22. package/src/helpers/lineLength.ts +241 -0
  23. package/src/helpers/sML.ts +25 -3
  24. package/src/index.ts +2 -1
  25. package/src/preferences/Configurable.ts +16 -0
  26. package/src/preferences/Preference.ts +272 -0
  27. package/src/preferences/PreferencesEditor.ts +6 -0
  28. package/src/preferences/Types.ts +38 -0
  29. package/src/preferences/index.ts +4 -0
  30. package/types/src/Navigator.d.ts +9 -0
  31. package/types/src/epub/EpubNavigator.d.ts +34 -4
  32. package/types/src/epub/css/Properties.d.ts +183 -0
  33. package/types/src/epub/css/ReadiumCSS.d.ts +31 -0
  34. package/types/src/epub/css/index.d.ts +2 -0
  35. package/types/src/epub/frame/FrameBlobBuilder.d.ts +5 -1
  36. package/types/src/epub/frame/FrameManager.d.ts +4 -0
  37. package/types/src/epub/frame/FramePoolManager.d.ts +8 -1
  38. package/types/src/epub/fxl/FXLFramePoolManager.d.ts +4 -4
  39. package/types/src/epub/index.d.ts +2 -0
  40. package/types/src/epub/preferences/EpubDefaults.d.ts +86 -0
  41. package/types/src/epub/preferences/EpubPreferences.d.ts +90 -0
  42. package/types/src/epub/preferences/EpubPreferencesEditor.d.ts +55 -0
  43. package/types/src/epub/preferences/EpubSettings.d.ts +89 -0
  44. package/types/src/epub/preferences/guards.d.ts +9 -0
  45. package/types/src/epub/preferences/index.d.ts +4 -0
  46. package/types/src/helpers/dimensions.d.ts +7 -0
  47. package/types/src/helpers/index.d.ts +1 -0
  48. package/types/src/helpers/lineLength.d.ts +54 -0
  49. package/types/src/helpers/sML.d.ts +6 -1
  50. package/types/src/index.d.ts +1 -0
  51. package/types/src/preferences/Configurable.d.ts +13 -0
  52. package/types/src/preferences/Preference.d.ts +117 -0
  53. package/types/src/preferences/PreferencesEditor.d.ts +5 -0
  54. package/types/src/preferences/PreferencesSerializer.d.ts +5 -0
  55. package/types/src/preferences/Types.d.ts +23 -0
  56. package/types/src/preferences/index.d.ts +4 -0
  57. package/LICENSE +0 -28
@@ -1,7 +1,7 @@
1
- (function(Q,hA){typeof exports=="object"&&typeof module<"u"?hA(exports):typeof define=="function"&&define.amd?define(["exports"],hA):(Q=typeof globalThis<"u"?globalThis:Q||self,hA(Q.navigator={}))})(this,function(Q){"use strict";let hA=class Se{constructor(A){this.algorithm=A.algorithm,this.compression=A.compression,this.originalLength=A.originalLength,this.profile=A.profile,this.scheme=A.scheme}static deserialize(A){if(A&&A.algorithm)return new Se({algorithm:A.algorithm,compression:A.compression,originalLength:A.originalLength,profile:A.profile,scheme:A.scheme})}serialize(){const A={algorithm:this.algorithm};return this.compression!==void 0&&(A.compression=this.compression),this.originalLength!==void 0&&(A.originalLength=this.originalLength),this.profile!==void 0&&(A.profile=this.profile),this.scheme!==void 0&&(A.scheme=this.scheme),A}};class U{constructor(A){this.otherProperties=A}static deserialize(A){if(A)return new U(A)}serialize(){return this.otherProperties}add(A){const t=Object.assign({},this.otherProperties);for(const e in A)t[e]=A[e];return new U(t)}}Object.defineProperty(U.prototype,"encryption",{get:function(){return hA.deserialize(this.otherProperties.encrypted)}});var C=(i=>(i.fixed="fixed",i.reflowable="reflowable",i))(C||{}),X=(i=>(i.auto="auto",i.landscape="landscape",i.portrait="portrait",i))(X||{}),D=(i=>(i.left="left",i.right="right",i.center="center",i))(D||{}),uA=(i=>(i.auto="auto",i.both="both",i.none="none",i.landscape="landscape",i))(uA||{});U.prototype.getContains=function(){return new Set(this.otherProperties.contains||[])},U.prototype.getLayout=function(){return this.otherProperties.layout};class d{constructor(A){let t,e,n=A.mediaType.replace(/\s/g,"").split(";");const r=n[0].split("/");if(r.length===2){if(t=r[0].toLowerCase().trim(),e=r[1].toLowerCase().trim(),t.length===0||e.length===0)throw new Error("Invalid media type")}else throw new Error("Invalid media type");const s={};for(let g=1;g<n.length;g++){const u=n[g].split("=");if(u.length===2){const m=u[0].toLocaleLowerCase(),B=m==="charset"?u[1].toUpperCase():u[1];s[m]=B}}const o={},a=Object.keys(s);a.sort((g,u)=>g.localeCompare(u)),a.forEach(g=>o[g]=s[g]);let h="";for(const g in o){const u=o[g];h+=`;${g}=${u}`}const c=`${t}/${e}${h}`,l=o.encoding;this.string=c,this.type=t,this.subtype=e,this.parameters=o,this.encoding=l,this.name=A.name,this.fileExtension=A.fileExtension}static parse(A){return new d(A)}get structuredSyntaxSuffix(){const A=this.subtype.split("+");return A.length>1?`+${A[A.length-1]}`:void 0}get charset(){return this.parameters.charset}contains(A){const t=typeof A=="string"?d.parse({mediaType:A}):A;if(!((this.type==="*"||this.type===t.type)&&(this.subtype==="*"||this.subtype===t.subtype)))return!1;const e=new Set(Object.entries(this.parameters).map(([r,s])=>`${r}=${s}`)),n=new Set(Object.entries(t.parameters).map(([r,s])=>`${r}=${s}`));for(const r of Array.from(e.values()))if(!n.has(r))return!1;return!0}matches(A){const t=typeof A=="string"?d.parse({mediaType:A}):A;return this.contains(t)||t.contains(this)}matchesAny(...A){for(const t of A)if(this.matches(t))return!0;return!1}equals(A){return this.string===A.string}get isZIP(){return this.matchesAny(d.ZIP,d.LCP_PROTECTED_AUDIOBOOK,d.LCP_PROTECTED_PDF)||this.structuredSyntaxSuffix==="+zip"}get isJSON(){return this.matchesAny(d.JSON)||this.structuredSyntaxSuffix==="+json"}get isOPDS(){return this.matchesAny(d.OPDS1,d.OPDS1_ENTRY,d.OPDS2,d.OPDS2_PUBLICATION,d.OPDS_AUTHENTICATION)||this.structuredSyntaxSuffix==="+json"}get isHTML(){return this.matchesAny(d.HTML,d.XHTML)}get isBitmap(){return this.matchesAny(d.BMP,d.GIF,d.JPEG,d.PNG,d.TIFF,d.WEBP)}get isAudio(){return this.type==="audio"}get isVideo(){return this.type==="video"}get isRWPM(){return this.matchesAny(d.READIUM_AUDIOBOOK_MANIFEST,d.DIVINA_MANIFEST,d.READIUM_WEBPUB_MANIFEST)}get isPublication(){return this.matchesAny(d.READIUM_AUDIOBOOK,d.READIUM_AUDIOBOOK_MANIFEST,d.CBZ,d.DIVINA,d.DIVINA_MANIFEST,d.EPUB,d.LCP_PROTECTED_AUDIOBOOK,d.LCP_PROTECTED_PDF,d.LPF,d.PDF,d.W3C_WPUB_MANIFEST,d.READIUM_WEBPUB,d.READIUM_WEBPUB_MANIFEST,d.ZAB)}static get AAC(){return d.parse({mediaType:"audio/aac",fileExtension:"aac"})}static get ACSM(){return d.parse({mediaType:"application/vnd.adobe.adept+xml",name:"Adobe Content Server Message",fileExtension:"acsm"})}static get AIFF(){return d.parse({mediaType:"audio/aiff",fileExtension:"aiff"})}static get AVI(){return d.parse({mediaType:"video/x-msvideo",fileExtension:"avi"})}static get BINARY(){return d.parse({mediaType:"application/octet-stream"})}static get BMP(){return d.parse({mediaType:"image/bmp",fileExtension:"bmp"})}static get CBZ(){return d.parse({mediaType:"application/vnd.comicbook+zip",name:"Comic Book Archive",fileExtension:"cbz"})}static get CSS(){return d.parse({mediaType:"text/css",fileExtension:"css"})}static get DIVINA(){return d.parse({mediaType:"application/divina+zip",name:"Digital Visual Narratives",fileExtension:"divina"})}static get DIVINA_MANIFEST(){return d.parse({mediaType:"application/divina+json",name:"Digital Visual Narratives",fileExtension:"json"})}static get EPUB(){return d.parse({mediaType:"application/epub+zip",name:"EPUB",fileExtension:"epub"})}static get GIF(){return d.parse({mediaType:"image/gif",fileExtension:"gif"})}static get GZ(){return d.parse({mediaType:"application/gzip",fileExtension:"gz"})}static get HTML(){return d.parse({mediaType:"text/html",fileExtension:"html"})}static get JAVASCRIPT(){return d.parse({mediaType:"text/javascript",fileExtension:"js"})}static get JPEG(){return d.parse({mediaType:"image/jpeg",fileExtension:"jpeg"})}static get JSON(){return d.parse({mediaType:"application/json"})}static get LCP_LICENSE_DOCUMENT(){return d.parse({mediaType:"application/vnd.readium.lcp.license.v1.0+json",name:"LCP License",fileExtension:"lcpl"})}static get LCP_PROTECTED_AUDIOBOOK(){return d.parse({mediaType:"application/audiobook+lcp",name:"LCP Protected Audiobook",fileExtension:"lcpa"})}static get LCP_PROTECTED_PDF(){return d.parse({mediaType:"application/pdf+lcp",name:"LCP Protected PDF",fileExtension:"lcpdf"})}static get LCP_STATUS_DOCUMENT(){return d.parse({mediaType:"application/vnd.readium.license.status.v1.0+json"})}static get LPF(){return d.parse({mediaType:"application/lpf+zip",fileExtension:"lpf"})}static get MP3(){return d.parse({mediaType:"audio/mpeg",fileExtension:"mp3"})}static get MPEG(){return d.parse({mediaType:"video/mpeg",fileExtension:"mpeg"})}static get NCX(){return d.parse({mediaType:"application/x-dtbncx+xml",fileExtension:"ncx"})}static get OGG(){return d.parse({mediaType:"audio/ogg",fileExtension:"oga"})}static get OGV(){return d.parse({mediaType:"video/ogg",fileExtension:"ogv"})}static get OPDS1(){return d.parse({mediaType:"application/atom+xml;profile=opds-catalog"})}static get OPDS1_ENTRY(){return d.parse({mediaType:"application/atom+xml;type=entry;profile=opds-catalog"})}static get OPDS2(){return d.parse({mediaType:"application/opds+json"})}static get OPDS2_PUBLICATION(){return d.parse({mediaType:"application/opds-publication+json"})}static get OPDS_AUTHENTICATION(){return d.parse({mediaType:"application/opds-authentication+json"})}static get OPUS(){return d.parse({mediaType:"audio/opus",fileExtension:"opus"})}static get OTF(){return d.parse({mediaType:"font/otf",fileExtension:"otf"})}static get PDF(){return d.parse({mediaType:"application/pdf",name:"PDF",fileExtension:"pdf"})}static get PNG(){return d.parse({mediaType:"image/png",fileExtension:"png"})}static get READIUM_AUDIOBOOK(){return d.parse({mediaType:"application/audiobook+zip",name:"Readium Audiobook",fileExtension:"audiobook"})}static get READIUM_AUDIOBOOK_MANIFEST(){return d.parse({mediaType:"application/audiobook+json",name:"Readium Audiobook",fileExtension:"json"})}static get READIUM_CONTENT_DOCUMENT(){return d.parse({mediaType:"application/vnd.readium.content+json",name:"Readium Content Document",fileExtension:"json"})}static get READIUM_GUIDED_NAVIGATION_DOCUMENT(){return d.parse({mediaType:"application/guided-navigation+json",name:"Readium Guided Navigation Document",fileExtension:"json"})}static get READIUM_POSITION_LIST(){return d.parse({mediaType:"application/vnd.readium.position-list+json",name:"Readium Position List",fileExtension:"json"})}static get READIUM_WEBPUB(){return d.parse({mediaType:"application/webpub+zip",name:"Readium Web Publication",fileExtension:"webpub"})}static get READIUM_WEBPUB_MANIFEST(){return d.parse({mediaType:"application/webpub+json",name:"Readium Web Publication",fileExtension:"json"})}static get SMIL(){return d.parse({mediaType:"application/smil+xml",fileExtension:"smil"})}static get SVG(){return d.parse({mediaType:"image/svg+xml",fileExtension:"svg"})}static get TEXT(){return d.parse({mediaType:"text/plain",fileExtension:"txt"})}static get TIFF(){return d.parse({mediaType:"image/tiff",fileExtension:"tiff"})}static get TTF(){return d.parse({mediaType:"font/ttf",fileExtension:"ttf"})}static get W3C_WPUB_MANIFEST(){return d.parse({mediaType:"application/x.readium.w3c.wpub+json",name:"Web Publication",fileExtension:"json"})}static get WAV(){return d.parse({mediaType:"audio/wav",fileExtension:"wav"})}static get WEBM_AUDIO(){return d.parse({mediaType:"audio/webm",fileExtension:"webm"})}static get WEBM_VIDEO(){return d.parse({mediaType:"video/webm",fileExtension:"webm"})}static get WEBP(){return d.parse({mediaType:"image/webp",fileExtension:"webp"})}static get WOFF(){return d.parse({mediaType:"font/woff",fileExtension:"woff"})}static get WOFF2(){return d.parse({mediaType:"font/woff2",fileExtension:"woff2"})}static get XHTML(){return d.parse({mediaType:"application/xhtml+xml",fileExtension:"xhtml"})}static get XML(){return d.parse({mediaType:"application/xml",fileExtension:"xml"})}static get ZAB(){return d.parse({mediaType:"application/x.readium.zab+zip",name:"Zipped Audio Book",fileExtension:"zab"})}static get ZIP(){return d.parse({mediaType:"application/zip",fileExtension:"zip"})}}class ht{constructor(A){this.uri=A,this.parameters=this.getParameters(A)}getParameters(A){const t=/\{\??([^}]+)\}/g,e=A.match(t);return e?new Set(e.join(",").replace(t,"$1").split(",").map(n=>n.trim())):new Set}expand(A){const t=n=>n.split(",").map(r=>{const s=A[r];return s?encodeURIComponent(s):""}).join(","),e=n=>"?"+n.split(",").map(r=>{const s=r.split("=")[0],o=A[s];return o?`${s}=${encodeURIComponent(o)}`:""}).join("&");return this.uri.replace(/\{(\??)([^}]+)\}/g,(...n)=>n[1]?e(n[2]):t(n[2]))}}function Je(i){return i&&i instanceof Array?i:void 0}function ct(i){return i&&typeof i=="string"?[i]:Je(i)}function lt(i){return typeof i=="string"?new Date(i):void 0}function mA(i){return isNaN(i)?void 0:i}function T(i){return mA(i)!==void 0&&Math.sign(i)>=0?i:void 0}function Pe(i){const A=new Array;return i.forEach(t=>A.push(t)),A}class z{constructor(A){this.fragments=A.fragments?A.fragments:new Array,this.progression=A.progression,this.totalProgression=A.totalProgression,this.position=A.position,this.otherLocations=A.otherLocations}static deserialize(A){if(!A)return;const t=mA(A.progression),e=mA(A.totalProgression),n=mA(A.position),r=new Map,s=new Set(["fragment","fragments","progression","totalProgression","position"]);return Object.entries(A).forEach(([o,a])=>{s.has(o)||r.set(o,a)}),new z({fragments:ct(A.fragments||A.fragment),progression:t!==void 0&&t>=0&&t<=1?t:void 0,totalProgression:e!==void 0&&e>=0&&e<=1?e:void 0,position:n!==void 0&&n>0?n:void 0,otherLocations:r.size===0?void 0:r})}serialize(){const A={};return this.fragments&&(A.fragments=this.fragments),this.progression!==void 0&&(A.progression=this.progression),this.totalProgression!==void 0&&(A.totalProgression=this.totalProgression),this.position!==void 0&&(A.position=this.position),this.otherLocations&&this.otherLocations.forEach((t,e)=>A[e]=t),A}}class jA{constructor(A){this.after=A.after,this.before=A.before,this.highlight=A.highlight}static deserialize(A){if(A)return new jA({after:A.after,before:A.before,highlight:A.highlight})}serialize(){const A={};return this.after!==void 0&&(A.after=this.after),this.before!==void 0&&(A.before=this.before),this.highlight!==void 0&&(A.highlight=this.highlight),A}}let SA=class rt{constructor(A){this.href=A.href,this.type=A.type,this.title=A.title,this.locations=A.locations?A.locations:new z({}),this.text=A.text}static deserialize(A){if(A&&A.href&&A.type)return new rt({href:A.href,type:A.type,title:A.title,locations:z.deserialize(A.locations),text:jA.deserialize(A.text)})}serialize(){const A={href:this.href,type:this.type};return this.title!==void 0&&(A.title=this.title),this.locations&&(A.locations=this.locations.serialize()),this.text&&(A.text=this.text.serialize()),A}copyWithLocations(A){return new rt({href:this.href,type:this.type,title:this.title,text:this.text,locations:new z({...this.locations,...A})})}};class J{constructor(A){this.href=A.href,this.templated=A.templated,this.type=A.type,this.title=A.title,this.rels=A.rels,this.properties=A.properties,this.height=A.height,this.width=A.width,this.duration=A.duration,this.bitrate=A.bitrate,this.languages=A.languages,this.alternates=A.alternates,this.children=A.children}static deserialize(A){if(A&&A.href&&typeof A.href=="string")return new J({href:A.href,templated:A.templated,type:A.type,title:A.title,rels:A.rel?A.rel instanceof Array?new Set(A.rel):new Set([A.rel]):void 0,properties:U.deserialize(A.properties),height:T(A.height),width:T(A.width),duration:T(A.duration),bitrate:T(A.bitrate),languages:ct(A.language),alternates:BA.deserialize(A.alternate),children:BA.deserialize(A.children)})}serialize(){const A={href:this.href};return this.templated!==void 0&&(A.templated=this.templated),this.type!==void 0&&(A.type=this.type),this.title!==void 0&&(A.title=this.title),this.rels&&(A.rel=Pe(this.rels)),this.properties&&(A.properties=this.properties.serialize()),this.height!==void 0&&(A.height=this.height),this.width!==void 0&&(A.width=this.width),this.duration!==void 0&&(A.duration=this.duration),this.bitrate!==void 0&&(A.bitrate=this.bitrate),this.languages&&(A.language=this.languages),this.alternates&&(A.alternate=this.alternates.serialize()),this.children&&(A.children=this.children.serialize()),A}get mediaType(){return this.type!==void 0?d.parse({mediaType:this.type}):d.BINARY}toURL(A){const t=this.href.replace(/^(\/)/,"");if(t.length===0)return;let e=A||"/";return e.startsWith("/")&&(e="file://"+e),new URL(t,e).href.replace(/^(file:\/\/)/,"")}get templateParameters(){return this.templated?new ht(this.href).parameters:new Set}expandTemplate(A){return new J({href:new ht(this.href).expand(A),templated:!1})}addProperties(A){var t;const e=J.deserialize(this.serialize());return e.properties=e.properties?(t=e.properties)==null?void 0:t.add(A):new U(A),e}get locator(){let A=this.href.split("#");return new SA({href:A.length>0&&A[0]!==void 0?A[0]:this.href,type:this.type??"",title:this.title,locations:new z({fragments:A.length>1&&A[1]!==void 0?[A[1]]:[]})})}}class BA{constructor(A){this.items=A}static deserialize(A){if(A&&A instanceof Array)return new BA(A.map(t=>J.deserialize(t)).filter(t=>t!==void 0))}serialize(){return this.items.map(A=>A.serialize())}findWithRel(A){const t=e=>e.rels&&e.rels.has(A);return this.items.find(t)}filterByRel(A){const t=e=>e.rels&&e.rels.has(A);return this.items.filter(t)}findWithHref(A){const t=e=>e.href===A;return this.items.find(t)}findIndexWithHref(A){const t=e=>e.href===A;return this.items.findIndex(t)}findWithMediaType(A){const t=e=>e.mediaType.matches(A);return this.items.find(t)}filterByMediaType(A){const t=e=>e.mediaType.matches(A);return this.items.filter(t)}filterByMediaTypes(A){const t=e=>{for(const n of A)if(e.mediaType.matches(n))return!0;return!1};return this.items.filter(t)}everyIsAudio(){const A=t=>t.mediaType.isAudio;return this.items.length>0&&this.items.every(A)}everyIsBitmap(){const A=t=>t.mediaType.isBitmap;return this.items.length>0&&this.items.every(A)}everyIsHTML(){const A=t=>t.mediaType.isHTML;return this.items.length>0&&this.items.every(A)}everyIsVideo(){const A=t=>t.mediaType.isVideo;return this.items.length>0&&this.items.every(A)}everyMatchesMediaType(A){return Array.isArray(A)?this.items.length>0&&this.items.every(t=>{for(const e of A)return t.mediaType.matches(e);return!1}):this.items.length>0&&this.items.every(t=>t.mediaType.matches(A))}filterLinksHasType(){return this.items.filter(A=>A.type)}}let gt=class Ve{constructor(A){this.cssSelector=A.cssSelector,this.textNodeIndex=A.textNodeIndex,this.charOffset=A.charOffset}static deserialize(A){if(!(A&&A.cssSelector))return;let t=T(A.textNodeIndex);if(t===void 0)return;let e=T(A.charOffset);return e===void 0&&(e=T(A.offset)),new Ve({cssSelector:A.cssSelector,textNodeIndex:t,charOffset:e})}serialize(){const A={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(A.charOffset=this.charOffset),A}},ke=class De{constructor(A){this.start=A.start,this.end=A.end}static deserialize(A){if(!A)return;let t=gt.deserialize(A.start);if(t)return new De({start:t,end:gt.deserialize(A.end)})}serialize(){const A={start:this.start.serialize()};return this.end&&(A.end=this.end.serialize()),A}};z.prototype.getCssSelector=function(){var i;return(i=this.otherLocations)==null?void 0:i.get("cssSelector")},z.prototype.getPartialCfi=function(){var i;return(i=this.otherLocations)==null?void 0:i.get("partialCfi")},z.prototype.getDomRange=function(){var i;return ke.deserialize((i=this.otherLocations)==null?void 0:i.get("domRange"))},z.prototype.fragmentParameters=function(){return new Map(this.fragments.map(i=>i.startsWith("#")?i.slice(1):i).join("&").split("&").filter(i=>!i.startsWith("#")).map(i=>i.split("=")).filter(i=>i.length===2).map(i=>[i[0].trim().toLowerCase(),i[1].trim()]))},z.prototype.htmlId=function(){if(!this.fragments.length)return;let i=this.fragments.find(A=>A.length&&!A.includes("="));if(!i){const A=this.fragmentParameters();A.has("id")?i=A.get("id"):A.has("name")&&(i=A.get("name"))}return i!=null&&i.startsWith("#")?i.slice(1):i},z.prototype.page=function(){const i=parseInt(this.fragmentParameters().get("page"));if(!isNaN(i)&&i>=0)return i},z.prototype.time=function(){const i=parseInt(this.fragmentParameters().get("t"));if(!isNaN(i))return i},z.prototype.space=function(){const i=this.fragmentParameters();if(!i.has("xywh"))return;const A=i.get("xywh").split(",").map(t=>parseInt(t));if(A.length===4&&!A.some(isNaN))return A};let We=class He{constructor(A){this.currency=A.currency,this.value=A.value}static deserialize(A){if(!A)return;let t=A.currency;if(!(t&&typeof t=="string"&&t.length>0))return;let e=T(A.value);if(e!==void 0)return new He({currency:t,value:e})}serialize(){return{currency:this.currency,value:this.value}}};class cA{constructor(A){this.type=A.type,this.children=A.children}static deserialize(A){if(A&&A.type)return new cA({type:A.type,children:cA.deserializeArray(A.children)})}static deserializeArray(A){if(A instanceof Array)return A.map(t=>cA.deserialize(t)).filter(t=>t!==void 0)}serialize(){const A={type:this.type};return this.children&&(A.children=this.children.map(t=>t.serialize())),A}}let Le=class Ge{constructor(A){this.total=A.total,this.position=A.position}static deserialize(A){if(A)return new Ge({total:T(A.total),position:T(A.position)})}serialize(){const A={};return this.total!==void 0&&(A.total=this.total),this.position!==void 0&&(A.position=this.position),A}},Oe=class ve{constructor(A){this.total=A.total,this.available=A.available}static deserialize(A){if(A)return new ve({total:T(A.total),available:T(A.available)})}serialize(){const A={};return this.total!==void 0&&(A.total=this.total),this.available!==void 0&&(A.available=this.available),A}},Xe=class be{constructor(A){this.state=A.state,this.since=A.since,this.until=A.until}static deserialize(A){if(A&&A.state)return new be({state:A.state,since:lt(A.since),until:lt(A.until)})}serialize(){const A={state:this.state};return this.since!==void 0&&(A.since=this.since.toISOString()),this.until!==void 0&&(A.until=this.until.toISOString()),A}};U.prototype.getNumberOfItems=function(){return T(this.otherProperties.numberOfItems)},U.prototype.getPrice=function(){return We.deserialize(this.otherProperties.price)},U.prototype.getIndirectAcquisitions=function(){const i=this.otherProperties.indirectAcquisition;if(i&&i instanceof Array)return i.map(A=>cA.deserialize(A)).filter(A=>A!==void 0)},U.prototype.getHolds=function(){return Le.deserialize(this.otherProperties.holds)},U.prototype.getCopies=function(){return Oe.deserialize(this.otherProperties.copies)},U.prototype.getAvailability=function(){return Xe.deserialize(this.otherProperties.availability)},U.prototype.getAuthenticate=function(){return J.deserialize(this.otherProperties.authenticate)};var F=(i=>(i.auto="auto",i.btt="btt",i.ltr="ltr",i.rtl="rtl",i.ttb="ttb",i))(F||{});U.prototype.getClipped=function(){return this.otherProperties.clipped},U.prototype.getFit=function(){return this.otherProperties.fit},U.prototype.getOrientation=function(){return this.otherProperties.orientation},U.prototype.getOverflow=function(){return this.otherProperties.overflow},U.prototype.getPage=function(){return this.otherProperties.page||void 0},U.prototype.getSpread=function(){return this.otherProperties.spread||void 0};var P;(function(i){i.NONE="none",i.DESCENDANT="descendant",i.CHILD="child"})(P||(P={}));var S;(function(i){i.id="id",i.class="class",i.tag="tag",i.attribute="attribute",i.nthchild="nthchild",i.nthoftype="nthoftype"})(S||(S={}));const Ze="CssSelectorGenerator";function dt(i="unknown problem",...A){console.warn(`${Ze}: ${i}`,...A)}S.id,S.class,S.tag,S.attribute,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY;function Ke(i){return i instanceof RegExp}function qe(i){return i.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function _e(i){const A=i.map(t=>{if(Ke(t))return e=>t.test(e);if(typeof t=="function")return e=>{const n=t(e);return typeof n!="boolean"?(dt("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",t),!1):n};if(typeof t=="string"){const e=new RegExp("^"+qe(t)+"$");return n=>e.test(n)}return dt("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1});return t=>A.some(e=>e(t))}const $e="",Ai=" > ",ti=" ";P.NONE+"",P.NONE,P.DESCENDANT+"",P.DESCENDANT,P.CHILD+"",P.CHILD,S.nthoftype,S.tag,S.id,S.class,S.attribute,S.nthchild,_e(["class","id","ng-*"]);class Mt{}class ut extends Mt{goLeft(A=!1,t){this.readingProgression===F.ltr||this.readingProgression===F.ttb||this.readingProgression===F.auto?this.goBackward(A,t):(this.readingProgression===F.rtl||this.readingProgression===F.btt)&&this.goForward(A,t)}goRight(A=!1,t){this.readingProgression===F.ltr||this.readingProgression===F.ttb||this.readingProgression===F.auto?this.goForward(A,t):(this.readingProgression===F.rtl||this.readingProgression===F.btt)&&this.goBackward(A,t)}}const ei=`@namespace url(http://www.w3.org/1999/xhtml);@namespace epub url(http://www.idpf.org/2007/ops);@namespace m url(http://www.w3.org/1998/Math/MathML/);@namespace svg url(http://www.w3.org/2000/svg);:root{--RS__colWidth:45em;--RS__colCount:1;--RS__colGap:0;--RS__maxLineLength:40rem;--RS__pageGutter:20px;--RS__viewportWidth:100%}@page{margin:0!important}:root{position:relative;-webkit-column-width:var(--RS__colWidth);-moz-column-width:var(--RS__colWidth);column-width:var(--RS__colWidth);-webkit-column-count:var(--RS__colCount);-moz-column-count:var(--RS__colCount);column-count:var(--RS__colCount);-webkit-column-gap:var(--RS__colGap);-moz-column-gap:var(--RS__colGap);column-gap:var(--RS__colGap);-moz-column-fill:auto;column-fill:auto;width:var(--RS__viewportWidth);height:100vh;max-width:var(--RS__viewportWidth);max-height:100vh;min-width:var(--RS__viewportWidth);min-height:100vh;padding:0!important;margin:0!important;font-size:100%!important;-webkit-text-size-adjust:100%;box-sizing:border-box;-webkit-perspective:1;-webkit-touch-callout:none}body{width:100%;max-width:var(--RS__maxLineLength)!important;padding:0 var(--RS__pageGutter)!important;margin:0 auto!important;box-sizing:border-box}@media screen and (min-width: 35em){:root{--RS__pageGutter:30px}}@media screen and (min-width: 45em){:root{--RS__pageGutter:40px}}@media screen and (min-width: 75em){:root{--RS__pageGutter:50px}}@media screen and (min-width: 60em),screen and (min-device-width: 36em) and (max-device-width: 47em) and (orientation: landscape){:root{--RS__colWidth:20em;--RS__colCount:2;--RS__maxLineLength:39.99rem}}:root[style*=readium-scroll-on]{-webkit-columns:auto auto!important;-moz-columns:auto auto!important;columns:auto auto!important;width:auto!important;height:auto!important;max-width:none!important;max-height:none!important;min-width:0!important;min-height:0!important}:root[style*=readium-scroll-on] body{--RS__maxLineLength:40rem !important}:root[style*=readium-night-on]{--RS__backgroundColor:#000000;--RS__textColor:#FEFEFE;--RS__linkColor:#63caff;--RS__visitedColor:#0099E5;--RS__selectionBackgroundColor:#b4d8fe;--RS__selectionTextColor:inherit}:root[style*=readium-night-on] *:not(a){color:inherit!important;background-color:transparent!important;border-color:currentcolor!important}:root[style*=readium-night-on] svg text{fill:currentcolor!important;stroke:none!important}:root[style*=readium-night-on] a:link,:root[style*=readium-night-on] a:link *{color:var(--RS__linkColor)!important}:root[style*=readium-night-on] a:visited,:root[style*=readium-night-on] a:visited *{color:var(--RS__visitedColor)!important}:root[style*=readium-night-on] img[class*=gaiji],:root[style*=readium-night-on] *[epub\\:type~=titlepage] img:only-child,:root[style*=readium-night-on] *[epub|type~=titlepage] img:only-child{-webkit-filter:invert(100%);filter:invert(100%)}:root[style*=readium-night-on][style*=readium-darken-on] img{-webkit-filter:brightness(80%);filter:brightness(80%)}:root[style*=readium-night-on][style*=readium-invert-on] img{-webkit-filter:invert(100%);filter:invert(100%)}:root[style*=readium-night-on][style*=readium-darken-on][style*=readium-invert-on] img{-webkit-filter:brightness(80%) invert(100%);filter:brightness(80%) invert(100%)}:root[style*=readium-sepia-on]{--RS__backgroundColor:#faf4e8;--RS__textColor:#121212;--RS__linkColor:#0000EE;--RS__visitedColor:#551A8B;--RS__selectionBackgroundColor:#b4d8fe;--RS__selectionTextColor:inherit;--RS__maxLineLength:40.01rem}:root[style*=readium-sepia-on] *:not(a){color:inherit!important;background-color:transparent!important}:root[style*=readium-sepia-on] a:link,:root[style*=readium-sepia-on] a:link *{color:var(--RS__linkColor)}:root[style*=readium-sepia-on] a:visited,:root[style*=readium-sepia-on] a:visited *{color:var(--RS__visitedColor)}:root[style*=readium-sepia-on] svg,:root[style*=readium-sepia-on] img{background-color:transparent!important;mix-blend-mode:multiply}@media screen and (-ms-high-contrast: active){:root{color:windowText!important;background-color:window!important}:root :not(#\\#):not(#\\#):not(#\\#),:root :not(#\\#):not(#\\#):not(#\\#) :not(#\\#):not(#\\#):not(#\\#) :root :not(#\\#):not(#\\#):not(#\\#) :not(#\\#):not(#\\#):not(#\\#) :not(#\\#):not(#\\#):not(#\\#){color:inherit!important;background-color:inherit!important}.readiumCSS-mo-active-default{color:highlightText!important;background-color:highlight!important}}@media screen and (-ms-high-contrast: white-on-black){:root[style*=readium-night-on] img[class*=gaiji],:root[style*=readium-night-on] *[epub\\:type~=titlepage] img:only-child,:root[style*=readium-night-on] *[epub|type~=titlepage] img:only-child{-webkit-filter:none!important;filter:none!important}:root[style*=readium-night-on][style*=readium-invert-on] img{-webkit-filter:none!important;filter:none!important}:root[style*=readium-night-on][style*=readium-darken-on][style*=readium-invert-on] img{-webkit-filter:brightness(80%);filter:brightness(80%)}}@media screen and (inverted-colors){:root[style*=readium-night-on] img[class*=gaiji],:root[style*=readium-night-on] *[epub\\:type~=titlepage] img:only-child,:root[style*=readium-night-on] *[epub|type~=titlepage] img:only-child{-webkit-filter:none!important;filter:none!important}:root[style*=readium-night-on][style*=readium-invert-on] img{-webkit-filter:none!important;filter:none!important}:root[style*=readium-night-on][style*=readium-darken-on][style*=readium-invert-on] img{-webkit-filter:brightness(80%);filter:brightness(80%)}}@media screen and (min-width: 60em),screen and (min-device-width: 36em) and (max-device-width: 47em) and (orientation: landscape){:root[style*="--USER__colCount: 1"],:root[style*="--USER__colCount:1"],:root[style*="--USER__colCount: 2"],:root[style*="--USER__colCount:2"]{-webkit-column-count:var(--USER__colCount);-moz-column-count:var(--USER__colCount);column-count:var(--USER__colCount)}:root[style*="--USER__colCount: 1"],:root[style*="--USER__colCount:1"]{--RS__maxLineLength:40rem !important;--RS__colWidth:100vw}:root[style*="--USER__colCount: 2"],:root[style*="--USER__colCount:2"]{--RS__colWidth:auto}}:root[style*=--USER__pageMargins] body{padding:0 calc(var(--RS__pageGutter) * var(--USER__pageMargins))!important}:root[style*=--USER__backgroundColor]{background-color:var(--USER__backgroundColor)!important}:root[style*=--USER__backgroundColor] *{background-color:transparent!important}:root[style*=--USER__textColor]{color:var(--USER__textColor)!important}:root[style*=--USER__textColor] *:not(h1):not(h2):not(h3):not(h4):not(h5):not(h6):not(pre){color:inherit!important}:root[style*=readium-advanced-on][style*=--USER__textAlign]{text-align:var(--USER__textAlign)}:root[style*=readium-advanced-on][style*=--USER__textAlign] body,:root[style*=readium-advanced-on][style*=--USER__textAlign] *:not(blockquote):not(figcaption) p,:root[style*=readium-advanced-on][style*=--USER__textAlign] li{text-align:var(--USER__textAlign)!important;-moz-text-align-last:auto!important;-epub-text-align-last:auto!important;text-align-last:auto!important}:root[style*=readium-advanced-on][style*="--USER__textAlign: justify"] body,:root[style*=readium-advanced-on][style*="--USER__textAlign:justify"] body{-webkit-hyphens:auto;-moz-hyphens:auto;-ms-hyphens:auto;-epub-hyphens:auto;hyphens:auto}:root[style*=readium-advanced-on][style*="--USER__textAlign: left"] body,:root[style*=readium-advanced-on][style*="--USER__textAlign:left"] body,:root[style*=readium-advanced-on][style*="--USER__textAlign: right"] body,:root[style*=readium-advanced-on][style*="--USER__textAlign:right"] body{-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;-epub-hyphens:none;hyphens:none}:root[style*=readium-advanced-on][style*=--USER__bodyHyphens]{-webkit-hyphens:var(--USER__bodyHyphens)!important;-moz-hyphens:var(--USER__bodyHyphens)!important;-ms-hyphens:var(--USER__bodyHyphens)!important;-epub-hyphens:var(--USER__bodyHyphens)!important;hyphens:var(--USER__bodyHyphens)!important}:root[style*=readium-advanced-on][style*=--USER__bodyHyphens] body,:root[style*=readium-advanced-on][style*=--USER__bodyHyphens] p,:root[style*=readium-advanced-on][style*=--USER__bodyHyphens] li,:root[style*=readium-advanced-on][style*=--USER__bodyHyphens] div,:root[style*=readium-advanced-on][style*=--USER__bodyHyphens] dd{-webkit-hyphens:inherit;-moz-hyphens:inherit;-ms-hyphens:inherit;-epub-hyphens:inherit;hyphens:inherit}:root[style*=readium-font-on][style*=--USER__fontFamily]{font-family:var(--USER__fontFamily)!important}:root[style*=readium-font-on][style*=--USER__fontFamily] body,:root[style*=readium-font-on][style*=--USER__fontFamily] p,:root[style*=readium-font-on][style*=--USER__fontFamily] li,:root[style*=readium-font-on][style*=--USER__fontFamily] div,:root[style*=readium-font-on][style*=--USER__fontFamily] dt,:root[style*=readium-font-on][style*=--USER__fontFamily] dd{font-family:inherit!important}:root[style*=readium-font-on][style*=--USER__fontFamily] i:not([lang]),:root[style*=readium-font-on][style*=--USER__fontFamily] i:not([xml\\:lang]),:root[style*=readium-font-on][style*=--USER__fontFamily] em:not([lang]),:root[style*=readium-font-on][style*=--USER__fontFamily] em:not([xml\\:lang]),:root[style*=readium-font-on][style*=--USER__fontFamily] cite:not([lang]),:root[style*=readium-font-on][style*=--USER__fontFamily] cite:not([xml\\:lang]),:root[style*=readium-font-on][style*=--USER__fontFamily] b:not([lang]),:root[style*=readium-font-on][style*=--USER__fontFamily] b:not([xml\\:lang]),:root[style*=readium-font-on][style*=--USER__fontFamily] strong:not([lang]),:root[style*=readium-font-on][style*=--USER__fontFamily] strong:not([xml\\:lang]),:root[style*=readium-font-on][style*=--USER__fontFamily] span:not([lang]),:root[style*=readium-font-on][style*=--USER__fontFamily] span:not([xml\\:lang]){font-family:inherit!important}:root[style*=readium-font-on][style*=AccessibleDfA]{font-family:AccessibleDfA,Verdana,Tahoma,Trebuchet MS,sans-serif!important;--RS__lineHeightCompensation:1.167}:root[style*=readium-font-on][style*="IA Writer Duospace"]{font-family:IA Writer Duospace,Menlo,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier,monospace!important;--RS__lineHeightCompensation:1.167}:root[style*=readium-font-on][style*=readium-a11y-on]{font-family:var(--USER__fontFamily)!important;--RS__lineHeightCompensation:1.167}:root[style*=readium-font-on][style*=AccessibleDfA],:root[style*=readium-font-on][style*="IA Writer Duospace"],:root[style*=readium-font-on][style*=readium-a11y-on]{font-style:normal!important;font-weight:400!important}:root[style*=readium-font-on][style*=AccessibleDfA] *:not(code):not(var):not(kbd):not(samp),:root[style*=readium-font-on][style*="IA Writer Duospace"] *:not(code):not(var):not(kbd):not(samp),:root[style*=readium-font-on][style*=readium-a11y-on] *:not(code):not(var):not(kbd):not(samp){font-family:inherit!important;font-style:inherit!important;font-weight:inherit!important}:root[style*=readium-font-on][style*=AccessibleDfA] *,:root[style*=readium-font-on][style*="IA Writer Duospace"] *,:root[style*=readium-font-on][style*=readium-a11y-on] *{text-decoration:none!important;font-variant-caps:normal!important;font-variant-numeric:normal!important;font-variant-position:normal!important}:root[style*=readium-font-on][style*=AccessibleDfA] sup,:root[style*=readium-font-on][style*="IA Writer Duospace"] sup,:root[style*=readium-font-on][style*=readium-a11y-on] sup,:root[style*=readium-font-on][style*=AccessibleDfA] sub,:root[style*=readium-font-on][style*="IA Writer Duospace"] sub,:root[style*=readium-font-on][style*=readium-a11y-on] sub{font-size:1rem!important;vertical-align:baseline!important}:root[style*=--USER__fontSize]{font-size:var(--USER__fontSize)!important}:root[style*=readium-advanced-on][style*=--USER__lineHeight]{line-height:var(--USER__lineHeight)!important}:root[style*=readium-advanced-on][style*=--USER__lineHeight] body,:root[style*=readium-advanced-on][style*=--USER__lineHeight] p,:root[style*=readium-advanced-on][style*=--USER__lineHeight] li,:root[style*=readium-advanced-on][style*=--USER__lineHeight] div{line-height:inherit}:root[style*=readium-advanced-on][style*=--USER__paraSpacing] p{margin-top:var(--USER__paraSpacing)!important;margin-bottom:var(--USER__paraSpacing)!important}:root[style*=readium-advanced-on][style*=--USER__paraIndent] p{text-indent:var(--USER__paraIndent)!important}:root[style*=readium-advanced-on][style*=--USER__paraIndent] p *,:root[style*=readium-advanced-on][style*=--USER__paraIndent] p:first-letter{text-indent:0!important}:root[style*=readium-advanced-on][style*=--USER__wordSpacing] h1,:root[style*=readium-advanced-on][style*=--USER__wordSpacing] h2,:root[style*=readium-advanced-on][style*=--USER__wordSpacing] h3,:root[style*=readium-advanced-on][style*=--USER__wordSpacing] h4,:root[style*=readium-advanced-on][style*=--USER__wordSpacing] h5,:root[style*=readium-advanced-on][style*=--USER__wordSpacing] h6,:root[style*=readium-advanced-on][style*=--USER__wordSpacing] p,:root[style*=readium-advanced-on][style*=--USER__wordSpacing] li,:root[style*=readium-advanced-on][style*=--USER__wordSpacing] div{word-spacing:var(--USER__wordSpacing)}:root[style*=readium-advanced-on][style*=--USER__letterSpacing] h1,:root[style*=readium-advanced-on][style*=--USER__letterSpacing] h2,:root[style*=readium-advanced-on][style*=--USER__letterSpacing] h3,:root[style*=readium-advanced-on][style*=--USER__letterSpacing] h4,:root[style*=readium-advanced-on][style*=--USER__letterSpacing] h5,:root[style*=readium-advanced-on][style*=--USER__letterSpacing] h6,:root[style*=readium-advanced-on][style*=--USER__letterSpacing] p,:root[style*=readium-advanced-on][style*=--USER__letterSpacing] li,:root[style*=readium-advanced-on][style*=--USER__letterSpacing] div{letter-spacing:var(--USER__letterSpacing);font-variant:none}:root[style*=readium-advanced-on]{--USER__typeScale:1.2}:root[style*=readium-advanced-on] p,:root[style*=readium-advanced-on] li,:root[style*=readium-advanced-on] div,:root[style*=readium-advanced-on] pre,:root[style*=readium-advanced-on] dd{font-size:1rem!important}:root[style*=readium-advanced-on] h1{font-size:1.75rem!important;font-size:calc(((1rem * var(--USER__typeScale)) * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-advanced-on] h2{font-size:1.5rem!important;font-size:calc((1rem * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-advanced-on] h3{font-size:1.25rem!important;font-size:calc(1rem * var(--USER__typeScale))!important}:root[style*=readium-advanced-on] h4,:root[style*=readium-advanced-on] h5,:root[style*=readium-advanced-on] h6{font-size:1rem!important}:root[style*=readium-advanced-on] small{font-size:smaller!important}:root[style*=readium-advanced-on] sub,:root[style*=readium-advanced-on] sup{font-size:67.5%!important}:root[style*=readium-advanced-on][style*=--USER__typeScale] h1{font-size:calc(((1rem * var(--USER__typeScale)) * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-advanced-on][style*=--USER__typeScale] h2{font-size:calc((1rem * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-advanced-on][style*=--USER__typeScale] h3{font-size:calc(1rem * var(--USER__typeScale))!important}
2
- `,ii=`@namespace url(http://www.w3.org/1999/xhtml);@namespace epub url(http://www.idpf.org/2007/ops);@namespace m url(http://www.w3.org/1998/Math/MathML/);@namespace svg url(http://www.w3.org/2000/svg);@-ms-viewport{width:device-width}@viewport{width:device-width;zoom:1}:root{--RS__oldStyleTf:"Iowan Old Style", "Sitka Text", palatino, "Book Antiqua", serif;--RS__modernTf:athelas, constantia, georgia, serif;--RS__sansTf:-apple-system, system-ui, blinkmacsystemfont, "Segoe UI", roboto, "Helvetica Neue", arial, sans-serif;--RS__humanistTf:seravek, calibri, roboto, arial, sans-serif;--RS__monospaceTf:"Andale Mono", consolas, monospace;--RS__baseFontFamily:var(--RS__oldStyleTf);--RS__lineHeightCompensation:1;--RS__baseLineHeight:calc((1em + (2ex - 1ch) - ((1rem - 16px) * .1667)) * var(--RS__lineHeightCompensation))}html{font-family:var(--RS__baseFontFamily);line-height:1.6;line-height:var(--RS__baseLineHeight);text-rendering:optimizelegibility}h1,h2,h3{line-height:normal}:lang(ja),:lang(zh),:lang(ko){word-wrap:break-word;-webkit-line-break:strict;-epub-line-break:strict;line-break:strict}math{font-family:"Latin Modern Math","STIX Two Math","XITS Math","STIX Math","Libertinus Math","TeX Gyre Termes Math","TeX Gyre Bonum Math",TeX Gyre Schola,"DejaVu Math TeX Gyre","TeX Gyre Pagella Math","Asana Math","Cambria Math","Lucida Bright Math","Minion Math",STIXGeneral,STIXSizeOneSym,Symbol,Times New Roman,serif}:lang(am){--RS__baseFontFamily:kefa, nyala, roboto, noto, "Noto Sans Ethiopic", serif;--RS__lineHeightCompensation:1.167}:lang(ar){--RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif}:lang(bn){--RS__baseFontFamily:"Kohinoor Bangla", "Bangla Sangam MN", vrinda, roboto, noto, "Noto Sans Bengali", sans-serif;--RS__lineHeightCompensation:1.067}:lang(bo){--RS__baseFontFamily:kailasa, "Microsoft Himalaya", roboto, noto, "Noto Sans Tibetan", sans-serif}:lang(chr){--RS__baseFontFamily:"Plantagenet Cherokee", roboto, noto, "Noto Sans Cherokee";--RS__lineHeightCompensation:1.167}:lang(fa){--RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif}:lang(gu){--RS__baseFontFamily:"Gujarati Sangam MN", "Nirmala UI", shruti, roboto, noto, "Noto Sans Gujarati", sans-serif;--RS__lineHeightCompensation:1.167}:lang(he){--RS__baseFontFamily:"New Peninim MT", "Arial Hebrew", gisha, "Times New Roman", roboto, noto, "Noto Sans Hebrew" sans-serif;--RS__lineHeightCompensation:1.1}:lang(hi){--RS__baseFontFamily:"Kohinoor Devanagari", "Devanagari Sangam MN", kokila, "Nirmala UI", roboto, noto, "Noto Sans Devanagari", sans-serif;--RS__lineHeightCompensation:1.1}:lang(hy){--RS__baseFontFamily:mshtakan, sylfaen, roboto, noto, "Noto Serif Armenian", serif}:lang(iu){--RS__baseFontFamily:"Euphemia UCAS", euphemia, roboto, noto, "Noto Sans Canadian Aboriginal", sans-serif}:lang(ja){--RS__baseFontFamily:yugothic, "Hiragino Maru Gothic ProN", "Hiragino Sans", "Yu Gothic UI", "Meiryo UI", "MS Gothic", roboto, noto, "Noto Sans CJK JP", sans-serif;--RS__lineHeightCompensation:1.167;--RS__serif-ja:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDPMincho", "Yu Mincho", "MS P明朝", "MS PMincho", serif;--RS__sans-serif-ja:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDPGothic", "Yu Gothic", "MS Pゴシック", "MS PGothic", sans-serif;--RS__serif-ja-v:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDMincho", "Yu Mincho", "MS明朝", "MS Mincho", serif;--RS__sans-serif-ja-v:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDGothic", "Yu Gothic", "MSゴシック", "MS Gothic", sans-serif}:lang(km){--RS__baseFontFamily:"Khmer Sangam MN", "Leelawadee UI", "Khmer UI", roboto, noto, "Noto Sans Khmer", sans-serif;--RS__lineHeightCompensation:1.067}:lang(kn){--RS__baseFontFamily:"Kannada Sangam MN", "Nirmala UI", tunga, roboto, noto, "Noto Sans Kannada", sans-serif;--RS__lineHeightCompensation:1.1}:lang(ko){--RS__baseFontFamily:"Nanum Gothic", "Apple SD Gothic Neo", "Malgun Gothic", roboto, noto, "Noto Sans CJK KR", sans-serif;--RS__lineHeightCompensation:1.167}:lang(lo){--RS__baseFontFamily:"Lao Sangam MN", "Leelawadee UI", "Lao UI", roboto, noto, "Noto Sans Lao", sans-serif}:lang(ml){--RS__baseFontFamily:"Malayalam Sangam MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Malayalam", sans-serif;--RS__lineHeightCompensation:1.067}:lang(or){--RS__baseFontFamily:"Oriya Sangam MN", "Nirmala UI", kalinga, roboto, noto, "Noto Sans Oriya", sans-serif;--RS__lineHeightCompensation:1.167}:lang(pa){--RS__baseFontFamily:"Gurmukhi MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Gurmukhi", sans-serif;--RS__lineHeightCompensation:1.1}:lang(si){--RS__baseFontFamily:"Sinhala Sangam MN", "Nirmala UI", "Iskoola Pota", roboto, noto, "Noto Sans Sinhala", sans-serif;--RS__lineHeightCompensation:1.167}:lang(ta){--RS__baseFontFamily:"Tamil Sangam MN", "Nirmala UI", latha, roboto, noto, "Noto Sans Tamil", sans-serif;--RS__lineHeightCompensation:1.067}:lang(te){--RS__baseFontFamily:"Kohinoor Telugu", "Telugu Sangam MN", "Nirmala UI", gautami, roboto, noto, "Noto Sans Telugu", sans-serif}:lang(th){--RS__baseFontFamily:"Thonburi", "Leelawadee UI", "Cordia New", roboto, noto, "Noto Sans Thai", sans-serif;--RS__lineHeightCompensation:1.067}:lang(zh){--RS__baseFontFamily:"方体", "PingFang SC", "黑体", "Heiti SC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK SC", sans-serif;--RS__lineHeightCompensation:1.167}:lang(zh-Hant),:lang(zh-TW){--RS__baseFontFamily:"方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;--RS__lineHeightCompensation:1.167}:lang(zh-HK){--RS__baseFontFamily:"方體", "PingFang HK", "方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;--RS__lineHeightCompensation:1.167}:root{--RS__backgroundColor:#FFFFFF;--RS__textColor:#121212;--RS__selectionBackgroundColor:#b4d8fe;--RS__selectionTextColor:inherit}:root{color:var(--RS__textColor)!important;background-color:var(--RS__backgroundColor)!important}::-moz-selection{color:var(--RS__selectionTextColor);background-color:var(--RS__selectionBackgroundColor)}::selection{color:var(--RS__selectionTextColor);background-color:var(--RS__selectionBackgroundColor)}@font-face{font-family:AccessibleDfA;font-style:normal;font-weight:400;src:local("AccessibleDfA"),url(./assets/AccessibleDfA-Regular.woff2) format("woff2"),url(./assets/AccessibleDfA-Regular.woff) format("woff")}@font-face{font-family:AccessibleDfA;font-style:normal;font-weight:700;src:local("AccessibleDfA"),url(./assets/AccessibleDfA-Bold.woff2) format("woff2")}@font-face{font-family:AccessibleDfA;font-style:italic;font-weight:400;src:local("AccessibleDfA"),url(./assets/AccessibleDfA-Italic.woff2) format("woff2")}@font-face{font-family:IA Writer Duospace;font-style:normal;font-weight:400;src:local("iAWriterDuospace-Regular"),url(./assets/iAWriterDuospace-Regular.ttf) format("truetype")}body{widows:2;orphans:2}figcaption,th,td{widows:1;orphans:1}h2,h3,h4,h5,h6,dt,hr,caption{-webkit-column-break-after:avoid;page-break-after:avoid;break-after:avoid}h1,h2,h3,h4,h5,h6,dt,figure,tr{-webkit-column-break-inside:avoid;page-break-inside:avoid;break-inside:avoid}body{-webkit-hyphenate-character:"-";-moz-hyphenate-character:"-";-ms-hyphenate-character:"-";hyphenate-character:"-";-webkit-hyphenate-limit-lines:3;-ms-hyphenate-limit-lines:3;hyphenate-limit-lines:3}h1,h2,h3,h4,h5,h6,dt,figcaption,pre,caption,address,center,code,var{-ms-hyphens:none;-moz-hyphens:none;-webkit-hyphens:none;-epub-hyphens:none;hyphens:none}body{font-variant-numeric:oldstyle-nums proportional-nums}:lang(ja) body,:lang(zh) body,:lang(ko) body{font-variant-numeric:lining-nums proportional-nums}h1,h2,h3,h4,h5,h6,dt{font-variant-numeric:lining-nums proportional-nums}table{font-variant-numeric:lining-nums tabular-nums}code,var{font-variant-ligatures:none;font-variant-numeric:lining-nums tabular-nums slashed-zero}rt{font-variant-east-asian:ruby}:lang(ar){font-variant-ligatures:common-ligatures}:lang(ko){font-kerning:normal}hr{color:inherit;border-color:currentcolor}table,th,td{border-color:currentcolor}figure,blockquote{margin:1em 5%}ul,ol{padding-left:5%}dd{margin-left:5%}pre{white-space:pre-wrap;-ms-tab-size:2;-moz-tab-size:2;-webkit-tab-size:2;tab-size:2}abbr[title],acronym[title]{text-decoration:dotted underline}nobr wbr{white-space:normal}ruby>rt,ruby>rp{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}*:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)),*:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)),*:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)),:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) cite,:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) dfn,:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) em,:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) i,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) cite,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) dfn,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) em,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) i,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) cite,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) dfn,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) em,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) i{font-style:normal}:lang(ja) a,:lang(zh) a,:lang(ko) a{text-decoration:none}:root{--RS__maxMediaWidth:100%;--RS__maxMediaHeight:95vh;--RS__boxSizingMedia:border-box;--RS__boxSizingTable:border-box}html{-webkit-line-box-contain:block glyphs replaced}:lang(ja){-webkit-line-box-contain:block inline replaced}a,h1,h2,h3,h4,h5,h6{word-wrap:break-word}div{max-width:var(--RS__maxMediaWidth)}img,svg,video{object-fit:contain;width:auto;height:auto;max-width:var(--RS__maxMediaWidth);max-height:var(--RS__maxMediaHeight)!important;box-sizing:var(--RS__boxSizingMedia);-webkit-column-break-inside:avoid;page-break-inside:avoid;break-inside:avoid}audio{max-width:100%;-webkit-column-break-inside:avoid;page-break-inside:avoid;break-inside:avoid}table{max-width:var(--RS__maxMediaWidth);box-sizing:var(--RS__boxSizingTable)}
3
- `,ni=`@namespace url(http://www.w3.org/1999/xhtml);@namespace epub url(http://www.idpf.org/2007/ops);@namespace m url(http://www.w3.org/1998/Math/MathML/);@namespace svg url(http://www.w3.org/2000/svg);:root{--RS__compFontFamily:var(--RS__baseFontFamily);--RS__codeFontFamily:var(--RS__monospaceTf);--RS__typeScale:1.125;--RS__baseFontSize:100%;--RS__flowSpacing:1.5rem;--RS__paraSpacing:0;--RS__paraIndent:1em;--RS__linkColor:#0000EE;--RS__visitedColor:#551A8B;--RS__primaryColor:;--RS__secondaryColor:}body{font-size:var(--RS__baseFontSize)}h1,h2,h3,h4,h5,h6{font-family:var(--RS__compFontFamily)}blockquote,figure,p,pre,aside,footer,form,hr{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing)}p{margin-top:var(--RS__paraSpacing);margin-bottom:var(--RS__paraSpacing);text-indent:var(--RS__paraIndent)}h1+p,h2+p,h3+p,h4+p,h5+p,h6+p,hr+p{text-indent:0}pre{font-family:var(--RS__codeFontFamily)}code,kbd,samp,tt{font-family:var(--RS__codeFontFamily)}sub,sup{position:relative;font-size:67.5%;line-height:1}sub{bottom:-.2ex}sup{bottom:0}:link{color:var(--RS__linkColor)}:visited{color:var(--RS__visitedColor)}h1{margin-top:calc(var(--RS__flowSpacing) * 2);margin-bottom:calc(var(--RS__flowSpacing) * 2);font-size:calc(((1em * var(--RS__typeScale)) * var(--RS__typeScale)) * var(--RS__typeScale))}h2{margin-top:calc(var(--RS__flowSpacing) * 2);margin-bottom:var(--RS__flowSpacing);font-size:calc((1em * var(--RS__typeScale)) * var(--RS__typeScale))}h3{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing);font-size:calc(1em * var(--RS__typeScale))}h4{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing);font-size:1em}h5{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing);font-size:1em;font-variant:small-caps}h6{margin-top:var(--RS__flowSpacing);margin-bottom:0;font-size:1em;text-transform:lowercase;font-variant:small-caps}dl,ol,ul{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing)}table{margin:var(--RS__flowSpacing) 0;border:1px solid currentcolor;border-collapse:collapse;empty-cells:show}thead,tbody,tfoot,table>tr{vertical-align:top}th{text-align:left}th,td{padding:4px;border:1px solid currentcolor}
4
- `,k=(i,A)=>URL.createObjectURL(new Blob([i],{type:A})),mt=i=>i.replace(/\/\/.*/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\n/g,"").replace(/\s+/g," "),VA=i=>i.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g,"").replace(/ {2,}/g," ").replace(/url\((?!(https?:)?\/\/)("?)\/([^\)]+)/g,`url($2${window.location.origin}/$3`),DA=(i,A)=>{const t=i.createElement("script");return t.dataset.readium="true",t.src=A.startsWith("blob:")?A:k(A,"text/javascript"),t},HA=(i,A)=>{const t=i.createElement("link");return t.dataset.readium="true",t.rel="stylesheet",t.type="text/css",t.href=A.startsWith("blob:")?A:k(A,"text/css"),t},GA=new Map,tA=(i,A)=>{if(GA.has(i))return GA.get(i);const t=A();return GA.set(i,t),t},ri=i=>DA(i,tA("css-selector-generator",()=>k('!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports._readium_cssSelectorGenerator=e():t._readium_cssSelectorGenerator=e()}(self,(()=>(()=>{"use strict";var t,e,n={d:(t,e)=>{for(var o in e)n.o(e,o)&&!n.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:e[o]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},o={};function r(t){return t&&t instanceof Element}function i(t="unknown problem",...e){console.warn(`CssSelectorGenerator: ${t}`,...e)}n.r(o),n.d(o,{default:()=>z,getCssSelector:()=>U}),function(t){t.NONE="none",t.DESCENDANT="descendant",t.CHILD="child"}(t||(t={})),function(t){t.id="id",t.class="class",t.tag="tag",t.attribute="attribute",t.nthchild="nthchild",t.nthoftype="nthoftype"}(e||(e={}));const c={selectors:[e.id,e.class,e.tag,e.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY};function u(t){return t instanceof RegExp}function s(t){return["string","function"].includes(typeof t)||u(t)}function l(t){return Array.isArray(t)?t.filter(s):[]}function a(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return function(t){return t instanceof Node}(t)&&e.includes(t.nodeType)}function f(t,e){if(a(t))return t.contains(e)||i("element root mismatch","Provided root does not contain the element. This will most likely result in producing a fallback selector using element\'s real root node. If you plan to use the selector using provided root (e.g. `root.querySelector`), it will nto work as intended."),t;const n=e.getRootNode({composed:!1});return a(n)?(n!==document&&i("shadow root inferred","You did not provide a root and the element is a child of Shadow DOM. This will produce a selector using ShadowRoot as a root. If you plan to use the selector using document as a root (e.g. `document.querySelector`), it will not work as intended."),n):e.ownerDocument.querySelector(":root")}function d(t){return"number"==typeof t?t:Number.POSITIVE_INFINITY}function m(t=[]){const[e=[],...n]=t;return 0===n.length?e:n.reduce(((t,e)=>t.filter((t=>e.includes(t)))),e)}function p(t){return[].concat(...t)}function h(t){const e=t.map((t=>{if(u(t))return e=>t.test(e);if("function"==typeof t)return e=>{const n=t(e);return"boolean"!=typeof n?(i("pattern matcher function invalid","Provided pattern matching function does not return boolean. It\'s result will be ignored.",t),!1):n};if("string"==typeof t){const e=new RegExp("^"+t.replace(/[|\\\\{}()[\\]^$+?.]/g,"\\\\$&").replace(/\\*/g,".+")+"$");return t=>e.test(t)}return i("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1}));return t=>e.some((e=>e(t)))}function g(t,e,n){const o=Array.from(f(n,t[0]).querySelectorAll(e));return o.length===t.length&&t.every((t=>o.includes(t)))}function y(t,e){e=null!=e?e:function(t){return t.ownerDocument.querySelector(":root")}(t);const n=[];let o=t;for(;r(o)&&o!==e;)n.push(o),o=o.parentElement;return n}function b(t,e){return m(t.map((t=>y(t,e))))}const N={[t.NONE]:{type:t.NONE,value:""},[t.DESCENDANT]:{type:t.DESCENDANT,value:" > "},[t.CHILD]:{type:t.CHILD,value:" "}},S=new RegExp(["^$","\\\\s"].join("|")),E=new RegExp(["^$"].join("|")),w=[e.nthoftype,e.tag,e.id,e.class,e.attribute,e.nthchild],v=h(["class","id","ng-*"]);function C({nodeName:t}){return`[${t}]`}function O({nodeName:t,nodeValue:e}){return`[${t}=\'${L(e)}\']`}function T(t){const e=Array.from(t.attributes).filter((e=>function({nodeName:t},e){const n=e.tagName.toLowerCase();return!(["input","option"].includes(n)&&"value"===t||v(t))}(e,t)));return[...e.map(C),...e.map(O)]}function I(t){return(t.getAttribute("class")||"").trim().split(/\\s+/).filter((t=>!E.test(t))).map((t=>`.${L(t)}`))}function x(t){const e=t.getAttribute("id")||"",n=`#${L(e)}`,o=t.getRootNode({composed:!1});return!S.test(e)&&g([t],n,o)?[n]:[]}function j(t){const e=t.parentNode;if(e){const n=Array.from(e.childNodes).filter(r).indexOf(t);if(n>-1)return[`:nth-child(${n+1})`]}return[]}function A(t){return[L(t.tagName.toLowerCase())]}function D(t){const e=[...new Set(p(t.map(A)))];return 0===e.length||e.length>1?[]:[e[0]]}function $(t){const e=D([t])[0],n=t.parentElement;if(n){const o=Array.from(n.children).filter((t=>t.tagName.toLowerCase()===e)),r=o.indexOf(t);if(r>-1)return[`${e}:nth-of-type(${r+1})`]}return[]}function R(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){const n=[];let o=0,r=k(1);for(;r.length<=t.length&&o<e;)o+=1,n.push(r.map((e=>t[e]))),r=P(r,t.length-1);return n}function P(t=[],e=0){const n=t.length;if(0===n)return[];const o=[...t];o[n-1]+=1;for(let t=n-1;t>=0;t--)if(o[t]>e){if(0===t)return k(n+1);o[t-1]++,o[t]=o[t-1]+1}return o[n-1]>e?k(n+1):o}function k(t=1){return Array.from(Array(t).keys())}const _=":".charCodeAt(0).toString(16).toUpperCase(),M=/[ !"#$%&\'()\\[\\]{|}<>*+,./;=?@^`~\\\\]/;function L(t=""){var e,n;return null!==(n=null===(e=null===CSS||void 0===CSS?void 0:CSS.escape)||void 0===e?void 0:e.call(CSS,t))&&void 0!==n?n:function(t=""){return t.split("").map((t=>":"===t?`\\\\${_} `:M.test(t)?`\\\\${t}`:escape(t).replace(/%/g,"\\\\"))).join("")}(t)}const q={tag:D,id:function(t){return 0===t.length||t.length>1?[]:x(t[0])},class:function(t){return m(t.map(I))},attribute:function(t){return m(t.map(T))},nthchild:function(t){return m(t.map(j))},nthoftype:function(t){return m(t.map($))}},F={tag:A,id:x,class:I,attribute:T,nthchild:j,nthoftype:$};function V(t){return t.includes(e.tag)||t.includes(e.nthoftype)?[...t]:[...t,e.tag]}function Y(t={}){const n=[...w];return t[e.tag]&&t[e.nthoftype]&&n.splice(n.indexOf(e.tag),1),n.map((e=>{return(o=t)[n=e]?o[n].join(""):"";var n,o})).join("")}function B(t,e,n="",o){const r=function(t,e){return""===e?t:function(t,e){return[...t.map((t=>e+" "+t)),...t.map((t=>e+" > "+t))]}(t,e)}(function(t,e,n){const o=function(t,e){const{blacklist:n,whitelist:o,combineWithinSelector:r,maxCombinations:i}=e,c=h(n),u=h(o);return function(t){const{selectors:e,includeTag:n}=t,o=[].concat(e);return n&&!o.includes("tag")&&o.push("tag"),o}(e).reduce(((e,n)=>{const o=function(t,e){var n;return(null!==(n=q[e])&&void 0!==n?n:()=>[])(t)}(t,n),s=function(t=[],e,n){return t.filter((t=>n(t)||!e(t)))}(o,c,u),l=function(t=[],e){return t.sort(((t,n)=>{const o=e(t),r=e(n);return o&&!r?-1:!o&&r?1:0}))}(s,u);return e[n]=r?R(l,{maxResults:i}):l.map((t=>[t])),e}),{})}(t,n),r=function(t,e){return function(t){const{selectors:e,combineBetweenSelectors:n,includeTag:o,maxCandidates:r}=t,i=n?R(e,{maxResults:r}):e.map((t=>[t]));return o?i.map(V):i}(e).map((e=>function(t,e){const n={};return t.forEach((t=>{const o=e[t];o.length>0&&(n[t]=o)})),function(t={}){let e=[];return Object.entries(t).forEach((([t,n])=>{e=n.flatMap((n=>0===e.length?[{[t]:n}]:e.map((e=>Object.assign(Object.assign({},e),{[t]:n})))))})),e}(n).map(Y)}(e,t))).filter((t=>t.length>0))}(o,n),i=p(r);return[...new Set(i)]}(t,o.root,o),n);for(const e of r)if(g(t,e,o.root))return e;return null}function G(t){return{value:t,include:!1}}function W({selectors:t,operator:n}){let o=[...w];t[e.tag]&&t[e.nthoftype]&&(o=o.filter((t=>t!==e.tag)));let r="";return o.forEach((e=>{(t[e]||[]).forEach((({value:t,include:e})=>{e&&(r+=t)}))})),n.value+r}function H(n){return[":root",...y(n).reverse().map((n=>{const o=function(e,n,o=t.NONE){const r={};return n.forEach((t=>{Reflect.set(r,t,function(t,e){return F[e](t)}(e,t).map(G))})),{element:e,operator:N[o],selectors:r}}(n,[e.nthchild],t.DESCENDANT);return o.selectors.nthchild.forEach((t=>{t.include=!0})),o})).map(W)].join("")}function U(t,n={}){const o=function(t){const e=(Array.isArray(t)?t:[t]).filter(r);return[...new Set(e)]}(t),i=function(t,n={}){const o=Object.assign(Object.assign({},c),n);return{selectors:(r=o.selectors,Array.isArray(r)?r.filter((t=>{return n=e,o=t,Object.values(n).includes(o);var n,o})):[]),whitelist:l(o.whitelist),blacklist:l(o.blacklist),root:f(o.root,t),combineWithinSelector:!!o.combineWithinSelector,combineBetweenSelectors:!!o.combineBetweenSelectors,includeTag:!!o.includeTag,maxCombinations:d(o.maxCombinations),maxCandidates:d(o.maxCandidates)};var r}(o[0],n);let u="",s=i.root;function a(){return function(t,e,n="",o){if(0===t.length)return null;const r=[t.length>1?t:[],...b(t,e).map((t=>[t]))];for(const t of r){const e=B(t,0,n,o);if(e)return{foundElements:t,selector:e}}return null}(o,s,u,i)}let m=a();for(;m;){const{foundElements:t,selector:e}=m;if(g(o,e,i.root))return e;s=t[0],u=e,m=a()}return o.length>1?o.map((t=>U(t,i))).join(", "):function(t){return t.map(H).join(", ")}(o)}const z=U;return o})()));',"text/javascript"))),si=i=>DA(i,tA("JS-Before",()=>k(mt(`
1
+ (function(E,V){typeof exports=="object"&&typeof module<"u"?V(exports):typeof define=="function"&&define.amd?define(["exports"],V):(E=typeof globalThis<"u"?globalThis:E||self,V(E.navigator={}))})(this,function(E){"use strict";const V=class Bt{constructor(t){if(typeof t=="string"){if(!Bt.VALID_MODES.has(t.toLowerCase()))return;this.value=t.toLowerCase()}else{const e=t.filter(A=>Bt.VALID_MODES.has(A.toLowerCase()));if(e.length===0)return;this.value=Array.from(new Set(e))}}static deserialize(t){if(!t)return;if(typeof t=="string")return new Bt(t);if(!Array.isArray(t))return;const e=t.filter(A=>A?Bt.VALID_MODES.has(A.toLowerCase()):!1);if(e.length!==0)return new Bt(e)}serialize(){return this.value}};V.VALID_MODES=new Set(["auditory","tactile","textual","visual"]),V.AUDITORY=new V("auditory"),V.TACTILE=new V("tactile"),V.TEXTUAL=new V("textual"),V.VISUAL=new V("visual");var p=(n=>(n.fixed="fixed",n.reflowable="reflowable",n))(p||{}),nt=(n=>(n.auto="auto",n.landscape="landscape",n.portrait="portrait",n))(nt||{}),O=(n=>(n.left="left",n.right="right",n.center="center",n))(O||{}),zt=(n=>(n.auto="auto",n.both="both",n.none="none",n.landscape="landscape",n))(zt||{});let Y=class fe{constructor(t){this.otherProperties=t}static deserialize(t){if(t)return new fe(t)}serialize(){return this.otherProperties}add(t){const e=Object.assign({},this.otherProperties);for(const A in t)e[A]=t[A];return new fe(e)}};Y.prototype.getContains=function(){return new Set(this.otherProperties.contains||[])},Y.prototype.getLayout=function(){return this.otherProperties.layout};class d{constructor(t){let e,A,i=t.mediaType.replace(/\s/g,"").split(";");const r=i[0].split("/");if(r.length===2){if(e=r[0].toLowerCase().trim(),A=r[1].toLowerCase().trim(),e.length===0||A.length===0)throw new Error("Invalid media type")}else throw new Error("Invalid media type");const s={};for(let g=1;g<i.length;g++){const m=i[g].split("=");if(m.length===2){const M=m[0].toLocaleLowerCase(),B=M==="charset"?m[1].toUpperCase():m[1];s[M]=B}}const o={},a=Object.keys(s);a.sort((g,m)=>g.localeCompare(m)),a.forEach(g=>o[g]=s[g]);let l="";for(const g in o){const m=o[g];l+=`;${g}=${m}`}const h=`${e}/${A}${l}`,c=o.encoding;this.string=h,this.type=e,this.subtype=A,this.parameters=o,this.encoding=c,this.name=t.name,this.fileExtension=t.fileExtension}static parse(t){return new d(t)}get structuredSyntaxSuffix(){const t=this.subtype.split("+");return t.length>1?`+${t[t.length-1]}`:void 0}get charset(){return this.parameters.charset}contains(t){const e=typeof t=="string"?d.parse({mediaType:t}):t;if(!((this.type==="*"||this.type===e.type)&&(this.subtype==="*"||this.subtype===e.subtype)))return!1;const A=new Set(Object.entries(this.parameters).map(([r,s])=>`${r}=${s}`)),i=new Set(Object.entries(e.parameters).map(([r,s])=>`${r}=${s}`));for(const r of Array.from(A.values()))if(!i.has(r))return!1;return!0}matches(t){const e=typeof t=="string"?d.parse({mediaType:t}):t;return this.contains(e)||e.contains(this)}matchesAny(...t){for(const e of t)if(this.matches(e))return!0;return!1}equals(t){return this.string===t.string}get isZIP(){return this.matchesAny(d.ZIP,d.LCP_PROTECTED_AUDIOBOOK,d.LCP_PROTECTED_PDF)||this.structuredSyntaxSuffix==="+zip"}get isJSON(){return this.matchesAny(d.JSON)||this.structuredSyntaxSuffix==="+json"}get isOPDS(){return this.matchesAny(d.OPDS1,d.OPDS1_ENTRY,d.OPDS2,d.OPDS2_PUBLICATION,d.OPDS_AUTHENTICATION)||this.structuredSyntaxSuffix==="+json"}get isHTML(){return this.matchesAny(d.HTML,d.XHTML)}get isBitmap(){return this.matchesAny(d.BMP,d.GIF,d.JPEG,d.PNG,d.TIFF,d.WEBP)}get isAudio(){return this.type==="audio"}get isVideo(){return this.type==="video"}get isRWPM(){return this.matchesAny(d.READIUM_AUDIOBOOK_MANIFEST,d.DIVINA_MANIFEST,d.READIUM_WEBPUB_MANIFEST)}get isPublication(){return this.matchesAny(d.READIUM_AUDIOBOOK,d.READIUM_AUDIOBOOK_MANIFEST,d.CBZ,d.DIVINA,d.DIVINA_MANIFEST,d.EPUB,d.LCP_PROTECTED_AUDIOBOOK,d.LCP_PROTECTED_PDF,d.LPF,d.PDF,d.W3C_WPUB_MANIFEST,d.READIUM_WEBPUB,d.READIUM_WEBPUB_MANIFEST,d.ZAB)}static get AAC(){return d.parse({mediaType:"audio/aac",fileExtension:"aac"})}static get ACSM(){return d.parse({mediaType:"application/vnd.adobe.adept+xml",name:"Adobe Content Server Message",fileExtension:"acsm"})}static get AIFF(){return d.parse({mediaType:"audio/aiff",fileExtension:"aiff"})}static get AVI(){return d.parse({mediaType:"video/x-msvideo",fileExtension:"avi"})}static get BINARY(){return d.parse({mediaType:"application/octet-stream"})}static get BMP(){return d.parse({mediaType:"image/bmp",fileExtension:"bmp"})}static get CBZ(){return d.parse({mediaType:"application/vnd.comicbook+zip",name:"Comic Book Archive",fileExtension:"cbz"})}static get CSS(){return d.parse({mediaType:"text/css",fileExtension:"css"})}static get DIVINA(){return d.parse({mediaType:"application/divina+zip",name:"Digital Visual Narratives",fileExtension:"divina"})}static get DIVINA_MANIFEST(){return d.parse({mediaType:"application/divina+json",name:"Digital Visual Narratives",fileExtension:"json"})}static get EPUB(){return d.parse({mediaType:"application/epub+zip",name:"EPUB",fileExtension:"epub"})}static get GIF(){return d.parse({mediaType:"image/gif",fileExtension:"gif"})}static get GZ(){return d.parse({mediaType:"application/gzip",fileExtension:"gz"})}static get HTML(){return d.parse({mediaType:"text/html",fileExtension:"html"})}static get JAVASCRIPT(){return d.parse({mediaType:"text/javascript",fileExtension:"js"})}static get JPEG(){return d.parse({mediaType:"image/jpeg",fileExtension:"jpeg"})}static get JSON(){return d.parse({mediaType:"application/json"})}static get LCP_LICENSE_DOCUMENT(){return d.parse({mediaType:"application/vnd.readium.lcp.license.v1.0+json",name:"LCP License",fileExtension:"lcpl"})}static get LCP_PROTECTED_AUDIOBOOK(){return d.parse({mediaType:"application/audiobook+lcp",name:"LCP Protected Audiobook",fileExtension:"lcpa"})}static get LCP_PROTECTED_PDF(){return d.parse({mediaType:"application/pdf+lcp",name:"LCP Protected PDF",fileExtension:"lcpdf"})}static get LCP_STATUS_DOCUMENT(){return d.parse({mediaType:"application/vnd.readium.license.status.v1.0+json"})}static get LPF(){return d.parse({mediaType:"application/lpf+zip",fileExtension:"lpf"})}static get MP3(){return d.parse({mediaType:"audio/mpeg",fileExtension:"mp3"})}static get MPEG(){return d.parse({mediaType:"video/mpeg",fileExtension:"mpeg"})}static get NCX(){return d.parse({mediaType:"application/x-dtbncx+xml",fileExtension:"ncx"})}static get OGG(){return d.parse({mediaType:"audio/ogg",fileExtension:"oga"})}static get OGV(){return d.parse({mediaType:"video/ogg",fileExtension:"ogv"})}static get OPDS1(){return d.parse({mediaType:"application/atom+xml;profile=opds-catalog"})}static get OPDS1_ENTRY(){return d.parse({mediaType:"application/atom+xml;type=entry;profile=opds-catalog"})}static get OPDS2(){return d.parse({mediaType:"application/opds+json"})}static get OPDS2_PUBLICATION(){return d.parse({mediaType:"application/opds-publication+json"})}static get OPDS_AUTHENTICATION(){return d.parse({mediaType:"application/opds-authentication+json"})}static get OPUS(){return d.parse({mediaType:"audio/opus",fileExtension:"opus"})}static get OTF(){return d.parse({mediaType:"font/otf",fileExtension:"otf"})}static get PDF(){return d.parse({mediaType:"application/pdf",name:"PDF",fileExtension:"pdf"})}static get PNG(){return d.parse({mediaType:"image/png",fileExtension:"png"})}static get READIUM_AUDIOBOOK(){return d.parse({mediaType:"application/audiobook+zip",name:"Readium Audiobook",fileExtension:"audiobook"})}static get READIUM_AUDIOBOOK_MANIFEST(){return d.parse({mediaType:"application/audiobook+json",name:"Readium Audiobook",fileExtension:"json"})}static get READIUM_CONTENT_DOCUMENT(){return d.parse({mediaType:"application/vnd.readium.content+json",name:"Readium Content Document",fileExtension:"json"})}static get READIUM_GUIDED_NAVIGATION_DOCUMENT(){return d.parse({mediaType:"application/guided-navigation+json",name:"Readium Guided Navigation Document",fileExtension:"json"})}static get READIUM_POSITION_LIST(){return d.parse({mediaType:"application/vnd.readium.position-list+json",name:"Readium Position List",fileExtension:"json"})}static get READIUM_WEBPUB(){return d.parse({mediaType:"application/webpub+zip",name:"Readium Web Publication",fileExtension:"webpub"})}static get READIUM_WEBPUB_MANIFEST(){return d.parse({mediaType:"application/webpub+json",name:"Readium Web Publication",fileExtension:"json"})}static get SMIL(){return d.parse({mediaType:"application/smil+xml",fileExtension:"smil"})}static get SVG(){return d.parse({mediaType:"image/svg+xml",fileExtension:"svg"})}static get TEXT(){return d.parse({mediaType:"text/plain",fileExtension:"txt"})}static get TIFF(){return d.parse({mediaType:"image/tiff",fileExtension:"tiff"})}static get TTF(){return d.parse({mediaType:"font/ttf",fileExtension:"ttf"})}static get W3C_WPUB_MANIFEST(){return d.parse({mediaType:"application/x.readium.w3c.wpub+json",name:"Web Publication",fileExtension:"json"})}static get WAV(){return d.parse({mediaType:"audio/wav",fileExtension:"wav"})}static get WEBM_AUDIO(){return d.parse({mediaType:"audio/webm",fileExtension:"webm"})}static get WEBM_VIDEO(){return d.parse({mediaType:"video/webm",fileExtension:"webm"})}static get WEBP(){return d.parse({mediaType:"image/webp",fileExtension:"webp"})}static get WOFF(){return d.parse({mediaType:"font/woff",fileExtension:"woff"})}static get WOFF2(){return d.parse({mediaType:"font/woff2",fileExtension:"woff2"})}static get XHTML(){return d.parse({mediaType:"application/xhtml+xml",fileExtension:"xhtml"})}static get XML(){return d.parse({mediaType:"application/xml",fileExtension:"xml"})}static get ZAB(){return d.parse({mediaType:"application/x.readium.zab+zip",name:"Zipped Audio Book",fileExtension:"zab"})}static get ZIP(){return d.parse({mediaType:"application/zip",fileExtension:"zip"})}}let Ie=class{constructor(t){this.uri=t,this.parameters=this.getParameters(t)}getParameters(t){const e=/\{\??([^}]+)\}/g,A=t.match(e);return A?new Set(A.join(",").replace(e,"$1").split(",").map(i=>i.trim())):new Set}expand(t){const e=i=>i.split(",").map(r=>{const s=t[r];return s?encodeURIComponent(s):""}).join(","),A=i=>"?"+i.split(",").map(r=>{const s=r.split("=")[0],o=t[s];return o?`${s}=${encodeURIComponent(o)}`:""}).join("&");return this.uri.replace(/\{(\??)([^}]+)\}/g,(...i)=>i[1]?A(i[2]):e(i[2]))}};function ii(n){return n&&n instanceof Array?n:void 0}function Fe(n){return n&&typeof n=="string"?[n]:ii(n)}function Ue(n){return typeof n=="string"?new Date(n):void 0}function Yt(n){return isNaN(n)?void 0:n}function P(n){return Yt(n)!==void 0&&Math.sign(n)>=0?n:void 0}function ni(n){const t=new Array;return n.forEach(e=>t.push(e)),t}let G=class XA{constructor(t){this.fragments=t.fragments?t.fragments:new Array,this.progression=t.progression,this.totalProgression=t.totalProgression,this.position=t.position,this.otherLocations=t.otherLocations}static deserialize(t){if(!t)return;const e=Yt(t.progression),A=Yt(t.totalProgression),i=Yt(t.position),r=new Map,s=new Set(["fragment","fragments","progression","totalProgression","position"]);return Object.entries(t).forEach(([o,a])=>{s.has(o)||r.set(o,a)}),new XA({fragments:Fe(t.fragments||t.fragment),progression:e!==void 0&&e>=0&&e<=1?e:void 0,totalProgression:A!==void 0&&A>=0&&A<=1?A:void 0,position:i!==void 0&&i>0?i:void 0,otherLocations:r.size===0?void 0:r})}serialize(){const t={};return this.fragments&&(t.fragments=this.fragments),this.progression!==void 0&&(t.progression=this.progression),this.totalProgression!==void 0&&(t.totalProgression=this.totalProgression),this.position!==void 0&&(t.position=this.position),this.otherLocations&&this.otherLocations.forEach((e,A)=>t[A]=e),t}},ri=class ZA{constructor(t){this.after=t.after,this.before=t.before,this.highlight=t.highlight}static deserialize(t){if(t)return new ZA({after:t.after,before:t.before,highlight:t.highlight})}serialize(){const t={};return this.after!==void 0&&(t.after=this.after),this.before!==void 0&&(t.before=this.before),this.highlight!==void 0&&(t.highlight=this.highlight),t}},Lt=class pe{constructor(t){this.href=t.href,this.type=t.type,this.title=t.title,this.locations=t.locations?t.locations:new G({}),this.text=t.text}static deserialize(t){if(t&&t.href&&t.type)return new pe({href:t.href,type:t.type,title:t.title,locations:G.deserialize(t.locations),text:ri.deserialize(t.text)})}serialize(){const t={href:this.href,type:this.type};return this.title!==void 0&&(t.title=this.title),this.locations&&(t.locations=this.locations.serialize()),this.text&&(t.text=this.text.serialize()),t}copyWithLocations(t){return new pe({href:this.href,type:this.type,title:this.title,text:this.text,locations:new G({...this.locations,...t})})}},wt=class Jt{constructor(t){this.href=t.href,this.templated=t.templated,this.type=t.type,this.title=t.title,this.rels=t.rels,this.properties=t.properties,this.height=t.height,this.width=t.width,this.duration=t.duration,this.bitrate=t.bitrate,this.languages=t.languages,this.alternates=t.alternates,this.children=t.children}static deserialize(t){if(!(!t||typeof t.href!="string"))return new Jt({href:t.href,templated:t.templated,type:t.type,title:t.title,rels:t.rel?t.rel instanceof Array?new Set(t.rel):new Set([t.rel]):void 0,properties:Y.deserialize(t.properties),height:P(t.height),width:P(t.width),duration:P(t.duration),bitrate:P(t.bitrate),languages:Fe(t.language),alternates:ye.deserialize(t.alternate),children:ye.deserialize(t.children)})}serialize(){const t={href:this.href};return this.templated!==void 0&&(t.templated=this.templated),this.type!==void 0&&(t.type=this.type),this.title!==void 0&&(t.title=this.title),this.rels&&(t.rel=ni(this.rels)),this.properties&&(t.properties=this.properties.serialize()),this.height!==void 0&&(t.height=this.height),this.width!==void 0&&(t.width=this.width),this.duration!==void 0&&(t.duration=this.duration),this.bitrate!==void 0&&(t.bitrate=this.bitrate),this.languages&&(t.language=this.languages),this.alternates&&(t.alternate=this.alternates.serialize()),this.children&&(t.children=this.children.serialize()),t}get mediaType(){return this.type!==void 0?d.parse({mediaType:this.type}):d.BINARY}toURL(t){const e=this.href.replace(/^(\/)/,"");if(e.length===0)return;let A=t||"/";return A.startsWith("/")&&(A="file://"+A),new URL(e,A).href.replace(/^(file:\/\/)/,"")}get templateParameters(){return this.templated?new Ie(this.href).parameters:new Set}expandTemplate(t){return new Jt({href:new Ie(this.href).expand(t),templated:!1})}addProperties(t){var e;const A=Jt.deserialize(this.serialize());return A.properties=A.properties?(e=A.properties)==null?void 0:e.add(t):new Y(t),A}get locator(){let t=this.href.split("#");return new Lt({href:t.length>0&&t[0]!==void 0?t[0]:this.href,type:this.type??"",title:this.title,locations:new G({fragments:t.length>1&&t[1]!==void 0?[t[1]]:[]})})}},ye=class KA{constructor(t){this.items=t}static deserialize(t){if(t&&t instanceof Array)return new KA(t.map(e=>wt.deserialize(e)).filter(e=>e!==void 0))}serialize(){return this.items.map(t=>t.serialize())}findWithRel(t){const e=A=>A.rels&&A.rels.has(t);return this.items.find(e)}filterByRel(t){const e=A=>A.rels&&A.rels.has(t);return this.items.filter(e)}findWithHref(t){const e=A=>A.href===t;return this.items.find(e)}findIndexWithHref(t){const e=A=>A.href===t;return this.items.findIndex(e)}findWithMediaType(t){const e=A=>A.mediaType.matches(t);return this.items.find(e)}filterByMediaType(t){const e=A=>A.mediaType.matches(t);return this.items.filter(e)}filterByMediaTypes(t){const e=A=>{for(const i of t)if(A.mediaType.matches(i))return!0;return!1};return this.items.filter(e)}everyIsAudio(){const t=e=>e.mediaType.isAudio;return this.items.length>0&&this.items.every(t)}everyIsBitmap(){const t=e=>e.mediaType.isBitmap;return this.items.length>0&&this.items.every(t)}everyIsHTML(){const t=e=>e.mediaType.isHTML;return this.items.length>0&&this.items.every(t)}everyIsVideo(){const t=e=>e.mediaType.isVideo;return this.items.length>0&&this.items.every(t)}everyMatchesMediaType(t){return Array.isArray(t)?this.items.length>0&&this.items.every(e=>{for(const A of t)return e.mediaType.matches(A);return!1}):this.items.length>0&&this.items.every(e=>e.mediaType.matches(t))}filterLinksHasType(){return this.items.filter(t=>t.type)}};class Ot{constructor(t){this.algorithm=t.algorithm,this.compression=t.compression,this.originalLength=t.originalLength,this.profile=t.profile,this.scheme=t.scheme}static deserialize(t){if(t&&t.algorithm)return new Ot({algorithm:t.algorithm,compression:t.compression,originalLength:t.originalLength,profile:t.profile,scheme:t.scheme})}serialize(){const t={algorithm:this.algorithm};return this.compression!==void 0&&(t.compression=this.compression),this.originalLength!==void 0&&(t.originalLength=this.originalLength),this.profile!==void 0&&(t.profile=this.profile),this.scheme!==void 0&&(t.scheme=this.scheme),t}}Object.defineProperty(Y.prototype,"encryption",{get:function(){return Ot.deserialize(this.otherProperties.encrypted)}});let Ce=class qA{constructor(t){this.cssSelector=t.cssSelector,this.textNodeIndex=t.textNodeIndex,this.charOffset=t.charOffset}static deserialize(t){if(!(t&&t.cssSelector))return;let e=P(t.textNodeIndex);if(e===void 0)return;let A=P(t.charOffset);return A===void 0&&(A=P(t.offset)),new qA({cssSelector:t.cssSelector,textNodeIndex:e,charOffset:A})}serialize(){const t={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(t.charOffset=this.charOffset),t}},si=class _A{constructor(t){this.start=t.start,this.end=t.end}static deserialize(t){if(!t)return;let e=Ce.deserialize(t.start);if(e)return new _A({start:e,end:Ce.deserialize(t.end)})}serialize(){const t={start:this.start.serialize()};return this.end&&(t.end=this.end.serialize()),t}};G.prototype.getCssSelector=function(){var n;return(n=this.otherLocations)==null?void 0:n.get("cssSelector")},G.prototype.getPartialCfi=function(){var n;return(n=this.otherLocations)==null?void 0:n.get("partialCfi")},G.prototype.getDomRange=function(){var n;return si.deserialize((n=this.otherLocations)==null?void 0:n.get("domRange"))},G.prototype.fragmentParameters=function(){return new Map(this.fragments.map(n=>n.startsWith("#")?n.slice(1):n).join("&").split("&").filter(n=>!n.startsWith("#")).map(n=>n.split("=")).filter(n=>n.length===2).map(n=>[n[0].trim().toLowerCase(),n[1].trim()]))},G.prototype.htmlId=function(){if(!this.fragments.length)return;let n=this.fragments.find(t=>t.length&&!t.includes("="));if(!n){const t=this.fragmentParameters();t.has("id")?n=t.get("id"):t.has("name")&&(n=t.get("name"))}return n!=null&&n.startsWith("#")?n.slice(1):n},G.prototype.page=function(){const n=parseInt(this.fragmentParameters().get("page"));if(!isNaN(n)&&n>=0)return n},G.prototype.time=function(){const n=parseInt(this.fragmentParameters().get("t"));if(!isNaN(n))return n},G.prototype.space=function(){const n=this.fragmentParameters();if(!n.has("xywh"))return;const t=n.get("xywh").split(",").map(e=>parseInt(e));if(t.length===4&&!t.some(isNaN))return t};let oi=class $A{constructor(t){this.currency=t.currency,this.value=t.value}static deserialize(t){if(!t)return;let e=t.currency;if(!(e&&typeof e=="string"&&e.length>0))return;let A=P(t.value);if(A!==void 0)return new $A({currency:e,value:A})}serialize(){return{currency:this.currency,value:this.value}}},ai=class Wt{constructor(t){this.type=t.type,this.children=t.children}static deserialize(t){if(t&&t.type)return new Wt({type:t.type,children:Wt.deserializeArray(t.children)})}static deserializeArray(t){if(t instanceof Array)return t.map(e=>Wt.deserialize(e)).filter(e=>e!==void 0)}serialize(){const t={type:this.type};return this.children&&(t.children=this.children.map(e=>e.serialize())),t}},li=class ti{constructor(t){this.total=t.total,this.position=t.position}static deserialize(t){if(t)return new ti({total:P(t.total),position:P(t.position)})}serialize(){const t={};return this.total!==void 0&&(t.total=this.total),this.position!==void 0&&(t.position=this.position),t}},hi=class ei{constructor(t){this.total=t.total,this.available=t.available}static deserialize(t){if(t)return new ei({total:P(t.total),available:P(t.available)})}serialize(){const t={};return this.total!==void 0&&(t.total=this.total),this.available!==void 0&&(t.available=this.available),t}},ci=class Ai{constructor(t){this.state=t.state,this.since=t.since,this.until=t.until}static deserialize(t){if(t&&t.state)return new Ai({state:t.state,since:Ue(t.since),until:Ue(t.until)})}serialize(){const t={state:this.state};return this.since!==void 0&&(t.since=this.since.toISOString()),this.until!==void 0&&(t.until=this.until.toISOString()),t}};Y.prototype.getNumberOfItems=function(){return P(this.otherProperties.numberOfItems)},Y.prototype.getPrice=function(){return oi.deserialize(this.otherProperties.price)},Y.prototype.getIndirectAcquisitions=function(){const n=this.otherProperties.indirectAcquisition;if(n&&n instanceof Array)return n.map(t=>ai.deserialize(t)).filter(t=>t!==void 0)},Y.prototype.getHolds=function(){return li.deserialize(this.otherProperties.holds)},Y.prototype.getCopies=function(){return hi.deserialize(this.otherProperties.copies)},Y.prototype.getAvailability=function(){return ci.deserialize(this.otherProperties.availability)},Y.prototype.getAuthenticate=function(){return wt.deserialize(this.otherProperties.authenticate)};var w=(n=>(n.auto="auto",n.btt="btt",n.ltr="ltr",n.rtl="rtl",n.ttb="ttb",n))(w||{});Y.prototype.getClipped=function(){return this.otherProperties.clipped},Y.prototype.getFit=function(){return this.otherProperties.fit},Y.prototype.getOrientation=function(){return this.otherProperties.orientation},Y.prototype.getOverflow=function(){return this.otherProperties.overflow},Y.prototype.getPage=function(){return this.otherProperties.page||void 0},Y.prototype.getSpread=function(){return this.otherProperties.spread||void 0};var _;(function(n){n.NONE="none",n.DESCENDANT="descendant",n.CHILD="child"})(_||(_={}));var H;(function(n){n.id="id",n.class="class",n.tag="tag",n.attribute="attribute",n.nthchild="nthchild",n.nthoftype="nthoftype"})(H||(H={}));const gi="CssSelectorGenerator";function Re(n="unknown problem",...t){console.warn(`${gi}: ${n}`,...t)}H.id,H.class,H.tag,H.attribute,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY;function di(n){return n instanceof RegExp}function ui(n){return n.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function mi(n){const t=n.map(e=>{if(di(e))return A=>e.test(A);if(typeof e=="function")return A=>{const i=e(A);return typeof i!="boolean"?(Re("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",e),!1):i};if(typeof e=="string"){const A=new RegExp("^"+ui(e)+"$");return i=>A.test(i)}return Re("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",e),()=>!1});return e=>t.some(A=>A(e))}const Mi="",fi=" > ",pi=" ";_.NONE+"",_.NONE,_.DESCENDANT+"",_.DESCENDANT,_.CHILD+"",_.CHILD,H.nthoftype,H.tag,H.id,H.class,H.attribute,H.nthchild,mi(["class","id","ng-*"]);class Qe{}class ze extends Qe{goLeft(t=!1,e){this.readingProgression===w.ltr||this.readingProgression===w.ttb||this.readingProgression===w.auto?this.goBackward(t,e):(this.readingProgression===w.rtl||this.readingProgression===w.btt)&&this.goForward(t,e)}goRight(t=!1,e){this.readingProgression===w.ltr||this.readingProgression===w.ttb||this.readingProgression===w.auto?this.goForward(t,e):(this.readingProgression===w.rtl||this.readingProgression===w.btt)&&this.goBackward(t,e)}}const Bi=`@namespace url(http://www.w3.org/1999/xhtml);@namespace epub url(http://www.idpf.org/2007/ops);@namespace m url(http://www.w3.org/1998/Math/MathML);@namespace svg url(http://www.w3.org/2000/svg);:root{--RS__viewportWidth:100%;--RS__pageGutter:0;--RS__defaultLineLength:40rem;--RS__colGap:0;--RS__colCount:1;--RS__colWidth:100vw}@page{margin:0!important}:root{position:relative;-webkit-column-width:var(--RS__colWidth);-moz-column-width:var(--RS__colWidth);column-width:var(--RS__colWidth);-webkit-column-count:var(--RS__colCount);-moz-column-count:var(--RS__colCount);column-count:var(--RS__colCount);-webkit-column-gap:var(--RS__colGap);-moz-column-gap:var(--RS__colGap);column-gap:var(--RS__colGap);-moz-column-fill:auto;column-fill:auto;width:var(--RS__viewportWidth);height:100vh;max-width:var(--RS__viewportWidth);max-height:100vh;min-width:var(--RS__viewportWidth);min-height:100vh;padding:0!important;margin:0!important;font-size:1rem!important;box-sizing:border-box;-webkit-touch-callout:none}body{width:100%;max-width:var(--RS__defaultLineLength)!important;padding:0 var(--RS__pageGutter)!important;margin:0 auto!important;box-sizing:border-box}:root:not([style*=readium-noOverflow-on]) body{overflow:hidden}@supports (overflow: clip){:root:not([style*=readium-noOverflow-on]){overflow:clip}:root:not([style*=readium-noOverflow-on]) body{overflow:clip;overflow-clip-margin:content-box}}:root[style*=readium-scroll-on]{-webkit-columns:auto auto!important;-moz-columns:auto auto!important;columns:auto auto!important;width:auto!important;height:auto!important;max-width:none!important;max-height:none!important;min-width:0!important;min-height:0!important}:root[style*=readium-scroll-on] body{max-width:var(--RS__defaultLineLength)!important;box-sizing:border-box!important}:root[style*=readium-scroll-on]:not([style*=readium-noOverflow-on]) body{overflow:auto}@supports (overflow: clip){:root[style*=readium-scroll-on]:not([style*=readium-noOverflow-on]){overflow:auto}:root[style*=readium-scroll-on]:not([style*=readium-noOverflow-on]) body{overflow:clip}}:root[style*=readium-scroll-on][style*=--RS__scrollPaddingTop] body{padding-top:var(--RS__scrollPaddingTop)!important}:root[style*=readium-scroll-on][style*=--RS__scrollPaddingBottom] body{padding-bottom:var(--RS__scrollPaddingBottom)!important}:root[style*=readium-scroll-on][style*=--RS__scrollPaddingLeft] body{padding-left:var(--RS__scrollPaddingLeft)!important}:root[style*=readium-scroll-on][style*=--RS__scrollPaddingRight] body{padding-right:var(--RS__scrollPaddingRight)!important}:root[style*=readium-night-on]{--RS__selectionTextColor:inherit;--RS__selectionBackgroundColor:#b4d8fe;--RS__visitedColor:#0099E5;--RS__linkColor:#63caff;--RS__textColor:#FEFEFE;--RS__backgroundColor:#000000}:root[style*=readium-night-on] *:not(a){color:inherit!important;background-color:transparent!important;border-color:currentcolor!important}:root[style*=readium-night-on] svg text{fill:currentcolor!important;stroke:none!important}:root[style*=readium-night-on] a:link,:root[style*=readium-night-on] a:link *{color:var(--RS__linkColor)!important}:root[style*=readium-night-on] a:visited,:root[style*=readium-night-on] a:visited *{color:var(--RS__visitedColor)!important}:root[style*=readium-night-on] img[class*=gaiji],:root[style*=readium-night-on] *[epub\\:type~=titlepage] img:only-child,:root[style*=readium-night-on] *[epub|type~=titlepage] img:only-child{-webkit-filter:invert(100%);filter:invert(100%)}:root[style*=readium-sepia-on]{--RS__selectionTextColor:inherit;--RS__selectionBackgroundColor:#b4d8fe;--RS__visitedColor:#551A8B;--RS__linkColor:#0000EE;--RS__textColor:#121212;--RS__backgroundColor:#faf4e8}:root[style*=readium-sepia-on] *:not(a){color:inherit!important;background-color:transparent!important}:root[style*=readium-sepia-on] a:link,:root[style*=readium-sepia-on] a:link *{color:var(--RS__linkColor)}:root[style*=readium-sepia-on] a:visited,:root[style*=readium-sepia-on] a:visited *{color:var(--RS__visitedColor)}@media screen and (-ms-high-contrast: active){:root{color:windowText!important;background-color:window!important}:root :not(#\\#):not(#\\#):not(#\\#),:root :not(#\\#):not(#\\#):not(#\\#) :not(#\\#):not(#\\#):not(#\\#) :root :not(#\\#):not(#\\#):not(#\\#) :not(#\\#):not(#\\#):not(#\\#) :not(#\\#):not(#\\#):not(#\\#){color:inherit!important;background-color:inherit!important}.readiumCSS-mo-active-default{color:highlightText!important;background-color:highlight!important}}@media screen and (-ms-high-contrast: white-on-black){:root[style*=readium-night-on] img[class*=gaiji],:root[style*=readium-night-on] *[epub\\:type~=titlepage] img:only-child,:root[style*=readium-night-on] *[epub|type~=titlepage] img:only-child{-webkit-filter:none!important;filter:none!important}:root[style*=readium-night-on][style*=readium-invert-on] img{-webkit-filter:none!important;filter:none!important}:root[style*=readium-night-on][style*=readium-darken-on][style*=readium-invert-on] img{-webkit-filter:brightness(80%);filter:brightness(80%)}}@media screen and (inverted-colors){:root[style*=readium-night-on] img[class*=gaiji],:root[style*=readium-night-on] *[epub\\:type~=titlepage] img:only-child,:root[style*=readium-night-on] *[epub|type~=titlepage] img:only-child{-webkit-filter:none!important;filter:none!important}:root[style*=readium-night-on][style*=readium-invert-on] img{-webkit-filter:none!important;filter:none!important}:root[style*=readium-night-on][style*=readium-darken-on][style*=readium-invert-on] img{-webkit-filter:brightness(80%);filter:brightness(80%)}}:root[style*=--USER__backgroundColor]{background-color:var(--USER__backgroundColor)!important}:root[style*=--USER__backgroundColor] *{background-color:transparent!important}:root[style*=--USER__textColor]{color:var(--USER__textColor)!important}:root[style*=--USER__textColor] *:not(a){color:inherit!important;background-color:transparent!important;border-color:currentcolor!important}:root[style*=--USER__textColor] svg text{fill:currentcolor!important;stroke:none!important}:root[style*=--USER__linkColor] a:link,:root[style*=--USER__linkColor] a:link *{color:var(--USER__linkColor)!important}:root[style*=--USER__visitedColor] a:visited,:root[style*=--USER__visitedColor] a:visited *{color:var(--USER__visitedColor)!important}:root[style*=--USER__selectionBackgroundColor][style*=--USER__selectionTextColor] ::-moz-selection{color:var(--USER__selectionTextColor)!important;background-color:var(--USER__selectionBackgroundColor)!important}:root[style*=--USER__selectionBackgroundColor][style*=--USER__selectionTextColor] ::selection{color:var(--USER__selectionTextColor)!important;background-color:var(--USER__selectionBackgroundColor)!important}:root[style*=--USER__colCount]{-webkit-column-count:var(--USER__colCount);-moz-column-count:var(--USER__colCount);column-count:var(--USER__colCount);--RS__colWidth:auto}:root[style*="--USER__colCount: 0"],:root[style*="--USER__colCount:0"]{-webkit-column-count:1;-moz-column-count:1;column-count:1}:root[style*="--USER__colCount: 0"],:root[style*="--USER__colCount:0"],:root[style*="--USER__colCount: 1"],:root[style*="--USER__colCount:1"]{--RS__colWidth:100vw}:root[style*=--USER__lineLength] body{max-width:var(--USER__lineLength)!important}:root[style*=--USER__textAlign]{text-align:var(--USER__textAlign)}:root[style*=--USER__textAlign] body,:root[style*=--USER__textAlign] p:not(blockquote p):not(figcaption p):not(hgroup p),:root[style*=--USER__textAlign] li,:root[style*=--USER__textAlign] dd{text-align:var(--USER__textAlign)!important;-moz-text-align-last:auto!important;-epub-text-align-last:auto!important;text-align-last:auto!important}:root[style*=--USER__bodyHyphens]{-webkit-hyphens:var(--USER__bodyHyphens)!important;-moz-hyphens:var(--USER__bodyHyphens)!important;-ms-hyphens:var(--USER__bodyHyphens)!important;-epub-hyphens:var(--USER__bodyHyphens)!important;hyphens:var(--USER__bodyHyphens)!important}:root[style*=--USER__bodyHyphens] body,:root[style*=--USER__bodyHyphens] p,:root[style*=--USER__bodyHyphens] li,:root[style*=--USER__bodyHyphens] div,:root[style*=--USER__bodyHyphens] dd{-webkit-hyphens:inherit;-moz-hyphens:inherit;-ms-hyphens:inherit;-epub-hyphens:inherit;hyphens:inherit}:root[style*=--USER__fontFamily]{font-family:var(--USER__fontFamily)!important}:root[style*=--USER__fontFamily] *{font-family:revert!important}:root[style*=AccessibleDfA]{font-family:AccessibleDfA,Verdana,Tahoma,Trebuchet MS,sans-serif!important}:root[style*="IA Writer Duospace"]{font-family:IA Writer Duospace,Menlo,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier,monospace!important}:root[style*=AccessibleDfA],:root[style*="IA Writer Duospace"],:root[style*=readium-a11y-on]{font-style:normal!important;font-weight:400!important}:root[style*=AccessibleDfA] *:not(code):not(var):not(kbd):not(samp),:root[style*="IA Writer Duospace"] *:not(code):not(var):not(kbd):not(samp),:root[style*=readium-a11y-on] *:not(code):not(var):not(kbd):not(samp){font-family:inherit!important;font-style:inherit!important;font-weight:inherit!important}:root[style*=AccessibleDfA] *,:root[style*="IA Writer Duospace"] *,:root[style*=readium-a11y-on] *{text-decoration:none!important;font-variant-caps:normal!important;font-variant-numeric:normal!important;font-variant-position:normal!important}:root[style*=AccessibleDfA] sup,:root[style*="IA Writer Duospace"] sup,:root[style*=readium-a11y-on] sup,:root[style*=AccessibleDfA] sub,:root[style*="IA Writer Duospace"] sub,:root[style*=readium-a11y-on] sub{font-size:1rem!important;vertical-align:baseline!important}:root:not([style*=readium-deprecatedFontSize-on]):not([style*=readium-iOSPatch-on])[style*=--USER__fontSize] body{zoom:var(--USER__fontSize)!important}:root[style*=readium-iOSPatch-on][style*=--USER__fontSize] body{-webkit-text-size-adjust:var(--USER__fontSize)!important}@supports not (zoom: 1){:root[style*=--USER__fontSize]{font-size:var(--USER__fontSize)!important}}:root[style*=readium-deprecatedFontSize-on][style*=--USER__fontSize]{font-size:var(--USER__fontSize)!important}:root[style*=--USER__lineHeight]{line-height:var(--USER__lineHeight)!important}:root[style*=--USER__lineHeight] body,:root[style*=--USER__lineHeight] p,:root[style*=--USER__lineHeight] li,:root[style*=--USER__lineHeight] div{line-height:inherit}:root[style*=--USER__paraSpacing] p{margin-top:var(--USER__paraSpacing)!important;margin-bottom:var(--USER__paraSpacing)!important}:root[style*=--USER__paraIndent] p{text-indent:var(--USER__paraIndent)!important}:root[style*=--USER__paraIndent] p *,:root[style*=--USER__paraIndent] p:first-letter{text-indent:0!important}:root[style*=--USER__wordSpacing] h1,:root[style*=--USER__wordSpacing] h2,:root[style*=--USER__wordSpacing] h3,:root[style*=--USER__wordSpacing] h4,:root[style*=--USER__wordSpacing] h5,:root[style*=--USER__wordSpacing] h6,:root[style*=--USER__wordSpacing] p,:root[style*=--USER__wordSpacing] li,:root[style*=--USER__wordSpacing] div,:root[style*=--USER__wordSpacing] dt,:root[style*=--USER__wordSpacing] dd{word-spacing:var(--USER__wordSpacing)}:root[style*=--USER__letterSpacing] h1,:root[style*=--USER__letterSpacing] h2,:root[style*=--USER__letterSpacing] h3,:root[style*=--USER__letterSpacing] h4,:root[style*=--USER__letterSpacing] h5,:root[style*=--USER__letterSpacing] h6,:root[style*=--USER__letterSpacing] p,:root[style*=--USER__letterSpacing] li,:root[style*=--USER__letterSpacing] div,:root[style*=--USER__letterSpacing] dt,:root[style*=--USER__letterSpacing] dd{letter-spacing:var(--USER__letterSpacing);font-variant:none}:root[style*=--USER__fontWeight] body{font-weight:var(--USER__fontWeight)!important}:root[style*=--USER__fontWeight] b,:root[style*=--USER__fontWeight] strong{font-weight:bolder}:root[style*=--USER__fontWidth] body{font-stretch:var(--USER__fontWidth)!important}:root[style*=--USER__fontOpticalSizing] body{font-optical-sizing:var(--USER__fontOpticalSizing)!important}:root[style*=readium-blend-on] svg,:root[style*=readium-blend-on] img{background-color:transparent!important;mix-blend-mode:multiply!important}:root[style*=--USER__darkenImages] img{-webkit-filter:brightness(var(--USER__darkenImages))!important;filter:brightness(var(--USER__darkenImages))!important}:root[style*=readium-darken-on] img{-webkit-filter:brightness(80%)!important;filter:brightness(80%)!important}:root[style*=--USER__invertImages] img{-webkit-filter:invert(var(--USER__invertImages))!important;filter:invert(var(--USER__invertImages))!important}:root[style*=readium-invert-on] img{-webkit-filter:invert(100%)!important;filter:invert(100%)!important}:root[style*=--USER__darkenImages][style*=--USER__invertImages] img{-webkit-filter:brightness(var(--USER__darkenImages)) invert(var(--USER__invertImages))!important;filter:brightness(var(--USER__darkenImages)) invert(var(--USER__invertImages))!important}:root[style*=readium-darken-on][style*=--USER__invertImages] img{-webkit-filter:brightness(80%) invert(var(--USER__invertImages))!important;filter:brightness(80%) invert(var(--USER__invertImages))!important}:root[style*=--USER__darkenImages][style*=readium-invert-on] img{-webkit-filter:brightness(var(--USER__darkenImages)) invert(100%)!important;filter:brightness(var(--USER__darkenImages)) invert(100%)!important}:root[style*=readium-darken-on][style*=readium-invert-on] img{-webkit-filter:brightness(80%) invert(100%)!important;filter:brightness(80%) invert(100%)!important}:root[style*=--USER__invertGaiji] img[class*=gaiji]{-webkit-filter:invert(var(--USER__invertGaiji))!important;filter:invert(var(--USER__invertGaiji))!important}:root[style*=readium-invertGaiji-on] img[class*=gaiji]{-webkit-filter:invert(100%)!important;filter:invert(100%)!important}:root[style*=readium-normalize-on]{--USER__typeScale:1.2}:root[style*=readium-normalize-on] p,:root[style*=readium-normalize-on] li,:root[style*=readium-normalize-on] div,:root[style*=readium-normalize-on] pre,:root[style*=readium-normalize-on] dd{font-size:1rem!important}:root[style*=readium-normalize-on] h1{font-size:1.75rem!important;font-size:calc(((1rem * var(--USER__typeScale)) * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-normalize-on] h2{font-size:1.5rem!important;font-size:calc((1rem * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-normalize-on] h3{font-size:1.25rem!important;font-size:calc(1rem * var(--USER__typeScale))!important}:root[style*=readium-normalize-on] h4,:root[style*=readium-normalize-on] h5,:root[style*=readium-normalize-on] h6{font-size:1rem!important}:root[style*=readium-normalize-on] small{font-size:smaller!important}:root[style*=readium-normalize-on] sub,:root[style*=readium-normalize-on] sup{font-size:67.5%!important}:root[style*=readium-normalize-on][style*=--USER__typeScale] h1{font-size:calc(((1rem * var(--USER__typeScale)) * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-normalize-on][style*=--USER__typeScale] h2{font-size:calc((1rem * var(--USER__typeScale)) * var(--USER__typeScale))!important}:root[style*=readium-normalize-on][style*=--USER__typeScale] h3{font-size:calc(1rem * var(--USER__typeScale))!important}:root[style*=readium-iPadOSPatch-on] body{-webkit-text-size-adjust:none}:root[style*=readium-iPadOSPatch-on] p,:root[style*=readium-iPadOSPatch-on] h1,:root[style*=readium-iPadOSPatch-on] h2,:root[style*=readium-iPadOSPatch-on] h3,:root[style*=readium-iPadOSPatch-on] h4,:root[style*=readium-iPadOSPatch-on] h5,:root[style*=readium-iPadOSPatch-on] h6,:root[style*=readium-iPadOSPatch-on] li,:root[style*=readium-iPadOSPatch-on] th,:root[style*=readium-iPadOSPatch-on] td,:root[style*=readium-iPadOSPatch-on] dt,:root[style*=readium-iPadOSPatch-on] dd,:root[style*=readium-iPadOSPatch-on] pre,:root[style*=readium-iPadOSPatch-on] address,:root[style*=readium-iPadOSPatch-on] details,:root[style*=readium-iPadOSPatch-on] summary,:root[style*=readium-iPadOSPatch-on] figcaption,:root[style*=readium-iPadOSPatch-on] div:not(:has(p,h1,h2,h3,h4,h5,h6,li,th,td,dt,dd,pre,address,aside,details,figcaption,summary)),:root[style*=readium-iPadOSPatch-on] aside:not(:has(p,h1,h2,h3,h4,h5,h6,li,th,td,dt,dd,pre,address,aside,details,figcaption,summary)){-webkit-text-zoom:reset}:root[style*=readium-iPadOSPatch-on] abbr,:root[style*=readium-iPadOSPatch-on] b,:root[style*=readium-iPadOSPatch-on] bdi,:root[style*=readium-iPadOSPatch-on] bdo,:root[style*=readium-iPadOSPatch-on] cite,:root[style*=readium-iPadOSPatch-on] code,:root[style*=readium-iPadOSPatch-on] dfn,:root[style*=readium-iPadOSPatch-on] em,:root[style*=readium-iPadOSPatch-on] i,:root[style*=readium-iPadOSPatch-on] kbd,:root[style*=readium-iPadOSPatch-on] mark,:root[style*=readium-iPadOSPatch-on] q,:root[style*=readium-iPadOSPatch-on] rp,:root[style*=readium-iPadOSPatch-on] rt,:root[style*=readium-iPadOSPatch-on] ruby,:root[style*=readium-iPadOSPatch-on] s,:root[style*=readium-iPadOSPatch-on] samp,:root[style*=readium-iPadOSPatch-on] small,:root[style*=readium-iPadOSPatch-on] span,:root[style*=readium-iPadOSPatch-on] strong,:root[style*=readium-iPadOSPatch-on] sub,:root[style*=readium-iPadOSPatch-on] sup,:root[style*=readium-iPadOSPatch-on] time,:root[style*=readium-iPadOSPatch-on] u,:root[style*=readium-iPadOSPatch-on] var{-webkit-text-zoom:normal}:root[style*=readium-iPadOSPatch-on] p:not(:has(b,cite,em,i,q,s,small,span,strong)):first-line{-webkit-text-zoom:normal}
2
+ `,Ei=`@namespace url(http://www.w3.org/1999/xhtml);@namespace epub url(http://www.idpf.org/2007/ops);@namespace m url(http://www.w3.org/1998/Math/MathML);@namespace svg url(http://www.w3.org/2000/svg);@-ms-viewport{width:device-width}@viewport{width:device-width;zoom:1}:root{--RS__monospaceTf:ui-monospace, "Andale Mono", "Cascadia Code", "Source Code Pro", Menlo, Consolas, "DejaVu Sans Mono", monospace;--RS__humanistTf:Seravek, Calibri, "Gill Sans Nova", Roboto, Ubuntu, "DejaVu Sans", source-sans-pro, sans-serif;--RS__sansTf:-ui-sans-serif, -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI Variable", "Segoe UI", Inter, Roboto, "Helvetica Neue", "Arial Nova", "Liberation Sans", Arial, sans-serif;--RS__modernTf:Athelas, Constantia, Charter, "Bitstream Charter", Cambria, "Georgia Pro", Georgia, serif;--RS__oldStyleTf:"Iowan Old Style", Sitka, "Sitka Text", Palatino, "Book Antiqua", "URW Palladio L", P052, serif;--RS__baseFontFamily:var(--RS__oldStyleTf);--RS__lineHeightCompensation:1;--RS__baseLineHeight:calc(1.5 * var(--RS__lineHeightCompensation));--RS__selectionTextColor:inherit;--RS__selectionBackgroundColor:#b4d8fe;--RS__visitedColor:#551A8B;--RS__linkColor:#0000EE;--RS__textColor:#121212;--RS__backgroundColor:#FFFFFF;color:var(--RS__textColor)!important;background-color:var(--RS__backgroundColor)!important}::-moz-selection{color:var(--RS__selectionTextColor);background-color:var(--RS__selectionBackgroundColor)}::selection{color:var(--RS__selectionTextColor);background-color:var(--RS__selectionBackgroundColor)}html{font-family:var(--RS__baseFontFamily);line-height:1.6;line-height:var(--RS__baseLineHeight);text-rendering:optimizelegibility}h1,h2,h3{line-height:normal}:lang(ja),:lang(zh),:lang(ko){word-wrap:break-word;-webkit-line-break:strict;-epub-line-break:strict;line-break:strict}math{font-family:"Latin Modern Math","STIX Two Math","XITS Math","STIX Math","Libertinus Math","TeX Gyre Termes Math","TeX Gyre Bonum Math",TeX Gyre Schola,"DejaVu Math TeX Gyre","TeX Gyre Pagella Math","Asana Math","Cambria Math","Lucida Bright Math","Minion Math",STIXGeneral,STIXSizeOneSym,Symbol,Times New Roman,serif}:lang(am){--RS__baseFontFamily:kefa, nyala, roboto, noto, "Noto Sans Ethiopic", serif;--RS__lineHeightCompensation:1.167}:lang(ar){--RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif}:lang(bn){--RS__baseFontFamily:"Kohinoor Bangla", "Bangla Sangam MN", vrinda, roboto, noto, "Noto Sans Bengali", sans-serif;--RS__lineHeightCompensation:1.067}:lang(bo){--RS__baseFontFamily:kailasa, "Microsoft Himalaya", roboto, noto, "Noto Sans Tibetan", sans-serif}:lang(chr){--RS__baseFontFamily:"Plantagenet Cherokee", roboto, noto, "Noto Sans Cherokee";--RS__lineHeightCompensation:1.167}:lang(fa){--RS__baseFontFamily:"Geeza Pro", "Arabic Typesetting", roboto, noto, "Noto Naskh Arabic", "Times New Roman", serif}:lang(gu){--RS__baseFontFamily:"Gujarati Sangam MN", "Nirmala UI", shruti, roboto, noto, "Noto Sans Gujarati", sans-serif;--RS__lineHeightCompensation:1.167}:lang(he){--RS__baseFontFamily:"New Peninim MT", "Arial Hebrew", gisha, "Times New Roman", roboto, noto, "Noto Sans Hebrew" sans-serif;--RS__lineHeightCompensation:1.1}:lang(hi){--RS__baseFontFamily:"Kohinoor Devanagari", "Devanagari Sangam MN", kokila, "Nirmala UI", roboto, noto, "Noto Sans Devanagari", sans-serif;--RS__lineHeightCompensation:1.1}:lang(hy){--RS__baseFontFamily:mshtakan, sylfaen, roboto, noto, "Noto Serif Armenian", serif}:lang(iu){--RS__baseFontFamily:"Euphemia UCAS", euphemia, roboto, noto, "Noto Sans Canadian Aboriginal", sans-serif}:lang(ja){--RS__baseFontFamily:yugothic, "Hiragino Maru Gothic ProN", "Hiragino Sans", "Yu Gothic UI", "Meiryo UI", "MS Gothic", roboto, noto, "Noto Sans CJK JP", sans-serif;--RS__lineHeightCompensation:1.167;--RS__serif-ja:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDPMincho", "Yu Mincho", "MS P明朝", "MS PMincho", serif;--RS__sans-serif-ja:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDPGothic", "Yu Gothic", "MS Pゴシック", "MS PGothic", sans-serif;--RS__serif-ja-v:"Hiragino Mincho ProN", "Hiragino Mincho Pro", "YuMincho", "BIZ UDMincho", "Yu Mincho", "MS明朝", "MS Mincho", serif;--RS__sans-serif-ja-v:"Hiragino Sans", "Hiragino Kaku Gothic ProN", "Hiragino Kaku Gothic Pro", "ヒラギノ角ゴ W3", "YuGothic", "Yu Gothic Medium", "BIZ UDGothic", "Yu Gothic", "MSゴシック", "MS Gothic", sans-serif}:lang(km){--RS__baseFontFamily:"Khmer Sangam MN", "Leelawadee UI", "Khmer UI", roboto, noto, "Noto Sans Khmer", sans-serif;--RS__lineHeightCompensation:1.067}:lang(kn){--RS__baseFontFamily:"Kannada Sangam MN", "Nirmala UI", tunga, roboto, noto, "Noto Sans Kannada", sans-serif;--RS__lineHeightCompensation:1.1}:lang(ko){--RS__baseFontFamily:"Nanum Gothic", "Apple SD Gothic Neo", "Malgun Gothic", roboto, noto, "Noto Sans CJK KR", sans-serif;--RS__lineHeightCompensation:1.167}:lang(lo){--RS__baseFontFamily:"Lao Sangam MN", "Leelawadee UI", "Lao UI", roboto, noto, "Noto Sans Lao", sans-serif}:lang(ml){--RS__baseFontFamily:"Malayalam Sangam MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Malayalam", sans-serif;--RS__lineHeightCompensation:1.067}:lang(or){--RS__baseFontFamily:"Oriya Sangam MN", "Nirmala UI", kalinga, roboto, noto, "Noto Sans Oriya", sans-serif;--RS__lineHeightCompensation:1.167}:lang(pa){--RS__baseFontFamily:"Gurmukhi MN", "Nirmala UI", kartika, roboto, noto, "Noto Sans Gurmukhi", sans-serif;--RS__lineHeightCompensation:1.1}:lang(si){--RS__baseFontFamily:"Sinhala Sangam MN", "Nirmala UI", "Iskoola Pota", roboto, noto, "Noto Sans Sinhala", sans-serif;--RS__lineHeightCompensation:1.167}:lang(ta){--RS__baseFontFamily:"Tamil Sangam MN", "Nirmala UI", latha, roboto, noto, "Noto Sans Tamil", sans-serif;--RS__lineHeightCompensation:1.067}:lang(te){--RS__baseFontFamily:"Kohinoor Telugu", "Telugu Sangam MN", "Nirmala UI", gautami, roboto, noto, "Noto Sans Telugu", sans-serif}:lang(th){--RS__baseFontFamily:"Thonburi", "Leelawadee UI", "Cordia New", roboto, noto, "Noto Sans Thai", sans-serif;--RS__lineHeightCompensation:1.067}:lang(zh){--RS__baseFontFamily:"方体", "PingFang SC", "黑体", "Heiti SC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK SC", sans-serif;--RS__lineHeightCompensation:1.167}:lang(zh-Hant),:lang(zh-TW){--RS__baseFontFamily:"方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;--RS__lineHeightCompensation:1.167}:lang(zh-HK){--RS__baseFontFamily:"方體", "PingFang HK", "方體", "PingFang TC", "黑體", "Heiti TC", "Microsoft JhengHei UI", "Microsoft JhengHei", roboto, noto, "Noto Sans CJK TC", sans-serif;--RS__lineHeightCompensation:1.167}@font-face{font-family:AccessibleDfA;font-style:normal;font-weight:400;src:local("AccessibleDfA"),url(./assets/AccessibleDfA-Regular.woff2) format("woff2"),url(./assets/AccessibleDfA-Regular.woff) format("woff")}@font-face{font-family:AccessibleDfA;font-style:normal;font-weight:700;src:local("AccessibleDfA"),url(./assets/AccessibleDfA-Bold.woff2) format("woff2")}@font-face{font-family:AccessibleDfA;font-style:italic;font-weight:400;src:local("AccessibleDfA"),url(./assets/AccessibleDfA-Italic.woff2) format("woff2")}@font-face{font-family:IA Writer Duospace;font-style:normal;font-weight:400;src:local("iAWriterDuospace-Regular"),url(./assets/iAWriterDuospace-Regular.ttf) format("truetype")}body{widows:2;orphans:2}figcaption,th,td{widows:1;orphans:1}h2,h3,h4,h5,h6,dt,hr,caption{-webkit-column-break-after:avoid;page-break-after:avoid;break-after:avoid}h1,h2,h3,h4,h5,h6,dt,figure,tr{-webkit-column-break-inside:avoid;page-break-inside:avoid;break-inside:avoid}body{-webkit-hyphenate-character:"-";-moz-hyphenate-character:"-";-ms-hyphenate-character:"-";hyphenate-character:"-";-webkit-hyphenate-limit-lines:3;-ms-hyphenate-limit-lines:3;hyphenate-limit-lines:3}h1,h2,h3,h4,h5,h6,dt,figcaption,pre,caption,address,center,code,var{-ms-hyphens:none;-moz-hyphens:none;-webkit-hyphens:none;-epub-hyphens:none;hyphens:none}body{font-variant-numeric:oldstyle-nums proportional-nums}:lang(ja) body,:lang(zh) body,:lang(ko) body{font-variant-numeric:lining-nums proportional-nums}h1,h2,h3,h4,h5,h6,dt{font-variant-numeric:lining-nums proportional-nums}table{font-variant-numeric:lining-nums tabular-nums}code,var{font-variant-ligatures:none;font-variant-numeric:lining-nums tabular-nums slashed-zero}rt{font-variant-east-asian:ruby}:lang(ar){font-variant-ligatures:common-ligatures}:lang(ko){font-kerning:normal}hr{color:inherit;border-color:currentcolor}table,th,td{border-color:currentcolor}figure,blockquote{margin:1em 5%}ul,ol{padding-left:5%}dd{margin-left:5%}pre{white-space:pre-wrap;-ms-tab-size:2;-moz-tab-size:2;-webkit-tab-size:2;tab-size:2}abbr[title],acronym[title]{text-decoration:dotted underline}nobr wbr{white-space:normal}ruby>rt,ruby>rp{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}*:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)),*:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)),*:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)),:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) cite,:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) dfn,:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) em,:lang(ja):not(:lang(ja-Latn)):not(:lang(ja-Cyrl)) i,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) cite,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) dfn,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) em,:lang(zh):not(:lang(zh-Latn)):not(:lang(zh-Cyrl)) i,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) cite,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) dfn,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) em,:lang(ko):not(:lang(ko-Latn)):not(:lang(ko-Cyrl)) i{font-style:normal}:lang(ja) a,:lang(zh) a,:lang(ko) a{text-decoration:none}:root{--RS__maxMediaWidth:100%;--RS__maxMediaHeight:95vh;--RS__boxSizingMedia:border-box;--RS__boxSizingTable:border-box}a,a span,span a,h1,h2,h3,h4,h5,h6{word-wrap:break-word}div{max-width:var(--RS__maxMediaWidth)}img,svg|svg,video{object-fit:contain;width:auto;height:auto;max-width:var(--RS__maxMediaWidth);max-height:var(--RS__maxMediaHeight)!important;box-sizing:var(--RS__boxSizingMedia);-webkit-column-break-inside:avoid;page-break-inside:avoid;break-inside:avoid}audio{max-width:100%;-webkit-column-break-inside:avoid;page-break-inside:avoid;break-inside:avoid}table{max-width:var(--RS__maxMediaWidth);box-sizing:var(--RS__boxSizingTable)}
3
+ `,wi=`@namespace url(http://www.w3.org/1999/xhtml);@namespace epub url(http://www.idpf.org/2007/ops);@namespace m url(http://www.w3.org/1998/Math/MathML);@namespace svg url(http://www.w3.org/2000/svg);:root{--RS__compFontFamily:var(--RS__baseFontFamily);--RS__codeFontFamily:var(--RS__monospaceTf);--RS__typeScale:1.125;--RS__baseFontSize:100%;--RS__flowSpacing:1.5rem;--RS__paraSpacing:0;--RS__paraIndent:1em;--RS__linkColor:#0000EE;--RS__visitedColor:#551A8B;--RS__primaryColor:;--RS__secondaryColor:}body{font-size:var(--RS__baseFontSize)}h1,h2,h3,h4,h5,h6{font-family:var(--RS__compFontFamily)}blockquote,figure,p,pre,aside,footer,form,hr{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing)}p{margin-top:var(--RS__paraSpacing);margin-bottom:var(--RS__paraSpacing);text-indent:var(--RS__paraIndent)}h1+p,h2+p,h3+p,h4+p,h5+p,h6+p,hr+p{text-indent:0}pre{font-family:var(--RS__codeFontFamily)}code,kbd,samp,tt{font-family:var(--RS__codeFontFamily)}sub,sup{position:relative;font-size:67.5%;line-height:1}sub{bottom:-.2ex}sup{bottom:0}:link{color:var(--RS__linkColor)}:visited{color:var(--RS__visitedColor)}h1{margin-top:calc(var(--RS__flowSpacing) * 2);margin-bottom:calc(var(--RS__flowSpacing) * 2);font-size:calc(((1em * var(--RS__typeScale)) * var(--RS__typeScale)) * var(--RS__typeScale))}h2{margin-top:calc(var(--RS__flowSpacing) * 2);margin-bottom:var(--RS__flowSpacing);font-size:calc((1em * var(--RS__typeScale)) * var(--RS__typeScale))}h3{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing);font-size:calc(1em * var(--RS__typeScale))}h4{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing);font-size:1em}h5{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing);font-size:1em;font-variant:small-caps}h6{margin-top:var(--RS__flowSpacing);margin-bottom:0;font-size:1em;text-transform:lowercase;font-variant:small-caps}dl,ol,ul{margin-top:var(--RS__flowSpacing);margin-bottom:var(--RS__flowSpacing)}table{margin:var(--RS__flowSpacing) 0;border:1px solid currentcolor;border-collapse:collapse;empty-cells:show}thead,tbody,tfoot,table>tr{vertical-align:top}th{text-align:left}th,td{padding:4px;border:1px solid currentcolor}
4
+ `,$=(n,t)=>URL.createObjectURL(new Blob([n],{type:t})),Ye=n=>n.replace(/\/\/.*/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\n/g,"").replace(/\s+/g," "),Xt=n=>n.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g,"").replace(/ {2,}/g," ").replace(/url\((?!(https?:)?\/\/)("?)\/([^\)]+)/g,`url($2${window.location.origin}/$3`),Zt=(n,t)=>{const e=n.createElement("script");return e.dataset.readium="true",e.src=t.startsWith("blob:")?t:$(t,"text/javascript"),e},Kt=(n,t)=>{const e=n.createElement("link");return e.dataset.readium="true",e.rel="stylesheet",e.type="text/css",e.href=t.startsWith("blob:")?t:$(t,"text/css"),e},qt=new Map,ot=(n,t)=>{if(qt.has(n))return qt.get(n);const e=t();return qt.set(n,e),e},Ii=n=>Zt(n,ot("css-selector-generator",()=>$('!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports._readium_cssSelectorGenerator=e():t._readium_cssSelectorGenerator=e()}(self,(()=>(()=>{"use strict";var t,e,n={d:(t,e)=>{for(var o in e)n.o(e,o)&&!n.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:e[o]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},o={};function r(t){return t&&t instanceof Element}function i(t="unknown problem",...e){console.warn(`CssSelectorGenerator: ${t}`,...e)}n.r(o),n.d(o,{default:()=>z,getCssSelector:()=>U}),function(t){t.NONE="none",t.DESCENDANT="descendant",t.CHILD="child"}(t||(t={})),function(t){t.id="id",t.class="class",t.tag="tag",t.attribute="attribute",t.nthchild="nthchild",t.nthoftype="nthoftype"}(e||(e={}));const c={selectors:[e.id,e.class,e.tag,e.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY};function u(t){return t instanceof RegExp}function s(t){return["string","function"].includes(typeof t)||u(t)}function l(t){return Array.isArray(t)?t.filter(s):[]}function a(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return function(t){return t instanceof Node}(t)&&e.includes(t.nodeType)}function f(t,e){if(a(t))return t.contains(e)||i("element root mismatch","Provided root does not contain the element. This will most likely result in producing a fallback selector using element\'s real root node. If you plan to use the selector using provided root (e.g. `root.querySelector`), it will nto work as intended."),t;const n=e.getRootNode({composed:!1});return a(n)?(n!==document&&i("shadow root inferred","You did not provide a root and the element is a child of Shadow DOM. This will produce a selector using ShadowRoot as a root. If you plan to use the selector using document as a root (e.g. `document.querySelector`), it will not work as intended."),n):e.ownerDocument.querySelector(":root")}function d(t){return"number"==typeof t?t:Number.POSITIVE_INFINITY}function m(t=[]){const[e=[],...n]=t;return 0===n.length?e:n.reduce(((t,e)=>t.filter((t=>e.includes(t)))),e)}function p(t){return[].concat(...t)}function h(t){const e=t.map((t=>{if(u(t))return e=>t.test(e);if("function"==typeof t)return e=>{const n=t(e);return"boolean"!=typeof n?(i("pattern matcher function invalid","Provided pattern matching function does not return boolean. It\'s result will be ignored.",t),!1):n};if("string"==typeof t){const e=new RegExp("^"+t.replace(/[|\\\\{}()[\\]^$+?.]/g,"\\\\$&").replace(/\\*/g,".+")+"$");return t=>e.test(t)}return i("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1}));return t=>e.some((e=>e(t)))}function g(t,e,n){const o=Array.from(f(n,t[0]).querySelectorAll(e));return o.length===t.length&&t.every((t=>o.includes(t)))}function y(t,e){e=null!=e?e:function(t){return t.ownerDocument.querySelector(":root")}(t);const n=[];let o=t;for(;r(o)&&o!==e;)n.push(o),o=o.parentElement;return n}function b(t,e){return m(t.map((t=>y(t,e))))}const N={[t.NONE]:{type:t.NONE,value:""},[t.DESCENDANT]:{type:t.DESCENDANT,value:" > "},[t.CHILD]:{type:t.CHILD,value:" "}},S=new RegExp(["^$","\\\\s"].join("|")),E=new RegExp(["^$"].join("|")),w=[e.nthoftype,e.tag,e.id,e.class,e.attribute,e.nthchild],v=h(["class","id","ng-*"]);function C({nodeName:t}){return`[${t}]`}function O({nodeName:t,nodeValue:e}){return`[${t}=\'${L(e)}\']`}function T(t){const e=Array.from(t.attributes).filter((e=>function({nodeName:t},e){const n=e.tagName.toLowerCase();return!(["input","option"].includes(n)&&"value"===t||v(t))}(e,t)));return[...e.map(C),...e.map(O)]}function I(t){return(t.getAttribute("class")||"").trim().split(/\\s+/).filter((t=>!E.test(t))).map((t=>`.${L(t)}`))}function x(t){const e=t.getAttribute("id")||"",n=`#${L(e)}`,o=t.getRootNode({composed:!1});return!S.test(e)&&g([t],n,o)?[n]:[]}function j(t){const e=t.parentNode;if(e){const n=Array.from(e.childNodes).filter(r).indexOf(t);if(n>-1)return[`:nth-child(${n+1})`]}return[]}function A(t){return[L(t.tagName.toLowerCase())]}function D(t){const e=[...new Set(p(t.map(A)))];return 0===e.length||e.length>1?[]:[e[0]]}function $(t){const e=D([t])[0],n=t.parentElement;if(n){const o=Array.from(n.children).filter((t=>t.tagName.toLowerCase()===e)),r=o.indexOf(t);if(r>-1)return[`${e}:nth-of-type(${r+1})`]}return[]}function R(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){const n=[];let o=0,r=k(1);for(;r.length<=t.length&&o<e;)o+=1,n.push(r.map((e=>t[e]))),r=P(r,t.length-1);return n}function P(t=[],e=0){const n=t.length;if(0===n)return[];const o=[...t];o[n-1]+=1;for(let t=n-1;t>=0;t--)if(o[t]>e){if(0===t)return k(n+1);o[t-1]++,o[t]=o[t-1]+1}return o[n-1]>e?k(n+1):o}function k(t=1){return Array.from(Array(t).keys())}const _=":".charCodeAt(0).toString(16).toUpperCase(),M=/[ !"#$%&\'()\\[\\]{|}<>*+,./;=?@^`~\\\\]/;function L(t=""){var e,n;return null!==(n=null===(e=null===CSS||void 0===CSS?void 0:CSS.escape)||void 0===e?void 0:e.call(CSS,t))&&void 0!==n?n:function(t=""){return t.split("").map((t=>":"===t?`\\\\${_} `:M.test(t)?`\\\\${t}`:escape(t).replace(/%/g,"\\\\"))).join("")}(t)}const q={tag:D,id:function(t){return 0===t.length||t.length>1?[]:x(t[0])},class:function(t){return m(t.map(I))},attribute:function(t){return m(t.map(T))},nthchild:function(t){return m(t.map(j))},nthoftype:function(t){return m(t.map($))}},F={tag:A,id:x,class:I,attribute:T,nthchild:j,nthoftype:$};function V(t){return t.includes(e.tag)||t.includes(e.nthoftype)?[...t]:[...t,e.tag]}function Y(t={}){const n=[...w];return t[e.tag]&&t[e.nthoftype]&&n.splice(n.indexOf(e.tag),1),n.map((e=>{return(o=t)[n=e]?o[n].join(""):"";var n,o})).join("")}function B(t,e,n="",o){const r=function(t,e){return""===e?t:function(t,e){return[...t.map((t=>e+" "+t)),...t.map((t=>e+" > "+t))]}(t,e)}(function(t,e,n){const o=function(t,e){const{blacklist:n,whitelist:o,combineWithinSelector:r,maxCombinations:i}=e,c=h(n),u=h(o);return function(t){const{selectors:e,includeTag:n}=t,o=[].concat(e);return n&&!o.includes("tag")&&o.push("tag"),o}(e).reduce(((e,n)=>{const o=function(t,e){var n;return(null!==(n=q[e])&&void 0!==n?n:()=>[])(t)}(t,n),s=function(t=[],e,n){return t.filter((t=>n(t)||!e(t)))}(o,c,u),l=function(t=[],e){return t.sort(((t,n)=>{const o=e(t),r=e(n);return o&&!r?-1:!o&&r?1:0}))}(s,u);return e[n]=r?R(l,{maxResults:i}):l.map((t=>[t])),e}),{})}(t,n),r=function(t,e){return function(t){const{selectors:e,combineBetweenSelectors:n,includeTag:o,maxCandidates:r}=t,i=n?R(e,{maxResults:r}):e.map((t=>[t]));return o?i.map(V):i}(e).map((e=>function(t,e){const n={};return t.forEach((t=>{const o=e[t];o.length>0&&(n[t]=o)})),function(t={}){let e=[];return Object.entries(t).forEach((([t,n])=>{e=n.flatMap((n=>0===e.length?[{[t]:n}]:e.map((e=>Object.assign(Object.assign({},e),{[t]:n})))))})),e}(n).map(Y)}(e,t))).filter((t=>t.length>0))}(o,n),i=p(r);return[...new Set(i)]}(t,o.root,o),n);for(const e of r)if(g(t,e,o.root))return e;return null}function G(t){return{value:t,include:!1}}function W({selectors:t,operator:n}){let o=[...w];t[e.tag]&&t[e.nthoftype]&&(o=o.filter((t=>t!==e.tag)));let r="";return o.forEach((e=>{(t[e]||[]).forEach((({value:t,include:e})=>{e&&(r+=t)}))})),n.value+r}function H(n){return[":root",...y(n).reverse().map((n=>{const o=function(e,n,o=t.NONE){const r={};return n.forEach((t=>{Reflect.set(r,t,function(t,e){return F[e](t)}(e,t).map(G))})),{element:e,operator:N[o],selectors:r}}(n,[e.nthchild],t.DESCENDANT);return o.selectors.nthchild.forEach((t=>{t.include=!0})),o})).map(W)].join("")}function U(t,n={}){const o=function(t){const e=(Array.isArray(t)?t:[t]).filter(r);return[...new Set(e)]}(t),i=function(t,n={}){const o=Object.assign(Object.assign({},c),n);return{selectors:(r=o.selectors,Array.isArray(r)?r.filter((t=>{return n=e,o=t,Object.values(n).includes(o);var n,o})):[]),whitelist:l(o.whitelist),blacklist:l(o.blacklist),root:f(o.root,t),combineWithinSelector:!!o.combineWithinSelector,combineBetweenSelectors:!!o.combineBetweenSelectors,includeTag:!!o.includeTag,maxCombinations:d(o.maxCombinations),maxCandidates:d(o.maxCandidates)};var r}(o[0],n);let u="",s=i.root;function a(){return function(t,e,n="",o){if(0===t.length)return null;const r=[t.length>1?t:[],...b(t,e).map((t=>[t]))];for(const t of r){const e=B(t,0,n,o);if(e)return{foundElements:t,selector:e}}return null}(o,s,u,i)}let m=a();for(;m;){const{foundElements:t,selector:e}=m;if(g(o,e,i.root))return e;s=t[0],u=e,m=a()}return o.length>1?o.map((t=>U(t,i))).join(", "):function(t){return t.map(H).join(", ")}(o)}const z=U;return o})()));',"text/javascript"))),Fi=n=>Zt(n,ot("JS-Before",()=>$(Ye(`
5
5
  window._readium_blockedEvents = [];
6
6
  window._readium_blockEvents = true;
7
7
  window._readium_eventBlocker = (e) => {
@@ -13,7 +13,7 @@
13
13
  ]);
14
14
  };
15
15
  window.addEventListener("DOMContentLoaded", window._readium_eventBlocker, true);
16
- window.addEventListener("load", window._readium_eventBlocker, true);`),"text/javascript"))),oi=i=>DA(i,tA("JS-After",()=>k(mt(`
16
+ window.addEventListener("load", window._readium_eventBlocker, true);`),"text/javascript"))),Ui=n=>Zt(n,ot("JS-After",()=>$(Ye(`
17
17
  if(window.onload) window.onload = new Proxy(window.onload, {
18
18
  apply: function(target, receiver, args) {
19
19
  if(!window._readium_blockEvents) {
@@ -24,21 +24,21 @@
24
24
  0, target, receiver, args
25
25
  ]);
26
26
  }
27
- });`),"text/javascript")));class Bt{constructor(A,t,e){this.pub=A,this.item=e,this.burl=e.toURL(t)||""}async build(A=!1){if(this.item.mediaType.isHTML)return await this.buildHtmlFrame(A);if(this.item.mediaType.isBitmap)return this.buildImageFrame();throw Error("Unsupported frame mediatype "+this.item.mediaType.string)}async buildHtmlFrame(A=!1){const t=await this.pub.get(this.item).readAsString();if(!t)throw new Error(`Failed reading item ${this.item.href}`);const e=new DOMParser().parseFromString(t,this.item.mediaType.string),n=e.querySelector("parsererror");if(n){const r=n.querySelector("div");throw new Error(`Failed parsing item ${this.item.href}: ${(r==null?void 0:r.textContent)||n.textContent}`)}return this.finalizeDOM(e,this.burl,this.item.mediaType,A)}buildImageFrame(){const A=document.implementation.createHTMLDocument(this.item.title||this.item.href),t=document.createElement("img");return t.src=this.burl||"",t.alt=this.item.title||"",t.decoding="async",A.body.appendChild(t),this.finalizeDOM(A,this.burl,this.item.mediaType,!0)}hasExecutable(A){return!!A.querySelector("script")||!!A.querySelector("body[onload]:not(body[onload=''])")}hasStyle(A){return!!(A.querySelector("link[rel='stylesheet']")||A.querySelector("style")||A.querySelector("[style]:not([style=''])"))}finalizeDOM(A,t,e,n=!1){if(!A)return"";if(!n){const s=HA(A,tA("ReadiumCSS-before",()=>k(VA(ii),"text/css")));A.head.firstChild?A.head.firstChild.before(s):A.head.appendChild(s);const o=A.createElement("style");o.dataset.readium="true",o.innerHTML="audio[controls] { width: revert; height: revert; }",s.after(o),this.hasStyle(A)||s.after(HA(A,tA("ReadiumCSS-default",()=>k(VA(ni),"text/css")))),A.head.appendChild(HA(A,tA("ReadiumCSS-after",()=>k(VA(ei),"text/css"))))}if(A.body.querySelectorAll("img").forEach(s=>{s.setAttribute("fetchpriority","high")}),t!==void 0){const s=A.createElement("base");s.href=t,s.dataset.readium="true",A.head.firstChild.before(s)}const r=this.hasExecutable(A);return r&&A.head.firstChild.before(si(A)),A.head.firstChild.before(ri(A)),r&&A.head.appendChild(oi(A)),URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(A)],{type:e.isHTML?e.string:"application/xhtml+xml"}))}}const ai=Math.pow(2,32),Et=()=>Math.round(Math.random()*ai).toString(36),vA=()=>`${Math.round(performance.now())}-${Et()}-${Et()}`,eA=1;class hi{constructor(A){this.destination=null,this.registrar=new Map,this.origin="",this.channelId="",this.receiver=this.receive.bind(this),this.preLog=[],this.wnd=A,A.addEventListener("message",this.receiver)}receive(A){if(A.source===null)throw Error("Event source is null");if(typeof A.data!="object")return;const t=A.data;if(!(!("_readium"in t)||!t._readium||t._readium<=0)){if(t.key==="_ping"){if(!this.destination){if(this.destination=A.source,this.origin=A.origin,this.channelId=t._channel,t._readium!==eA){t._readium>eA?this.send("error",`received comms version ${t._readium} higher than ${eA}`):this.send("error",`received comms version ${t._readium} lower than ${eA}`),this.destination=null,this.origin="",this.channelId="";return}this.send("_pong",void 0),this.preLog.forEach(e=>this.send("log",e)),this.preLog=[]}return}else if(this.channelId){if(t._channel!==this.channelId||A.origin!==this.origin)return}else return;this.handle(t)}}handle(A){const t=this.registrar.get(A.key);if(!t||t.length===0){A.strict&&this.send("_unhandled",A);return}t.forEach(e=>e.cb(A.data,n=>{this.send("_ack",n,A.id)}))}register(A,t,e){Array.isArray(A)||(A=[A]),A.forEach(n=>{const r=this.registrar.get(n);if(r&&r.length>=0){if(r.find(s=>s.module===t))throw new Error(`Trying to register another callback for combination of event ${n} and module ${t}`);r.push({cb:e,module:t}),this.registrar.set(n,r)}else this.registrar.set(n,[{cb:e,module:t}])})}unregister(A,t){Array.isArray(A)||(A=[A]),A.forEach(e=>{const n=this.registrar.get(e);!n||n.length===0||n.splice(n.findIndex(r=>r.module===t),1)})}unregisterAll(A){this.registrar.forEach((t,e)=>this.registrar.set(e,t.filter(n=>n.module!==A)))}log(...A){this.destination?this.send("log",A):this.preLog.push(A)}get ready(){return!!this.destination}destroy(){this.destination=null,this.channelId="",this.preLog=[],this.registrar.clear(),this.wnd.removeEventListener("message",this.receiver)}send(A,t,e=void 0,n=[]){if(!this.destination)throw Error("Attempted to send comms message before destination has been initialized");const r={_readium:eA,_channel:this.channelId,id:e??vA(),key:A,data:t};try{this.destination.postMessage(r,{targetOrigin:this.origin,transfer:n})}catch(s){if(n.length>0)throw s;this.destination.postMessage(r,this.origin,n)}}}class bA{constructor(A){this.algorithm=A.algorithm,this.compression=A.compression,this.originalLength=A.originalLength,this.profile=A.profile,this.scheme=A.scheme}static deserialize(A){if(A&&A.algorithm)return new bA({algorithm:A.algorithm,compression:A.compression,originalLength:A.originalLength,profile:A.profile,scheme:A.scheme})}serialize(){const A={algorithm:this.algorithm};return this.compression!==void 0&&(A.compression=this.compression),this.originalLength!==void 0&&(A.originalLength=this.originalLength),this.profile!==void 0&&(A.profile=this.profile),this.scheme!==void 0&&(A.scheme=this.scheme),A}}class y{constructor(A){this.otherProperties=A}static deserialize(A){if(A)return new y(A)}serialize(){return this.otherProperties}add(A){const t=Object.assign({},this.otherProperties);for(const e in A)t[e]=A[e];return new y(t)}}Object.defineProperty(y.prototype,"encryption",{get:function(){return bA.deserialize(this.otherProperties.encrypted)}}),y.prototype.getContains=function(){return new Set(this.otherProperties.contains||[])},y.prototype.getLayout=function(){return this.otherProperties.layout};class M{constructor(A){let t,e,n=A.mediaType.replace(/\s/g,"").split(";");const r=n[0].split("/");if(r.length===2){if(t=r[0].toLowerCase().trim(),e=r[1].toLowerCase().trim(),t.length===0||e.length===0)throw new Error("Invalid media type")}else throw new Error("Invalid media type");const s={};for(let g=1;g<n.length;g++){const u=n[g].split("=");if(u.length===2){const m=u[0].toLocaleLowerCase(),B=m==="charset"?u[1].toUpperCase():u[1];s[m]=B}}const o={},a=Object.keys(s);a.sort((g,u)=>g.localeCompare(u)),a.forEach(g=>o[g]=s[g]);let h="";for(const g in o){const u=o[g];h+=`;${g}=${u}`}const c=`${t}/${e}${h}`,l=o.encoding;this.string=c,this.type=t,this.subtype=e,this.parameters=o,this.encoding=l,this.name=A.name,this.fileExtension=A.fileExtension}static parse(A){return new M(A)}get structuredSyntaxSuffix(){const A=this.subtype.split("+");return A.length>1?`+${A[A.length-1]}`:void 0}get charset(){return this.parameters.charset}contains(A){const t=typeof A=="string"?M.parse({mediaType:A}):A;if(!((this.type==="*"||this.type===t.type)&&(this.subtype==="*"||this.subtype===t.subtype)))return!1;const e=new Set(Object.entries(this.parameters).map(([r,s])=>`${r}=${s}`)),n=new Set(Object.entries(t.parameters).map(([r,s])=>`${r}=${s}`));for(const r of Array.from(e.values()))if(!n.has(r))return!1;return!0}matches(A){const t=typeof A=="string"?M.parse({mediaType:A}):A;return this.contains(t)||t.contains(this)}matchesAny(...A){for(const t of A)if(this.matches(t))return!0;return!1}equals(A){return this.string===A.string}get isZIP(){return this.matchesAny(M.ZIP,M.LCP_PROTECTED_AUDIOBOOK,M.LCP_PROTECTED_PDF)||this.structuredSyntaxSuffix==="+zip"}get isJSON(){return this.matchesAny(M.JSON)||this.structuredSyntaxSuffix==="+json"}get isOPDS(){return this.matchesAny(M.OPDS1,M.OPDS1_ENTRY,M.OPDS2,M.OPDS2_PUBLICATION,M.OPDS_AUTHENTICATION)||this.structuredSyntaxSuffix==="+json"}get isHTML(){return this.matchesAny(M.HTML,M.XHTML)}get isBitmap(){return this.matchesAny(M.BMP,M.GIF,M.JPEG,M.PNG,M.TIFF,M.WEBP)}get isAudio(){return this.type==="audio"}get isVideo(){return this.type==="video"}get isRWPM(){return this.matchesAny(M.READIUM_AUDIOBOOK_MANIFEST,M.DIVINA_MANIFEST,M.READIUM_WEBPUB_MANIFEST)}get isPublication(){return this.matchesAny(M.READIUM_AUDIOBOOK,M.READIUM_AUDIOBOOK_MANIFEST,M.CBZ,M.DIVINA,M.DIVINA_MANIFEST,M.EPUB,M.LCP_PROTECTED_AUDIOBOOK,M.LCP_PROTECTED_PDF,M.LPF,M.PDF,M.W3C_WPUB_MANIFEST,M.READIUM_WEBPUB,M.READIUM_WEBPUB_MANIFEST,M.ZAB)}static get AAC(){return M.parse({mediaType:"audio/aac",fileExtension:"aac"})}static get ACSM(){return M.parse({mediaType:"application/vnd.adobe.adept+xml",name:"Adobe Content Server Message",fileExtension:"acsm"})}static get AIFF(){return M.parse({mediaType:"audio/aiff",fileExtension:"aiff"})}static get AVI(){return M.parse({mediaType:"video/x-msvideo",fileExtension:"avi"})}static get BINARY(){return M.parse({mediaType:"application/octet-stream"})}static get BMP(){return M.parse({mediaType:"image/bmp",fileExtension:"bmp"})}static get CBZ(){return M.parse({mediaType:"application/vnd.comicbook+zip",name:"Comic Book Archive",fileExtension:"cbz"})}static get CSS(){return M.parse({mediaType:"text/css",fileExtension:"css"})}static get DIVINA(){return M.parse({mediaType:"application/divina+zip",name:"Digital Visual Narratives",fileExtension:"divina"})}static get DIVINA_MANIFEST(){return M.parse({mediaType:"application/divina+json",name:"Digital Visual Narratives",fileExtension:"json"})}static get EPUB(){return M.parse({mediaType:"application/epub+zip",name:"EPUB",fileExtension:"epub"})}static get GIF(){return M.parse({mediaType:"image/gif",fileExtension:"gif"})}static get GZ(){return M.parse({mediaType:"application/gzip",fileExtension:"gz"})}static get HTML(){return M.parse({mediaType:"text/html",fileExtension:"html"})}static get JAVASCRIPT(){return M.parse({mediaType:"text/javascript",fileExtension:"js"})}static get JPEG(){return M.parse({mediaType:"image/jpeg",fileExtension:"jpeg"})}static get JSON(){return M.parse({mediaType:"application/json"})}static get LCP_LICENSE_DOCUMENT(){return M.parse({mediaType:"application/vnd.readium.lcp.license.v1.0+json",name:"LCP License",fileExtension:"lcpl"})}static get LCP_PROTECTED_AUDIOBOOK(){return M.parse({mediaType:"application/audiobook+lcp",name:"LCP Protected Audiobook",fileExtension:"lcpa"})}static get LCP_PROTECTED_PDF(){return M.parse({mediaType:"application/pdf+lcp",name:"LCP Protected PDF",fileExtension:"lcpdf"})}static get LCP_STATUS_DOCUMENT(){return M.parse({mediaType:"application/vnd.readium.license.status.v1.0+json"})}static get LPF(){return M.parse({mediaType:"application/lpf+zip",fileExtension:"lpf"})}static get MP3(){return M.parse({mediaType:"audio/mpeg",fileExtension:"mp3"})}static get MPEG(){return M.parse({mediaType:"video/mpeg",fileExtension:"mpeg"})}static get NCX(){return M.parse({mediaType:"application/x-dtbncx+xml",fileExtension:"ncx"})}static get OGG(){return M.parse({mediaType:"audio/ogg",fileExtension:"oga"})}static get OGV(){return M.parse({mediaType:"video/ogg",fileExtension:"ogv"})}static get OPDS1(){return M.parse({mediaType:"application/atom+xml;profile=opds-catalog"})}static get OPDS1_ENTRY(){return M.parse({mediaType:"application/atom+xml;type=entry;profile=opds-catalog"})}static get OPDS2(){return M.parse({mediaType:"application/opds+json"})}static get OPDS2_PUBLICATION(){return M.parse({mediaType:"application/opds-publication+json"})}static get OPDS_AUTHENTICATION(){return M.parse({mediaType:"application/opds-authentication+json"})}static get OPUS(){return M.parse({mediaType:"audio/opus",fileExtension:"opus"})}static get OTF(){return M.parse({mediaType:"font/otf",fileExtension:"otf"})}static get PDF(){return M.parse({mediaType:"application/pdf",name:"PDF",fileExtension:"pdf"})}static get PNG(){return M.parse({mediaType:"image/png",fileExtension:"png"})}static get READIUM_AUDIOBOOK(){return M.parse({mediaType:"application/audiobook+zip",name:"Readium Audiobook",fileExtension:"audiobook"})}static get READIUM_AUDIOBOOK_MANIFEST(){return M.parse({mediaType:"application/audiobook+json",name:"Readium Audiobook",fileExtension:"json"})}static get READIUM_CONTENT_DOCUMENT(){return M.parse({mediaType:"application/vnd.readium.content+json",name:"Readium Content Document",fileExtension:"json"})}static get READIUM_GUIDED_NAVIGATION_DOCUMENT(){return M.parse({mediaType:"application/guided-navigation+json",name:"Readium Guided Navigation Document",fileExtension:"json"})}static get READIUM_POSITION_LIST(){return M.parse({mediaType:"application/vnd.readium.position-list+json",name:"Readium Position List",fileExtension:"json"})}static get READIUM_WEBPUB(){return M.parse({mediaType:"application/webpub+zip",name:"Readium Web Publication",fileExtension:"webpub"})}static get READIUM_WEBPUB_MANIFEST(){return M.parse({mediaType:"application/webpub+json",name:"Readium Web Publication",fileExtension:"json"})}static get SMIL(){return M.parse({mediaType:"application/smil+xml",fileExtension:"smil"})}static get SVG(){return M.parse({mediaType:"image/svg+xml",fileExtension:"svg"})}static get TEXT(){return M.parse({mediaType:"text/plain",fileExtension:"txt"})}static get TIFF(){return M.parse({mediaType:"image/tiff",fileExtension:"tiff"})}static get TTF(){return M.parse({mediaType:"font/ttf",fileExtension:"ttf"})}static get W3C_WPUB_MANIFEST(){return M.parse({mediaType:"application/x.readium.w3c.wpub+json",name:"Web Publication",fileExtension:"json"})}static get WAV(){return M.parse({mediaType:"audio/wav",fileExtension:"wav"})}static get WEBM_AUDIO(){return M.parse({mediaType:"audio/webm",fileExtension:"webm"})}static get WEBM_VIDEO(){return M.parse({mediaType:"video/webm",fileExtension:"webm"})}static get WEBP(){return M.parse({mediaType:"image/webp",fileExtension:"webp"})}static get WOFF(){return M.parse({mediaType:"font/woff",fileExtension:"woff"})}static get WOFF2(){return M.parse({mediaType:"font/woff2",fileExtension:"woff2"})}static get XHTML(){return M.parse({mediaType:"application/xhtml+xml",fileExtension:"xhtml"})}static get XML(){return M.parse({mediaType:"application/xml",fileExtension:"xml"})}static get ZAB(){return M.parse({mediaType:"application/x.readium.zab+zip",name:"Zipped Audio Book",fileExtension:"zab"})}static get ZIP(){return M.parse({mediaType:"application/zip",fileExtension:"zip"})}}class ft{constructor(A){this.uri=A,this.parameters=this.getParameters(A)}getParameters(A){const t=/\{\??([^}]+)\}/g,e=A.match(t);return e?new Set(e.join(",").replace(t,"$1").split(",").map(n=>n.trim())):new Set}expand(A){const t=n=>n.split(",").map(r=>{const s=A[r];return s?encodeURIComponent(s):""}).join(","),e=n=>"?"+n.split(",").map(r=>{const s=r.split("=")[0],o=A[s];return o?`${s}=${encodeURIComponent(o)}`:""}).join("&");return this.uri.replace(/\{(\??)([^}]+)\}/g,(...n)=>n[1]?e(n[2]):t(n[2]))}}function ci(i){return i&&i instanceof Array?i:void 0}function It(i){return i&&typeof i=="string"?[i]:ci(i)}function pt(i){return typeof i=="string"?new Date(i):void 0}function EA(i){return isNaN(i)?void 0:i}function x(i){return EA(i)!==void 0&&Math.sign(i)>=0?i:void 0}function li(i){const A=new Array;return i.forEach(t=>A.push(t)),A}class R{constructor(A){this.fragments=A.fragments?A.fragments:new Array,this.progression=A.progression,this.totalProgression=A.totalProgression,this.position=A.position,this.otherLocations=A.otherLocations}static deserialize(A){if(!A)return;const t=EA(A.progression),e=EA(A.totalProgression),n=EA(A.position),r=new Map,s=new Set(["fragment","fragments","progression","totalProgression","position"]);return Object.entries(A).forEach(([o,a])=>{s.has(o)||r.set(o,a)}),new R({fragments:It(A.fragments||A.fragment),progression:t!==void 0&&t>=0&&t<=1?t:void 0,totalProgression:e!==void 0&&e>=0&&e<=1?e:void 0,position:n!==void 0&&n>0?n:void 0,otherLocations:r.size===0?void 0:r})}serialize(){const A={};return this.fragments&&(A.fragments=this.fragments),this.progression!==void 0&&(A.progression=this.progression),this.totalProgression!==void 0&&(A.totalProgression=this.totalProgression),this.position!==void 0&&(A.position=this.position),this.otherLocations&&this.otherLocations.forEach((t,e)=>A[e]=t),A}}class iA{constructor(A){this.after=A.after,this.before=A.before,this.highlight=A.highlight}static deserialize(A){if(A)return new iA({after:A.after,before:A.before,highlight:A.highlight})}serialize(){const A={};return this.after!==void 0&&(A.after=this.after),this.before!==void 0&&(A.before=this.before),this.highlight!==void 0&&(A.highlight=this.highlight),A}}class W{constructor(A){this.href=A.href,this.type=A.type,this.title=A.title,this.locations=A.locations?A.locations:new R({}),this.text=A.text}static deserialize(A){if(A&&A.href&&A.type)return new W({href:A.href,type:A.type,title:A.title,locations:R.deserialize(A.locations),text:iA.deserialize(A.text)})}serialize(){const A={href:this.href,type:this.type};return this.title!==void 0&&(A.title=this.title),this.locations&&(A.locations=this.locations.serialize()),this.text&&(A.text=this.text.serialize()),A}copyWithLocations(A){return new W({href:this.href,type:this.type,title:this.title,text:this.text,locations:new R({...this.locations,...A})})}}class nA{constructor(A){this.href=A.href,this.templated=A.templated,this.type=A.type,this.title=A.title,this.rels=A.rels,this.properties=A.properties,this.height=A.height,this.width=A.width,this.duration=A.duration,this.bitrate=A.bitrate,this.languages=A.languages,this.alternates=A.alternates,this.children=A.children}static deserialize(A){if(A&&A.href&&typeof A.href=="string")return new nA({href:A.href,templated:A.templated,type:A.type,title:A.title,rels:A.rel?A.rel instanceof Array?new Set(A.rel):new Set([A.rel]):void 0,properties:y.deserialize(A.properties),height:x(A.height),width:x(A.width),duration:x(A.duration),bitrate:x(A.bitrate),languages:It(A.language),alternates:fA.deserialize(A.alternate),children:fA.deserialize(A.children)})}serialize(){const A={href:this.href};return this.templated!==void 0&&(A.templated=this.templated),this.type!==void 0&&(A.type=this.type),this.title!==void 0&&(A.title=this.title),this.rels&&(A.rel=li(this.rels)),this.properties&&(A.properties=this.properties.serialize()),this.height!==void 0&&(A.height=this.height),this.width!==void 0&&(A.width=this.width),this.duration!==void 0&&(A.duration=this.duration),this.bitrate!==void 0&&(A.bitrate=this.bitrate),this.languages&&(A.language=this.languages),this.alternates&&(A.alternate=this.alternates.serialize()),this.children&&(A.children=this.children.serialize()),A}get mediaType(){return this.type!==void 0?M.parse({mediaType:this.type}):M.BINARY}toURL(A){const t=this.href.replace(/^(\/)/,"");if(t.length===0)return;let e=A||"/";return e.startsWith("/")&&(e="file://"+e),new URL(t,e).href.replace(/^(file:\/\/)/,"")}get templateParameters(){return this.templated?new ft(this.href).parameters:new Set}expandTemplate(A){return new nA({href:new ft(this.href).expand(A),templated:!1})}addProperties(A){var t;const e=nA.deserialize(this.serialize());return e.properties=e.properties?(t=e.properties)==null?void 0:t.add(A):new y(A),e}get locator(){let A=this.href.split("#");return new W({href:A.length>0&&A[0]!==void 0?A[0]:this.href,type:this.type??"",title:this.title,locations:new R({fragments:A.length>1&&A[1]!==void 0?[A[1]]:[]})})}}class fA{constructor(A){this.items=A}static deserialize(A){if(A&&A instanceof Array)return new fA(A.map(t=>nA.deserialize(t)).filter(t=>t!==void 0))}serialize(){return this.items.map(A=>A.serialize())}findWithRel(A){const t=e=>e.rels&&e.rels.has(A);return this.items.find(t)}filterByRel(A){const t=e=>e.rels&&e.rels.has(A);return this.items.filter(t)}findWithHref(A){const t=e=>e.href===A;return this.items.find(t)}findIndexWithHref(A){const t=e=>e.href===A;return this.items.findIndex(t)}findWithMediaType(A){const t=e=>e.mediaType.matches(A);return this.items.find(t)}filterByMediaType(A){const t=e=>e.mediaType.matches(A);return this.items.filter(t)}filterByMediaTypes(A){const t=e=>{for(const n of A)if(e.mediaType.matches(n))return!0;return!1};return this.items.filter(t)}everyIsAudio(){const A=t=>t.mediaType.isAudio;return this.items.length>0&&this.items.every(A)}everyIsBitmap(){const A=t=>t.mediaType.isBitmap;return this.items.length>0&&this.items.every(A)}everyIsHTML(){const A=t=>t.mediaType.isHTML;return this.items.length>0&&this.items.every(A)}everyIsVideo(){const A=t=>t.mediaType.isVideo;return this.items.length>0&&this.items.every(A)}everyMatchesMediaType(A){return Array.isArray(A)?this.items.length>0&&this.items.every(t=>{for(const e of A)return t.mediaType.matches(e);return!1}):this.items.length>0&&this.items.every(t=>t.mediaType.matches(A))}filterLinksHasType(){return this.items.filter(A=>A.type)}}class IA{constructor(A){this.cssSelector=A.cssSelector,this.textNodeIndex=A.textNodeIndex,this.charOffset=A.charOffset}static deserialize(A){if(!(A&&A.cssSelector))return;let t=x(A.textNodeIndex);if(t===void 0)return;let e=x(A.charOffset);return e===void 0&&(e=x(A.offset)),new IA({cssSelector:A.cssSelector,textNodeIndex:t,charOffset:e})}serialize(){const A={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(A.charOffset=this.charOffset),A}}class JA{constructor(A){this.start=A.start,this.end=A.end}static deserialize(A){if(!A)return;let t=IA.deserialize(A.start);if(t)return new JA({start:t,end:IA.deserialize(A.end)})}serialize(){const A={start:this.start.serialize()};return this.end&&(A.end=this.end.serialize()),A}}R.prototype.getCssSelector=function(){var i;return(i=this.otherLocations)==null?void 0:i.get("cssSelector")},R.prototype.getPartialCfi=function(){var i;return(i=this.otherLocations)==null?void 0:i.get("partialCfi")},R.prototype.getDomRange=function(){var i;return JA.deserialize((i=this.otherLocations)==null?void 0:i.get("domRange"))},R.prototype.fragmentParameters=function(){return new Map(this.fragments.map(i=>i.startsWith("#")?i.slice(1):i).join("&").split("&").filter(i=>!i.startsWith("#")).map(i=>i.split("=")).filter(i=>i.length===2).map(i=>[i[0].trim().toLowerCase(),i[1].trim()]))},R.prototype.htmlId=function(){if(!this.fragments.length)return;let i=this.fragments.find(A=>A.length&&!A.includes("="));if(!i){const A=this.fragmentParameters();A.has("id")?i=A.get("id"):A.has("name")&&(i=A.get("name"))}return i!=null&&i.startsWith("#")?i.slice(1):i},R.prototype.page=function(){const i=parseInt(this.fragmentParameters().get("page"));if(!isNaN(i)&&i>=0)return i},R.prototype.time=function(){const i=parseInt(this.fragmentParameters().get("t"));if(!isNaN(i))return i},R.prototype.space=function(){const i=this.fragmentParameters();if(!i.has("xywh"))return;const A=i.get("xywh").split(",").map(t=>parseInt(t));if(A.length===4&&!A.some(isNaN))return A};class PA{constructor(A){this.currency=A.currency,this.value=A.value}static deserialize(A){if(!A)return;let t=A.currency;if(!(t&&typeof t=="string"&&t.length>0))return;let e=x(A.value);if(e!==void 0)return new PA({currency:t,value:e})}serialize(){return{currency:this.currency,value:this.value}}}class lA{constructor(A){this.type=A.type,this.children=A.children}static deserialize(A){if(A&&A.type)return new lA({type:A.type,children:lA.deserializeArray(A.children)})}static deserializeArray(A){if(A instanceof Array)return A.map(t=>lA.deserialize(t)).filter(t=>t!==void 0)}serialize(){const A={type:this.type};return this.children&&(A.children=this.children.map(t=>t.serialize())),A}}class kA{constructor(A){this.total=A.total,this.position=A.position}static deserialize(A){if(A)return new kA({total:x(A.total),position:x(A.position)})}serialize(){const A={};return this.total!==void 0&&(A.total=this.total),this.position!==void 0&&(A.position=this.position),A}}class WA{constructor(A){this.total=A.total,this.available=A.available}static deserialize(A){if(A)return new WA({total:x(A.total),available:x(A.available)})}serialize(){const A={};return this.total!==void 0&&(A.total=this.total),this.available!==void 0&&(A.available=this.available),A}}class LA{constructor(A){this.state=A.state,this.since=A.since,this.until=A.until}static deserialize(A){if(A&&A.state)return new LA({state:A.state,since:pt(A.since),until:pt(A.until)})}serialize(){const A={state:this.state};return this.since!==void 0&&(A.since=this.since.toISOString()),this.until!==void 0&&(A.until=this.until.toISOString()),A}}y.prototype.getNumberOfItems=function(){return x(this.otherProperties.numberOfItems)},y.prototype.getPrice=function(){return PA.deserialize(this.otherProperties.price)},y.prototype.getIndirectAcquisitions=function(){const i=this.otherProperties.indirectAcquisition;if(i&&i instanceof Array)return i.map(A=>lA.deserialize(A)).filter(A=>A!==void 0)},y.prototype.getHolds=function(){return kA.deserialize(this.otherProperties.holds)},y.prototype.getCopies=function(){return WA.deserialize(this.otherProperties.copies)},y.prototype.getAvailability=function(){return LA.deserialize(this.otherProperties.availability)},y.prototype.getAuthenticate=function(){return nA.deserialize(this.otherProperties.authenticate)},y.prototype.getClipped=function(){return this.otherProperties.clipped},y.prototype.getFit=function(){return this.otherProperties.fit},y.prototype.getOrientation=function(){return this.otherProperties.orientation},y.prototype.getOverflow=function(){return this.otherProperties.overflow},y.prototype.getPage=function(){return this.otherProperties.page||void 0},y.prototype.getSpread=function(){return this.otherProperties.spread||void 0};class pA{}function wt(i){return i.split("").reverse().join("")}function gi(i,A,t){const e=wt(A);return t.map(n=>{const r=Math.max(0,n.end-A.length-n.errors),s=wt(i.slice(r,n.end));return{start:Ut(s,e,n.errors).reduce((o,a)=>n.end-a.end<o?n.end-a.end:o,n.end),end:n.end,errors:n.errors}})}function OA(i){return(i|-i)>>31&1}function Ft(i,A,t,e){let n=i.P[t],r=i.M[t];const s=e>>>31,o=A[t]|s,a=o|r,h=(o&n)+n^n|o;let c=r|~(h|n),l=n&h;const g=OA(c&i.lastRowMask[t])-OA(l&i.lastRowMask[t]);return c<<=1,l<<=1,l|=s,c|=OA(e)-s,n=l|~(a|c),r=c&a,i.P[t]=n,i.M[t]=r,g}function Ut(i,A,t){if(A.length===0)return[];t=Math.min(t,A.length);const e=[],n=32,r=Math.ceil(A.length/n)-1,s={P:new Uint32Array(r+1),M:new Uint32Array(r+1),lastRowMask:new Uint32Array(r+1)};s.lastRowMask.fill(1<<31),s.lastRowMask[r]=1<<(A.length-1)%n;const o=new Uint32Array(r+1),a=new Map,h=[];for(let g=0;g<256;g++)h.push(o);for(let g=0;g<A.length;g+=1){const u=A.charCodeAt(g);if(a.has(u))continue;const m=new Uint32Array(r+1);a.set(u,m),u<h.length&&(h[u]=m);for(let B=0;B<=r;B+=1){m[B]=0;for(let f=0;f<n;f+=1){const E=B*n+f;E>=A.length||A.charCodeAt(E)===u&&(m[B]|=1<<f)}}}let c=Math.max(0,Math.ceil(t/n)-1);const l=new Uint32Array(r+1);for(let g=0;g<=c;g+=1)l[g]=(g+1)*n;l[r]=A.length;for(let g=0;g<=c;g+=1)s.P[g]=-1,s.M[g]=0;for(let g=0;g<i.length;g+=1){const u=i.charCodeAt(g);let m;u<h.length?m=h[u]:(m=a.get(u),typeof m>"u"&&(m=o));let B=0;for(let f=0;f<=c;f+=1)B=Ft(s,m,f,B),l[f]+=B;if(l[c]-B<=t&&c<r&&(m[c+1]&1||B<0)){c+=1,s.P[c]=-1,s.M[c]=0;let f;if(c===r){const E=A.length%n;f=E===0?n:E}else f=n;l[c]=l[c-1]+f-B+Ft(s,m,c,B)}else for(;c>0&&l[c]>=t+n;)c-=1;c===r&&l[c]<=t&&(l[c]<t&&e.splice(0,e.length),e.push({start:-1,end:g+1,errors:l[c]}),t=l[c])}return e}function di(i,A,t){const e=Ut(i,A,t);return gi(i,A,e)}function yt(i,A,t){let e=0;const n=[];for(;e!==-1;)e=i.indexOf(A,e),e!==-1&&(n.push({start:e,end:e+A.length,errors:0}),e+=1);return n.length>0?n:di(i,A,t)}function Qt(i,A){return A.length===0||i.length===0?0:1-yt(i,A,A.length)[0].errors/A.length}function Mi(i,A,t={}){if(A.length===0)return null;const e=Math.min(256,A.length/2),n=yt(i,A,e);if(n.length===0)return null;const r=o=>{const a=1-o.errors/A.length,h=t.prefix?Qt(i.slice(Math.max(0,o.start-t.prefix.length),o.start),t.prefix):1,c=t.suffix?Qt(i.slice(o.end,o.end+t.suffix.length),t.suffix):1;let l=1;typeof t.hint=="number"&&(l=1-Math.abs(o.start-t.hint)/i.length);const g=50*a+20*h+20*c+2*l,u=50+20+20+2;return g/u},s=n.map(o=>({start:o.start,end:o.end,score:r(o)}));return s.sort((o,a)=>a.score-o.score),s[0]}function XA(i,A,t){const e=t===1?A:A-1;if(i.charAt(e).trim()!=="")return A;let n,r;if(t===2?(n=i.substring(0,A),r=n.trimEnd()):(n=i.substring(A),r=n.trimStart()),!r.length)return-1;const s=n.length-r.length;return t===2?A-s:A+s}function Rt(i,A){const t=i.commonAncestorContainer.ownerDocument.createNodeIterator(i.commonAncestorContainer,NodeFilter.SHOW_TEXT),e=A===1?i.startContainer:i.endContainer,n=A===1?i.endContainer:i.startContainer;let r=t.nextNode();for(;r&&r!==e;)r=t.nextNode();A===2&&(r=t.previousNode());let s=-1;const o=()=>{if(r=A===1?t.nextNode():t.previousNode(),r){const a=r.textContent,h=A===1?0:a.length;s=XA(a,h,A)}};for(;r&&s===-1&&r!==n;)o();if(r&&s>=0)return{node:r,offset:s};throw new RangeError("No text nodes with non-whitespace text found in range")}function ui(i){if(!i.toString().trim().length)throw new RangeError("Range contains no non-whitespace text");if(i.startContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range startContainer is not a text node");if(i.endContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range endContainer is not a text node");const A=i.cloneRange();let t=!1,e=!1;const n={start:XA(i.startContainer.textContent,i.startOffset,1),end:XA(i.endContainer.textContent,i.endOffset,2)};if(n.start>=0&&(A.setStart(i.startContainer,n.start),t=!0),n.end>0&&(A.setEnd(i.endContainer,n.end),e=!0),t&&e)return A;if(!t){const{node:r,offset:s}=Rt(A,1);r&&s>=0&&A.setStart(r,s)}if(!e){const{node:r,offset:s}=Rt(A,2);r&&s>0&&A.setEnd(r,s)}return A}function Yt(i){var A;switch(i.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return((A=i.textContent)==null?void 0:A.length)??0;default:return 0}}function Ct(i){let A=i.previousSibling,t=0;for(;A;)t+=Yt(A),A=A.previousSibling;return t}function zt(i,...A){let t=A.shift();const e=i.ownerDocument.createNodeIterator(i,NodeFilter.SHOW_TEXT),n=[];let r=e.nextNode(),s,o=0;for(;t!==void 0&&r;)s=r,o+s.data.length>t?(n.push({node:s,offset:t-o}),t=A.shift()):(r=e.nextNode(),o+=s.data.length);for(;t!==void 0&&s&&o===t;)n.push({node:s,offset:s.data.length}),t=A.shift();if(t!==void 0)throw new RangeError("Offset exceeds text length");return n}class G{constructor(A,t){if(t<0)throw new Error("Offset is invalid");this.element=A,this.offset=t}relativeTo(A){if(!A.contains(this.element))throw new Error("Parent is not an ancestor of current element");let t=this.element,e=this.offset;for(;t!==A;)e+=Ct(t),t=t.parentElement;return new G(t,e)}resolve(A={}){try{return zt(this.element,this.offset)[0]}catch(t){if(this.offset===0&&A.direction!==void 0){const e=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);e.currentNode=this.element;const n=A.direction===1,r=n?e.nextNode():e.previousNode();if(!r)throw t;return{node:r,offset:n?0:r.data.length}}else throw t}}static fromCharOffset(A,t){switch(A.nodeType){case Node.TEXT_NODE:return G.fromPoint(A,t);case Node.ELEMENT_NODE:return new G(A,t);default:throw new Error("Node is not an element or text node")}}static fromPoint(A,t){switch(A.nodeType){case Node.TEXT_NODE:{if(t<0||t>A.data.length)throw new Error("Text node offset is out of range");if(!A.parentElement)throw new Error("Text node has no parent");const e=Ct(A)+t;return new G(A.parentElement,e)}case Node.ELEMENT_NODE:{if(t<0||t>A.childNodes.length)throw new Error("Child node offset is out of range");let e=0;for(let n=0;n<t;n++)e+=Yt(A.childNodes[n]);return new G(A,e)}default:throw new Error("Point is not in an element or text node")}}}class L{constructor(A,t){this.start=A,this.end=t}relativeTo(A){return new L(this.start.relativeTo(A),this.end.relativeTo(A))}toRange(){let A,t;this.start.element===this.end.element&&this.start.offset<=this.end.offset?[A,t]=zt(this.start.element,this.start.offset,this.end.offset):(A=this.start.resolve({direction:1}),t=this.end.resolve({direction:2}));const e=new Range;return e.setStart(A.node,A.offset),e.setEnd(t.node,t.offset),e}static fromRange(A){const t=G.fromPoint(A.startContainer,A.startOffset),e=G.fromPoint(A.endContainer,A.endOffset);return new L(t,e)}static fromOffsets(A,t,e){return new L(new G(A,t),new G(A,e))}static trimmedRange(A){return ui(L.fromRange(A).toRange())}}class wA{constructor(A,t,e){this.root=A,this.start=t,this.end=e}static fromRange(A,t){const e=L.fromRange(t).relativeTo(A);return new wA(A,e.start.offset,e.end.offset)}static fromSelector(A,t){return new wA(A,t.start,t.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return L.fromOffsets(this.root,this.start,this.end).toRange()}}class FA{constructor(A,t,e={}){this.root=A,this.exact=t,this.context=e}static fromRange(A,t){const e=A.textContent,n=L.fromRange(t).relativeTo(A),r=n.start.offset,s=n.end.offset,o=32;return new FA(A,e.slice(r,s),{prefix:e.slice(Math.max(0,r-o),r),suffix:e.slice(s,Math.min(e.length,s+o))})}static fromSelector(A,t){const{prefix:e,suffix:n}=t;return new FA(A,t.exact,{prefix:e,suffix:n})}toSelector(){return{type:"TextQuoteSelector",exact:this.exact,prefix:this.context.prefix,suffix:this.context.suffix}}toRange(A={}){return this.toPositionAnchor(A).toRange()}toPositionAnchor(A={}){const t=this.root.textContent,e=Mi(t,this.exact,{...this.context,hint:A.hint});if(!e)throw new Error("Quote not found");return new wA(this.root,e.start,e.end)}}function mi(i){const A=i.tagName.toUpperCase();return A==="IMG"||A==="VIDEO"||A==="AUDIO"||A==="IFRAME"||A==="OBJECT"||A==="EMBED"||A==="CANVAS"}function ZA(i,A){try{const t=A.locations,e=A.text;if(e&&e.highlight){let n;t&&t.getCssSelector()&&(n=i.querySelector(t.getCssSelector())),n||(n=i.body);const r=new FA(n,e.highlight,{prefix:e.before,suffix:e.after});try{return r.toRange()}catch{return console.warn("Quote not found:",r),null}}if(t){let n=null;if(!n&&t.getCssSelector()&&(n=i.querySelector(t.getCssSelector())),!n&&t.fragments){for(const r of t.fragments)if(n=i.getElementById(r),n)break}if(n){const r=i.createRange();return n.childNodes.length===0||mi(n)?(r.selectNode(n),r):(r.setStartBefore(n),r.setEndAfter(n),r)}}}catch(t){console.error(t)}return null}function Bi(i,A){let t=i.getClientRects();t.length||i.commonAncestorContainer.nodeType===Node.ELEMENT_NODE&&(t=i.commonAncestorContainer.getClientRects());const e=1,n=[];for(const h of t)n.push({bottom:h.bottom,height:h.height,left:h.left,right:h.right,top:h.top,width:h.width});const r=Nt(n,e,A),s=fi(r,e),o=Tt(s),a=2*2;for(let h=o.length-1;h>=0;h--){const c=o[h];if(!(c.width*c.height>a))if(o.length>1)o.splice(h,1);else break}return o}function Nt(i,A,t){for(let e=0;e<i.length;e++)for(let n=e+1;n<i.length;n++){const r=i[e],s=i[n];if(r===s)continue;const o=V(r.top,s.top,A)&&V(r.bottom,s.bottom,A),a=V(r.left,s.left,A)&&V(r.right,s.right,A);if((a&&!t||o&&!a)&&jt(r,s,A)){const h=i.filter(l=>l!==r&&l!==s),c=Ei(r,s);return h.push(c),Nt(h,A,t)}}return i}function Ei(i,A){const t=Math.min(i.left,A.left),e=Math.max(i.right,A.right),n=Math.min(i.top,A.top),r=Math.max(i.bottom,A.bottom);return{bottom:r,height:r-n,left:t,right:e,top:n,width:e-t}}function fi(i,A){const t=new Set(i);for(const e of i){if(!(e.width>1&&e.height>1)){t.delete(e);continue}for(const n of i)if(e!==n&&t.has(n)&&Ii(n,e,A)){t.delete(e);break}}return Array.from(t)}function Ii(i,A,t){return UA(i,A.left,A.top,t)&&UA(i,A.right,A.top,t)&&UA(i,A.left,A.bottom,t)&&UA(i,A.right,A.bottom,t)}function UA(i,A,t,e){return(i.left<A||V(i.left,A,e))&&(i.right>A||V(i.right,A,e))&&(i.top<t||V(i.top,t,e))&&(i.bottom>t||V(i.bottom,t,e))}function Tt(i){for(let A=0;A<i.length;A++)for(let t=A+1;t<i.length;t++){const e=i[A],n=i[t];if(e!==n&&jt(e,n,-1)){let r=[],s;const o=xt(e,n);if(o.length===1)r=o,s=e;else{const h=xt(n,e);o.length<h.length?(r=o,s=e):(r=h,s=n)}const a=i.filter(h=>h!==s);return Array.prototype.push.apply(a,r),Tt(a)}}return i}function xt(i,A){const t=pi(A,i);if(t.height===0||t.width===0)return[i];const e=[];{const n={bottom:i.bottom,height:0,left:i.left,right:t.left,top:i.top,width:0};n.width=n.right-n.left,n.height=n.bottom-n.top,n.height!==0&&n.width!==0&&e.push(n)}{const n={bottom:t.top,height:0,left:t.left,right:t.right,top:i.top,width:0};n.width=n.right-n.left,n.height=n.bottom-n.top,n.height!==0&&n.width!==0&&e.push(n)}{const n={bottom:i.bottom,height:0,left:t.left,right:t.right,top:t.bottom,width:0};n.width=n.right-n.left,n.height=n.bottom-n.top,n.height!==0&&n.width!==0&&e.push(n)}{const n={bottom:i.bottom,height:0,left:t.right,right:i.right,top:i.top,width:0};n.width=n.right-n.left,n.height=n.bottom-n.top,n.height!==0&&n.width!==0&&e.push(n)}return e}function pi(i,A){const t=Math.max(i.left,A.left),e=Math.min(i.right,A.right),n=Math.max(i.top,A.top),r=Math.min(i.bottom,A.bottom);return{bottom:r,height:Math.max(0,r-n),left:t,right:e,top:n,width:Math.max(0,e-t)}}function jt(i,A,t){return(i.left<A.right||t>=0&&V(i.left,A.right,t))&&(A.left<i.right||t>=0&&V(A.left,i.right,t))&&(i.top<A.bottom||t>=0&&V(i.top,A.bottom,t))&&(A.top<i.bottom||t>=0&&V(A.top,i.bottom,t))}function V(i,A,t){return Math.abs(i-A)<=t}var Z=[],wi=function(){return Z.some(function(i){return i.activeTargets.length>0})},Fi=function(){return Z.some(function(i){return i.skippedTargets.length>0})},St="ResizeObserver loop completed with undelivered notifications.",Ui=function(){var i;typeof ErrorEvent=="function"?i=new ErrorEvent("error",{message:St}):(i=document.createEvent("Event"),i.initEvent("error",!1,!1),i.message=St),window.dispatchEvent(i)},gA;(function(i){i.BORDER_BOX="border-box",i.CONTENT_BOX="content-box",i.DEVICE_PIXEL_CONTENT_BOX="device-pixel-content-box"})(gA||(gA={}));var K=function(i){return Object.freeze(i)},yi=function(){function i(A,t){this.inlineSize=A,this.blockSize=t,K(this)}return i}(),Vt=function(){function i(A,t,e,n){return this.x=A,this.y=t,this.width=e,this.height=n,this.top=this.y,this.left=this.x,this.bottom=this.top+this.height,this.right=this.left+this.width,K(this)}return i.prototype.toJSON=function(){var A=this,t=A.x,e=A.y,n=A.top,r=A.right,s=A.bottom,o=A.left,a=A.width,h=A.height;return{x:t,y:e,top:n,right:r,bottom:s,left:o,width:a,height:h}},i.fromRect=function(A){return new i(A.x,A.y,A.width,A.height)},i}(),KA=function(i){return i instanceof SVGElement&&"getBBox"in i},Dt=function(i){if(KA(i)){var A=i.getBBox(),t=A.width,e=A.height;return!t&&!e}var n=i,r=n.offsetWidth,s=n.offsetHeight;return!(r||s||i.getClientRects().length)},Ht=function(i){var A;if(i instanceof Element)return!0;var t=(A=i==null?void 0:i.ownerDocument)===null||A===void 0?void 0:A.defaultView;return!!(t&&i instanceof t.Element)},Qi=function(i){switch(i.tagName){case"INPUT":if(i.type!=="image")break;case"VIDEO":case"AUDIO":case"EMBED":case"OBJECT":case"CANVAS":case"IFRAME":case"IMG":return!0}return!1},dA=typeof window<"u"?window:{},yA=new WeakMap,Gt=/auto|scroll/,Ri=/^tb|vertical/,Yi=/msie|trident/i.test(dA.navigator&&dA.navigator.userAgent),v=function(i){return parseFloat(i||"0")},rA=function(i,A,t){return i===void 0&&(i=0),A===void 0&&(A=0),t===void 0&&(t=!1),new yi((t?A:i)||0,(t?i:A)||0)},vt=K({devicePixelContentBoxSize:rA(),borderBoxSize:rA(),contentBoxSize:rA(),contentRect:new Vt(0,0,0,0)}),bt=function(i,A){if(A===void 0&&(A=!1),yA.has(i)&&!A)return yA.get(i);if(Dt(i))return yA.set(i,vt),vt;var t=getComputedStyle(i),e=KA(i)&&i.ownerSVGElement&&i.getBBox(),n=!Yi&&t.boxSizing==="border-box",r=Ri.test(t.writingMode||""),s=!e&&Gt.test(t.overflowY||""),o=!e&&Gt.test(t.overflowX||""),a=e?0:v(t.paddingTop),h=e?0:v(t.paddingRight),c=e?0:v(t.paddingBottom),l=e?0:v(t.paddingLeft),g=e?0:v(t.borderTopWidth),u=e?0:v(t.borderRightWidth),m=e?0:v(t.borderBottomWidth),B=e?0:v(t.borderLeftWidth),f=l+h,E=a+c,p=B+u,I=g+m,w=o?i.offsetHeight-I-i.clientHeight:0,Y=s?i.offsetWidth-p-i.clientWidth:0,oA=n?f+p:0,_=n?E+I:0,$=e?e.width:v(t.width)-oA-Y,AA=e?e.height:v(t.height)-_-w,TA=$+f+Y+p,xA=AA+E+w+I,aA=K({devicePixelContentBoxSize:rA(Math.round($*devicePixelRatio),Math.round(AA*devicePixelRatio),r),borderBoxSize:rA(TA,xA,r),contentBoxSize:rA($,AA,r),contentRect:new Vt(l,a,$,AA)});return yA.set(i,aA),aA},Jt=function(i,A,t){var e=bt(i,t),n=e.borderBoxSize,r=e.contentBoxSize,s=e.devicePixelContentBoxSize;switch(A){case gA.DEVICE_PIXEL_CONTENT_BOX:return s;case gA.BORDER_BOX:return n;default:return r}},Ci=function(){function i(A){var t=bt(A);this.target=A,this.contentRect=t.contentRect,this.borderBoxSize=K([t.borderBoxSize]),this.contentBoxSize=K([t.contentBoxSize]),this.devicePixelContentBoxSize=K([t.devicePixelContentBoxSize])}return i}(),Pt=function(i){if(Dt(i))return 1/0;for(var A=0,t=i.parentNode;t;)A+=1,t=t.parentNode;return A},zi=function(){var i=1/0,A=[];Z.forEach(function(r){if(r.activeTargets.length!==0){var s=[];r.activeTargets.forEach(function(o){var a=new Ci(o.target),h=Pt(o.target);s.push(a),o.lastReportedSize=Jt(o.target,o.observedBox),h<i&&(i=h)}),A.push(function(){r.callback.call(r.observer,s,r.observer)}),r.activeTargets.splice(0,r.activeTargets.length)}});for(var t=0,e=A;t<e.length;t++){var n=e[t];n()}return i},kt=function(i){Z.forEach(function(A){A.activeTargets.splice(0,A.activeTargets.length),A.skippedTargets.splice(0,A.skippedTargets.length),A.observationTargets.forEach(function(t){t.isActive()&&(Pt(t.target)>i?A.activeTargets.push(t):A.skippedTargets.push(t))})})},Ni=function(){var i=0;for(kt(i);wi();)i=zi(),kt(i);return Fi()&&Ui(),i>0},qA,Wt=[],Ti=function(){return Wt.splice(0).forEach(function(i){return i()})},xi=function(i){if(!qA){var A=0,t=document.createTextNode(""),e={characterData:!0};new MutationObserver(function(){return Ti()}).observe(t,e),qA=function(){t.textContent="".concat(A?A--:A++)}}Wt.push(i),qA()},ji=function(i){xi(function(){requestAnimationFrame(i)})},QA=0,Si=function(){return!!QA},Vi=250,Di={attributes:!0,characterData:!0,childList:!0,subtree:!0},Lt=["resize","load","transitionend","animationend","animationstart","animationiteration","keyup","keydown","mouseup","mousedown","mouseover","mouseout","blur","focus"],Ot=function(i){return i===void 0&&(i=0),Date.now()+i},_A=!1,Hi=function(){function i(){var A=this;this.stopped=!0,this.listener=function(){return A.schedule()}}return i.prototype.run=function(A){var t=this;if(A===void 0&&(A=Vi),!_A){_A=!0;var e=Ot(A);ji(function(){var n=!1;try{n=Ni()}finally{if(_A=!1,A=e-Ot(),!Si())return;n?t.run(1e3):A>0?t.run(A):t.start()}})}},i.prototype.schedule=function(){this.stop(),this.run()},i.prototype.observe=function(){var A=this,t=function(){return A.observer&&A.observer.observe(document.body,Di)};document.body?t():dA.addEventListener("DOMContentLoaded",t)},i.prototype.start=function(){var A=this;this.stopped&&(this.stopped=!1,this.observer=new MutationObserver(this.listener),this.observe(),Lt.forEach(function(t){return dA.addEventListener(t,A.listener,!0)}))},i.prototype.stop=function(){var A=this;this.stopped||(this.observer&&this.observer.disconnect(),Lt.forEach(function(t){return dA.removeEventListener(t,A.listener,!0)}),this.stopped=!0)},i}(),$A=new Hi,Xt=function(i){!QA&&i>0&&$A.start(),QA+=i,!QA&&$A.stop()},Gi=function(i){return!KA(i)&&!Qi(i)&&getComputedStyle(i).display==="inline"},vi=function(){function i(A,t){this.target=A,this.observedBox=t||gA.CONTENT_BOX,this.lastReportedSize={inlineSize:0,blockSize:0}}return i.prototype.isActive=function(){var A=Jt(this.target,this.observedBox,!0);return Gi(this.target)&&(this.lastReportedSize=A),this.lastReportedSize.inlineSize!==A.inlineSize||this.lastReportedSize.blockSize!==A.blockSize},i}(),bi=function(){function i(A,t){this.activeTargets=[],this.skippedTargets=[],this.observationTargets=[],this.observer=A,this.callback=t}return i}(),RA=new WeakMap,Zt=function(i,A){for(var t=0;t<i.length;t+=1)if(i[t].target===A)return t;return-1},YA=function(){function i(){}return i.connect=function(A,t){var e=new bi(A,t);RA.set(A,e)},i.observe=function(A,t,e){var n=RA.get(A),r=n.observationTargets.length===0;Zt(n.observationTargets,t)<0&&(r&&Z.push(n),n.observationTargets.push(new vi(t,e&&e.box)),Xt(1),$A.schedule())},i.unobserve=function(A,t){var e=RA.get(A),n=Zt(e.observationTargets,t),r=e.observationTargets.length===1;n>=0&&(r&&Z.splice(Z.indexOf(e),1),e.observationTargets.splice(n,1),Xt(-1))},i.disconnect=function(A){var t=this,e=RA.get(A);e.observationTargets.slice().forEach(function(n){return t.unobserve(A,n.target)}),e.activeTargets.splice(0,e.activeTargets.length)},i}(),Kt=function(){function i(A){if(arguments.length===0)throw new TypeError("Failed to construct 'ResizeObserver': 1 argument required, but only 0 present.");if(typeof A!="function")throw new TypeError("Failed to construct 'ResizeObserver': The callback provided as parameter 1 is not a function.");YA.connect(this,A)}return i.prototype.observe=function(A,t){if(arguments.length===0)throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': 1 argument required, but only 0 present.");if(!Ht(A))throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': parameter 1 is not of type 'Element");YA.observe(this,A,t)},i.prototype.unobserve=function(A){if(arguments.length===0)throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': 1 argument required, but only 0 present.");if(!Ht(A))throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': parameter 1 is not of type 'Element");YA.unobserve(this,A)},i.prototype.disconnect=function(){YA.disconnect(this)},i.toString=function(){return"function ResizeObserver () { [polyfill code] }"},i}();function Ji(i,A){return i.document.documentElement.style.getPropertyValue(A)}function At(i,A,t){i.document.documentElement.style.setProperty(A,t)}function qt(i,A){i.document.documentElement.style.removeProperty(A)}const Pi=window.ResizeObserver||Kt,ki="Highlight"in window,_t=["IMG","IMAGE","AUDIO","VIDEO","SVG"];class Wi{constructor(A,t,e,n){this.wnd=A,this.comms=t,this.id=e,this.name=n,this.items=[],this.lastItemId=0,this.container=void 0,this.activateable=!1,this.experimentalHighlights=!1,this.currentRender=0,ki&&(this.experimentalHighlights=!0,this.notTextFlag=new Map)}get activeable(){return this.activateable}set activeable(A){this.activateable=A}add(A){var t,e,n,r;const s=`${this.id}-${this.lastItemId++}`,o=ZA(this.wnd.document,A.locator);if(!o){this.comms.log("Can't locate DOM range for decoration",A);return}const a=o.commonAncestorContainer;a.nodeType!==Node.TEXT_NODE&&this.experimentalHighlights&&(_t.includes(a.nodeName.toUpperCase())&&((t=this.notTextFlag)==null||t.set(s,!0)),a.querySelector(_t.join(", ").toLowerCase())&&((e=this.notTextFlag)==null||e.set(s,!0)),(((n=a.textContent)==null?void 0:n.trim())||"").length===0&&((r=this.notTextFlag)==null||r.set(s,!0)));const h={decoration:A,id:s,range:o};this.items.push(h),this.layout(h),this.renderLayout([h])}remove(A){var t,e;const n=this.items.findIndex(s=>s.decoration.id===A);if(n<0)return;const r=this.items[n];if(this.items.splice(n,1),r.clickableElements=void 0,r.container&&(r.container.remove(),r.container=void 0),this.experimentalHighlights&&!((t=this.notTextFlag)!=null&&t.has(r.id))){const s=this.wnd.CSS.highlights.get(this.id);s==null||s.delete(r.range)}(e=this.notTextFlag)==null||e.delete(r.id)}update(A){this.remove(A.id),this.add(A)}clear(){var A;this.clearContainer(),this.items.length=0,(A=this.notTextFlag)==null||A.clear()}requestLayout(){this.wnd.cancelAnimationFrame(this.currentRender),this.clearContainer(),this.items.forEach(A=>this.layout(A)),this.renderLayout(this.items)}experimentalLayout(A){var t,e;const[n,r]=this.requireContainer(!0);r.add(A.range),n.innerHTML=`
27
+ });`),"text/javascript")));class Se{constructor(t,e,A,i){this.pub=t,this.item=A,this.burl=A.toURL(e)||"",this.cssProperties=i}async build(t=!1){if(this.item.mediaType.isHTML)return await this.buildHtmlFrame(t);if(this.item.mediaType.isBitmap)return this.buildImageFrame();throw Error("Unsupported frame mediatype "+this.item.mediaType.string)}async buildHtmlFrame(t=!1){const e=await this.pub.get(this.item).readAsString();if(!e)throw new Error(`Failed reading item ${this.item.href}`);const A=new DOMParser().parseFromString(e,this.item.mediaType.string),i=A.querySelector("parsererror");if(i){const r=i.querySelector("div");throw new Error(`Failed parsing item ${this.item.href}: ${(r==null?void 0:r.textContent)||i.textContent}`)}return this.finalizeDOM(A,this.burl,this.item.mediaType,t,this.cssProperties)}buildImageFrame(){const t=document.implementation.createHTMLDocument(this.item.title||this.item.href),e=document.createElement("img");return e.src=this.burl||"",e.alt=this.item.title||"",e.decoding="async",t.body.appendChild(e),this.finalizeDOM(t,this.burl,this.item.mediaType,!0)}hasExecutable(t){return!!t.querySelector("script")||!!t.querySelector("body[onload]:not(body[onload=''])")}hasStyle(t){return!!(t.querySelector("link[rel='stylesheet']")||t.querySelector("style")||t.querySelector("[style]:not([style=''])"))}setProperties(t,e){for(const A in t){const i=t[A];i&&e.documentElement.style.setProperty(A,i)}}finalizeDOM(t,e,A,i=!1,r){var o;if(!t)return"";if(!i){const a=Kt(t,ot("ReadiumCSS-before",()=>$(Xt(Ei),"text/css")));t.head.firstChild?t.head.firstChild.before(a):t.head.appendChild(a),this.hasStyle(t)||a.after(Kt(t,ot("ReadiumCSS-default",()=>$(Xt(wi),"text/css")))),t.head.appendChild(Kt(t,ot("ReadiumCSS-after",()=>$(Xt(Bi),"text/css")))),r&&this.setProperties(r,t)}if(t.body.querySelectorAll("img").forEach(a=>{a.setAttribute("fetchpriority","high")}),A.isHTML&&((o=this.pub.metadata.languages)!=null&&o[0])){const a=this.pub.metadata.languages[0];if(A===d.XHTML){const l=document.documentElement.lang||document.documentElement.getAttribute("xml:lang"),h=document.body.lang||document.body.getAttribute("xml:lang");h&&!l?(document.documentElement.lang=h,document.documentElement.setAttribute("xml:lang",h),document.body.removeAttribute("xml:lang"),document.body.removeAttribute("lang")):l||(document.documentElement.lang=a,document.documentElement.setAttribute("xml:lang",a))}else A===d.HTML&&!document.documentElement.lang&&(document.documentElement.lang=a)}if(e!==void 0){const a=t.createElement("base");a.href=e,a.dataset.readium="true",t.head.firstChild.before(a)}const s=this.hasExecutable(t);return s&&t.head.firstChild.before(Fi(t)),t.head.firstChild.before(Ii(t)),s&&t.head.appendChild(Ui(t)),URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(t)],{type:A.isHTML?A.string:"application/xhtml+xml"}))}}const yi=Math.pow(2,32),Ne=()=>Math.round(Math.random()*yi).toString(36),_t=()=>`${Math.round(performance.now())}-${Ne()}-${Ne()}`,at=1;class Ci{constructor(t){this.destination=null,this.registrar=new Map,this.origin="",this.channelId="",this.receiver=this.receive.bind(this),this.preLog=[],this.wnd=t,t.addEventListener("message",this.receiver)}receive(t){if(t.source===null)throw Error("Event source is null");if(typeof t.data!="object")return;const e=t.data;if(!(!("_readium"in e)||!e._readium||e._readium<=0)){if(e.key==="_ping"){if(!this.destination){if(this.destination=t.source,this.origin=t.origin,this.channelId=e._channel,e._readium!==at){e._readium>at?this.send("error",`received comms version ${e._readium} higher than ${at}`):this.send("error",`received comms version ${e._readium} lower than ${at}`),this.destination=null,this.origin="",this.channelId="";return}this.send("_pong",void 0),this.preLog.forEach(A=>this.send("log",A)),this.preLog=[]}return}else if(this.channelId){if(e._channel!==this.channelId||t.origin!==this.origin)return}else return;this.handle(e)}}handle(t){const e=this.registrar.get(t.key);if(!e||e.length===0){t.strict&&this.send("_unhandled",t);return}e.forEach(A=>A.cb(t.data,i=>{this.send("_ack",i,t.id)}))}register(t,e,A){Array.isArray(t)||(t=[t]),t.forEach(i=>{const r=this.registrar.get(i);if(r&&r.length>=0){if(r.find(s=>s.module===e))throw new Error(`Trying to register another callback for combination of event ${i} and module ${e}`);r.push({cb:A,module:e}),this.registrar.set(i,r)}else this.registrar.set(i,[{cb:A,module:e}])})}unregister(t,e){Array.isArray(t)||(t=[t]),t.forEach(A=>{const i=this.registrar.get(A);!i||i.length===0||i.splice(i.findIndex(r=>r.module===e),1)})}unregisterAll(t){this.registrar.forEach((e,A)=>this.registrar.set(A,e.filter(i=>i.module!==t)))}log(...t){this.destination?this.send("log",t):this.preLog.push(t)}get ready(){return!!this.destination}destroy(){this.destination=null,this.channelId="",this.preLog=[],this.registrar.clear(),this.wnd.removeEventListener("message",this.receiver)}send(t,e,A=void 0,i=[]){if(!this.destination)throw Error("Attempted to send comms message before destination has been initialized");const r={_readium:at,_channel:this.channelId,id:A??_t(),key:t,data:e};try{this.destination.postMessage(r,{targetOrigin:this.origin,transfer:i})}catch(s){if(i.length>0)throw s;this.destination.postMessage(r,this.origin,i)}}}const q=class Et{constructor(t){if(typeof t=="string"){if(!Et.VALID_MODES.has(t.toLowerCase()))return;this.value=t.toLowerCase()}else{const e=t.filter(A=>Et.VALID_MODES.has(A.toLowerCase()));if(e.length===0)return;this.value=Array.from(new Set(e))}}static deserialize(t){if(!t)return;if(typeof t=="string")return new Et(t);if(!Array.isArray(t))return;const e=t.filter(A=>A?Et.VALID_MODES.has(A.toLowerCase()):!1);if(e.length!==0)return new Et(e)}serialize(){return this.value}};q.VALID_MODES=new Set(["auditory","tactile","textual","visual"]),q.AUDITORY=new q("auditory"),q.TACTILE=new q("tactile"),q.TEXTUAL=new q("textual"),q.VISUAL=new q("visual");class R{constructor(t){this.otherProperties=t}static deserialize(t){if(t)return new R(t)}serialize(){return this.otherProperties}add(t){const e=Object.assign({},this.otherProperties);for(const A in t)e[A]=t[A];return new R(e)}}R.prototype.getContains=function(){return new Set(this.otherProperties.contains||[])},R.prototype.getLayout=function(){return this.otherProperties.layout};class u{constructor(t){let e,A,i=t.mediaType.replace(/\s/g,"").split(";");const r=i[0].split("/");if(r.length===2){if(e=r[0].toLowerCase().trim(),A=r[1].toLowerCase().trim(),e.length===0||A.length===0)throw new Error("Invalid media type")}else throw new Error("Invalid media type");const s={};for(let g=1;g<i.length;g++){const m=i[g].split("=");if(m.length===2){const M=m[0].toLocaleLowerCase(),B=M==="charset"?m[1].toUpperCase():m[1];s[M]=B}}const o={},a=Object.keys(s);a.sort((g,m)=>g.localeCompare(m)),a.forEach(g=>o[g]=s[g]);let l="";for(const g in o){const m=o[g];l+=`;${g}=${m}`}const h=`${e}/${A}${l}`,c=o.encoding;this.string=h,this.type=e,this.subtype=A,this.parameters=o,this.encoding=c,this.name=t.name,this.fileExtension=t.fileExtension}static parse(t){return new u(t)}get structuredSyntaxSuffix(){const t=this.subtype.split("+");return t.length>1?`+${t[t.length-1]}`:void 0}get charset(){return this.parameters.charset}contains(t){const e=typeof t=="string"?u.parse({mediaType:t}):t;if(!((this.type==="*"||this.type===e.type)&&(this.subtype==="*"||this.subtype===e.subtype)))return!1;const A=new Set(Object.entries(this.parameters).map(([r,s])=>`${r}=${s}`)),i=new Set(Object.entries(e.parameters).map(([r,s])=>`${r}=${s}`));for(const r of Array.from(A.values()))if(!i.has(r))return!1;return!0}matches(t){const e=typeof t=="string"?u.parse({mediaType:t}):t;return this.contains(e)||e.contains(this)}matchesAny(...t){for(const e of t)if(this.matches(e))return!0;return!1}equals(t){return this.string===t.string}get isZIP(){return this.matchesAny(u.ZIP,u.LCP_PROTECTED_AUDIOBOOK,u.LCP_PROTECTED_PDF)||this.structuredSyntaxSuffix==="+zip"}get isJSON(){return this.matchesAny(u.JSON)||this.structuredSyntaxSuffix==="+json"}get isOPDS(){return this.matchesAny(u.OPDS1,u.OPDS1_ENTRY,u.OPDS2,u.OPDS2_PUBLICATION,u.OPDS_AUTHENTICATION)||this.structuredSyntaxSuffix==="+json"}get isHTML(){return this.matchesAny(u.HTML,u.XHTML)}get isBitmap(){return this.matchesAny(u.BMP,u.GIF,u.JPEG,u.PNG,u.TIFF,u.WEBP)}get isAudio(){return this.type==="audio"}get isVideo(){return this.type==="video"}get isRWPM(){return this.matchesAny(u.READIUM_AUDIOBOOK_MANIFEST,u.DIVINA_MANIFEST,u.READIUM_WEBPUB_MANIFEST)}get isPublication(){return this.matchesAny(u.READIUM_AUDIOBOOK,u.READIUM_AUDIOBOOK_MANIFEST,u.CBZ,u.DIVINA,u.DIVINA_MANIFEST,u.EPUB,u.LCP_PROTECTED_AUDIOBOOK,u.LCP_PROTECTED_PDF,u.LPF,u.PDF,u.W3C_WPUB_MANIFEST,u.READIUM_WEBPUB,u.READIUM_WEBPUB_MANIFEST,u.ZAB)}static get AAC(){return u.parse({mediaType:"audio/aac",fileExtension:"aac"})}static get ACSM(){return u.parse({mediaType:"application/vnd.adobe.adept+xml",name:"Adobe Content Server Message",fileExtension:"acsm"})}static get AIFF(){return u.parse({mediaType:"audio/aiff",fileExtension:"aiff"})}static get AVI(){return u.parse({mediaType:"video/x-msvideo",fileExtension:"avi"})}static get BINARY(){return u.parse({mediaType:"application/octet-stream"})}static get BMP(){return u.parse({mediaType:"image/bmp",fileExtension:"bmp"})}static get CBZ(){return u.parse({mediaType:"application/vnd.comicbook+zip",name:"Comic Book Archive",fileExtension:"cbz"})}static get CSS(){return u.parse({mediaType:"text/css",fileExtension:"css"})}static get DIVINA(){return u.parse({mediaType:"application/divina+zip",name:"Digital Visual Narratives",fileExtension:"divina"})}static get DIVINA_MANIFEST(){return u.parse({mediaType:"application/divina+json",name:"Digital Visual Narratives",fileExtension:"json"})}static get EPUB(){return u.parse({mediaType:"application/epub+zip",name:"EPUB",fileExtension:"epub"})}static get GIF(){return u.parse({mediaType:"image/gif",fileExtension:"gif"})}static get GZ(){return u.parse({mediaType:"application/gzip",fileExtension:"gz"})}static get HTML(){return u.parse({mediaType:"text/html",fileExtension:"html"})}static get JAVASCRIPT(){return u.parse({mediaType:"text/javascript",fileExtension:"js"})}static get JPEG(){return u.parse({mediaType:"image/jpeg",fileExtension:"jpeg"})}static get JSON(){return u.parse({mediaType:"application/json"})}static get LCP_LICENSE_DOCUMENT(){return u.parse({mediaType:"application/vnd.readium.lcp.license.v1.0+json",name:"LCP License",fileExtension:"lcpl"})}static get LCP_PROTECTED_AUDIOBOOK(){return u.parse({mediaType:"application/audiobook+lcp",name:"LCP Protected Audiobook",fileExtension:"lcpa"})}static get LCP_PROTECTED_PDF(){return u.parse({mediaType:"application/pdf+lcp",name:"LCP Protected PDF",fileExtension:"lcpdf"})}static get LCP_STATUS_DOCUMENT(){return u.parse({mediaType:"application/vnd.readium.license.status.v1.0+json"})}static get LPF(){return u.parse({mediaType:"application/lpf+zip",fileExtension:"lpf"})}static get MP3(){return u.parse({mediaType:"audio/mpeg",fileExtension:"mp3"})}static get MPEG(){return u.parse({mediaType:"video/mpeg",fileExtension:"mpeg"})}static get NCX(){return u.parse({mediaType:"application/x-dtbncx+xml",fileExtension:"ncx"})}static get OGG(){return u.parse({mediaType:"audio/ogg",fileExtension:"oga"})}static get OGV(){return u.parse({mediaType:"video/ogg",fileExtension:"ogv"})}static get OPDS1(){return u.parse({mediaType:"application/atom+xml;profile=opds-catalog"})}static get OPDS1_ENTRY(){return u.parse({mediaType:"application/atom+xml;type=entry;profile=opds-catalog"})}static get OPDS2(){return u.parse({mediaType:"application/opds+json"})}static get OPDS2_PUBLICATION(){return u.parse({mediaType:"application/opds-publication+json"})}static get OPDS_AUTHENTICATION(){return u.parse({mediaType:"application/opds-authentication+json"})}static get OPUS(){return u.parse({mediaType:"audio/opus",fileExtension:"opus"})}static get OTF(){return u.parse({mediaType:"font/otf",fileExtension:"otf"})}static get PDF(){return u.parse({mediaType:"application/pdf",name:"PDF",fileExtension:"pdf"})}static get PNG(){return u.parse({mediaType:"image/png",fileExtension:"png"})}static get READIUM_AUDIOBOOK(){return u.parse({mediaType:"application/audiobook+zip",name:"Readium Audiobook",fileExtension:"audiobook"})}static get READIUM_AUDIOBOOK_MANIFEST(){return u.parse({mediaType:"application/audiobook+json",name:"Readium Audiobook",fileExtension:"json"})}static get READIUM_CONTENT_DOCUMENT(){return u.parse({mediaType:"application/vnd.readium.content+json",name:"Readium Content Document",fileExtension:"json"})}static get READIUM_GUIDED_NAVIGATION_DOCUMENT(){return u.parse({mediaType:"application/guided-navigation+json",name:"Readium Guided Navigation Document",fileExtension:"json"})}static get READIUM_POSITION_LIST(){return u.parse({mediaType:"application/vnd.readium.position-list+json",name:"Readium Position List",fileExtension:"json"})}static get READIUM_WEBPUB(){return u.parse({mediaType:"application/webpub+zip",name:"Readium Web Publication",fileExtension:"webpub"})}static get READIUM_WEBPUB_MANIFEST(){return u.parse({mediaType:"application/webpub+json",name:"Readium Web Publication",fileExtension:"json"})}static get SMIL(){return u.parse({mediaType:"application/smil+xml",fileExtension:"smil"})}static get SVG(){return u.parse({mediaType:"image/svg+xml",fileExtension:"svg"})}static get TEXT(){return u.parse({mediaType:"text/plain",fileExtension:"txt"})}static get TIFF(){return u.parse({mediaType:"image/tiff",fileExtension:"tiff"})}static get TTF(){return u.parse({mediaType:"font/ttf",fileExtension:"ttf"})}static get W3C_WPUB_MANIFEST(){return u.parse({mediaType:"application/x.readium.w3c.wpub+json",name:"Web Publication",fileExtension:"json"})}static get WAV(){return u.parse({mediaType:"audio/wav",fileExtension:"wav"})}static get WEBM_AUDIO(){return u.parse({mediaType:"audio/webm",fileExtension:"webm"})}static get WEBM_VIDEO(){return u.parse({mediaType:"video/webm",fileExtension:"webm"})}static get WEBP(){return u.parse({mediaType:"image/webp",fileExtension:"webp"})}static get WOFF(){return u.parse({mediaType:"font/woff",fileExtension:"woff"})}static get WOFF2(){return u.parse({mediaType:"font/woff2",fileExtension:"woff2"})}static get XHTML(){return u.parse({mediaType:"application/xhtml+xml",fileExtension:"xhtml"})}static get XML(){return u.parse({mediaType:"application/xml",fileExtension:"xml"})}static get ZAB(){return u.parse({mediaType:"application/x.readium.zab+zip",name:"Zipped Audio Book",fileExtension:"zab"})}static get ZIP(){return u.parse({mediaType:"application/zip",fileExtension:"zip"})}}class xe{constructor(t){this.uri=t,this.parameters=this.getParameters(t)}getParameters(t){const e=/\{\??([^}]+)\}/g,A=t.match(e);return A?new Set(A.join(",").replace(e,"$1").split(",").map(i=>i.trim())):new Set}expand(t){const e=i=>i.split(",").map(r=>{const s=t[r];return s?encodeURIComponent(s):""}).join(","),A=i=>"?"+i.split(",").map(r=>{const s=r.split("=")[0],o=t[s];return o?`${s}=${encodeURIComponent(o)}`:""}).join("&");return this.uri.replace(/\{(\??)([^}]+)\}/g,(...i)=>i[1]?A(i[2]):e(i[2]))}}function Ri(n){return n&&n instanceof Array?n:void 0}function Te(n){return n&&typeof n=="string"?[n]:Ri(n)}function je(n){return typeof n=="string"?new Date(n):void 0}function St(n){return isNaN(n)?void 0:n}function D(n){return St(n)!==void 0&&Math.sign(n)>=0?n:void 0}function Qi(n){const t=new Array;return n.forEach(e=>t.push(e)),t}class S{constructor(t){this.fragments=t.fragments?t.fragments:new Array,this.progression=t.progression,this.totalProgression=t.totalProgression,this.position=t.position,this.otherLocations=t.otherLocations}static deserialize(t){if(!t)return;const e=St(t.progression),A=St(t.totalProgression),i=St(t.position),r=new Map,s=new Set(["fragment","fragments","progression","totalProgression","position"]);return Object.entries(t).forEach(([o,a])=>{s.has(o)||r.set(o,a)}),new S({fragments:Te(t.fragments||t.fragment),progression:e!==void 0&&e>=0&&e<=1?e:void 0,totalProgression:A!==void 0&&A>=0&&A<=1?A:void 0,position:i!==void 0&&i>0?i:void 0,otherLocations:r.size===0?void 0:r})}serialize(){const t={};return this.fragments&&(t.fragments=this.fragments),this.progression!==void 0&&(t.progression=this.progression),this.totalProgression!==void 0&&(t.totalProgression=this.totalProgression),this.position!==void 0&&(t.position=this.position),this.otherLocations&&this.otherLocations.forEach((e,A)=>t[A]=e),t}}class lt{constructor(t){this.after=t.after,this.before=t.before,this.highlight=t.highlight}static deserialize(t){if(t)return new lt({after:t.after,before:t.before,highlight:t.highlight})}serialize(){const t={};return this.after!==void 0&&(t.after=this.after),this.before!==void 0&&(t.before=this.before),this.highlight!==void 0&&(t.highlight=this.highlight),t}}class tt{constructor(t){this.href=t.href,this.type=t.type,this.title=t.title,this.locations=t.locations?t.locations:new S({}),this.text=t.text}static deserialize(t){if(t&&t.href&&t.type)return new tt({href:t.href,type:t.type,title:t.title,locations:S.deserialize(t.locations),text:lt.deserialize(t.text)})}serialize(){const t={href:this.href,type:this.type};return this.title!==void 0&&(t.title=this.title),this.locations&&(t.locations=this.locations.serialize()),this.text&&(t.text=this.text.serialize()),t}copyWithLocations(t){return new tt({href:this.href,type:this.type,title:this.title,text:this.text,locations:new S({...this.locations,...t})})}}class ht{constructor(t){this.href=t.href,this.templated=t.templated,this.type=t.type,this.title=t.title,this.rels=t.rels,this.properties=t.properties,this.height=t.height,this.width=t.width,this.duration=t.duration,this.bitrate=t.bitrate,this.languages=t.languages,this.alternates=t.alternates,this.children=t.children}static deserialize(t){if(!(!t||typeof t.href!="string"))return new ht({href:t.href,templated:t.templated,type:t.type,title:t.title,rels:t.rel?t.rel instanceof Array?new Set(t.rel):new Set([t.rel]):void 0,properties:R.deserialize(t.properties),height:D(t.height),width:D(t.width),duration:D(t.duration),bitrate:D(t.bitrate),languages:Te(t.language),alternates:Nt.deserialize(t.alternate),children:Nt.deserialize(t.children)})}serialize(){const t={href:this.href};return this.templated!==void 0&&(t.templated=this.templated),this.type!==void 0&&(t.type=this.type),this.title!==void 0&&(t.title=this.title),this.rels&&(t.rel=Qi(this.rels)),this.properties&&(t.properties=this.properties.serialize()),this.height!==void 0&&(t.height=this.height),this.width!==void 0&&(t.width=this.width),this.duration!==void 0&&(t.duration=this.duration),this.bitrate!==void 0&&(t.bitrate=this.bitrate),this.languages&&(t.language=this.languages),this.alternates&&(t.alternate=this.alternates.serialize()),this.children&&(t.children=this.children.serialize()),t}get mediaType(){return this.type!==void 0?u.parse({mediaType:this.type}):u.BINARY}toURL(t){const e=this.href.replace(/^(\/)/,"");if(e.length===0)return;let A=t||"/";return A.startsWith("/")&&(A="file://"+A),new URL(e,A).href.replace(/^(file:\/\/)/,"")}get templateParameters(){return this.templated?new xe(this.href).parameters:new Set}expandTemplate(t){return new ht({href:new xe(this.href).expand(t),templated:!1})}addProperties(t){var e;const A=ht.deserialize(this.serialize());return A.properties=A.properties?(e=A.properties)==null?void 0:e.add(t):new R(t),A}get locator(){let t=this.href.split("#");return new tt({href:t.length>0&&t[0]!==void 0?t[0]:this.href,type:this.type??"",title:this.title,locations:new S({fragments:t.length>1&&t[1]!==void 0?[t[1]]:[]})})}}class Nt{constructor(t){this.items=t}static deserialize(t){if(t&&t instanceof Array)return new Nt(t.map(e=>ht.deserialize(e)).filter(e=>e!==void 0))}serialize(){return this.items.map(t=>t.serialize())}findWithRel(t){const e=A=>A.rels&&A.rels.has(t);return this.items.find(e)}filterByRel(t){const e=A=>A.rels&&A.rels.has(t);return this.items.filter(e)}findWithHref(t){const e=A=>A.href===t;return this.items.find(e)}findIndexWithHref(t){const e=A=>A.href===t;return this.items.findIndex(e)}findWithMediaType(t){const e=A=>A.mediaType.matches(t);return this.items.find(e)}filterByMediaType(t){const e=A=>A.mediaType.matches(t);return this.items.filter(e)}filterByMediaTypes(t){const e=A=>{for(const i of t)if(A.mediaType.matches(i))return!0;return!1};return this.items.filter(e)}everyIsAudio(){const t=e=>e.mediaType.isAudio;return this.items.length>0&&this.items.every(t)}everyIsBitmap(){const t=e=>e.mediaType.isBitmap;return this.items.length>0&&this.items.every(t)}everyIsHTML(){const t=e=>e.mediaType.isHTML;return this.items.length>0&&this.items.every(t)}everyIsVideo(){const t=e=>e.mediaType.isVideo;return this.items.length>0&&this.items.every(t)}everyMatchesMediaType(t){return Array.isArray(t)?this.items.length>0&&this.items.every(e=>{for(const A of t)return e.mediaType.matches(A);return!1}):this.items.length>0&&this.items.every(e=>e.mediaType.matches(t))}filterLinksHasType(){return this.items.filter(t=>t.type)}}class $t{constructor(t){this.algorithm=t.algorithm,this.compression=t.compression,this.originalLength=t.originalLength,this.profile=t.profile,this.scheme=t.scheme}static deserialize(t){if(t&&t.algorithm)return new $t({algorithm:t.algorithm,compression:t.compression,originalLength:t.originalLength,profile:t.profile,scheme:t.scheme})}serialize(){const t={algorithm:this.algorithm};return this.compression!==void 0&&(t.compression=this.compression),this.originalLength!==void 0&&(t.originalLength=this.originalLength),this.profile!==void 0&&(t.profile=this.profile),this.scheme!==void 0&&(t.scheme=this.scheme),t}}Object.defineProperty(R.prototype,"encryption",{get:function(){return $t.deserialize(this.otherProperties.encrypted)}});class xt{constructor(t){this.cssSelector=t.cssSelector,this.textNodeIndex=t.textNodeIndex,this.charOffset=t.charOffset}static deserialize(t){if(!(t&&t.cssSelector))return;let e=D(t.textNodeIndex);if(e===void 0)return;let A=D(t.charOffset);return A===void 0&&(A=D(t.offset)),new xt({cssSelector:t.cssSelector,textNodeIndex:e,charOffset:A})}serialize(){const t={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(t.charOffset=this.charOffset),t}}class te{constructor(t){this.start=t.start,this.end=t.end}static deserialize(t){if(!t)return;let e=xt.deserialize(t.start);if(e)return new te({start:e,end:xt.deserialize(t.end)})}serialize(){const t={start:this.start.serialize()};return this.end&&(t.end=this.end.serialize()),t}}S.prototype.getCssSelector=function(){var n;return(n=this.otherLocations)==null?void 0:n.get("cssSelector")},S.prototype.getPartialCfi=function(){var n;return(n=this.otherLocations)==null?void 0:n.get("partialCfi")},S.prototype.getDomRange=function(){var n;return te.deserialize((n=this.otherLocations)==null?void 0:n.get("domRange"))},S.prototype.fragmentParameters=function(){return new Map(this.fragments.map(n=>n.startsWith("#")?n.slice(1):n).join("&").split("&").filter(n=>!n.startsWith("#")).map(n=>n.split("=")).filter(n=>n.length===2).map(n=>[n[0].trim().toLowerCase(),n[1].trim()]))},S.prototype.htmlId=function(){if(!this.fragments.length)return;let n=this.fragments.find(t=>t.length&&!t.includes("="));if(!n){const t=this.fragmentParameters();t.has("id")?n=t.get("id"):t.has("name")&&(n=t.get("name"))}return n!=null&&n.startsWith("#")?n.slice(1):n},S.prototype.page=function(){const n=parseInt(this.fragmentParameters().get("page"));if(!isNaN(n)&&n>=0)return n},S.prototype.time=function(){const n=parseInt(this.fragmentParameters().get("t"));if(!isNaN(n))return n},S.prototype.space=function(){const n=this.fragmentParameters();if(!n.has("xywh"))return;const t=n.get("xywh").split(",").map(e=>parseInt(e));if(t.length===4&&!t.some(isNaN))return t};class ee{constructor(t){this.currency=t.currency,this.value=t.value}static deserialize(t){if(!t)return;let e=t.currency;if(!(e&&typeof e=="string"&&e.length>0))return;let A=D(t.value);if(A!==void 0)return new ee({currency:e,value:A})}serialize(){return{currency:this.currency,value:this.value}}}class It{constructor(t){this.type=t.type,this.children=t.children}static deserialize(t){if(t&&t.type)return new It({type:t.type,children:It.deserializeArray(t.children)})}static deserializeArray(t){if(t instanceof Array)return t.map(e=>It.deserialize(e)).filter(e=>e!==void 0)}serialize(){const t={type:this.type};return this.children&&(t.children=this.children.map(e=>e.serialize())),t}}class Ae{constructor(t){this.total=t.total,this.position=t.position}static deserialize(t){if(t)return new Ae({total:D(t.total),position:D(t.position)})}serialize(){const t={};return this.total!==void 0&&(t.total=this.total),this.position!==void 0&&(t.position=this.position),t}}class ie{constructor(t){this.total=t.total,this.available=t.available}static deserialize(t){if(t)return new ie({total:D(t.total),available:D(t.available)})}serialize(){const t={};return this.total!==void 0&&(t.total=this.total),this.available!==void 0&&(t.available=this.available),t}}class ne{constructor(t){this.state=t.state,this.since=t.since,this.until=t.until}static deserialize(t){if(t&&t.state)return new ne({state:t.state,since:je(t.since),until:je(t.until)})}serialize(){const t={state:this.state};return this.since!==void 0&&(t.since=this.since.toISOString()),this.until!==void 0&&(t.until=this.until.toISOString()),t}}R.prototype.getNumberOfItems=function(){return D(this.otherProperties.numberOfItems)},R.prototype.getPrice=function(){return ee.deserialize(this.otherProperties.price)},R.prototype.getIndirectAcquisitions=function(){const n=this.otherProperties.indirectAcquisition;if(n&&n instanceof Array)return n.map(t=>It.deserialize(t)).filter(t=>t!==void 0)},R.prototype.getHolds=function(){return Ae.deserialize(this.otherProperties.holds)},R.prototype.getCopies=function(){return ie.deserialize(this.otherProperties.copies)},R.prototype.getAvailability=function(){return ne.deserialize(this.otherProperties.availability)},R.prototype.getAuthenticate=function(){return ht.deserialize(this.otherProperties.authenticate)},R.prototype.getClipped=function(){return this.otherProperties.clipped},R.prototype.getFit=function(){return this.otherProperties.fit},R.prototype.getOrientation=function(){return this.otherProperties.orientation},R.prototype.getOverflow=function(){return this.otherProperties.overflow},R.prototype.getPage=function(){return this.otherProperties.page||void 0},R.prototype.getSpread=function(){return this.otherProperties.spread||void 0};var et;(function(n){n.NONE="none",n.DESCENDANT="descendant",n.CHILD="child"})(et||(et={}));var k;(function(n){n.id="id",n.class="class",n.tag="tag",n.attribute="attribute",n.nthchild="nthchild",n.nthoftype="nthoftype"})(k||(k={}));const zi="CssSelectorGenerator";function Ve(n="unknown problem",...t){console.warn(`${zi}: ${n}`,...t)}k.id,k.class,k.tag,k.attribute;function Yi(n){return n instanceof RegExp}function Si(n){return n.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".+")}function Ni(n){const t=n.map(e=>{if(Yi(e))return A=>e.test(A);if(typeof e=="function")return A=>{const i=e(A);return typeof i!="boolean"?(Ve("pattern matcher function invalid","Provided pattern matching function does not return boolean. It's result will be ignored.",e),!1):i};if(typeof e=="string"){const A=new RegExp("^"+Si(e)+"$");return i=>A.test(i)}return Ve("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",e),()=>!1});return e=>t.some(A=>A(e))}et.NONE+"",et.NONE,et.DESCENDANT+"",et.DESCENDANT,et.CHILD+"",et.CHILD,k.nthoftype,k.tag,k.id,k.class,k.attribute,k.nthchild,Ni(["class","id","ng-*"]);class Tt{}function Pe(n){return n.split("").reverse().join("")}function xi(n,t,e){const A=Pe(t);return e.map(i=>{const r=Math.max(0,i.end-t.length-i.errors),s=Pe(n.slice(r,i.end));return{start:ve(s,A,i.errors).reduce((o,a)=>i.end-a.end<o?i.end-a.end:o,i.end),end:i.end,errors:i.errors}})}function re(n){return(n|-n)>>31&1}function De(n,t,e,A){let i=n.P[e],r=n.M[e];const s=A>>>31,o=t[e]|s,a=o|r,l=(o&i)+i^i|o;let h=r|~(l|i),c=i&l;const g=re(h&n.lastRowMask[e])-re(c&n.lastRowMask[e]);return h<<=1,c<<=1,c|=s,h|=re(A)-s,i=c|~(a|h),r=h&a,n.P[e]=i,n.M[e]=r,g}function ve(n,t,e){if(t.length===0)return[];e=Math.min(e,t.length);const A=[],i=32,r=Math.ceil(t.length/i)-1,s={P:new Uint32Array(r+1),M:new Uint32Array(r+1),lastRowMask:new Uint32Array(r+1)};s.lastRowMask.fill(1<<31),s.lastRowMask[r]=1<<(t.length-1)%i;const o=new Uint32Array(r+1),a=new Map,l=[];for(let g=0;g<256;g++)l.push(o);for(let g=0;g<t.length;g+=1){const m=t.charCodeAt(g);if(a.has(m))continue;const M=new Uint32Array(r+1);a.set(m,M),m<l.length&&(l[m]=M);for(let B=0;B<=r;B+=1){M[B]=0;for(let f=0;f<i;f+=1){const F=B*i+f;F>=t.length||t.charCodeAt(F)===m&&(M[B]|=1<<f)}}}let h=Math.max(0,Math.ceil(e/i)-1);const c=new Uint32Array(r+1);for(let g=0;g<=h;g+=1)c[g]=(g+1)*i;c[r]=t.length;for(let g=0;g<=h;g+=1)s.P[g]=-1,s.M[g]=0;for(let g=0;g<n.length;g+=1){const m=n.charCodeAt(g);let M;m<l.length?M=l[m]:(M=a.get(m),typeof M>"u"&&(M=o));let B=0;for(let f=0;f<=h;f+=1)B=De(s,M,f,B),c[f]+=B;if(c[h]-B<=e&&h<r&&(M[h+1]&1||B<0)){h+=1,s.P[h]=-1,s.M[h]=0;let f;if(h===r){const F=t.length%i;f=F===0?i:F}else f=i;c[h]=c[h-1]+f-B+De(s,M,h,B)}else for(;h>0&&c[h]>=e+i;)h-=1;h===r&&c[h]<=e&&(c[h]<e&&A.splice(0,A.length),A.push({start:-1,end:g+1,errors:c[h]}),e=c[h])}return A}function Ti(n,t,e){const A=ve(n,t,e);return xi(n,t,A)}function be(n,t,e){let A=0;const i=[];for(;A!==-1;)A=n.indexOf(t,A),A!==-1&&(i.push({start:A,end:A+t.length,errors:0}),A+=1);return i.length>0?i:Ti(n,t,e)}function Ge(n,t){return t.length===0||n.length===0?0:1-be(n,t,t.length)[0].errors/t.length}function ji(n,t,e={}){if(t.length===0)return null;const A=Math.min(256,t.length/2),i=be(n,t,A);if(i.length===0)return null;const r=o=>{const a=1-o.errors/t.length,l=e.prefix?Ge(n.slice(Math.max(0,o.start-e.prefix.length),o.start),e.prefix):1,h=e.suffix?Ge(n.slice(o.end,o.end+e.suffix.length),e.suffix):1;let c=1;typeof e.hint=="number"&&(c=1-Math.abs(o.start-e.hint)/n.length);const g=50*a+20*l+20*h+2*c,m=50+20+20+2;return g/m},s=i.map(o=>({start:o.start,end:o.end,score:r(o)}));return s.sort((o,a)=>a.score-o.score),s[0]}function se(n,t,e){const A=e===1?t:t-1;if(n.charAt(A).trim()!=="")return t;let i,r;if(e===2?(i=n.substring(0,t),r=i.trimEnd()):(i=n.substring(t),r=i.trimStart()),!r.length)return-1;const s=i.length-r.length;return e===2?t-s:t+s}function He(n,t){const e=n.commonAncestorContainer.ownerDocument.createNodeIterator(n.commonAncestorContainer,NodeFilter.SHOW_TEXT),A=t===1?n.startContainer:n.endContainer,i=t===1?n.endContainer:n.startContainer;let r=e.nextNode();for(;r&&r!==A;)r=e.nextNode();t===2&&(r=e.previousNode());let s=-1;const o=()=>{if(r=t===1?e.nextNode():e.previousNode(),r){const a=r.textContent,l=t===1?0:a.length;s=se(a,l,t)}};for(;r&&s===-1&&r!==i;)o();if(r&&s>=0)return{node:r,offset:s};throw new RangeError("No text nodes with non-whitespace text found in range")}function Vi(n){if(!n.toString().trim().length)throw new RangeError("Range contains no non-whitespace text");if(n.startContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range startContainer is not a text node");if(n.endContainer.nodeType!==Node.TEXT_NODE)throw new RangeError("Range endContainer is not a text node");const t=n.cloneRange();let e=!1,A=!1;const i={start:se(n.startContainer.textContent,n.startOffset,1),end:se(n.endContainer.textContent,n.endOffset,2)};if(i.start>=0&&(t.setStart(n.startContainer,i.start),e=!0),i.end>0&&(t.setEnd(n.endContainer,i.end),A=!0),e&&A)return t;if(!e){const{node:r,offset:s}=He(t,1);r&&s>=0&&t.setStart(r,s)}if(!A){const{node:r,offset:s}=He(t,2);r&&s>0&&t.setEnd(r,s)}return t}function ke(n){var t;switch(n.nodeType){case Node.ELEMENT_NODE:case Node.TEXT_NODE:return((t=n.textContent)==null?void 0:t.length)??0;default:return 0}}function Je(n){let t=n.previousSibling,e=0;for(;t;)e+=ke(t),t=t.previousSibling;return e}function We(n,...t){let e=t.shift();const A=n.ownerDocument.createNodeIterator(n,NodeFilter.SHOW_TEXT),i=[];let r=A.nextNode(),s,o=0;for(;e!==void 0&&r;)s=r,o+s.data.length>e?(i.push({node:s,offset:e-o}),e=t.shift()):(r=A.nextNode(),o+=s.data.length);for(;e!==void 0&&s&&o===e;)i.push({node:s,offset:s.data.length}),e=t.shift();if(e!==void 0)throw new RangeError("Offset exceeds text length");return i}class Z{constructor(t,e){if(e<0)throw new Error("Offset is invalid");this.element=t,this.offset=e}relativeTo(t){if(!t.contains(this.element))throw new Error("Parent is not an ancestor of current element");let e=this.element,A=this.offset;for(;e!==t;)A+=Je(e),e=e.parentElement;return new Z(e,A)}resolve(t={}){try{return We(this.element,this.offset)[0]}catch(e){if(this.offset===0&&t.direction!==void 0){const A=document.createTreeWalker(this.element.getRootNode(),NodeFilter.SHOW_TEXT);A.currentNode=this.element;const i=t.direction===1,r=i?A.nextNode():A.previousNode();if(!r)throw e;return{node:r,offset:i?0:r.data.length}}else throw e}}static fromCharOffset(t,e){switch(t.nodeType){case Node.TEXT_NODE:return Z.fromPoint(t,e);case Node.ELEMENT_NODE:return new Z(t,e);default:throw new Error("Node is not an element or text node")}}static fromPoint(t,e){switch(t.nodeType){case Node.TEXT_NODE:{if(e<0||e>t.data.length)throw new Error("Text node offset is out of range");if(!t.parentElement)throw new Error("Text node has no parent");const A=Je(t)+e;return new Z(t.parentElement,A)}case Node.ELEMENT_NODE:{if(e<0||e>t.childNodes.length)throw new Error("Child node offset is out of range");let A=0;for(let i=0;i<e;i++)A+=ke(t.childNodes[i]);return new Z(t,A)}default:throw new Error("Point is not in an element or text node")}}}class At{constructor(t,e){this.start=t,this.end=e}relativeTo(t){return new At(this.start.relativeTo(t),this.end.relativeTo(t))}toRange(){let t,e;this.start.element===this.end.element&&this.start.offset<=this.end.offset?[t,e]=We(this.start.element,this.start.offset,this.end.offset):(t=this.start.resolve({direction:1}),e=this.end.resolve({direction:2}));const A=new Range;return A.setStart(t.node,t.offset),A.setEnd(e.node,e.offset),A}static fromRange(t){const e=Z.fromPoint(t.startContainer,t.startOffset),A=Z.fromPoint(t.endContainer,t.endOffset);return new At(e,A)}static fromOffsets(t,e,A){return new At(new Z(t,e),new Z(t,A))}static trimmedRange(t){return Vi(At.fromRange(t).toRange())}}class jt{constructor(t,e,A){this.root=t,this.start=e,this.end=A}static fromRange(t,e){const A=At.fromRange(e).relativeTo(t);return new jt(t,A.start.offset,A.end.offset)}static fromSelector(t,e){return new jt(t,e.start,e.end)}toSelector(){return{type:"TextPositionSelector",start:this.start,end:this.end}}toRange(){return At.fromOffsets(this.root,this.start,this.end).toRange()}}class Vt{constructor(t,e,A={}){this.root=t,this.exact=e,this.context=A}static fromRange(t,e){const A=t.textContent,i=At.fromRange(e).relativeTo(t),r=i.start.offset,s=i.end.offset,o=32;return new Vt(t,A.slice(r,s),{prefix:A.slice(Math.max(0,r-o),r),suffix:A.slice(s,Math.min(A.length,s+o))})}static fromSelector(t,e){const{prefix:A,suffix:i}=e;return new Vt(t,e.exact,{prefix:A,suffix:i})}toSelector(){return{type:"TextQuoteSelector",exact:this.exact,prefix:this.context.prefix,suffix:this.context.suffix}}toRange(t={}){return this.toPositionAnchor(t).toRange()}toPositionAnchor(t={}){const e=this.root.textContent,A=ji(e,this.exact,{...this.context,hint:t.hint});if(!A)throw new Error("Quote not found");return new jt(this.root,A.start,A.end)}}function Pi(n){const t=n.tagName.toUpperCase();return t==="IMG"||t==="VIDEO"||t==="AUDIO"||t==="IFRAME"||t==="OBJECT"||t==="EMBED"||t==="CANVAS"}function oe(n,t){try{const e=t.locations,A=t.text;if(A&&A.highlight){let i;e&&e.getCssSelector()&&(i=n.querySelector(e.getCssSelector())),i||(i=n.body);const r=new Vt(i,A.highlight,{prefix:A.before,suffix:A.after});try{return r.toRange()}catch{return console.warn("Quote not found:",r),null}}if(e){let i=null;if(!i&&e.getCssSelector()&&(i=n.querySelector(e.getCssSelector())),!i&&e.fragments){for(const r of e.fragments)if(i=n.getElementById(r),i)break}if(i){const r=n.createRange();return i.childNodes.length===0||Pi(i)?(r.selectNode(i),r):(r.setStartBefore(i),r.setEndAfter(i),r)}}}catch(e){console.error(e)}return null}function Di(n,t){let e=n.getClientRects();e.length||n.commonAncestorContainer.nodeType===Node.ELEMENT_NODE&&(e=n.commonAncestorContainer.getClientRects());const A=1,i=[];for(const l of e)i.push({bottom:l.bottom,height:l.height,left:l.left,right:l.right,top:l.top,width:l.width});const r=Le(i,A,t),s=bi(r,A),o=Oe(s),a=2*2;for(let l=o.length-1;l>=0;l--){const h=o[l];if(!(h.width*h.height>a))if(o.length>1)o.splice(l,1);else break}return o}function Le(n,t,e){for(let A=0;A<n.length;A++)for(let i=A+1;i<n.length;i++){const r=n[A],s=n[i];if(r===s)continue;const o=J(r.top,s.top,t)&&J(r.bottom,s.bottom,t),a=J(r.left,s.left,t)&&J(r.right,s.right,t);if((a&&!e||o&&!a)&&Ze(r,s,t)){const l=n.filter(c=>c!==r&&c!==s),h=vi(r,s);return l.push(h),Le(l,t,e)}}return n}function vi(n,t){const e=Math.min(n.left,t.left),A=Math.max(n.right,t.right),i=Math.min(n.top,t.top),r=Math.max(n.bottom,t.bottom);return{bottom:r,height:r-i,left:e,right:A,top:i,width:A-e}}function bi(n,t){const e=new Set(n);for(const A of n){if(!(A.width>1&&A.height>1)){e.delete(A);continue}for(const i of n)if(A!==i&&e.has(i)&&Gi(i,A,t)){e.delete(A);break}}return Array.from(e)}function Gi(n,t,e){return Pt(n,t.left,t.top,e)&&Pt(n,t.right,t.top,e)&&Pt(n,t.left,t.bottom,e)&&Pt(n,t.right,t.bottom,e)}function Pt(n,t,e,A){return(n.left<t||J(n.left,t,A))&&(n.right>t||J(n.right,t,A))&&(n.top<e||J(n.top,e,A))&&(n.bottom>e||J(n.bottom,e,A))}function Oe(n){for(let t=0;t<n.length;t++)for(let e=t+1;e<n.length;e++){const A=n[t],i=n[e];if(A!==i&&Ze(A,i,-1)){let r=[],s;const o=Xe(A,i);if(o.length===1)r=o,s=A;else{const l=Xe(i,A);o.length<l.length?(r=o,s=A):(r=l,s=i)}const a=n.filter(l=>l!==s);return Array.prototype.push.apply(a,r),Oe(a)}}return n}function Xe(n,t){const e=Hi(t,n);if(e.height===0||e.width===0)return[n];const A=[];{const i={bottom:n.bottom,height:0,left:n.left,right:e.left,top:n.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&A.push(i)}{const i={bottom:e.top,height:0,left:e.left,right:e.right,top:n.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&A.push(i)}{const i={bottom:n.bottom,height:0,left:e.left,right:e.right,top:e.bottom,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&A.push(i)}{const i={bottom:n.bottom,height:0,left:e.right,right:n.right,top:n.top,width:0};i.width=i.right-i.left,i.height=i.bottom-i.top,i.height!==0&&i.width!==0&&A.push(i)}return A}function Hi(n,t){const e=Math.max(n.left,t.left),A=Math.min(n.right,t.right),i=Math.max(n.top,t.top),r=Math.min(n.bottom,t.bottom);return{bottom:r,height:Math.max(0,r-i),left:e,right:A,top:i,width:Math.max(0,A-e)}}function Ze(n,t,e){return(n.left<t.right||e>=0&&J(n.left,t.right,e))&&(t.left<n.right||e>=0&&J(t.left,n.right,e))&&(n.top<t.bottom||e>=0&&J(n.top,t.bottom,e))&&(t.top<n.bottom||e>=0&&J(t.top,n.bottom,e))}function J(n,t,e){return Math.abs(n-t)<=e}function Ke(n){const t={},e=n.document.documentElement.style;for(const A in n.document.documentElement.style)Object.hasOwn(e,A)&&!Number.isNaN(Number.parseInt(A))&&(t[e[A]]=e.getPropertyValue(e[A]));return t}function ki(n,t){const e=Ke(n);Object.keys(e).forEach(A=>{t.hasOwnProperty(A)||ae(n,A)}),Object.entries(t).forEach(([A,i])=>{e[A]!==i&&Dt(n,A,i)})}function qe(n,t){return n.document.documentElement.style.getPropertyValue(t)}function Dt(n,t,e){n.document.documentElement.style.setProperty(t,e)}function ae(n,t){n.document.documentElement.style.removeProperty(t)}const Ji=n=>{if(n.startsWith("rgb")){const t=n.match(/rgb\((\d+),\s(\d+),\s(\d+)(?:,\s(\d+))?\)/);if(t)return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10),a:t[4]?parseInt(t[4],10)/255:1}}else if(n.startsWith("#")){const t=n.slice(1);if(t.length===3||t.length===4)return{r:parseInt(t[0]+t[0],16)/255,g:parseInt(t[1]+t[1],16)/255,b:parseInt(t[2]+t[2],16)/255,a:t.length===4?parseInt(t[3]+t[3],16)/255:1};if(t.length===6||t.length===8)return{r:parseInt(t[0]+t[1],16)/255,g:parseInt(t[2]+t[3],16)/255,b:parseInt(t[4]+t[5],16)/255,a:t.length===8?parseInt(t[6]+t[7],16)/255:1}}return{r:0,g:0,b:0,a:1}},Wi=n=>.2126*n.r*n.a+.7152*n.g*n.a+.0722*n.b*n.a,Li=n=>{const t=Ji(n);return Wi(t)<128},Oi=()=>"Highlight"in window,_e=["IMG","IMAGE","AUDIO","VIDEO","SVG"];class Xi{constructor(t,e,A,i){this.wnd=t,this.comms=e,this.id=A,this.name=i,this.items=[],this.lastItemId=0,this.container=void 0,this.activateable=!1,this.experimentalHighlights=!1,this.currentRender=0,Oi()&&(this.experimentalHighlights=!0,this.notTextFlag=new Map)}get activeable(){return this.activateable}set activeable(t){this.activateable=t}add(t){var e,A,i,r;const s=`${this.id}-${this.lastItemId++}`,o=oe(this.wnd.document,t.locator);if(!o){this.comms.log("Can't locate DOM range for decoration",t);return}const a=o.commonAncestorContainer;a.nodeType!==Node.TEXT_NODE&&this.experimentalHighlights&&(_e.includes(a.nodeName.toUpperCase())&&((e=this.notTextFlag)==null||e.set(s,!0)),a.querySelector(_e.join(", ").toLowerCase())&&((A=this.notTextFlag)==null||A.set(s,!0)),(((i=a.textContent)==null?void 0:i.trim())||"").length===0&&((r=this.notTextFlag)==null||r.set(s,!0)));const l={decoration:t,id:s,range:o};this.items.push(l),this.layout(l),this.renderLayout([l])}remove(t){var e,A;const i=this.items.findIndex(s=>s.decoration.id===t);if(i<0)return;const r=this.items[i];if(this.items.splice(i,1),r.clickableElements=void 0,r.container&&(r.container.remove(),r.container=void 0),this.experimentalHighlights&&!((e=this.notTextFlag)!=null&&e.has(r.id))){const s=this.wnd.CSS.highlights.get(this.id);s==null||s.delete(r.range)}(A=this.notTextFlag)==null||A.delete(r.id)}update(t){this.remove(t.id),this.add(t)}clear(){var t;this.clearContainer(),this.items.length=0,(t=this.notTextFlag)==null||t.clear()}requestLayout(){this.wnd.cancelAnimationFrame(this.currentRender),this.clearContainer(),this.items.forEach(t=>this.layout(t)),this.renderLayout(this.items)}experimentalLayout(t){var e,A;const[i,r]=this.requireContainer(!0);r.add(t.range),i.innerHTML=`
28
28
  ::highlight(${this.id}) {
29
29
  color: black;
30
- background-color: ${((e=(t=A.decoration)==null?void 0:t.style)==null?void 0:e.tint)??"yellow"};
31
- }`}layout(A){var t,e,n,r,s;if(this.experimentalHighlights&&!((t=this.notTextFlag)!=null&&t.has(A.id)))return this.experimentalLayout(A);const o=this.wnd.document.createElement("div");o.setAttribute("id",A.id),o.style.setProperty("pointer-events","none");const a=this.wnd.innerWidth,h=parseInt(getComputedStyle(this.wnd.document.documentElement).getPropertyValue("column-count")),c=a/(h||1),l=this.wnd.document.scrollingElement,g=l.scrollLeft,u=l.scrollTop,m=(I,w,Y)=>{var oA,_,$,AA,TA,xA;if(I.style.position="absolute",((_=(oA=A.decoration)==null?void 0:oA.style)==null?void 0:_.width)==="viewport"){I.style.width=`${a}px`,I.style.height=`${w.height}px`;let aA=Math.floor(w.left/a)*a;I.style.left=`${aA+g}px`,I.style.top=`${w.top+u}px`}else if(((AA=($=A.decoration)==null?void 0:$.style)==null?void 0:AA.width)==="bounds")I.style.width=`${Y.width}px`,I.style.height=`${w.height}px`,I.style.left=`${Y.left+g}px`,I.style.top=`${w.top+u}px`;else if(((xA=(TA=A.decoration)==null?void 0:TA.style)==null?void 0:xA.width)==="page"){I.style.width=`${c}px`,I.style.height=`${w.height}px`;let aA=Math.floor(w.left/c)*c;I.style.left=`${aA+g}px`,I.style.top=`${w.top+u}px`}else I.style.width=`${w.width}px`,I.style.height=`${w.height}px`,I.style.left=`${w.left+g}px`,I.style.top=`${w.top+u}px`},B=A.range.getBoundingClientRect();let f=this.wnd.document.createElement("template");const E=Ji(this.wnd,"--USER__appearance")==="readium-night-on";f.innerHTML=`
30
+ background-color: ${((A=(e=t.decoration)==null?void 0:e.style)==null?void 0:A.tint)??"yellow"};
31
+ }`}layout(t){var e,A,i,r,s;if(this.experimentalHighlights&&!((e=this.notTextFlag)!=null&&e.has(t.id)))return this.experimentalLayout(t);const o=this.wnd.document.createElement("div");o.setAttribute("id",t.id),o.style.setProperty("pointer-events","none");const a=this.wnd.innerWidth,l=parseInt(getComputedStyle(this.wnd.document.documentElement).getPropertyValue("column-count")),h=a/(l||1),c=this.wnd.document.scrollingElement,g=c.scrollLeft,m=c.scrollTop,M=(I,U,v)=>{var kt,Qt,JA,WA,LA,OA;if(I.style.position="absolute",((Qt=(kt=t.decoration)==null?void 0:kt.style)==null?void 0:Qt.width)==="viewport"){I.style.width=`${a}px`,I.style.height=`${U.height}px`;let Me=Math.floor(U.left/a)*a;I.style.left=`${Me+g}px`,I.style.top=`${U.top+m}px`}else if(((WA=(JA=t.decoration)==null?void 0:JA.style)==null?void 0:WA.width)==="bounds")I.style.width=`${v.width}px`,I.style.height=`${U.height}px`,I.style.left=`${v.left+g}px`,I.style.top=`${U.top+m}px`;else if(((OA=(LA=t.decoration)==null?void 0:LA.style)==null?void 0:OA.width)==="page"){I.style.width=`${h}px`,I.style.height=`${U.height}px`;let Me=Math.floor(U.left/h)*h;I.style.left=`${Me+g}px`,I.style.top=`${U.top+m}px`}else I.style.width=`${U.width}px`,I.style.height=`${U.height}px`,I.style.left=`${U.left+g}px`,I.style.top=`${U.top+m}px`},B=t.range.getBoundingClientRect();let f=this.wnd.document.createElement("template");const F=qe(this.wnd,"--USER__appearance")==="readium-night-on"||Li(qe(this.wnd,"--USER__backgroundColor"));f.innerHTML=`
32
32
  <div
33
33
  class="r2-highlight-0"
34
- style="${[`background-color: ${((n=(e=A.decoration)==null?void 0:e.style)==null?void 0:n.tint)??"yellow"} !important`,`mix-blend-mode: ${E?"exclusion":"multiply"} !important`,"opacity: 1 !important","box-sizing: border-box !important"].join("; ")}"
34
+ style="${[`background-color: ${((i=(A=t.decoration)==null?void 0:A.style)==null?void 0:i.tint)??"yellow"} !important`,`mix-blend-mode: ${F?"exclusion":"multiply"} !important`,"opacity: 1 !important","box-sizing: border-box !important"].join("; ")}"
35
35
  >
36
36
  </div>
37
- `.trim();const p=f.content.firstElementChild;if(((s=(r=A.decoration)==null?void 0:r.style)==null?void 0:s.layout)==="bounds"){const I=p.cloneNode(!0);I.style.setProperty("pointer-events","none"),m(I,B,B),o.append(I)}else{let I=Bi(A.range,!0);I=I.sort((w,Y)=>w.top<Y.top?-1:w.top>Y.top?1:0);for(let w of I){const Y=p.cloneNode(!0);Y.style.setProperty("pointer-events","none"),m(Y,w,B),o.append(Y)}}A.container=o,A.clickableElements=Array.from(o.querySelectorAll("[data-activable='1']")),A.clickableElements.length||(A.clickableElements=Array.from(o.children))}renderLayout(A){this.wnd.cancelAnimationFrame(this.currentRender),this.currentRender=this.wnd.requestAnimationFrame(()=>{A=A.filter(t=>{var e;return!this.experimentalHighlights||!!((e=this.notTextFlag)!=null&&e.has(t.id))}),!(!A||A.length===0)&&this.requireContainer().append(...A.map(t=>t.container).filter(t=>!!t))})}requireContainer(A=!1){if(A){let t;this.wnd.document.getElementById(`${this.id}-style`)?t=this.wnd.document.getElementById(`${this.id}-style`):(t=this.wnd.document.createElement("style"),t.dataset.readium="true",t.id=`${this.id}-style`,this.wnd.document.head.appendChild(t));let e;return this.wnd.CSS.highlights.has(this.id)?e=this.wnd.CSS.highlights.get(this.id):(e=new this.wnd.Highlight,this.wnd.CSS.highlights.set(this.id,e)),[t,e]}return this.container||(this.container=this.wnd.document.createElement("div"),this.container.setAttribute("id",this.id),this.container.dataset.group=this.name,this.container.dataset.readium="true",this.container.style.setProperty("pointer-events","none"),this.container.style.display="contents",this.wnd.document.body.append(this.container)),this.container}clearContainer(){this.experimentalHighlights&&this.wnd.CSS.highlights.delete(this.id),this.container&&(this.container.remove(),this.container=void 0)}}const $t=class st extends pA{constructor(){super(...arguments),this.resizeFrame=0,this.lastGroupId=0,this.groups=new Map,this.handleResizer=this.handleResize.bind(this)}cleanup(){this.groups.forEach(A=>A.clear()),this.groups.clear()}handleResize(){this.wnd.clearTimeout(this.resizeFrame),this.resizeFrame=this.wnd.setTimeout(()=>{this.groups.forEach(A=>{A.experimentalHighlights||A.requestLayout()})},50)}mount(A,t){return this.wnd=A,t.register("decorate",st.moduleName,(e,n)=>{const r=e;r.decoration&&r.decoration.locator&&(r.decoration.locator=W.deserialize(r.decoration.locator)),this.groups.has(r.group)||this.groups.set(r.group,new Wi(A,t,`readium-decoration-${this.lastGroupId++}`,r.group));const s=this.groups.get(r.group);switch(r.action){case"add":s==null||s.add(r.decoration);break;case"remove":s==null||s.remove(r.decoration.id);break;case"clear":s==null||s.clear();break;case"update":s==null||s.update(r.decoration);break}n(!0)}),this.resizeObserver=new Pi(()=>A.requestAnimationFrame(()=>this.handleResize())),this.resizeObserver.observe(A.document.body),A.addEventListener("orientationchange",this.handleResizer),A.addEventListener("resize",this.handleResizer),t.log("Decorator Mounted"),!0}unmount(A,t){return A.removeEventListener("orientationchange",this.handleResizer),A.removeEventListener("resize",this.handleResizer),t.unregisterAll(st.moduleName),this.resizeObserver.disconnect(),this.cleanup(),t.log("Decorator Unmounted"),!0}};$t.moduleName="decorator";let Li=$t;const Ae="readium-snapper-style",te=class ot extends pA{constructor(){super(...arguments),this.protected=!1}buildStyles(){return`
37
+ `.trim();const Q=f.content.firstElementChild;if(((s=(r=t.decoration)==null?void 0:r.style)==null?void 0:s.layout)==="bounds"){const I=Q.cloneNode(!0);I.style.setProperty("pointer-events","none"),M(I,B,B),o.append(I)}else{let I=Di(t.range,!0);I=I.sort((U,v)=>U.top<v.top?-1:U.top>v.top?1:0);for(let U of I){const v=Q.cloneNode(!0);v.style.setProperty("pointer-events","none"),M(v,U,B),o.append(v)}}t.container=o,t.clickableElements=Array.from(o.querySelectorAll("[data-activable='1']")),t.clickableElements.length||(t.clickableElements=Array.from(o.children))}renderLayout(t){this.wnd.cancelAnimationFrame(this.currentRender),this.currentRender=this.wnd.requestAnimationFrame(()=>{t=t.filter(e=>{var A;return!this.experimentalHighlights||!!((A=this.notTextFlag)!=null&&A.has(e.id))}),!(!t||t.length===0)&&this.requireContainer().append(...t.map(e=>e.container).filter(e=>!!e))})}requireContainer(t=!1){if(t){let e;this.wnd.document.getElementById(`${this.id}-style`)?e=this.wnd.document.getElementById(`${this.id}-style`):(e=this.wnd.document.createElement("style"),e.dataset.readium="true",e.id=`${this.id}-style`,this.wnd.document.head.appendChild(e));let A;return this.wnd.CSS.highlights.has(this.id)?A=this.wnd.CSS.highlights.get(this.id):(A=new this.wnd.Highlight,this.wnd.CSS.highlights.set(this.id,A)),[e,A]}return this.container||(this.container=this.wnd.document.createElement("div"),this.container.setAttribute("id",this.id),this.container.dataset.group=this.name,this.container.dataset.readium="true",this.container.style.setProperty("pointer-events","none"),this.container.style.display="contents",this.wnd.document.body.append(this.container)),this.container}clearContainer(){this.experimentalHighlights&&this.wnd.CSS.highlights.delete(this.id),this.container&&(this.container.remove(),this.container=void 0)}}const $e=class Be extends Tt{constructor(){super(...arguments),this.resizeFrame=0,this.lastGroupId=0,this.groups=new Map,this.handleResizer=this.handleResize.bind(this)}cleanup(){this.groups.forEach(t=>t.clear()),this.groups.clear()}handleResize(){this.wnd.clearTimeout(this.resizeFrame),this.resizeFrame=this.wnd.setTimeout(()=>{this.groups.forEach(t=>{t.experimentalHighlights||t.requestLayout()})},50)}mount(t,e){return this.wnd=t,e.register("decorate",Be.moduleName,(A,i)=>{const r=A;r.decoration&&r.decoration.locator&&(r.decoration.locator=tt.deserialize(r.decoration.locator)),this.groups.has(r.group)||this.groups.set(r.group,new Xi(t,e,`readium-decoration-${this.lastGroupId++}`,r.group));const s=this.groups.get(r.group);switch(r.action){case"add":s==null||s.add(r.decoration);break;case"remove":s==null||s.remove(r.decoration.id);break;case"clear":s==null||s.clear();break;case"update":s==null||s.update(r.decoration);break}i(!0)}),this.resizeObserver=new ResizeObserver(()=>t.requestAnimationFrame(()=>this.handleResize())),this.resizeObserver.observe(t.document.body),t.addEventListener("orientationchange",this.handleResizer),t.addEventListener("resize",this.handleResizer),e.log("Decorator Mounted"),!0}unmount(t,e){return t.removeEventListener("orientationchange",this.handleResizer),t.removeEventListener("resize",this.handleResizer),e.unregisterAll(Be.moduleName),this.resizeObserver.disconnect(),this.cleanup(),e.log("Decorator Unmounted"),!0}};$e.moduleName="decorator";let Zi=$e;const tA="readium-snapper-style",eA=class Ee extends Tt{constructor(){super(...arguments),this.protected=!1}buildStyles(){return`
38
38
  html, body {
39
39
  touch-action: manipulation;
40
40
  user-select: ${this.protected?"none":"auto"};
41
- }`}mount(A,t){const e=A.document.createElement("style");return e.dataset.readium="true",e.id=Ae,e.textContent=this.buildStyles(),A.document.head.appendChild(e),t.register("protect",ot.moduleName,(n,r)=>{this.protected=!0,e.textContent=this.buildStyles(),r(!0)}),t.register("unprotect",ot.moduleName,(n,r)=>{this.protected=!1,e.textContent=this.buildStyles(),r(!0)}),t.log("Snapper Mounted"),!0}unmount(A,t){var e;return(e=A.document.getElementById(Ae))==null||e.remove(),t.log("Snapper Unmounted"),!0}};te.moduleName="snapper";let ee=te;function q(i){return i.document.body.dir.toLowerCase()==="rtl"}function ie(i){return parseInt(i.getComputedStyle(i.document.documentElement).getPropertyValue("column-count"))}function Oi(i){const A="readium-virtual-page";let t=i.document.getElementById(A);if(ie(i)!==2)t&&t.remove();else{const e=i.document.scrollingElement.scrollWidth/i.innerWidth;Math.round(e*2)/2%1>.1&&(t?t.remove():(t=i.document.createElement("div"),t.setAttribute("id",A),t.dataset.readium="true",t.style.breakBefore="column",t.innerHTML="&#8203;",i.document.body.appendChild(t)))}}function Xi(i){return i<.5?2*i*i:-1+(4-2*i)*i}function N(i){const A=i.getSelection();A&&A.removeAllRanges()}const Zi=["a","audio","button","canvas","details","input","label","option","select","submit","textarea","video"];function ne(i){var A;return Zi.indexOf(i.nodeName.toLowerCase())!==-1||i.hasAttribute("contenteditable")&&((A=i.getAttribute("contenteditable"))==null?void 0:A.toLowerCase())!=="false"?i:i.parentElement?ne(i.parentElement):null}function re(i,A){const t=se(i,i.document.body,A);return new W({href:"#",type:"application/xhtml+xml",locations:new R({otherLocations:new Map([["cssSelector",i._readium_cssSelectorGenerator.getCssSelector(t)]])}),text:new iA({highlight:t.textContent||void 0})})}function se(i,A,t){for(var e=0;e<A.children.length;e++){const n=A.children[e];if(!qi(n)&&Ki(i,n,t))return se(i,n,t)}return A}function Ki(i,A,t){if(A===document.body||A===document.documentElement)return!0;if(!document||!document.documentElement||!document.body)return!1;const e=A.getBoundingClientRect();return t?e.bottom>0&&e.top<i.innerHeight:e.right>0&&e.left<i.innerWidth}function qi(i){const A=getComputedStyle(i);return!!(A&&(A.getPropertyValue("display")!="block"||A.getPropertyValue("opacity")==="0"))}const oe="readium-column-snapper-style",_i=200,ae=class j extends ee{constructor(){super(...arguments),this.shakeTimeout=0,this.snappingCancelled=!1,this.alreadyScrollLeft=0,this.overscroll=0,this.cachedScrollWidth=0,this.touchState=0,this.startingX=void 0,this.endingX=void 0,this.onTouchStarter=this.onTouchStart.bind(this),this.onTouchEnder=this.onTouchEnd.bind(this),this.onWidthChanger=this.onWidthChange.bind(this),this.onTouchMover=this.onTouchMove.bind(this)}doc(){return this.wnd.document.scrollingElement}scrollOffset(){return this.doc().scrollLeft>0?this.doc().scrollLeft:this.alreadyScrollLeft}snapOffset(A){const t=A+(q(this.wnd)?-1:1);return t-t%this.wnd.innerWidth}reportProgress(){this.comms.send("progress",{progress:this.wnd.scrollX/this.cachedScrollWidth,reference:this.wnd.innerWidth/this.doc().scrollWidth})}shake(){if(this.overscroll!==0||this.shakeTimeout!==0)return;const A=this.doc();A.classList.add(q(this.wnd)?"readium-bounce-l":"readium-bounce-r");const t=this.scrollOffset();this.shakeTimeout=this.wnd.setTimeout(()=>{A.classList.remove("readium-bounce-l"),A.classList.remove("readium-bounce-r"),this.shakeTimeout=0,this.doc().scrollLeft=t},150)}takeOverSnap(){var A;this.snappingCancelled=!0,this.clearTouches();const t=this.doc();this.overscroll=((A=t.style.transform)==null?void 0:A.length)>12?parseFloat(t.style.transform.slice(12).split("px")[0]):0}snapCurrentOffset(A=!1,t=!1){const e=this.wnd.scrollX>0?this.wnd.scrollX:this.alreadyScrollLeft,n=this.doc(),r=this.dragOffset(),s=ie(this.wnd),o=Math.min(Math.max(0,e),this.cachedScrollWidth),a=q(this.wnd)?-1:1,h=a*(this.wnd.innerWidth/3)*(a*r>0?2:1),c=this.snapOffset(o+h);if(A&&c!==this.scrollOffset()){this.snappingCancelled=!1;const l=(B,f,E,p)=>E>p?f:B+(f-B)*Xi(E/p),g=_i*s;let u;const m=B=>{if(this.snappingCancelled)return;u||(u=B);const f=B-u,E=l(this.overscroll,0,f,g),p=l(e,c,f,g);n.scrollLeft=p,this.overscroll!==0&&(n.style.transform=`translate3d(${-E}px, 0px, 0px)`),f<g?this.wnd.requestAnimationFrame(m):(this.clearTouches(),n.style.removeProperty("transform"),n.scrollLeft=c,t||this.reportProgress())};this.wnd.requestAnimationFrame(m)}else n.style.removeProperty("transform"),this.wnd.requestAnimationFrame(()=>{n.scrollLeft=c,this.clearTouches(),t||this.reportProgress()})}dragOffset(){return(this.startingX??0)-(this.endingX??0)}clearTouches(){this.startingX=void 0,this.endingX=void 0,this.overscroll=0}onTouchStart(A){switch(A.stopPropagation(),this.takeOverSnap(),A.touches.length){case 1:break;case 2:this.onTouchEnd(A);return;default:{this.onTouchEnd(A),this.comms.send("tap_more",A.touches.length);return}}this.startingX=A.touches[0].clientX,this.alreadyScrollLeft=this.doc().scrollLeft,this.touchState=1}onTouchEnd(A){if(this.touchState===2){const t=this.dragOffset(),e=this.scrollOffset();this.cachedScrollWidth<=this.wnd.innerWidth?(this.reportProgress(),t>5&&this.comms.send("no_more",void 0),t<-5&&this.comms.send("no_less",void 0)):e<5&&t<5?(this.alreadyScrollLeft=0,this.comms.send("no_less",void 0)):this.cachedScrollWidth-e-this.wnd.innerWidth<5&&t>5&&(this.alreadyScrollLeft=this.cachedScrollWidth,this.comms.send("no_more",void 0)),this.snapCurrentOffset(!0),this.comms.send("swipe",t)}this.touchState=0}onWidthChange(){this.cachedScrollWidth=this.doc().scrollWidth,this.comms.ready&&this.snapCurrentOffset()}onTouchMove(A){if(this.touchState===0)return;this.touchState===1&&(this.touchState=2,N(this.wnd)),this.endingX=A.touches[0].clientX;const t=this.dragOffset(),e=this.alreadyScrollLeft+t;e<0?(this.overscroll=e,this.doc().style.transform=`translate3d(${-this.overscroll}px, 0px, 0px)`):e+this.wnd.innerWidth>this.cachedScrollWidth?(this.overscroll=e,this.doc().style.transform=`translate3d(${-e}px, 0px, 0px)`):(this.overscroll=0,this.doc().style.removeProperty("transform"),this.doc().scrollLeft=this.alreadyScrollLeft+t)}mount(A,t){if(this.wnd=A,this.comms=t,!super.mount(A,t))return!1;A.navigator.epubReadingSystem.layoutStyle="paginated";const e=A.document.createElement("style");e.dataset.readium="true",e.id=oe,e.textContent=`
41
+ }`}mount(t,e){const A=t.document.createElement("style");return A.dataset.readium="true",A.id=tA,A.textContent=this.buildStyles(),t.document.head.appendChild(A),e.register("protect",Ee.moduleName,(i,r)=>{this.protected=!0,A.textContent=this.buildStyles(),r(!0)}),e.register("unprotect",Ee.moduleName,(i,r)=>{this.protected=!1,A.textContent=this.buildStyles(),r(!0)}),e.log("Snapper Mounted"),!0}unmount(t,e){var A;return(A=t.document.getElementById(tA))==null||A.remove(),e.log("Snapper Unmounted"),!0}};eA.moduleName="snapper";let AA=eA;function rt(n){return n.document.body.dir.toLowerCase()==="rtl"}function iA(n){return parseInt(n.getComputedStyle(n.document.documentElement).getPropertyValue("column-count"))}function Ki(n){const t=getComputedStyle(n),e=parseFloat(t.paddingTop||"0"),A=parseFloat(t.paddingBottom||"0");return n.clientHeight-e-A}function nA(n){const t=iA(n);if(!t)return!1;const e=n.document.querySelectorAll("div[id^='readium-virtual-page']");for(const a of e)a.remove();const A=e.length,i=n.document.scrollingElement.scrollWidth,r=n.visualViewport.width,s=Math.round(i/r*t)%t,o=t===1||s===0?0:t-s;if(o>0)for(let a=0;a<o;a++){const l=n.document.createElement("div");l.setAttribute("id",`readium-virtual-page-${a}`),l.dataset.readium="true",CSS.supports("break-before","column")?l.style.breakBefore="column":(CSS.supports("break-inside","avoid-column")&&(l.style.breakInside="avoid-column"),l.style.height=Ki(n.document.documentElement)+"px"),l.innerHTML="&#8203;",n.document.body.appendChild(l)}return A!==o}function qi(n){const t=n.document.createElement("style");t.appendChild(n.document.createTextNode("*{}")),n.document.body.appendChild(t),n.document.body.removeChild(t)}function _i(n){return n<.5?2*n*n:-1+(4-2*n)*n}function T(n){const t=n.getSelection();t&&t.removeAllRanges()}const $i=["a","audio","button","canvas","details","input","label","option","select","submit","textarea","video"];function rA(n){var t;return $i.indexOf(n.nodeName.toLowerCase())!==-1||n.hasAttribute("contenteditable")&&((t=n.getAttribute("contenteditable"))==null?void 0:t.toLowerCase())!=="false"?n:n.parentElement?rA(n.parentElement):null}function sA(n,t){const e=oA(n,n.document.body,t),A=n._readium_cssSelectorGenerator.getCssSelector(e,{selectors:["tag","id","class","nthchild","nthoftype","attribute"]});return new tt({href:"#",type:"application/xhtml+xml",locations:new S({otherLocations:new Map([["cssSelector",A]])}),text:new lt({highlight:e.textContent||void 0})})}function oA(n,t,e){for(var A=0;A<t.children.length;A++){const i=t.children[A];if(!An(i)&&tn(n,i,e))return en(n,i)?i:oA(n,i,e)}return t}function tn(n,t,e){if(t===document.body||t===document.documentElement)return!0;if(!document||!document.documentElement||!document.body)return!1;const A=t.getBoundingClientRect();return e?A.bottom>0&&A.top<n.innerHeight:A.right>0&&A.left<n.innerWidth}function en(n,t){const e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=n.innerHeight&&e.right<=n.innerWidth}function An(n){const t=getComputedStyle(n);if(t){const e=t.getPropertyValue("display");if(e!="block"&&e!="list-item"||t.getPropertyValue("opacity")==="0")return!0}return!1}const aA="readium-column-snapper-style",nn=200,lA=class b extends AA{constructor(){super(...arguments),this.shakeTimeout=0,this.snappingCancelled=!1,this.alreadyScrollLeft=0,this.overscroll=0,this.cachedScrollWidth=0,this.touchState=0,this.startingX=void 0,this.endingX=void 0,this.onTouchStarter=this.onTouchStart.bind(this),this.onTouchEnder=this.onTouchEnd.bind(this),this.onWidthChanger=this.onWidthChange.bind(this),this.onTouchMover=this.onTouchMove.bind(this)}doc(){return this.wnd.document.scrollingElement}scrollOffset(){return this.doc().scrollLeft>0?this.doc().scrollLeft:this.alreadyScrollLeft}snapOffset(t){const e=t+(rt(this.wnd)?-1:1);return e-e%this.wnd.innerWidth}reportProgress(){const t=this.wnd.scrollX,e=this.cachedScrollWidth,A=Math.max(0,Math.min(1,t/e)),i=Math.max(0,Math.min(1,(t+this.wnd.innerWidth)/e));this.comms.send("progress",{start:A,end:i})}shake(){if(this.overscroll!==0||this.shakeTimeout!==0)return;const t=this.doc();t.classList.add(rt(this.wnd)?"readium-bounce-l":"readium-bounce-r");const e=this.scrollOffset();this.shakeTimeout=this.wnd.setTimeout(()=>{t.classList.remove("readium-bounce-l"),t.classList.remove("readium-bounce-r"),this.shakeTimeout=0,this.doc().scrollLeft=e},150)}takeOverSnap(){var t;this.snappingCancelled=!0,this.clearTouches();const e=this.doc();this.overscroll=((t=e.style.transform)==null?void 0:t.length)>12?parseFloat(e.style.transform.slice(12).split("px")[0]):0}snapCurrentOffset(t=!1,e=!1){const A=this.wnd.scrollX>0?this.wnd.scrollX:this.alreadyScrollLeft,i=this.doc(),r=this.dragOffset(),s=iA(this.wnd),o=Math.min(Math.max(0,A),this.cachedScrollWidth),a=rt(this.wnd)?-1:1,l=a*(this.wnd.innerWidth/3)*(a*r>0?2:1),h=this.snapOffset(o+l);if(t&&h!==this.scrollOffset()){this.snappingCancelled=!1;const c=(B,f,F,Q)=>F>Q?f:B+(f-B)*_i(F/Q),g=nn*s;let m;const M=B=>{if(this.snappingCancelled)return;m||(m=B);const f=B-m,F=c(this.overscroll,0,f,g),Q=c(A,h,f,g);i.scrollLeft=Q,this.overscroll!==0&&(i.style.transform=`translate3d(${-F}px, 0px, 0px)`),f<g?this.wnd.requestAnimationFrame(M):(this.clearTouches(),i.style.removeProperty("transform"),i.scrollLeft=h,e||this.reportProgress())};this.wnd.requestAnimationFrame(M)}else i.style.removeProperty("transform"),this.wnd.requestAnimationFrame(()=>{i.scrollLeft=h,this.clearTouches(),e||this.reportProgress()})}dragOffset(){return(this.startingX??0)-(this.endingX??0)}clearTouches(){this.startingX=void 0,this.endingX=void 0,this.overscroll=0}onTouchStart(t){switch(t.stopPropagation(),this.takeOverSnap(),t.touches.length){case 1:break;case 2:this.onTouchEnd(t);return;default:{this.onTouchEnd(t),this.comms.send("tap_more",t.touches.length);return}}this.startingX=t.touches[0].clientX,this.alreadyScrollLeft=this.doc().scrollLeft,this.touchState=1}onTouchEnd(t){if(this.touchState===2){const e=this.dragOffset(),A=this.scrollOffset();this.cachedScrollWidth<=this.wnd.innerWidth?(this.reportProgress(),e>5&&this.comms.send("no_more",void 0),e<-5&&this.comms.send("no_less",void 0)):A<5&&e<5?(this.alreadyScrollLeft=0,this.comms.send("no_less",void 0)):this.cachedScrollWidth-A-this.wnd.innerWidth<5&&e>5&&(this.alreadyScrollLeft=this.cachedScrollWidth,this.comms.send("no_more",void 0)),this.snapCurrentOffset(!0),this.comms.send("swipe",e)}this.touchState=0}onWidthChange(){this.cachedScrollWidth=this.doc().scrollWidth,this.comms.ready&&this.snapCurrentOffset()}onTouchMove(t){if(this.touchState===0)return;this.touchState===1&&(this.touchState=2,T(this.wnd)),this.endingX=t.touches[0].clientX;const e=this.dragOffset(),A=this.alreadyScrollLeft+e;A<0?(this.overscroll=A,this.doc().style.transform=`translate3d(${-this.overscroll}px, 0px, 0px)`):A+this.wnd.innerWidth>this.cachedScrollWidth?(this.overscroll=A,this.doc().style.transform=`translate3d(${-A}px, 0px, 0px)`):(this.overscroll=0,this.doc().style.removeProperty("transform"),this.doc().scrollLeft=this.alreadyScrollLeft+e)}mount(t,e){if(this.wnd=t,this.comms=e,!super.mount(t,e))return!1;t.navigator.epubReadingSystem.layoutStyle="paginated";const A=t.document.createElement("style");A.dataset.readium="true",A.id=aA,A.textContent=`
42
42
  @keyframes readium-bounce-l-animation {
43
43
  0%, 100% {transform: translate3d(0, 0, 0);}
44
44
  50% {transform: translate3d(-50px, 0, 0);}
@@ -72,7 +72,7 @@
72
72
  body::-webkit-scrollbar {
73
73
  display: none; /* for Chrome, Safari, and Opera */
74
74
  }
75
- `,A.document.head.appendChild(e);const n=A.ResizeObserver||Kt;this.resizeObserver=new n(()=>A.requestAnimationFrame(()=>{A&&Oi(A)})),this.resizeObserver.observe(A.document.body),this.mutationObserver=new MutationObserver(()=>{this.wnd.requestAnimationFrame(()=>this.cachedScrollWidth=this.doc().scrollWidth)}),A.frameElement&&this.mutationObserver.observe(A.frameElement,{attributes:!0,attributeFilter:["style"]}),this.mutationObserver.observe(A.document,{attributes:!0,attributeFilter:["style"]});const r=s=>{const o=this.doc().scrollLeft;return this.doc().scrollLeft=this.snapOffset(s),o!==this.doc().scrollLeft};return A.addEventListener("orientationchange",this.onWidthChanger),A.addEventListener("resize",this.onWidthChanger),A.requestAnimationFrame(()=>this.cachedScrollWidth=this.doc().scrollWidth),t.register("go_progression",j.moduleName,(s,o)=>{const a=s;if(a<0||a>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),o(!1);return}this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const h=this.cachedScrollWidth,c=q(A)?-1:1,l=h*a*c;this.doc().scrollLeft=this.snapOffset(l),this.reportProgress(),N(this.wnd),o(!0)})}),t.register("go_id",j.moduleName,(s,o)=>{const a=A.document.getElementById(s);if(!a){o(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollLeft=this.snapOffset(a.getBoundingClientRect().left+A.scrollX),this.reportProgress(),N(this.wnd),o(!0)})}),t.register("go_text",j.moduleName,(s,o)=>{let a;Array.isArray(s)&&(s.length>1&&(a=s[1]),s=s[0]);const h=iA.deserialize(s),c=ZA(this.wnd.document,new W({href:A.location.href,type:"text/html",text:h,locations:a?new R({otherLocations:new Map([["cssSelector",a]])}):void 0}));if(!c){o(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollLeft=this.snapOffset(c.getBoundingClientRect().left+A.scrollX),this.reportProgress(),N(this.wnd),o(!0)})}),t.register("go_end",j.moduleName,(s,o)=>{const a=q(A)?-1:1;this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const h=this.cachedScrollWidth*a;if(this.doc().scrollLeft===h)return o(!1);this.doc().scrollLeft=this.snapOffset(h),this.reportProgress(),N(this.wnd),o(!0)})}),t.register("go_start",j.moduleName,(s,o)=>{this.wnd.requestAnimationFrame(()=>{if(this.doc().scrollLeft===0)return o(!1);this.doc().scrollLeft=0,this.reportProgress(),N(this.wnd),o(!0)})}),t.register("go_prev",j.moduleName,(s,o)=>{this.wnd.requestAnimationFrame(()=>{const a=A.scrollX-A.innerWidth,h=q(A)?-(this.cachedScrollWidth-A.innerWidth):0,c=r(Math.max(a,h));c&&(this.reportProgress(),N(this.wnd)),o(c)})}),t.register("go_next",j.moduleName,(s,o)=>{this.wnd.requestAnimationFrame(()=>{const a=A.scrollX+A.innerWidth,h=q(A)?0:this.cachedScrollWidth-A.innerWidth,c=r(Math.min(a,h));c&&(this.reportProgress(),N(this.wnd)),o(c)})}),t.register("unfocus",j.moduleName,(s,o)=>{this.snappingCancelled=!0,N(this.wnd),o(!0)}),t.register("shake",j.moduleName,(s,o)=>{this.shake(),o(!0)}),t.register("focus",j.moduleName,(s,o)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth,this.snapCurrentOffset(!1,!0),this.reportProgress(),o(!0)})}),t.register("first_visible_locator",j.moduleName,(s,o)=>{const a=re(A,!1);this.comms.send("first_visible_locator",a.serialize()),o(!0)}),A.addEventListener("touchstart",this.onTouchStarter,{passive:!0}),A.addEventListener("touchend",this.onTouchEnder,{passive:!0}),A.addEventListener("touchmove",this.onTouchMover,{passive:!0}),A.document.addEventListener("touchstart",()=>{}),t.log("ColumnSnapper Mounted"),!0}unmount(A,t){var e;return this.snappingCancelled=!0,t.unregisterAll(j.moduleName),this.resizeObserver.disconnect(),this.mutationObserver.disconnect(),A.removeEventListener("touchstart",this.onTouchStarter),A.removeEventListener("touchend",this.onTouchEnder),A.removeEventListener("touchmove",this.onTouchMover),A.removeEventListener("orientationchange",this.onWidthChanger),A.removeEventListener("resize",this.onWidthChanger),(e=A.document.getElementById(oe))==null||e.remove(),t.log("ColumnSnapper Unmounted"),super.unmount(A,t)}};ae.moduleName="column_snapper";let $i=ae;const CA={top:"js-iframe-reader-top-anchor",bottom:"js-iframe-reader-bottom-anchor"};class An extends HTMLElement{connectedCallback(){this.setAttribute("aria-hidden","true"),this.style.setProperty("display","block","important"),this.style.setProperty("padding","0","important"),this.style.setProperty("margin","0","important"),this.style.setProperty("visibility","hidden","important")}}function tn(i){const A=i.getElementsByTagName("body")[0],t=document.createElement("anchor-observer"),e=document.createElement("anchor-observer");t.dataset.readium="true",e.dataset.readium="true",t==null||t.setAttribute("id",CA.top),t==null||t.style.setProperty("height","115px","important"),e==null||e.setAttribute("id",CA.bottom),e==null||e.style.setProperty("height","80px","important"),A==null||A.insertBefore(t,A.firstChild),A==null||A.appendChild(e)}function en(i){var A,t;const e=i.getElementsByTagName("body")[0],n=e==null?void 0:e.querySelector(`#${CA.top}`),r=e==null?void 0:e.querySelector(`#${CA.bottom}`);n&&((A=n.parentElement)==null||A.removeChild(n)),r&&((t=r.parentElement)==null||t.removeChild(r))}const he="readium-scroll-snapper-style",ce=class H extends ee{constructor(){super(...arguments),this.createAnchorElements=()=>{tn(this.doc())},this.removeAnchorElements=()=>{en(this.doc())},this.createCustomElement=()=>{customElements.get("anchor-observer")||customElements.define("anchor-observer",An)}}doc(){return this.wnd.document.scrollingElement}reportProgress(A){this.comms.send("progress",A)}mount(A,t){this.wnd=A,this.comms=t,A.navigator.epubReadingSystem.layoutStyle="scrolling";const e=A.document.createElement("style");return e.dataset.readium="true",e.id=he,e.textContent=`
75
+ `,t.document.head.appendChild(A),this.resizeObserver=new ResizeObserver(()=>{t.requestAnimationFrame(()=>{t&&nA(t)}),this.onWidthChange()}),this.resizeObserver.observe(t.document.body),this.mutationObserver=new MutationObserver(r=>{for(const s of r)if(s.target===this.wnd.document.documentElement){const o=s.oldValue,a=s.target.getAttribute("style"),l=/transform\s*:\s*([^;]+)/,h=o==null?void 0:o.match(l),c=a==null?void 0:a.match(l);(!h&&!c||h&&!c||h&&c&&h[1]!==c[1])&&(t.requestAnimationFrame(()=>{t&&nA(t)}),this.onWidthChange())}else t.requestAnimationFrame(()=>this.cachedScrollWidth=this.doc().scrollWidth)}),t.frameElement&&this.mutationObserver.observe(t.frameElement,{attributes:!0,attributeFilter:["style"]}),this.mutationObserver.observe(t.document,{attributes:!0,attributeFilter:["style"]}),this.mutationObserver.observe(t.document.documentElement,{attributes:!0,attributeFilter:["style"]});const i=r=>{const s=this.doc().scrollLeft;return this.doc().scrollLeft=this.snapOffset(r),s!==this.doc().scrollLeft};return t.addEventListener("orientationchange",this.onWidthChanger),t.addEventListener("resize",this.onWidthChanger),t.requestAnimationFrame(()=>this.cachedScrollWidth=this.doc().scrollWidth),e.register("go_progression",b.moduleName,(r,s)=>{const o=r;if(o<0||o>1){e.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),s(!1);return}this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const a=this.cachedScrollWidth,l=rt(t)?-1:1,h=a*o*l;this.doc().scrollLeft=this.snapOffset(h),this.reportProgress(),T(this.wnd),s(!0)})}),e.register("go_id",b.moduleName,(r,s)=>{const o=t.document.getElementById(r);if(!o){s(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollLeft=this.snapOffset(o.getBoundingClientRect().left+t.scrollX),this.reportProgress(),T(this.wnd),s(!0)})}),e.register("go_text",b.moduleName,(r,s)=>{let o;Array.isArray(r)&&(r.length>1&&(o=r[1]),r=r[0]);const a=lt.deserialize(r),l=oe(this.wnd.document,new tt({href:t.location.href,type:"text/html",text:a,locations:o?new S({otherLocations:new Map([["cssSelector",o]])}):void 0}));if(!l){s(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollLeft=this.snapOffset(l.getBoundingClientRect().left+t.scrollX),this.reportProgress(),T(this.wnd),s(!0)})}),e.register("go_end",b.moduleName,(r,s)=>{const o=rt(t)?-1:1;this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const a=this.cachedScrollWidth*o;if(this.doc().scrollLeft===a)return s(!1);this.doc().scrollLeft=this.snapOffset(a),this.reportProgress(),T(this.wnd),s(!0)})}),e.register("go_start",b.moduleName,(r,s)=>{this.wnd.requestAnimationFrame(()=>{if(this.doc().scrollLeft===0)return s(!1);this.doc().scrollLeft=0,this.reportProgress(),T(this.wnd),s(!0)})}),e.register("go_prev",b.moduleName,(r,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const o=t.scrollX-t.innerWidth,a=rt(t)?-(this.cachedScrollWidth-t.innerWidth):0,l=i(Math.max(o,a));l&&(this.reportProgress(),T(this.wnd)),s(l)})}),e.register("go_next",b.moduleName,(r,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth;const o=t.scrollX+t.innerWidth,a=rt(t)?0:this.cachedScrollWidth-t.innerWidth,l=i(Math.min(o,a));l&&(this.reportProgress(),T(this.wnd)),s(l)})}),e.register("unfocus",b.moduleName,(r,s)=>{this.snappingCancelled=!0,T(this.wnd),s(!0)}),e.register("shake",b.moduleName,(r,s)=>{this.shake(),s(!0)}),e.register("focus",b.moduleName,(r,s)=>{this.wnd.requestAnimationFrame(()=>{this.cachedScrollWidth=this.doc().scrollWidth,this.snapCurrentOffset(!1,!0),this.reportProgress(),s(!0)})}),e.register("first_visible_locator",b.moduleName,(r,s)=>{const o=sA(t,!1);this.comms.send("first_visible_locator",o.serialize()),s(!0)}),t.addEventListener("touchstart",this.onTouchStarter,{passive:!0}),t.addEventListener("touchend",this.onTouchEnder,{passive:!0}),t.addEventListener("touchmove",this.onTouchMover,{passive:!0}),t.document.addEventListener("touchstart",()=>{}),e.log("ColumnSnapper Mounted"),!0}unmount(t,e){var A;return this.snappingCancelled=!0,e.unregisterAll(b.moduleName),this.resizeObserver.disconnect(),this.mutationObserver.disconnect(),t.removeEventListener("touchstart",this.onTouchStarter),t.removeEventListener("touchend",this.onTouchEnder),t.removeEventListener("touchmove",this.onTouchMover),t.removeEventListener("orientationchange",this.onWidthChanger),t.removeEventListener("resize",this.onWidthChanger),(A=t.document.getElementById(aA))==null||A.remove(),e.log("ColumnSnapper Unmounted"),super.unmount(t,e)}};lA.moduleName="column_snapper";let rn=lA;const hA="readium-scroll-snapper-style",cA=class L extends AA{constructor(){super(...arguments),this.isScrolling=!1,this.handleScroll=()=>{this.isScrolling||(this.isScrolling=!0,this.wnd.requestAnimationFrame(()=>{this.reportProgress(),this.isScrolling=!1}))}}doc(){return this.wnd.document.scrollingElement}reportProgress(){const t=this.doc().scrollTop,e=this.doc().scrollHeight,A=Math.max(0,Math.min(1,t/e)),i=Math.max(0,Math.min(1,(t+this.wnd.innerHeight)/e));this.comms.send("progress",{start:A,end:i})}mount(t,e){this.wnd=t,this.comms=e,t.navigator.epubReadingSystem.layoutStyle="scrolling";const A=t.document.createElement("style");return A.dataset.readium="true",A.id=hA,A.textContent=`
76
76
  * {
77
77
  scrollbar-width: none; /* for Firefox */
78
78
  }
@@ -80,7 +80,7 @@
80
80
  body::-webkit-scrollbar {
81
81
  display: none; /* for Chrome, Safari, and Opera */
82
82
  }
83
- `,A.document.head.appendChild(e),t.register("go_progression",H.moduleName,(n,r)=>{const s=n;if(s<0||s>1){t.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*s,this.reportProgress({progress:s,reference:this.wnd.innerHeight/this.doc().scrollHeight}),N(this.wnd),r(!0)})}),t.register("go_id",H.moduleName,(n,r)=>{const s=A.document.getElementById(n);if(!s){r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=s.getBoundingClientRect().top+A.scrollY-A.innerHeight/2;const o=this.doc().scrollTop/this.doc().offsetHeight;this.reportProgress({progress:o,reference:this.wnd.innerHeight/this.doc().scrollHeight}),N(this.wnd),r(!0)})}),t.register("go_text",H.moduleName,(n,r)=>{let s;Array.isArray(n)&&(n.length>1&&(s=n[1]),n=n[0]);const o=iA.deserialize(n),a=ZA(this.wnd.document,new W({href:A.location.href,type:"text/html",text:o,locations:s?new R({otherLocations:new Map([["cssSelector",s]])}):void 0}));if(!a){r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=a.getBoundingClientRect().top+A.scrollY-A.innerHeight/2;const h=this.doc().scrollTop/this.doc().offsetHeight;this.reportProgress({progress:h,reference:this.wnd.innerHeight/this.doc().scrollHeight}),N(this.wnd),r(!0)})}),t.register("go_start",H.moduleName,(n,r)=>{if(this.doc().scrollTop===0)return r(!1);this.doc().scrollTop=0,this.reportProgress({progress:0,reference:this.wnd.innerHeight/this.doc().scrollHeight}),r(!0)}),t.register("go_end",H.moduleName,(n,r)=>{if(this.doc().scrollTop===0)return r(!1);this.doc().scrollTop=0,this.reportProgress({progress:0,reference:this.wnd.innerHeight/this.doc().scrollHeight}),r(!0)}),t.register("unfocus",H.moduleName,(n,r)=>{N(this.wnd),r(!0)}),t.register(["go_next","go_prev"],H.moduleName,(n,r)=>r(!1)),t.register("focus",H.moduleName,(n,r)=>{const s=this.doc().scrollTop/this.doc().offsetHeight;this.reportProgress({progress:s,reference:this.wnd.innerHeight/this.doc().scrollHeight}),r(!0)}),t.register("first_visible_locator",H.moduleName,(n,r)=>{const s=re(A,!0);this.comms.send("first_visible_locator",s.serialize()),r(!0)}),t.log("ScrollSnapper Mounted"),this.createCustomElement(),this.createAnchorElements(),!0}unmount(A,t){var e;return t.unregisterAll(H.moduleName),this.removeAnchorElements(),(e=A.document.getElementById(he))==null||e.remove(),t.log("ScrollSnapper Unmounted"),!0}};ce.moduleName="scroll_snapper";let nn=ce;class le extends pA{constructor(){super(...arguments),this.pointerMoved=!1,this.onPointerUp=this.onPointUp.bind(this),this.onPointerMove=this.onPointMove.bind(this),this.onPointerDown=this.onPointDown.bind(this),this.onContextMenu=this.onContext.bind(this),this.onClicker=this.onClick.bind(this)}onPointUp(A){var t,e,n,r,s;const o=this.wnd.getSelection();if(o&&((t=o.toString())==null?void 0:t.length)>0){const h=(e=o.getRangeAt(0))==null?void 0:e.getClientRects();if(!h||h.length===0)return;const c=h[0],l={text:o.toString(),x:c.x,y:c.y,width:c.width,height:c.height,targetFrameSrc:(r=(n=this.wnd)==null?void 0:n.location)==null?void 0:r.href};this.comms.send("text_selected",l)}if(this.pointerMoved){this.pointerMoved=!1;return}if(!(o!=null&&o.isCollapsed)||!A.isPrimary)return;const a=this.wnd.devicePixelRatio;A.preventDefault(),this.comms.send(A.pointerType==="touch"?"tap":"click",{defaultPrevented:A.defaultPrevented,x:A.clientX*a,y:A.clientY*a,targetFrameSrc:this.wnd.location.href,targetElement:A.target.outerHTML,interactiveElement:(s=ne(A.target))==null?void 0:s.outerHTML,cssSelector:this.wnd._readium_cssSelectorGenerator.getCssSelector(A.target)}),this.pointerMoved=!1}onPointMove(A){if(A.movementY!==void 0&&A.movementX!==void 0){(Math.abs(A.movementX)>1||Math.abs(A.movementY)>1)&&(this.pointerMoved=!0);return}this.pointerMoved=!0}onPointDown(){this.pointerMoved=!1}onContext(A){this.onPointUp(A),this.pointerMoved=!1}onClick(A){if(A.preventDefault(),!A.isTrusted){const t=new PointerEvent("pointerup",{isPrimary:!0,pointerType:"mouse",clientX:A.clientX,clientY:A.clientY});Object.defineProperty(t,"target",{writable:!1,value:A.target}),Object.defineProperty(t,"defaultPrevented",{writable:!1,value:A.defaultPrevented}),this.onPointUp(t)}}mount(A,t){return this.wnd=A,this.comms=t,A.document.addEventListener("pointerdown",this.onPointerDown),A.document.addEventListener("pointerup",this.onPointerUp),A.document.addEventListener("contextmenu",this.onContextMenu),A.document.addEventListener("pointermove",this.onPointerMove),A.document.addEventListener("click",this.onClicker),t.log("Peripherals Mounted"),!0}unmount(A,t){return A.document.removeEventListener("pointerdown",this.onPointerDown),A.document.removeEventListener("pointerup",this.onPointerUp),A.document.removeEventListener("contextmenu",this.onContextMenu),A.document.removeEventListener("pointermove",this.onPointerMove),A.document.removeEventListener("click",this.onClicker),t.log("Peripherals Unmounted"),!0}}le.moduleName="peripherals";const ge=class at extends pA{constructor(){super(...arguments),this.mediaPlayingCount=0,this.allAnimations=new Set}wndOnErr(A){var t;(t=this.comms)==null||t.send("error",{message:A.message,filename:A.filename,lineno:A.lineno,colno:A.colno})}unblock(A){var t;for(A._readium_blockEvents=!1;((t=A._readium_blockedEvents)==null?void 0:t.length)>0;){const e=A._readium_blockedEvents.shift();switch(e[0]){case 0:Reflect.apply(e[1],e[2],e[3]);break;case 1:const n=e[1],r=e[2];A.removeEventListener(n.type,A._readium_eventBlocker,!0);const s=new Event(n.type,{bubbles:n.bubbles,cancelable:n.cancelable});r?r.dispatchEvent(s):A.dispatchEvent(s);break}}}onMediaPlayEvent(){var A;this.mediaPlayingCount++,(A=this.comms)==null||A.send("media_play",this.mediaPlayingCount)}onMediaPauseEvent(){var A;this.mediaPlayingCount>0&&this.mediaPlayingCount--,(A=this.comms)==null||A.send("media_pause",this.mediaPlayingCount)}pauseAllMedia(A){const t=A.document.querySelectorAll("audio,video");for(let e=0;e<t.length;e++)t[e].pause()}mount(A,t){this.comms=t,A.addEventListener("error",this.wndOnErr,!1),Reflect.defineProperty(A.navigator,"epubReadingSystem",{value:{name:"readium-ts-toolkit",version:"1.3.2",hasFeature:(n,r="")=>{switch(n){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!0;case"embedded-web-content":return!0;default:return!1}}},writable:!1}),"getAnimations"in A.document&&A.document.getAnimations().forEach(n=>{n.cancel(),this.allAnimations.add(n)}),t.register("activate",at.moduleName,(n,r)=>{this.allAnimations.forEach(s=>{s.cancel(),s.play()}),r(!0)}),t.register("unfocus",at.moduleName,(n,r)=>{this.pauseAllMedia(A),this.allAnimations.forEach(s=>s.pause()),r(!0)});const e=A.document.querySelectorAll("audio,video");for(let n=0;n<e.length;n++){const r=e[n];r.addEventListener("play",this.onMediaPlayEvent,{passive:!0}),r.addEventListener("pause",this.onMediaPauseEvent,{passive:!0})}return t.log("Setup Mounted"),!0}unmount(A,t){return A.removeEventListener("error",this.wndOnErr),A.removeEventListener("play",this.onMediaPlayEvent),A.removeEventListener("pause",this.onMediaPauseEvent),this.allAnimations.forEach(e=>e.cancel()),this.allAnimations.clear(),t.log("Setup Unmounted"),!0}};ge.moduleName="setup";let de=ge;const Me="readium-viewport",ue=class MA extends de{onViewportWidthChanged(A){const t=A.target;At(t,"--RS__viewportWidth",`${t.innerWidth}px`)}mount(A,t){if(!super.mount(A,t))return!1;const e=A.document.createElement("meta");return e.dataset.readium="true",e.setAttribute("name","viewport"),e.setAttribute("id",Me),e.setAttribute("content","width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no"),A.document.head.appendChild(e),A.addEventListener("orientationchange",this.onViewportWidthChanged),A.addEventListener("resize",this.onViewportWidthChanged),this.onViewportWidthChanged({target:A}),t.register("set_property",MA.moduleName,(n,r)=>{const s=n;At(A,s[0],s[1]),r(!0)}),t.register("remove_property",MA.moduleName,(n,r)=>{qt(A,n),r(!0)}),t.register("activate",MA.moduleName,(n,r)=>{this.unblock(A),r(!0)}),t.log("ReflowableSetup Mounted"),!0}unmount(A,t){var e;return t.unregisterAll(MA.moduleName),(e=A.document.head.querySelector(`#${Me}`))==null||e.remove(),A.removeEventListener("orientationchange",this.onViewportWidthChanged),t.log("ReflowableSetup Unmounted"),super.unmount(A,t)}};ue.moduleName="reflowable_setup";let rn=ue;const me="readium-fixed-style",Be=class O extends de{mount(A,t){if(!super.mount(A,t))return!1;A.navigator.epubReadingSystem.layoutStyle="paginated";const e=A.document.createElement("style");return e.id=me,e.dataset.readium="true",e.textContent=`
83
+ `,t.document.head.appendChild(A),this.resizeObserver=new ResizeObserver(()=>{this.comms.ready&&this.handleScroll()}),this.resizeObserver.observe(t.document.body),t.addEventListener("scroll",this.handleScroll,{passive:!0}),e.register("force_webkit_recalc",L.moduleName,()=>{qi(this.wnd);const i=this.doc().scrollTop;this.doc().scrollTop=i+1,this.doc().scrollTop=i}),e.register("go_progression",L.moduleName,(i,r)=>{const s=i;if(s<0||s>1){e.send("error",{message:"go_progression must be given a position from 0.0 to 1.0"}),r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=this.doc().offsetHeight*s,this.reportProgress(),T(this.wnd),r(!0)})}),e.register("go_id",L.moduleName,(i,r)=>{const s=t.document.getElementById(i);if(!s){r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=s.getBoundingClientRect().top+t.scrollY-t.innerHeight/2,this.reportProgress(),T(this.wnd),r(!0)})}),e.register("go_text",L.moduleName,(i,r)=>{let s;Array.isArray(i)&&(i.length>1&&(s=i[1]),i=i[0]);const o=lt.deserialize(i),a=oe(this.wnd.document,new tt({href:t.location.href,type:"text/html",text:o,locations:s?new S({otherLocations:new Map([["cssSelector",s]])}):void 0}));if(!a){r(!1);return}this.wnd.requestAnimationFrame(()=>{this.doc().scrollTop=a.getBoundingClientRect().top+t.scrollY-t.innerHeight/2,this.reportProgress(),T(this.wnd),r(!0)})}),e.register("go_start",L.moduleName,(i,r)=>{if(this.doc().scrollTop===0)return r(!1);this.doc().scrollTop=0,this.reportProgress(),r(!0)}),e.register("go_end",L.moduleName,(i,r)=>{if(this.doc().scrollTop===this.doc().scrollHeight-this.doc().offsetHeight)return r(!1);this.doc().scrollTop=this.doc().scrollHeight-this.doc().offsetHeight,this.reportProgress(),r(!0)}),e.register("unfocus",L.moduleName,(i,r)=>{T(this.wnd),r(!0)}),e.register(["go_next","go_prev"],L.moduleName,(i,r)=>r(!1)),e.register("focus",L.moduleName,(i,r)=>{this.reportProgress(),r(!0)}),e.register("first_visible_locator",L.moduleName,(i,r)=>{const s=sA(t,!0);this.comms.send("first_visible_locator",s.serialize()),r(!0)}),e.log("ScrollSnapper Mounted"),!0}unmount(t,e){var A;return e.unregisterAll(L.moduleName),this.resizeObserver.disconnect(),this.handleScroll&&t.removeEventListener("scroll",this.handleScroll),(A=t.document.getElementById(hA))==null||A.remove(),e.log("ScrollSnapper Unmounted"),!0}};cA.moduleName="scroll_snapper";let sn=cA;class gA extends Tt{constructor(){super(...arguments),this.pointerMoved=!1,this.onPointerUp=this.onPointUp.bind(this),this.onPointerMove=this.onPointMove.bind(this),this.onPointerDown=this.onPointDown.bind(this),this.onContextMenu=this.onContext.bind(this),this.onClicker=this.onClick.bind(this)}onPointUp(t){var e,A,i,r,s;const o=this.wnd.getSelection();if(o&&((e=o.toString())==null?void 0:e.length)>0){const l=(A=o.getRangeAt(0))==null?void 0:A.getClientRects();if(!l||l.length===0)return;const h=l[0],c={text:o.toString(),x:h.x,y:h.y,width:h.width,height:h.height,targetFrameSrc:(r=(i=this.wnd)==null?void 0:i.location)==null?void 0:r.href};this.comms.send("text_selected",c)}if(this.pointerMoved){this.pointerMoved=!1;return}if(!(o!=null&&o.isCollapsed)||!t.isPrimary)return;const a=this.wnd.devicePixelRatio;t.preventDefault(),this.comms.send(t.pointerType==="touch"?"tap":"click",{defaultPrevented:t.defaultPrevented,x:t.clientX*a,y:t.clientY*a,targetFrameSrc:this.wnd.location.href,targetElement:t.target.outerHTML,interactiveElement:(s=rA(t.target))==null?void 0:s.outerHTML,cssSelector:this.wnd._readium_cssSelectorGenerator.getCssSelector(t.target)}),this.pointerMoved=!1}onPointMove(t){if(t.movementY!==void 0&&t.movementX!==void 0){(Math.abs(t.movementX)>1||Math.abs(t.movementY)>1)&&(this.pointerMoved=!0);return}this.pointerMoved=!0}onPointDown(){this.pointerMoved=!1}onContext(t){this.onPointUp(t),this.pointerMoved=!1}onClick(t){if(t.preventDefault(),!t.isTrusted){const e=new PointerEvent("pointerup",{isPrimary:!0,pointerType:"mouse",clientX:t.clientX,clientY:t.clientY});Object.defineProperty(e,"target",{writable:!1,value:t.target}),Object.defineProperty(e,"defaultPrevented",{writable:!1,value:t.defaultPrevented}),this.onPointUp(e)}}mount(t,e){return this.wnd=t,this.comms=e,t.document.addEventListener("pointerdown",this.onPointerDown),t.document.addEventListener("pointerup",this.onPointerUp),t.document.addEventListener("contextmenu",this.onContextMenu),t.document.addEventListener("pointermove",this.onPointerMove),t.document.addEventListener("click",this.onClicker),e.log("Peripherals Mounted"),!0}unmount(t,e){return t.document.removeEventListener("pointerdown",this.onPointerDown),t.document.removeEventListener("pointerup",this.onPointerUp),t.document.removeEventListener("contextmenu",this.onContextMenu),t.document.removeEventListener("pointermove",this.onPointerMove),t.document.removeEventListener("click",this.onClicker),e.log("Peripherals Unmounted"),!0}}gA.moduleName="peripherals";const dA=class we extends Tt{constructor(){super(...arguments),this.mediaPlayingCount=0,this.allAnimations=new Set}wndOnErr(t){var e;(e=this.comms)==null||e.send("error",{message:t.message,filename:t.filename,lineno:t.lineno,colno:t.colno})}unblock(t){var e;for(t._readium_blockEvents=!1;((e=t._readium_blockedEvents)==null?void 0:e.length)>0;){const A=t._readium_blockedEvents.shift();switch(A[0]){case 0:Reflect.apply(A[1],A[2],A[3]);break;case 1:const i=A[1],r=A[2];t.removeEventListener(i.type,t._readium_eventBlocker,!0);const s=new Event(i.type,{bubbles:i.bubbles,cancelable:i.cancelable});r?r.dispatchEvent(s):t.dispatchEvent(s);break}}}onMediaPlayEvent(){var t;this.mediaPlayingCount++,(t=this.comms)==null||t.send("media_play",this.mediaPlayingCount)}onMediaPauseEvent(){var t;this.mediaPlayingCount>0&&this.mediaPlayingCount--,(t=this.comms)==null||t.send("media_pause",this.mediaPlayingCount)}pauseAllMedia(t){const e=t.document.querySelectorAll("audio,video");for(let A=0;A<e.length;A++)e[A].pause()}mount(t,e){this.comms=e,t.addEventListener("error",this.wndOnErr,!1),Reflect.defineProperty(t.navigator,"epubReadingSystem",{value:{name:"readium-ts-toolkit",version:"2.0.0-beta.4",hasFeature:(i,r="")=>{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!0;case"embedded-web-content":return!0;default:return!1}}},writable:!1}),"getAnimations"in t.document&&t.document.getAnimations().forEach(i=>{i.cancel(),this.allAnimations.add(i)}),e.register("activate",we.moduleName,(i,r)=>{this.allAnimations.forEach(s=>{s.cancel(),s.play()}),r(!0)}),e.register("unfocus",we.moduleName,(i,r)=>{this.pauseAllMedia(t),this.allAnimations.forEach(s=>s.pause()),r(!0)});const A=t.document.querySelectorAll("audio,video");for(let i=0;i<A.length;i++){const r=A[i];r.addEventListener("play",this.onMediaPlayEvent,{passive:!0}),r.addEventListener("pause",this.onMediaPauseEvent,{passive:!0})}return e.log("Setup Mounted"),!0}unmount(t,e){return t.removeEventListener("error",this.wndOnErr),t.removeEventListener("play",this.onMediaPlayEvent),t.removeEventListener("pause",this.onMediaPauseEvent),this.allAnimations.forEach(A=>A.cancel()),this.allAnimations.clear(),e.log("Setup Unmounted"),!0}};dA.moduleName="setup";let uA=dA;const mA="readium-viewport",MA=class st extends uA{onViewportWidthChanged(t){const e=t.target;Dt(e,"--RS__viewportWidth",`${e.innerWidth}px`)}mount(t,e){if(!super.mount(t,e))return!1;const A=t.document.createElement("meta");return A.dataset.readium="true",A.setAttribute("name","viewport"),A.setAttribute("id",mA),A.setAttribute("content","width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no"),t.document.head.appendChild(A),t.addEventListener("orientationchange",this.onViewportWidthChanged),t.addEventListener("resize",this.onViewportWidthChanged),this.onViewportWidthChanged({target:t}),e.register("get_properties",st.moduleName,(i,r)=>{Ke(t),r(!0)}),e.register("update_properties",st.moduleName,(i,r)=>{i["--RS__viewportWidth"]=`${t.innerWidth}px`,ki(t,i),r(!0)}),e.register("set_property",st.moduleName,(i,r)=>{const s=i;Dt(t,s[0],s[1]),r(!0)}),e.register("remove_property",st.moduleName,(i,r)=>{ae(t,i),r(!0)}),e.register("activate",st.moduleName,(i,r)=>{this.unblock(t),r(!0)}),e.log("ReflowableSetup Mounted"),!0}unmount(t,e){var A;return e.unregisterAll(st.moduleName),(A=t.document.head.querySelector(`#${mA}`))==null||A.remove(),t.removeEventListener("orientationchange",this.onViewportWidthChanged),e.log("ReflowableSetup Unmounted"),super.unmount(t,e)}};MA.moduleName="reflowable_setup";let on=MA;const fA="readium-fixed-style",pA=class it extends uA{mount(t,e){if(!super.mount(t,e))return!1;t.navigator.epubReadingSystem.layoutStyle="paginated";const A=t.document.createElement("style");return A.id=fA,A.dataset.readium="true",A.textContent=`
84
84
  html, body {
85
85
  text-size-adjust: none;
86
86
  -ms-text-size-adjust: none;
@@ -92,7 +92,7 @@
92
92
  min-height: 100%;
93
93
 
94
94
  /*cursor: var() TODO*/
95
- }`,A.document.head.appendChild(e),t.register("set_property",O.moduleName,(n,r)=>{const s=n;At(A,s[0],s[1]),r(!0)}),t.register("remove_property",O.moduleName,(n,r)=>{qt(A,n),r(!0)}),t.register("first_visible_locator",O.moduleName,(n,r)=>r(!1)),t.register("unfocus",O.moduleName,(n,r)=>{N(A),r(!0)}),t.register(["focus","go_next","go_prev","go_id","go_end","go_start","go_text","go_progression"],O.moduleName,(n,r)=>r(!0)),t.register("activate",O.moduleName,(n,r)=>{this.unblock(A),r(!0)}),t.log("FixedSetup Mounted"),!0}unmount(A,t){var e;return t.unregisterAll(O.moduleName),(e=A.document.getElementById(me))==null||e.remove(),t.log("FixedSetup Unmounted"),super.unmount(A,t)}};Be.moduleName="fixed_setup";let sn=Be;const on=["fixed_setup","decorator","peripherals"],an=["reflowable_setup","decorator","peripherals","column_snapper","scroll_snapper"],tt=new Map([sn,rn,le,Li,$i,nn].map(i=>[i.moduleName,i]));class zA{constructor(A=window,t=[]){this.loadedModules=[],this.wnd=A,this.comms=new hi(A);const e=[...new Set(t)];if(e.length){if(typeof A>"u")throw Error("Loader is not in a web browser");A.parent!==A&&this.comms.log("Loader is probably in a frame"),this.loadedModules=e.map(n=>{const r=this.loadModule(n);if(r)return r.mount(this.wnd,this.comms),r}).filter(n=>n!==void 0)}}loadModule(A){const t=tt.get(A);return t===void 0?(this.comms.log(`Module "${name}" does not exist in the library`),t):new t}addModule(A){const t=this.loadModule(A);return!t||!t.mount(this.wnd,this.comms)?!1:(this.loadedModules.push(t),!0)}removeModule(A){const t=tt.get(A);if(t===void 0)return this.comms.log(`Module "${A}" does not exist in the library`),!1;const e=this.loadedModules.findIndex(n=>n instanceof t);return e<0?!1:(this.loadedModules[e].unmount(this.wnd,this.comms),this.loadedModules.splice(e,1),!0)}destroy(){this.comms.destroy(),this.loadedModules.forEach(A=>A.unmount(this.wnd,this.comms)),this.loadedModules=[]}}const hn=1e4;class et{constructor(A,t){this.registry=new Map,this._ready=!1,this.listenerBuffer=[],this.handler=this.handle.bind(this),this.wnd=A,this.origin=t;try{this.channelId=window.crypto.randomUUID()}catch{this.channelId=vA()}this.gc=setInterval(()=>{this.registry.forEach((e,n)=>{performance.now()-e.time>hn&&(console.warn(n,"event for",e.key,"was never handled!"),this.registry.delete(n))})},5e3),window.addEventListener("message",this.handler),this.send("_ping",void 0)}set listener(A){this.listenerBuffer.length>0&&this.listenerBuffer.forEach(t=>A(t[0],t[1])),this.listenerBuffer=[],this._listener=A}clearListener(){typeof this._listener=="function"&&(this._listener=void 0)}halt(){this._ready=!1,window.removeEventListener("message",this.handler),clearInterval(this.gc),this._listener=void 0,this.registry.clear()}resume(){window.addEventListener("message",this.handler),this._ready=!0}handle(A){const t=A.data;if(!t._readium){console.warn("Ignoring",t);return}if(t._channel===this.channelId)switch(t.key){case"_ack":{if(!t.id)return;const e=this.registry.get(t.id);if(!e)return;this.registry.delete(t.id),e.cb(!!t.data);return}case"_pong":this._ready=!0;default:{if(!this.ready)return;typeof this._listener=="function"?this._listener(t.key,t.data):this.listenerBuffer.push([t.key,t.data])}}}get ready(){return this._ready}send(A,t,e,n=!1,r=[]){const s=vA();return e&&this.registry.set(s,{cb:e,time:performance.now(),key:A}),this.wnd.postMessage({_readium:eA,_channel:this.channelId,id:s,data:t,key:A,strict:n},"/",r),s}}class Ee{constructor(A){this.destroyed=!1,this.currModules=[],this.frame=document.createElement("iframe"),this.frame.classList.add("readium-navigator-iframe"),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transition="visibility 0s, opacity 0.1s linear",this.source=A}async load(A){return new Promise((t,e)=>{var n;if(this.loader){const r=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...A].sort().join("|")){try{t(r)}catch{}return}(n=this.comms)==null||n.halt(),this.loader.destroy(),this.loader=new zA(r,A),this.currModules=A,this.comms=void 0;try{t(r)}catch{}return}this.frame.onload=()=>{const r=this.frame.contentWindow;this.loader=new zA(r,A),this.currModules=A;try{t(r)}catch{}},this.frame.onerror=r=>{try{e(r)}catch{}},this.frame.contentWindow.location.replace(this.source)})}async destroy(){var A;await this.hide(),(A=this.loader)==null||A.destroy(),this.frame.remove(),this.destroyed=!0}async hide(){var A;if(!this.destroyed){if(this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.pointerEvents="none",this.frame.parentElement)return this.comms===void 0||!this.comms.ready?void 0:new Promise((t,e)=>{var n;(n=this.comms)==null||n.send("unfocus",void 0,r=>{var s;(s=this.comms)==null||s.halt(),t()})});(A=this.comms)==null||A.halt()}}async show(A){if(this.destroyed)throw Error("Trying to show frame when it doesn't exist");if(!this.frame.parentElement)throw Error("Trying to show frame that is not attached to the DOM");return this.comms?this.comms.resume():this.comms=new et(this.frame.contentWindow,this.source),new Promise((t,e)=>{var n;(n=this.comms)==null||n.send("activate",void 0,()=>{var r;(r=this.comms)==null||r.send("focus",void 0,()=>{var o;const s=()=>{this.frame.style.removeProperty("visibility"),this.frame.style.removeProperty("aria-hidden"),this.frame.style.removeProperty("opacity"),this.frame.style.removeProperty("pointer-events"),t()};A&&A>0?(o=this.comms)==null||o.send("go_progression",A,s):s()})})})}get iframe(){if(this.destroyed)throw Error("Trying to use frame when it doesn't exist");return this.frame}get realSize(){if(this.destroyed)throw Error("Trying to use frame client rect when it doesn't exist");return this.frame.getBoundingClientRect()}get window(){if(this.destroyed||!this.frame.contentWindow)throw Error("Trying to use frame window when it doesn't exist");return this.frame.contentWindow}get atLeft(){return this.window.scrollX<5}get atRight(){return this.window.scrollX>this.window.document.scrollingElement.scrollWidth-this.window.innerWidth-5}get msg(){return this.comms}get ldr(){return this.loader}}const fe=5,Ie=3;class pe{constructor(A,t){this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.container=A,this.positions=t}async destroy(){let A=this.inprogress.values(),t=A.next();const e=[];for(;t.value;)e.push(t.value),t=A.next();e.length>0&&await Promise.allSettled(e),this.inprogress.clear();let n=this.pool.values(),r=n.next();for(;r.value;)await r.value.destroy(),r=n.next();this.pool.clear(),this.blobs.forEach(s=>URL.revokeObjectURL(s)),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}async update(A,t,e,n=!1){let r=this.positions.findIndex(a=>a.locations.position===t.locations.position);if(r<0)throw Error(`Locator not found in position list: ${t.locations.position} > ${this.positions.reduce((a,h)=>h.locations.position||0>a?h.locations.position||0:a,0)}`);const s=this.positions[r].href;this.inprogress.has(s)&&await this.inprogress.get(s);const o=new Promise(async(a,h)=>{var m,B,f;const c=[],l=[];this.positions.forEach((E,p)=>{(p>r+fe||p<r-fe)&&(c.includes(E.href)||c.push(E.href)),p<r+Ie&&p>r-Ie&&(l.includes(E.href)||l.push(E.href))}),c.forEach(async E=>{var p;l.includes(E)||this.pool.has(E)&&(await((p=this.pool.get(E))==null?void 0:p.destroy()),this.pool.delete(E))}),this.currentBaseURL!==void 0&&A.baseURL!==this.currentBaseURL&&(this.blobs.forEach(E=>URL.revokeObjectURL(E)),this.blobs.clear()),this.currentBaseURL=A.baseURL;const g=async E=>{if(this.pool.has(E)){const w=this.pool.get(E);if(!this.blobs.has(E))await w.destroy(),this.pool.delete(E);else{await w.load(e);return}}const p=A.readingOrder.findWithHref(E);if(!p)return;if(!this.blobs.has(E)){const Y=await new Bt(A,this.currentBaseURL||"",p).build();this.blobs.set(E,Y)}const I=new Ee(this.blobs.get(E));E!==s&&await I.hide(),this.container.appendChild(I.iframe),await I.load(e),this.pool.set(E,I)};try{await Promise.all(l.map(E=>g(E)))}catch(E){h(E)}const u=this.pool.get(s);if((u==null?void 0:u.source)!==((m=this._currentFrame)==null?void 0:m.source)||n){await((B=this._currentFrame)==null?void 0:B.hide()),u&&await u.load(e);const E=(((f=t==null?void 0:t.locations)==null?void 0:f.progression)??0)>0;u&&await u.show(E?t.locations.progression:void 0),this._currentFrame=u}a()});this.inprogress.set(s,o),await o,this.inprogress.delete(s)}get currentFrames(){return[this._currentFrame]}get currentBounds(){const A={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(t=>{if(!t)return;const e=t.realSize;A.x=Math.min(A.x,e.x),A.y=Math.min(A.y,e.y),A.width+=e.width,A.height=Math.max(A.height,e.height),A.top=Math.min(A.top,e.top),A.right=Math.min(A.right,e.right),A.bottom=Math.min(A.bottom,e.bottom),A.left=Math.min(A.left,e.left)}),A}}class we{constructor(A,t,e){this.currModules=[],this.cachedPage=void 0,this.peripherals=A,this.debugHref=e,this.frame=document.createElement("iframe"),this.frame.classList.add("readium-navigator-iframe"),this.frame.classList.add("blank"),this.frame.scrolling="no",this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.display="none",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transformOrigin="0 0",this.frame.style.transform="scale(1)",this.frame.style.background="#fff",this.frame.style.touchAction="none",this.frame.dataset.originalHref=e,this.source="about:blank",this.wrapper=document.createElement("div"),this.wrapper.style.position="relative",this.wrapper.style.float=this.wrapper.style.cssFloat=t===F.rtl?"right":"left",this.wrapper.appendChild(this.frame)}async load(A,t){return this.source===t&&this.loadPromise&&[...this.currModules].sort().join("|")===[...A].sort().join("|")?this.loadPromise:(this.loaded&&this.source!==t&&this.window.stop(),this.source=t,this.loadPromise=new Promise((e,n)=>{var r;if(this.loader&&this.loaded){const s=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...A].sort().join("|")){try{e(s),this.loadPromise=void 0}catch{}return}(r=this.comms)==null||r.halt(),this.loader.destroy(),this.loader=new zA(s,A),this.currModules=A,this.comms=void 0;try{e(s),this.loadPromise=void 0}catch{}return}this.frame.addEventListener("load",()=>{const s=this.frame.contentWindow;this.loader=new zA(s,A),this.currModules=A,this.peripherals.observe(this.wrapper),this.peripherals.observe(s);try{e(s)}catch{}},{once:!0}),this.frame.addEventListener("error",s=>{try{n(s.error),this.loadPromise=void 0}catch{}},{once:!0}),this.frame.style.removeProperty("display"),this.frame.contentWindow.location.replace(this.source)}),this.loadPromise)}loadPageSize(){const A=this.frame.contentWindow,t=A.document.head.querySelector("meta[name=viewport]");if(t){const e=/(\w+) *= *([^\s,]+)/g;let n,r=0,s=0;for(;n=e.exec(t.content);)n[1]==="width"?r=Number.parseFloat(n[2]):n[1]==="height"&&(s=Number.parseFloat(n[2]));if(r>0&&s>0)return{width:r,height:s}}return{width:A.document.body.scrollWidth,height:A.document.body.scrollHeight}}update(A){if(!this.loaded)return;const t=this.loadPageSize();this.frame.style.height=`${t.height}px`,this.frame.style.width=`${t.width}px`;const e=Math.min(this.wrapper.clientWidth/t.width,this.wrapper.clientHeight/t.height);this.frame.style.transform=`scale(${e})`;const n=this.frame.getBoundingClientRect(),r=this.wrapper.clientHeight-n.height;if(this.frame.style.top=`${r/2}px`,A===D.left){const s=this.wrapper.clientWidth-n.width;this.frame.style.left=`${s}px`}else if(A===D.center){const s=this.wrapper.clientWidth-n.width;this.frame.style.left=`${s/2}px`}else this.frame.style.left="0px";this.frame.style.removeProperty("visibility"),this.frame.style.removeProperty("aria-hidden"),this.frame.style.removeProperty("pointer-events"),this.frame.classList.remove("blank"),this.frame.classList.add("loaded")}async destroy(){var A;await this.unfocus(),(A=this.loader)==null||A.destroy(),this.wrapper.remove()}async unload(){var A,t;if(this.loaded)return this.deselect(),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.pointerEvents="none",this.frame.classList.add("blank"),this.frame.classList.remove("loaded"),(A=this.comms)==null||A.halt(),(t=this.loader)==null||t.destroy(),this.comms=void 0,this.frame.blur(),new Promise((e,n)=>{this.frame.addEventListener("load",()=>{try{this.showPromise=void 0,e()}catch{}},{once:!0}),this.frame.addEventListener("error",r=>{try{this.showPromise=void 0,n(r.error)}catch{}},{once:!0}),this.source="about:blank",this.frame.contentWindow.location.replace("about:blank"),this.frame.style.display="none"})}deselect(){var A,t;(t=(A=this.frame.contentWindow)==null?void 0:A.getSelection())==null||t.removeAllRanges()}async unfocus(){var A;if(this.frame.parentElement)return this.comms===void 0?void 0:new Promise((t,e)=>{var n;(n=this.comms)==null||n.send("unfocus",void 0,r=>{var s;(s=this.comms)==null||s.halt(),this.showPromise=void 0,t()})});(A=this.comms)==null||A.halt()}async show(A){if(!this.frame.parentElement){console.warn("Trying to show frame that is not attached to the DOM");return}if(!this.loaded){this.showPromise=void 0;return}return this.showPromise?(this.cachedPage!==A&&(this.update(A),this.cachedPage=A),this.showPromise):(this.cachedPage=A,this.comms?this.comms.resume():this.comms=new et(this.frame.contentWindow,this.source),this.showPromise=new Promise((t,e)=>{this.comms.send("focus",void 0,n=>{this.update(this.cachedPage),t()})}),this.showPromise)}async activate(){return new Promise((A,t)=>{var e;if(!this.comms)return A();(e=this.comms)==null||e.send("activate",void 0,()=>{A()})})}get element(){return this.wrapper}get iframe(){return this.frame}get realSize(){return this.frame.getBoundingClientRect()}get loaded(){return this.frame.contentWindow&&this.frame.contentWindow.location.href!=="about:blank"}set width(A){const t=`${A}%`;this.wrapper.style.width!==t&&(this.wrapper.style.width=t)}set height(A){const t=`${A}px`;this.wrapper.style.height!==t&&(this.wrapper.style.height=t)}get window(){if(!this.frame.contentWindow)throw Error("Trying to use frame window when it doesn't exist");return this.frame.contentWindow}get atLeft(){return this.window.scrollX<5}get atRight(){return this.window.scrollX>this.window.document.scrollingElement.scrollWidth-this.window.innerWidth-5}get msg(){return this.comms}get ldr(){return this.loader}}/*!
95
+ }`,t.document.head.appendChild(A),e.register("set_property",it.moduleName,(i,r)=>{const s=i;Dt(t,s[0],s[1]),r(!0)}),e.register("remove_property",it.moduleName,(i,r)=>{ae(t,i),r(!0)}),e.register("first_visible_locator",it.moduleName,(i,r)=>r(!1)),e.register("unfocus",it.moduleName,(i,r)=>{T(t),r(!0)}),e.register(["focus","go_next","go_prev","go_id","go_end","go_start","go_text","go_progression"],it.moduleName,(i,r)=>r(!0)),e.register("activate",it.moduleName,(i,r)=>{this.unblock(t),r(!0)}),e.log("FixedSetup Mounted"),!0}unmount(t,e){var A;return e.unregisterAll(it.moduleName),(A=t.document.getElementById(fA))==null||A.remove(),e.log("FixedSetup Unmounted"),super.unmount(t,e)}};pA.moduleName="fixed_setup";let an=pA;const ln=["fixed_setup","decorator","peripherals"],hn=["reflowable_setup","decorator","peripherals","column_snapper","scroll_snapper"],le=new Map([an,on,gA,Zi,rn,sn].map(n=>[n.moduleName,n]));class vt{constructor(t=window,e=[]){this.loadedModules=[],this.wnd=t,this.comms=new Ci(t);const A=[...new Set(e)];if(A.length){if(typeof t>"u")throw Error("Loader is not in a web browser");t.parent!==t&&this.comms.log("Loader is probably in a frame"),this.loadedModules=A.map(i=>{const r=this.loadModule(i);if(r)return r.mount(this.wnd,this.comms),r}).filter(i=>i!==void 0)}}loadModule(t){const e=le.get(t);return e===void 0?(this.comms.log(`Module "${name}" does not exist in the library`),e):new e}addModule(t){const e=this.loadModule(t);return!e||!e.mount(this.wnd,this.comms)?!1:(this.loadedModules.push(e),!0)}removeModule(t){const e=le.get(t);if(e===void 0)return this.comms.log(`Module "${t}" does not exist in the library`),!1;const A=this.loadedModules.findIndex(i=>i instanceof e);return A<0?!1:(this.loadedModules[A].unmount(this.wnd,this.comms),this.loadedModules.splice(A,1),!0)}destroy(){this.comms.destroy(),this.loadedModules.forEach(t=>t.unmount(this.wnd,this.comms)),this.loadedModules=[]}}const cn=1e4;class bt{constructor(t,e){this.registry=new Map,this._ready=!1,this.listenerBuffer=[],this.handler=this.handle.bind(this),this.wnd=t,this.origin=e;try{this.channelId=window.crypto.randomUUID()}catch{this.channelId=_t()}this.gc=setInterval(()=>{this.registry.forEach((A,i)=>{performance.now()-A.time>cn&&(console.warn(i,"event for",A.key,"was never handled!"),this.registry.delete(i))})},5e3),window.addEventListener("message",this.handler),this.send("_ping",void 0)}set listener(t){this.listenerBuffer.length>0&&this.listenerBuffer.forEach(e=>t(e[0],e[1])),this.listenerBuffer=[],this._listener=t}clearListener(){typeof this._listener=="function"&&(this._listener=void 0)}halt(){this._ready=!1,window.removeEventListener("message",this.handler),clearInterval(this.gc),this._listener=void 0,this.registry.clear()}resume(){window.addEventListener("message",this.handler),this._ready=!0}handle(t){const e=t.data;if(!e._readium){console.warn("Ignoring",e);return}if(e._channel===this.channelId)switch(e.key){case"_ack":{if(!e.id)return;const A=this.registry.get(e.id);if(!A)return;this.registry.delete(e.id),A.cb(!!e.data);return}case"_pong":this._ready=!0;default:{if(!this.ready)return;typeof this._listener=="function"?this._listener(e.key,e.data):this.listenerBuffer.push([e.key,e.data])}}}get ready(){return this._ready}send(t,e,A,i=!1,r=[]){const s=_t();return A&&this.registry.set(s,{cb:A,time:performance.now(),key:t}),this.wnd.postMessage({_readium:at,_channel:this.channelId,id:s,data:e,key:t,strict:i},"/",r),s}}const gn={RS__oldStyleTf:"'Iowan Old Style', Sitka, 'Sitka Text', Palatino, 'Book Antiqua', 'URW Palladio L', P052, serif",RS__modernTf:"Athelas, Constantia, Charter, 'Bitstream Charter', Cambria, 'Georgia Pro', Georgia, serif",RS__sansTf:"-ui-sans-serif, -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI Variable', 'Segoe UI', Inter, Roboto, 'Helvetica Neue', 'Arial Nova', 'Liberation Sans', Arial, sans-serif",RS__humanistTf:"Seravek, Calibri, 'Gill Sans Nova', Roboto, Ubuntu, 'DejaVu Sans', source-sans-pro, sans-serif",RS__monospaceTf:"ui-monospace, 'Andale Mono', 'Cascadia Code', 'Source Code Pro', Menlo, Consolas, 'DejaVu Sans Mono', monospace"},dn=16,BA=gn.RS__oldStyleTf;class ct{constructor(t){this._optimalLineLength=null,this._canvas=document.createElement("canvas"),this._optimalChars=t.optimalChars,this._minChars=t.minChars,this._maxChars=t.maxChars,this._baseFontSize=t.baseFontSize||dn,this._fontFace=t.fontFace||BA,this._sample=t.sample||null,this._pageGutter=t.pageGutter||0,this._letterSpacing=t.letterSpacing?Math.round(t.letterSpacing*this._baseFontSize):0,this._wordSpacing=t.wordSpacing?Math.round(t.wordSpacing*this._baseFontSize):0,this._isCJK=t.isCJK||!1,this._getRelative=t.getRelative||!1,this._padding=this._pageGutter*2,this._minDivider=this._minChars&&this._minChars<this._optimalChars?this._optimalChars/this._minChars:this._minChars===null?null:1,this._maxMultiplier=this._maxChars&&this._maxChars>this._optimalChars?this._maxChars/this._optimalChars:this._maxChars===null?null:1,this._approximatedWordSpaces=ct.approximateWordSpaces(this._optimalChars,this._sample)}updateMultipliers(){this._minDivider=this._minChars&&this._minChars<this._optimalChars?this._optimalChars/this._minChars:this._minChars===null?null:1,this._maxMultiplier=this._maxChars&&this._maxChars>this._optimalChars?this._maxChars/this._optimalChars:this._maxChars===null?null:1}update(t){t.optimalChars&&(this._optimalChars=t.optimalChars),t.minChars!==void 0&&(this._minChars=t.minChars),t.maxChars!==void 0&&(this._maxChars=t.maxChars),t.baseFontSize&&(this._baseFontSize=t.baseFontSize),t.fontFace!==void 0&&(this._fontFace=t.fontFace||BA),t.letterSpacing&&(this._letterSpacing=t.letterSpacing),t.wordSpacing&&(this._wordSpacing=t.wordSpacing),t.isCJK!=null&&(this._isCJK=t.isCJK),t.pageGutter&&(this._pageGutter=t.pageGutter),t.getRelative&&(this._getRelative=t.getRelative),t.sample&&(this._sample=t.sample,this._approximatedWordSpaces=ct.approximateWordSpaces(this._optimalChars,this._sample)),this.updateMultipliers(),this._optimalLineLength=this.getOptimalLineLength()}get baseFontSize(){return this._baseFontSize}get minimalLineLength(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),this._minDivider!==null?Math.round(this._optimalLineLength/this._minDivider+this._padding)/(this._getRelative?this._baseFontSize:1):null}get maximalLineLength(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),this._maxMultiplier!==null?Math.round(this._optimalLineLength*this._maxMultiplier+this._padding)/(this._getRelative?this._baseFontSize:1):null}get optimalLineLength(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),Math.round(this._optimalLineLength+this._padding)/(this._getRelative?this._baseFontSize:1)}get all(){return this._optimalLineLength||(this._optimalLineLength=this.getOptimalLineLength()),{min:this.minimalLineLength,max:this.maximalLineLength,optimal:this.optimalLineLength,baseFontSize:this._baseFontSize}}static approximateWordSpaces(t,e){let A=0;if(e&&e.length>=t){const i=e.match(/([\s]+)/gi);A=(i?i.length:0)*(t/e.length)}return A}getLineLengthFallback(){const t=this._letterSpacing*(this._optimalChars-1),e=this._wordSpacing*this._approximatedWordSpaces;return this._optimalChars*(this._baseFontSize*.5)+t+e}getOptimalLineLength(){if(this._fontFace){if(typeof this._fontFace=="string")return this.measureText(this._fontFace);{const t=new FontFace(this._fontFace.name,`url(${this._fontFace.url})`);t.load().then(()=>(document.fonts.add(t),this.measureText(t.family)),e=>{})}}return this.getLineLengthFallback()}measureText(t){const e=this._canvas.getContext("2d");if(e&&t){let A=this._isCJK?"水".repeat(this._optimalChars):"0".repeat(this._optimalChars);if(e.font=`${this._baseFontSize}px ${t}`,this._sample&&this._sample.length>=this._optimalChars&&(A=this._sample.slice(0,this._optimalChars)),Object.hasOwn(e,"letterSpacing")&&Object.hasOwn(e,"wordSpacing"))return e.letterSpacing=this._letterSpacing.toString()+"px",e.wordSpacing=this._wordSpacing.toString()+"px",e.measureText(A).width;{const i=this._letterSpacing*(this._optimalChars-1),r=this._wordSpacing*ct.approximateWordSpaces(this._optimalChars,this._sample);return e.measureText(A).width+i+r}}else return this.getLineLengthFallback()}}/*!
96
96
  * (℠)
97
97
  * # sML.js | I'm a Simple and Middling Library.
98
98
  *
@@ -101,7 +101,7 @@
101
101
  *
102
102
  * Portions of this code come from the sML library
103
103
  * Current version: 1.0.36
104
- */class cn{constructor(){const A=navigator.userAgentData,t=navigator.userAgent,e=r=>(typeof r=="string"||typeof r=="number")&&r?String(r).replace(/_/g,".").split(".").map(s=>parseInt(s)||0):[],n=(r="")=>{if(!r)return[];const s=new RegExp("^.*"+r+"[ :\\/]?(\\d+([\\._]\\d+)*).*$");return s.test(t)?e(t.replace(s,"$1")):[]};this.OS=(r=>(/(macOS|Mac OS X)/.test(t)?(/\(iP(hone|od touch);/.test(t)&&(r.iOS=n("CPU (?:iPhone )?OS ")),/\(iPad;/.test(t)?r.iOS=r.iPadOS=n("CPU (?:iPhone )?OS "):/(macOS|Mac OS X) \d/.test(t)&&(document.ontouchend!==void 0?r.iOS=r.iPadOS=n():r.macOS=n("(?:macOS|Mac OS X) "))):/Windows( NT)? \d/.test(t)?r.Windows=(s=>s[0]!==6||!s[1]?s:s[1]===1?[7]:s[1]===2?[8]:[8,1])(n("Windows(?: NT)?")):/Android \d/.test(t)?r.Android=n("Android"):/CrOS/.test(t)?r.ChromeOS=n():/X11;/.test(t)&&(r.Linux=n()),r))({}),A&&A.getHighEntropyValues(["architecture","model","platform","platformVersion","uaFullVersion"]).then(r=>(s=>{const o=r.platform,a=r.platformVersion;if(!(!o||!a)){if(/^i(OS|P(hone|od touch))$/.test(o))s.iOS=e(a);else if(/^iPad(OS)?$/.test(o))s.iOS=s.iPadOS=e(a);else if(/^(macOS|(Mac )?OS X|Mac(Intel)?)$/.test(o))document.ontouchend!==void 0?s.iOS=s.iPadOS=e():s.macOS=e(a);else if(/^(Microsoft )?Windows$/.test(o))s.Windows=e(a);else if(/^(Google )?Android$/.test(o))s.Android=e(a);else if(/^((Google )?Chrome OS|CrOS)$/.test(o))s.ChromeOS=e(a);else if(/^(Linux|Ubuntu|X11)$/.test(o))s.Linux=e(a);else return;Object.keys(this.OS).forEach(h=>delete this.OS[h]),Object.assign(this.OS,s)}})({})),this.UA=(r=>{let s=!1;if(A&&Array.isArray(A.brands)){const o=A.brands.reduce((a,h)=>(a[h.brand]=[h.version*1],a),{});o["Google Chrome"]?(s=!0,r.Blink=r.Chromium=o.Chromium||[],r.Chrome=o["Google Chrome"]):o["Microsoft Edge"]?(s=!0,r.Blink=r.Chromium=o.Chromium||[],r.Edge=o["Microsoft Edge"]):o.Opera&&(s=!0,r.Blink=r.Chromium=o.Chromium||[],r.Opera=o.Opera)}return s||(/ Gecko\/\d/.test(t)?(r.Gecko=n("rv"),/ Waterfox\/\d/.test(t)?r.Waterfox=n("Waterfox"):/ Firefox\/\d/.test(t)&&(r.Firefox=n("Firefox"))):/ Edge\/\d/.test(t)?(r.EdgeHTML=n("Edge"),r.Edge=r.EdgeHTML):/ Chrom(ium|e)\/\d/.test(t)?(r.Blink=r.Chromium=(o=>o[0]?o:n("Chrome"))(n("Chromium")),/ EdgA?\/\d/.test(t)?r.Edge=(o=>o[0]?o:n("Edg"))(n("EdgA")):/ OPR\/\d/.test(t)?r.Opera=n("OPR"):/ Vivaldi\/\d/.test(t)?r.Vivaldi=n("Vivaldi"):/ Silk\/\d/.test(t)?r.Silk=n("Silk"):/ UCBrowser\/\d/.test(t)?r.UCBrowser=n("UCBrowser"):/ Phoebe\/\d/.test(t)?r.Phoebe=n("Phoebe"):r.Chrome=(o=>o[0]?o:r.Chromium)(n("Chrome"))):/ AppleWebKit\/\d/.test(t)?(r.WebKit=n("AppleWebKit"),/ CriOS \d/.test(t)?r.Chrome=n("CriOS"):/ FxiOS \d/.test(t)?r.Firefox=n("FxiOS"):/ EdgiOS\/\d/.test(t)?r.Edge=n("EdgiOS"):/ Version\/\d/.test(t)&&(r.Safari=n("Version"))):/ Trident\/\d/.test(t)&&(r.Trident=n("Trident"),r.InternetExplorer=(o=>o[0]?o:n("MSIE"))(n("rv")))),/[\[; ]FB(AN|_IAB)\//.test(t)&&(r.Facebook=n("FBAV")),/ Line\/\d/.test(t)&&(r.LINE=n("Line")),r})({}),this.Env={get:()=>[this.OS,this.UA].reduce((r,s)=>{for(const o in s)s[o]&&r.push(o);return r},[])}}}const NA=new cn;var Fe=(i=>(i[i.Left=0]="Left",i[i.Center=1]="Center",i[i.Right=2]="Right",i))(Fe||{}),Ue=(i=>(i[i.Top=0]="Top",i[i.Middle=1]="Middle",i[i.Bottom=2]="Bottom",i))(Ue||{});class ye{constructor(){this.outerWidth=0,this.outerHeight=0,this.HTML=document.documentElement,this.Head=document.head,this.Body=document.body}refreshOuterPixels(A){NA.OS.iOS||(this.outerHeight=window.outerHeight-window.innerHeight,NA.OS.Android&&NA.UA.Chrome&&window.screen.height>window.innerHeight&&(this.outerHeight=(window.screen.height-window.innerHeight)/1.5),this.outerWidth=window.outerWidth-window.innerWidth)}getBibiEventCoord(A,t=0){var n;const e={X:0,Y:0};return/^touch/.test(A.type)?(e.X=A.touches[t].screenX,e.Y=A.touches[t].screenY):(e.X=A.screenX,e.Y=A.screenY),(((n=A.target.ownerDocument)==null?void 0:n.documentElement)||A.target.documentElement)===this.HTML&&(e.X-=this.HTML.scrollLeft+this.Body.scrollLeft,e.Y-=this.HTML.scrollTop+this.Body.scrollTop),e.X-=this.outerWidth,e.Y-=this.outerHeight,e}getTouchDistance(A){if(A.touches.length!==2)return 0;const t=A.touches[0].screenX-this.outerWidth,e=A.touches[0].screenY-this.outerHeight,n=A.touches[1].screenX-this.outerWidth,r=A.touches[1].screenY-this.outerHeight;return Math.sqrt(Math.pow(n-t,2)+Math.pow(r-e,2))}getTouchCenter(A){if(A.touches.length!==2)return null;const t=this.HTML.scrollLeft+this.Body.scrollLeft,e=this.HTML.scrollTop+this.Body.scrollTop,n=A.touches[0].screenX-this.outerWidth-t,r=A.touches[0].screenY-this.outerHeight-e,s=A.touches[1].screenX-this.outerWidth-t,o=A.touches[1].screenY-this.outerHeight-e;return{X:(n+s)/2,Y:(r+o)/2}}getBibiEvent(A){if(!A)return{Coord:null,Division:null,Ratio:null,Target:null};const t=this.getBibiEventCoord(A);let e=.3;const n={X:t.X/window.innerWidth,Y:t.Y/window.innerHeight};let r,s,o,a;o=r=e,a=s=1-e;const h={X:null,Y:null};return n.X<o?h.X=0:a<n.X?h.X=2:h.X=1,n.Y<r?h.Y=0:s<n.Y?h.Y=2:h.Y=1,{Target:A.target,Coord:t,Ratio:n,Division:h}}}class ln{constructor(){this._DOM={show:!1,pinchTarget:document.createElement("div"),touch1:document.createElement("div"),touch2:document.createElement("div"),center:document.createElement("div"),stats:document.createElement("div")},this._DOM.show=!0,this._DOM.pinchTarget.style.zIndex=this._DOM.stats.style.zIndex=this._DOM.center.style.zIndex=this._DOM.touch1.style.zIndex=this._DOM.touch2.style.zIndex="100000",this._DOM.pinchTarget.style.position=this._DOM.stats.style.position=this._DOM.center.style.position=this._DOM.touch1.style.position=this._DOM.touch2.style.position="absolute",this._DOM.pinchTarget.style.borderRadius=this._DOM.center.style.borderRadius=this._DOM.touch1.style.borderRadius=this._DOM.touch2.style.borderRadius="50%",this._DOM.pinchTarget.style.pointerEvents=this._DOM.stats.style.pointerEvents=this._DOM.center.style.pointerEvents=this._DOM.touch1.style.pointerEvents=this._DOM.touch2.style.pointerEvents="none",this._DOM.pinchTarget.style.display=this._DOM.center.style.display=this._DOM.touch1.style.display=this._DOM.touch2.style.display="none",this._DOM.pinchTarget.style.paddingTop=this._DOM.center.style.paddingTop="10px",this._DOM.pinchTarget.style.width=this._DOM.pinchTarget.style.height=this._DOM.center.style.width=this._DOM.center.style.height="10px",this._DOM.pinchTarget.style.backgroundColor="green",this._DOM.center.style.backgroundColor="red",this._DOM.touch1.style.backgroundColor=this._DOM.touch2.style.backgroundColor="blue",this._DOM.touch1.style.height=this._DOM.touch2.style.height="20px",this._DOM.touch1.style.width=this._DOM.touch2.style.width="20px",this._DOM.touch1.style.paddingTop=this._DOM.touch2.style.paddingTop="20px",this._DOM.touch1.textContent="1",this._DOM.touch2.textContent="2",this._DOM.stats.style.padding="20px",this._DOM.stats.style.backgroundColor="rgba(0,0,0,0.5)",this._DOM.stats.style.color="white",this._DOM.stats.textContent="[stats]",document.body.appendChild(this._DOM.stats),document.body.appendChild(this._DOM.center),document.body.appendChild(this._DOM.touch1),document.body.appendChild(this._DOM.touch2),document.body.appendChild(this._DOM.pinchTarget)}get show(){return this.DOM.show}get DOM(){return this._DOM}}const Qe=6,it=1.02,Re=50;class Ye{constructor(A,t=!1){this.dragState=0,this.minimumMoved=!1,this.pan={startX:0,endX:0,startY:0,overscrollX:0,overscrollY:0,letItGo:!1,preventClick:!1,translateX:0,translateY:0,touchID:0},this.pinch={startDistance:0,startScale:0,target:{X:0,Y:0},touchN:0,startTranslate:{X:0,Y:0}},this._scale=1,this.scaleDebouncer=0,this.frameBounds=null,this.debugger=null,this.btouchstartHandler=this.touchstartHandler.bind(this),this.btouchendHandler=this.touchendHandler.bind(this),this.btouchmoveHandler=this.touchmoveHandler.bind(this),this.bdblclickHandler=this.dblclickHandler.bind(this),this.bmousedownHandler=this.mousedownHandler.bind(this),this.bmouseupHandler=this.mouseupHandler.bind(this),this.bmousemoveHandler=this.mousemoveHandler.bind(this),this.moveFrame=0,this.manager=A,this.coordinator=new ye,this.attachEvents(),t&&(this.debugger=new ln)}get scale(){return this._scale}set scale(A){isNaN(A)&&(A=1),window.clearTimeout(this.scaleDebouncer),this.scaleDebouncer=window.setTimeout(()=>{this.dragState===0&&this.scale<it&&(this.pan.translateX=0,this.pan.translateY=0,this.clearPan(),this.manager.updateBookStyle()),this.manager.listener("zoom",A)},100),this._scale=A}attachEvents(){this.observe(this.manager.spineElement),this.pan={startX:0,startY:0,endX:0,overscrollX:0,overscrollY:0,letItGo:!1,preventClick:!1,translateX:0,translateY:0,touchID:0},this.pinch={startDistance:0,startScale:0,target:{X:0,Y:0},startTranslate:{X:0,Y:0},touchN:0}}clearPan(){this.pan.letItGo=!1,this.pan.touchID=0,this.pan.endX=0,this.pan.overscrollX=0,this.pan.overscrollY=0}clearPinch(){this.pinch={startDistance:0,startScale:this.pinch.startScale,target:{X:0,Y:0},touchN:0,startTranslate:{X:0,Y:0}}}observe(A){A.addEventListener("touchstart",this.btouchstartHandler),A.addEventListener("touchend",this.btouchendHandler),A.addEventListener("touchmove",this.btouchmoveHandler,{passive:!0}),A.addEventListener("dblclick",this.bdblclickHandler,{passive:!0}),A.addEventListener("mousedown",this.bmousedownHandler),A.addEventListener("mouseup",this.bmouseupHandler),A.addEventListener("mousemove",this.bmousemoveHandler)}clickHandler(A){}touchstartHandler(A){var n,r;if(["TEXTAREA","OPTION","INPUT","SELECT"].indexOf(A.target.nodeName)!==-1)return;switch(A.stopPropagation(),this.frameBounds=this.manager.currentBounds,this.coordinator.refreshOuterPixels(this.frameBounds),A.touches.length){case 3:return;case 2:{A.preventDefault(),this.pinch.startDistance=this.coordinator.getTouchDistance(A);const s=this.startTouch(A);this.pan.startX=s.X,this.pan.startY=s.Y,this.dragState=2,this.manager.updateBookStyle(!0),this.isScaled?(this.pinch.target.X-=this.pan.translateX*(this.pinch.startScale/this.scale),this.pinch.target.Y-=this.pan.translateY*(this.pinch.startScale/this.scale),this.pinch.target={X:0,Y:0},this.pinch.startScale=1/this.scale):(this.pinch.target={X:0,Y:0},this.pinch.startScale=this.scale),this.pinch.startTranslate={X:this.pan.translateX,Y:this.pan.translateY},(n=this.debugger)!=null&&n.show&&(this.debugger.DOM.touch2.style.display="",this.debugger.DOM.center.style.display="",this.debugger.DOM.pinchTarget.style.display="");return}case 1:this.pan.touchID=A.touches[0].identifier,(r=this.debugger)!=null&&r.show&&(this.debugger.DOM.touch1.style.display="");default:this.dragState<1&&(this.dragState=1),this.manager.updateBookStyle(!0)}this.manager.updateSpineStyle(!1);const e=this.startTouch(A);this.pan.startX=e.X,this.pan.startY=e.Y}startTouch(A){const t=this.coordinator.getTouchCenter(A)||this.coordinator.getBibiEventCoord(A);return{X:t.X-this.manager.width/2-this.pan.translateX*this.scale+this.manager.width/2,Y:t.Y-this.manager.height/2-this.pan.translateY*this.scale+this.manager.height/2}}touchendHandler(A){var t,e;if(A.stopPropagation(),!A.touches||A.touches.length===0)this.pan.endX&&!this.isScaled?(this.pinch.touchN&&(this.pan.endX=this.pan.startX),this.updateAfterDrag()):!this.pinch.touchN&&Math.abs(this.pan.overscrollX)>Re&&Math.abs(this.pan.overscrollY)<Re/2&&(this.pan.startX=0,this.pan.endX=-this.pan.overscrollX,this.updateAfterDrag()),this.dragState=0,this.minimumMoved=!1,this.clearPinch(),(t=this.debugger)!=null&&t.show&&(this.debugger.DOM.center.style.display="none",this.debugger.DOM.touch1.style.display="none",this.debugger.DOM.touch2.style.display="none");else if(A.touches.length===1){this.dragState=1,A.touches[0].identifier!==this.pan.touchID&&(this.pan.touchID=A.touches[0].identifier),(e=this.debugger)!=null&&e.show&&(this.debugger.DOM.center.style.display="none",this.debugger.DOM.touch2.style.display="none",this.debugger.DOM.pinchTarget.style.display="none");const n=this.startTouch(A);this.pan.startX=n.X,this.pan.startY=n.Y}window.setTimeout(()=>{this.manager.updateBookStyle(!0),this.dragState===0&&(this.scale<it&&(this.pan.translateX=0,this.pan.translateY=0),this.clearPan()),this.manager.updateBookStyle(!0)},50)}touchmoveHandler(A){var s,o,a,h,c;A.stopPropagation();const t=this.coordinator.getBibiEventCoord(A);Math.abs(this.pan.startY-t.Y)+Math.abs(this.pan.startX-t.X)>5&&(this.minimumMoved||(this.manager.deselect(),this.minimumMoved=!0),this.dragState<1&&(this.dragState=1));const e=(s=this.coordinator)==null?void 0:s.getTouchDistance(A);let n=!1;const r=this.scale;if(this.dragState===2&&e){if(this.pinch.touchN++,this.pinch.touchN<4)return;let l=e/this.pinch.startDistance*this.scale;l>=Qe&&(l=Qe),l<=it&&(l=1),this.scale=l,this.pinch.startDistance=e,n=!0}if(this.pan.letItGo===!1&&(this.pan.letItGo=Math.abs(this.pan.startY-t.Y)<Math.abs(this.pan.startX-t.X)),(o=this.debugger)!=null&&o.show&&(this.debugger.DOM.touch1.style.top=`${t.Y-10}px`,this.debugger.DOM.touch1.style.left=`${t.X-10}px`,this.debugger.DOM.touch1.innerText=`${t.X.toFixed(2)},${t.Y.toFixed(2)}`),this.dragState>0&&this.isScaled||this.dragState>1){if(this.dragState===1){const u={X:t.X-this.manager.width/2,Y:t.Y-this.manager.height/2};this.pan.translateX=(u.X-(this.pan.startX-this.manager.width/2))*1/this.scale,this.pan.translateY=(u.Y-(this.pan.startY-this.manager.height/2))*1/this.scale}else if(this.dragState===2){const u=this.coordinator.getTouchCenter(A);if((a=this.debugger)!=null&&a.show){this.debugger.DOM.center.style.top=`${u.Y-5}px`,this.debugger.DOM.center.style.left=`${u.X-5}px`,this.debugger.DOM.center.innerText=`${u.X.toFixed(2)},${u.Y.toFixed(2)}`;const p=this.coordinator.getBibiEventCoord(A,1);this.debugger.DOM.touch2.style.top=`${p.Y-10}px`,this.debugger.DOM.touch2.style.left=`${p.X-10}px`,this.debugger.DOM.touch2.innerText=`${p.X.toFixed(2)},${p.Y.toFixed(2)}`}u.X-=this.manager.width/2,u.Y-=this.manager.height/2;let m=-u.X/r;m+=u.X/this.scale,this.pinch.target.X+=m,u.X+=this.pinch.target.X*this.scale/this.pinch.startScale;let B=-u.Y/r;B+=u.Y/this.scale,this.pinch.target.Y+=B,u.Y+=this.pinch.target.Y*this.scale/this.pinch.startScale;let f=(u.X-(this.pan.startX-this.manager.width/2))*1/this.scale,E=(u.Y-(this.pan.startY-this.manager.height/2))*1/this.scale;this.pan.translateX=f,this.pan.translateY=E,(h=this.debugger)!=null&&h.show&&(this.debugger.DOM.pinchTarget.style.left=`${this.pinch.target.X*this.scale/this.pinch.startScale-5+this.manager.width/2}px`,this.debugger.DOM.pinchTarget.style.top=`${this.pinch.target.Y*this.scale/this.pinch.startScale-5+this.manager.height/2}px`,this.debugger.DOM.pinchTarget.innerText=`${(this.pinch.target.X*this.scale/this.pinch.startScale).toFixed(2)},${(this.pinch.target.Y*this.scale/this.pinch.startScale).toFixed(2)}`)}const l=this.frameBounds.width/6,g=this.frameBounds.height/6;this.pan.translateX<-l&&(this.pan.overscrollX=-(l+this.pan.translateX),this.pan.translateX=-l),this.pan.translateY<-g&&(this.pan.overscrollY=-(g+this.pan.translateY),this.pan.translateY=-g),this.pan.translateX>l&&(this.pan.overscrollX=l-this.pan.translateX,this.pan.translateX=l),this.pan.translateY>g&&(this.pan.overscrollY=g-this.pan.translateY,this.pan.translateY=g),n=!0,(c=this.debugger)!=null&&c.show&&(this.debugger.DOM.stats.innerText=`TX: ${this.pan.translateX.toFixed(2)}
104
+ */const EA=()=>typeof navigator>"u"?"":navigator.userAgent||"",wA=()=>typeof navigator>"u"?void 0:navigator.userAgentData||void 0;class IA{constructor(){const t=wA(),e=EA(),A=r=>(typeof r=="string"||typeof r=="number")&&r?String(r).replace(/_/g,".").split(".").map(s=>parseInt(s)||0):[],i=(r="")=>{if(!r)return[];const s=new RegExp("^.*"+r+"[ :\\/]?(\\d+([\\._]\\d+)*).*$");return s.test(e)?A(e.replace(s,"$1")):[]};this.OS=(r=>(/(macOS|Mac OS X)/.test(e)?(/\(iP(hone|od touch);/.test(e)&&(r.iOS=i("CPU (?:iPhone )?OS ")),/\(iPad;/.test(e)?r.iOS=r.iPadOS=i("CPU (?:iPhone )?OS "):/(macOS|Mac OS X) \d/.test(e)&&(document.ontouchend!==void 0?r.iOS=r.iPadOS=i():r.macOS=i("(?:macOS|Mac OS X) "))):/Windows( NT)? \d/.test(e)?r.Windows=(s=>s[0]!==6||!s[1]?s:s[1]===1?[7]:s[1]===2?[8]:[8,1])(i("Windows(?: NT)?")):/Android \d/.test(e)?r.Android=i("Android"):/CrOS/.test(e)?r.ChromeOS=i():/X11;/.test(e)&&(r.Linux=i()),r))({}),t&&t.getHighEntropyValues(["architecture","model","platform","platformVersion","uaFullVersion"]).then(r=>(s=>{const o=r.platform,a=r.platformVersion;if(!(!o||!a)){if(/^i(OS|P(hone|od touch))$/.test(o))s.iOS=A(a);else if(/^iPad(OS)?$/.test(o))s.iOS=s.iPadOS=A(a);else if(/^(macOS|(Mac )?OS X|Mac(Intel)?)$/.test(o))document.ontouchend!==void 0?s.iOS=s.iPadOS=A():s.macOS=A(a);else if(/^(Microsoft )?Windows$/.test(o))s.Windows=A(a);else if(/^(Google )?Android$/.test(o))s.Android=A(a);else if(/^((Google )?Chrome OS|CrOS)$/.test(o))s.ChromeOS=A(a);else if(/^(Linux|Ubuntu|X11)$/.test(o))s.Linux=A(a);else return;Object.keys(this.OS).forEach(l=>delete this.OS[l]),Object.assign(this.OS,s)}})({})),this.UA=(r=>{let s=!1;if(t&&Array.isArray(t.brands)){const o=t.brands.reduce((a,l)=>(a[l.brand]=[l.version*1],a),{});o["Google Chrome"]?(s=!0,r.Blink=r.Chromium=o.Chromium||[],r.Chrome=o["Google Chrome"]):o["Microsoft Edge"]?(s=!0,r.Blink=r.Chromium=o.Chromium||[],r.Edge=o["Microsoft Edge"]):o.Opera&&(s=!0,r.Blink=r.Chromium=o.Chromium||[],r.Opera=o.Opera)}return s||(/ Gecko\/\d/.test(e)?(r.Gecko=i("rv"),/ Waterfox\/\d/.test(e)?r.Waterfox=i("Waterfox"):/ Firefox\/\d/.test(e)&&(r.Firefox=i("Firefox"))):/ Edge\/\d/.test(e)?(r.EdgeHTML=i("Edge"),r.Edge=r.EdgeHTML):/ Chrom(ium|e)\/\d/.test(e)?(r.Blink=r.Chromium=(o=>o[0]?o:i("Chrome"))(i("Chromium")),/ EdgA?\/\d/.test(e)?r.Edge=(o=>o[0]?o:i("Edg"))(i("EdgA")):/ OPR\/\d/.test(e)?r.Opera=i("OPR"):/ Vivaldi\/\d/.test(e)?r.Vivaldi=i("Vivaldi"):/ Silk\/\d/.test(e)?r.Silk=i("Silk"):/ UCBrowser\/\d/.test(e)?r.UCBrowser=i("UCBrowser"):/ Phoebe\/\d/.test(e)?r.Phoebe=i("Phoebe"):r.Chrome=(o=>o[0]?o:r.Chromium)(i("Chrome"))):/ AppleWebKit\/\d/.test(e)?(r.WebKit=i("AppleWebKit"),/ CriOS \d/.test(e)?r.Chrome=i("CriOS"):/ FxiOS \d/.test(e)?r.Firefox=i("FxiOS"):/ EdgiOS\/\d/.test(e)?r.Edge=i("EdgiOS"):/ Version\/\d/.test(e)&&(r.Safari=i("Version"))):/ Trident\/\d/.test(e)&&(r.Trident=i("Trident"),r.InternetExplorer=(o=>o[0]?o:i("MSIE"))(i("rv")))),/[\[; ]FB(AN|_IAB)\//.test(e)&&(r.Facebook=i("FBAV")),/ Line\/\d/.test(e)&&(r.LINE=i("Line")),r})({}),this.Env={get:()=>[this.OS,this.UA].reduce((r,s)=>{for(const o in s)s[o]&&r.push(o);return r},[])}}}class un extends IA{get iOSRequest(){const t=wA(),e=EA();if(this.OS.iOS&&!this.OS.iPadOS)return"mobile";if(this.OS.iPadOS)return/\(iPad;/.test(e)||t&&/^iPad(OS)?$/.test(t.platform)?"mobile":"desktop"}}const Ft=new IA,X=new un;class FA{constructor(t){this.hidden=!0,this.destroyed=!1,this.currModules=[],this.frame=document.createElement("iframe"),this.frame.classList.add("readium-navigator-iframe"),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transition="visibility 0s, opacity 0.1s linear",this.source=t}async load(t){return new Promise((e,A)=>{var i;if(this.loader){const r=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...t].sort().join("|")){try{e(r)}catch{}return}(i=this.comms)==null||i.halt(),this.loader.destroy(),this.loader=new vt(r,t),this.currModules=t,this.comms=void 0;try{e(r)}catch{}return}this.frame.onload=()=>{const r=this.frame.contentWindow;this.loader=new vt(r,t),this.currModules=t;try{e(r)}catch{}},this.frame.onerror=r=>{try{A(r)}catch{}},this.frame.contentWindow.location.replace(this.source)})}async destroy(){var t;await this.hide(),(t=this.loader)==null||t.destroy(),this.frame.remove(),this.destroyed=!0}async hide(){var t;if(!this.destroyed){if(this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.opacity="0",this.frame.style.pointerEvents="none",this.hidden=!0,this.frame.parentElement)return this.comms===void 0||!this.comms.ready?void 0:new Promise((e,A)=>{var i;(i=this.comms)==null||i.send("unfocus",void 0,r=>{var s;(s=this.comms)==null||s.halt(),e()})});(t=this.comms)==null||t.halt()}}async show(t){if(this.destroyed)throw Error("Trying to show frame when it doesn't exist");if(!this.frame.parentElement)throw Error("Trying to show frame that is not attached to the DOM");return this.comms?this.comms.resume():this.comms=new bt(this.frame.contentWindow,this.source),new Promise((e,A)=>{var i;(i=this.comms)==null||i.send("activate",void 0,()=>{var r;(r=this.comms)==null||r.send("focus",void 0,()=>{var o;const s=()=>{var a;this.frame.style.removeProperty("visibility"),this.frame.style.removeProperty("aria-hidden"),this.frame.style.removeProperty("opacity"),this.frame.style.removeProperty("pointer-events"),this.hidden=!1,Ft.UA.WebKit&&((a=this.comms)==null||a.send("force_webkit_recalc",void 0)),e()};t!==void 0?(o=this.comms)==null||o.send("go_progression",t,s):s()})})})}setCSSProperties(t){var e,A,i;this.destroyed||!this.frame.contentWindow||(this.hidden&&(this.comms?(e=this.comms)==null||e.resume():this.comms=new bt(this.frame.contentWindow,this.source)),(A=this.comms)==null||A.send("update_properties",t),this.hidden&&((i=this.comms)==null||i.halt()))}get iframe(){if(this.destroyed)throw Error("Trying to use frame when it doesn't exist");return this.frame}get realSize(){if(this.destroyed)throw Error("Trying to use frame client rect when it doesn't exist");return this.frame.getBoundingClientRect()}get window(){if(this.destroyed||!this.frame.contentWindow)throw Error("Trying to use frame window when it doesn't exist");return this.frame.contentWindow}get atLeft(){return this.window.scrollX<5}get atRight(){return this.window.scrollX>this.window.document.scrollingElement.scrollWidth-this.window.innerWidth-5}get msg(){return this.comms}get ldr(){return this.loader}}const UA=5,yA=3;class CA{constructor(t,e,A){this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.pendingUpdates=new Map,this.container=t,this.positions=e,this.currentCssProperties=A}async destroy(){let t=this.inprogress.values(),e=t.next();const A=[];for(;e.value;)A.push(e.value),e=t.next();A.length>0&&await Promise.allSettled(A),this.inprogress.clear();let i=this.pool.values(),r=i.next();for(;r.value;)await r.value.destroy(),r=i.next();this.pool.clear(),this.blobs.forEach(s=>URL.revokeObjectURL(s)),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}async update(t,e,A,i=!1){let r=this.positions.findIndex(a=>a.locations.position===e.locations.position);if(r<0)throw Error(`Locator not found in position list: ${e.locations.position} > ${this.positions.reduce((a,l)=>l.locations.position||0>a?l.locations.position||0:a,0)}`);const s=this.positions[r].href;this.inprogress.has(s)&&await this.inprogress.get(s);const o=new Promise(async(a,l)=>{var M,B;const h=[],c=[];this.positions.forEach((f,F)=>{(F>r+UA||F<r-UA)&&(h.includes(f.href)||h.push(f.href)),F<r+yA&&F>r-yA&&(c.includes(f.href)||c.push(f.href))}),h.forEach(async f=>{var F;c.includes(f)||this.pool.has(f)&&(await((F=this.pool.get(f))==null?void 0:F.destroy()),this.pool.delete(f),this.pendingUpdates.has(f)&&this.pendingUpdates.set(f,{inPool:!1}))}),this.currentBaseURL!==void 0&&t.baseURL!==this.currentBaseURL&&(this.blobs.forEach(f=>URL.revokeObjectURL(f)),this.blobs.clear()),this.currentBaseURL=t.baseURL;const g=async f=>{var I;if(i&&(this.blobs.forEach(U=>URL.revokeObjectURL(U)),this.blobs.clear(),this.pendingUpdates.clear()),this.pendingUpdates.has(f)&&((I=this.pendingUpdates.get(f))==null?void 0:I.inPool)===!1){const U=this.blobs.get(f);U&&(URL.revokeObjectURL(U),this.blobs.delete(f),this.pendingUpdates.delete(f))}if(this.pool.has(f)){const U=this.pool.get(f);if(!this.blobs.has(f))await U.destroy(),this.pool.delete(f),this.pendingUpdates.delete(f);else{await U.load(A);return}}const F=t.readingOrder.findWithHref(f);if(!F)return;if(!this.blobs.has(f)){const v=await new Se(t,this.currentBaseURL||"",F,this.currentCssProperties).build();this.blobs.set(f,v)}const Q=new FA(this.blobs.get(f));f!==s&&await Q.hide(),this.container.appendChild(Q.iframe),await Q.load(A),this.pool.set(f,Q)};try{await Promise.all(c.map(f=>g(f)))}catch(f){l(f)}const m=this.pool.get(s);((m==null?void 0:m.source)!==((M=this._currentFrame)==null?void 0:M.source)||i)&&(await((B=this._currentFrame)==null?void 0:B.hide()),m&&await m.load(A),m&&await m.show(e.locations.progression),this._currentFrame=m),a()});this.inprogress.set(s,o),await o,this.inprogress.delete(s)}setCSSProperties(t){if(!((A,i)=>{const r=Object.keys(A),s=Object.keys(i);if(r.length!==s.length)return!1;for(const o of r)if(A[o]!==i[o])return!1;return!0})(this.currentCssProperties||{},t)){this.currentCssProperties=t,this.pool.forEach(A=>{A.setCSSProperties(t)});for(const A of this.blobs.keys())this.pendingUpdates.set(A,{inPool:this.pool.has(A)})}}get currentFrames(){return[this._currentFrame]}get currentBounds(){const t={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(e=>{if(!e)return;const A=e.realSize;t.x=Math.min(t.x,A.x),t.y=Math.min(t.y,A.y),t.width+=A.width,t.height=Math.max(t.height,A.height),t.top=Math.min(t.top,A.top),t.right=Math.min(t.right,A.right),t.bottom=Math.min(t.bottom,A.bottom),t.left=Math.min(t.left,A.left)}),t}}class RA{constructor(t,e,A){this.currModules=[],this.cachedPage=void 0,this.peripherals=t,this.debugHref=A,this.frame=document.createElement("iframe"),this.frame.classList.add("readium-navigator-iframe"),this.frame.classList.add("blank"),this.frame.scrolling="no",this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.display="none",this.frame.style.position="absolute",this.frame.style.pointerEvents="none",this.frame.style.transformOrigin="0 0",this.frame.style.transform="scale(1)",this.frame.style.background="#fff",this.frame.style.touchAction="none",this.frame.dataset.originalHref=A,this.source="about:blank",this.wrapper=document.createElement("div"),this.wrapper.style.position="relative",this.wrapper.style.float=this.wrapper.style.cssFloat=e===w.rtl?"right":"left",this.wrapper.appendChild(this.frame)}async load(t,e){return this.source===e&&this.loadPromise&&[...this.currModules].sort().join("|")===[...t].sort().join("|")?this.loadPromise:(this.loaded&&this.source!==e&&this.window.stop(),this.source=e,this.loadPromise=new Promise((A,i)=>{var r;if(this.loader&&this.loaded){const s=this.frame.contentWindow;if([...this.currModules].sort().join("|")===[...t].sort().join("|")){try{A(s),this.loadPromise=void 0}catch{}return}(r=this.comms)==null||r.halt(),this.loader.destroy(),this.loader=new vt(s,t),this.currModules=t,this.comms=void 0;try{A(s),this.loadPromise=void 0}catch{}return}this.frame.addEventListener("load",()=>{const s=this.frame.contentWindow;this.loader=new vt(s,t),this.currModules=t,this.peripherals.observe(this.wrapper),this.peripherals.observe(s);try{A(s)}catch{}},{once:!0}),this.frame.addEventListener("error",s=>{try{i(s.error),this.loadPromise=void 0}catch{}},{once:!0}),this.frame.style.removeProperty("display"),this.frame.contentWindow.location.replace(this.source)}),this.loadPromise)}loadPageSize(){const t=this.frame.contentWindow,e=t.document.head.querySelector("meta[name=viewport]");if(e){const A=/(\w+) *= *([^\s,]+)/g;let i,r=0,s=0;for(;i=A.exec(e.content);)i[1]==="width"?r=Number.parseFloat(i[2]):i[1]==="height"&&(s=Number.parseFloat(i[2]));if(r>0&&s>0)return{width:r,height:s}}return{width:t.document.body.scrollWidth,height:t.document.body.scrollHeight}}update(t){if(!this.loaded)return;const e=this.loadPageSize();this.frame.style.height=`${e.height}px`,this.frame.style.width=`${e.width}px`;const A=Math.min(this.wrapper.clientWidth/e.width,this.wrapper.clientHeight/e.height);this.frame.style.transform=`scale(${A})`;const i=this.frame.getBoundingClientRect(),r=this.wrapper.clientHeight-i.height;if(this.frame.style.top=`${r/2}px`,t===O.left){const s=this.wrapper.clientWidth-i.width;this.frame.style.left=`${s}px`}else if(t===O.center){const s=this.wrapper.clientWidth-i.width;this.frame.style.left=`${s/2}px`}else this.frame.style.left="0px";this.frame.style.removeProperty("visibility"),this.frame.style.removeProperty("aria-hidden"),this.frame.style.removeProperty("pointer-events"),this.frame.classList.remove("blank"),this.frame.classList.add("loaded")}async destroy(){var t;await this.unfocus(),(t=this.loader)==null||t.destroy(),this.wrapper.remove()}async unload(){var t,e;if(this.loaded)return this.deselect(),this.frame.style.visibility="hidden",this.frame.style.setProperty("aria-hidden","true"),this.frame.style.pointerEvents="none",this.frame.classList.add("blank"),this.frame.classList.remove("loaded"),(t=this.comms)==null||t.halt(),(e=this.loader)==null||e.destroy(),this.comms=void 0,this.frame.blur(),new Promise((A,i)=>{this.frame.addEventListener("load",()=>{try{this.showPromise=void 0,A()}catch{}},{once:!0}),this.frame.addEventListener("error",r=>{try{this.showPromise=void 0,i(r.error)}catch{}},{once:!0}),this.source="about:blank",this.frame.contentWindow.location.replace("about:blank"),this.frame.style.display="none"})}deselect(){var t,e;(e=(t=this.frame.contentWindow)==null?void 0:t.getSelection())==null||e.removeAllRanges()}async unfocus(){var t;if(this.frame.parentElement)return this.comms===void 0?void 0:new Promise((e,A)=>{var i;(i=this.comms)==null||i.send("unfocus",void 0,r=>{var s;(s=this.comms)==null||s.halt(),this.showPromise=void 0,e()})});(t=this.comms)==null||t.halt()}async show(t){if(!this.frame.parentElement){console.warn("Trying to show frame that is not attached to the DOM");return}if(!this.loaded){this.showPromise=void 0;return}return this.showPromise?(this.cachedPage!==t&&(this.update(t),this.cachedPage=t),this.showPromise):(this.cachedPage=t,this.comms?this.comms.resume():this.comms=new bt(this.frame.contentWindow,this.source),this.showPromise=new Promise((e,A)=>{this.comms.send("focus",void 0,i=>{this.update(this.cachedPage),e()})}),this.showPromise)}async activate(){return new Promise((t,e)=>{var A;if(!this.comms)return t();(A=this.comms)==null||A.send("activate",void 0,()=>{t()})})}get element(){return this.wrapper}get iframe(){return this.frame}get realSize(){return this.frame.getBoundingClientRect()}get loaded(){return this.frame.contentWindow&&this.frame.contentWindow.location.href!=="about:blank"}set width(t){const e=`${t}%`;this.wrapper.style.width!==e&&(this.wrapper.style.width=e)}set height(t){const e=`${t}px`;this.wrapper.style.height!==e&&(this.wrapper.style.height=e)}get window(){if(!this.frame.contentWindow)throw Error("Trying to use frame window when it doesn't exist");return this.frame.contentWindow}get atLeft(){return this.window.scrollX<5}get atRight(){return this.window.scrollX>this.window.document.scrollingElement.scrollWidth-this.window.innerWidth-5}get msg(){return this.comms}get ldr(){return this.loader}}var QA=(n=>(n[n.Left=0]="Left",n[n.Center=1]="Center",n[n.Right=2]="Right",n))(QA||{}),zA=(n=>(n[n.Top=0]="Top",n[n.Middle=1]="Middle",n[n.Bottom=2]="Bottom",n))(zA||{});class YA{constructor(){this.outerWidth=0,this.outerHeight=0,this.HTML=document.documentElement,this.Head=document.head,this.Body=document.body}refreshOuterPixels(t){Ft.OS.iOS||(this.outerHeight=window.outerHeight-window.innerHeight,Ft.OS.Android&&Ft.UA.Chrome&&window.screen.height>window.innerHeight&&(this.outerHeight=(window.screen.height-window.innerHeight)/1.5),this.outerWidth=window.outerWidth-window.innerWidth)}getBibiEventCoord(t,e=0){var i;const A={X:0,Y:0};return/^touch/.test(t.type)?(A.X=t.touches[e].screenX,A.Y=t.touches[e].screenY):(A.X=t.screenX,A.Y=t.screenY),(((i=t.target.ownerDocument)==null?void 0:i.documentElement)||t.target.documentElement)===this.HTML&&(A.X-=this.HTML.scrollLeft+this.Body.scrollLeft,A.Y-=this.HTML.scrollTop+this.Body.scrollTop),A.X-=this.outerWidth,A.Y-=this.outerHeight,A}getTouchDistance(t){if(t.touches.length!==2)return 0;const e=t.touches[0].screenX-this.outerWidth,A=t.touches[0].screenY-this.outerHeight,i=t.touches[1].screenX-this.outerWidth,r=t.touches[1].screenY-this.outerHeight;return Math.sqrt(Math.pow(i-e,2)+Math.pow(r-A,2))}getTouchCenter(t){if(t.touches.length!==2)return null;const e=this.HTML.scrollLeft+this.Body.scrollLeft,A=this.HTML.scrollTop+this.Body.scrollTop,i=t.touches[0].screenX-this.outerWidth-e,r=t.touches[0].screenY-this.outerHeight-A,s=t.touches[1].screenX-this.outerWidth-e,o=t.touches[1].screenY-this.outerHeight-A;return{X:(i+s)/2,Y:(r+o)/2}}getBibiEvent(t){if(!t)return{Coord:null,Division:null,Ratio:null,Target:null};const e=this.getBibiEventCoord(t);let A=.3;const i={X:e.X/window.innerWidth,Y:e.Y/window.innerHeight};let r,s,o,a;o=r=A,a=s=1-A;const l={X:null,Y:null};return i.X<o?l.X=0:a<i.X?l.X=2:l.X=1,i.Y<r?l.Y=0:s<i.Y?l.Y=2:l.Y=1,{Target:t.target,Coord:e,Ratio:i,Division:l}}}class mn{constructor(){this._DOM={show:!1,pinchTarget:document.createElement("div"),touch1:document.createElement("div"),touch2:document.createElement("div"),center:document.createElement("div"),stats:document.createElement("div")},this._DOM.show=!0,this._DOM.pinchTarget.style.zIndex=this._DOM.stats.style.zIndex=this._DOM.center.style.zIndex=this._DOM.touch1.style.zIndex=this._DOM.touch2.style.zIndex="100000",this._DOM.pinchTarget.style.position=this._DOM.stats.style.position=this._DOM.center.style.position=this._DOM.touch1.style.position=this._DOM.touch2.style.position="absolute",this._DOM.pinchTarget.style.borderRadius=this._DOM.center.style.borderRadius=this._DOM.touch1.style.borderRadius=this._DOM.touch2.style.borderRadius="50%",this._DOM.pinchTarget.style.pointerEvents=this._DOM.stats.style.pointerEvents=this._DOM.center.style.pointerEvents=this._DOM.touch1.style.pointerEvents=this._DOM.touch2.style.pointerEvents="none",this._DOM.pinchTarget.style.display=this._DOM.center.style.display=this._DOM.touch1.style.display=this._DOM.touch2.style.display="none",this._DOM.pinchTarget.style.paddingTop=this._DOM.center.style.paddingTop="10px",this._DOM.pinchTarget.style.width=this._DOM.pinchTarget.style.height=this._DOM.center.style.width=this._DOM.center.style.height="10px",this._DOM.pinchTarget.style.backgroundColor="green",this._DOM.center.style.backgroundColor="red",this._DOM.touch1.style.backgroundColor=this._DOM.touch2.style.backgroundColor="blue",this._DOM.touch1.style.height=this._DOM.touch2.style.height="20px",this._DOM.touch1.style.width=this._DOM.touch2.style.width="20px",this._DOM.touch1.style.paddingTop=this._DOM.touch2.style.paddingTop="20px",this._DOM.touch1.textContent="1",this._DOM.touch2.textContent="2",this._DOM.stats.style.padding="20px",this._DOM.stats.style.backgroundColor="rgba(0,0,0,0.5)",this._DOM.stats.style.color="white",this._DOM.stats.textContent="[stats]",document.body.appendChild(this._DOM.stats),document.body.appendChild(this._DOM.center),document.body.appendChild(this._DOM.touch1),document.body.appendChild(this._DOM.touch2),document.body.appendChild(this._DOM.pinchTarget)}get show(){return this.DOM.show}get DOM(){return this._DOM}}const SA=6,he=1.02,NA=50;class xA{constructor(t,e=!1){this.dragState=0,this.minimumMoved=!1,this.pan={startX:0,endX:0,startY:0,overscrollX:0,overscrollY:0,letItGo:!1,preventClick:!1,translateX:0,translateY:0,touchID:0},this.pinch={startDistance:0,startScale:0,target:{X:0,Y:0},touchN:0,startTranslate:{X:0,Y:0}},this._scale=1,this.scaleDebouncer=0,this.frameBounds=null,this.debugger=null,this.btouchstartHandler=this.touchstartHandler.bind(this),this.btouchendHandler=this.touchendHandler.bind(this),this.btouchmoveHandler=this.touchmoveHandler.bind(this),this.bdblclickHandler=this.dblclickHandler.bind(this),this.bmousedownHandler=this.mousedownHandler.bind(this),this.bmouseupHandler=this.mouseupHandler.bind(this),this.bmousemoveHandler=this.mousemoveHandler.bind(this),this.moveFrame=0,this.manager=t,this.coordinator=new YA,this.attachEvents(),e&&(this.debugger=new mn)}get scale(){return this._scale}set scale(t){isNaN(t)&&(t=1),window.clearTimeout(this.scaleDebouncer),this.scaleDebouncer=window.setTimeout(()=>{this.dragState===0&&this.scale<he&&(this.pan.translateX=0,this.pan.translateY=0,this.clearPan(),this.manager.updateBookStyle()),this.manager.listener("zoom",t)},100),this._scale=t}attachEvents(){this.observe(this.manager.spineElement),this.pan={startX:0,startY:0,endX:0,overscrollX:0,overscrollY:0,letItGo:!1,preventClick:!1,translateX:0,translateY:0,touchID:0},this.pinch={startDistance:0,startScale:0,target:{X:0,Y:0},startTranslate:{X:0,Y:0},touchN:0}}clearPan(){this.pan.letItGo=!1,this.pan.touchID=0,this.pan.endX=0,this.pan.overscrollX=0,this.pan.overscrollY=0}clearPinch(){this.pinch={startDistance:0,startScale:this.pinch.startScale,target:{X:0,Y:0},touchN:0,startTranslate:{X:0,Y:0}}}observe(t){t.addEventListener("touchstart",this.btouchstartHandler),t.addEventListener("touchend",this.btouchendHandler),t.addEventListener("touchmove",this.btouchmoveHandler,{passive:!0}),t.addEventListener("dblclick",this.bdblclickHandler,{passive:!0}),t.addEventListener("mousedown",this.bmousedownHandler),t.addEventListener("mouseup",this.bmouseupHandler),t.addEventListener("mousemove",this.bmousemoveHandler)}clickHandler(t){}touchstartHandler(t){var i,r;if(["TEXTAREA","OPTION","INPUT","SELECT"].indexOf(t.target.nodeName)!==-1)return;switch(t.stopPropagation(),this.frameBounds=this.manager.currentBounds,this.coordinator.refreshOuterPixels(this.frameBounds),t.touches.length){case 3:return;case 2:{t.preventDefault(),this.pinch.startDistance=this.coordinator.getTouchDistance(t);const s=this.startTouch(t);this.pan.startX=s.X,this.pan.startY=s.Y,this.dragState=2,this.manager.updateBookStyle(!0),this.isScaled?(this.pinch.target.X-=this.pan.translateX*(this.pinch.startScale/this.scale),this.pinch.target.Y-=this.pan.translateY*(this.pinch.startScale/this.scale),this.pinch.target={X:0,Y:0},this.pinch.startScale=1/this.scale):(this.pinch.target={X:0,Y:0},this.pinch.startScale=this.scale),this.pinch.startTranslate={X:this.pan.translateX,Y:this.pan.translateY},(i=this.debugger)!=null&&i.show&&(this.debugger.DOM.touch2.style.display="",this.debugger.DOM.center.style.display="",this.debugger.DOM.pinchTarget.style.display="");return}case 1:this.pan.touchID=t.touches[0].identifier,(r=this.debugger)!=null&&r.show&&(this.debugger.DOM.touch1.style.display="");default:this.dragState<1&&(this.dragState=1),this.manager.updateBookStyle(!0)}this.manager.updateSpineStyle(!1);const A=this.startTouch(t);this.pan.startX=A.X,this.pan.startY=A.Y}startTouch(t){const e=this.coordinator.getTouchCenter(t)||this.coordinator.getBibiEventCoord(t);return{X:e.X-this.manager.width/2-this.pan.translateX*this.scale+this.manager.width/2,Y:e.Y-this.manager.height/2-this.pan.translateY*this.scale+this.manager.height/2}}touchendHandler(t){var e,A;if(t.stopPropagation(),!t.touches||t.touches.length===0)this.pan.endX&&!this.isScaled?(this.pinch.touchN&&(this.pan.endX=this.pan.startX),this.updateAfterDrag()):!this.pinch.touchN&&Math.abs(this.pan.overscrollX)>NA&&Math.abs(this.pan.overscrollY)<NA/2&&(this.pan.startX=0,this.pan.endX=-this.pan.overscrollX,this.updateAfterDrag()),this.dragState=0,this.minimumMoved=!1,this.clearPinch(),(e=this.debugger)!=null&&e.show&&(this.debugger.DOM.center.style.display="none",this.debugger.DOM.touch1.style.display="none",this.debugger.DOM.touch2.style.display="none");else if(t.touches.length===1){this.dragState=1,t.touches[0].identifier!==this.pan.touchID&&(this.pan.touchID=t.touches[0].identifier),(A=this.debugger)!=null&&A.show&&(this.debugger.DOM.center.style.display="none",this.debugger.DOM.touch2.style.display="none",this.debugger.DOM.pinchTarget.style.display="none");const i=this.startTouch(t);this.pan.startX=i.X,this.pan.startY=i.Y}window.setTimeout(()=>{this.manager.updateBookStyle(!0),this.dragState===0&&(this.scale<he&&(this.pan.translateX=0,this.pan.translateY=0),this.clearPan()),this.manager.updateBookStyle(!0)},50)}touchmoveHandler(t){var s,o,a,l,h;t.stopPropagation();const e=this.coordinator.getBibiEventCoord(t);Math.abs(this.pan.startY-e.Y)+Math.abs(this.pan.startX-e.X)>5&&(this.minimumMoved||(this.manager.deselect(),this.minimumMoved=!0),this.dragState<1&&(this.dragState=1));const A=(s=this.coordinator)==null?void 0:s.getTouchDistance(t);let i=!1;const r=this.scale;if(this.dragState===2&&A){if(this.pinch.touchN++,this.pinch.touchN<4)return;let c=A/this.pinch.startDistance*this.scale;c>=SA&&(c=SA),c<=he&&(c=1),this.scale=c,this.pinch.startDistance=A,i=!0}if(this.pan.letItGo===!1&&(this.pan.letItGo=Math.abs(this.pan.startY-e.Y)<Math.abs(this.pan.startX-e.X)),(o=this.debugger)!=null&&o.show&&(this.debugger.DOM.touch1.style.top=`${e.Y-10}px`,this.debugger.DOM.touch1.style.left=`${e.X-10}px`,this.debugger.DOM.touch1.innerText=`${e.X.toFixed(2)},${e.Y.toFixed(2)}`),this.dragState>0&&this.isScaled||this.dragState>1){if(this.dragState===1){const m={X:e.X-this.manager.width/2,Y:e.Y-this.manager.height/2};this.pan.translateX=(m.X-(this.pan.startX-this.manager.width/2))*1/this.scale,this.pan.translateY=(m.Y-(this.pan.startY-this.manager.height/2))*1/this.scale}else if(this.dragState===2){const m=this.coordinator.getTouchCenter(t);if((a=this.debugger)!=null&&a.show){this.debugger.DOM.center.style.top=`${m.Y-5}px`,this.debugger.DOM.center.style.left=`${m.X-5}px`,this.debugger.DOM.center.innerText=`${m.X.toFixed(2)},${m.Y.toFixed(2)}`;const Q=this.coordinator.getBibiEventCoord(t,1);this.debugger.DOM.touch2.style.top=`${Q.Y-10}px`,this.debugger.DOM.touch2.style.left=`${Q.X-10}px`,this.debugger.DOM.touch2.innerText=`${Q.X.toFixed(2)},${Q.Y.toFixed(2)}`}m.X-=this.manager.width/2,m.Y-=this.manager.height/2;let M=-m.X/r;M+=m.X/this.scale,this.pinch.target.X+=M,m.X+=this.pinch.target.X*this.scale/this.pinch.startScale;let B=-m.Y/r;B+=m.Y/this.scale,this.pinch.target.Y+=B,m.Y+=this.pinch.target.Y*this.scale/this.pinch.startScale;let f=(m.X-(this.pan.startX-this.manager.width/2))*1/this.scale,F=(m.Y-(this.pan.startY-this.manager.height/2))*1/this.scale;this.pan.translateX=f,this.pan.translateY=F,(l=this.debugger)!=null&&l.show&&(this.debugger.DOM.pinchTarget.style.left=`${this.pinch.target.X*this.scale/this.pinch.startScale-5+this.manager.width/2}px`,this.debugger.DOM.pinchTarget.style.top=`${this.pinch.target.Y*this.scale/this.pinch.startScale-5+this.manager.height/2}px`,this.debugger.DOM.pinchTarget.innerText=`${(this.pinch.target.X*this.scale/this.pinch.startScale).toFixed(2)},${(this.pinch.target.Y*this.scale/this.pinch.startScale).toFixed(2)}`)}const c=this.frameBounds.width/6,g=this.frameBounds.height/6;this.pan.translateX<-c&&(this.pan.overscrollX=-(c+this.pan.translateX),this.pan.translateX=-c),this.pan.translateY<-g&&(this.pan.overscrollY=-(g+this.pan.translateY),this.pan.translateY=-g),this.pan.translateX>c&&(this.pan.overscrollX=c-this.pan.translateX,this.pan.translateX=c),this.pan.translateY>g&&(this.pan.overscrollY=g-this.pan.translateY,this.pan.translateY=g),i=!0,(h=this.debugger)!=null&&h.show&&(this.debugger.DOM.stats.innerText=`TX: ${this.pan.translateX.toFixed(2)}
105
105
  TY: ${this.pan.translateY.toFixed(2)}
106
106
  Zoom: ${this.scale.toFixed(2)}
107
- Overscroll: ${this.pan.overscrollX.toFixed(2)},${this.pan.overscrollY.toFixed(2)}`)}if(n){this.manager.updateBookStyle();return}if(this.dragState>0&&this.pan.letItGo){this.pan.endX=t.X;const g=this.manager.currentSlide*(this.manager.width/this.manager.perPage),u=this.pan.endX-this.pan.startX,m=this.manager.rtl?g+u:g-u;cancelAnimationFrame(this.moveFrame),this.moveFrame=requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.manager.spineElement.style.transform=`translate3d(${(this.manager.rtl?1:-1)*m}px, 0, 0)`})})}}dblclickHandler(A){clearTimeout(this.dtimer),this.pdblclick=!0,this.dtimer=window.setTimeout(()=>this.pdblclick=!1,200),!this.disableDblClick&&this.isScaled&&(this.scale=1)}get isScaled(){return this.scale>1}addTouch(A){A.touches=[{pageX:A.pageX,pageY:A.pageY}]}mousedownHandler(A){this.isScaled&&(this.addTouch(A),this.touchstartHandler(A))}mouseupHandler(A){this.isScaled&&this.touchendHandler(A)}mousemoveHandler(A){this.isScaled&&A.buttons>0&&(A.preventDefault(),this.addTouch(A),this.touchmoveHandler(A))}updateAfterDrag(){const A=(this.manager.rtl?-1:1)*(this.pan.endX-this.pan.startX),t=Math.abs(A);A>0&&t>this.manager.threshold&&this.manager.slength>this.manager.perPage?this.manager.listener("no_less",void 0):A<0&&t>this.manager.threshold&&this.manager.slength>this.manager.perPage&&this.manager.listener("no_more",void 0),this.manager.slideToCurrent(!0,!0)}}class Ce{constructor(A){this.shift=!0,this.spreads=[],this.nLandscape=0,this.index(A),this.testShift(A),console.log(`Indexed ${this.spreads.length} spreads for ${A.readingOrder.items.length} items`)}index(A,t=!1){this.nLandscape=0,A.readingOrder.items.forEach((e,n)=>{var s,o,a,h,c;t||(A.readingOrder.items[n]=e.addProperties({number:n+1,isImage:((s=e.type)==null?void 0:s.indexOf("image/"))===0}));const r=((o=e.properties)==null?void 0:o.getOrientation())===X.landscape;(!((a=e.properties)!=null&&a.getPage())||t)&&(e.properties=(h=e.properties)==null?void 0:h.add({page:r?"center":((this.shift?0:1)+n-this.nLandscape)%2?A.metadata.readingProgression===F.rtl?"right":"left":A.metadata.readingProgression===F.rtl?"left":"right"})),(r||(c=e.properties)!=null&&c.otherProperties.addBlank)&&this.nLandscape++}),t&&(this.spreads=[]),this.buildSpreads(A.readingOrder)}testShift(A){let t=!1;this.spreads.forEach((e,n)=>{var o,a,h,c,l;if(e.length>1)return;const r=e[0],s=(o=r.properties)==null?void 0:o.getOrientation();n===0&&(s===X.landscape||s!==X.portrait&&((r.width||0)>(r.height||0)||((a=r.properties)==null?void 0:a.getSpread())===uA.both))&&(this.shift=!1),t&&((h=r.properties)==null?void 0:h.getPage())===D.center&&this.spreads[n-1][0].addProperties({addBlank:!0}),s===X.portrait&&((c=r.properties)==null?void 0:c.getPage())!=="center"&&((l=r.properties)==null?void 0:l.otherProperties.number)>1?t=!0:t=!1}),this.shift||this.index(A,!0)}buildSpreads(A){let t=[];A.items.forEach((e,n)=>{var r;!n&&this.shift?this.spreads.push([e]):((r=e.properties)==null?void 0:r.getPage())===D.center?(t.length>0&&this.spreads.push(t),this.spreads.push([e]),t=[]):t.length>=2?(this.spreads.push(t),t=[e]):t.push(e)}),t.length>0&&this.spreads.push(t)}currentSpread(A,t){return this.spreads[Math.min(Math.floor(A/t),this.spreads.length-1)]}findByLink(A){return this.spreads.find(t=>t.includes(A))||void 0}}const ze=8,Ne=5,gn=300,dn=15e3,Mn=250,un=150,mn=500;class Te{constructor(A,t,e){var n;if(this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.delayedShow=new Map,this.delayedTimeout=new Map,this.previousFrames=[],this.width=0,this.height=0,this.transform="",this.currentSlide=0,this.spread=!0,this.orientationInternal=-1,this.container=A,this.positions=t,this.pub=e,this.spreadPresentation=((n=e.metadata.getPresentation())==null?void 0:n.spread)||uA.auto,this.pub.metadata.effectiveReadingProgression!==F.rtl&&this.pub.metadata.effectiveReadingProgression!==F.ltr)throw Error("Unsupported reading progression for EPUB");this.spreader=new Ce(this.pub),this.containerHeightCached=A.clientHeight,this.resizeBoundHandler=this.nativeResizeHandler.bind(this),this.ownerWindow.addEventListener("resize",this.resizeBoundHandler),this.ownerWindow.addEventListener("orientationchange",this.resizeBoundHandler),this.bookElement=document.createElement("div"),this.bookElement.ariaLabel="Book",this.bookElement.tabIndex=-1,this.updateBookStyle(!0),this.spineElement=document.createElement("div"),this.spineElement.ariaLabel="Spine",this.bookElement.appendChild(this.spineElement),this.container.appendChild(this.bookElement),this.updateSpineStyle(!0),this.peripherals=new Ye(this),this.pub.readingOrder.items.forEach(r=>{var o,a;const s=new we(this.peripherals,this.pub.metadata.effectiveReadingProgression,r.href);this.spineElement.appendChild(s.element),this.pool.set(r.href,s),s.width=100/this.length*(((o=r.properties)==null?void 0:o.getOrientation())===X.landscape||(a=r.properties)!=null&&a.otherProperties.addBlank?this.perPage:1),s.height=this.height})}set listener(A){this._listener=A}get listener(){return this._listener}get doNotDisturb(){return this.peripherals.pan.touchID>0}nativeResizeHandler(A){this.resizeHandler(!0)}resizeHandler(A=!0,t=!0){this.currentSlide+this.perPage>this.length&&(this.currentSlide=this.length<=this.perPage?0:this.length-1),this.containerHeightCached=this.container.clientHeight,this.orientationInternal=-1,this.updateSpineStyle(!0),A&&(this.currentSlide=this.reAlign(),this.slideToCurrent(!t,t)),clearTimeout(this.resizeTimeout),this.resizeTimeout=window.setTimeout(()=>{this.pool.forEach((e,n)=>{var a,h;let r=this.pub.readingOrder.items.findIndex(c=>c.href===n);const s=this.pub.readingOrder.items[r];if(e.width=100/this.length*(((a=s.properties)==null?void 0:a.getOrientation())===X.landscape||(h=s.properties)!=null&&h.otherProperties.addBlank?this.perPage:1),e.height=this.height,!e.loaded)return;const o=this.spreader.findByLink(s);e.update(this.spreadPosition(o,s))})},Mn)}updateDimensions(){this.width=this.bookElement.clientWidth,this.height=this.bookElement.clientHeight}get rtl(){return this.pub.metadata.effectiveReadingProgression===F.rtl}get single(){return!this.spread||this.portrait}get perPage(){return this.spread&&!this.portrait?2:1}get threshold(){return 50}get portrait(){return this.spreadPresentation===uA.none?!0:(this.orientationInternal===-1&&(this.orientationInternal=this.containerHeightCached>this.container.clientWidth?1:0),this.orientationInternal===1)}updateSpineStyle(A,t=!0){let e="0";this.updateDimensions(),this.perPage>1&&(e=`${this.width/2}px`);const n={transition:A?`all ${t?un:mn}ms ease-out`:"all 0ms ease-out",marginRight:this.rtl?e:"0",marginLeft:this.rtl?"0":e,width:`${this.width/this.perPage*this.length}px`,transform:this.transform,contain:"content"};Object.assign(this.spineElement.style,n)}updateBookStyle(A=!1){var t,e;if(A){const n={overflow:"hidden",direction:this.pub.metadata.effectiveReadingProgression,cursor:"",height:"100%",width:"100%",position:"relative",outline:"none",transition:(t=this.peripherals)!=null&&t.dragState?"none":"transform .15s ease-in-out",touchAction:"none"};Object.assign(this.bookElement.style,n)}this.bookElement.style.transform=`scale(${((e=this.peripherals)==null?void 0:e.scale)||1})`+(this.peripherals?` translate3d(${this.peripherals.pan.translateX}px, ${this.peripherals.pan.translateY}px, 0px)`:"")}goTo(A){if(this.slength<=this.perPage)return;A=this.reAlign(A);const t=this.currentSlide;this.currentSlide=Math.min(Math.max(A,0),this.length-1),t!==this.currentSlide&&this.slideToCurrent(!1)}onChange(){this.peripherals.scale=1,this.updateBookStyle()}get offset(){return(this.rtl?1:-1)*this.currentSlide*(this.width/this.perPage)}get length(){if(this.single)return this.slength;const A=this.slength+this.nLandscape;return this.shift&&A%2===0?A+1:A}get slength(){return this.pub.readingOrder.items.length||0}get shift(){return this.spreader.shift}get nLandscape(){return this.spreader.nLandscape}setPerPage(A){A===0?this.spread=!0:A===1?this.spread=!1:this.spread=!0,requestAnimationFrame(()=>this.resizeHandler(!0))}slideToCurrent(A,t=!0){if(this.updateDimensions(),A)requestAnimationFrame(()=>{requestAnimationFrame(()=>{const e=`translate3d(${this.offset}px, 0, 0)`;this.spineElement.style.transform!==e&&(this.transform=e,this.updateSpineStyle(!0,t),this.deselect())})});else{const e=`translate3d(${this.offset}px, 0, 0)`;if(this.spineElement.style.transform===e)return;this.transform=e,this.updateSpineStyle(!1),this.deselect()}}bounce(A=!1){requestAnimationFrame(()=>{this.transform=`translate3d(${this.offset+50*(A?1:-1)}px, 0, 0)`,this.updateSpineStyle(!0,!0),setTimeout(()=>{this.transform=`translate3d(${this.offset}px, 0, 0)`,this.updateSpineStyle(!0,!0)},100)})}next(A=1){if(this.slength<=this.perPage)return!1;const t=this.currentSlide;return this.currentSlide=Math.min(this.currentSlide+A,this.length-1),this.perPage>1&&this.currentSlide%2&&this.currentSlide--,this.currentSlide===t&&(this.currentSlide+1,this.length),t!==this.currentSlide?(this.slideToCurrent(!0),this.onChange(),!0):(this.bounce(this.rtl),!1)}prev(A=1){if(this.slength<=this.perPage)return!1;const t=this.currentSlide;return this.currentSlide=Math.max(this.currentSlide-A,0),this.perPage>1&&this.currentSlide%2&&this.currentSlide++,t!==this.currentSlide?(this.slideToCurrent(!0),this.onChange(),!0):(this.bounce(!this.rtl),!1)}get ownerWindow(){return this.container.ownerDocument.defaultView||window}async destroy(){this.ownerWindow.removeEventListener("resize",this.resizeBoundHandler),this.ownerWindow.removeEventListener("orientationchange",this.resizeBoundHandler);let A=this.inprogress.values(),t=A.next();const e=[];for(;t.value;)e.push(t.value),t=A.next();e.length>0&&await Promise.allSettled(e),this.inprogress.clear();let n=this.pool.values(),r=n.next();for(;r.value;)await r.value.destroy(),r=n.next();this.pool.clear(),this.blobs.forEach(s=>URL.revokeObjectURL(s)),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}makeSpread(A){return this.perPage<2?[this.pub.readingOrder.items[A]]:this.spreader.currentSpread(A,this.perPage)}reAlign(A=this.currentSlide){return A%2&&!this.single&&A++,A}spreadPosition(A,t){return this.perPage<2||A.length<2?D.center:t.href===A[0].href?this.rtl?D.right:D.left:this.rtl?D.left:D.right}async waitForItem(A){if(this.inprogress.has(A)&&await this.inprogress.get(A),this.delayedShow.has(A)){const t=this.delayedTimeout.get(A);t>0?clearTimeout(t):await this.delayedShow.get(A),this.delayedTimeout.set(A,0),this.delayedShow.delete(A)}}async cancelShowing(A){if(this.delayedShow.has(A)){const t=this.delayedTimeout.get(A);t>0&&clearTimeout(t),this.delayedShow.delete(A)}}async update(A,t,e,n=!1){let r=this.pub.readingOrder.items.findIndex(a=>a.href===t.href);if(r<0)throw Error("Href not found in reading order");this.currentSlide!==r&&(this.currentSlide=this.reAlign(r),this.slideToCurrent(!0));const s=this.makeSpread(this.currentSlide);this.perPage>1&&r++;for(const a of s)await this.waitForItem(a.href);const o=new Promise(async(a,h)=>{const c=[],l=[];this.positions.forEach((m,B)=>{(B>r+ze||B<r-ze)&&(c.includes(m.href)||c.push(m.href)),B<r+Ne&&B>r-Ne&&(l.includes(m.href)||l.push(m.href))}),c.forEach(async m=>{var B;l.includes(m)||this.pool.has(m)&&(this.cancelShowing(m),await((B=this.pool.get(m))==null?void 0:B.unload()))}),this.currentBaseURL!==void 0&&A.baseURL!==this.currentBaseURL&&(this.blobs.forEach(m=>URL.revokeObjectURL(m)),this.blobs.clear()),this.currentBaseURL=A.baseURL;const g=async m=>{const B=A.readingOrder.findIndexWithHref(m),f=A.readingOrder.items[B];if(f){if(!this.blobs.has(m)){const p=await new Bt(A,this.currentBaseURL||"",f).build(!0);this.blobs.set(m,p)}this.delayedShow.has(m)||this.delayedShow.set(m,new Promise((E,p)=>{let I=!1;const w=window.setTimeout(async()=>{this.delayedTimeout.set(m,0);const Y=this.makeSpread(this.reAlign(B)),oA=this.spreadPosition(Y,f),_=this.pool.get(m);await _.load(e,this.blobs.get(m)),this.peripherals.isScaled||await _.show(oA),this.delayedShow.delete(m),I=!0,E()},gn);setTimeout(()=>{!I&&this.delayedShow.has(m)&&p(`Offscreen load timeout: ${m}`)},dn),this.delayedTimeout.set(m,w)}))}};try{await Promise.all(l.map(m=>g(m)))}catch(m){h(m)}const u=[];for(const m of s){const B=this.pool.get(m.href),f=this.blobs.get(m.href);f&&(this.cancelShowing(m.href),await B.load(e,f),await B.show(this.spreadPosition(s,m)),this.previousFrames.push(B),await B.activate(),u.push(B))}for(;this.previousFrames.length>0;){const m=this.previousFrames.shift();m&&!u.includes(m)&&await m.unfocus()}this.previousFrames=u,a()});for(const a of s)this.inprogress.set(a.href,o);await o;for(const a of s)this.inprogress.delete(a.href)}get currentFrames(){if(this.perPage<2){const t=this.pub.readingOrder.items[this.currentSlide];return[this.pool.get(t.href)]}return this.spreader.currentSpread(this.currentSlide,this.perPage).map(t=>this.pool.get(t.href))}get currentBounds(){const A={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(t=>{if(!t)return;const e=t.realSize;A.x=Math.min(A.x,e.x),A.y=Math.min(A.y,e.y),A.width+=e.width,A.height=Math.max(A.height,e.height),A.top=Math.min(A.top,e.top),A.right=Math.min(A.right,e.right),A.bottom=Math.min(A.bottom,e.bottom),A.left=Math.min(A.left,e.left)}),A}get currentNumbers(){var t,e,n,r;if(this.perPage<2)return[(t=this.pub.readingOrder.items[this.currentSlide].properties)==null?void 0:t.otherProperties.number];const A=this.spreader.currentSpread(this.currentSlide,this.perPage);return A.length>1?[(e=A[0].properties)==null?void 0:e.otherProperties.number,(n=A[A.length-1].properties)==null?void 0:n.otherProperties.number]:[(r=A[0].properties)==null?void 0:r.otherProperties.number]}deselect(){var A;(A=this.currentFrames)==null||A.forEach(t=>t==null?void 0:t.deselect())}}function b(i){if(typeof i!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function xe(i,A){for(var t="",e=0,n=-1,r=0,s,o=0;o<=i.length;++o){if(o<i.length)s=i.charCodeAt(o);else{if(s===47)break;s=47}if(s===47){if(!(n===o-1||r===1))if(n!==o-1&&r===2){if(t.length<2||e!==2||t.charCodeAt(t.length-1)!==46||t.charCodeAt(t.length-2)!==46){if(t.length>2){var a=t.lastIndexOf("/");if(a!==t.length-1){a===-1?(t="",e=0):(t=t.slice(0,a),e=t.length-1-t.lastIndexOf("/")),n=o,r=0;continue}}else if(t.length===2||t.length===1){t="",e=0,n=o,r=0;continue}}A&&(t.length>0?t+="/..":t="..",e=2)}else t.length>0?t+="/"+i.slice(n+1,o):t=i.slice(n+1,o),e=o-n-1;n=o,r=0}else s===46&&r!==-1?++r:r=-1}return t}function Bn(i,A){var t=A.dir||A.root,e=A.base||(A.name||"")+(A.ext||"");return t?t===A.root?t+e:t+i+e:e}var sA={resolve:function(){for(var A="",t=!1,e,n=arguments.length-1;n>=-1&&!t;n--){var r;n>=0?r=arguments[n]:(e===void 0&&(e=process.cwd()),r=e),b(r),r.length!==0&&(A=r+"/"+A,t=r.charCodeAt(0)===47)}return A=xe(A,!t),t?A.length>0?"/"+A:"/":A.length>0?A:"."},normalize:function(A){if(b(A),A.length===0)return".";var t=A.charCodeAt(0)===47,e=A.charCodeAt(A.length-1)===47;return A=xe(A,!t),A.length===0&&!t&&(A="."),A.length>0&&e&&(A+="/"),t?"/"+A:A},isAbsolute:function(A){return b(A),A.length>0&&A.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var A,t=0;t<arguments.length;++t){var e=arguments[t];b(e),e.length>0&&(A===void 0?A=e:A+="/"+e)}return A===void 0?".":sA.normalize(A)},relative:function(A,t){if(b(A),b(t),A===t||(A=sA.resolve(A),t=sA.resolve(t),A===t))return"";for(var e=1;e<A.length&&A.charCodeAt(e)===47;++e);for(var n=A.length,r=n-e,s=1;s<t.length&&t.charCodeAt(s)===47;++s);for(var o=t.length,a=o-s,h=r<a?r:a,c=-1,l=0;l<=h;++l){if(l===h){if(a>h){if(t.charCodeAt(s+l)===47)return t.slice(s+l+1);if(l===0)return t.slice(s+l)}else r>h&&(A.charCodeAt(e+l)===47?c=l:l===0&&(c=0));break}var g=A.charCodeAt(e+l),u=t.charCodeAt(s+l);if(g!==u)break;g===47&&(c=l)}var m="";for(l=e+c+1;l<=n;++l)(l===n||A.charCodeAt(l)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+t.slice(s+c):(s+=c,t.charCodeAt(s)===47&&++s,t.slice(s))},_makeLong:function(A){return A},dirname:function(A){if(b(A),A.length===0)return".";for(var t=A.charCodeAt(0),e=t===47,n=-1,r=!0,s=A.length-1;s>=1;--s)if(t=A.charCodeAt(s),t===47){if(!r){n=s;break}}else r=!1;return n===-1?e?"/":".":e&&n===1?"//":A.slice(0,n)},basename:function(A,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');b(A);var e=0,n=-1,r=!0,s;if(t!==void 0&&t.length>0&&t.length<=A.length){if(t.length===A.length&&t===A)return"";var o=t.length-1,a=-1;for(s=A.length-1;s>=0;--s){var h=A.charCodeAt(s);if(h===47){if(!r){e=s+1;break}}else a===-1&&(r=!1,a=s+1),o>=0&&(h===t.charCodeAt(o)?--o===-1&&(n=s):(o=-1,n=a))}return e===n?n=a:n===-1&&(n=A.length),A.slice(e,n)}else{for(s=A.length-1;s>=0;--s)if(A.charCodeAt(s)===47){if(!r){e=s+1;break}}else n===-1&&(r=!1,n=s+1);return n===-1?"":A.slice(e,n)}},extname:function(A){b(A);for(var t=-1,e=0,n=-1,r=!0,s=0,o=A.length-1;o>=0;--o){var a=A.charCodeAt(o);if(a===47){if(!r){e=o+1;break}continue}n===-1&&(r=!1,n=o+1),a===46?t===-1?t=o:s!==1&&(s=1):t!==-1&&(s=-1)}return t===-1||n===-1||s===0||s===1&&t===n-1&&t===e+1?"":A.slice(t,n)},format:function(A){if(A===null||typeof A!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof A);return Bn("/",A)},parse:function(A){b(A);var t={root:"",dir:"",base:"",ext:"",name:""};if(A.length===0)return t;var e=A.charCodeAt(0),n=e===47,r;n?(t.root="/",r=1):r=0;for(var s=-1,o=0,a=-1,h=!0,c=A.length-1,l=0;c>=r;--c){if(e=A.charCodeAt(c),e===47){if(!h){o=c+1;break}continue}a===-1&&(h=!1,a=c+1),e===46?s===-1?s=c:l!==1&&(l=1):s!==-1&&(l=-1)}return s===-1||a===-1||l===0||l===1&&s===a-1&&s===o+1?a!==-1&&(o===0&&n?t.base=t.name=A.slice(1,a):t.base=t.name=A.slice(o,a)):(o===0&&n?(t.name=A.slice(1,s),t.base=A.slice(1,a)):(t.name=A.slice(o,s),t.base=A.slice(o,a)),t.ext=A.slice(s,a)),o>0?t.dir=A.slice(0,o-1):n&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null};sA.posix=sA;var je=sA;const En=i=>({frameLoaded:i.frameLoaded||(()=>{}),positionChanged:i.positionChanged||(()=>{}),tap:i.tap||(()=>!1),click:i.click||(()=>!1),zoom:i.zoom||(()=>{}),miscPointer:i.miscPointer||(()=>{}),customEvent:i.customEvent||(()=>{}),handleLocator:i.handleLocator||(()=>!1),textSelected:i.textSelected||(()=>{})});class nt extends ut{constructor(A,t,e,n=[],r=void 0){super(),this.pub=t,this.layout=nt.determineLayout(t),this.currentProgression=t.metadata.effectiveReadingProgression,this.container=A,this.listeners=En(e),this.currentLocation=r,n.length&&(this.positions=n)}static determineLayout(A){var e;const t=A.metadata.getPresentation();return(t==null?void 0:t.layout)==C.fixed||A.metadata.otherMetadata&&"http://openmangaformat.org/schema/1.0#version"in A.metadata.otherMetadata||((e=A.metadata.otherMetadata)==null?void 0:e.conformsTo)==="https://readium.org/webpub-manifest/profiles/divina"?C.fixed:C.reflowable}async load(){var A;(A=this.positions)!=null&&A.length||(this.positions=await this.pub.positionsFromManifest()),this.layout===C.fixed?(this.framePool=new Te(this.container,this.positions,this.pub),this.framePool.listener=(t,e)=>{this.eventListener(t,e)}):this.framePool=new pe(this.container,this.positions),this.currentLocation===void 0&&(this.currentLocation=this.positions[0]),await this.apply()}get _cframes(){return this.framePool.currentFrames}get pool(){return this.framePool}eventListener(A,t){var e,n,r,s,o,a;switch(A){case"_pong":this.listeners.frameLoaded(this._cframes[0].iframe.contentWindow),this.listeners.positionChanged(this.currentLocation);break;case"first_visible_locator":const h=SA.deserialize(t);if(!h)break;this.currentLocation=new SA({href:this.currentLocation.href,type:this.currentLocation.type,title:this.currentLocation.title,locations:h==null?void 0:h.locations,text:h==null?void 0:h.text}),this.listeners.positionChanged(this.currentLocation);break;case"text_selected":this.listeners.textSelected(t);break;case"click":case"tap":const c=t;if(c.interactiveElement){const l=new DOMParser().parseFromString(c.interactiveElement,"text/html").body.children[0];if(l.nodeType===l.ELEMENT_NODE&&l.nodeName==="A"&&l.hasAttribute("href")){const g=(e=l.attributes.getNamedItem("href"))==null?void 0:e.value;if(g.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[g.substring(1)]}),!1,()=>{});else if(g.startsWith("http://")||g.startsWith("https://")||g.startsWith("mailto:")||g.startsWith("tel:"))this.listeners.handleLocator(new J({href:g}).locator);else try{this.goLink(new J({href:je.join(je.dirname(this.currentLocation.href),g)}),!1,()=>{})}catch(u){console.warn(`Couldn't go to link for ${g}: ${u}`),this.listeners.handleLocator(new J({href:g}).locator)}}else console.log("Clicked on",l)}else{if(this.layout===C.fixed&&this.framePool.doNotDisturb&&(c.doNotDisturb=!0),this.layout===C.fixed&&(this.currentProgression===F.rtl||this.currentProgression===F.ltr)&&this.framePool.currentFrames.length>1){const u=this.framePool.currentFrames;c.targetFrameSrc===((n=u[this.currentProgression===F.rtl?0:1])==null?void 0:n.source)&&(c.x+=(((s=(r=u[this.currentProgression===F.rtl?1:0])==null?void 0:r.iframe.contentWindow)==null?void 0:s.innerWidth)??0)*window.devicePixelRatio)}if(A==="click"?this.listeners.click(c):this.listeners.tap(c))break;if(this.currentProgression===F.ttb||this.currentProgression===F.btt)return;const g=(this._cframes.length===2?this._cframes[0].window.innerWidth+this._cframes[1].window.innerWidth:this._cframes[0].window.innerWidth)*window.devicePixelRatio/4;c.x>=g&&c.x<=g*3&&this.listeners.miscPointer(1),c.x<g?this.goLeft(!1,()=>{}):c.x>g*3&&this.goRight(!1,()=>{})}break;case"tap_more":this.listeners.miscPointer(t);break;case"no_more":this.changeResource(1);break;case"no_less":this.changeResource(-1);break;case"swipe":break;case"zoom":this.listeners.zoom(t);break;case"progress":this.syncLocation(t);break;case"log":console.log((a=(o=this._cframes[0])==null?void 0:o.source)==null?void 0:a.split("/")[3],...t);break;default:this.listeners.customEvent(A,t);break}}determineModules(){let A=Array.from(tt.keys());return this.layout===C.fixed?A.filter(t=>on.includes(t)):(A=A.filter(t=>an.includes(t)),this.readingProgression===F.ttb||this.readingProgression===F.btt?A=A.filter(t=>t!=="column_snapper"):A=A.filter(t=>t!=="scroll_snapper"),A)}attachListener(){const A=this._cframes.filter(t=>!!t);if(A.length===0)throw Error("no cframe to attach listener to");A.forEach(t=>{t.msg&&(t.msg.listener=(e,n)=>{this.eventListener(e,n)})})}async apply(){if(await this.framePool.update(this.pub,this.currentLocator,this.determineModules()),this.attachListener(),this.pub.readingOrder.findIndexWithHref(this.currentLocation.href)<0)throw Error("Link for "+this.currentLocation.href+" not found!")}async destroy(){var A;await((A=this.framePool)==null?void 0:A.destroy())}async changeResource(A){var n,r;if(A===0)return!1;if(this.layout===C.fixed){const s=this.framePool,o=s.currentNumbers[0];if(A===1){if(!s.next(s.perPage))return!1}else if(A===-1){if(!s.prev(s.perPage))return!1}else throw Error("Invalid relative value for FXL");const a=s.currentNumbers[0];if(o>a){for(let h=this.positions.length-1;h>=0;h--)if(this.positions[h].href===this.pub.readingOrder.items[a-1].href){this.currentLocation=this.positions[h].copyWithLocations({progression:.999999999999});break}}else if(o<a){for(let h=0;h<this.positions.length;h++)if(this.positions[h].href===this.pub.readingOrder.items[a-1].href){this.currentLocation=this.positions[h];break}}return await this.apply(),!0}const t=this.pub.readingOrder.findIndexWithHref(this.currentLocation.href),e=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,t+A));if(e===t)return(r=(n=this._cframes[0])==null?void 0:n.msg)==null||r.send("shake",void 0,async s=>{}),!1;if(t>e){for(let s=this.positions.length-1;s>=0;s--)if(this.positions[s].href===this.pub.readingOrder.items[e].href){this.currentLocation=this.positions[s].copyWithLocations({progression:.999999999999});break}}else for(let s=0;s<this.positions.length;s++)if(this.positions[s].href===this.pub.readingOrder.items[e].href){this.currentLocation=this.positions[s];break}return await this.apply(),!0}findLastPositionInProgressionRange(A,t){const e=A.findLastIndex(n=>{const r=n.locations.progression;return!!(r&&r>Math.min(...t)&&r<=Math.max(...t))});return e!==-1?A[e]:void 0}findNearestPositions(A){const t=this.positions.filter(r=>r.href===this.currentLocation.href);let e=this.currentLocation,n;return t.some((r,s)=>{const o=r.locations.progression??0;if(A.progress<=o){e=r;const a=t.splice(s+1,t.length),h=[A.progress,A.progress+A.reference];return n=this.findLastPositionInProgressionRange(a,h),!0}else return!1}),{first:e,last:n}}async syncLocation(A){const t=this.findNearestPositions(A);this.currentLocation=t.first.copyWithLocations({progression:A.progress}),this.lastLocationInView=t.last,this.listeners.positionChanged(this.currentLocation),await this.framePool.update(this.pub,this.currentLocation,this.determineModules())}goBackward(A,t){var e,n;this.layout===C.fixed?(this.changeResource(-1),t(!0)):(n=(e=this._cframes[0])==null?void 0:e.msg)==null||n.send("go_prev",void 0,async r=>{t(r?!0:await this.changeResource(-1))})}goForward(A,t){var e,n;this.layout===C.fixed?(this.changeResource(1),t(!0)):(n=(e=this._cframes[0])==null?void 0:e.msg)==null||n.send("go_next",void 0,async r=>{t(r?!0:await this.changeResource(1))})}get currentLocator(){return this.currentLocation}get currentPositionNumbers(){var A,t;return this.layout===C.fixed?this.framePool.currentNumbers:[((A=this.currentLocator)==null?void 0:A.locations.position)??0,...(t=this.lastLocationInView)!=null&&t.locations.position?[this.lastLocationInView.locations.position]:[]]}get readingProgression(){return this.currentProgression}async setReadingProgression(A){this.currentProgression!==A&&(this.currentProgression=A,await this.framePool.update(this.pub,this.currentLocator,this.determineModules(),!0),this.attachListener())}get publication(){return this.pub}async loadLocator(A,t){var a,h;let e=!1,n=typeof A.locations.getCssSelector=="function"&&A.locations.getCssSelector();if((a=A.text)!=null&&a.highlight?e=await new Promise((c,l)=>{var g,u;this._cframes[0].msg.send("go_text",n?[(g=A.text)==null?void 0:g.serialize(),n]:(u=A.text)==null?void 0:u.serialize(),m=>c(m))}):n&&(e=await new Promise((c,l)=>{this._cframes[0].msg.send("go_text",["",n],g=>c(g))})),e){t(e);return}const r=typeof A.locations.htmlId=="function"&&A.locations.htmlId();if(r&&(e=await new Promise((c,l)=>{this._cframes[0].msg.send("go_id",r,g=>c(g))})),e){t(e);return}const s=(h=A==null?void 0:A.locations)==null?void 0:h.progression;s&&s>0?e=await new Promise((c,l)=>{this._cframes[0].msg.send("go_progression",s,g=>c(g))}):e=!0,t(e)}go(A,t,e){const n=A.href.split("#")[0];let r=this.pub.readingOrder.findWithHref(n);if(!r)return e(this.listeners.handleLocator(A));this.currentLocation=this.positions.find(s=>s.href===r.href),this.apply().then(()=>this.loadLocator(A,s=>e(s))).then(()=>{this.attachListener()})}goLink(A,t,e){return this.go(A.locator,t,e)}}class fn{constructor(A){var t;this.sourceNode=null,this.listeners={},this.isMutedValue=!1,this.isPlayingValue=!1,this.isPausedValue=!1,this.isLoadingValue=!1,this.isLoadedValue=!1,this.isEndedValue=!1,this.playback=A.playback,this.audioContext=A.audioContext,this.gainNode=(t=this.audioContext)==null?void 0:t.createGain(),this.setVolume(this.playback.state.volume),this.mediaElement=document.createElement("audio"),this.mediaElement.crossOrigin="use-credentials",this.mediaElement.addEventListener("canplaythrough",this.onCanPlayThrough.bind(this)),this.mediaElement.addEventListener("timeupdate",this.onTimeUpdate.bind(this)),this.mediaElement.addEventListener("error",this.onError.bind(this)),this.mediaElement.addEventListener("ended",this.onEnded.bind(this)),this.mediaElement.currentTime=this.playback.state.currentTime}on(A,t){this.listeners[A]||(this.listeners[A]=[]),this.listeners[A].push(t)}off(A,t){this.listeners[A]&&(this.listeners[A]=this.listeners[A].filter(e=>e!==t))}loadAudio(A){this.isLoadingValue=!0,this.mediaElement.src=A,this.mediaElement.load(),this.sourceNode||(this.sourceNode=new MediaElementAudioSourceNode(this.audioContext,{mediaElement:this.mediaElement}),this.sourceNode.connect(this.gainNode),this.gainNode.connect(this.audioContext.destination))}async ensureAudioContextRunning(){this.audioContext.state==="suspended"&&await this.audioContext.resume()}onTimeUpdate(){this.emit("timeupdate",this.mediaElement.currentTime)}onCanPlayThrough(){this.isLoadingValue=!1,this.isLoadedValue=!0,this.emit("canplaythrough",null)}onError(){console.error("Error loading media element"),this.emit("error",this.mediaElement.error)}onEnded(){this.isPlayingValue=!1,this.isPausedValue=!1,this.isEndedValue=!0,this.emit("ended",null)}emit(A,t){this.listeners[A]&&this.listeners[A].forEach(e=>e(t))}async playLocator(A,t){}async play(){if(await this.ensureAudioContextRunning(),this.isPlayingValue){this.stop(),console.error("Audio is already playing");return}try{await this.mediaElement.play(),this.isPlayingValue=!0,this.isPausedValue=!1}catch(A){console.error("error trying to play media element",A)}}pause(){this.mediaElement.pause(),this.isPlayingValue=!1,this.isPausedValue=!0}stop(){this.mediaElement.pause(),this.mediaElement.currentTime=0,this.isPlayingValue=!1,this.isPausedValue=!1}setVolume(A){if(A<0){this.gainNode.gain.value=0,this.isMutedValue=!0;return}if(A>1){this.setVolume(A/100);return}this.gainNode.gain.value=A}skip(A){if(!this.mediaElement){console.error("Audio not loaded");return}const t=this.mediaElement.currentTime+A;t<0?this.mediaElement.currentTime=0:t>this.mediaElement.duration?this.mediaElement.currentTime=this.mediaElement.duration:this.mediaElement.currentTime=t}currentTime(){return this.mediaElement.currentTime}duration(){return this.mediaElement.duration}isPlaying(){return this.isPlayingValue}isPaused(){return this.isPausedValue}isStopped(){return!1}isLoading(){return this.isLoadingValue}isLoaded(){return this.isLoadedValue}isEnded(){return this.isEndedValue}isMuted(){return this.isMutedValue}}Q.EpubNavigator=nt,Q.FXLCoordinator=ye,Q.FXLFrameManager=we,Q.FXLFramePoolManager=Te,Q.FXLPeripherals=Ye,Q.FXLSpreader=Ce,Q.FrameComms=et,Q.FrameManager=Ee,Q.FramePoolManager=pe,Q.HorizontalThird=Fe,Q.Navigator=Mt,Q.VerticalThird=Ue,Q.VisualNavigator=ut,Q.WebAudioEngine=fn,Q.sML=NA,Object.defineProperty(Q,Symbol.toStringTag,{value:"Module"})});
107
+ Overscroll: ${this.pan.overscrollX.toFixed(2)},${this.pan.overscrollY.toFixed(2)}`)}if(i){this.manager.updateBookStyle();return}if(this.dragState>0&&this.pan.letItGo){this.pan.endX=e.X;const g=this.manager.currentSlide*(this.manager.width/this.manager.perPage),m=this.pan.endX-this.pan.startX,M=this.manager.rtl?g+m:g-m;cancelAnimationFrame(this.moveFrame),this.moveFrame=requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.manager.spineElement.style.transform=`translate3d(${(this.manager.rtl?1:-1)*M}px, 0, 0)`})})}}dblclickHandler(t){clearTimeout(this.dtimer),this.pdblclick=!0,this.dtimer=window.setTimeout(()=>this.pdblclick=!1,200),!this.disableDblClick&&this.isScaled&&(this.scale=1)}get isScaled(){return this.scale>1}addTouch(t){t.touches=[{pageX:t.pageX,pageY:t.pageY}]}mousedownHandler(t){this.isScaled&&(this.addTouch(t),this.touchstartHandler(t))}mouseupHandler(t){this.isScaled&&this.touchendHandler(t)}mousemoveHandler(t){this.isScaled&&t.buttons>0&&(t.preventDefault(),this.addTouch(t),this.touchmoveHandler(t))}updateAfterDrag(){const t=(this.manager.rtl?-1:1)*(this.pan.endX-this.pan.startX),e=Math.abs(t);t>0&&e>this.manager.threshold&&this.manager.slength>this.manager.perPage?this.manager.listener("no_less",void 0):t<0&&e>this.manager.threshold&&this.manager.slength>this.manager.perPage&&this.manager.listener("no_more",void 0),this.manager.slideToCurrent(!0,!0)}}class TA{constructor(t){this.shift=!0,this.spreads=[],this.nLandscape=0,this.index(t),this.testShift(t),console.log(`Indexed ${this.spreads.length} spreads for ${t.readingOrder.items.length} items`)}index(t,e=!1){this.nLandscape=0,t.readingOrder.items.forEach((A,i)=>{var s,o,a,l,h;e||(t.readingOrder.items[i]=A.addProperties({number:i+1,isImage:((s=A.type)==null?void 0:s.indexOf("image/"))===0}));const r=((o=A.properties)==null?void 0:o.getOrientation())===nt.landscape;(!((a=A.properties)!=null&&a.getPage())||e)&&(A.properties=(l=A.properties)==null?void 0:l.add({page:r?"center":((this.shift?0:1)+i-this.nLandscape)%2?t.metadata.readingProgression===w.rtl?"right":"left":t.metadata.readingProgression===w.rtl?"left":"right"})),(r||(h=A.properties)!=null&&h.otherProperties.addBlank)&&this.nLandscape++}),e&&(this.spreads=[]),this.buildSpreads(t.readingOrder)}testShift(t){let e=!1;this.spreads.forEach((A,i)=>{var o,a,l,h,c;if(A.length>1)return;const r=A[0],s=(o=r.properties)==null?void 0:o.getOrientation();i===0&&(s===nt.landscape||s!==nt.portrait&&((r.width||0)>(r.height||0)||((a=r.properties)==null?void 0:a.getSpread())===zt.both))&&(this.shift=!1),e&&((l=r.properties)==null?void 0:l.getPage())===O.center&&this.spreads[i-1][0].addProperties({addBlank:!0}),s===nt.portrait&&((h=r.properties)==null?void 0:h.getPage())!=="center"&&((c=r.properties)==null?void 0:c.otherProperties.number)>1?e=!0:e=!1}),this.shift||this.index(t,!0)}buildSpreads(t){let e=[];t.items.forEach((A,i)=>{var r;!i&&this.shift?this.spreads.push([A]):((r=A.properties)==null?void 0:r.getPage())===O.center?(e.length>0&&this.spreads.push(e),this.spreads.push([A]),e=[]):e.length>=2?(this.spreads.push(e),e=[A]):e.push(A)}),e.length>0&&this.spreads.push(e)}currentSpread(t,e){return this.spreads[Math.min(Math.floor(t/e),this.spreads.length-1)]}findByLink(t){return this.spreads.find(e=>e.includes(t))||void 0}}const jA=8,VA=5,Mn=300,fn=15e3,pn=250,Bn=150,En=500;class PA{constructor(t,e,A){var i;if(this.pool=new Map,this.blobs=new Map,this.inprogress=new Map,this.delayedShow=new Map,this.delayedTimeout=new Map,this.previousFrames=[],this.width=0,this.height=0,this.transform="",this.currentSlide=0,this.spread=!0,this.orientationInternal=-1,this.container=t,this.positions=e,this.pub=A,this.spreadPresentation=((i=A.metadata.getPresentation())==null?void 0:i.spread)||zt.auto,this.pub.metadata.effectiveReadingProgression!==w.rtl&&this.pub.metadata.effectiveReadingProgression!==w.ltr)throw Error("Unsupported reading progression for EPUB");this.spreader=new TA(this.pub),this.containerHeightCached=t.clientHeight,this.bookElement=document.createElement("div"),this.bookElement.ariaLabel="Book",this.bookElement.tabIndex=-1,this.updateBookStyle(!0),this.spineElement=document.createElement("div"),this.spineElement.ariaLabel="Spine",this.bookElement.appendChild(this.spineElement),this.container.appendChild(this.bookElement),this.updateSpineStyle(!0),this.peripherals=new xA(this),this.pub.readingOrder.items.forEach(r=>{var o,a;const s=new RA(this.peripherals,this.pub.metadata.effectiveReadingProgression,r.href);this.spineElement.appendChild(s.element),this.pool.set(r.href,s),s.width=100/this.length*(((o=r.properties)==null?void 0:o.getOrientation())===nt.landscape||(a=r.properties)!=null&&a.otherProperties.addBlank?this.perPage:1),s.height=this.height})}set listener(t){this._listener=t}get listener(){return this._listener}get doNotDisturb(){return this.peripherals.pan.touchID>0}resizeHandler(t=!0,e=!0){this.currentSlide+this.perPage>this.length&&(this.currentSlide=this.length<=this.perPage?0:this.length-1),this.containerHeightCached=this.container.clientHeight,this.orientationInternal=-1,this.updateSpineStyle(!0),t&&(this.currentSlide=this.reAlign(),this.slideToCurrent(!e,e)),clearTimeout(this.resizeTimeout),this.resizeTimeout=window.setTimeout(()=>{this.pool.forEach((A,i)=>{var a,l;let r=this.pub.readingOrder.items.findIndex(h=>h.href===i);const s=this.pub.readingOrder.items[r];if(A.width=100/this.length*(((a=s.properties)==null?void 0:a.getOrientation())===nt.landscape||(l=s.properties)!=null&&l.otherProperties.addBlank?this.perPage:1),A.height=this.height,!A.loaded)return;const o=this.spreader.findByLink(s);A.update(this.spreadPosition(o,s))})},pn)}updateDimensions(){this.width=this.bookElement.clientWidth,this.height=this.bookElement.clientHeight}get rtl(){return this.pub.metadata.effectiveReadingProgression===w.rtl}get single(){return!this.spread||this.portrait}get perPage(){return this.spread&&!this.portrait?2:1}get threshold(){return 50}get portrait(){return this.spreadPresentation===zt.none?!0:(this.orientationInternal===-1&&(this.orientationInternal=this.containerHeightCached>this.container.clientWidth?1:0),this.orientationInternal===1)}updateSpineStyle(t,e=!0){let A="0";this.updateDimensions(),this.perPage>1&&(A=`${this.width/2}px`);const i={transition:t?`all ${e?Bn:En}ms ease-out`:"all 0ms ease-out",marginRight:this.rtl?A:"0",marginLeft:this.rtl?"0":A,width:`${this.width/this.perPage*this.length}px`,transform:this.transform,contain:"content"};Object.assign(this.spineElement.style,i)}updateBookStyle(t=!1){var e,A;if(t){const i={overflow:"hidden",direction:this.pub.metadata.effectiveReadingProgression,cursor:"",height:"100%",width:"100%",position:"relative",outline:"none",transition:(e=this.peripherals)!=null&&e.dragState?"none":"transform .15s ease-in-out",touchAction:"none"};Object.assign(this.bookElement.style,i)}this.bookElement.style.transform=`scale(${((A=this.peripherals)==null?void 0:A.scale)||1})`+(this.peripherals?` translate3d(${this.peripherals.pan.translateX}px, ${this.peripherals.pan.translateY}px, 0px)`:"")}goTo(t){if(this.slength<=this.perPage)return;t=this.reAlign(t);const e=this.currentSlide;this.currentSlide=Math.min(Math.max(t,0),this.length-1),e!==this.currentSlide&&this.slideToCurrent(!1)}onChange(){this.peripherals.scale=1,this.updateBookStyle()}get offset(){return(this.rtl?1:-1)*this.currentSlide*(this.width/this.perPage)}get length(){if(this.single)return this.slength;const t=this.slength+this.nLandscape;return this.shift&&t%2===0?t+1:t}get slength(){return this.pub.readingOrder.items.length||0}get shift(){return this.spreader.shift}get nLandscape(){return this.spreader.nLandscape}setPerPage(t){t===null?this.spread=!0:t===1?this.spread=!1:this.spread=!0,requestAnimationFrame(()=>this.resizeHandler(!0))}slideToCurrent(t,e=!0){if(this.updateDimensions(),t)requestAnimationFrame(()=>{requestAnimationFrame(()=>{const A=`translate3d(${this.offset}px, 0, 0)`;this.spineElement.style.transform!==A&&(this.transform=A,this.updateSpineStyle(!0,e),this.deselect())})});else{const A=`translate3d(${this.offset}px, 0, 0)`;if(this.spineElement.style.transform===A)return;this.transform=A,this.updateSpineStyle(!1),this.deselect()}}bounce(t=!1){requestAnimationFrame(()=>{this.transform=`translate3d(${this.offset+50*(t?1:-1)}px, 0, 0)`,this.updateSpineStyle(!0,!0),setTimeout(()=>{this.transform=`translate3d(${this.offset}px, 0, 0)`,this.updateSpineStyle(!0,!0)},100)})}next(t=1){if(this.slength<=this.perPage)return!1;const e=this.currentSlide;return this.currentSlide=Math.min(this.currentSlide+t,this.length-1),this.perPage>1&&this.currentSlide%2&&this.currentSlide--,this.currentSlide===e&&(this.currentSlide+1,this.length),e!==this.currentSlide?(this.slideToCurrent(!0),this.onChange(),!0):(this.bounce(this.rtl),!1)}prev(t=1){if(this.slength<=this.perPage)return!1;const e=this.currentSlide;return this.currentSlide=Math.max(this.currentSlide-t,0),this.perPage>1&&this.currentSlide%2&&this.currentSlide++,e!==this.currentSlide?(this.slideToCurrent(!0),this.onChange(),!0):(this.bounce(!this.rtl),!1)}get ownerWindow(){return this.container.ownerDocument.defaultView||window}async destroy(){let t=this.inprogress.values(),e=t.next();const A=[];for(;e.value;)A.push(e.value),e=t.next();A.length>0&&await Promise.allSettled(A),this.inprogress.clear();let i=this.pool.values(),r=i.next();for(;r.value;)await r.value.destroy(),r=i.next();this.pool.clear(),this.blobs.forEach(s=>URL.revokeObjectURL(s)),this.container.childNodes.forEach(s=>{(s.nodeType===Node.ELEMENT_NODE||s.nodeType===Node.TEXT_NODE)&&s.remove()})}makeSpread(t){return this.perPage<2?[this.pub.readingOrder.items[t]]:this.spreader.currentSpread(t,this.perPage)}reAlign(t=this.currentSlide){return t%2&&!this.single&&t++,t}spreadPosition(t,e){return this.perPage<2||t.length<2?O.center:e.href===t[0].href?this.rtl?O.right:O.left:this.rtl?O.left:O.right}async waitForItem(t){if(this.inprogress.has(t)&&await this.inprogress.get(t),this.delayedShow.has(t)){const e=this.delayedTimeout.get(t);e>0?clearTimeout(e):await this.delayedShow.get(t),this.delayedTimeout.set(t,0),this.delayedShow.delete(t)}}async cancelShowing(t){if(this.delayedShow.has(t)){const e=this.delayedTimeout.get(t);e>0&&clearTimeout(e),this.delayedShow.delete(t)}}async update(t,e,A,i=!1){let r=this.pub.readingOrder.items.findIndex(a=>a.href===e.href);if(r<0)throw Error("Href not found in reading order");this.currentSlide!==r&&(this.currentSlide=this.reAlign(r),this.slideToCurrent(!0));const s=this.makeSpread(this.currentSlide);this.perPage>1&&r++;for(const a of s)await this.waitForItem(a.href);const o=new Promise(async(a,l)=>{const h=[],c=[];this.positions.forEach((M,B)=>{(B>r+jA||B<r-jA)&&(h.includes(M.href)||h.push(M.href)),B<r+VA&&B>r-VA&&(c.includes(M.href)||c.push(M.href))}),h.forEach(async M=>{var B;c.includes(M)||this.pool.has(M)&&(this.cancelShowing(M),await((B=this.pool.get(M))==null?void 0:B.unload()))}),this.currentBaseURL!==void 0&&t.baseURL!==this.currentBaseURL&&(this.blobs.forEach(M=>URL.revokeObjectURL(M)),this.blobs.clear()),this.currentBaseURL=t.baseURL;const g=async M=>{const B=t.readingOrder.findIndexWithHref(M),f=t.readingOrder.items[B];if(f){if(!this.blobs.has(M)){const Q=await new Se(t,this.currentBaseURL||"",f).build(!0);this.blobs.set(M,Q)}this.delayedShow.has(M)||this.delayedShow.set(M,new Promise((F,Q)=>{let I=!1;const U=window.setTimeout(async()=>{this.delayedTimeout.set(M,0);const v=this.makeSpread(this.reAlign(B)),kt=this.spreadPosition(v,f),Qt=this.pool.get(M);await Qt.load(A,this.blobs.get(M)),this.peripherals.isScaled||await Qt.show(kt),this.delayedShow.delete(M),I=!0,F()},Mn);setTimeout(()=>{!I&&this.delayedShow.has(M)&&Q(`Offscreen load timeout: ${M}`)},fn),this.delayedTimeout.set(M,U)}))}};try{await Promise.all(c.map(M=>g(M)))}catch(M){l(M)}const m=[];for(const M of s){const B=this.pool.get(M.href),f=this.blobs.get(M.href);f&&(this.cancelShowing(M.href),await B.load(A,f),await B.show(this.spreadPosition(s,M)),this.previousFrames.push(B),await B.activate(),m.push(B))}for(;this.previousFrames.length>0;){const M=this.previousFrames.shift();M&&!m.includes(M)&&await M.unfocus()}this.previousFrames=m,a()});for(const a of s)this.inprogress.set(a.href,o);await o;for(const a of s)this.inprogress.delete(a.href)}get currentFrames(){if(this.perPage<2){const e=this.pub.readingOrder.items[this.currentSlide];return[this.pool.get(e.href)]}return this.spreader.currentSpread(this.currentSlide,this.perPage).map(e=>this.pool.get(e.href))}get currentBounds(){const t={x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0,toJSON(){return this}};return this.currentFrames.forEach(e=>{if(!e)return;const A=e.realSize;t.x=Math.min(t.x,A.x),t.y=Math.min(t.y,A.y),t.width+=A.width,t.height=Math.max(t.height,A.height),t.top=Math.min(t.top,A.top),t.right=Math.min(t.right,A.right),t.bottom=Math.min(t.bottom,A.bottom),t.left=Math.min(t.left,A.left)}),t}get viewport(){const t={readingOrder:[],progressions:new Map,positions:null};return this.spreader.currentSpread(this.currentSlide,this.perPage).forEach(A=>{t.readingOrder.push(A.href),t.progressions.set(A.href,{start:0,end:1})}),t.positions=this.getCurrentNumbers(),t}getCurrentNumbers(){var e,A,i,r;if(this.perPage<2)return[(e=this.pub.readingOrder.items[this.currentSlide].properties)==null?void 0:e.otherProperties.number];const t=this.spreader.currentSpread(this.currentSlide,this.perPage);return t.length>1?[(A=t[0].properties)==null?void 0:A.otherProperties.number,(i=t[t.length-1].properties)==null?void 0:i.otherProperties.number]:[(r=t[0].properties)==null?void 0:r.otherProperties.number]}deselect(){var t;(t=this.currentFrames)==null||t.forEach(e=>e==null?void 0:e.deselect())}}function K(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function DA(n,t){for(var e="",A=0,i=-1,r=0,s,o=0;o<=n.length;++o){if(o<n.length)s=n.charCodeAt(o);else{if(s===47)break;s=47}if(s===47){if(!(i===o-1||r===1))if(i!==o-1&&r===2){if(e.length<2||A!==2||e.charCodeAt(e.length-1)!==46||e.charCodeAt(e.length-2)!==46){if(e.length>2){var a=e.lastIndexOf("/");if(a!==e.length-1){a===-1?(e="",A=0):(e=e.slice(0,a),A=e.length-1-e.lastIndexOf("/")),i=o,r=0;continue}}else if(e.length===2||e.length===1){e="",A=0,i=o,r=0;continue}}t&&(e.length>0?e+="/..":e="..",A=2)}else e.length>0?e+="/"+n.slice(i+1,o):e=n.slice(i+1,o),A=o-i-1;i=o,r=0}else s===46&&r!==-1?++r:r=-1}return e}function wn(n,t){var e=t.dir||t.root,A=t.base||(t.name||"")+(t.ext||"");return e?e===t.root?e+A:e+n+A:A}var gt={resolve:function(){for(var t="",e=!1,A,i=arguments.length-1;i>=-1&&!e;i--){var r;i>=0?r=arguments[i]:(A===void 0&&(A=process.cwd()),r=A),K(r),r.length!==0&&(t=r+"/"+t,e=r.charCodeAt(0)===47)}return t=DA(t,!e),e?t.length>0?"/"+t:"/":t.length>0?t:"."},normalize:function(t){if(K(t),t.length===0)return".";var e=t.charCodeAt(0)===47,A=t.charCodeAt(t.length-1)===47;return t=DA(t,!e),t.length===0&&!e&&(t="."),t.length>0&&A&&(t+="/"),e?"/"+t:t},isAbsolute:function(t){return K(t),t.length>0&&t.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var t,e=0;e<arguments.length;++e){var A=arguments[e];K(A),A.length>0&&(t===void 0?t=A:t+="/"+A)}return t===void 0?".":gt.normalize(t)},relative:function(t,e){if(K(t),K(e),t===e||(t=gt.resolve(t),e=gt.resolve(e),t===e))return"";for(var A=1;A<t.length&&t.charCodeAt(A)===47;++A);for(var i=t.length,r=i-A,s=1;s<e.length&&e.charCodeAt(s)===47;++s);for(var o=e.length,a=o-s,l=r<a?r:a,h=-1,c=0;c<=l;++c){if(c===l){if(a>l){if(e.charCodeAt(s+c)===47)return e.slice(s+c+1);if(c===0)return e.slice(s+c)}else r>l&&(t.charCodeAt(A+c)===47?h=c:c===0&&(h=0));break}var g=t.charCodeAt(A+c),m=e.charCodeAt(s+c);if(g!==m)break;g===47&&(h=c)}var M="";for(c=A+h+1;c<=i;++c)(c===i||t.charCodeAt(c)===47)&&(M.length===0?M+="..":M+="/..");return M.length>0?M+e.slice(s+h):(s+=h,e.charCodeAt(s)===47&&++s,e.slice(s))},_makeLong:function(t){return t},dirname:function(t){if(K(t),t.length===0)return".";for(var e=t.charCodeAt(0),A=e===47,i=-1,r=!0,s=t.length-1;s>=1;--s)if(e=t.charCodeAt(s),e===47){if(!r){i=s;break}}else r=!1;return i===-1?A?"/":".":A&&i===1?"//":t.slice(0,i)},basename:function(t,e){if(e!==void 0&&typeof e!="string")throw new TypeError('"ext" argument must be a string');K(t);var A=0,i=-1,r=!0,s;if(e!==void 0&&e.length>0&&e.length<=t.length){if(e.length===t.length&&e===t)return"";var o=e.length-1,a=-1;for(s=t.length-1;s>=0;--s){var l=t.charCodeAt(s);if(l===47){if(!r){A=s+1;break}}else a===-1&&(r=!1,a=s+1),o>=0&&(l===e.charCodeAt(o)?--o===-1&&(i=s):(o=-1,i=a))}return A===i?i=a:i===-1&&(i=t.length),t.slice(A,i)}else{for(s=t.length-1;s>=0;--s)if(t.charCodeAt(s)===47){if(!r){A=s+1;break}}else i===-1&&(r=!1,i=s+1);return i===-1?"":t.slice(A,i)}},extname:function(t){K(t);for(var e=-1,A=0,i=-1,r=!0,s=0,o=t.length-1;o>=0;--o){var a=t.charCodeAt(o);if(a===47){if(!r){A=o+1;break}continue}i===-1&&(r=!1,i=o+1),a===46?e===-1?e=o:s!==1&&(s=1):e!==-1&&(s=-1)}return e===-1||i===-1||s===0||s===1&&e===i-1&&e===A+1?"":t.slice(e,i)},format:function(t){if(t===null||typeof t!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof t);return wn("/",t)},parse:function(t){K(t);var e={root:"",dir:"",base:"",ext:"",name:""};if(t.length===0)return e;var A=t.charCodeAt(0),i=A===47,r;i?(e.root="/",r=1):r=0;for(var s=-1,o=0,a=-1,l=!0,h=t.length-1,c=0;h>=r;--h){if(A=t.charCodeAt(h),A===47){if(!l){o=h+1;break}continue}a===-1&&(l=!1,a=h+1),A===46?s===-1?s=h:c!==1&&(c=1):s!==-1&&(c=-1)}return s===-1||a===-1||c===0||c===1&&s===a-1&&s===o+1?a!==-1&&(o===0&&i?e.base=e.name=t.slice(1,a):e.base=e.name=t.slice(o,a)):(o===0&&i?(e.name=t.slice(1,s),e.base=t.slice(1,a)):(e.name=t.slice(o,s),e.base=t.slice(o,a)),e.ext=t.slice(s,a)),o>0?e.dir=t.slice(0,o-1):i&&(e.dir="/"),e},sep:"/",delimiter:":",win32:null,posix:null};gt.posix=gt;var vA=gt,dt=(n=>(n.start="start",n.left="left",n.right="right",n.justify="justify",n))(dt||{}),Ut=(n=>(n.sepia="sepia",n.night="night",n.custom="custom",n))(Ut||{}),C=(n=>(n.margin="margin",n.lineLength="lineLength",n.columns="columns",n))(C||{});const yt={range:[.7,4],step:.05},Ct={range:[100,1e3],step:100},Rt={range:[50,250],step:10};function In(n,t){return n==null||t==null||n<=t?n:void 0}function Fn(n,t){return n==null||t==null||n>=t?n:void 0}function j(n){return typeof n=="string"?n:n===null?null:void 0}function z(n){return typeof n=="boolean"||n==null?n:void 0}function ut(n,t){if(n!==void 0)return n===null?null:t[n]!==void 0?n:void 0}function mt(n){return typeof n=="boolean"||typeof n=="number"&&n>=0?n:n===null?null:void 0}function y(n){if(n!==void 0)return n===null?null:n<0?void 0:n}function Mt(n,t){if(n===void 0)return;if(n===null)return null;const e=Math.min(...t),A=Math.max(...t);return n>=e&&n<=A?n:void 0}function ce(n,t){return n===void 0?t:n}class ft{constructor(t={}){this.backgroundColor=j(t.backgroundColor),this.blendFilter=z(t.blendFilter),this.constraint=y(t.constraint),this.columnCount=y(t.columnCount),this.darkenFilter=mt(t.darkenFilter),this.deprecatedFontSize=z(t.deprecatedFontSize),this.fontFamily=j(t.fontFamily),this.fontSize=Mt(t.fontSize,yt.range),this.fontSizeNormalize=z(t.fontSizeNormalize),this.fontOpticalSizing=z(t.fontOpticalSizing),this.fontWeight=Mt(t.fontWeight,Ct.range),this.fontWidth=Mt(t.fontWidth,Rt.range),this.hyphens=z(t.hyphens),this.invertFilter=mt(t.invertFilter),this.invertGaijiFilter=mt(t.invertGaijiFilter),this.iOSPatch=z(t.iOSPatch),this.iPadOSPatch=z(t.iPadOSPatch),this.layoutStrategy=ut(t.layoutStrategy,C),this.letterSpacing=y(t.letterSpacing),this.ligatures=z(t.ligatures),this.lineHeight=y(t.lineHeight),this.linkColor=j(t.linkColor),this.noRuby=z(t.noRuby),this.pageGutter=y(t.pageGutter),this.paragraphIndent=y(t.paragraphIndent),this.paragraphSpacing=y(t.paragraphSpacing),this.scroll=z(t.scroll),this.scrollPaddingTop=y(t.scrollPaddingTop),this.scrollPaddingBottom=y(t.scrollPaddingBottom),this.selectionBackgroundColor=j(t.selectionBackgroundColor),this.selectionTextColor=j(t.selectionTextColor),this.textAlign=ut(t.textAlign,dt),this.textColor=j(t.textColor),this.textNormalization=z(t.textNormalization),this.theme=ut(t.theme,Ut),this.visitedColor=j(t.visitedColor),this.wordSpacing=y(t.wordSpacing),this.optimalLineLength=y(t.optimalLineLength),this.maximalLineLength=y(t.maximalLineLength),this.minimalLineLength=y(t.minimalLineLength)}static serialize(t){const{...e}=t;return JSON.stringify(e)}static deserialize(t){try{const e=JSON.parse(t);return new ft(e)}catch(e){return console.error("Failed to deserialize preferences:",e),null}}merging(t){const e={...this};for(const A of Object.keys(t))t[A]!==void 0&&(A!=="maximalLineLength"||t[A]===null||t[A]>=(t.optimalLineLength??e.optimalLineLength??65))&&(A!=="minimalLineLength"||t[A]===null||t[A]<=(t.optimalLineLength??e.optimalLineLength??65))&&(e[A]=t[A]);return new ft(e)}}class bA{constructor(t){this.backgroundColor=j(t.backgroundColor)||null,this.blendFilter=z(t.blendFilter)??!1,this.constraint=y(t.constraint)||0,this.columnCount=y(t.columnCount)||null,this.darkenFilter=mt(t.darkenFilter)??!1,this.deprecatedFontSize=z(t.deprecatedFontSize),(this.deprecatedFontSize===!1||this.deprecatedFontSize===null)&&(this.deprecatedFontSize=!CSS.supports("zoom","1")),this.fontFamily=j(t.fontFamily)||null,this.fontSize=Mt(t.fontSize,yt.range)||1,this.fontSizeNormalize=z(t.fontSizeNormalize)??!1,this.fontOpticalSizing=z(t.fontOpticalSizing)??null,this.fontWeight=Mt(t.fontWeight,Ct.range)||null,this.fontWidth=Mt(t.fontWidth,Rt.range)||null,this.hyphens=z(t.hyphens)??null,this.invertFilter=mt(t.invertFilter)??!1,this.invertGaijiFilter=mt(t.invertGaijiFilter)??!1,this.iOSPatch=t.iOSPatch===!1?!1:(X.OS.iOS||X.OS.iPadOS)&&X.iOSRequest==="mobile",this.iPadOSPatch=t.iPadOSPatch===!1?!1:X.OS.iPadOS&&X.iOSRequest==="desktop",this.layoutStrategy=ut(t.layoutStrategy,C)||C.lineLength,this.letterSpacing=y(t.letterSpacing)||null,this.ligatures=z(t.ligatures)??null,this.lineHeight=y(t.lineHeight)||null,this.linkColor=j(t.linkColor)||null,this.noRuby=z(t.noRuby)??!1,this.pageGutter=ce(y(t.pageGutter),20),this.paragraphIndent=y(t.paragraphIndent)??null,this.paragraphSpacing=y(t.paragraphSpacing)??null,this.scroll=z(t.scroll)??!1,this.scrollPaddingTop=y(t.scrollPaddingTop)??null,this.scrollPaddingBottom=y(t.scrollPaddingBottom)??null,this.selectionBackgroundColor=j(t.selectionBackgroundColor)||null,this.selectionTextColor=j(t.selectionTextColor)||null,this.textAlign=ut(t.textAlign,dt)||null,this.textColor=j(t.textColor)||null,this.textNormalization=z(t.textNormalization)??!1,this.theme=ut(t.theme,Ut)||null,this.visitedColor=j(t.visitedColor)||null,this.wordSpacing=y(t.wordSpacing)||null,this.optimalLineLength=y(t.optimalLineLength)||65,this.maximalLineLength=ce(Fn(t.maximalLineLength,this.optimalLineLength),80),this.minimalLineLength=ce(In(t.minimalLineLength,this.optimalLineLength),40)}}class N{constructor({initialValue:t=null,effectiveValue:e,isEffective:A,onChange:i}){this._value=t,this._effectiveValue=e,this._isEffective=A,this._onChange=i}set value(t){this._value=t,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}clear(){this._value=null}}class W extends N{set value(t){this._value=t,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}clear(){this._value=null}toggle(){this._value=!this._value,this._onChange(this._value)}}class Gt extends N{constructor({initialValue:t=null,effectiveValue:e,isEffective:A,onChange:i,supportedValues:r}){super({initialValue:t,effectiveValue:e,isEffective:A,onChange:i}),this._supportedValues=r}set value(t){if(t&&!this._supportedValues.includes(t))throw new Error(`Value '${String(t)}' is not in the supported values for this preference.`);this._value=t,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}get supportedValues(){return this._supportedValues}clear(){this._value=null}}class x extends N{constructor({initialValue:t=null,effectiveValue:e,isEffective:A,onChange:i,supportedRange:r,step:s}){super({initialValue:t,effectiveValue:e,isEffective:A,onChange:i}),this._supportedRange=r,this._step=s,this._decimals=this._step.toString().includes(".")?this._step.toString().split(".")[1].length:0}set value(t){if(t&&(t<this._supportedRange[0]||t>this._supportedRange[1]))throw new Error(`Value '${String(t)}' is out of the supported range for this preference.`);this._value=t,this._onChange(this._value)}get value(){return this._value}get effectiveValue(){return this._effectiveValue}get isEffective(){return this._isEffective}get supportedRange(){return this._supportedRange}get step(){return this._step}increment(){this._value&&this._value<this._supportedRange[1]&&(this._value=Math.min(Math.round((this._value+this._step)*10**this._decimals)/10**this._decimals,this._supportedRange[1]),this._onChange(this._value))}decrement(){this._value&&this._value>this._supportedRange[0]&&(this._value=Math.max(Math.round((this._value-this._step)*10**this._decimals)/10**this._decimals,this._supportedRange[0]),this._onChange(this._value))}format(t){return t.toString()}clear(){this._value=null}}const pt={RS__backgroundColor:"#FFFFFF",RS__textColor:"#121212",RS__linkColor:"#0000EE",RS__visitedColor:"#551A8B",RS__selectionBackgroundColor:"#b4d8fe",RS__selectionTextColor:"inherit"};class ge{constructor(t,e,A){var i,r;this.preferences=t,this.settings=e,this.metadata=A,this.layout=((r=(i=this.metadata)==null?void 0:i.getPresentation())==null?void 0:r.layout)||p.reflowable}clear(){this.preferences=new ft({optimalLineLength:65})}updatePreference(t,e){this.preferences[t]=e}get backgroundColor(){return new N({initialValue:this.preferences.backgroundColor,effectiveValue:this.settings.backgroundColor||pt.RS__backgroundColor,isEffective:this.preferences.backgroundColor!==null,onChange:t=>{this.updatePreference("backgroundColor",t||null)}})}get blendFilter(){return new W({initialValue:this.preferences.blendFilter,effectiveValue:this.settings.blendFilter||!1,isEffective:this.preferences.blendFilter!==null,onChange:t=>{this.updatePreference("blendFilter",t||null)}})}get columnCount(){return new N({initialValue:this.preferences.columnCount,effectiveValue:this.settings.columnCount||null,isEffective:this.layout===p.reflowable&&!this.settings.scroll,onChange:t=>{this.updatePreference("columnCount",t||null)}})}get constraint(){return new N({initialValue:this.preferences.constraint,effectiveValue:this.preferences.constraint||0,isEffective:!0,onChange:t=>{this.updatePreference("constraint",t||null)}})}get darkenFilter(){return new x({initialValue:typeof this.preferences.darkenFilter=="boolean"?100:this.preferences.darkenFilter,effectiveValue:typeof this.settings.darkenFilter=="boolean"?100:this.settings.darkenFilter||0,isEffective:this.settings.darkenFilter!==null,onChange:t=>{this.updatePreference("darkenFilter",t||null)},supportedRange:[0,100],step:1})}get deprecatedFontSize(){return new W({initialValue:this.preferences.deprecatedFontSize,effectiveValue:CSS.supports("zoom","1")?this.settings.deprecatedFontSize||!1:!0,isEffective:this.layout===p.reflowable,onChange:t=>{this.updatePreference("deprecatedFontSize",t||null)}})}get fontFamily(){return new N({initialValue:this.preferences.fontFamily,effectiveValue:this.settings.fontFamily||null,isEffective:this.layout===p.reflowable,onChange:t=>{this.updatePreference("fontFamily",t||null)}})}get fontSize(){return new x({initialValue:this.preferences.fontSize,effectiveValue:this.settings.fontSize||1,isEffective:this.layout===p.reflowable,onChange:t=>{this.updatePreference("fontSize",t||null)},supportedRange:yt.range,step:yt.step})}get fontSizeNormalize(){return new W({initialValue:this.preferences.fontSizeNormalize,effectiveValue:this.settings.fontSizeNormalize||!1,isEffective:this.layout===p.reflowable&&this.preferences.fontSizeNormalize!==null,onChange:t=>{this.updatePreference("fontSizeNormalize",t||null)}})}get fontOpticalSizing(){return new W({initialValue:this.preferences.fontOpticalSizing,effectiveValue:this.settings.fontOpticalSizing||!0,isEffective:this.layout===p.reflowable&&this.preferences.fontOpticalSizing!==null,onChange:t=>{this.updatePreference("fontOpticalSizing",t||null)}})}get fontWeight(){return new x({initialValue:this.preferences.fontWeight,effectiveValue:this.settings.fontWeight||400,isEffective:this.layout===p.reflowable&&this.preferences.fontWeight!==null,onChange:t=>{this.updatePreference("fontWeight",t||null)},supportedRange:Ct.range,step:Ct.step})}get fontWidth(){return new x({initialValue:this.preferences.fontWidth,effectiveValue:this.settings.fontWidth||100,isEffective:this.layout===p.reflowable&&this.preferences.fontWidth!==null,onChange:t=>{this.updatePreference("fontWidth",t||null)},supportedRange:Rt.range,step:Rt.step})}get hyphens(){var t;return new W({initialValue:this.preferences.hyphens,effectiveValue:this.settings.hyphens||!1,isEffective:this.layout===p.reflowable&&((t=this.metadata)==null?void 0:t.effectiveReadingProgression)===w.ltr&&this.preferences.hyphens!==null,onChange:e=>{this.updatePreference("hyphens",e||null)}})}get invertFilter(){return new x({initialValue:typeof this.preferences.invertFilter=="boolean"?100:this.preferences.invertFilter,effectiveValue:typeof this.settings.invertFilter=="boolean"?100:this.settings.invertFilter||0,isEffective:this.settings.invertFilter!==null,onChange:t=>{this.updatePreference("invertFilter",t||null)},supportedRange:[0,100],step:1})}get invertGaijiFilter(){return new x({initialValue:typeof this.preferences.invertGaijiFilter=="boolean"?100:this.preferences.invertGaijiFilter,effectiveValue:typeof this.settings.invertGaijiFilter=="boolean"?100:this.settings.invertGaijiFilter||0,isEffective:this.preferences.invertGaijiFilter!==null,onChange:t=>{this.updatePreference("invertGaijiFilter",t||null)},supportedRange:[0,100],step:1})}get iOSPatch(){return new W({initialValue:this.preferences.iOSPatch,effectiveValue:this.settings.iOSPatch||!1,isEffective:this.layout===p.reflowable,onChange:t=>{this.updatePreference("iOSPatch",t||null)}})}get iPadOSPatch(){return new W({initialValue:this.preferences.iPadOSPatch,effectiveValue:this.settings.iPadOSPatch||!1,isEffective:this.layout===p.reflowable,onChange:t=>{this.updatePreference("iPadOSPatch",t||null)}})}get layoutStrategy(){return new Gt({initialValue:this.preferences.layoutStrategy,effectiveValue:this.settings.layoutStrategy,isEffective:this.layout===p.reflowable,onChange:t=>{this.updatePreference("layoutStrategy",t||null)},supportedValues:Object.values(C)})}get letterSpacing(){return new x({initialValue:this.preferences.letterSpacing,effectiveValue:this.settings.letterSpacing||0,isEffective:this.layout===p.reflowable&&this.preferences.letterSpacing!==null,onChange:t=>{this.updatePreference("letterSpacing",t||null)},supportedRange:[0,1],step:.125})}get ligatures(){var t,e;return new W({initialValue:this.preferences.ligatures,effectiveValue:this.settings.ligatures||!0,isEffective:this.layout===p.reflowable&&((e=(t=this.metadata)==null?void 0:t.languages)==null?void 0:e.some(A=>A==="ar"||A==="fa"))&&this.preferences.ligatures!==null||!1,onChange:A=>{this.updatePreference("ligatures",A||null)}})}get lineHeight(){return new x({initialValue:this.preferences.lineHeight,effectiveValue:this.settings.lineHeight,isEffective:this.layout===p.reflowable&&this.preferences.lineHeight!==null,onChange:t=>{this.updatePreference("lineHeight",t||null)},supportedRange:[1,2],step:.1})}get linkColor(){return new N({initialValue:this.preferences.linkColor,effectiveValue:this.settings.linkColor||pt.RS__linkColor,isEffective:this.layout===p.reflowable&&this.preferences.linkColor!==null,onChange:t=>{this.updatePreference("linkColor",t||null)}})}get maximalLineLength(){return new x({initialValue:this.preferences.maximalLineLength,effectiveValue:this.settings.maximalLineLength,isEffective:this.layout===p.reflowable,onChange:t=>{this.updatePreference("maximalLineLength",t)},supportedRange:[20,100],step:1})}get minimalLineLength(){return new x({initialValue:this.preferences.minimalLineLength,effectiveValue:this.settings.minimalLineLength,isEffective:this.layout===p.reflowable,onChange:t=>{this.updatePreference("minimalLineLength",t)},supportedRange:[20,100],step:1})}get noRuby(){var t,e;return new W({initialValue:this.preferences.noRuby,effectiveValue:this.settings.noRuby||!1,isEffective:this.layout===p.reflowable&&((e=(t=this.metadata)==null?void 0:t.languages)==null?void 0:e.includes("ja"))||!1,onChange:A=>{this.updatePreference("noRuby",A||null)}})}get optimalLineLength(){return new x({initialValue:this.preferences.optimalLineLength,effectiveValue:this.settings.optimalLineLength,isEffective:this.layout===p.reflowable,onChange:t=>{this.updatePreference("optimalLineLength",t)},supportedRange:[20,100],step:1})}get pageGutter(){return new N({initialValue:this.preferences.pageGutter,effectiveValue:this.settings.pageGutter,isEffective:this.layout===p.reflowable,onChange:t=>{this.updatePreference("pageGutter",t||null)}})}get paragraphIndent(){return new x({initialValue:this.preferences.paragraphIndent,effectiveValue:this.settings.paragraphIndent||0,isEffective:this.layout===p.reflowable&&this.preferences.paragraphIndent!==null,onChange:t=>{this.updatePreference("paragraphIndent",t||null)},supportedRange:[0,3],step:.25})}get paragraphSpacing(){return new x({initialValue:this.preferences.paragraphSpacing,effectiveValue:this.settings.paragraphSpacing||0,isEffective:this.layout===p.reflowable&&this.preferences.paragraphSpacing!==null,onChange:t=>{this.updatePreference("paragraphSpacing",t||null)},supportedRange:[0,3],step:.25})}get scroll(){return new W({initialValue:this.preferences.scroll,effectiveValue:this.settings.scroll||!1,isEffective:this.layout===p.reflowable,onChange:t=>{this.updatePreference("scroll",t||null)}})}get scrollPaddingTop(){return new N({initialValue:this.preferences.scrollPaddingTop,effectiveValue:this.settings.scrollPaddingTop||0,isEffective:this.layout===p.reflowable&&!!this.settings.scroll&&this.preferences.scrollPaddingTop!==null,onChange:t=>{this.updatePreference("scrollPaddingTop",t||null)}})}get scrollPaddingBottom(){return new N({initialValue:this.preferences.scrollPaddingBottom,effectiveValue:this.settings.scrollPaddingBottom||0,isEffective:this.layout===p.reflowable&&!!this.settings.scroll&&this.preferences.scrollPaddingBottom!==null,onChange:t=>{this.updatePreference("scrollPaddingBottom",t||null)}})}get selectionBackgroundColor(){return new N({initialValue:this.preferences.selectionBackgroundColor,effectiveValue:this.settings.selectionBackgroundColor||pt.RS__selectionBackgroundColor,isEffective:this.layout===p.reflowable&&this.preferences.selectionBackgroundColor!==null,onChange:t=>{this.updatePreference("selectionBackgroundColor",t||null)}})}get selectionTextColor(){return new N({initialValue:this.preferences.selectionTextColor,effectiveValue:this.settings.selectionTextColor||pt.RS__selectionTextColor,isEffective:this.layout===p.reflowable&&this.preferences.selectionTextColor!==null,onChange:t=>{this.updatePreference("selectionTextColor",t||null)}})}get textAlign(){return new Gt({initialValue:this.preferences.textAlign,effectiveValue:this.settings.textAlign||dt.start,isEffective:this.layout===p.reflowable&&this.preferences.textAlign!==null,onChange:t=>{this.updatePreference("textAlign",t||null)},supportedValues:Object.values(dt)})}get textColor(){return new N({initialValue:this.preferences.textColor,effectiveValue:this.settings.textColor||pt.RS__textColor,isEffective:this.layout===p.reflowable&&this.preferences.textColor!==null,onChange:t=>{this.updatePreference("textColor",t||null)}})}get textNormalization(){return new W({initialValue:this.preferences.textNormalization,effectiveValue:this.settings.textNormalization||!1,isEffective:this.layout===p.reflowable,onChange:t=>{this.updatePreference("textNormalization",t||null)}})}get theme(){return new Gt({initialValue:this.preferences.theme,effectiveValue:this.settings.theme||null,isEffective:this.layout===p.reflowable,onChange:t=>{this.updatePreference("theme",t||null)},supportedValues:Object.values(Ut)})}get visitedColor(){return new N({initialValue:this.preferences.visitedColor,effectiveValue:this.settings.visitedColor||pt.RS__visitedColor,isEffective:this.layout===p.reflowable&&this.preferences.visitedColor!==null,onChange:t=>{this.updatePreference("visitedColor",t||null)}})}get wordSpacing(){return new x({initialValue:this.preferences.wordSpacing,effectiveValue:this.settings.wordSpacing||0,isEffective:this.layout===p.reflowable&&this.preferences.wordSpacing!==null,onChange:t=>{this.updatePreference("wordSpacing",t||null)},supportedRange:[0,2],step:.125})}}class de{constructor(t,e){this.backgroundColor=t.backgroundColor||e.backgroundColor||null,this.blendFilter=typeof t.blendFilter=="boolean"?t.blendFilter:e.blendFilter??null,this.columnCount=t.columnCount!==void 0?t.columnCount:e.columnCount!==void 0?e.columnCount:null,this.constraint=t.constraint||e.constraint,this.darkenFilter=typeof t.darkenFilter=="boolean"?t.darkenFilter:e.darkenFilter??null,this.deprecatedFontSize=typeof t.deprecatedFontSize=="boolean"?t.deprecatedFontSize:e.deprecatedFontSize??null,this.fontFamily=t.fontFamily||e.fontFamily||null,this.fontSize=t.fontSize!==void 0?t.fontSize:e.fontSize!==void 0?e.fontSize:null,this.fontSizeNormalize=typeof t.fontSizeNormalize=="boolean"?t.fontSizeNormalize:e.fontSizeNormalize??null,this.fontOpticalSizing=typeof t.fontOpticalSizing=="boolean"?t.fontOpticalSizing:e.fontOpticalSizing??null,this.fontWeight=t.fontWeight!==void 0?t.fontWeight:e.fontWeight!==void 0?e.fontWeight:null,this.fontWidth=t.fontWidth!==void 0?t.fontWidth:e.fontWidth!==void 0?e.fontWidth:null,this.hyphens=typeof t.hyphens=="boolean"?t.hyphens:e.hyphens??null,this.invertFilter=typeof t.invertFilter=="boolean"?t.invertFilter:e.invertFilter??null,this.invertGaijiFilter=typeof t.invertGaijiFilter=="boolean"?t.invertGaijiFilter:e.invertGaijiFilter??null,this.iOSPatch=this.deprecatedFontSize||t.iOSPatch===!1?!1:t.iOSPatch===!0?(X.OS.iOS||X.OS.iPadOS)&&X.iOSRequest==="mobile":e.iOSPatch,this.iPadOSPatch=this.deprecatedFontSize||t.iPadOSPatch===!1?!1:t.iPadOSPatch===!0?X.OS.iPadOS&&X.iOSRequest==="desktop":e.iPadOSPatch,this.layoutStrategy=t.layoutStrategy||e.layoutStrategy||null,this.letterSpacing=t.letterSpacing!==void 0?t.letterSpacing:e.letterSpacing!==void 0?e.letterSpacing:null,this.ligatures=typeof t.ligatures=="boolean"?t.ligatures:e.ligatures??null,this.lineHeight=t.lineHeight!==void 0?t.lineHeight:e.lineHeight!==void 0?e.lineHeight:null,this.linkColor=t.linkColor||e.linkColor||null,this.maximalLineLength=t.maximalLineLength===null?null:t.maximalLineLength||e.maximalLineLength||null,this.minimalLineLength=t.minimalLineLength===null?null:t.minimalLineLength||e.minimalLineLength||null,this.noRuby=typeof t.noRuby=="boolean"?t.noRuby:e.noRuby??null,this.optimalLineLength=t.optimalLineLength||e.optimalLineLength,this.pageGutter=t.pageGutter!==void 0?t.pageGutter:e.pageGutter!==void 0?e.pageGutter:null,this.paragraphIndent=t.paragraphIndent!==void 0?t.paragraphIndent:e.paragraphIndent!==void 0?e.paragraphIndent:null,this.paragraphSpacing=t.paragraphSpacing!==void 0?t.paragraphSpacing:e.paragraphSpacing!==void 0?e.paragraphSpacing:null,this.scroll=typeof t.scroll=="boolean"?t.scroll:e.scroll??null,this.scrollPaddingTop=t.scrollPaddingTop!==void 0?t.scrollPaddingTop:e.scrollPaddingTop!==void 0?e.scrollPaddingTop:null,this.scrollPaddingBottom=t.scrollPaddingBottom!==void 0?t.scrollPaddingBottom:e.scrollPaddingBottom!==void 0?e.scrollPaddingBottom:null,this.selectionBackgroundColor=t.selectionBackgroundColor||e.selectionBackgroundColor||null,this.selectionTextColor=t.selectionTextColor||e.selectionTextColor||null,this.textAlign=t.textAlign||e.textAlign||null,this.textColor=t.textColor||e.textColor||null,this.textNormalization=typeof t.textNormalization=="boolean"?t.textNormalization:e.textNormalization??null,this.theme=t.theme||e.theme||null,this.visitedColor=t.visitedColor||e.visitedColor||null,this.wordSpacing=t.wordSpacing!==void 0?t.wordSpacing:e.wordSpacing!==void 0?e.wordSpacing:null}}function Ht(n){const t=getComputedStyle(n),e=parseFloat(t.paddingLeft||"0"),A=parseFloat(t.paddingRight||"0");return n.clientWidth-e-A}class GA{constructor(){}toFlag(t){return`readium-${t}-on`}toUnitless(t){return t.toString()}toPercentage(t,e=!1){return e||t>0&&t<=1?`${Math.round(t*100)}%`:`${t}%`}toVw(t){const e=Math.round(t*100);return`${Math.min(e,100)}vw`}toVh(t){const e=Math.round(t*100);return`${Math.min(e,100)}vh`}toPx(t){return`${t}px`}toRem(t){return`${t}rem`}}class ue extends GA{constructor(t){super(),this.a11yNormalize=t.a11yNormalize??null,this.appearance=t.appearance??null,this.backgroundColor=t.backgroundColor??null,this.blendFilter=t.blendFilter??null,this.bodyHyphens=t.bodyHyphens??null,this.colCount=t.colCount??null,this.darkenFilter=t.darkenFilter??null,this.deprecatedFontSize=t.deprecatedFontSize??null,this.fontFamily=t.fontFamily??null,this.fontOpticalSizing=t.fontOpticalSizing??null,this.fontSize=t.fontSize??null,this.fontSizeNormalize=t.fontSizeNormalize??null,this.fontWeight=t.fontWeight??null,this.fontWidth=t.fontWidth??null,this.invertFilter=t.invertFilter??null,this.invertGaijiFilter=t.invertGaijiFilter??null,this.iOSPatch=t.iOSPatch??null,this.iPadOSPatch=t.iPadOSPatch??null,this.letterSpacing=t.letterSpacing??null,this.ligatures=t.ligatures??null,this.lineHeight=t.lineHeight??null,this.lineLength=t.lineLength??null,this.linkColor=t.linkColor??null,this.noRuby=t.noRuby??null,this.paraIndent=t.paraIndent??null,this.paraSpacing=t.paraSpacing??null,this.selectionBackgroundColor=t.selectionBackgroundColor??null,this.selectionTextColor=t.selectionTextColor??null,this.textAlign=t.textAlign??null,this.textColor=t.textColor??null,this.view=t.view??null,this.visitedColor=t.visitedColor??null,this.wordSpacing=t.wordSpacing??null}toCSSProperties(){const t={};return this.a11yNormalize&&(t["--USER__a11yNormalize"]=this.toFlag("a11y")),this.appearance&&(t["--USER__appearance"]=this.toFlag(this.appearance)),this.backgroundColor&&(t["--USER__backgroundColor"]=this.backgroundColor),this.blendFilter&&(t["--USER__blendFilter"]=this.toFlag("blend")),this.bodyHyphens&&(t["--USER__bodyHyphens"]=this.bodyHyphens),this.colCount&&(t["--USER__colCount"]=this.toUnitless(this.colCount)),this.darkenFilter===!0?t["--USER__darkenFilter"]=this.toFlag("darken"):typeof this.darkenFilter=="number"&&(t["--USER__darkenFilter"]=this.toPercentage(this.darkenFilter)),this.deprecatedFontSize&&(t["--USER__fontSizeImplementation"]=this.toFlag("deprecatedFontSize")),this.fontFamily&&(t["--USER__fontFamily"]=this.fontFamily),this.fontOpticalSizing!=null&&(t["--USER__fontOpticalSizing"]=this.fontOpticalSizing),this.fontSize!=null&&(t["--USER__fontSize"]=this.toPercentage(this.fontSize,!0)),this.fontSizeNormalize&&(t["--USER__fontSizeNormalize"]=this.toFlag("normalize")),this.fontWeight!=null&&(t["--USER__fontWeight"]=this.toUnitless(this.fontWeight)),this.fontWidth!=null&&(t["--USER__fontWidth"]=typeof this.fontWidth=="string"?this.fontWidth:this.toUnitless(this.fontWidth)),this.invertFilter===!0?t["--USER__invertFilter"]=this.toFlag("invert"):typeof this.invertFilter=="number"&&(t["--USER__invertFilter"]=this.toPercentage(this.invertFilter)),this.invertGaijiFilter===!0?t["--USER__invertGaiji"]=this.toFlag("invertGaiji"):typeof this.invertGaijiFilter=="number"&&(t["--USER__invertGaiji"]=this.toPercentage(this.invertGaijiFilter)),this.iOSPatch&&(t["--USER__iOSPatch"]=this.toFlag("iOSPatch")),this.iPadOSPatch&&(t["--USER__iPadOSPatch"]=this.toFlag("iPadOSPatch")),this.letterSpacing!=null&&(t["--USER__letterSpacing"]=this.toRem(this.letterSpacing)),this.ligatures&&(t["--USER__ligatures"]=this.ligatures),this.lineHeight!=null&&(t["--USER__lineHeight"]=this.toUnitless(this.lineHeight)),this.lineLength!=null&&(t["--USER__lineLength"]=this.toPx(this.lineLength)),this.linkColor&&(t["--USER__linkColor"]=this.linkColor),this.noRuby&&(t["--USER__noRuby"]=this.toFlag("noRuby")),this.paraIndent!=null&&(t["--USER__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(t["--USER__paraSpacing"]=this.toRem(this.paraSpacing)),this.selectionBackgroundColor&&(t["--USER__selectionBackgroundColor"]=this.selectionBackgroundColor),this.selectionTextColor&&(t["--USER__selectionTextColor"]=this.selectionTextColor),this.textAlign&&(t["--USER__textAlign"]=this.textAlign),this.textColor&&(t["--USER__textColor"]=this.textColor),this.view&&(t["--USER__view"]=this.toFlag(this.view)),this.visitedColor&&(t["--USER__visitedColor"]=this.visitedColor),this.wordSpacing!=null&&(t["--USER__wordSpacing"]=this.toRem(this.wordSpacing)),t}}class HA extends GA{constructor(t){super(),this.backgroundColor=t.backgroundColor??null,this.baseFontFamily=t.baseFontFamily??null,this.baseFontSize=t.baseFontSize??null,this.baseLineHeight=t.baseLineHeight??null,this.boxSizingMedia=t.boxSizingMedia??null,this.boxSizingTable=t.boxSizingTable??null,this.colWidth=t.colWidth??null,this.colCount=t.colCount??null,this.colGap=t.colGap??null,this.codeFontFamily=t.codeFontFamily??null,this.compFontFamily=t.compFontFamily??null,this.defaultLineLength=t.defaultLineLength??null,this.flowSpacing=t.flowSpacing??null,this.humanistTf=t.humanistTf??null,this.linkColor=t.linkColor??null,this.maxMediaWidth=t.maxMediaWidth??null,this.maxMediaHeight=t.maxMediaHeight??null,this.modernTf=t.modernTf??null,this.monospaceTf=t.monospaceTf??null,this.noOverflow=t.noOverflow??null,this.noVerticalPagination=t.noVerticalPagination??null,this.oldStyleTf=t.oldStyleTf??null,this.pageGutter=t.pageGutter??null,this.paraIndent=t.paraIndent??null,this.paraSpacing=t.paraSpacing??null,this.primaryColor=t.primaryColor??null,this.scrollPaddingBottom=t.scrollPaddingBottom??null,this.scrollPaddingTop=t.scrollPaddingTop??null,this.sansSerifJa=t.sansSerifJa??null,this.sansSerifJaV=t.sansSerifJaV??null,this.sansTf=t.sansTf??null,this.secondaryColor=t.secondaryColor??null,this.selectionBackgroundColor=t.selectionBackgroundColor??null,this.selectionTextColor=t.selectionTextColor??null,this.serifJa=t.serifJa??null,this.serifJaV=t.serifJaV??null,this.textColor=t.textColor??null,this.typeScale=t.typeScale??null,this.visitedColor=t.visitedColor??null}toCSSProperties(){const t={};return this.backgroundColor&&(t["--RS__backgroundColor"]=this.backgroundColor),this.baseFontFamily&&(t["--RS__baseFontFamily"]=this.baseFontFamily),this.baseFontSize!=null&&(t["--RS__baseFontSize"]=this.toRem(this.baseFontSize)),this.baseLineHeight!=null&&(t["--RS__baseLineHeight"]=this.toUnitless(this.baseLineHeight)),this.boxSizingMedia&&(t["--RS__boxSizingMedia"]=this.boxSizingMedia),this.boxSizingTable&&(t["--RS__boxSizingTable"]=this.boxSizingTable),this.colWidth!=null&&(t["--RS__colWidth"]=this.colWidth),this.colCount!=null&&(t["--RS__colCount"]=this.toUnitless(this.colCount)),this.colGap!=null&&(t["--RS__colGap"]=this.toPx(this.colGap)),this.codeFontFamily&&(t["--RS__codeFontFamily"]=this.codeFontFamily),this.compFontFamily&&(t["--RS__compFontFamily"]=this.compFontFamily),this.defaultLineLength!=null&&(t["--RS__defaultLineLength"]=this.toPx(this.defaultLineLength)),this.flowSpacing!=null&&(t["--RS__flowSpacing"]=this.toRem(this.flowSpacing)),this.humanistTf&&(t["--RS__humanistTf"]=this.humanistTf),this.linkColor&&(t["--RS__linkColor"]=this.linkColor),this.maxMediaWidth&&(t["--RS__maxMediaWidth"]=this.toVw(this.maxMediaWidth)),this.maxMediaHeight&&(t["--RS__maxMediaHeight"]=this.toVh(this.maxMediaHeight)),this.modernTf&&(t["--RS__modernTf"]=this.modernTf),this.monospaceTf&&(t["--RS__monospaceTf"]=this.monospaceTf),this.noOverflow&&(t["--RS__disableOverflow"]=this.toFlag("noOverflow")),this.noVerticalPagination&&(t["--RS__disablePagination"]=this.toFlag("noVerticalPagination")),this.oldStyleTf&&(t["--RS__oldStyleTf"]=this.oldStyleTf),this.pageGutter!=null&&(t["--RS__pageGutter"]=this.toPx(this.pageGutter)),this.paraIndent!=null&&(t["--RS__paraIndent"]=this.toRem(this.paraIndent)),this.paraSpacing!=null&&(t["--RS__paraSpacing"]=this.toRem(this.paraSpacing)),this.primaryColor&&(t["--RS__primaryColor"]=this.primaryColor),this.sansSerifJa&&(t["--RS__sans-serif-ja"]=this.sansSerifJa),this.sansSerifJaV&&(t["--RS__sans-serif-ja-v"]=this.sansSerifJaV),this.sansTf&&(t["--RS__sansTf"]=this.sansTf),this.scrollPaddingBottom!=null&&(t["--RS__scrollPaddingBottom"]=this.toPx(this.scrollPaddingBottom)),this.scrollPaddingTop!=null&&(t["--RS__scrollPaddingTop"]=this.toPx(this.scrollPaddingTop)),this.secondaryColor&&(t["--RS__secondaryColor"]=this.secondaryColor),this.selectionBackgroundColor&&(t["--RS__selectionBackgroundColor"]=this.selectionBackgroundColor),this.selectionTextColor&&(t["--RS__selectionTextColor"]=this.selectionTextColor),this.serifJa&&(t["--RS__serif-ja"]=this.serifJa),this.serifJaV&&(t["--RS__serif-ja-v"]=this.serifJaV),this.textColor&&(t["--RS__textColor"]=this.textColor),this.typeScale&&(t["--RS__typeScale"]=this.toUnitless(this.typeScale)),this.visitedColor&&(t["--RS__visitedColor"]=this.visitedColor),t}}class kA{constructor(t){this.rsProperties=t.rsProperties,this.userProperties=t.userProperties,this.lineLengths=t.lineLengths,this.container=t.container,this.containerParent=t.container.parentElement||document.documentElement,this.constraint=t.constraint,this.layoutStrategy=t.layoutStrategy||C.lineLength,this.cachedColCount=t.userProperties.colCount,this.effectiveContainerWidth=Ht(this.containerParent)}update(t){this.cachedColCount=t.columnCount,t.constraint!==this.constraint&&(this.constraint=t.constraint),t.layoutStrategy&&t.layoutStrategy!==this.layoutStrategy&&(this.layoutStrategy=t.layoutStrategy),t.pageGutter!==this.rsProperties.pageGutter&&(this.rsProperties.pageGutter=t.pageGutter),t.scrollPaddingBottom!==this.rsProperties.scrollPaddingBottom&&(this.rsProperties.scrollPaddingBottom=t.scrollPaddingBottom),t.scrollPaddingTop!==this.rsProperties.scrollPaddingTop&&(this.rsProperties.scrollPaddingTop=t.scrollPaddingTop),this.lineLengths.update({fontFace:t.fontFamily,letterSpacing:t.letterSpacing,pageGutter:t.pageGutter,wordSpacing:t.wordSpacing,optimalChars:t.optimalLineLength,minChars:t.minimalLineLength,maxChars:t.maximalLineLength});const e=this.updateLayout(t.fontSize,t.deprecatedFontSize||t.iOSPatch,t.scroll,t.columnCount);e!=null&&e.effectiveContainerWidth&&(this.effectiveContainerWidth=e==null?void 0:e.effectiveContainerWidth);const A={a11yNormalize:t.textNormalization,appearance:t.theme,backgroundColor:t.backgroundColor,blendFilter:t.blendFilter,bodyHyphens:typeof t.hyphens!="boolean"?null:t.hyphens?"auto":"none",colCount:e==null?void 0:e.colCount,darkenFilter:t.darkenFilter,deprecatedFontSize:t.deprecatedFontSize,fontFamily:t.fontFamily,fontOpticalSizing:typeof t.fontOpticalSizing!="boolean"?null:t.fontOpticalSizing?"auto":"none",fontSize:t.fontSize,fontSizeNormalize:t.fontSizeNormalize,fontWeight:t.fontWeight,fontWidth:t.fontWidth,invertFilter:t.invertFilter,invertGaijiFilter:t.invertGaijiFilter,iOSPatch:t.iOSPatch,iPadOSPatch:t.iPadOSPatch,letterSpacing:t.letterSpacing,ligatures:typeof t.ligatures!="boolean"?null:t.ligatures?"common-ligatures":"none",lineHeight:t.lineHeight,lineLength:e==null?void 0:e.effectiveLineLength,linkColor:t.linkColor,noRuby:t.noRuby,paraIndent:t.paragraphIndent,paraSpacing:t.paragraphSpacing,selectionBackgroundColor:t.selectionBackgroundColor,selectionTextColor:t.selectionTextColor,textAlign:t.textAlign,textColor:t.textColor,view:typeof t.scroll!="boolean"?null:t.scroll?"scroll":"paged",visitedColor:t.visitedColor,wordSpacing:t.wordSpacing};this.userProperties=new ue(A)}updateLayout(t,e,A,i){return A??this.userProperties.view==="scroll"?this.computeScrollLength(t,e):this.paginate(t,e,i)}getCompensatedMetrics(t,e){const A=t||this.userProperties.fontSize||1,i=A<1?this.layoutStrategy===C.margin?1/(A+.003):1/A:e?A:1;return{zoomFactor:A,zoomCompensation:i,optimal:Math.round(this.lineLengths.optimalLineLength)*A,minimal:this.lineLengths.minimalLineLength!==null?Math.round(this.lineLengths.minimalLineLength*A):null,maximal:this.lineLengths.maximalLineLength!==null?Math.round(this.lineLengths.maximalLineLength*A):null}}paginate(t,e,A){const i=Math.round(Ht(this.containerParent)-this.constraint),r=this.getCompensatedMetrics(t,e),s=r.zoomCompensation,o=r.optimal,a=r.minimal,l=r.maximal;let h=1,c=i;if(A===void 0)return{colCount:void 0,effectiveContainerWidth:c,effectiveLineLength:Math.round(c/h*s)};if(A===null){if(this.layoutStrategy===C.margin)if(i>=o){h=Math.floor(i/o);const g=Math.round(h*(o*s));c=Math.min(g,i)}else h=1,c=i;else if(this.layoutStrategy===C.lineLength)if(i<o||l===null)h=1,c=i;else{h=Math.floor(i/o);const g=Math.round(h*(l*s));c=Math.min(g,i)}else if(this.layoutStrategy===C.columns)if(i>=o)if(l===null)h=Math.floor(i/o),c=i;else{h=Math.floor(i/(a||o));const g=Math.round(h*(o*s));c=Math.min(g,i)}else h=1,c=i}else if(A>1){const g=Math.round(A*(a!==null?a:o));if(i>=g){if(h=A,this.layoutStrategy===C.margin){const m=Math.round(h*(o*s));c=Math.min(m,i)}else if(this.layoutStrategy===C.lineLength||this.layoutStrategy===C.columns){if(l===null)c=i;else{const m=Math.round(h*(l*s));c=Math.min(m,i)}this.layoutStrategy===C.columns&&console.error("Columns strategy is not compatible with a column count whose value is a number. Falling back to lineLength strategy.")}}else{a!==null&&i<Math.round(A*a)?h=Math.floor(i/a):h=A;const m=Math.round(h*(o*s));c=Math.min(m,i)}}else if(h=1,i>=o){if(this.layoutStrategy===C.margin){const g=Math.round(o*s);c=Math.min(g,i)}else if(this.layoutStrategy===C.lineLength||this.layoutStrategy===C.columns){if(l===null)c=i;else{const g=Math.round(l*s);c=Math.min(g,i)}this.layoutStrategy===C.columns&&console.error("Columns strategy is not compatible with a column count whose value is a number. Falling back to lineLength strategy.")}}else c=i;return{colCount:h,effectiveContainerWidth:c,effectiveLineLength:Math.round(c/h/(t&&t>=1?t:1)*s)}}computeScrollLength(t,e){const A=Math.round(Ht(this.containerParent)-this.constraint),i=this.getCompensatedMetrics(t&&(t<1||e)?t:1,e),r=i.zoomCompensation,s=i.optimal,o=i.maximal;let a,l=A,h=Math.round(s*r);if(this.layoutStrategy===C.margin){const c=Math.min(Math.round(s*r),A);h=e?c:Math.round(c*r)}else if(this.layoutStrategy===C.lineLength||this.layoutStrategy===C.columns)if(this.layoutStrategy===C.columns&&console.error("Columns strategy is not compatible with scroll. Falling back to lineLength strategy."),o===null)h=A;else{const c=Math.min(Math.round(o*r),A);h=e?c:Math.round(c*r)}return{colCount:a,effectiveContainerWidth:l,effectiveLineLength:h}}setContainerWidth(){this.container.style.width=`${this.effectiveContainerWidth}px`}resizeHandler(){const t=this.updateLayout(this.userProperties.fontSize,this.userProperties.deprecatedFontSize||this.userProperties.iOSPatch,this.userProperties.view==="scroll",this.cachedColCount);this.userProperties.colCount=t.colCount,this.userProperties.lineLength=t.effectiveLineLength,this.effectiveContainerWidth=t.effectiveContainerWidth,this.container.style.width=`${this.effectiveContainerWidth}px`}}const Un=n=>({frameLoaded:n.frameLoaded||(()=>{}),positionChanged:n.positionChanged||(()=>{}),tap:n.tap||(()=>!1),click:n.click||(()=>!1),zoom:n.zoom||(()=>{}),miscPointer:n.miscPointer||(()=>{}),customEvent:n.customEvent||(()=>{}),handleLocator:n.handleLocator||(()=>!1),textSelected:n.textSelected||(()=>{})});class me extends ze{constructor(t,e,A,i=[],r=void 0,s={preferences:{},defaults:{}}){super(),this._preferencesEditor=null,this.reflowViewport={readingOrder:[],progressions:new Map,positions:null},this.pub=e,this.layout=me.determineLayout(e),this.container=t,this.listeners=Un(A),this.currentLocation=r,i.length&&(this.positions=i),this._preferences=new ft(s.preferences),this._defaults=new bA(s.defaults),this._settings=new de(this._preferences,this._defaults),this._css=new kA({rsProperties:new HA({}),userProperties:new ue({}),lineLengths:new ct({optimalChars:this._settings.optimalLineLength,minChars:this._settings.minimalLineLength,maxChars:this._settings.maximalLineLength,pageGutter:this._settings.pageGutter,fontFace:this._settings.fontFamily,letterSpacing:this._settings.letterSpacing,wordSpacing:this._settings.wordSpacing}),container:t,constraint:this._settings.constraint}),this.currentProgression=this.layout===p.reflowable&&this._settings.scroll?w.ttb:e.metadata.effectiveReadingProgression,this.resizeObserver=new ResizeObserver(()=>this.ownerWindow.requestAnimationFrame(async()=>await this.resizeHandler())),this.resizeObserver.observe(this.container.parentElement||document.documentElement)}static determineLayout(t){var A;const e=t.metadata.getPresentation();return(e==null?void 0:e.layout)==p.fixed||t.metadata.otherMetadata&&"http://openmangaformat.org/schema/1.0#version"in t.metadata.otherMetadata||((A=t.metadata.otherMetadata)==null?void 0:A.conformsTo)==="https://readium.org/webpub-manifest/profiles/divina"?p.fixed:p.reflowable}async load(){var t;if((t=this.positions)!=null&&t.length||(this.positions=await this.pub.positionsFromManifest()),this.layout===p.fixed)this.framePool=new PA(this.container,this.positions,this.pub),this.framePool.listener=(e,A)=>{this.eventListener(e,A)};else{await this.updateCSS(!1);const e=this.compileCSSProperties(this._css);this.framePool=new CA(this.container,this.positions,e)}this.currentLocation===void 0&&(this.currentLocation=this.positions[0]),await this.resizeHandler(),await this.apply()}get settings(){if(this.layout===p.fixed)return Object.freeze({...this._settings});{const t=this._css.userProperties.colCount||this._css.rsProperties.colCount||this._settings.columnCount;return Object.freeze({...this._settings,columnCount:t})}}get preferencesEditor(){return this._preferencesEditor===null&&(this._preferencesEditor=new ge(this._preferences,this.settings,this.pub.metadata)),this._preferencesEditor}async submitPreferences(t){this._preferences=this._preferences.merging(t),await this.applyPreferences()}async applyPreferences(){const t=this._settings;this._settings=new de(this._preferences,this._defaults),this._preferencesEditor!==null&&(this._preferencesEditor=new ge(this._preferences,this.settings,this.pub.metadata)),this.layout===p.fixed?this.handleFXLPrefs(t,this._settings):await this.updateCSS(!0)}handleFXLPrefs(t,e){t.columnCount!==e.columnCount&&this.framePool.setPerPage(e.columnCount)}async updateCSS(t){this._css.update(this._settings),t&&await this.commitCSS(this._css)}compileCSSProperties(t){const e={};for(const[A,i]of Object.entries(t.rsProperties.toCSSProperties()))e[A]=i;for(const[A,i]of Object.entries(t.userProperties.toCSSProperties()))e[A]=i;return e}async commitCSS(t){const e=this.compileCSSProperties(t);this.framePool.setCSSProperties(e),this._css.userProperties.view==="paged"&&this.readingProgression===w.ttb?await this.setReadingProgression(this.pub.metadata.effectiveReadingProgression):this._css.userProperties.view==="scroll"&&(this.readingProgression===w.ltr||this.readingProgression===w.rtl)&&await this.setReadingProgression(w.ttb),this._css.setContainerWidth()}async resizeHandler(){const t=this.container.parentElement||document.documentElement;if(this.layout===p.fixed)this.container.style.width=`${Ht(t)-this._settings.constraint}px`,this.framePool.resizeHandler();else{const e=this._css.userProperties.colCount,A=this._css.userProperties.lineLength;this._css.resizeHandler(),(this._css.userProperties.view!=="scroll"&&e!==this._css.userProperties.colCount||A!==this._css.userProperties.lineLength)&&await this.commitCSS(this._css)}}get ownerWindow(){return this.container.ownerDocument.defaultView||window}get _cframes(){return this.framePool.currentFrames}get pool(){return this.framePool}eventListener(t,e){var A,i,r,s,o,a;switch(t){case"_pong":this.listeners.frameLoaded(this._cframes[0].iframe.contentWindow),this.listeners.positionChanged(this.currentLocation);break;case"first_visible_locator":const l=Lt.deserialize(e);if(!l)break;this.currentLocation=new Lt({href:this.currentLocation.href,type:this.currentLocation.type,title:this.currentLocation.title,locations:l==null?void 0:l.locations,text:l==null?void 0:l.text}),this.listeners.positionChanged(this.currentLocation);break;case"text_selected":this.listeners.textSelected(e);break;case"click":case"tap":const h=e;if(h.interactiveElement){const c=new DOMParser().parseFromString(h.interactiveElement,"text/html").body.children[0];if(c.nodeType===c.ELEMENT_NODE&&c.nodeName==="A"&&c.hasAttribute("href")){const g=(A=c.attributes.getNamedItem("href"))==null?void 0:A.value;if(g.startsWith("#"))this.go(this.currentLocation.copyWithLocations({fragments:[g.substring(1)]}),!1,()=>{});else if(g.startsWith("http://")||g.startsWith("https://")||g.startsWith("mailto:")||g.startsWith("tel:"))this.listeners.handleLocator(new wt({href:g}).locator);else try{this.goLink(new wt({href:vA.join(vA.dirname(this.currentLocation.href),g)}),!1,()=>{})}catch(m){console.warn(`Couldn't go to link for ${g}: ${m}`),this.listeners.handleLocator(new wt({href:g}).locator)}}else console.log("Clicked on",c)}else{if(this.layout===p.fixed&&this.framePool.doNotDisturb&&(h.doNotDisturb=!0),this.layout===p.fixed&&(this.currentProgression===w.rtl||this.currentProgression===w.ltr)&&this.framePool.currentFrames.length>1){const m=this.framePool.currentFrames;h.targetFrameSrc===((i=m[this.currentProgression===w.rtl?0:1])==null?void 0:i.source)&&(h.x+=(((s=(r=m[this.currentProgression===w.rtl?1:0])==null?void 0:r.iframe.contentWindow)==null?void 0:s.innerWidth)??0)*window.devicePixelRatio)}if(t==="click"?this.listeners.click(h):this.listeners.tap(h))break;if(this.currentProgression===w.ttb||this.currentProgression===w.btt)return;const g=(this._cframes.length===2?this._cframes[0].window.innerWidth+this._cframes[1].window.innerWidth:this._cframes[0].window.innerWidth)*window.devicePixelRatio/4;h.x>=g&&h.x<=g*3&&this.listeners.miscPointer(1),h.x<g?this.goLeft(!1,()=>{}):h.x>g*3&&this.goRight(!1,()=>{})}break;case"tap_more":this.listeners.miscPointer(e);break;case"no_more":this.changeResource(1);break;case"no_less":this.changeResource(-1);break;case"swipe":break;case"zoom":this.listeners.zoom(e);break;case"progress":this.syncLocation(e);break;case"log":console.log((a=(o=this._cframes[0])==null?void 0:o.source)==null?void 0:a.split("/")[3],...e);break;default:this.listeners.customEvent(t,e);break}}determineModules(){let t=Array.from(le.keys());return this.layout===p.fixed?t.filter(e=>ln.includes(e)):(t=t.filter(e=>hn.includes(e)),this.readingProgression===w.ttb||this.readingProgression===w.btt?t=t.filter(e=>e!=="column_snapper"):t=t.filter(e=>e!=="scroll_snapper"),t)}attachListener(){const t=this._cframes.filter(e=>!!e);if(t.length===0)throw Error("no cframe to attach listener to");t.forEach(e=>{e.msg&&(e.msg.listener=(A,i)=>{this.eventListener(A,i)})})}async apply(){if(await this.framePool.update(this.pub,this.currentLocator,this.determineModules()),this.attachListener(),this.pub.readingOrder.findIndexWithHref(this.currentLocation.href)<0)throw Error("Link for "+this.currentLocation.href+" not found!")}async destroy(){var t;await((t=this.framePool)==null?void 0:t.destroy())}async changeResource(t){var i,r;if(t===0)return!1;if(this.layout===p.fixed){const s=this.framePool,o=s.viewport.positions[0];if(t===1){if(!s.next(s.perPage))return!1}else if(t===-1){if(!s.prev(s.perPage))return!1}else throw Error("Invalid relative value for FXL");const a=s.viewport.positions[0];if(o>a){for(let l=this.positions.length-1;l>=0;l--)if(this.positions[l].href===this.pub.readingOrder.items[a-1].href){this.currentLocation=this.positions[l].copyWithLocations({progression:.999999999999});break}}else if(o<a){for(let l=0;l<this.positions.length;l++)if(this.positions[l].href===this.pub.readingOrder.items[a-1].href){this.currentLocation=this.positions[l];break}}return await this.apply(),!0}const e=this.pub.readingOrder.findIndexWithHref(this.currentLocation.href),A=Math.max(0,Math.min(this.pub.readingOrder.items.length-1,e+t));if(A===e)return(r=(i=this._cframes[0])==null?void 0:i.msg)==null||r.send("shake",void 0,async s=>{}),!1;if(e>A){for(let s=this.positions.length-1;s>=0;s--)if(this.positions[s].href===this.pub.readingOrder.items[A].href){this.currentLocation=this.positions[s].copyWithLocations({progression:.999999999999});break}}else for(let s=0;s<this.positions.length;s++)if(this.positions[s].href===this.pub.readingOrder.items[A].href){this.currentLocation=this.positions[s];break}return await this.apply(),!0}findLastPositionInProgressionRange(t,e){const A=t.findLastIndex(i=>{const r=i.locations.progression;return!!(r&&r>e.start&&r<=e.end)});return A!==-1?t[A]:void 0}findNearestPositions(t){const e=this.positions.filter(r=>r.href===this.currentLocation.href);let A=this.currentLocation,i;return e.some((r,s)=>{const o=r.locations.progression??0;if(t.start<=o){A=r;const a=e.splice(s+1,e.length);return i=this.findLastPositionInProgressionRange(a,t),!0}else return!1}),{first:A,last:i}}updateViewport(t){var e,A,i;this.reflowViewport.readingOrder=[],this.reflowViewport.progressions.clear(),this.reflowViewport.positions=null,this.currentLocation&&(this.reflowViewport.readingOrder.push(this.currentLocation.href),this.reflowViewport.progressions.set(this.currentLocation.href,t),((e=this.currentLocation.locations)==null?void 0:e.position)!==void 0&&(this.reflowViewport.positions=[this.currentLocation.locations.position],((i=(A=this.lastLocationInView)==null?void 0:A.locations)==null?void 0:i.position)!==void 0&&this.reflowViewport.positions.push(this.lastLocationInView.locations.position)))}async syncLocation(t){const e=t,A=this.findNearestPositions(e);this.currentLocation=A.first.copyWithLocations({progression:e.start}),this.lastLocationInView=A.last,this.updateViewport(e),this.listeners.positionChanged(this.currentLocation),await this.framePool.update(this.pub,this.currentLocation,this.determineModules())}goBackward(t,e){var A,i;this.layout===p.fixed?(this.changeResource(-1),e(!0)):(i=(A=this._cframes[0])==null?void 0:A.msg)==null||i.send("go_prev",void 0,async r=>{e(r?!0:await this.changeResource(-1))})}goForward(t,e){var A,i;this.layout===p.fixed?(this.changeResource(1),e(!0)):(i=(A=this._cframes[0])==null?void 0:A.msg)==null||i.send("go_next",void 0,async r=>{e(r?!0:await this.changeResource(1))})}get currentLocator(){return this.currentLocation}get viewport(){return this.layout===p.fixed?this.framePool.viewport:this.reflowViewport}get isScrollStart(){const t=this.viewport.readingOrder[0],e=this.viewport.progressions.get(t);return(e==null?void 0:e.start)===0}get isScrollEnd(){const t=this.viewport.readingOrder[this.viewport.readingOrder.length-1],e=this.viewport.progressions.get(t);return(e==null?void 0:e.end)===1}get canGoBackward(){var e,A;const t=(e=this.pub.readingOrder.items[0])==null?void 0:e.href;return this.viewport.progressions.has(t)&&((A=this.viewport.progressions.get(t))==null?void 0:A.start)===0}get canGoForward(){var e,A;const t=(e=this.pub.readingOrder.items[this.pub.readingOrder.items.length-1])==null?void 0:e.href;return this.viewport.progressions.has(t)&&((A=this.viewport.progressions.get(t))==null?void 0:A.end)===1}get readingProgression(){return this.currentProgression}async setReadingProgression(t){this.currentProgression===t||!this.framePool||(this.currentProgression=t,await this.framePool.update(this.pub,this.currentLocator,this.determineModules(),!0),this.attachListener())}get publication(){return this.pub}async loadLocator(t,e){var a,l;let A=!1,i=typeof t.locations.getCssSelector=="function"&&t.locations.getCssSelector();if((a=t.text)!=null&&a.highlight?A=await new Promise((h,c)=>{var g,m;this._cframes[0].msg.send("go_text",i?[(g=t.text)==null?void 0:g.serialize(),i]:(m=t.text)==null?void 0:m.serialize(),M=>h(M))}):i&&(A=await new Promise((h,c)=>{this._cframes[0].msg.send("go_text",["",i],g=>h(g))})),A){e(A);return}const r=typeof t.locations.htmlId=="function"&&t.locations.htmlId();if(r&&(A=await new Promise((h,c)=>{this._cframes[0].msg.send("go_id",r,g=>h(g))})),A){e(A);return}const s=(l=t==null?void 0:t.locations)==null?void 0:l.progression;s&&s>0?A=await new Promise((h,c)=>{this._cframes[0].msg.send("go_progression",s,g=>h(g))}):A=!0,e(A)}go(t,e,A){const i=t.href.split("#")[0];let r=this.pub.readingOrder.findWithHref(i);if(!r)return A(this.listeners.handleLocator(t));this.currentLocation=this.positions.find(s=>s.href===r.href),this.apply().then(()=>this.loadLocator(t,s=>A(s))).then(()=>{this.attachListener()})}goLink(t,e,A){return this.go(t.locator,e,A)}}class yn{constructor(t){var e;this.sourceNode=null,this.listeners={},this.isMutedValue=!1,this.isPlayingValue=!1,this.isPausedValue=!1,this.isLoadingValue=!1,this.isLoadedValue=!1,this.isEndedValue=!1,this.playback=t.playback,this.audioContext=t.audioContext,this.gainNode=(e=this.audioContext)==null?void 0:e.createGain(),this.setVolume(this.playback.state.volume),this.mediaElement=document.createElement("audio"),this.mediaElement.crossOrigin="use-credentials",this.mediaElement.addEventListener("canplaythrough",this.onCanPlayThrough.bind(this)),this.mediaElement.addEventListener("timeupdate",this.onTimeUpdate.bind(this)),this.mediaElement.addEventListener("error",this.onError.bind(this)),this.mediaElement.addEventListener("ended",this.onEnded.bind(this)),this.mediaElement.currentTime=this.playback.state.currentTime}on(t,e){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e)}off(t,e){this.listeners[t]&&(this.listeners[t]=this.listeners[t].filter(A=>A!==e))}loadAudio(t){this.isLoadingValue=!0,this.mediaElement.src=t,this.mediaElement.load(),this.sourceNode||(this.sourceNode=new MediaElementAudioSourceNode(this.audioContext,{mediaElement:this.mediaElement}),this.sourceNode.connect(this.gainNode),this.gainNode.connect(this.audioContext.destination))}async ensureAudioContextRunning(){this.audioContext.state==="suspended"&&await this.audioContext.resume()}onTimeUpdate(){this.emit("timeupdate",this.mediaElement.currentTime)}onCanPlayThrough(){this.isLoadingValue=!1,this.isLoadedValue=!0,this.emit("canplaythrough",null)}onError(){console.error("Error loading media element"),this.emit("error",this.mediaElement.error)}onEnded(){this.isPlayingValue=!1,this.isPausedValue=!1,this.isEndedValue=!0,this.emit("ended",null)}emit(t,e){this.listeners[t]&&this.listeners[t].forEach(A=>A(e))}async playLocator(t,e){}async play(){if(await this.ensureAudioContextRunning(),this.isPlayingValue){this.stop(),console.error("Audio is already playing");return}try{await this.mediaElement.play(),this.isPlayingValue=!0,this.isPausedValue=!1}catch(t){console.error("error trying to play media element",t)}}pause(){this.mediaElement.pause(),this.isPlayingValue=!1,this.isPausedValue=!0}stop(){this.mediaElement.pause(),this.mediaElement.currentTime=0,this.isPlayingValue=!1,this.isPausedValue=!1}setVolume(t){if(t<0){this.gainNode.gain.value=0,this.isMutedValue=!0;return}if(t>1){this.setVolume(t/100);return}this.gainNode.gain.value=t}skip(t){if(!this.mediaElement){console.error("Audio not loaded");return}const e=this.mediaElement.currentTime+t;e<0?this.mediaElement.currentTime=0:e>this.mediaElement.duration?this.mediaElement.currentTime=this.mediaElement.duration:this.mediaElement.currentTime=e}currentTime(){return this.mediaElement.currentTime}duration(){return this.mediaElement.duration}isPlaying(){return this.isPlayingValue}isPaused(){return this.isPausedValue}isStopped(){return!1}isLoading(){return this.isLoadingValue}isLoaded(){return this.isLoadedValue}isEnded(){return this.isEndedValue}isMuted(){return this.isMutedValue}}E.BooleanPreference=W,E.EnumPreference=Gt,E.EpubDefaults=bA,E.EpubNavigator=me,E.EpubPreferences=ft,E.EpubPreferencesEditor=ge,E.EpubSettings=de,E.FXLCoordinator=YA,E.FXLFrameManager=RA,E.FXLFramePoolManager=PA,E.FXLPeripherals=xA,E.FXLSpreader=TA,E.FrameComms=bt,E.FrameManager=FA,E.FramePoolManager=CA,E.HorizontalThird=QA,E.LayoutStrategy=C,E.LineLengths=ct,E.Navigator=Qe,E.Preference=N,E.RSProperties=HA,E.RangePreference=x,E.ReadiumCSS=kA,E.TextAlignment=dt,E.Theme=Ut,E.UserProperties=ue,E.VerticalThird=zA,E.VisualNavigator=ze,E.WebAudioEngine=yn,E.fontSizeRangeConfig=yt,E.fontWeightRangeConfig=Ct,E.fontWidthRangeConfig=Rt,E.sML=Ft,E.sMLWithRequest=X,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})});