From 07d780eedb2e9ed9e576a18f3b9d55ebd7766c68 Mon Sep 17 00:00:00 2001 From: troyeguo Date: Sat, 29 Jul 2023 11:45:28 +0800 Subject: [PATCH] fix bug --- public/lib/kookit/kookit.min.js | 6 +- src/assets/locales/cn/translation.json | 6 +- src/assets/locales/en/translation.json | 6 +- src/components/bookCardItem/component.tsx | 6 +- src/components/bookCardItem/index.tsx | 2 + src/components/bookCardItem/interface.tsx | 2 + src/components/bookCoverItem/component.tsx | 6 ++ src/components/bookCoverItem/index.tsx | 2 + src/components/bookCoverItem/interface.tsx | 2 + .../dialogs/actionDialog/component.tsx | 5 +- src/components/popups/popupMenu/component.tsx | 17 +++-- src/components/selectBook/component.tsx | 67 +++++++++++++++++++ src/containers/htmlViewer/component.tsx | 6 +- .../lists/contentList/component.tsx | 4 +- .../panels/progressPanel/component.tsx | 2 +- src/model/HtmlBook.ts | 8 +-- src/utils/readUtils/linkUtil.tsx | 4 +- src/utils/readUtils/sortUtil.tsx | 3 +- 18 files changed, 125 insertions(+), 29 deletions(-) diff --git a/public/lib/kookit/kookit.min.js b/public/lib/kookit/kookit.min.js index 30e7fe2e9f..8ae47404f3 100644 --- a/public/lib/kookit/kookit.min.js +++ b/public/lib/kookit/kookit.min.js @@ -1,9 +1,9 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Kookit={})}(this,function(e){"use strict";function g(e,o,a,l){return new(a=a||Promise)(function(i,t){function r(e){try{s(l.next(e))}catch(e){t(e)}}function n(e){try{s(l.throw(e))}catch(e){t(e)}}function s(e){var t;e.done?i(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(r,n)}s((l=l.apply(e,o||[])).next())})}const y=e=>e?parseFloat(e+""):0,p=i=>g(void 0,void 0,void 0,function*(){let t="";if(i.load){let e=yield fetch(yield i.load()).then(e=>e.blob());t=yield e.text()}return i.loadAsset&&(t=yield r(t,i.loadAsset)),n(t)}),h=e=>Array.from(e.querySelectorAll("img, image")),r=(r,n)=>g(void 0,void 0,void 0,function*(){let e=(new DOMParser).parseFromString(r,"text/html"),t=h(e);for(let e=0;eg(void 0,void 0,void 0,function*(){e.getAttribute("href")&&(e.href=yield n(e.getAttribute("href")))})),e.documentElement.innerHTML}),n=e=>{var t=(new DOMParser).parseFromString(e,"text/html");let i=h(t);if(0===i.length)return e;for(let e=0;e{var i=document.createElement("iframe");i.style.width="100%",i.style.border="0",i.style.margin="0",i.style.padding="0",i.style.minHeight="calc(100% - 2px)",i.style.fontSize="100%",i.style.font="inherit",i.scrolling="no",i.tabIndex=0,i.style.verticalAlign="baseline",e.innerHTML="",e.appendChild(i)},l=i=>g(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){t=t.contentDocument;if(t)return 1===parseInt(t.body.scrollWidth/t.body.clientWidth+"")&&(yield new Promise(e=>setTimeout(e,1e3))),{totalPage:"scroll"===i?1:parseInt(t.body.scrollWidth/t.body.clientWidth+"")+1,currentPage:parseInt(y(t.body.scrollLeft)/t.body.clientWidth+"")+1}}}}),m=()=>{let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;if(e){var i=e.querySelectorAll("a, article, cite, code, div, li, p, pre, span, table");for(let e=0;e{let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;if(e){var s,t=Math.floor(i.clientWidth/12),o=t%2==0?t:t-1;for(s of e.querySelectorAll("img, image")){var a=s.parentElement;let e=0,t=0;n.startsWith("CB")&&"scroll"===r?t=a.offsetWidth:n.startsWith("CB")&&"single"===r?(e=i.clientHeight,t=i.clientWidth):s.width&&s.height?s.height/s.width>a.clientHeight/a.clientWidth?(e=a.clientHeight,t=e*s.width/s.height):(t=a.clientWidth,e=t*s.height/s.width):e=a&&a.clientWidth&&0{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){let t=n.contentDocument;if(t){let e=t.createElement("style");e.id="default-style",e.textContent="p,empty-line{display: inherit;margin-block-start: inherit;margin-block-end: inherit;margin-inline-start: inherit;margin-inline-end: inherit;}body{margin: 0px}",t.head.appendChild(e),"scroll"!==r&&(n="double"===r?2:1,r=(r=Math.floor(i.clientWidth/12))%2==0?r:r-1,t.body.setAttribute("style",`width: auto;height: 100%;overflow-y: hidden;overflow-X: hidden;padding-left: 0px;padding-right: 0px;margin: 0px;box-sizing: border-box;max-width: inherit;column-fill: auto;column-gap: ${r}px;column-count: 12;column-width: ${(i.clientWidth-r)/n}px;`))}}}};class d{constructor(e){this.book=e,this.chapterList=[],this.flattenChapters=[],this.chapterDocList=[]}getChapter(e){return g(this,void 0,void 0,function*(){return this.chapterList=e?yield Promise.all(e.map(t=>g(this,void 0,void 0,function*(){var e=t.href&&(yield this.book.resolveHref(t.href))?(yield this.book.resolveHref(t.href)).index:-1;return{title:t.label||e,href:t.href,index:e,subitems:t.subitems?yield this.getChapter(t.subitems):[]}}))):yield Promise.all(this.book.sections.map((e,t)=>g(this,void 0,void 0,function*(){return{title:e.label||t,href:e.href||"",index:t,subitems:e.subitems?yield this.getChapter(e.subitems):[]}}))),this.flattenChapters=this.flatChapter(this.chapterList),this.chapterList})}getChapterDoc(){return g(this,void 0,void 0,function*(){const i=this.flattenChapters.map(e=>e.index);return this.book.sections.map((e,t)=>-1"no"!==e.text.linear)})}flatChapter(t){let i=[];for(let e=0;eg(this,void 0,void 0,function*(){const t=this.book.metadata;try{var i=yield this.book.getCover(),e=new FileReader;e.readAsDataURL(i),e.onloadend=()=>{r({name:t.title,author:t.author?t.author[0].name:"",description:t.description,publisher:t.publisher,cover:e.result})}}catch(e){i=t.author&&t.author[0]&&t.author[0].name?t.author[0].name:t.author&&t.author[0]?t.author[0]:t.author||"";r({name:t.title,author:i,description:t.description,publisher:t.publisher,cover:""})}}))}}const i=(e,r)=>e.map((e,t,i)=>r(e,t,i)?t:null).filter(e=>null!=e),a=(r,e)=>[-1,...e,r.length].reduce(({xs:e,a:t},i)=>({xs:e?.concat([r.slice(t+1,i)])??[],a:i}),{}).xs,c=(e,t)=>e.slice(0,-1).concat([e[e.length-1].concat(t[0])]).concat(t.slice(1)),u=/\d/,f=/^epubcfi\((.*)\)$/,v=e=>e.replace(/[\^[\](),;=]/g,"^$&"),t=e=>f.test(e)?e:`epubcfi(${e})`,w=(e,t)=>i(e,([e])=>e===t),x=e=>{const t=[];let i;for(var[r,n]of e){if("/"===r)t.push({index:n});else{const s=t[t.length-1];if(":"===r)s.offset=n;else if("~"===r)s.temporal=n;else if("@"===r)s.spatial=(s.spatial??[]).concat(n);else if(";s"===r)s.side=n;else if("["===r){if("/"!==i||!n){s.text=(s.text??[]).concat(n);continue}s.id=n}}i=r}return t},C=e=>a(e,w(e,"!")).map(x),k=e=>{var t=(e=>{const t=[];let i,r,n="";var s=e=>(t.push(e),i=null,n=""),o=e=>(n+=e,r=!1);for(const a of Array.from(e.trim()).concat(""))if("^"!==a||r){if("!"===i)s(["!"]);else if(","===i)s([","]);else if("/"===i||":"===i){if(u.test(a)){o(a);continue}s([i,parseInt(n)])}else if("~"===i){if(u.test(a)||"."===a){o(a);continue}s(["~",parseFloat(n)])}else if("@"===i){if(":"===a){s(["@",parseFloat(n)]),i="@";continue}if(u.test(a)||"."===a){o(a);continue}s(["@",parseFloat(n)])}else{if("["===i){";"!==a||r?","!==a||r?"]"!==a||r?o(a):s(["[",n]):(s(["[",n]),i="["):(s(["[",n]),i=";");continue}if(i?.startsWith(";")){"="!==a||r?";"!==a||r?"]"!==a||r?o(a):s([i,n]):(s([i,n]),i=";"):(i=`;${n}`,n="");continue}}"/"!==a&&":"!==a&&"~"!==a&&"@"!==a&&"["!==a&&"!"!==a&&","!==a||(i=a)}else r=!0;return t})((i=e).match(f)?.[1]??i),e=w(t,",");if(!e.length)return C(t);var[i,t,e]=a(t,e).map(C);return{parent:i,start:t,end:e}},T=({index:e,id:t,offset:i,temporal:r,spatial:n,text:s,side:o})=>{var a=o?`;s=${o}`:"";return`/${e}`+(t?`[${v(t)}${a}]`:"")+(null!=i&&e%2?`:${i}`:"")+(r?`~${r}`:"")+(n?`@${n.join(":")}`:"")+(s||!t&&o?"["+(s?.map(v)?.join(",")??"")+a+"]":"")},L=e=>e.parent?[e.parent,e.start,e.end].map(L).join(","):e.map(e=>e.map(T).join("")).join("!"),S=e=>t(L(e)),A=(e,t)=>"string"==typeof e?S(A(k(e),t)):e.parent?c(e.parent,e[t?"end":"start"]):e,B=({nodeType:e})=>3===e||4===e,E=({nodeType:e})=>1===e,I=e=>{const t=Array.from(e.childNodes).filter(e=>B(e)||E(e)).reduce((e,t)=>{let i=e[e.length-1];return i?B(t)?Array.isArray(i)?i.push(t):B(i)?e[e.length-1]=[i,t]:e.push(t):E(i)?e.push(null,t):e.push(t):e.push(t),e},[]);return E(t[0])&&t.unshift("first"),E(t[t.length-1])&&t.push("last"),t.unshift("before"),t.push("after"),t},M=(e,t)=>e?I(e)[t]:null,D=(e,t)=>{var i,r=t[t.length-1]["id"];if(r){r=e.ownerDocument.getElementById(r);if(r)return{node:r,offset:0}}for({index:i}of t){var n=M(e,i);if("first"===n)return{node:e.firstChild??e};if("last"===n)return{node:e.lastChild??e};if("before"===n)return{node:e,before:!0};if("after"===n)return{node:e,after:!0};e=n}var s=t[t.length-1]["offset"];if(!Array.isArray(e))return{node:e,offset:s};let o=0;for(const l of e){var a=l.nodeValue["length"];if(o+a>=s)return{node:l,offset:s-o};o+=a}},R=(t,i)=>{var{parentNode:e,id:r}=t;const n=I(e);var s=n.findIndex(e=>Array.isArray(e)?e.some(e=>e===t):e===t),o=n[s];if(Array.isArray(o)){let e=0;for(const a of o){if(a===t){e+=i;break}e+=a.nodeValue.length}i=e}s={id:r,index:s,offset:i};return e!==t.ownerDocument.documentElement?R(e).concat(s):[s]},N=(e,t)=>D(e.documentElement,A(t)).node,O={CONTAINER:"urn:oasis:names:tc:opendocument:xmlns:container",XHTML:"http://www.w3.org/1999/xhtml",OPF:"http://www.idpf.org/2007/opf",EPUB:"http://www.idpf.org/2007/ops",DC:"http://purl.org/dc/elements/1.1/",DCTERMS:"http://purl.org/dc/terms/",ENC:"http://www.w3.org/2001/04/xmlenc#",NCX:"http://www.daisy.org/z3986/2005/ncx/",XLINK:"http://www.w3.org/1999/xlink",SMIL:"http://www.w3.org/ns/SMIL"},H={XML:"application/xml",NCX:"application/x-dtbncx+xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml",JS:/\/(x-)?(javascript|ecmascript)/},$=e=>e.toLowerCase().replace(/[-:](.)/g,(e,t)=>t.toUpperCase()),F=e=>e?e.trim().replace(/\s{2,}/g," "):"",U=(t,i,e)=>e?e=>e.getAttribute(t)?.split(/\s/)?.includes(i):"function"==typeof i?e=>i(e.getAttribute(t)):e=>e.getAttribute(t)===i,P=(...e)=>t=>t?Object.fromEntries(e.map(e=>[$(e),t.getAttribute(e)])):null,z=e=>F(e?.textContent),j=(e,i)=>{e=e.lookupNamespaceURI(null)===i||e.lookupPrefix(i);const r=e?(e,t)=>e=>e.namespaceURI===i&&e.localName===t:(e,t)=>e=>e.localName===t;return{$:(e,t)=>[...e.children].find(r(e,t)),$$:(e,t)=>[...e.children].filter(r(e,t)),$$$:e?(e,t)=>[...e.getElementsByTagNameNS(i,t)]:(e,t)=>[...e.getElementsByTagName(i,t)]}},W=(t,e)=>{try{if(e.includes(":"))return new URL(t,e);var i="whatever://whatever/";return decodeURI(new URL(t,i+e).href.replace(i,""))}catch(e){return console.warn(e),t}},X=e=>/^(?!blob)\w+:/i.test(e),q=async(e,t,i)=>{const r=[];e.replace(t,(...e)=>(r.push(e),null));const n=[];for(const s of r)n.push(await i(...s));return e.replace(t,()=>n.shift())},K=e=>e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&");var J={attrs:["dir","xml:lang"]},G={name:"alternate-script",many:!0,...J,props:["file-as"]},Z={many:!0,...J,props:[{name:"role",many:!0,attrs:["scheme"]},"file-as",G]};const _=[{name:"title",many:!0,...J,props:["title-type","display-seq","file-as",G]},{name:"identifier",many:!0,props:[{name:"identifier-type",attrs:["scheme"]}]},{name:"language",many:!0},{name:"creator",...Z},{name:"contributor",...Z},{name:"publisher",...J,props:["file-as",G]},{name:"description",...J,props:[G]},{name:"rights",...J,props:[G]},{name:"date"},{name:"dcterms:modified",type:"meta"},{name:"subject",many:!0,...J,props:["term","authority",G]},{name:"belongs-to-collection",type:"meta",many:!0,...J,props:["collection-type","group-position","dcterms:identifier","file-as",G,{name:"belongs-to-collection",recursive:!0}]}],V=(e,s=e=>e)=>{const{$:o,$$:i,$$$:t}=j(e,O.XHTML),r=n=>e=>{const t=o(e,"a")??o(e,"span");var i=o(e,"ol"),e=(e=t?.getAttribute("href"))?decodeURI(s(e)):null;const r={label:z(t)||t?.getAttribute("title"),href:e,subitems:a(i)};return n&&(r.type=t?.getAttributeNS(O.EPUB,"type")?.split(/\s/)),r},a=(e,t)=>e?i(e,"li").map(r(t)):null;var n=(e,t)=>a(o(e,"ol"),t);let l=null,c=null,h=null,d=[];for(const u of t(e,"nav")){const f=u.getAttributeNS(O.EPUB,"type")?.split(/\s/)??[];f.includes("toc")?l??=n(u):f.includes("page-list")?c??=n(u):f.includes("landmarks")?h??=n(u,!0):d.push({label:z(u.firstElementChild),type:f,list:n(u)})}return{toc:l,pageList:c,landmarks:h,others:d}},Y=(i,s=e=>e)=>{const{$:o,$$:a}=j(i,O.NCX),l=e=>{var t=o(e,"navLabel");const i=o(e,"content");var r=z(t),t=(t=i.getAttribute("src"))?decodeURI(s(t)):null;if("navPoint"!==e.localName)return{label:r,href:t};{const n=a(e,"navPoint");return{label:r,href:t,subitems:n.length?n.map(l):null}}},r=(e,t)=>a(e,t).map(l);var e=(e,t)=>{e=o(i.documentElement,e);return e?r(e,t):null};return{toc:e("navMap","navPoint"),pageList:e("pageList","pageTarget"),others:a(i.documentElement,"navList").map(e=>({label:z(o(e,"navLabel")),list:r(e,"navTarget")}))}},Q=e=>{if(e){var t=e.split(":").map(e=>parseFloat(e));if(3===t.length){var[i,r,n]=t;return 60*i*60+60*r+n}if(2===t.length){var[t,s]=t;return 60*t+s}var[s,e]=e.split(/(?=[^\d.])/);return parseFloat(s)*("h"===e?3600:"min"===e?60:"ms"===e?.001:1)}},ee=(e,r=e=>e)=>{const{$:n,$$$:t}=j(e,O.SMIL);return t(e,"par").map(e=>{var t=n(e,"text")?.getAttribute("src")?.split("#")?.[1];const i=n(e,"audio");return i?{id:t,audio:{src:(e=i.getAttribute("src"))?decodeURI(r(e)):null,clipBegin:Q(i.getAttribute("clipBegin")),clipEnd:Q(i.getAttribute("clipEnd"))}}:{id:t}})},te=/([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/,ie=e=>z(e.getElementById(e.documentElement.getAttribute("unique-identifier"))??e.getElementsByTagNameNS(O.DC,"identifier")[0]),re=async(e,t,i)=>{const r=new Uint8Array(await i.slice(0,t).arrayBuffer());t=Math.min(t,r.length);for(var n=0;n{e=(new TextEncoder).encode(e),e=await globalThis.crypto.subtle.digest("SHA-1",e);return new Uint8Array(e)})=>({"http://www.idpf.org/2008/embedding":{key:e=>t(ie(e).replaceAll(/[\u0020\u0009\u000d\u000a]/g,"")),decode:(e,t)=>re(e,1040,t)},"http://ns.adobe.com/pdf/enc#RC":{key:e=>{const i=(e=>{for(const i of e.getElementsByTagNameNS(O.DC,"identifier")){var[t]=z(i).split(":").slice(-1);if(te.test(t))return t}return""})(e).replaceAll("-","");return Uint8Array.from({length:16},(e,t)=>parseInt(i.slice(2*t,2*t+2),16))},decode:(e,t)=>re(e,1024,t)}});class se{#uris=new Map;#decoders=new Map;#algorithms;constructor(e){this.#algorithms=e}async init(e,t){var i,r;if(e)for({algorithm:i,uri:r}of Array.from(e.getElementsByTagNameNS(O.ENC,"EncryptedData"),e=>({algorithm:e.getElementsByTagNameNS(O.ENC,"EncryptionMethod")[0]?.getAttribute("Algorithm"),uri:e.getElementsByTagNameNS(O.ENC,"CipherReference")[0]?.getAttribute("URI")}))){if(!this.#decoders.has(i)){const n=this.#algorithms[i];if(!n){console.warn("Unknown encryption algorithm");continue}const s=await n.key(t);this.#decoders.set(i,e=>n.decode(s,e))}this.#uris.set(r,i)}}getDecoder(e){return this.#decoders.get(this.#uris.get(e))??(e=>e)}}class oe{constructor({opf:e,resolveHref:r}){this.opf=e;const{$:t,$$:i,$$$:n}=j(e,O.OPF);var s=t(e.documentElement,"manifest");const o=t(e.documentElement,"spine"),a=i(o,"itemref");this.manifest=i(s,"item").map(P("href","id","media-type","properties","media-overlay")).map(e=>(e.href=r(e.href),e.properties=e.properties?.split(/\s/),e)),this.spine=a.map(P("idref","id","linear","properties")).map(e=>(e.properties=e.properties?.split(/\s/),e)),this.pageProgressionDirection=o.getAttribute("page-progression-direction"),this.navPath=this.getItemByProperty("nav")?.href,this.ncxPath=(this.getItemByID(o.getAttribute("toc"))??this.manifest.find(e=>e.mediaType===H.NCX))?.href;s=t(e.documentElement,"guide");s&&(this.guide=i(s,"reference").map(P("type","title","href")).map(({type:e,title:t,href:i})=>({label:t,type:e.split(/\s/),href:r(i)}))),this.cover=this.getItemByProperty("cover-image")??this.getItemByID(n(e,"meta").find(U("name","cover"))?.getAttribute("content"))??this.getItemByHref(this.guide?.find(e=>e.type.includes("cover"))?.href),this.cfis=(e=>{const t=[];var i,r,n=e[0]["parentNode"];const s=R(n);for([i,r]of I(n).entries()){var o=e[t.length];r===o&&t.push(S([s.concat({id:o.id,index:i})]))}return t})(a)}getItemByID(t){return this.manifest.find(e=>e.id===t)}getItemByHref(t){return this.manifest.find(e=>e.href===t)}getItemByProperty(t){return this.manifest.find(e=>e.properties?.includes(t))}resolveCFI(e){const t=k(e),i=(t.parent??t).shift();let r=N(this.opf,i);r&&"idref"!==r.nodeName&&(i.at(-1).id=null,r=N(this.opf,i));const n=r?.getAttribute("idref");return{index:this.spine.findIndex(e=>e.idref===n),anchor:e=>((e,t)=>{var i=A(t),r=A(t,!0),t=e.documentElement,i=D(t,i[0]),r=D(t,r[0]);const n=e.createRange();return i.before?n.setStartBefore(i.node):i.after?n.setStartAfter(i.node):n.setStart(i.node,i.offset),r.before?n.setEndBefore(r.node):r.after?n.setEndAfter(r.node):n.setEnd(r.node,r.offset),n})(e,t)}}}class ae{#cache=new Map;#children=new Map;#refCount=new Map;allowScript=!1;constructor({loadText:e,loadBlob:t,resources:i}){this.loadText=e,this.loadBlob=t,this.manifest=i.manifest,this.assets=i.manifest}createURL(e,t,i,r){if(!t)return"";i=URL.createObjectURL(new Blob([t],{type:i}));if(this.#cache.set(e,i),this.#refCount.set(e,1),r){const n=this.#children.get(r);n?n.push(e):this.#children.set(r,[e])}return i}ref(e,t){const i=this.#children.get(t);return i?.includes(e)||(this.#refCount.set(e,this.#refCount.get(e)+1),i?i.push(e):this.#children.set(t,[e])),this.#cache.get(e)}unref(e){if(this.#refCount.has(e)){var t=this.#refCount.get(e)-1;if(t<1){URL.revokeObjectURL(this.#cache.get(e)),this.#cache.delete(e),this.#refCount.delete(e);const i=this.#children.get(e);if(i)for(;i.length;)this.unref(i.pop());this.#children.delete(e)}else this.#refCount.set(e,t)}}async loadItem(e,t=[]){if(!e)return null;const{href:i,mediaType:r}=e;var n=H.JS.test(e.mediaType);if(n&&!this.allowScript)return null;var s=t.at(-1);return this.#cache.has(i)?this.ref(i,s):(n||[H.XHTML,H.HTML,H.CSS,H.SVG].includes(r))&&t.every(e=>e!==i)?this.loadReplaced(e,t):this.createURL(i,await this.loadBlob(i),r,s)}async loadHref(e,t,i=[]){if(X(e))return e;const r=W(e,t);var n=this.manifest.find(e=>e.href===r);return n?this.loadItem(n,i.concat(t)):e}async loadReplaced(e,n=[]){const{href:s,mediaType:i}=e;var r,o=n.at(-1),a=await this.loadText(s);if(!a)return null;if([H.XHTML,H.HTML,H.SVG].includes(i)){let t=(new DOMParser).parseFromString(a,i);if(i===H.XHTML&&t.querySelector("parsererror")&&(console.warn(t.querySelector("parsererror").innerText),e.mediaType=H.HTML,t=(new DOMParser).parseFromString(a,e.mediaType)),[H.XHTML,H.SVG].includes(e.mediaType)){let e=t.firstChild;for(;e instanceof ProcessingInstruction;)e.data&&(r=await q(e.data,/(?:^|\s*)(href\s*=\s*['"])([^'"]*)(['"])/i,(e,t,i,r)=>this.loadHref(i,s,n).then(e=>`${t}${e}${r}`)),e.replaceWith(t.createProcessingInstruction(e.target,r))),e=e.nextSibling}var l=async(e,t)=>e.setAttribute(t,await this.loadHref(e.getAttribute(t),s,n));for(const h of t.querySelectorAll("link[href]"))await l(h,"href");for(const d of t.querySelectorAll("[src]"))await l(d,"src");for(const u of t.querySelectorAll("[poster]"))await l(u,"poster");for(const f of t.querySelectorAll("object[data]"))await l(f,"data");for(const p of t.querySelectorAll("[*|href]:not([href]"))p.setAttributeNS(O.XLINK,"href",await this.loadHref(p.getAttributeNS(O.XLINK,"href"),s,n));for(const m of t.querySelectorAll("style"))m.textContent&&(m.textContent=await this.replaceCSS(m.textContent,s,n));for(const g of t.querySelectorAll("[style]"))g.setAttribute("style",await this.replaceCSS(g.getAttribute("style"),s,n));const c=(new XMLSerializer).serializeToString(t);return this.createURL(s,c,e.mediaType,o)}const c=i===H.CSS?await this.replaceCSS(a,s,n):await this.replaceString(a,s,n);return this.createURL(s,c,i,o)}async replaceCSS(e,i,r=[]){e=await q(e,/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,(e,t)=>this.loadHref(t,i,r).then(e=>`url("${e}")`));const t=await q(e,/@import\s*["']([^"'\n]*?)["']/gi,(e,t)=>this.loadHref(t,i,r).then(e=>`@import "${e}"`)),n=window?.innerWidth??800,s=window?.innerHeight??600;return t.replace(/-epub-/gi,"").replace(/(\d*\.?\d+)vw/gi,(e,t)=>parseFloat(t)*n/100+"px").replace(/(\d*\.?\d+)vh/gi,(e,t)=>parseFloat(t)*s/100+"px").replace(/page-break-(after|before|inside)/gi,(e,t)=>`-webkit-column-break-${t}`)}replaceString(e,o,t=[]){const a=new Map,i=this.assets.map(e=>{if(e.href!==o){var t=((e,t)=>{if(!e)return t;const i=e.replace(/\/$/,"").split("/"),r=t.replace(/\/$/,"").split("/");t=(i.length>r.length?i:r).findIndex((e,t)=>i[t]!==r[t]);return t<0?"":Array(i.length-t).fill("..").concat(r.slice(t)).join("/")})(o.slice(0,o.lastIndexOf("/")+1),e.href),i=encodeURI(t),r="/"+e.href,n=encodeURI(r),n=new Set([t,i,r,n]);for(const s of n)a.set(s,e);return Array.from(n)}}).flat().filter(e=>e);if(!i.length)return e;var r=new RegExp(i.map(K).join("|"),"g");return q(e,r,async e=>this.loadItem(a.get(e.replace(/^\//,"")),t.concat(o)))}unloadItem(e){this.unref(e?.href)}}class le{parser=new DOMParser;#encryption;constructor({loadText:e,loadBlob:t,getSize:i,sha1:r}){this.loadText=e,this.loadBlob=t,this.getSize=i,this.#encryption=new se(ne(r))}#parseXML(e){return e?this.parser.parseFromString(e,H.XML):null}async#loadXML(e){return this.#parseXML(await this.loadText(e))}async init(){const e=await this.#loadXML("META-INF/container.xml");if(!e)throw new Error("Failed to load container file");var t=Array.from(e.getElementsByTagNameNS(O.CONTAINER,"rootfile"),P("full-path","media-type")).filter(e=>"application/oebps-package+xml"===e.mediaType);if(!t.length)throw new Error("No package document defined in container");const i=t[0].fullPath;var r=await this.#loadXML(i);if(!r)throw new Error("Failed to load package document");t=await this.#loadXML("META-INF/encryption.xml");await this.#encryption.init(t,r),this.resources=new oe({opf:r,resolveHref:e=>W(e,i)});const s=new ae({loadText:this.loadText,loadBlob:e=>Promise.resolve(this.loadBlob(e)).then(this.#encryption.getDecoder(e)),resources:this.resources});this.sections=this.resources.spine.map((e,t)=>{var{idref:i,linear:r,properties:e=[]}=e;const n=this.resources.getItemByID(i);return n?{id:this.resources.getItemByID(i)?.href,load:()=>s.loadItem(n),unload:()=>s.unloadItem(n),createDocument:()=>this.loadDocument(n),size:this.getSize(n.href),cfi:this.resources.cfis[t],linear:r,pageSpread:(e=>{for(const t of e){if("page-spread-left"===t||"rendition:page-spread-left"===t)return"left";if("page-spread-right"===t||"rendition:page-spread-right"===t)return"right";if("rendition:page-spread-center"===t)return"center"}})(e),resolveHref:e=>W(e,n.href),loadMediaOverlay:()=>this.loadMediaOverlay(n)}:(console.warn(`Could not find item with ID "${i}" in manifest`),null)}).filter(e=>e);const{navPath:n,ncxPath:o}=this.resources;if(n)try{var a=V(await this.#loadXML(n),e=>W(e,n));this.toc=a.toc,this.pageList=a.pageList,this.landmarks=a.landmarks}catch(e){console.warn(e)}if(!this.toc&&o)try{var l=Y(await this.#loadXML(o),e=>W(e,o));this.toc=l.toc,this.pageList=l.pageList}catch(e){console.warn(e)}this.landmarks??=this.resources.guide;const{metadata:c,rendition:h,media:d}=(e=>{const{$:t,$$:i}=j(e,O.OPF),r=t(e.documentElement,"metadata"),s=Array.from(r.children),l=(o,t)=>{if(!t)return null;const{props:e=[],attrs:i=[]}=o,r=z(t);if(!e.length&&!i.length)return r;var n=t.getAttribute("id");const a=n?s.filter(U("refines","#"+n)):[];return Object.fromEntries([["value",r]].concat(e.map(e=>{var{many:t,recursive:i}=e,r="string"==typeof e?e:e.name,n=U("property",r);const s=i?o:e;return[$(r),t?a.filter(n).map(e=>l(s,e)):l(s,a.find(n))]})).concat(i.map(e=>[$(e),t.getAttribute(e)])))},o=s.filter(U("refines",null));e=t=>Object.fromEntries(i(r,"meta").filter(U("property",e=>e?.startsWith(t))).map(e=>[e.getAttribute("property").replace(t,""),z(e)]));return{metadata:Object.fromEntries(_.map(t=>{const{type:e,name:i,many:r}=t;var n="meta"===e?e=>e.namespaceURI===O.OPF&&e.getAttribute("property")===i:e=>e.namespaceURI===O.DC&&e.localName===i;return[$(i),r?o.filter(n).map(e=>l(t,e)):l(t,o.find(n))]})),rendition:e("rendition:"),media:e("media:")}})(r);this.rendition=h,this.media=d,d.duration=Q(d.duration),this.dir=this.resources.pageProgressionDirection,this.rawMetadata=c;l=c?.title?.[0];this.metadata={title:l?.value,sortAs:l?.fileAs,language:c?.language,identifier:ie(r),description:c?.description?.value,publisher:c?.publisher?.value,published:c?.date,modified:c?.dctermsModified,subject:c?.subject?.filter(({value:e,code:t})=>e||t)?.map(({value:e,code:t,scheme:i})=>({name:e,code:t,scheme:i})),rights:c?.rights?.value};const u={art:"artist",aut:"author",bkp:"producer",clr:"colorist",edt:"editor",ill:"illustrator",trl:"translator",pbl:"publisher"};r=i=>e=>{var t=[...new Set(e.role?.map(({value:e,scheme:t})=>(t&&"marc:relators"!==t?null:u[e])??i))],e={name:e.value,sortAs:e.fileAs};return[t.length?t:[i],e]};return c?.creator?.map(r("author"))?.concat(c?.contributor?.map?.(r("contributor")))?.forEach(([e,t])=>e.forEach(e=>{this.metadata[e]?this.metadata[e].push(t):this.metadata[e]=[t]})),this}async loadDocument(e){var t=await this.loadText(e.href);return this.parser.parseFromString(t,e.mediaType)}async loadMediaOverlay(e){e=e.mediaOverlay;if(!e)return null;const t=this.resources.getItemByID(e);e=await this.#loadXML(t.href);return ee(e,e=>W(e,t.href))}resolveCFI(e){return this.resources.resolveCFI(e)}resolveHref(e){const[t,i]=e.split("#"),r=this.resources.getItemByHref(decodeURI(t));return r?{index:this.resources.spine.findIndex(({idref:e})=>e===r.id),anchor:i?e=>((e,t)=>e.getElementById(t)??e.querySelector(`[name="${CSS.escape(t)}"]`))(e,i):()=>0}:null}splitTOCHref(e){return e?.split("#")??[]}getTOCFragment(e,t){return e.getElementById(t)??e.querySelector(`[name="${CSS.escape(t)}"]`)}isExternal(e){return X(e)}async getCover(){var e=this.resources?.cover;return e?.href?new Blob([await this.loadBlob(e.href)],{type:e.mediaType}):null}async getCalibreBookmarks(){const e=await this.loadText("META-INF/calibre_bookmarks.txt");var t="encoding=json+base64:";if(e?.startsWith(t)){t=atob(e.slice(t.length));return JSON.parse(t)}}}class ce{static getReaderConfig(e){return(JSON.parse(localStorage.getItem("readerConfig"))||{})[e]}static setReaderConfig(e,t){let i=JSON.parse(localStorage.getItem("readerConfig"))||{};i[e]=t,localStorage.setItem("readerConfig",JSON.stringify(i))}static getKookitConfig(e){return(JSON.parse(localStorage.getItem("kookitConfig"))||{})[e]}static setKookitConfig(e,t){let i=JSON.parse(localStorage.getItem("kookitConfig"))||{};i[e]=t,localStorage.setItem("kookitConfig",JSON.stringify(i))}static removeKookitConfig(){localStorage.removeItem("kookitConfig")}}let he=!1;const de=e=>Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address")),ue=e=>e.trim().replace(/(\r\n|\n|\r|\t)/gm,"").substring(0,100),fe=(c,h,d,u,f,p,m)=>g(void 0,void 0,void 0,function*(){var t="yes"===ce.getReaderConfig("isSliding");let e=document.getElementById("page-area");if(e){var i,r,n,s,o,a,l=e.getElementsByTagName("iframe")[0];if(l){let e=l.contentDocument;e&&(l=(l=Math.floor(c.clientWidth/12))%2==0?l:l-1,0{let n=window._.findLastIndex(i,{href:t});return n=t&&-1g(void 0,void 0,void 0,function*(){var e=parseInt(ce.getKookitConfig("chapterDocIndex")||"0"),t=ce.getKookitConfig("chapterHref")||"";0===e||(t=pe(e,t,r,"prev"))&&(ce.setKookitConfig("text","prevChapter"),ce.setKookitConfig("page",""),yield ge(t.index,t.title,t.href,r,i,n,s))}),ge=(a,l,c,h,d,u,f)=>g(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){let t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;var i,r,n,s,o;e&&(e.body.innerHTML="",t.height="0px",e.body.scrollTo(0,0),(-1===(a=l&&!a||l!==h[a].title?window._.findLastIndex(h,{title:l}):a)||a>h.length-1)&&(a=0),e.body.innerHTML=yield p(h[a].text),i=e,yield g(void 0,void 0,void 0,function*(){let e=Array.from(i.getElementsByTagName("link"));e.forEach(e=>{e.onload=()=>{console.log("finished")}});let t=[];e.forEach(i=>{i.href.endsWith("null")||t.push(new Promise((e,t)=>{i.addEventListener("load",e)}))});try{yield Promise.race([Promise.all(t),new Promise((e,t)=>{setTimeout(()=>{t(new Error("Timeout"))},1e3)})])}catch(e){console.log(e)}}),ce.setKookitConfig("chapterTitle",l),ce.setKookitConfig("chapterHref",c),ce.setKookitConfig("chapterDocIndex",a+""),ce.setKookitConfig("percentage",a/h.length+""),ce.setKookitConfig("text",""),r=d,n=u,s=t,o=f,yield g(void 0,void 0,void 0,function*(){let t=s.contentDocument;if(t)if(yield Promise.all(Array.from(t.images).map(t=>t.complete?Promise.resolve(0!==t.naturalHeight):new Promise(e=>{t.addEventListener("load",()=>e(!0)),t.addEventListener("error",()=>e(!1))}))).then(e=>{e.every(e=>e)?console.log("all images loaded successfully!!"):console.log("some images failed to load, all finished loading")}),b(r,n,o),m(),"scroll"!==n){if(s.height=r.clientHeight+"px","double"===n){var e=Math.floor(r.clientWidth/12),e=(r.clientWidth+(e%2==0?e:e-1))/2;if((t.body.scrollWidth-t.body.clientWidth)/e%2==1){let e=document.createElement("div");e.setAttribute("style","height: "+t.body.clientHeight+"px"),t.body.appendChild(e)}}}else s.height=t.body.scrollHeight+"px",s.height=t.body.scrollHeight+"px"}),ye(d,u,"","","",""))}}}),ye=(a,l,c,h,d,u)=>g(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var s=e.getElementsByTagName("iframe")[0];if(s){let n=s.contentDocument;if(n){let t=0,i=0,r=n.body;if(u&&"scroll"!==l){s=Math.floor(a.clientWidth/12),s=a.clientWidth+(s%2==0?s:s-1);i=s*(parseInt(u)-1)}else if(c){let e=de(n.body);var o=e.filter((e,t)=>ue(e.textContent).slim()&&(ue(e.textContent).slim()===ue(c).slim()||ue(e.textContent).slim()===window.ChineseS2T.t2s(ue(c).slim())||ue(e.textContent).slim()===window.ChineseS2T.s2t(ue(c)).slim())&&(Math.abs(t-parseInt(h))<2||"search"===h));if(0===o.length)return void console.log("fail");r=be(o[0],a),i=r?y(r.offsetLeft)-y(r.marginLeft||parseFloat(getComputedStyle(r).marginLeft)):"prevChapter"===c?n.body.scrollWidth:0,t=r?y(r.offsetTop)-y(r.marginTop||parseInt(getComputedStyle(r).marginTop)):0}else if(d&&-1{var i=Math.floor(t.clientWidth/12),i=i%2==0?i:i-1;return parseInt(y(e.offsetLeft)-y(e.marginLeft||parseFloat(getComputedStyle(e).marginLeft))+"")%((t.clientWidth+i)/2)!=0&&e.parentElement?be(e.parentElement,t):e},ve=(s,o,a)=>g(void 0,void 0,void 0,function*(){if(!he){let e=document.getElementById("page-area");if(e){var r=e.getElementsByTagName("iframe")[0];if(r){var r=r.contentDocument;if(r){let t=de(r.body);var r=t.filter(e=>ke(s,e,o)&&(e.textContent||"").trim()),n=r[0];let i=0;for(let e=0;e{let e=ce.getKookitConfig("chapterHref")||"",r=e.lastIndexOf("#"),n=e.substring(0,r),s=e.substring(r+1);for(let e=0;e-1)ce.setKookitConfig("chapterHref",e)}}})(r,a),n&&!((e,t)=>{let i=Math.floor(t.clientWidth/12),r=i%2===0?i:i-1;if(Math.abs(e.offsetLeft-be(e,t).offsetLeft)>(t.clientWidth+r)/2)return true;else return false})(n,s)?(ce.setKookitConfig("text",n&&n.textContent||""),ce.setKookitConfig("count",i+""),ce.setKookitConfig("page","")):ce.setKookitConfig("page",(null===(r=yield l(o))||void 0===r?void 0:r.currentPage)+""),he=!0,setTimeout(()=>{he=!1},100)}}}}}),we=(i,e,r,n,s)=>g(void 0,void 0,void 0,function*(){var e=parseInt(ce.getKookitConfig("chapterDocIndex")||"0"),t=ce.getKookitConfig("chapterHref")||"";e>=r.length-1||(t=pe(e,t,r,"next"))&&(ce.setKookitConfig("page",""),yield ge(t.index,t.title,t.href,r,i,n,s))}),xe=(i,r)=>{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){n=n.contentDocument;if(n){let e=de(n.body).filter(e=>!Ce(e)),t=e.filter(e=>ke(i,e,r)&&(e.textContent||"").trim());return("scroll"!==r?t:e).filter(e=>"img"!==e.textContent).map(e=>e.textContent)}}}},Ce=e=>{var t=e.children;let i=!1;for(var r=/^(address|blockquote|body|center|dir|div|dl|fieldset|form|h[1-6]|hr|isindex|menu|noframes|noscript|ol|p|pre|table|ul|dd|dt|frameset|li|tbody|td|tfoot|th|thead|tr|html)$/i,n=0;n{var r,n=!1,s=t.getBoundingClientRect();return"scroll"!==i&&t.textContent&&t.textContent.trim()?n=-10<(r=s.left)&&r<=e.clientWidth:t.textContent&&t.textContent.trim()?n=(t=s.top)>=e.scrollTop&&t<=e.scrollTop+e.clientHeight:"scroll"!==i&&(n=0<=(s=s.left)&&s<=e.clientWidth),n};const Te={svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",html:"text/html",htm:"text/html",xml:"text/xml",xhtml:"application/xhtml+xml",css:"text/css"},Le={"image/svg+xml":"svg","image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","application/zip":"zip","application/x-rar-compressed":"rar","application/x-7z-compressed":"7z","application/x-tar":"tar","text/html":"html","text/xml":"xml","application/xhtml+xml":"xhtml","text/css":"css"};class Se extends class{constructor(){this.callbacks={},this.callbacks.base={}}on(e,t){const i=this;if(void 0===e||""===e)return console.warn("wrong names"),!1;if(void 0===t)return console.warn("wrong callback"),!1;const r=this.resolveNames(e);return r.forEach(function(e){e=i.resolveName(e);i.callbacks[e.namespace]instanceof Object||(i.callbacks[e.namespace]={}),i.callbacks[e.namespace][e.value]instanceof Array||(i.callbacks[e.namespace][e.value]=[]),i.callbacks[e.namespace][e.value].push(t)}),this}off(e){const r=this;if(void 0===e||""===e)return console.warn("wrong name"),!1;const t=this.resolveNames(e);return t.forEach(function(e){var t=r.resolveName(e);if("base"!==t.namespace&&""===t.value)delete r.callbacks[t.namespace];else if("base"===t.namespace)for(const i in r.callbacks)r.callbacks[i]instanceof Object&&r.callbacks[i][t.value]instanceof Array&&(delete r.callbacks[i][t.value],0===Object.keys(r.callbacks[i]).length&&delete r.callbacks[i]);else r.callbacks[t.namespace]instanceof Object&&r.callbacks[t.namespace][t.value]instanceof Array&&(delete r.callbacks[t.namespace][t.value],0===Object.keys(r.callbacks[t.namespace]).length&&delete r.callbacks[t.namespace])}),this}trigger(e,t=[]){if(void 0===e||""===e)return console.warn("wrong name"),!1;const i=this;const r=t instanceof Array?t:[];let n=this.resolveNames(e);n=this.resolveName(n[0]),setTimeout(()=>{if("base"===n.namespace)for(const e in i.callbacks){if(i.callbacks[e]instanceof Object&&i.callbacks[e][n.value]instanceof Array&&i.callbacks[e][n.value])i.callbacks[e][n.value].forEach(function(e){e.apply(i,r)});else if(this.callbacks[n.namespace]instanceof Object&&i.callbacks[n.namespace][n.value]){if(""===n.value)return console.warn("wrong name"),this;i.callbacks[n.namespace][n.value].forEach(function(e){e.apply(i,r)})}return null}},100)}resolveNames(e){let t=e;return t=t.replace(/[^a-zA-Z0-9 ,/.]/g,""),t=t.replace(/[,/]+/g," "),t=t.split(" "),t}resolveName(e){const t={};var i=e.split(".");return t.original=e,t.value=i[0],t.namespace="base",1g(this,void 0,void 0,function*(){let e=new d(c);this.chapterList=yield e.getChapter(c.toc),this.chapterDocList=yield e.getChapterDoc();var t=this.chapterList,i=this.chapterDocList.map(e=>({href:e.href,title:e.title})),r=yield Promise.all(this.chapterDocList.map(i=>g(this,void 0,void 0,function*(){let t="";if(i.text.load){let e=yield fetch(yield i.text.load()).then(e=>e.blob());t=yield e.text()}return t})));let s=new window.JSZip;s.file("toc.json",JSON.stringify(t)),s.file("sections.json",JSON.stringify(i));let o=[];for(let n=0;ne.blob());e.file(t+"."+Le[a.type],a),i[t].src="imgs/"+n+"/"+t+"."+Le[a.type]}catch(e){console.log(e)}}let t=Array.from(e.getElementsByTagName("link"));t.forEach((i,r)=>g(this,void 0,void 0,function*(){let e=s.folder("css/"+n);if(i.getAttribute("href"))try{var t=yield fetch(yield i.getAttribute("href")).then(e=>e.blob());e.file(r+"."+Le[t.type],t),i.href="css/"+n+"/"+r+"."+Le[t.type]}catch(e){console.log(e)}})),o.push(e.documentElement.innerHTML)}let n=s.folder("chapters");for(let e=0;eg(this,void 0,void 0,function*(){l(yield new Response(e).arrayBuffer())})).catch(e=>{l("err")})}))}resolveChapter(e){var t=e;let i=-1;for(let e=0;e{let e=document.getElementById("page-area");if(e){var o=e.getElementsByTagName("iframe")[0];if(o){o=o.contentDocument;if(o){let e=de(o.body).filter(e=>!Ce(e)),t=e.filter(e=>(e.textContent||"").trim()),i=("scroll"!==s?t:e).filter(e=>"img"!==e.textContent).map(e=>e.textContent),r=0;return xe(n,s)&&0{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){n=n.contentDocument;if(n){let e=de(n.body),t=e.filter(e=>(e.getAttribute("style")===r&&e.setAttribute("style",""),(e.textContent||"").trim()&&e.textContent===i));0!Ce(e));for(let e=0;esetTimeout(e,1e3))),yield ve(this.element,this.mode,this.flatChapter(this.chapterList))})}getPosition(){return{text:ce.getKookitConfig("text"),chapterTitle:ce.getKookitConfig("chapterTitle"),chapterDocIndex:ce.getKookitConfig("chapterDocIndex"),chapterHref:ce.getKookitConfig("chapterHref"),count:ce.getKookitConfig("count"),percentage:ce.getKookitConfig("percentage"),page:ce.getKookitConfig("page")}}setStyle(t){let e=document.getElementById("page-area");if(e){var i=e.getElementsByTagName("iframe")[0];if(i){let e=i.contentDocument;e&&e.body.setAttribute("style",t+e.body.getAttribute("style"))}}}}const Ae=e=>{if(!e)return"";const t=document.createElement("textarea");return t.innerHTML=e,t.value},Be={XML:"application/xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml"},Ee={name:[0,32,"string"],type:[60,4,"string"],creator:[64,4,"string"],numRecords:[76,2,"uint"]},Ie={compression:[0,2,"uint"],numTextRecords:[8,2,"uint"],recordSize:[10,2,"uint"],encryption:[12,2,"uint"]},Me={magic:[16,4,"string"],length:[20,4,"uint"],type:[24,4,"uint"],encoding:[28,4,"uint"],uid:[32,4,"uint"],version:[36,4,"uint"],titleOffset:[84,4,"uint"],titleLength:[88,4,"uint"],localeRegion:[94,1,"uint"],localeLanguage:[95,1,"uint"],resourceStart:[108,4,"uint"],huffcdic:[112,4,"uint"],numHuffcdic:[116,4,"uint"],exthFlag:[128,4,"uint"],trailingFlags:[240,4,"uint"],indx:[244,4,"uint"]},De={resourceStart:[108,4,"uint"],fdst:[192,4,"uint"],numFdst:[196,4,"uint"],frag:[248,4,"uint"],skel:[252,4,"uint"],guide:[260,4,"uint"]},Re={magic:[0,4,"string"],length:[4,4,"uint"],count:[8,4,"uint"]},Ne={magic:[0,4,"string"],length:[4,4,"uint"],type:[8,4,"uint"],idxt:[20,4,"uint"],numRecords:[24,4,"uint"],encoding:[28,4,"uint"],language:[32,4,"uint"],total:[36,4,"uint"],ordt:[40,4,"uint"],ligt:[44,4,"uint"],numLigt:[48,4,"uint"],numCncx:[52,4,"uint"]},Oe={magic:[0,4,"string"],length:[4,4,"uint"],numControlBytes:[8,4,"uint"]},He={magic:[0,4,"string"],offset1:[8,4,"uint"],offset2:[12,4,"uint"]},$e={magic:[0,4,"string"],length:[4,4,"uint"],numEntries:[8,4,"uint"],codeLength:[12,4,"uint"]},Fe={magic:[0,4,"string"],numEntries:[8,4,"uint"]},Ue={flags:[8,4,"uint"],dataStart:[12,4,"uint"],keyLength:[16,4,"uint"],keyStart:[20,4,"uint"]},Pe={1252:"windows-1252",65001:"utf-8"},ze={100:["creator","string",!0],101:["publisher"],103:["description"],104:["isbn"],105:["subject","string",!0],106:["date"],108:["contributor","string",!0],109:["rights"],110:["subjectCode","string",!0],112:["source","string",!0],113:["asin"],121:["boundary","uint"],122:["fixedLayout"],125:["numResources","uint"],126:["originalResolution"],127:["zeroGutter"],128:["zeroMargin"],129:["coverURI"],132:["regionMagnification"],201:["coverOffset","uint"],202:["thumbnailOffset","uint"],503:["title"],524:["language","string",!0],527:["pageProgressionDirection"]},je={1:["ar","ar-SA","ar-IQ","ar-EG","ar-LY","ar-DZ","ar-MA","ar-TN","ar-OM","ar-YE","ar-SY","ar-JO","ar-LB","ar-KW","ar-AE","ar-BH","ar-QA"],2:["bg"],3:["ca"],4:["zh","zh-TW","zh-CN","zh-HK","zh-SG"],5:["cs"],6:["da"],7:["de","de-DE","de-CH","de-AT","de-LU","de-LI"],8:["el"],9:["en","en-US","en-GB","en-AU","en-CA","en-NZ","en-IE","en-ZA","en-JM",null,"en-BZ","en-TT","en-ZW","en-PH"],10:["es","es-ES","es-MX",null,"es-GT","es-CR","es-PA","es-DO","es-VE","es-CO","es-PE","es-AR","es-EC","es-CL","es-UY","es-PY","es-BO","es-SV","es-HN","es-NI","es-PR"],11:["fi"],12:["fr","fr-FR","fr-BE","fr-CA","fr-CH","fr-LU","fr-MC"],13:["he"],14:["hu"],15:["is"],16:["it","it-IT","it-CH"],17:["ja"],18:["ko"],19:["nl","nl-NL","nl-BE"],20:["no","nb","nn"],21:["pl"],22:["pt","pt-BR","pt-PT"],23:["rm"],24:["ro"],25:["ru"],26:["hr",null,"sr"],27:["sk"],28:["sq"],29:["sv","sv-SE","sv-FI"],30:["th"],31:["tr"],32:["ur"],33:["id"],34:["uk"],35:["be"],36:["sl"],37:["et"],38:["lv"],39:["lt"],41:["fa"],42:["vi"],43:["hy"],44:["az"],45:["eu"],46:["hsb"],47:["mk"],48:["st"],49:["ts"],50:["tn"],52:["xh"],53:["zu"],54:["af"],55:["ka"],56:["fo"],57:["hi"],58:["mt"],59:["se"],62:["ms"],63:["kk"],65:["sw"],67:["uz",null,"uz-UZ"],68:["tt"],69:["bn"],70:["pa"],71:["gu"],72:["or"],73:["ta"],74:["te"],75:["kn"],76:["ml"],77:["as"],78:["mr"],79:["sa"],82:["cy","cy-GB"],83:["gl","gl-ES"],87:["kok"],97:["ne"],98:["fy"]},We=(e,t)=>{const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},Xe=(e,t,i)=>{const r=new e.constructor(e.length+t.length+i.length);return r.set(e),r.set(t,e.length),r.set(i,e.length+t.length),r},qe=new TextDecoder,Ke=e=>qe.decode(e),Je=e=>{if(e){var t=e.byteLength,t=4===t?"getUint32":2===t?"getUint16":"getUint8";return new DataView(e)[t](0)}},Ge=(e,n)=>Object.fromEntries(Array.from(Object.entries(e)).map(([e,[t,i,r]])=>[e,("string"===r?Ke:Je)(n.slice(t,t+i))])),Ze=e=>new TextDecoder(Pe[e]),_e=(e,t=0)=>{let i=0,r=0;for(const n of e.subarray(t,t+4))if(i=i<<7|(127&n)>>>0,r++,128&n)break;return{value:i,length:r}},Ve=e=>{let t=0;for(;0>=1)1==(1&e)&&t++;return t},Ye=e=>{let t=0;for(;0==(1&e);)e>>=1,t++;return t},Qe=t=>{let i=[];for(let e=0;e>>3,o=3+(7&n);for(let e=0;e{const r=await i(t.huffcdic),{magic:e,offset1:n,offset2:s}=Ge(He,r);if("HUFF"!==e)throw new Error("Invalid HUFF record");const d=Array.from({length:256},(e,t)=>n+4*t).map(e=>Je(r.slice(e,e+4))).map(e=>[128&e,31&e,e>>>8]),u=[null].concat(Array.from({length:32},(e,t)=>s+8*t).map(e=>[Je(r.slice(e,e+4)),Je(r.slice(e+4,e+8))])),f=[];for(let e=1;e{let a=new Uint8Array;var l=8*o.byteLength;for(let s=0;s{var e=i+32,r=e>>3;let n=0n;for(let e=i>>3;e<=r;e++)n=n<<8n|BigInt(t[e]??0);return n>>8n-BigInt(7&e)&0xffffffffn})(o,s));let[e,t,i]=d[c>>>24];if(!e){for(;c>>>32-tl)break;var h=i-(c>>>32-t);let[r,n]=f[h];n||(r=p(r),f[h]=[r,!0]),a=We(a,r)}return a};return p},tt=async(t,i)=>{const e=await i(t),r=Ge(Ne,e);if("INDX"!==r.magic)throw new Error("Invalid INDX record");const n=Ze(r.encoding),s=e.slice(r.length);var o=Ge(Oe,s);if("TAGX"!==o.magic)throw new Error("Invalid TAGX section");var a=(o.length-12)/4,l=Array.from({length:a},(e,t)=>new Uint8Array(s.slice(12+4*t,12+4*t+4)));const c={};let h=0;for(let e=0;e>Ye(C),null,x]));const U={};for([A,B,E,I]of F){const P=[];if(null!=B)for(let e=0;eJe(i.slice(8*t,8*t+4))).map((e,t,i)=>[e,i[t+1]])}loadRecord(e){e=this.#offsets[e];if(!e)throw new RangeError("Record index out of bounds");return this.#file.slice(...e).arrayBuffer()}async loadMagic(e){e=this.#offsets[e][0];return Ke(await this.#file.slice(e,e+4).arrayBuffer())}}{#start=0;#resourceStart;#decoder;#encoder;#decompress;#removeTrailingEntries;constructor({unzlib:e}){super(),this.unzlib=e}async open(e){await super.open(e),this.headers=this.#getHeaders(await super.loadRecord(0)),this.#resourceStart=this.headers.mobi.resourceStart;let t=8<=this.headers.mobi.version;if(!t){e=this.headers.exth?.boundary;if(e<4294967295)try{this.headers=this.#getHeaders(await super.loadRecord(e)),this.#start=e,t=!0}catch(e){console.warn(e),console.warn("Failed to open KF8; falling back to MOBI")}}return await this.#setup(),new(t?dt:st)(this).init()}#getHeaders(e){var t=Ge(Ie,e);const i=Ge(Me,e);if("MOBI"!==i.magic)throw new Error("Missing MOBI header");var{titleOffset:r,titleLength:n,localeLanguage:s,localeRegion:o}=i;i.title=e.slice(r,r+n);s=je[s];i.language=s?.[o>>2]??s?.[0];s=64&i.exthFlag?((t,e)=>{var{magic:i,count:r}=Ge(Re,t);if("EXTH"!==i)throw new Error("Invalid EXTH header");const n=Ze(e),s={};let o=12;for(let e=0;ee:2===e?Qe:17480===e?await et(t,this.loadRecord.bind(this)):null,!this.#decompress)throw new Error("Unknown compression type");var t=t["trailingFlags"];const r=1&t,n=Ve(t>>>1);this.#removeTrailingEntries=t=>{for(let e=0;e{let t=0;for(const i of e.subarray(-4))128&i&&(t=0),t=t<<7|127&i;return t})(t);t=t.subarray(0,-i)}var e;return r&&(e=1+(3&t[t.length-1]),t=t.subarray(0,-e)),t}}decode(...e){return this.#decoder.decode(...e)}encode(...e){return this.#encoder.encode(...e)}loadRecord(e){return super.loadRecord(this.#start+e)}loadMagic(e){return super.loadMagic(this.#start+e)}loadText(e){return this.loadRecord(e+1).then(e=>new Uint8Array(e)).then(this.#removeTrailingEntries).then(this.#decompress)}async loadResource(e){const t=await super.loadRecord(this.#resourceStart+e);e=Ke(t.slice(0,4));return"FONT"===e?(async(e,t)=>{var{flags:i,dataStart:r,keyLength:n,keyStart:s}=Ge(Ue,e);const o=new Uint8Array(e.slice(r));if(2&i)for(var r=16===n?1024:1040,a=new Uint8Array(e.slice(s,s+n)),l=Math.min(r,o.length),c=0;c{const{table:i,cncx:r}=await tt(e,t),n=i.map(({tagMap:e},t)=>({index:t,offset:e[1]?.[0],size:e[2]?.[0],label:r[e[3]]??"",headingLevel:e[4]?.[0],pos:e[6],parent:e[21]?.[0],firstChild:e[22]?.[0],lastChild:e[23]?.[0]})),s=t=>(null==t.firstChild||(t.children=n.filter(e=>e.parent===t.index).map(s)),t);return n.filter(e=>0===e.headingLevel).map(s)})(e,this.loadRecord.bind(this))}getMetadata(){const{mobi:e,exth:t}=this.headers;return{identifier:e.uid.toString(),title:Ae(t?.title||this.decode(e.title)),author:t?.creator?.map(Ae),publisher:Ae(t?.publisher),language:t?.language??e.language,published:t?.date,description:Ae(t?.description),subject:t?.subject?.map(Ae),rights:Ae(t?.rights)}}async getCover(){var e=this.headers["exth"],e=e?.coverOffset<4294967295?e?.coverOffset:e?.thumbnailOffset<4294967295?e?.thumbnailOffset:null;if(null!=e){e=await this.loadResource(e);return new Blob([e])}}}const rt=/<\s*(?:mbp:)?pagebreak[^>]*>/gi,nt=/<[^<>]+filepos=['"]{0,1}(\d+)[^<>]*>/gi;class st{parser=new DOMParser;serializer=new XMLSerializer;#resourceCache=new Map;#textCache=new Map;#cache=new Map;#sections;#fileposList=[];#type=Be.HTML;constructor(e){this.mobi=e}async init(){let t=new Uint8Array;for(let e=0;eString.fromCharCode(e)).join("");this.#sections=[0].concat(Array.from(r.matchAll(rt),e=>e.index)).map((e,t,i)=>r.slice(e,i[t+1])).map(e=>Uint8Array.from(e,e=>e.charCodeAt(0))).map(e=>({book:this,raw:e})).reduce((e,t)=>{var i=e[e.length-1];return t.start=i?.end??0,t.end=t.start+t.raw.byteLength,e.concat(t)},[]),this.sections=this.#sections.map((e,t)=>({id:t,load:()=>this.loadSection(e),createDocument:()=>this.createDocument(e),size:e.end-e.start}));const n=[];try{const s=await this.mobi.getNCX(),o=({label:e,offset:t,children:i})=>{var r=t.toString().padStart(10,"0"),t=`filepos:${r}`;return n.push(r),{label:e=Ae(e),href:t,subitems:i?.map(o)}};if(this.toc=s?.map(o),this.landmarks=await this.getGuide(),!this.toc){var e=this.landmarks.find(({type:e})=>e?.includes("toc"))?.href;if(e){var i=this.resolveHref(e)["index"];const a=await this.sections[i].createDocument();this.toc=Array.from(a.querySelectorAll("a[filepos]"),e=>({label:e.innerText?.trim(),href:`filepos:${e.getAttribute("filepos")}`}))}}}catch(e){console.warn(e)}return this.#fileposList=[...new Set(n.concat(Array.from(r.matchAll(nt),e=>e[1])))].map(e=>({filepos:e,number:Number(e)})).sort((e,t)=>e.number-t.number),this.metadata=this.mobi.getMetadata(),this.getCover=this.mobi.getCover.bind(this.mobi),this}async getGuide(){const e=await this.createDocument(this.#sections[0]);return Array.from(e.getElementsByTagName("reference"),e=>({label:e.getAttribute("title"),type:e.getAttribute("type")?.split(/\s/),href:`filepos:${e.getAttribute("filepos")}`}))}async loadResource(e){if(this.#resourceCache.has(e))return this.#resourceCache.get(e);var t=await this.mobi.loadResource(e),t=URL.createObjectURL(new Blob([t]));return this.#resourceCache.set(e,t),t}async loadRecindex(e){return this.loadResource(Number(e)-1)}async replaceResources(e){for(const s of e.querySelectorAll("img[recindex]")){var t=s.getAttribute("recindex");try{s.src=await this.loadRecindex(t)}catch(e){console.warn(`Failed to load image ${t}`)}}for(const o of e.querySelectorAll("[mediarecindex]")){var i=o.getAttribute("mediarecindex"),r=o.getAttribute("recindex");try{o.src=await this.loadRecindex(i),r&&(o.poster=await this.loadRecindex(r))}catch(e){console.warn(`Failed to load media ${i}`)}}for(const a of e.querySelectorAll("[filepos]")){var n=a.getAttribute("filepos");a.href=`filepos:${n}`}}async loadText(t){if(this.#textCache.has(t))return this.#textCache.get(t);const r=t["raw"],n=this.#fileposList.filter(({number:e})=>e>=t.start&&e({...e,offset:e.number-t.start}));let s=r;n.length&&(s=r.subarray(0,n[0].offset),n.forEach(({filepos:e,offset:t},i)=>{i=n[i+1],e=this.mobi.encode(``);s=Xe(s,e,r.subarray(t,i?.offset))}));var e=this.mobi.decode(s).replaceAll(rt,"");return this.#textCache.set(t,e),e}async createDocument(e){e=await this.loadText(e);return this.parser.parseFromString(e,this.#type)}async loadSection(e){if(this.#cache.has(e))return this.#cache.get(e);const t=await this.createDocument(e),i=t.createElement("style");t.head.append(i),i.append(t.createTextNode(`blockquote { +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Kookit={})}(this,function(e){"use strict";function g(e,o,a,l){return new(a=a||Promise)(function(i,t){function r(e){try{s(l.next(e))}catch(e){t(e)}}function n(e){try{s(l.throw(e))}catch(e){t(e)}}function s(e){var t;e.done?i(e.value):((t=e.value)instanceof a?t:new a(function(e){e(t)})).then(r,n)}s((l=l.apply(e,o||[])).next())})}const y=e=>e?parseFloat(e+""):0,p=i=>g(void 0,void 0,void 0,function*(){let t="";if(i.load){let e=yield fetch(yield i.load()).then(e=>e.blob());t=yield e.text()}return i.loadAsset&&(t=yield r(t,i.loadAsset)),n(t)}),u=e=>Array.from(e.querySelectorAll("img, image")),r=(n,s)=>g(void 0,void 0,void 0,function*(){let e=(new DOMParser).parseFromString(n,"text/html"),t=u(e);for(let e=0;e{var t=(new DOMParser).parseFromString(e,"text/html");let i=u(t);if(0===i.length)return e;for(let e=0;e{var i=document.createElement("iframe");i.style.width="100%",i.style.border="0",i.style.margin="0",i.style.padding="0",i.style.minHeight="calc(100% - 2px)",i.style.fontSize="100%",i.style.font="inherit",i.scrolling="no",i.tabIndex=0,i.style.verticalAlign="baseline",e.innerHTML="",e.appendChild(i)},l=i=>g(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){t=t.contentDocument;if(t)return 1===parseInt(t.body.scrollWidth/t.body.clientWidth+"")&&(yield new Promise(e=>setTimeout(e,1e3))),{totalPage:"scroll"===i?1:parseInt(t.body.scrollWidth/t.body.clientWidth+"")+1,currentPage:parseInt(y(t.body.scrollLeft)/t.body.clientWidth+"")+1}}}}),m=()=>{let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;if(e){var i=e.querySelectorAll("a, article, cite, code, div, li, p, pre, span, table");for(let e=0;e{let e=document.getElementById("page-area");if(e){var t=e.getElementsByTagName("iframe")[0];if(t){let r=t.contentDocument;if(r){var a,t=Math.floor(n.clientWidth/12),l=t%2==0?t:t-1;for(a of r.querySelectorAll("img, image")){let e=a.parentElement,t=0,i=0;var c=a.getAttribute("width"),h=a.getAttribute("height");o.startsWith("CB")&&"scroll"===s?i=e.offsetWidth:o.startsWith("CB")&&"single"===s?(t=n.clientHeight,i=n.clientWidth):c&&h?(h/c>e.clientHeight/e.clientWidth?(t=e.clientHeight,i=parseInt(t*c/h+"")):(i=e.clientWidth,t=parseInt(i*h/c+"")),t>r.body.clientHeight&&(i=parseInt(i*(r.body.clientHeight/t)+""),t=r.body.clientHeight)):t=e&&e.clientWidth&&0{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){let t=n.contentDocument;if(t){let e=t.createElement("style");e.id="default-style",e.textContent="p,empty-line{display: inherit;margin-block-start: inherit;margin-block-end: inherit;margin-inline-start: inherit;margin-inline-end: inherit;}body{margin: 0px}",t.head.appendChild(e),"scroll"!==r&&(n="double"===r?2:1,r=(r=Math.floor(i.clientWidth/12))%2==0?r:r-1,t.body.setAttribute("style",`width: auto;height: 100%;overflow-y: hidden;overflow-X: hidden;padding-left: 0px;padding-right: 0px;margin: 0px;box-sizing: border-box;max-width: inherit;column-fill: auto;column-gap: ${r}px;column-count: 12;column-width: ${(i.clientWidth-r)/n}px;`))}}}};class f{constructor(e){this.book=e,this.chapterList=[],this.flattenChapters=[],this.chapterDocList=[]}getChapter(e){return g(this,void 0,void 0,function*(){return this.chapterList=e?yield Promise.all(e.map(t=>g(this,void 0,void 0,function*(){var e=t.href&&(yield this.book.resolveHref(t.href))?(yield this.book.resolveHref(t.href)).index:-1;return{label:t.label||e,href:t.href,index:e,subitems:t.subitems?yield this.getChapter(t.subitems):[]}}))):yield Promise.all(this.book.sections.map((e,t)=>g(this,void 0,void 0,function*(){return{label:e.label||t,href:e.href||"",index:t,subitems:e.subitems?yield this.getChapter(e.subitems):[]}}))),this.flattenChapters=this.flatChapter(this.chapterList),this.chapterList})}getChapterDoc(){return g(this,void 0,void 0,function*(){const i=this.flattenChapters.map(e=>e.index);return this.book.sections.map((e,t)=>-1"no"!==e.text.linear)})}flatChapter(t){let i=[];for(let e=0;eg(this,void 0,void 0,function*(){const t=this.book.metadata;try{var i=yield this.book.getCover(),e=new FileReader;e.readAsDataURL(i),e.onloadend=()=>{r({name:t.title,author:t.author?t.author[0].name:"",description:t.description,publisher:t.publisher,cover:e.result})}}catch(e){i=t.author&&t.author[0]&&t.author[0].name?t.author[0].name:t.author&&t.author[0]?t.author[0]:t.author||"";r({name:t.title,author:i,description:t.description,publisher:t.publisher,cover:""})}}))}}const i=(e,r)=>e.map((e,t,i)=>r(e,t,i)?t:null).filter(e=>null!=e),a=(r,e)=>[-1,...e,r.length].reduce(({xs:e,a:t},i)=>({xs:e?.concat([r.slice(t+1,i)])??[],a:i}),{}).xs,c=(e,t)=>e.slice(0,-1).concat([e[e.length-1].concat(t[0])]).concat(t.slice(1)),h=/\d/,d=/^epubcfi\((.*)\)$/,v=e=>e.replace(/[\^[\](),;=]/g,"^$&"),t=e=>d.test(e)?e:`epubcfi(${e})`,w=(e,t)=>i(e,([e])=>e===t),x=e=>{const t=[];let i;for(var[r,n]of e){if("/"===r)t.push({index:n});else{const s=t[t.length-1];if(":"===r)s.offset=n;else if("~"===r)s.temporal=n;else if("@"===r)s.spatial=(s.spatial??[]).concat(n);else if(";s"===r)s.side=n;else if("["===r){if("/"!==i||!n){s.text=(s.text??[]).concat(n);continue}s.id=n}}i=r}return t},C=e=>a(e,w(e,"!")).map(x),k=e=>{var t=(e=>{const t=[];let i,r,n="";var s=e=>(t.push(e),i=null,n=""),o=e=>(n+=e,r=!1);for(const a of Array.from(e.trim()).concat(""))if("^"!==a||r){if("!"===i)s(["!"]);else if(","===i)s([","]);else if("/"===i||":"===i){if(h.test(a)){o(a);continue}s([i,parseInt(n)])}else if("~"===i){if(h.test(a)||"."===a){o(a);continue}s(["~",parseFloat(n)])}else if("@"===i){if(":"===a){s(["@",parseFloat(n)]),i="@";continue}if(h.test(a)||"."===a){o(a);continue}s(["@",parseFloat(n)])}else{if("["===i){";"!==a||r?","!==a||r?"]"!==a||r?o(a):s(["[",n]):(s(["[",n]),i="["):(s(["[",n]),i=";");continue}if(i?.startsWith(";")){"="!==a||r?";"!==a||r?"]"!==a||r?o(a):s([i,n]):(s([i,n]),i=";"):(i=`;${n}`,n="");continue}}"/"!==a&&":"!==a&&"~"!==a&&"@"!==a&&"["!==a&&"!"!==a&&","!==a||(i=a)}else r=!0;return t})((i=e).match(d)?.[1]??i),e=w(t,",");if(!e.length)return C(t);var[i,t,e]=a(t,e).map(C);return{parent:i,start:t,end:e}},T=({index:e,id:t,offset:i,temporal:r,spatial:n,text:s,side:o})=>{var a=o?`;s=${o}`:"";return`/${e}`+(t?`[${v(t)}${a}]`:"")+(null!=i&&e%2?`:${i}`:"")+(r?`~${r}`:"")+(n?`@${n.join(":")}`:"")+(s||!t&&o?"["+(s?.map(v)?.join(",")??"")+a+"]":"")},L=e=>e.parent?[e.parent,e.start,e.end].map(L).join(","):e.map(e=>e.map(T).join("")).join("!"),S=e=>t(L(e)),A=(e,t)=>"string"==typeof e?S(A(k(e),t)):e.parent?c(e.parent,e[t?"end":"start"]):e,B=({nodeType:e})=>3===e||4===e,E=({nodeType:e})=>1===e,I=e=>{const t=Array.from(e.childNodes).filter(e=>B(e)||E(e)).reduce((e,t)=>{let i=e[e.length-1];return i?B(t)?Array.isArray(i)?i.push(t):B(i)?e[e.length-1]=[i,t]:e.push(t):E(i)?e.push(null,t):e.push(t):e.push(t),e},[]);return E(t[0])&&t.unshift("first"),E(t[t.length-1])&&t.push("last"),t.unshift("before"),t.push("after"),t},M=(e,t)=>e?I(e)[t]:null,D=(e,t)=>{var i,r=t[t.length-1]["id"];if(r){r=e.ownerDocument.getElementById(r);if(r)return{node:r,offset:0}}for({index:i}of t){var n=M(e,i);if("first"===n)return{node:e.firstChild??e};if("last"===n)return{node:e.lastChild??e};if("before"===n)return{node:e,before:!0};if("after"===n)return{node:e,after:!0};e=n}var s=t[t.length-1]["offset"];if(!Array.isArray(e))return{node:e,offset:s};let o=0;for(const l of e){var a=l.nodeValue["length"];if(o+a>=s)return{node:l,offset:s-o};o+=a}},R=(t,i)=>{var{parentNode:e,id:r}=t;const n=I(e);var s=n.findIndex(e=>Array.isArray(e)?e.some(e=>e===t):e===t),o=n[s];if(Array.isArray(o)){let e=0;for(const a of o){if(a===t){e+=i;break}e+=a.nodeValue.length}i=e}s={id:r,index:s,offset:i};return e!==t.ownerDocument.documentElement?R(e).concat(s):[s]},N=(e,t)=>D(e.documentElement,A(t)).node,O={CONTAINER:"urn:oasis:names:tc:opendocument:xmlns:container",XHTML:"http://www.w3.org/1999/xhtml",OPF:"http://www.idpf.org/2007/opf",EPUB:"http://www.idpf.org/2007/ops",DC:"http://purl.org/dc/elements/1.1/",DCTERMS:"http://purl.org/dc/terms/",ENC:"http://www.w3.org/2001/04/xmlenc#",NCX:"http://www.daisy.org/z3986/2005/ncx/",XLINK:"http://www.w3.org/1999/xlink",SMIL:"http://www.w3.org/ns/SMIL"},H={XML:"application/xml",NCX:"application/x-dtbncx+xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml",JS:/\/(x-)?(javascript|ecmascript)/},$=e=>e.toLowerCase().replace(/[-:](.)/g,(e,t)=>t.toUpperCase()),F=e=>e?e.trim().replace(/\s{2,}/g," "):"",U=(t,i,e)=>e?e=>e.getAttribute(t)?.split(/\s/)?.includes(i):"function"==typeof i?e=>i(e.getAttribute(t)):e=>e.getAttribute(t)===i,P=(...e)=>t=>t?Object.fromEntries(e.map(e=>[$(e),t.getAttribute(e)])):null,z=e=>F(e?.textContent),j=(e,i)=>{e=e.lookupNamespaceURI(null)===i||e.lookupPrefix(i);const r=e?(e,t)=>e=>e.namespaceURI===i&&e.localName===t:(e,t)=>e=>e.localName===t;return{$:(e,t)=>[...e.children].find(r(e,t)),$$:(e,t)=>[...e.children].filter(r(e,t)),$$$:e?(e,t)=>[...e.getElementsByTagNameNS(i,t)]:(e,t)=>[...e.getElementsByTagName(i,t)]}},W=(t,e)=>{try{if(e.includes(":"))return new URL(t,e);var i="whatever://whatever/";return decodeURI(new URL(t,i+e).href.replace(i,""))}catch(e){return console.warn(e),t}},X=e=>/^(?!blob)\w+:/i.test(e),q=async(e,t,i)=>{const r=[];e.replace(t,(...e)=>(r.push(e),null));const n=[];for(const s of r)n.push(await i(...s));return e.replace(t,()=>n.shift())},K=e=>e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&");var J={attrs:["dir","xml:lang"]},G={name:"alternate-script",many:!0,...J,props:["file-as"]},Z={many:!0,...J,props:[{name:"role",many:!0,attrs:["scheme"]},"file-as",G]};const _=[{name:"title",many:!0,...J,props:["title-type","display-seq","file-as",G]},{name:"identifier",many:!0,props:[{name:"identifier-type",attrs:["scheme"]}]},{name:"language",many:!0},{name:"creator",...Z},{name:"contributor",...Z},{name:"publisher",...J,props:["file-as",G]},{name:"description",...J,props:[G]},{name:"rights",...J,props:[G]},{name:"date"},{name:"dcterms:modified",type:"meta"},{name:"subject",many:!0,...J,props:["term","authority",G]},{name:"belongs-to-collection",type:"meta",many:!0,...J,props:["collection-type","group-position","dcterms:identifier","file-as",G,{name:"belongs-to-collection",recursive:!0}]}],V=(e,s=e=>e)=>{const{$:o,$$:i,$$$:t}=j(e,O.XHTML),r=n=>e=>{const t=o(e,"a")??o(e,"span");var i=o(e,"ol"),e=(e=t?.getAttribute("href"))?decodeURI(s(e)):null;const r={label:z(t)||t?.getAttribute("title"),href:e,subitems:a(i)};return n&&(r.type=t?.getAttributeNS(O.EPUB,"type")?.split(/\s/)),r},a=(e,t)=>e?i(e,"li").map(r(t)):null;var n=(e,t)=>a(o(e,"ol"),t);let l=null,c=null,h=null,d=[];for(const u of t(e,"nav")){const f=u.getAttributeNS(O.EPUB,"type")?.split(/\s/)??[];f.includes("toc")?l??=n(u):f.includes("page-list")?c??=n(u):f.includes("landmarks")?h??=n(u,!0):d.push({label:z(u.firstElementChild),type:f,list:n(u)})}return{toc:l,pageList:c,landmarks:h,others:d}},Y=(i,s=e=>e)=>{const{$:o,$$:a}=j(i,O.NCX),l=e=>{var t=o(e,"navLabel");const i=o(e,"content");var r=z(t),t=(t=i.getAttribute("src"))?decodeURI(s(t)):null;if("navPoint"!==e.localName)return{label:r,href:t};{const n=a(e,"navPoint");return{label:r,href:t,subitems:n.length?n.map(l):null}}},r=(e,t)=>a(e,t).map(l);var e=(e,t)=>{e=o(i.documentElement,e);return e?r(e,t):null};return{toc:e("navMap","navPoint"),pageList:e("pageList","pageTarget"),others:a(i.documentElement,"navList").map(e=>({label:z(o(e,"navLabel")),list:r(e,"navTarget")}))}},Q=e=>{if(e){var t=e.split(":").map(e=>parseFloat(e));if(3===t.length){var[i,r,n]=t;return 60*i*60+60*r+n}if(2===t.length){var[t,s]=t;return 60*t+s}var[s,e]=e.split(/(?=[^\d.])/);return parseFloat(s)*("h"===e?3600:"min"===e?60:"ms"===e?.001:1)}},ee=(e,r=e=>e)=>{const{$:n,$$$:t}=j(e,O.SMIL);return t(e,"par").map(e=>{var t=n(e,"text")?.getAttribute("src")?.split("#")?.[1];const i=n(e,"audio");return i?{id:t,audio:{src:(e=i.getAttribute("src"))?decodeURI(r(e)):null,clipBegin:Q(i.getAttribute("clipBegin")),clipEnd:Q(i.getAttribute("clipEnd"))}}:{id:t}})},te=/([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/,ie=e=>z(e.getElementById(e.documentElement.getAttribute("unique-identifier"))??e.getElementsByTagNameNS(O.DC,"identifier")[0]),re=async(e,t,i)=>{const r=new Uint8Array(await i.slice(0,t).arrayBuffer());t=Math.min(t,r.length);for(var n=0;n{e=(new TextEncoder).encode(e),e=await globalThis.crypto.subtle.digest("SHA-1",e);return new Uint8Array(e)})=>({"http://www.idpf.org/2008/embedding":{key:e=>t(ie(e).replaceAll(/[\u0020\u0009\u000d\u000a]/g,"")),decode:(e,t)=>re(e,1040,t)},"http://ns.adobe.com/pdf/enc#RC":{key:e=>{const i=(e=>{for(const i of e.getElementsByTagNameNS(O.DC,"identifier")){var[t]=z(i).split(":").slice(-1);if(te.test(t))return t}return""})(e).replaceAll("-","");return Uint8Array.from({length:16},(e,t)=>parseInt(i.slice(2*t,2*t+2),16))},decode:(e,t)=>re(e,1024,t)}});class se{#uris=new Map;#decoders=new Map;#algorithms;constructor(e){this.#algorithms=e}async init(e,t){var i,r;if(e)for({algorithm:i,uri:r}of Array.from(e.getElementsByTagNameNS(O.ENC,"EncryptedData"),e=>({algorithm:e.getElementsByTagNameNS(O.ENC,"EncryptionMethod")[0]?.getAttribute("Algorithm"),uri:e.getElementsByTagNameNS(O.ENC,"CipherReference")[0]?.getAttribute("URI")}))){if(!this.#decoders.has(i)){const n=this.#algorithms[i];if(!n){console.warn("Unknown encryption algorithm");continue}const s=await n.key(t);this.#decoders.set(i,e=>n.decode(s,e))}this.#uris.set(r,i)}}getDecoder(e){return this.#decoders.get(this.#uris.get(e))??(e=>e)}}class oe{constructor({opf:e,resolveHref:r}){this.opf=e;const{$:t,$$:i,$$$:n}=j(e,O.OPF);var s=t(e.documentElement,"manifest");const o=t(e.documentElement,"spine"),a=i(o,"itemref");this.manifest=i(s,"item").map(P("href","id","media-type","properties","media-overlay")).map(e=>(e.href=r(e.href),e.properties=e.properties?.split(/\s/),e)),this.spine=a.map(P("idref","id","linear","properties")).map(e=>(e.properties=e.properties?.split(/\s/),e)),this.pageProgressionDirection=o.getAttribute("page-progression-direction"),this.navPath=this.getItemByProperty("nav")?.href,this.ncxPath=(this.getItemByID(o.getAttribute("toc"))??this.manifest.find(e=>e.mediaType===H.NCX))?.href;s=t(e.documentElement,"guide");s&&(this.guide=i(s,"reference").map(P("type","title","href")).map(({type:e,title:t,href:i})=>({label:t,type:e.split(/\s/),href:r(i)}))),this.cover=this.getItemByProperty("cover-image")??this.getItemByID(n(e,"meta").find(U("name","cover"))?.getAttribute("content"))??this.getItemByHref(this.guide?.find(e=>e.type.includes("cover"))?.href),this.cfis=(e=>{const t=[];var i,r,n=e[0]["parentNode"];const s=R(n);for([i,r]of I(n).entries()){var o=e[t.length];r===o&&t.push(S([s.concat({id:o.id,index:i})]))}return t})(a)}getItemByID(t){return this.manifest.find(e=>e.id===t)}getItemByHref(t){return this.manifest.find(e=>e.href===t)}getItemByProperty(t){return this.manifest.find(e=>e.properties?.includes(t))}resolveCFI(e){const t=k(e),i=(t.parent??t).shift();let r=N(this.opf,i);r&&"idref"!==r.nodeName&&(i.at(-1).id=null,r=N(this.opf,i));const n=r?.getAttribute("idref");return{index:this.spine.findIndex(e=>e.idref===n),anchor:e=>((e,t)=>{var i=A(t),r=A(t,!0),t=e.documentElement,i=D(t,i[0]),r=D(t,r[0]);const n=e.createRange();return i.before?n.setStartBefore(i.node):i.after?n.setStartAfter(i.node):n.setStart(i.node,i.offset),r.before?n.setEndBefore(r.node):r.after?n.setEndAfter(r.node):n.setEnd(r.node,r.offset),n})(e,t)}}}class ae{#cache=new Map;#children=new Map;#refCount=new Map;allowScript=!1;constructor({loadText:e,loadBlob:t,resources:i}){this.loadText=e,this.loadBlob=t,this.manifest=i.manifest,this.assets=i.manifest}createURL(e,t,i,r){if(!t)return"";i=URL.createObjectURL(new Blob([t],{type:i}));if(this.#cache.set(e,i),this.#refCount.set(e,1),r){const n=this.#children.get(r);n?n.push(e):this.#children.set(r,[e])}return i}ref(e,t){const i=this.#children.get(t);return i?.includes(e)||(this.#refCount.set(e,this.#refCount.get(e)+1),i?i.push(e):this.#children.set(t,[e])),this.#cache.get(e)}unref(e){if(this.#refCount.has(e)){var t=this.#refCount.get(e)-1;if(t<1){URL.revokeObjectURL(this.#cache.get(e)),this.#cache.delete(e),this.#refCount.delete(e);const i=this.#children.get(e);if(i)for(;i.length;)this.unref(i.pop());this.#children.delete(e)}else this.#refCount.set(e,t)}}async loadItem(e,t=[]){if(!e)return null;const{href:i,mediaType:r}=e;var n=H.JS.test(e.mediaType);if(n&&!this.allowScript)return null;var s=t.at(-1);return this.#cache.has(i)?this.ref(i,s):(n||[H.XHTML,H.HTML,H.CSS,H.SVG].includes(r))&&t.every(e=>e!==i)?this.loadReplaced(e,t):this.createURL(i,await this.loadBlob(i),r,s)}async loadHref(e,t,i=[]){if(X(e))return e;const r=W(e,t);var n=this.manifest.find(e=>e.href===r);return n?this.loadItem(n,i.concat(t)):e}async loadReplaced(e,n=[]){const{href:s,mediaType:i}=e;var r,o=n.at(-1),a=await this.loadText(s);if(!a)return null;if([H.XHTML,H.HTML,H.SVG].includes(i)){let t=(new DOMParser).parseFromString(a,i);if(i===H.XHTML&&t.querySelector("parsererror")&&(console.warn(t.querySelector("parsererror").innerText),e.mediaType=H.HTML,t=(new DOMParser).parseFromString(a,e.mediaType)),[H.XHTML,H.SVG].includes(e.mediaType)){let e=t.firstChild;for(;e instanceof ProcessingInstruction;)e.data&&(r=await q(e.data,/(?:^|\s*)(href\s*=\s*['"])([^'"]*)(['"])/i,(e,t,i,r)=>this.loadHref(i,s,n).then(e=>`${t}${e}${r}`)),e.replaceWith(t.createProcessingInstruction(e.target,r))),e=e.nextSibling}var l=async(e,t)=>e.setAttribute(t,await this.loadHref(e.getAttribute(t),s,n));for(const h of t.querySelectorAll("link[href]"))await l(h,"href");for(const d of t.querySelectorAll("[src]"))await l(d,"src");for(const u of t.querySelectorAll("[poster]"))await l(u,"poster");for(const f of t.querySelectorAll("object[data]"))await l(f,"data");for(const p of t.querySelectorAll("[*|href]:not([href]"))p.setAttributeNS(O.XLINK,"href",await this.loadHref(p.getAttributeNS(O.XLINK,"href"),s,n));for(const m of t.querySelectorAll("style"))m.textContent&&(m.textContent=await this.replaceCSS(m.textContent,s,n));for(const g of t.querySelectorAll("[style]"))g.setAttribute("style",await this.replaceCSS(g.getAttribute("style"),s,n));const c=(new XMLSerializer).serializeToString(t);return this.createURL(s,c,e.mediaType,o)}const c=i===H.CSS?await this.replaceCSS(a,s,n):await this.replaceString(a,s,n);return this.createURL(s,c,i,o)}async replaceCSS(e,i,r=[]){e=await q(e,/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,(e,t)=>this.loadHref(t,i,r).then(e=>`url("${e}")`));const t=await q(e,/@import\s*["']([^"'\n]*?)["']/gi,(e,t)=>this.loadHref(t,i,r).then(e=>`@import "${e}"`)),n=window?.innerWidth??800,s=window?.innerHeight??600;return t.replace(/-epub-/gi,"").replace(/(\d*\.?\d+)vw/gi,(e,t)=>parseFloat(t)*n/100+"px").replace(/(\d*\.?\d+)vh/gi,(e,t)=>parseFloat(t)*s/100+"px").replace(/page-break-(after|before|inside)/gi,(e,t)=>`-webkit-column-break-${t}`)}replaceString(e,o,t=[]){const a=new Map,i=this.assets.map(e=>{if(e.href!==o){var t=((e,t)=>{if(!e)return t;const i=e.replace(/\/$/,"").split("/"),r=t.replace(/\/$/,"").split("/");t=(i.length>r.length?i:r).findIndex((e,t)=>i[t]!==r[t]);return t<0?"":Array(i.length-t).fill("..").concat(r.slice(t)).join("/")})(o.slice(0,o.lastIndexOf("/")+1),e.href),i=encodeURI(t),r="/"+e.href,n=encodeURI(r),n=new Set([t,i,r,n]);for(const s of n)a.set(s,e);return Array.from(n)}}).flat().filter(e=>e);if(!i.length)return e;var r=new RegExp(i.map(K).join("|"),"g");return q(e,r,async e=>this.loadItem(a.get(e.replace(/^\//,"")),t.concat(o)))}unloadItem(e){this.unref(e?.href)}}class le{parser=new DOMParser;#encryption;constructor({loadText:e,loadBlob:t,getSize:i,sha1:r}){this.loadText=e,this.loadBlob=t,this.getSize=i,this.#encryption=new se(ne(r))}#parseXML(e){return e?this.parser.parseFromString(e,H.XML):null}async#loadXML(e){return this.#parseXML(await this.loadText(e))}async init(){const e=await this.#loadXML("META-INF/container.xml");if(!e)throw new Error("Failed to load container file");var t=Array.from(e.getElementsByTagNameNS(O.CONTAINER,"rootfile"),P("full-path","media-type")).filter(e=>"application/oebps-package+xml"===e.mediaType);if(!t.length)throw new Error("No package document defined in container");const i=t[0].fullPath;var r=await this.#loadXML(i);if(!r)throw new Error("Failed to load package document");t=await this.#loadXML("META-INF/encryption.xml");await this.#encryption.init(t,r),this.resources=new oe({opf:r,resolveHref:e=>W(e,i)});const s=new ae({loadText:this.loadText,loadBlob:e=>Promise.resolve(this.loadBlob(e)).then(this.#encryption.getDecoder(e)),resources:this.resources});this.sections=this.resources.spine.map((e,t)=>{var{idref:i,linear:r,properties:e=[]}=e;const n=this.resources.getItemByID(i);return n?{id:this.resources.getItemByID(i)?.href,load:()=>s.loadItem(n),unload:()=>s.unloadItem(n),createDocument:()=>this.loadDocument(n),size:this.getSize(n.href),cfi:this.resources.cfis[t],linear:r,pageSpread:(e=>{for(const t of e){if("page-spread-left"===t||"rendition:page-spread-left"===t)return"left";if("page-spread-right"===t||"rendition:page-spread-right"===t)return"right";if("rendition:page-spread-center"===t)return"center"}})(e),resolveHref:e=>W(e,n.href),loadMediaOverlay:()=>this.loadMediaOverlay(n)}:(console.warn(`Could not find item with ID "${i}" in manifest`),null)}).filter(e=>e);const{navPath:n,ncxPath:o}=this.resources;if(n)try{var a=V(await this.#loadXML(n),e=>W(e,n));this.toc=a.toc,this.pageList=a.pageList,this.landmarks=a.landmarks}catch(e){console.warn(e)}if(!this.toc&&o)try{var l=Y(await this.#loadXML(o),e=>W(e,o));this.toc=l.toc,this.pageList=l.pageList}catch(e){console.warn(e)}this.landmarks??=this.resources.guide;const{metadata:c,rendition:h,media:d}=(e=>{const{$:t,$$:i}=j(e,O.OPF),r=t(e.documentElement,"metadata"),s=Array.from(r.children),l=(o,t)=>{if(!t)return null;const{props:e=[],attrs:i=[]}=o,r=z(t);if(!e.length&&!i.length)return r;var n=t.getAttribute("id");const a=n?s.filter(U("refines","#"+n)):[];return Object.fromEntries([["value",r]].concat(e.map(e=>{var{many:t,recursive:i}=e,r="string"==typeof e?e:e.name,n=U("property",r);const s=i?o:e;return[$(r),t?a.filter(n).map(e=>l(s,e)):l(s,a.find(n))]})).concat(i.map(e=>[$(e),t.getAttribute(e)])))},o=s.filter(U("refines",null));e=t=>Object.fromEntries(i(r,"meta").filter(U("property",e=>e?.startsWith(t))).map(e=>[e.getAttribute("property").replace(t,""),z(e)]));return{metadata:Object.fromEntries(_.map(t=>{const{type:e,name:i,many:r}=t;var n="meta"===e?e=>e.namespaceURI===O.OPF&&e.getAttribute("property")===i:e=>e.namespaceURI===O.DC&&e.localName===i;return[$(i),r?o.filter(n).map(e=>l(t,e)):l(t,o.find(n))]})),rendition:e("rendition:"),media:e("media:")}})(r);this.rendition=h,this.media=d,d.duration=Q(d.duration),this.dir=this.resources.pageProgressionDirection,this.rawMetadata=c;l=c?.title?.[0];this.metadata={title:l?.value,sortAs:l?.fileAs,language:c?.language,identifier:ie(r),description:c?.description?.value,publisher:c?.publisher?.value,published:c?.date,modified:c?.dctermsModified,subject:c?.subject?.filter(({value:e,code:t})=>e||t)?.map(({value:e,code:t,scheme:i})=>({name:e,code:t,scheme:i})),rights:c?.rights?.value};const u={art:"artist",aut:"author",bkp:"producer",clr:"colorist",edt:"editor",ill:"illustrator",trl:"translator",pbl:"publisher"};r=i=>e=>{var t=[...new Set(e.role?.map(({value:e,scheme:t})=>(t&&"marc:relators"!==t?null:u[e])??i))],e={name:e.value,sortAs:e.fileAs};return[t.length?t:[i],e]};return c?.creator?.map(r("author"))?.concat(c?.contributor?.map?.(r("contributor")))?.forEach(([e,t])=>e.forEach(e=>{this.metadata[e]?this.metadata[e].push(t):this.metadata[e]=[t]})),this}async loadDocument(e){var t=await this.loadText(e.href);return this.parser.parseFromString(t,e.mediaType)}async loadMediaOverlay(e){e=e.mediaOverlay;if(!e)return null;const t=this.resources.getItemByID(e);e=await this.#loadXML(t.href);return ee(e,e=>W(e,t.href))}resolveCFI(e){return this.resources.resolveCFI(e)}resolveHref(e){const[t,i]=e.split("#"),r=this.resources.getItemByHref(decodeURI(t));return r?{index:this.resources.spine.findIndex(({idref:e})=>e===r.id),anchor:i?e=>((e,t)=>e.getElementById(t)??e.querySelector(`[name="${CSS.escape(t)}"]`))(e,i):()=>0}:null}splitTOCHref(e){return e?.split("#")??[]}getTOCFragment(e,t){return e.getElementById(t)??e.querySelector(`[name="${CSS.escape(t)}"]`)}isExternal(e){return X(e)}async getCover(){var e=this.resources?.cover;return e?.href?new Blob([await this.loadBlob(e.href)],{type:e.mediaType}):null}async getCalibreBookmarks(){const e=await this.loadText("META-INF/calibre_bookmarks.txt");var t="encoding=json+base64:";if(e?.startsWith(t)){t=atob(e.slice(t.length));return JSON.parse(t)}}}class ce{static getReaderConfig(e){return(JSON.parse(localStorage.getItem("readerConfig"))||{})[e]}static setReaderConfig(e,t){let i=JSON.parse(localStorage.getItem("readerConfig"))||{};i[e]=t,localStorage.setItem("readerConfig",JSON.stringify(i))}static getKookitConfig(e){return(JSON.parse(localStorage.getItem("kookitConfig"))||{})[e]}static setKookitConfig(e,t){let i=JSON.parse(localStorage.getItem("kookitConfig"))||{};i[e]=t,localStorage.setItem("kookitConfig",JSON.stringify(i))}static removeKookitConfig(){localStorage.removeItem("kookitConfig")}}let he=!1;const de=e=>Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address")),ue=e=>e.trim().replace(/(\r\n|\n|\r|\t)/gm,"").substring(0,100),fe=(c,h,d,u,f,p,m)=>g(void 0,void 0,void 0,function*(){var t="yes"===ce.getReaderConfig("isSliding");let e=document.getElementById("page-area");if(e){var i,r,n,s,o,a,l=e.getElementsByTagName("iframe")[0];if(l){let e=l.contentDocument;e&&(l=(l=Math.floor(c.clientWidth/12))%2==0?l:l-1,0{let n=window._.findLastIndex(i,{href:t});return n=t&&-1g(void 0,void 0,void 0,function*(){var e=parseInt(ce.getKookitConfig("chapterDocIndex")||"0"),t=ce.getKookitConfig("chapterHref")||"";0===e||(t=pe(e,t,r,"prev"))&&(ce.setKookitConfig("text","prevChapter"),ce.setKookitConfig("page",""),yield ge(t.index,t.label,t.href,r,i,n,s))}),ge=(a,l,c,h,d,u,f)=>g(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){let t=e.getElementsByTagName("iframe")[0];if(t){let e=t.contentDocument;var s,i,r,n,o;e&&(e.body.innerHTML="",t.height="0px",e.body.scrollTo(0,0),(-1===(a=l&&!a||l!==h[a].label?window._.findLastIndex(h,{label:l}):a)||a>h.length-1)&&(a=0),e.body.innerHTML=yield p(h[a].text),s=e,yield g(void 0,void 0,void 0,function*(){var t=Array.from(s.getElementsByTagName("link"));for(let e=0;e{console.log("finished")}}let i=[];for(let e=0;e{n.addEventListener("load",e)}))}try{yield Promise.race([Promise.all(i),new Promise((e,t)=>{setTimeout(()=>{t(new Error("Timeout"))},1e3)})])}catch(e){console.log(e)}}),ce.setKookitConfig("chapterTitle",l),ce.setKookitConfig("chapterHref",c),ce.setKookitConfig("chapterDocIndex",a+""),ce.setKookitConfig("percentage",a/h.length+""),ce.setKookitConfig("text",""),i=d,r=u,n=t,o=f,yield g(void 0,void 0,void 0,function*(){let t=n.contentDocument;if(t)if(yield Promise.all(Array.from(t.images).map(t=>t.complete?Promise.resolve(0!==t.naturalHeight):new Promise(e=>{t.addEventListener("load",()=>e(!0)),t.addEventListener("error",()=>e(!1))}))).then(e=>{e.every(e=>e)?console.log("all images loaded successfully!!"):console.log("some images failed to load, all finished loading")}),b(i,r,o),m(),"scroll"!==r){if(n.height=i.clientHeight+"px","double"===r){var e=Math.floor(i.clientWidth/12),e=(i.clientWidth+(e%2==0?e:e-1))/2;if((t.body.scrollWidth-t.body.clientWidth)/e%2==1){let e=document.createElement("div");e.setAttribute("style","height: "+t.body.clientHeight+"px"),t.body.appendChild(e)}}}else n.height=t.body.scrollHeight+"px",n.height=t.body.scrollHeight+"px"}),ye(d,u,"","","",""))}}}),ye=(a,l,c,h,d,u)=>g(void 0,void 0,void 0,function*(){let e=document.getElementById("page-area");if(e){var s=e.getElementsByTagName("iframe")[0];if(s){let n=s.contentDocument;if(n){let t=0,i=0,r=n.body;if(u&&"scroll"!==l){s=Math.floor(a.clientWidth/12),s=a.clientWidth+(s%2==0?s:s-1);i=s*(parseInt(u)-1)}else if(c){let e=de(n.body);var o=e.filter((e,t)=>ue(e.textContent).slim()&&(ue(e.textContent).slim()===ue(c).slim()||ue(e.textContent).slim()===window.ChineseS2T.t2s(ue(c).slim())||ue(e.textContent).slim()===window.ChineseS2T.s2t(ue(c)).slim())&&(Math.abs(t-parseInt(h))<2||"search"===h));if(0===o.length)return void console.log("fail");r=be(o[0],a),i=r?y(r.offsetLeft)-y(r.marginLeft||parseFloat(getComputedStyle(r).marginLeft)):"prevChapter"===c?n.body.scrollWidth:0,t=r?y(r.offsetTop)-y(r.marginTop||parseInt(getComputedStyle(r).marginTop)):0}else if(d&&-1{var i=Math.floor(t.clientWidth/12),i=i%2==0?i:i-1;return parseInt(y(e.offsetLeft)-y(e.marginLeft||parseFloat(getComputedStyle(e).marginLeft))+"")%((t.clientWidth+i)/2)!=0&&e.parentElement?be(e.parentElement,t):e},ve=(s,o,a)=>g(void 0,void 0,void 0,function*(){if(!he){let e=document.getElementById("page-area");if(e){var r=e.getElementsByTagName("iframe")[0];if(r){var r=r.contentDocument;if(r){let t=de(r.body);var r=t.filter(e=>ke(s,e,o)&&(e.textContent||"").trim()),n=r[0];let i=0;for(let e=0;e{let e=ce.getKookitConfig("chapterHref")||"",r=e.lastIndexOf("#"),n=e.substring(0,r),s=e.substring(r+1);for(let e=0;e-1)ce.setKookitConfig("chapterHref",e)}}})(r,a),n&&!((e,t)=>{let i=Math.floor(t.clientWidth/12),r=i%2===0?i:i-1;if(Math.abs(e.offsetLeft-be(e,t).offsetLeft)>(t.clientWidth+r)/2)return true;else return false})(n,s)?(ce.setKookitConfig("text",n&&n.textContent||""),ce.setKookitConfig("count",i+""),ce.setKookitConfig("page","")):ce.setKookitConfig("page",(null===(r=yield l(o))||void 0===r?void 0:r.currentPage)+""),he=!0,setTimeout(()=>{he=!1},100)}}}}}),we=(i,e,r,n,s)=>g(void 0,void 0,void 0,function*(){var e=parseInt(ce.getKookitConfig("chapterDocIndex")||"0"),t=ce.getKookitConfig("chapterHref")||"";e>=r.length-1||(t=pe(e,t,r,"next"))&&(ce.setKookitConfig("page",""),yield ge(t.index,t.label,t.href,r,i,n,s))}),xe=(i,r)=>{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){n=n.contentDocument;if(n){let e=de(n.body).filter(e=>!Ce(e)),t=e.filter(e=>ke(i,e,r)&&(e.textContent||"").trim());return("scroll"!==r?t:e).filter(e=>"img"!==e.textContent).map(e=>e.textContent)}}}},Ce=e=>{var t=e.children;let i=!1;for(var r=/^(address|blockquote|body|center|dir|div|dl|fieldset|form|h[1-6]|hr|isindex|menu|noframes|noscript|ol|p|pre|table|ul|dd|dt|frameset|li|tbody|td|tfoot|th|thead|tr|html)$/i,n=0;n{var r,n=!1,s=t.getBoundingClientRect();return"scroll"!==i&&t.textContent&&t.textContent.trim()?n=-10<(r=s.left)&&r<=e.clientWidth:t.textContent&&t.textContent.trim()?n=(t=s.top)>=e.scrollTop&&t<=e.scrollTop+e.clientHeight:"scroll"!==i&&(n=0<=(s=s.left)&&s<=e.clientWidth),n};const Te={svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",html:"text/html",htm:"text/html",xml:"text/xml",xhtml:"application/xhtml+xml",css:"text/css"},Le={"image/svg+xml":"svg","image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","application/zip":"zip","application/x-rar-compressed":"rar","application/x-7z-compressed":"7z","application/x-tar":"tar","text/html":"html","text/xml":"xml","application/xhtml+xml":"xhtml","text/css":"css"};class Se extends class{constructor(){this.callbacks={},this.callbacks.base={}}on(e,t){const i=this;if(void 0===e||""===e)return console.warn("wrong names"),!1;if(void 0===t)return console.warn("wrong callback"),!1;const r=this.resolveNames(e);return r.forEach(function(e){e=i.resolveName(e);i.callbacks[e.namespace]instanceof Object||(i.callbacks[e.namespace]={}),i.callbacks[e.namespace][e.value]instanceof Array||(i.callbacks[e.namespace][e.value]=[]),i.callbacks[e.namespace][e.value].push(t)}),this}off(e){const r=this;if(void 0===e||""===e)return console.warn("wrong name"),!1;const t=this.resolveNames(e);return t.forEach(function(e){var t=r.resolveName(e);if("base"!==t.namespace&&""===t.value)delete r.callbacks[t.namespace];else if("base"===t.namespace)for(const i in r.callbacks)r.callbacks[i]instanceof Object&&r.callbacks[i][t.value]instanceof Array&&(delete r.callbacks[i][t.value],0===Object.keys(r.callbacks[i]).length&&delete r.callbacks[i]);else r.callbacks[t.namespace]instanceof Object&&r.callbacks[t.namespace][t.value]instanceof Array&&(delete r.callbacks[t.namespace][t.value],0===Object.keys(r.callbacks[t.namespace]).length&&delete r.callbacks[t.namespace])}),this}trigger(e,t=[]){if(void 0===e||""===e)return console.warn("wrong name"),!1;const i=this;const r=t instanceof Array?t:[];let n=this.resolveNames(e);n=this.resolveName(n[0]),setTimeout(()=>{if("base"===n.namespace)for(const e in i.callbacks){if(i.callbacks[e]instanceof Object&&i.callbacks[e][n.value]instanceof Array&&i.callbacks[e][n.value])i.callbacks[e][n.value].forEach(function(e){e.apply(i,r)});else if(this.callbacks[n.namespace]instanceof Object&&i.callbacks[n.namespace][n.value]){if(""===n.value)return console.warn("wrong name"),this;i.callbacks[n.namespace][n.value].forEach(function(e){e.apply(i,r)})}return null}},100)}resolveNames(e){let t=e;return t=t.replace(/[^a-zA-Z0-9 ,/.]/g,""),t=t.replace(/[,/]+/g," "),t=t.split(" "),t}resolveName(e){const t={};var i=e.split(".");return t.original=e,t.value=i[0],t.namespace="base",1g(this,void 0,void 0,function*(){let e=new f(d);this.chapterList=yield e.getChapter(d.toc),this.chapterDocList=yield e.getChapterDoc();var t=this.chapterList,i=this.chapterDocList.map(e=>({href:e.href,label:e.label})),n=yield Promise.all(this.chapterDocList.map(i=>g(this,void 0,void 0,function*(){let t="";if(i.text.load){let e=yield fetch(yield i.text.load()).then(e=>e.blob());t=yield e.text()}return t})));let s=new window.JSZip;s.file("toc.json",JSON.stringify(t)),s.file("sections.json",JSON.stringify(i));let o=[];for(let r=0;re.blob());e.file(t+"."+Le[a.type],a),i[t].src="imgs/"+r+"/"+t+"."+Le[a.type]}catch(e){console.log(e)}}var l=Array.from(e.getElementsByTagName("link"));for(let i=0;ie.blob());t.file(i+"."+Le[c.type],c),e.href="css/"+r+"/"+i+"."+Le[c.type]}catch(e){console.log(e)}}o.push(e.documentElement.innerHTML)}let r=s.folder("chapters");for(let e=0;eg(this,void 0,void 0,function*(){h(yield new Response(e).arrayBuffer())})).catch(e=>{h("err")})}))}resolveChapter(e){var t=e;let i=-1;for(let e=0;e{let e=document.getElementById("page-area");if(e){var o=e.getElementsByTagName("iframe")[0];if(o){o=o.contentDocument;if(o){let e=de(o.body).filter(e=>!Ce(e)),t=e.filter(e=>(e.textContent||"").trim()),i=("scroll"!==s?t:e).filter(e=>"img"!==e.textContent).map(e=>e.textContent),r=0;return xe(n,s)&&0{let e=document.getElementById("page-area");if(e){var n=e.getElementsByTagName("iframe")[0];if(n){n=n.contentDocument;if(n){let e=de(n.body),t=e.filter(e=>(e.getAttribute("style")===r&&e.setAttribute("style",""),(e.textContent||"").trim()&&e.textContent===i));0!Ce(e));for(let e=0;esetTimeout(e,1e3))),yield ve(this.element,this.mode,this.flatChapter(this.chapterList))})}getPosition(){return{text:ce.getKookitConfig("text"),chapterTitle:ce.getKookitConfig("chapterTitle"),chapterDocIndex:ce.getKookitConfig("chapterDocIndex"),chapterHref:ce.getKookitConfig("chapterHref"),count:ce.getKookitConfig("count"),percentage:ce.getKookitConfig("percentage"),page:ce.getKookitConfig("page")}}setStyle(t){let e=document.getElementById("page-area");if(e){var i=e.getElementsByTagName("iframe")[0];if(i){let e=i.contentDocument;e&&e.body.setAttribute("style",t+e.body.getAttribute("style"))}}}}const Ae=e=>{if(!e)return"";const t=document.createElement("textarea");return t.innerHTML=e,t.value},Be={XML:"application/xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml"},Ee={name:[0,32,"string"],type:[60,4,"string"],creator:[64,4,"string"],numRecords:[76,2,"uint"]},Ie={compression:[0,2,"uint"],numTextRecords:[8,2,"uint"],recordSize:[10,2,"uint"],encryption:[12,2,"uint"]},Me={magic:[16,4,"string"],length:[20,4,"uint"],type:[24,4,"uint"],encoding:[28,4,"uint"],uid:[32,4,"uint"],version:[36,4,"uint"],titleOffset:[84,4,"uint"],titleLength:[88,4,"uint"],localeRegion:[94,1,"uint"],localeLanguage:[95,1,"uint"],resourceStart:[108,4,"uint"],huffcdic:[112,4,"uint"],numHuffcdic:[116,4,"uint"],exthFlag:[128,4,"uint"],trailingFlags:[240,4,"uint"],indx:[244,4,"uint"]},De={resourceStart:[108,4,"uint"],fdst:[192,4,"uint"],numFdst:[196,4,"uint"],frag:[248,4,"uint"],skel:[252,4,"uint"],guide:[260,4,"uint"]},Re={magic:[0,4,"string"],length:[4,4,"uint"],count:[8,4,"uint"]},Ne={magic:[0,4,"string"],length:[4,4,"uint"],type:[8,4,"uint"],idxt:[20,4,"uint"],numRecords:[24,4,"uint"],encoding:[28,4,"uint"],language:[32,4,"uint"],total:[36,4,"uint"],ordt:[40,4,"uint"],ligt:[44,4,"uint"],numLigt:[48,4,"uint"],numCncx:[52,4,"uint"]},Oe={magic:[0,4,"string"],length:[4,4,"uint"],numControlBytes:[8,4,"uint"]},He={magic:[0,4,"string"],offset1:[8,4,"uint"],offset2:[12,4,"uint"]},$e={magic:[0,4,"string"],length:[4,4,"uint"],numEntries:[8,4,"uint"],codeLength:[12,4,"uint"]},Fe={magic:[0,4,"string"],numEntries:[8,4,"uint"]},Ue={flags:[8,4,"uint"],dataStart:[12,4,"uint"],keyLength:[16,4,"uint"],keyStart:[20,4,"uint"]},Pe={1252:"windows-1252",65001:"utf-8"},ze={100:["creator","string",!0],101:["publisher"],103:["description"],104:["isbn"],105:["subject","string",!0],106:["date"],108:["contributor","string",!0],109:["rights"],110:["subjectCode","string",!0],112:["source","string",!0],113:["asin"],121:["boundary","uint"],122:["fixedLayout"],125:["numResources","uint"],126:["originalResolution"],127:["zeroGutter"],128:["zeroMargin"],129:["coverURI"],132:["regionMagnification"],201:["coverOffset","uint"],202:["thumbnailOffset","uint"],503:["title"],524:["language","string",!0],527:["pageProgressionDirection"]},je={1:["ar","ar-SA","ar-IQ","ar-EG","ar-LY","ar-DZ","ar-MA","ar-TN","ar-OM","ar-YE","ar-SY","ar-JO","ar-LB","ar-KW","ar-AE","ar-BH","ar-QA"],2:["bg"],3:["ca"],4:["zh","zh-TW","zh-CN","zh-HK","zh-SG"],5:["cs"],6:["da"],7:["de","de-DE","de-CH","de-AT","de-LU","de-LI"],8:["el"],9:["en","en-US","en-GB","en-AU","en-CA","en-NZ","en-IE","en-ZA","en-JM",null,"en-BZ","en-TT","en-ZW","en-PH"],10:["es","es-ES","es-MX",null,"es-GT","es-CR","es-PA","es-DO","es-VE","es-CO","es-PE","es-AR","es-EC","es-CL","es-UY","es-PY","es-BO","es-SV","es-HN","es-NI","es-PR"],11:["fi"],12:["fr","fr-FR","fr-BE","fr-CA","fr-CH","fr-LU","fr-MC"],13:["he"],14:["hu"],15:["is"],16:["it","it-IT","it-CH"],17:["ja"],18:["ko"],19:["nl","nl-NL","nl-BE"],20:["no","nb","nn"],21:["pl"],22:["pt","pt-BR","pt-PT"],23:["rm"],24:["ro"],25:["ru"],26:["hr",null,"sr"],27:["sk"],28:["sq"],29:["sv","sv-SE","sv-FI"],30:["th"],31:["tr"],32:["ur"],33:["id"],34:["uk"],35:["be"],36:["sl"],37:["et"],38:["lv"],39:["lt"],41:["fa"],42:["vi"],43:["hy"],44:["az"],45:["eu"],46:["hsb"],47:["mk"],48:["st"],49:["ts"],50:["tn"],52:["xh"],53:["zu"],54:["af"],55:["ka"],56:["fo"],57:["hi"],58:["mt"],59:["se"],62:["ms"],63:["kk"],65:["sw"],67:["uz",null,"uz-UZ"],68:["tt"],69:["bn"],70:["pa"],71:["gu"],72:["or"],73:["ta"],74:["te"],75:["kn"],76:["ml"],77:["as"],78:["mr"],79:["sa"],82:["cy","cy-GB"],83:["gl","gl-ES"],87:["kok"],97:["ne"],98:["fy"]},We=(e,t)=>{const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},Xe=(e,t,i)=>{const r=new e.constructor(e.length+t.length+i.length);return r.set(e),r.set(t,e.length),r.set(i,e.length+t.length),r},qe=new TextDecoder,Ke=e=>qe.decode(e),Je=e=>{if(e){var t=e.byteLength,t=4===t?"getUint32":2===t?"getUint16":"getUint8";return new DataView(e)[t](0)}},Ge=(e,n)=>Object.fromEntries(Array.from(Object.entries(e)).map(([e,[t,i,r]])=>[e,("string"===r?Ke:Je)(n.slice(t,t+i))])),Ze=e=>new TextDecoder(Pe[e]),_e=(e,t=0)=>{let i=0,r=0;for(const n of e.subarray(t,t+4))if(i=i<<7|(127&n)>>>0,r++,128&n)break;return{value:i,length:r}},Ve=e=>{let t=0;for(;0>=1)1==(1&e)&&t++;return t},Ye=e=>{let t=0;for(;0==(1&e);)e>>=1,t++;return t},Qe=t=>{let i=[];for(let e=0;e>>3,o=3+(7&n);for(let e=0;e{const r=await i(t.huffcdic),{magic:e,offset1:n,offset2:s}=Ge(He,r);if("HUFF"!==e)throw new Error("Invalid HUFF record");const d=Array.from({length:256},(e,t)=>n+4*t).map(e=>Je(r.slice(e,e+4))).map(e=>[128&e,31&e,e>>>8]),u=[null].concat(Array.from({length:32},(e,t)=>s+8*t).map(e=>[Je(r.slice(e,e+4)),Je(r.slice(e+4,e+8))])),f=[];for(let e=1;e{let a=new Uint8Array;var l=8*o.byteLength;for(let s=0;s{var e=i+32,r=e>>3;let n=0n;for(let e=i>>3;e<=r;e++)n=n<<8n|BigInt(t[e]??0);return n>>8n-BigInt(7&e)&0xffffffffn})(o,s));let[e,t,i]=d[c>>>24];if(!e){for(;c>>>32-tl)break;var h=i-(c>>>32-t);let[r,n]=f[h];n||(r=p(r),f[h]=[r,!0]),a=We(a,r)}return a};return p},tt=async(t,i)=>{const e=await i(t),r=Ge(Ne,e);if("INDX"!==r.magic)throw new Error("Invalid INDX record");const n=Ze(r.encoding),s=e.slice(r.length);var o=Ge(Oe,s);if("TAGX"!==o.magic)throw new Error("Invalid TAGX section");var a=(o.length-12)/4,l=Array.from({length:a},(e,t)=>new Uint8Array(s.slice(12+4*t,12+4*t+4)));const c={};let h=0;for(let e=0;e>Ye(C),null,x]));const U={};for([A,B,E,I]of F){const P=[];if(null!=B)for(let e=0;eJe(i.slice(8*t,8*t+4))).map((e,t,i)=>[e,i[t+1]])}loadRecord(e){e=this.#offsets[e];if(!e)throw new RangeError("Record index out of bounds");return this.#file.slice(...e).arrayBuffer()}async loadMagic(e){e=this.#offsets[e][0];return Ke(await this.#file.slice(e,e+4).arrayBuffer())}}{#start=0;#resourceStart;#decoder;#encoder;#decompress;#removeTrailingEntries;constructor({unzlib:e}){super(),this.unzlib=e}async open(e){await super.open(e),this.headers=this.#getHeaders(await super.loadRecord(0)),this.#resourceStart=this.headers.mobi.resourceStart;let t=8<=this.headers.mobi.version;if(!t){e=this.headers.exth?.boundary;if(e<4294967295)try{this.headers=this.#getHeaders(await super.loadRecord(e)),this.#start=e,t=!0}catch(e){console.warn(e),console.warn("Failed to open KF8; falling back to MOBI")}}return await this.#setup(),new(t?dt:st)(this).init()}#getHeaders(e){var t=Ge(Ie,e);const i=Ge(Me,e);if("MOBI"!==i.magic)throw new Error("Missing MOBI header");var{titleOffset:r,titleLength:n,localeLanguage:s,localeRegion:o}=i;i.title=e.slice(r,r+n);s=je[s];i.language=s?.[o>>2]??s?.[0];s=64&i.exthFlag?((t,e)=>{var{magic:i,count:r}=Ge(Re,t);if("EXTH"!==i)throw new Error("Invalid EXTH header");const n=Ze(e),s={};let o=12;for(let e=0;ee:2===e?Qe:17480===e?await et(t,this.loadRecord.bind(this)):null,!this.#decompress)throw new Error("Unknown compression type");var t=t["trailingFlags"];const r=1&t,n=Ve(t>>>1);this.#removeTrailingEntries=t=>{for(let e=0;e{let t=0;for(const i of e.subarray(-4))128&i&&(t=0),t=t<<7|127&i;return t})(t);t=t.subarray(0,-i)}var e;return r&&(e=1+(3&t[t.length-1]),t=t.subarray(0,-e)),t}}decode(...e){return this.#decoder.decode(...e)}encode(...e){return this.#encoder.encode(...e)}loadRecord(e){return super.loadRecord(this.#start+e)}loadMagic(e){return super.loadMagic(this.#start+e)}loadText(e){return this.loadRecord(e+1).then(e=>new Uint8Array(e)).then(this.#removeTrailingEntries).then(this.#decompress)}async loadResource(e){const t=await super.loadRecord(this.#resourceStart+e);e=Ke(t.slice(0,4));return"FONT"===e?(async(e,t)=>{var{flags:i,dataStart:r,keyLength:n,keyStart:s}=Ge(Ue,e);const o=new Uint8Array(e.slice(r));if(2&i)for(var r=16===n?1024:1040,a=new Uint8Array(e.slice(s,s+n)),l=Math.min(r,o.length),c=0;c{const{table:i,cncx:r}=await tt(e,t),n=i.map(({tagMap:e},t)=>({index:t,offset:e[1]?.[0],size:e[2]?.[0],label:r[e[3]]??"",headingLevel:e[4]?.[0],pos:e[6],parent:e[21]?.[0],firstChild:e[22]?.[0],lastChild:e[23]?.[0]})),s=t=>(null==t.firstChild||(t.children=n.filter(e=>e.parent===t.index).map(s)),t);return n.filter(e=>0===e.headingLevel).map(s)})(e,this.loadRecord.bind(this))}getMetadata(){const{mobi:e,exth:t}=this.headers;return{identifier:e.uid.toString(),title:Ae(t?.title||this.decode(e.title)),author:t?.creator?.map(Ae),publisher:Ae(t?.publisher),language:t?.language??e.language,published:t?.date,description:Ae(t?.description),subject:t?.subject?.map(Ae),rights:Ae(t?.rights)}}async getCover(){var e=this.headers["exth"],e=e?.coverOffset<4294967295?e?.coverOffset:e?.thumbnailOffset<4294967295?e?.thumbnailOffset:null;if(null!=e){e=await this.loadResource(e);return new Blob([e])}}}const rt=/<\s*(?:mbp:)?pagebreak[^>]*>/gi,nt=/<[^<>]+filepos=['"]{0,1}(\d+)[^<>]*>/gi;class st{parser=new DOMParser;serializer=new XMLSerializer;#resourceCache=new Map;#textCache=new Map;#cache=new Map;#sections;#fileposList=[];#type=Be.HTML;constructor(e){this.mobi=e}async init(){let t=new Uint8Array;for(let e=0;eString.fromCharCode(e)).join("");this.#sections=[0].concat(Array.from(r.matchAll(rt),e=>e.index)).map((e,t,i)=>r.slice(e,i[t+1])).map(e=>Uint8Array.from(e,e=>e.charCodeAt(0))).map(e=>({book:this,raw:e})).reduce((e,t)=>{var i=e[e.length-1];return t.start=i?.end??0,t.end=t.start+t.raw.byteLength,e.concat(t)},[]),this.sections=this.#sections.map((e,t)=>({id:t,load:()=>this.loadSection(e),createDocument:()=>this.createDocument(e),size:e.end-e.start}));const n=[];try{const s=await this.mobi.getNCX(),o=({label:e,offset:t,children:i})=>{var r=t.toString().padStart(10,"0"),t=`filepos:${r}`;return n.push(r),{label:e=Ae(e),href:t,subitems:i?.map(o)}};if(this.toc=s?.map(o),this.landmarks=await this.getGuide(),!this.toc){var e=this.landmarks.find(({type:e})=>e?.includes("toc"))?.href;if(e){var i=this.resolveHref(e)["index"];const a=await this.sections[i].createDocument();this.toc=Array.from(a.querySelectorAll("a[filepos]"),e=>({label:e.innerText?.trim(),href:`filepos:${e.getAttribute("filepos")}`}))}}}catch(e){console.warn(e)}return this.#fileposList=[...new Set(n.concat(Array.from(r.matchAll(nt),e=>e[1])))].map(e=>({filepos:e,number:Number(e)})).sort((e,t)=>e.number-t.number),this.metadata=this.mobi.getMetadata(),this.getCover=this.mobi.getCover.bind(this.mobi),this}async getGuide(){const e=await this.createDocument(this.#sections[0]);return Array.from(e.getElementsByTagName("reference"),e=>({label:e.getAttribute("title"),type:e.getAttribute("type")?.split(/\s/),href:`filepos:${e.getAttribute("filepos")}`}))}async loadResource(e){if(this.#resourceCache.has(e))return this.#resourceCache.get(e);var t=await this.mobi.loadResource(e),t=URL.createObjectURL(new Blob([t]));return this.#resourceCache.set(e,t),t}async loadRecindex(e){return this.loadResource(Number(e)-1)}async replaceResources(e){for(const s of e.querySelectorAll("img[recindex]")){var t=s.getAttribute("recindex");try{s.src=await this.loadRecindex(t)}catch(e){console.warn(`Failed to load image ${t}`)}}for(const o of e.querySelectorAll("[mediarecindex]")){var i=o.getAttribute("mediarecindex"),r=o.getAttribute("recindex");try{o.src=await this.loadRecindex(i),r&&(o.poster=await this.loadRecindex(r))}catch(e){console.warn(`Failed to load media ${i}`)}}for(const a of e.querySelectorAll("[filepos]")){var n=a.getAttribute("filepos");a.href=`filepos:${n}`}}async loadText(t){if(this.#textCache.has(t))return this.#textCache.get(t);const r=t["raw"],n=this.#fileposList.filter(({number:e})=>e>=t.start&&e({...e,offset:e.number-t.start}));let s=r;n.length&&(s=r.subarray(0,n[0].offset),n.forEach(({filepos:e,offset:t},i)=>{i=n[i+1],e=this.mobi.encode(``);s=Xe(s,e,r.subarray(t,i?.offset))}));var e=this.mobi.decode(s).replaceAll(rt,"");return this.#textCache.set(t,e),e}async createDocument(e){e=await this.loadText(e);return this.parser.parseFromString(e,this.#type)}async loadSection(e){if(this.#cache.has(e))return this.#cache.get(e);const t=await this.createDocument(e),i=t.createElement("style");t.head.append(i),i.append(t.createTextNode(`blockquote { margin-block-start: 0; margin-block-end: 0; margin-inline-start: 1em; margin-inline-end: 0; - }`)),await this.replaceResources(t);var r=this.serializer.serializeToString(t),r=URL.createObjectURL(new Blob([r],{type:this.#type}));return this.#cache.set(e,r),r}resolveHref(e){const t=e.match(/filepos:(.*)/)[1],i=Number(t);return{index:this.#sections.findIndex(e=>e.end>i),anchor:e=>e.getElementById(`filepos${t}`)}}splitTOCHref(e){e=e.match(/filepos:(.*)/)[1];const t=Number(e);return[this.#sections.findIndex(e=>e.end>t),`filepos${e}`]}getTOCFragment(e,t){return e.getElementById(t)}isExternal(e){return/^(?!blob|filepos)\w+:/i.test(e)}}const ot=/kindle:(flow|embed):(\w+)(?:\?mime=(\w+\/[-+.\w]+))?/,at=/kindle:pos:fid:(\w+):off:(\w+)/,lt=e=>{var[t,e]=e.match(at).slice(1);return{fid:parseInt(t,32),off:parseInt(e,32)}},ct=(e=0,t=0)=>`kindle:pos:fid:${e.toString(32).toUpperCase().padStart(4,"0")}:off:${t.toString(32).toUpperCase().padStart(10,"0")}`,ht=e=>{var t=e.match(/\s(id|name|aid)\s*=\s*['"]([^'"]*)['"]/i);if(t){var[,e,t]=t;return`[${e}="${CSS.escape(t)}"]`}};class dt{parser=new DOMParser;#cache=new Map;#fragmentOffsets=new Map;#fragmentSelectors=new Map;#tables={};#sections;#fullRawLength;#rawHead=new Uint8Array;#rawTail=new Uint8Array;#lastLoadedHead=-1;#lastLoadedTail=-1;#checkType=!0;#type=Be.XHTML;constructor(e){this.mobi=e}async init(){const e=this.mobi.loadRecord.bind(this.mobi);var t=this.mobi.headers["kf8"];try{const l=await e(t.fdst);var i=Ge(Fe,l);if("FDST"!==i.magic)throw new Error("Missing FDST record");var r=Array.from({length:i.numEntries},(e,t)=>12+8*t).map(e=>[Je(l.slice(e,e+4)),Je(l.slice(e+4,e+8))]);this.#tables.fdstTable=r,this.#fullRawLength=r[r.length-1][1]}catch{}const n=(await tt(t.skel,e)).table.map(({name:e,tagMap:t},i)=>({index:i,name:e,numFrag:t[1][0],offset:t[6][0],length:t[6][1]})),s=await tt(t.frag,e),o=s.table.map(({name:e,tagMap:t})=>({insertOffset:parseInt(e),selector:s.cncx[t[2][0]],index:t[4][0],offset:t[6][0],length:t[6][1]}));this.#tables.skelTable=n,this.#tables.fragTable=o,this.#sections=n.reduce((e,t)=>{var i=e[e.length-1],r=i?.fragEnd??0,n=r+t.numFrag;const s=o.slice(r,n);r=t.length+s.map(e=>e.length).reduce((e,t)=>e+t);return e.concat({skel:t,frags:s,fragEnd:n,length:r,totalLength:(i?.totalLength??0)+r})},[]),this.#sections.unshift({frags:[]}),this.sections=this.#sections.map((e,t)=>e.frags.length?{id:t,load:()=>this.loadSection(e),createDocument:()=>this.createDocument(e),size:e.length}:{linear:"no"});try{const c=await this.mobi.getNCX(),h=({label:e,pos:t,children:i})=>{var[r,n]=t,t=ct(r,n);const s=this.#fragmentOffsets.get(r);return s?s.push(n):this.#fragmentOffsets.set(r,[n]),{label:Ae(e),href:t,subitems:i?.map(h)}};this.toc=c?.map(h),this.landmarks=await this.getGuide()}catch(e){console.warn(e)}const a=this.mobi.headers["exth"];return this.dir=a.pageProgressionDirection,this.rendition={layout:"true"===a.fixedLayout?"pre-paginated":"reflowable",viewport:Object.fromEntries(a.originalResolution?.split("x")?.slice(0,2)?.map((e,t)=>[t?"height":"width",e])??[])},this.metadata=this.mobi.getMetadata(),this.getCover=this.mobi.getCover.bind(this.mobi),this}async getResourcesByMagic(t){const i={};var r=this.mobi.headers.kf8.resourceStart,n=this.mobi.pdb.numRecords;for(let e=r;ee===o);s&&(i[s]=e)}catch{}return i}async getGuide(){var e=this.mobi.headers.kf8.guide;if(e<4294967295){var t=this.mobi.loadRecord.bind(this.mobi);const{table:i,cncx:r}=await tt(e,t);return i.map(({name:e,tagMap:t})=>({label:r[t[1][0]]??"",type:e?.split(/\s/),href:ct(t[6]?.[0]??t[3]?.[0])}))}}async loadResourceBlob(e){var{resourceType:t,id:i,type:e}=(e=>{var[t,i,e]=e.match(ot).slice(1);return{resourceType:t,id:parseInt(i,32),type:e}})(e),i="flow"===t?await this.loadFlow(i):await this.mobi.loadResource(i-1),i=[Be.XHTML,Be.HTML,Be.CSS,Be.SVG].includes(e)?await this.replaceResources(this.mobi.decode(i)):i;return new Blob([i],{type:e})}async loadResource(e){if(this.#cache.has(e))return this.#cache.get(e);var t=await this.loadResourceBlob(e),t=URL.createObjectURL(t);return this.#cache.set(e,t),t}replaceResources(e){return(async(e,t,i)=>{const r=[];e.replace(t,(...e)=>(r.push(e),null));const n=[];for(const s of r)n.push(await i(...s));return e.replace(t,()=>n.shift())})(e,new RegExp(ot,"g"),this.loadResource.bind(this))}async loadRaw(e,t){var i=t-this.#rawHead.length,r=null==this.#fullRawLength?1/0:this.#fullRawLength-this.#rawTail.length-e;if(i<0||ie;){var s=this.mobi.headers.palmdoc.numTextRecords-1-++this.#lastLoadedTail,s=await this.mobi.loadText(s);this.#rawTail=We(s,this.#rawTail)}r=this.#fullRawLength-this.#rawTail.length;return this.#rawTail.slice(e-r,t-r)}loadFlow(e){if(e<4294967295)return this.loadRaw(...this.#tables.fdstTable[e])}async loadText(e){var{skel:t,frags:i,length:e}=e;const r=await this.loadRaw(t.offset,t.offset+e);let n=r.slice(0,t.length);for(const c of i){var s=c.insertOffset-t.offset,o=t.length+c.offset,a=r.slice(o,o+c.length);n=Xe(n.slice(0,s),a,n.slice(s));s=this.#fragmentOffsets.get(c.index);if(s)for(const h of s){var l=this.mobi.decode(a).slice(h),l=ht(l);this.#setFragmentSelector(c.index,h,l)}}return this.mobi.decode(n)}async createDocument(e){e=await this.loadText(e);return this.parser.parseFromString(e,this.#type)}async loadSection(e){if(this.#cache.has(e))return this.#cache.get(e);var t=await this.loadText(e);this.#checkType&&this.parser.parseFromString(t,this.#type).querySelector("parsererror")&&(this.#type=Be.HTML),this.#checkType&&(this.#checkType=!1);t=await this.replaceResources(t),t=URL.createObjectURL(new Blob([t],{type:this.#type}));return this.#cache.set(e,t),t}getIndexByFID(t){return this.#sections.findIndex(e=>e.frags.some(e=>e.index===t))}#setFragmentSelector(e,t,i){const r=this.#fragmentSelectors.get(e);if(r)r.set(t,i);else{const r=new Map;this.#fragmentSelectors.set(e,r),r.set(t,i)}}async resolveHref(e){const{fid:t,off:i}=lt(e);var r=this.getIndexByFID(t);if(!(r<0)){const s=this.#fragmentSelectors.get(t)?.get(i);if(s)return{index:r,anchor:e=>e.querySelector(s)};const{skel:o,frags:a}=this.#sections[r];var n=a.find(e=>e.index===t),e=o.offset+o.length+n.offset,n=await this.loadRaw(e,e+n.length),n=this.mobi.decode(n).slice(i);const l=ht(n);this.#setFragmentSelector(t,i,l);return{index:r,anchor:e=>e.querySelector(l)}}}splitTOCHref(e){e=lt(e);return[this.getIndexByFID(e.fid),e]}getTOCFragment(e,{fid:t,off:i}){i=this.#fragmentSelectors.get(t)?.get(i);return e.querySelector(i)}isExternal(e){return/^(?!blob|kindle)\w+:/i.test(e)}}const ut=(e,t=!1)=>{e=(new DOMParser).parseFromString(t?(e=>{let t="",i=e.split("\n");for(let e of i)if(yt(e).slim()&&bt(yt(e).slim()))t+=`

${yt(e).slim()}

`;else t+=`

${e}

`;if(t)return t;else return`

Title

${e}

`})(e):e,"text/html");let i=Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,title"));0===i.length&&(i=(e=>{let t=e.getElementsByTagName("*"),i=Array.from(t).filter(e=>{return e.childNodes.length===1&&e.childNodes[0].nodeType===Node.TEXT_NODE&&bt(yt(e.textContent).slim())}),r=[];return i.forEach(e=>{const t=document.createElement("h1");t.innerHTML=e.innerText;e.parentNode.replaceChild(t,e);r.push(t)}),r})(e));for(let e=0;e{let t=[],i=e.split("
").filter(e=>e.trim()!==""),r=i.map(e=>{return wt(e)||xt(e)});return t=i.map((e,t)=>{return{index:t,title:r[t],text:e,href:"title"+t}})})(e.body.innerHTML),o={getCover:()=>""};return o.sections=s.map(e=>({id:e.index,load:()=>(e=>g(void 0,void 0,void 0,function*(){return URL.createObjectURL(new Blob([s[e].text],{type:"text/html"}))}))(e.index),unload:()=>{e.index}})),o.toc=s.map(e=>({label:e.title,href:"title"+e.index})).filter(e=>""!==e.label),o.rendition={layout:"pre-paginated"},o.resolveHref=e=>({index:parseInt(e.substring(5,e.length))}),o.splitTOCHref=e=>[e,null],o.getTOCFragment=e=>e.documentElement,o};let ft=["章","节","回","節","卷","部","輯","辑","話","集","话","篇"," "," "],pt=["[","(","。",";",";"],mt=["CHAPTER","Chapter","序章","前言","声明","写在前面的话","后记","楔子","后序"],gt=[" "," ","、","·",".",":",":"];String.prototype.contains=function(e){return-1"="!==e&&"-"!==e&&"_"!==e&&"+"!==e).join("")};const yt=e=>e.trim().replace(/(\r\n|\n|\r|\t)/gm,"").substring(0,100),bt=e=>{return e&&(n=e,!(0-1r.startsWith(e)||r.startsWith(window.ChineseS2T.s2t(e))).length||e.startsWith("第")&&vt(e)||e.startsWith("卷")&&(!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test((i=e).substring(1,i.indexOf(" ")))&&!/^\d+$/.test(i.substring(1,i.indexOf(" "))))||(!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(i.substring(1,i.indexOf(" ")))&&!/^\d+$/.test(i.substring(1,i.indexOf(" "))))||!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(i.substring(1))&&!/^\d+$/.test(i.substring(1)))))||e.contains("第")&&e.lastIndexOf("第")<2&&vt(e.substr(e.indexOf("第")))||(t=e,0-1{let i=!1;for(let e=0;e{const t=/([\s\S]*?)<\/h[1-6]>/.exec(e);return t?t[1].replace(/</g,"<").replace(/>/g,">"):""},xt=e=>{const t=/([\s\S]*?)<\/title>/.exec(e);return t?t[1].replace(/</g,"<").replace(/>/g,">"):""};const Ct=({entries:e,loadBlob:r,getSize:t},i)=>{const n=new Map,s=new Map,o=[".jpg",".jpeg",".png",".gif",".bmp",".webp",".svg"],a=e.map(e=>e.filename).filter(t=>o.some(e=>t.endsWith(e))).sort(),l={getCover:()=>r(a[0])};return l.metadata={title:i.name},l.sections=a.map(e=>({id:e,load:()=>(async e=>{if(n.has(e))return n.get(e);var t=URL.createObjectURL(await r(e)),i=URL.createObjectURL(new Blob([`<img src="${t}">`],{type:"text/html"}));return s.set(e,[t,i]),n.set(e,i),i})(e),unload:()=>(e=>{s.get(e)?.forEach?.(e=>URL.revokeObjectURL(e)),s.delete(e),n.delete(e)})(e),size:t(e)})),l.toc=a.map(e=>({label:e,href:e})),l.rendition={layout:"pre-paginated"},l.resolveHref=t=>({index:l.sections.findIndex(e=>e.id===t)}),l.splitTOCHref=e=>[e,null],l.getTOCFragment=e=>e.documentElement,l};const kt=e=>e?.trim()?.replace(/\s{2,}/g," "),Tt=e=>kt(e?.textContent),Lt={XLINK:"http://www.w3.org/1999/xlink",EPUB:"http://www.idpf.org/2007/ops"},St={XML:"application/xml",XHTML:"application/xhtml+xml"},At={strong:["strong","self"],emphasis:["em","self"],style:["span","self"],a:"anchor",strikethrough:["s","self"],sub:["sub","self"],sup:["sup","self"],code:["code","self"],image:"image"};const Bt={epigraph:["blockquote"],subtitle:["h2",At],"text-author":["p",At],date:["p",At],stanza:"stanza"},Et={title:["header",{p:["h1",At],"empty-line":["br"]}],epigraph:["blockquote","self"],image:"image",annotation:["aside"],section:["section","self"],p:["p",At],poem:["blockquote",Bt],subtitle:["h2",At],cite:["blockquote","self"],"empty-line":["br"],table:["table",{tr:["tr",["align"]],th:["th",["colspan","rowspan","align","valign"]],td:["td",["colspan","rowspan","align","valign"]]}],"text-author":["p",At]};Bt.epigraph.push(Et);const It={image:"image",title:["section",{p:["h1",At],"empty-line":["br"]}],epigraph:["section",Et],section:["section",Et]},Mt=e=>{const t=e.getAttributeNS(Lt.XLINK,"href");var[,i]=t.split("#");const r=e.getRootNode().getElementById(i);return r?`data:${r.getAttribute("content-type")};base64,${r.textContent}`:t};class Dt{constructor(e){this.fb2=e,this.doc=document.implementation.createDocument(Lt.XHTML,"html")}image(e){const t=this.doc.createElement("img");return t.alt=e.getAttribute("alt"),t.title=e.getAttribute("title"),t.setAttribute("src",Mt(e)),t}anchor(e){const t=this.convert(e,{a:["a",At]});return t.setAttribute("href",e.getAttributeNS(Lt.XLINK,"href")),"note"===e.getAttribute("type")&&t.setAttributeNS(Lt.EPUB,"epub:type","noteref"),t}stanza(e){const t=this.convert(e,{stanza:["p",{title:["header",{p:["strong",At],"empty-line":["br"]}],subtitle:["p",At]}]});for(const i of e.children)"v"===i.nodeName&&(t.append(this.doc.createTextNode(i.textContent)),t.append(this.doc.createElement("br")));return t}convert(e,t){if(3===e.nodeType)return this.doc.createTextNode(e.textContent);if(4===e.nodeType)return this.doc.createCDATASection(e.textContent);if(8===e.nodeType)return this.doc.createComment(e.textContent);var i=t?.[e.nodeName];if(!i)return null;if("string"==typeof i)return this[i](e);var[r,i]=i;const n=this.doc.createElement(r);if(e.id&&(n.id=e.id),n.classList.add(e.nodeName),Array.isArray(i))for(const l of i)n.setAttribute(l,e.getAttribute(l));var s="self"===i?t:Array.isArray(i)?null:i;let o=e.firstChild;for(;o;){var a=this.convert(o,s);a&&n.append(a),o=o.nextSibling}return n}}const Rt=URL.createObjectURL(new Blob([` + }`)),await this.replaceResources(t);var r=this.serializer.serializeToString(t),r=URL.createObjectURL(new Blob([r],{type:this.#type}));return this.#cache.set(e,r),r}resolveHref(e){const t=e.match(/filepos:(.*)/)[1],i=Number(t);return{index:this.#sections.findIndex(e=>e.end>i),anchor:e=>e.getElementById(`filepos${t}`)}}splitTOCHref(e){e=e.match(/filepos:(.*)/)[1];const t=Number(e);return[this.#sections.findIndex(e=>e.end>t),`filepos${e}`]}getTOCFragment(e,t){return e.getElementById(t)}isExternal(e){return/^(?!blob|filepos)\w+:/i.test(e)}}const ot=/kindle:(flow|embed):(\w+)(?:\?mime=(\w+\/[-+.\w]+))?/,at=/kindle:pos:fid:(\w+):off:(\w+)/,lt=e=>{var[t,e]=e.match(at).slice(1);return{fid:parseInt(t,32),off:parseInt(e,32)}},ct=(e=0,t=0)=>`kindle:pos:fid:${e.toString(32).toUpperCase().padStart(4,"0")}:off:${t.toString(32).toUpperCase().padStart(10,"0")}`,ht=e=>{var t=e.match(/\s(id|name|aid)\s*=\s*['"]([^'"]*)['"]/i);if(t){var[,e,t]=t;return`[${e}="${CSS.escape(t)}"]`}};class dt{parser=new DOMParser;#cache=new Map;#fragmentOffsets=new Map;#fragmentSelectors=new Map;#tables={};#sections;#fullRawLength;#rawHead=new Uint8Array;#rawTail=new Uint8Array;#lastLoadedHead=-1;#lastLoadedTail=-1;#checkType=!0;#type=Be.XHTML;constructor(e){this.mobi=e}async init(){const e=this.mobi.loadRecord.bind(this.mobi);var t=this.mobi.headers["kf8"];try{const l=await e(t.fdst);var i=Ge(Fe,l);if("FDST"!==i.magic)throw new Error("Missing FDST record");var r=Array.from({length:i.numEntries},(e,t)=>12+8*t).map(e=>[Je(l.slice(e,e+4)),Je(l.slice(e+4,e+8))]);this.#tables.fdstTable=r,this.#fullRawLength=r[r.length-1][1]}catch{}const n=(await tt(t.skel,e)).table.map(({name:e,tagMap:t},i)=>({index:i,name:e,numFrag:t[1][0],offset:t[6][0],length:t[6][1]})),s=await tt(t.frag,e),o=s.table.map(({name:e,tagMap:t})=>({insertOffset:parseInt(e),selector:s.cncx[t[2][0]],index:t[4][0],offset:t[6][0],length:t[6][1]}));this.#tables.skelTable=n,this.#tables.fragTable=o,this.#sections=n.reduce((e,t)=>{var i=e[e.length-1],r=i?.fragEnd??0,n=r+t.numFrag;const s=o.slice(r,n);r=t.length+s.map(e=>e.length).reduce((e,t)=>e+t);return e.concat({skel:t,frags:s,fragEnd:n,length:r,totalLength:(i?.totalLength??0)+r})},[]),this.#sections.unshift({frags:[]}),this.sections=this.#sections.map((e,t)=>e.frags.length?{id:t,load:()=>this.loadSection(e),createDocument:()=>this.createDocument(e),size:e.length}:{linear:"no"});try{const c=await this.mobi.getNCX(),h=({label:e,pos:t,children:i})=>{var[r,n]=t,t=ct(r,n);const s=this.#fragmentOffsets.get(r);return s?s.push(n):this.#fragmentOffsets.set(r,[n]),{label:Ae(e),href:t,subitems:i?.map(h)}};this.toc=c?.map(h),this.landmarks=await this.getGuide()}catch(e){console.warn(e)}const a=this.mobi.headers["exth"];return this.dir=a.pageProgressionDirection,this.rendition={layout:"true"===a.fixedLayout?"pre-paginated":"reflowable",viewport:Object.fromEntries(a.originalResolution?.split("x")?.slice(0,2)?.map((e,t)=>[t?"height":"width",e])??[])},this.metadata=this.mobi.getMetadata(),this.getCover=this.mobi.getCover.bind(this.mobi),this}async getResourcesByMagic(t){const i={};var r=this.mobi.headers.kf8.resourceStart,n=this.mobi.pdb.numRecords;for(let e=r;e<n;e++)try{const o=await this.mobi.loadMagic(e);var s=t.find(e=>e===o);s&&(i[s]=e)}catch{}return i}async getGuide(){var e=this.mobi.headers.kf8.guide;if(e<4294967295){var t=this.mobi.loadRecord.bind(this.mobi);const{table:i,cncx:r}=await tt(e,t);return i.map(({name:e,tagMap:t})=>({label:r[t[1][0]]??"",type:e?.split(/\s/),href:ct(t[6]?.[0]??t[3]?.[0])}))}}async loadResourceBlob(e){var{resourceType:t,id:i,type:e}=(e=>{var[t,i,e]=e.match(ot).slice(1);return{resourceType:t,id:parseInt(i,32),type:e}})(e),i="flow"===t?await this.loadFlow(i):await this.mobi.loadResource(i-1),i=[Be.XHTML,Be.HTML,Be.CSS,Be.SVG].includes(e)?await this.replaceResources(this.mobi.decode(i)):i;return new Blob([i],{type:e})}async loadResource(e){if(this.#cache.has(e))return this.#cache.get(e);var t=await this.loadResourceBlob(e),t=URL.createObjectURL(t);return this.#cache.set(e,t),t}replaceResources(e){return(async(e,t,i)=>{const r=[];e.replace(t,(...e)=>(r.push(e),null));const n=[];for(const s of r)n.push(await i(...s));return e.replace(t,()=>n.shift())})(e,new RegExp(ot,"g"),this.loadResource.bind(this))}async loadRaw(e,t){var i=t-this.#rawHead.length,r=null==this.#fullRawLength?1/0:this.#fullRawLength-this.#rawTail.length-e;if(i<0||i<r){for(;this.#rawHead.length<t;){var n=++this.#lastLoadedHead,n=await this.mobi.loadText(n);this.#rawHead=We(this.#rawHead,n)}return this.#rawHead.slice(e,t)}for(;this.#fullRawLength-this.#rawTail.length>e;){var s=this.mobi.headers.palmdoc.numTextRecords-1-++this.#lastLoadedTail,s=await this.mobi.loadText(s);this.#rawTail=We(s,this.#rawTail)}r=this.#fullRawLength-this.#rawTail.length;return this.#rawTail.slice(e-r,t-r)}loadFlow(e){if(e<4294967295)return this.loadRaw(...this.#tables.fdstTable[e])}async loadText(e){var{skel:t,frags:i,length:e}=e;const r=await this.loadRaw(t.offset,t.offset+e);let n=r.slice(0,t.length);for(const c of i){var s=c.insertOffset-t.offset,o=t.length+c.offset,a=r.slice(o,o+c.length);n=Xe(n.slice(0,s),a,n.slice(s));s=this.#fragmentOffsets.get(c.index);if(s)for(const h of s){var l=this.mobi.decode(a).slice(h),l=ht(l);this.#setFragmentSelector(c.index,h,l)}}return this.mobi.decode(n)}async createDocument(e){e=await this.loadText(e);return this.parser.parseFromString(e,this.#type)}async loadSection(e){if(this.#cache.has(e))return this.#cache.get(e);var t=await this.loadText(e);this.#checkType&&this.parser.parseFromString(t,this.#type).querySelector("parsererror")&&(this.#type=Be.HTML),this.#checkType&&(this.#checkType=!1);t=await this.replaceResources(t),t=URL.createObjectURL(new Blob([t],{type:this.#type}));return this.#cache.set(e,t),t}getIndexByFID(t){return this.#sections.findIndex(e=>e.frags.some(e=>e.index===t))}#setFragmentSelector(e,t,i){const r=this.#fragmentSelectors.get(e);if(r)r.set(t,i);else{const r=new Map;this.#fragmentSelectors.set(e,r),r.set(t,i)}}async resolveHref(e){const{fid:t,off:i}=lt(e);var r=this.getIndexByFID(t);if(!(r<0)){const s=this.#fragmentSelectors.get(t)?.get(i);if(s)return{index:r,anchor:e=>e.querySelector(s)};const{skel:o,frags:a}=this.#sections[r];var n=a.find(e=>e.index===t),e=o.offset+o.length+n.offset,n=await this.loadRaw(e,e+n.length),n=this.mobi.decode(n).slice(i);const l=ht(n);this.#setFragmentSelector(t,i,l);return{index:r,anchor:e=>e.querySelector(l)}}}splitTOCHref(e){e=lt(e);return[this.getIndexByFID(e.fid),e]}getTOCFragment(e,{fid:t,off:i}){i=this.#fragmentSelectors.get(t)?.get(i);return e.querySelector(i)}isExternal(e){return/^(?!blob|kindle)\w+:/i.test(e)}}const ut=(e,t=!1)=>{e=(new DOMParser).parseFromString(t?(e=>{let t="",i=e.split("\n");for(let e of i)if(yt(e).slim()&&bt(yt(e).slim()))t+=`<h1>${yt(e).slim()}</h1>`;else t+=`<p>${e}</p>`;if(t)return t;else return`<h1>Title</h1><p>${e}</p>`})(e):e,"text/html");let i=Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,title"));0===i.length&&(i=(e=>{let t=e.getElementsByTagName("*"),i=Array.from(t).filter(e=>{return e.childNodes.length===1&&e.childNodes[0].nodeType===Node.TEXT_NODE&&bt(yt(e.textContent).slim())}),r=[];for(let e=0;e<i.length;e++){const n=i[e];const s=document.createElement("h1");s.innerHTML=n.innerText;n.parentNode.replaceChild(s,n);r.push(s)}return r})(e));for(let e=0;e<i.length;e++){var r=document.createElement("address"),n=document.createTextNode(" ");r.appendChild(n),i[e].parentNode&&i[e].parentNode.insertBefore(r,i[e])}const s=(e=>{let t=[],i=e.split("<address> </address>").filter(e=>e.trim()!==""),r=i.map(e=>{return wt(e)||xt(e)});return t=i.map((e,t)=>{return{index:t,label:r[t],text:e,href:"title"+t}})})(e.body.innerHTML),o={getCover:()=>""};return o.sections=s.map(e=>({id:e.index,load:()=>(e=>g(void 0,void 0,void 0,function*(){return URL.createObjectURL(new Blob([s[e].text],{type:"text/html"}))}))(e.index),unload:()=>{e.index}})),o.toc=s.map(e=>({label:e.label,href:"title"+e.index})).filter(e=>""!==e.label),o.rendition={layout:"pre-paginated"},o.resolveHref=e=>({index:parseInt(e.substring(5,e.length))}),o.splitTOCHref=e=>[e,null],o.getTOCFragment=e=>e.documentElement,o};let ft=["章","节","回","節","卷","部","輯","辑","話","集","话","篇"," "," "],pt=["[","(","。",";",";"],mt=["CHAPTER","Chapter","序章","前言","声明","写在前面的话","后记","楔子","后序"],gt=[" "," ","、","·",".",":",":"];String.prototype.contains=function(e){return-1<this.indexOf(e)},String.prototype.slim=function(){return this.split("").filter(e=>"="!==e&&"-"!==e&&"_"!==e&&"+"!==e).join("")};const yt=e=>e.trim().replace(/(\r\n|\n|\r|\t)/gm,"").substring(0,100),bt=e=>{return e&&(n=e,!(0<pt.filter(e=>-1<n.indexOf(e)).length))&&(r=e,0<mt.filter(e=>r.startsWith(e)||r.startsWith(window.ChineseS2T.s2t(e))).length||e.startsWith("第")&&vt(e)||e.startsWith("卷")&&(!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test((i=e).substring(1,i.indexOf(" ")))&&!/^\d+$/.test(i.substring(1,i.indexOf(" "))))||(!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(i.substring(1,i.indexOf(" ")))&&!/^\d+$/.test(i.substring(1,i.indexOf(" "))))||!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(i.substring(1))&&!/^\d+$/.test(i.substring(1)))))||e.contains("第")&&e.lastIndexOf("第")<2&&vt(e.substr(e.indexOf("第")))||(t=e,0<gt.filter(e=>-1<t.indexOf(e)&&(/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(t.substring(0,t.indexOf(e)))||/^\d+$/.test(t.substring(0,t.indexOf(e))))).length));var t,i,r,n},vt=t=>{let i=!1;for(let e=0;e<ft.length&&((/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(t.substring(1,t.indexOf(ft[e])).trim())||/^\d+$/.test(t.substring(1,t.indexOf(ft[e])).trim()))&&(i=!0),!i);e++);return i},wt=e=>{const t=/<h[1-6]>([\s\S]*?)<\/h[1-6]>/.exec(e);return t?t[1].replace(/</g,"<").replace(/>/g,">"):""},xt=e=>{const t=/<title>([\s\S]*?)<\/title>/.exec(e);return t?t[1].replace(/</g,"<").replace(/>/g,">"):""};const Ct=({entries:e,loadBlob:r,getSize:t},i)=>{const n=new Map,s=new Map,o=[".jpg",".jpeg",".png",".gif",".bmp",".webp",".svg"],a=e.map(e=>e.filename).filter(t=>o.some(e=>t.endsWith(e))).sort(),l={getCover:()=>r(a[0])};return l.metadata={title:i.name},l.sections=a.map(e=>({id:e,load:()=>(async e=>{if(n.has(e))return n.get(e);var t=URL.createObjectURL(await r(e)),i=URL.createObjectURL(new Blob([`<img src="${t}">`],{type:"text/html"}));return s.set(e,[t,i]),n.set(e,i),i})(e),unload:()=>(e=>{s.get(e)?.forEach?.(e=>URL.revokeObjectURL(e)),s.delete(e),n.delete(e)})(e),size:t(e)})),l.toc=a.map(e=>({label:e,href:e})),l.rendition={layout:"pre-paginated"},l.resolveHref=t=>({index:l.sections.findIndex(e=>e.id===t)}),l.splitTOCHref=e=>[e,null],l.getTOCFragment=e=>e.documentElement,l};const kt=e=>e?.trim()?.replace(/\s{2,}/g," "),Tt=e=>kt(e?.textContent),Lt={XLINK:"http://www.w3.org/1999/xlink",EPUB:"http://www.idpf.org/2007/ops"},St={XML:"application/xml",XHTML:"application/xhtml+xml"},At={strong:["strong","self"],emphasis:["em","self"],style:["span","self"],a:"anchor",strikethrough:["s","self"],sub:["sub","self"],sup:["sup","self"],code:["code","self"],image:"image"};const Bt={epigraph:["blockquote"],subtitle:["h2",At],"text-author":["p",At],date:["p",At],stanza:"stanza"},Et={title:["header",{p:["h1",At],"empty-line":["br"]}],epigraph:["blockquote","self"],image:"image",annotation:["aside"],section:["section","self"],p:["p",At],poem:["blockquote",Bt],subtitle:["h2",At],cite:["blockquote","self"],"empty-line":["br"],table:["table",{tr:["tr",["align"]],th:["th",["colspan","rowspan","align","valign"]],td:["td",["colspan","rowspan","align","valign"]]}],"text-author":["p",At]};Bt.epigraph.push(Et);const It={image:"image",title:["section",{p:["h1",At],"empty-line":["br"]}],epigraph:["section",Et],section:["section",Et]},Mt=e=>{const t=e.getAttributeNS(Lt.XLINK,"href");var[,i]=t.split("#");const r=e.getRootNode().getElementById(i);return r?`data:${r.getAttribute("content-type")};base64,${r.textContent}`:t};class Dt{constructor(e){this.fb2=e,this.doc=document.implementation.createDocument(Lt.XHTML,"html")}image(e){const t=this.doc.createElement("img");return t.alt=e.getAttribute("alt"),t.title=e.getAttribute("title"),t.setAttribute("src",Mt(e)),t}anchor(e){const t=this.convert(e,{a:["a",At]});return t.setAttribute("href",e.getAttributeNS(Lt.XLINK,"href")),"note"===e.getAttribute("type")&&t.setAttributeNS(Lt.EPUB,"epub:type","noteref"),t}stanza(e){const t=this.convert(e,{stanza:["p",{title:["header",{p:["strong",At],"empty-line":["br"]}],subtitle:["p",At]}]});for(const i of e.children)"v"===i.nodeName&&(t.append(this.doc.createTextNode(i.textContent)),t.append(this.doc.createElement("br")));return t}convert(e,t){if(3===e.nodeType)return this.doc.createTextNode(e.textContent);if(4===e.nodeType)return this.doc.createCDATASection(e.textContent);if(8===e.nodeType)return this.doc.createComment(e.textContent);var i=t?.[e.nodeName];if(!i)return null;if("string"==typeof i)return this[i](e);var[r,i]=i;const n=this.doc.createElement(r);if(e.id&&(n.id=e.id),n.classList.add(e.nodeName),Array.isArray(i))for(const l of i)n.setAttribute(l,e.getAttribute(l));var s="self"===i?t:Array.isArray(i)?null:i;let o=e.firstChild;for(;o;){var a=this.convert(o,s);a&&n.append(a),o=o.nextSibling}return n}}const Rt=URL.createObjectURL(new Blob([` @namespace epub "http://www.idpf.org/2007/ops"; body > img, section > img { display: block; @@ -53,4 +53,4 @@ body:not(.notesBodyType) > .title, body:not(.notesBodyType) > .epigraph { <html xmlns="http://www.w3.org/1999/xhtml"> <head><link href="${Rt}" rel="stylesheet" type="text/css"/></head> <body>${s}</body> -</html>`);var s=new Blob([n],{type:St.XHTML});const o=URL.createObjectURL(s);return{ids:e,title:kt(i.querySelector(".title, .subtitle, p")?.textContent??(i.classList.contains("title")?i.textContent:"")),titles:t,load:()=>o,createDocument:()=>(new DOMParser).parseFromString(n,St.XHTML),size:s.size-Array.from(i.querySelectorAll("[src]"),e=>e.getAttribute("src")?.length??0).reduce((e,t)=>e+t,0),linear:r}}),h=new Map;return t.sections=c.map((e,t)=>{var{ids:i,load:r,createDocument:n,size:s,linear:e}=e;for(const o of i)o&&h.set(o,t);return{id:t,load:r,createDocument:n,size:s,linear:e}}),t.toc=c.map(({title:e,titles:t},i)=>{const r=i.toString();return{label:e,href:r,subitems:t?.length?t.map(({title:e,index:t})=>({label:e,href:`${r}#${t}`})):null}}).filter(e=>e),t.resolveHref=e=>{const[t,i]=e.split("#");return t?{index:Number(t),anchor:e=>e.querySelector(`[${Nt}="${i}"]`)}:{index:h.get(i),anchor:e=>e.getElementById(i)}},t.splitTOCHref=e=>e?.split("#")?.map(e=>Number(e))??[],t.getTOCFragment=(e,t)=>e.querySelector(`[${Nt}="${t}"]`),t};const Ht=s=>g(void 0,void 0,void 0,function*(){let r=yield window.JSZip.loadAsync(s);var e=r.file("toc.json");let t=[];e&&(t=JSON.parse(yield e.async("string")));e=r.file("sections.json");let i=[];e&&(i=JSON.parse(yield e.async("string")));const n={getCover:()=>""};return n.sections=i.map((e,t)=>({id:e.href,load:()=>(i=>g(void 0,void 0,void 0,function*(){var e=r.file("chapters/"+i+".html");let t="";return e&&(t=yield e.async("string")),URL.createObjectURL(new Blob([t],{type:"text/html"}))}))(t),unload:()=>{},loadAsset:e=>(i=>g(void 0,void 0,void 0,function*(){var e=r.file(i);let t="";return e&&(t=yield e.async("arraybuffer")),URL.createObjectURL(new Blob([t],{type:Te[i.split(".").reverse()[0]]}))}))(e)})),n.toc=t.map(e=>({label:e.title,href:e.href,subitems:e.subitems})),n.rendition={layout:"pre-paginated"},n.resolveHref=e=>({index:window._.findLastIndex(i,{href:e})}),n.splitTOCHref=e=>[e,null],n.getTOCFragment=e=>e.documentElement,n});window.e=window.eval,window.a=window.atob,e.CacheRender=class extends Se{constructor(e,t){super(t,"CACHE"),this.cacheBuffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.element=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book=yield Ht(this.cacheBuffer);let e=new d(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}},e.ComicRender=class extends Se{constructor(e,t,i){super(t,i),this.comicBuffer=e,this.mode=t,this.format=i,this.chapterList=[],this.chapterDocList=[],this.book="",this.element="",this.rpc}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,s(i),this.book||(yield this.parse());let e=new d(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){var e,t,i=new Blob([this.comicBuffer]),i=new File([i],"book."+this.format.toLocaleLowerCase(),{lastModified:(new Date).getTime(),type:i.type});"CBZ"===this.format?(e=yield this.makeZipLoader(i),this.book=Ct(e,i)):"CBT"===this.format?(e=yield this.makeTarLoader(),this.book=Ct(e,i)):"CBR"===this.format?(this.rpc=yield window.RPC.new("./lib/libunrar/worker.js",{loaded:function(){console.log("loaded")},progressShow:function(e,t,i){console.log(i)}}),yield new Promise(e=>setTimeout(e,200)),t=yield this.makeRarLoader(),this.book=Ct(t,i)):"CB7"===this.format&&(t=yield this.make7zLoader(),this.book=Ct(t,i))})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}makeZipLoader(c){return g(this,void 0,void 0,function*(){const{ZipReader:e,BlobReader:t,TextWriter:i,BlobWriter:r}=window.zip;window.zip.configure({useWebWorkers:!1});const n=new e(new t(c)),s=yield n.getEntries(),o=new Map(s.map(e=>[e.filename,e]));var a=i=>(e,...t)=>o.has(e)?i(o.get(e),...t):null,l=a(e=>e.getData(new i)),a=a((e,t)=>e.getData(new r(t)));return{entries:s,loadText:l,loadBlob:a,getSize:e=>{return null!==(e=null===(e=o.get(e))||void 0===e?void 0:e.uncompressedSize)&&void 0!==e?e:0}}})}makeTarLoader(){return g(this,void 0,void 0,function*(){const e=yield window.untar(this.comicBuffer),r=new Map(e.map(e=>[e.name,e]));var t=i=>(e,...t)=>r.has(e)?i(r.get(e),...t):null,i=t(e=>e.readAsString()),t=t((e,t)=>e.blob);return{entries:e.map(e=>({filename:e.name})),loadText:i,loadBlob:t,getSize:e=>{return null!==(e=null===(e=r.get(e))||void 0===e?void 0:e.size)&&void 0!==e?e:0}}})}makeRarLoader(){return g(this,void 0,void 0,function*(){return new Promise((n,e)=>{var t=[this.comicBuffer],i=[{name:"book.rar",content:this.comicBuffer}];this.rpc.transferables=t,this.rpc.unrar(i,null,0).then(e=>{var t=this.getRarEntries(e.ls);const r=new Map(Object.values(t).map(e=>[e.fullFileName,e]));var i=i=>(e,...t)=>r.has(e)?i(r.get(e),...t):null,e=i(e=>e.fullFileName),i=i((e,t)=>new Blob([e.fileContent]));n({entries:Object.values(t).map(e=>({filename:e.fullFileName})),loadText:e,loadBlob:i,getSize:e=>{return null!==(e=null===(e=r.get(e))||void 0===e?void 0:e.fileSize)&&void 0!==e?e:0}})}).catch(e=>{console.log(e)})})})}make7zLoader(){return g(this,void 0,void 0,function*(){var e="./lib/7z-wasm/7zz.wasm";if(!window.wasmBinary){const a=yield fetch(e,{credentials:"same-origin"});if(!a.ok)throw"failed to load wasm binary file at '"+e+"'";window.wasmBinary=yield a.arrayBuffer()}const t=yield window.SevenZip({wasmBinary:window.wasmBinary});var i=new Uint8Array(this.comicBuffer),r="archive.cb7",e=t.FS.open(r,"w+");t.FS.write(e,i,0,i.length),t.FS.close(e),t.callMain(["x",r]);const n=t.FS,s=this.get7zEntries(n.lookupPath("/").node),o=new Map(s.map(e=>[e.name,e]));e=i=>(e,...t)=>o.has(e)?i(o.get(e),...t):null,r=e(e=>e.name),e=e((e,t)=>new Blob([e.buffer]));return{entries:s.map(e=>({filename:e.name})),loadText:r,loadBlob:e,getSize:e=>{return null!==(e=null===(e=o.get(e))||void 0===e?void 0:e.packSize)&&void 0!==e?e:0}}})}getRarEntries(t){const e=Object.keys(t);let i=[];return e.forEach(e=>{"dir"===t[e].type?i=i.concat(this.getRarEntries(t[e].ls)):i.push({fullFileName:e,fileContent:t[e].fileContent,fileSize:t[e].fileSize})}),i}get7zEntries(e){const t=e.contents,i=Object.keys(t).filter(e=>"archive.cb7"!=e&&"dev"!=e&&"home"!=e&&"proc"!=e&&"tmp"!=e);let r=[];return i.forEach(e=>{t[e].isFolder?r=r.concat(this.get7zEntries(t[e])):r.push({name:e,buffer:t[e].contents,size:t[e].usedBytes})}),r}getMetadata(){return g(this,void 0,void 0,function*(){return new Promise((i,e)=>g(this,void 0,void 0,function*(){this.book||(yield this.parse());var e=yield this.book.getCover(),t=new FileReader;t.readAsDataURL(e),t.onloadend=()=>{i({cover:t.result})}}))})}},e.DocxRender=class extends Se{constructor(e,t){super(t,"MD"),this.docxBuffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.element=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book||(yield this.parse());let e=new d(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){return new Promise((t,e)=>{window.mammoth.convertToHtml({arrayBuffer:this.docxBuffer}).then(e=>g(this,void 0,void 0,function*(){this.book=ut(e.value,!0),t()}))})})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}},e.EpubRender=class extends Se{constructor(e,t){super(t,"EPUB"),this.epubBuffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.book="",this.element=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book||(yield this.parse());let e=new d(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){var e=new Blob([this.epubBuffer]),e=new File([e],"book",{lastModified:(new Date).getTime(),type:e.type}),e=yield this.makeZipLoader(e);this.book=yield new le(e).init()})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}makeZipLoader(c){return g(this,void 0,void 0,function*(){const{ZipReader:e,BlobReader:t,TextWriter:i,BlobWriter:r}=window.zip;window.zip.configure({useWebWorkers:!1});const n=new e(new t(c)),s=yield n.getEntries(),o=new Map(s.map(e=>[e.filename,e]));var a=i=>(e,...t)=>o.has(e)?i(o.get(e),...t):null,l=a(e=>e.getData(new i)),a=a((e,t)=>e.getData(new r(t)));return{entries:s,loadText:l,loadBlob:a,getSize:e=>{return null!==(e=null===(e=o.get(e))||void 0===e?void 0:e.uncompressedSize)&&void 0!==e?e:0}}})}getMetadata(){return g(this,void 0,void 0,function*(){this.book||(yield this.parse());let e=new d(this.book);return yield e.getMetadata()})}},e.Fb2Render=class extends Se{constructor(e,t){super(t,"FB2"),this.fb2Buffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.book="",this.element=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book||(yield this.parse());let e=new d(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){var e=new Blob([this.fb2Buffer]);this.book=yield Ot(e)})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}getMetadata(){return g(this,void 0,void 0,function*(){this.book||(yield this.parse());let e=new d(this.book);return yield e.getMetadata()})}},e.HtmlRender=class extends Se{constructor(e,t,i){super(t,"MD"),this.htmlBuffer=e,this.mode=t,this.format=i,this.chapterList=[],this.chapterDocList=[],this.element=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book||(yield this.parse());let e=new d(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){return new Promise((r,e)=>{var t=new Blob([this.htmlBuffer],{type:Te[this.format.toLocaleLowerCase()]}),i=new FileReader;i.onload=i=>g(this,void 0,void 0,function*(){var e;let t=null===(e=i.target)||void 0===e?void 0:e.result;"MHTML"===this.format&&(t=window.mhtml2html.convert(t).window.document.documentElement.innerHTML),this.book=ut(t,!0),r()}),i.readAsText(t,"UTF-8")})})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}},e.MdRender=class extends Se{constructor(e,t){super(t,"MD"),this.mdBuffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.element=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book||(yield this.parse());let e=new d(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){return new Promise((i,e)=>{var t=new Blob([this.mdBuffer],{type:"text/plain"}),r=new FileReader;r.onload=t=>g(this,void 0,void 0,function*(){var e=window.marked(null===(e=t.target)||void 0===e?void 0:e.result);this.book=ut(e,!0),i()}),r.readAsText(t,"UTF-8")})})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}},e.MobiRender=class extends Se{constructor(e,t){super(t,"MOBI"),this.mobiBuffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.book="",this.element=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book||(yield this.parse());let e=new d(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){var e=new Blob([this.mobiBuffer]),e=new File([e],"book",{lastModified:(new Date).getTime(),type:e.type});(yield(async e=>{return"BOOKMOBI"===Ke(await e.slice(60,68).arrayBuffer())})(e))&&(this.book=yield new it({unzlib:window.fflate.unzlibSync}).open(e))})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}getMetadata(){return g(this,void 0,void 0,function*(){this.book||(yield this.parse());let e=new d(this.book);return yield e.getMetadata()})}},e.TxtRender=class extends Se{constructor(e,t,i){super(t,"TXT"),this.txtBuffer=e,this.encoding=i,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.bookStr="",this.element="",this.book=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book||(yield this.parse());let e=new d(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){var e=new TextDecoder(this.encoding||"utf8").decode(this.txtBuffer);this.book=ut(e,!0)})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}getMetadata(){return g(this,void 0,void 0,function*(){var t=new Uint8Array(this.txtBuffer);let i="";for(let e=0;e<100;++e)i+=String.fromCharCode(t[e]);return{charset:window.jschardet.detect(i).encoding||"utf-8"||"utf8"}})}},Object.defineProperty(e,"__esModule",{value:!0})}); +</html>`);var s=new Blob([n],{type:St.XHTML});const o=URL.createObjectURL(s);return{ids:e,title:kt(i.querySelector(".title, .subtitle, p")?.textContent??(i.classList.contains("title")?i.textContent:"")),titles:t,load:()=>o,createDocument:()=>(new DOMParser).parseFromString(n,St.XHTML),size:s.size-Array.from(i.querySelectorAll("[src]"),e=>e.getAttribute("src")?.length??0).reduce((e,t)=>e+t,0),linear:r}}),h=new Map;return t.sections=c.map((e,t)=>{var{ids:i,load:r,createDocument:n,size:s,linear:e}=e;for(const o of i)o&&h.set(o,t);return{id:t,load:r,createDocument:n,size:s,linear:e}}),t.toc=c.map(({title:e,titles:t},i)=>{const r=i.toString();return{label:e,href:r,subitems:t?.length?t.map(({title:e,index:t})=>({label:e,href:`${r}#${t}`})):null}}).filter(e=>e),t.resolveHref=e=>{const[t,i]=e.split("#");return t?{index:Number(t),anchor:e=>e.querySelector(`[${Nt}="${i}"]`)}:{index:h.get(i),anchor:e=>e.getElementById(i)}},t.splitTOCHref=e=>e?.split("#")?.map(e=>Number(e))??[],t.getTOCFragment=(e,t)=>e.querySelector(`[${Nt}="${t}"]`),t};const Ht=s=>g(void 0,void 0,void 0,function*(){let r=yield window.JSZip.loadAsync(s);var e=r.file("toc.json");let t=[];e&&(t=JSON.parse(yield e.async("string")));e=r.file("sections.json");let i=[];e&&(i=JSON.parse(yield e.async("string")));const n={getCover:()=>""};return n.sections=i.map((e,t)=>({id:e.href,load:()=>(i=>g(void 0,void 0,void 0,function*(){var e=r.file("chapters/"+i+".html");let t="";return e&&(t=yield e.async("string")),URL.createObjectURL(new Blob([t],{type:"text/html"}))}))(t),unload:()=>{},loadAsset:e=>(i=>g(void 0,void 0,void 0,function*(){var e=r.file(i);let t="";return e&&(t=yield e.async("arraybuffer")),URL.createObjectURL(new Blob([t],{type:Te[i.split(".").reverse()[0]]}))}))(e)})),n.toc=t.map(e=>({label:e.label,href:e.href,subitems:e.subitems})),n.rendition={layout:"pre-paginated"},n.resolveHref=e=>({index:window._.findLastIndex(i,{href:e})}),n.splitTOCHref=e=>[e,null],n.getTOCFragment=e=>e.documentElement,n});window.e=window.eval,window.a=window.atob,e.CacheRender=class extends Se{constructor(e,t){super(t,"CACHE"),this.cacheBuffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.element=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book=yield Ht(this.cacheBuffer);let e=new f(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}},e.ComicRender=class extends Se{constructor(e,t,i){super(t,i),this.comicBuffer=e,this.mode=t,this.format=i,this.chapterList=[],this.chapterDocList=[],this.book="",this.element="",this.rpc}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,s(i),this.book||(yield this.parse());let e=new f(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){var e,t,i=new Blob([this.comicBuffer]),i=new File([i],"book."+this.format.toLocaleLowerCase(),{lastModified:(new Date).getTime(),type:i.type});"CBZ"===this.format?(e=yield this.makeZipLoader(i),this.book=Ct(e,i)):"CBT"===this.format?(e=yield this.makeTarLoader(),this.book=Ct(e,i)):"CBR"===this.format?(this.rpc=yield window.RPC.new("./lib/libunrar/worker.js",{loaded:function(){console.log("loaded")},progressShow:function(e,t,i){console.log(i)}}),yield new Promise(e=>setTimeout(e,200)),t=yield this.makeRarLoader(),this.book=Ct(t,i)):"CB7"===this.format&&(t=yield this.make7zLoader(),this.book=Ct(t,i))})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}makeZipLoader(c){return g(this,void 0,void 0,function*(){const{ZipReader:e,BlobReader:t,TextWriter:i,BlobWriter:r}=window.zip;window.zip.configure({useWebWorkers:!1});const n=new e(new t(c)),s=yield n.getEntries(),o=new Map(s.map(e=>[e.filename,e]));var a=i=>(e,...t)=>o.has(e)?i(o.get(e),...t):null,l=a(e=>e.getData(new i)),a=a((e,t)=>e.getData(new r(t)));return{entries:s,loadText:l,loadBlob:a,getSize:e=>{return null!==(e=null===(e=o.get(e))||void 0===e?void 0:e.uncompressedSize)&&void 0!==e?e:0}}})}makeTarLoader(){return g(this,void 0,void 0,function*(){const e=yield window.untar(this.comicBuffer),r=new Map(e.map(e=>[e.name,e]));var t=i=>(e,...t)=>r.has(e)?i(r.get(e),...t):null,i=t(e=>e.readAsString()),t=t((e,t)=>e.blob);return{entries:e.map(e=>({filename:e.name})),loadText:i,loadBlob:t,getSize:e=>{return null!==(e=null===(e=r.get(e))||void 0===e?void 0:e.size)&&void 0!==e?e:0}}})}makeRarLoader(){return g(this,void 0,void 0,function*(){return new Promise((n,e)=>{var t=[this.comicBuffer],i=[{name:"book.rar",content:this.comicBuffer}];this.rpc.transferables=t,this.rpc.unrar(i,null,0).then(e=>{var t=this.getRarEntries(e.ls);const r=new Map(Object.values(t).map(e=>[e.fullFileName,e]));var i=i=>(e,...t)=>r.has(e)?i(r.get(e),...t):null,e=i(e=>e.fullFileName),i=i((e,t)=>new Blob([e.fileContent]));n({entries:Object.values(t).map(e=>({filename:e.fullFileName})),loadText:e,loadBlob:i,getSize:e=>{return null!==(e=null===(e=r.get(e))||void 0===e?void 0:e.fileSize)&&void 0!==e?e:0}})}).catch(e=>{console.log(e)})})})}make7zLoader(){return g(this,void 0,void 0,function*(){var e="./lib/7z-wasm/7zz.wasm";if(!window.wasmBinary){const a=yield fetch(e,{credentials:"same-origin"});if(!a.ok)throw"failed to load wasm binary file at '"+e+"'";window.wasmBinary=yield a.arrayBuffer()}const t=yield window.SevenZip({wasmBinary:window.wasmBinary});var i=new Uint8Array(this.comicBuffer),r="archive.cb7",e=t.FS.open(r,"w+");t.FS.write(e,i,0,i.length),t.FS.close(e),t.callMain(["x",r]);const n=t.FS,s=this.get7zEntries(n.lookupPath("/").node),o=new Map(s.map(e=>[e.name,e]));e=i=>(e,...t)=>o.has(e)?i(o.get(e),...t):null,r=e(e=>e.name),e=e((e,t)=>new Blob([e.buffer]));return{entries:s.map(e=>({filename:e.name})),loadText:r,loadBlob:e,getSize:e=>{return null!==(e=null===(e=o.get(e))||void 0===e?void 0:e.packSize)&&void 0!==e?e:0}}})}getRarEntries(t){var i=Object.keys(t);let r=[];for(let e=0;e<i.length;e++){var n=i[e];"dir"===t[n].type?r=r.concat(this.getRarEntries(t[n].ls)):r.push({fullFileName:n,fileContent:t[n].fileContent,fileSize:t[n].fileSize})}return r}get7zEntries(e){var t=e.contents,i=Object.keys(t).filter(e=>"archive.cb7"!=e&&"dev"!=e&&"home"!=e&&"proc"!=e&&"tmp"!=e);let r=[];for(let e=0;e<i.length;e++){var n=i[e];t[n].isFolder?r=r.concat(this.get7zEntries(t[n])):r.push({name:n,buffer:t[n].contents,size:t[n].usedBytes})}return r}getMetadata(){return g(this,void 0,void 0,function*(){return new Promise((i,e)=>g(this,void 0,void 0,function*(){this.book||(yield this.parse());var e=yield this.book.getCover(),t=new FileReader;t.readAsDataURL(e),t.onloadend=()=>{i({cover:t.result})}}))})}},e.DocxRender=class extends Se{constructor(e,t){super(t,"MD"),this.docxBuffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.element=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book||(yield this.parse());let e=new f(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){return new Promise((t,e)=>{window.mammoth.convertToHtml({arrayBuffer:this.docxBuffer}).then(e=>g(this,void 0,void 0,function*(){this.book=ut(e.value,!0),t()}))})})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}},e.EpubRender=class extends Se{constructor(e,t){super(t,"EPUB"),this.epubBuffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.book="",this.element=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book||(yield this.parse());let e=new f(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){var e=new Blob([this.epubBuffer]),e=new File([e],"book",{lastModified:(new Date).getTime(),type:e.type}),e=yield this.makeZipLoader(e);this.book=yield new le(e).init()})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}makeZipLoader(c){return g(this,void 0,void 0,function*(){const{ZipReader:e,BlobReader:t,TextWriter:i,BlobWriter:r}=window.zip;window.zip.configure({useWebWorkers:!1});const n=new e(new t(c)),s=yield n.getEntries(),o=new Map(s.map(e=>[e.filename,e]));var a=i=>(e,...t)=>o.has(e)?i(o.get(e),...t):null,l=a(e=>e.getData(new i)),a=a((e,t)=>e.getData(new r(t)));return{entries:s,loadText:l,loadBlob:a,getSize:e=>{return null!==(e=null===(e=o.get(e))||void 0===e?void 0:e.uncompressedSize)&&void 0!==e?e:0}}})}getMetadata(){return g(this,void 0,void 0,function*(){this.book||(yield this.parse());let e=new f(this.book);return yield e.getMetadata()})}},e.Fb2Render=class extends Se{constructor(e,t){super(t,"FB2"),this.fb2Buffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.book="",this.element=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book||(yield this.parse());let e=new f(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){var e=new Blob([this.fb2Buffer]);this.book=yield Ot(e)})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}getMetadata(){return g(this,void 0,void 0,function*(){this.book||(yield this.parse());let e=new f(this.book);return yield e.getMetadata()})}},e.HtmlRender=class extends Se{constructor(e,t,i){super(t,"MD"),this.htmlBuffer=e,this.mode=t,this.format=i,this.chapterList=[],this.chapterDocList=[],this.element=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book||(yield this.parse());let e=new f(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){return new Promise((r,e)=>{var t=new Blob([this.htmlBuffer],{type:Te[this.format.toLocaleLowerCase()]}),i=new FileReader;i.onload=i=>g(this,void 0,void 0,function*(){var e;let t=null===(e=i.target)||void 0===e?void 0:e.result;"MHTML"===this.format&&(t=window.mhtml2html.convert(t).window.document.documentElement.innerHTML),this.book=ut(t,!0),r()}),i.readAsText(t,"UTF-8")})})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}},e.MdRender=class extends Se{constructor(e,t){super(t,"MD"),this.mdBuffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.element=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book||(yield this.parse());let e=new f(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){return new Promise((i,e)=>{var t=new Blob([this.mdBuffer],{type:"text/plain"}),r=new FileReader;r.onload=t=>g(this,void 0,void 0,function*(){var e=window.marked(null===(e=t.target)||void 0===e?void 0:e.result);this.book=ut(e,!0),i()}),r.readAsText(t,"UTF-8")})})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}},e.MobiRender=class extends Se{constructor(e,t){super(t,"MOBI"),this.mobiBuffer=e,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.book="",this.element=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book||(yield this.parse());let e=new f(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){var e=new Blob([this.mobiBuffer]),e=new File([e],"book",{lastModified:(new Date).getTime(),type:e.type});(yield(async e=>{return"BOOKMOBI"===Ke(await e.slice(60,68).arrayBuffer())})(e))&&(this.book=yield new it({unzlib:window.fflate.unzlibSync}).open(e))})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}getMetadata(){return g(this,void 0,void 0,function*(){this.book||(yield this.parse());let e=new f(this.book);return yield e.getMetadata()})}},e.TxtRender=class extends Se{constructor(e,t,i){super(t,"TXT"),this.txtBuffer=e,this.encoding=i,this.mode=t,this.chapterList=[],this.chapterDocList=[],this.bookStr="",this.element="",this.book=""}renderTo(i){return new Promise((t,e)=>g(this,void 0,void 0,function*(){this.element=i,this.book||(yield this.parse());let e=new f(this.book);this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),s(i),o(i,this.mode),this.trigger("rendered"),t()}))}parse(){return g(this,void 0,void 0,function*(){var e=new TextDecoder(this.encoding||"utf8").decode(this.txtBuffer);this.book=ut(e,!0)})}preCache(){return g(this,void 0,void 0,function*(){return this.book||(yield this.parse()),yield this.getCache(this.book)})}getMetadata(){return g(this,void 0,void 0,function*(){var t=new Uint8Array(this.txtBuffer);let i="";for(let e=0;e<100;++e)i+=String.fromCharCode(t[e]);return{charset:window.jschardet.detect(i).encoding||"utf-8"||"utf8"}})}},Object.defineProperty(e,"__esModule",{value:!0})}); diff --git a/src/assets/locales/cn/translation.json b/src/assets/locales/cn/translation.json index e8668fc9b8..7dc1913cf3 100644 --- a/src/assets/locales/cn/translation.json +++ b/src/assets/locales/cn/translation.json @@ -100,9 +100,11 @@ "Export Notes": "导出笔记", "Export Highlights": "导出高亮", "Precache": "预缓存", + "Precaching": "预缓存中", "Delete Precache": "删除预缓存", - "Precache Successfully": "预缓存成功", - "Precache failed": "预缓存失败", + "Precaching Successfully": "预缓存成功", + "Precaching failed": "预缓存失败", + "Nothing to precache": "无需预缓存", "Auto precache books after import": "自动预缓存导入的图书", "Precache books after import to increase opening speed, Koodo will generate a precache version of the original book and save it into your library": "预缓存图书以提升图书打开速度,Koodo会在导入图书之后,自动生成图书缓存并存入书库", "More Actions": "更多操作", diff --git a/src/assets/locales/en/translation.json b/src/assets/locales/en/translation.json index 352c07eac4..f746939fdf 100644 --- a/src/assets/locales/en/translation.json +++ b/src/assets/locales/en/translation.json @@ -114,9 +114,11 @@ "Nothing to export": "Nothing to export", "More Actions": "More Actions", "Precache": "Precache", - "Precache Successfully": "Precache Successfully", - "Precache failed": "Precache failed", + "Precaching": "Precaching", + "Precaching Successfully": "Precaching Successfully", + "Precaching failed": "Precaching failed", "Delete Precache": "Delete Precache", + "Nothing to precache": "Nothing to precache", "Auto precache books after import": "Auto precache books after import", "Precache books after import to increase opening speed, Koodo will generate a precache version of the original book and save it into your library": "Precache books after import to increase opening speed, Koodo will generate a precache version of the original book and save it into your library", "Take effect in a while": "Take effect in a while", diff --git a/src/components/bookCardItem/component.tsx b/src/components/bookCardItem/component.tsx index 5045eedd07..f62ecd1cd5 100644 --- a/src/components/bookCardItem/component.tsx +++ b/src/components/bookCardItem/component.tsx @@ -89,9 +89,11 @@ class BookCardItem extends React.Component<BookCardProps, BookCardState> { handleCancelLoveBook = () => { AddFavorite.clear(this.props.book.key); this.setState({ isFavorite: false }); - if (Object.keys(AddFavorite.getAllFavorite()).length === 0) { + if ( + Object.keys(AddFavorite.getAllFavorite()).length === 0 && + this.props.mode === "favorite" + ) { this.props.history.push("/manager/empty"); - document.title = "Koodo Reader"; } toast.success(this.props.t("Cancel Successfully")); }; diff --git a/src/components/bookCardItem/index.tsx b/src/components/bookCardItem/index.tsx index 4772241f2c..6d5eac594a 100644 --- a/src/components/bookCardItem/index.tsx +++ b/src/components/bookCardItem/index.tsx @@ -12,6 +12,8 @@ import { stateType } from "../../store"; const mapStateToProps = (state: stateType) => { return { + mode: state.sidebar.mode, + isOpenActionDialog: state.book.isOpenActionDialog, dragItem: state.book.dragItem, currentBook: state.book.currentBook, diff --git a/src/components/bookCardItem/interface.tsx b/src/components/bookCardItem/interface.tsx index dc7f0dc8a4..38a10ce41c 100644 --- a/src/components/bookCardItem/interface.tsx +++ b/src/components/bookCardItem/interface.tsx @@ -9,6 +9,8 @@ export interface BookCardProps extends RouteComponentProps<any> { isSelected: boolean; dragItem: string; selectedBooks: string[]; + mode: string; + handleReadingBook: (book: BookModel) => void; handleActionDialog: (isShowActionDialog: boolean) => void; t: (title: string) => string; diff --git a/src/components/bookCoverItem/component.tsx b/src/components/bookCoverItem/component.tsx index eb2ed2734f..b0ef9d7fae 100644 --- a/src/components/bookCoverItem/component.tsx +++ b/src/components/bookCoverItem/component.tsx @@ -90,6 +90,12 @@ class BookCoverItem extends React.Component<BookCoverProps, BookCoverState> { handleCancelLoveBook = () => { AddFavorite.clear(this.props.book.key); this.setState({ isFavorite: false }); + if ( + Object.keys(AddFavorite.getAllFavorite()).length === 0 && + this.props.mode === "favorite" + ) { + this.props.history.push("/manager/empty"); + } toast.success(this.props.t("Cancel Successfully")); }; //控制按钮的弹出 diff --git a/src/components/bookCoverItem/index.tsx b/src/components/bookCoverItem/index.tsx index a80c852c1c..44e9e02c9f 100644 --- a/src/components/bookCoverItem/index.tsx +++ b/src/components/bookCoverItem/index.tsx @@ -12,6 +12,8 @@ import { withTranslation } from "react-i18next"; const mapStateToProps = (state: stateType) => { return { + mode: state.sidebar.mode, + isOpenActionDialog: state.book.isOpenActionDialog, isCollapsed: state.sidebar.isCollapsed, dragItem: state.book.dragItem, diff --git a/src/components/bookCoverItem/interface.tsx b/src/components/bookCoverItem/interface.tsx index 0cfb8a3820..afa1b1b9c6 100644 --- a/src/components/bookCoverItem/interface.tsx +++ b/src/components/bookCoverItem/interface.tsx @@ -7,6 +7,8 @@ export interface BookCoverProps extends RouteComponentProps<any> { isOpenActionDialog: boolean; isCollapsed: boolean; dragItem: string; + mode: string; + isSelectBook: boolean; isSelected: boolean; selectedBooks: string[]; diff --git a/src/components/dialogs/actionDialog/component.tsx b/src/components/dialogs/actionDialog/component.tsx index 3296cfec32..a50108a8d1 100644 --- a/src/components/dialogs/actionDialog/component.tsx +++ b/src/components/dialogs/actionDialog/component.tsx @@ -336,6 +336,7 @@ class ActionDialog extends React.Component< <div className="action-dialog-edit" onClick={() => { + toast(this.props.t("Precaching")); BookUtil.fetchBook( this.props.currentBook.key, true, @@ -353,9 +354,9 @@ class ActionDialog extends React.Component< "cache-" + this.props.currentBook.key, cache ); - toast.success(this.props.t("Precache Successfully")); + toast.success(this.props.t("Precaching Successfully")); } else { - toast.error(this.props.t("Precache failed")); + toast.error(this.props.t("Precaching failed")); } }); }} diff --git a/src/components/popups/popupMenu/component.tsx b/src/components/popups/popupMenu/component.tsx index 6980658abb..5ad8dce82c 100644 --- a/src/components/popups/popupMenu/component.tsx +++ b/src/components/popups/popupMenu/component.tsx @@ -237,11 +237,18 @@ class PopupMenu extends React.Component<PopupMenuProps, PopupMenuStates> { let highlighters: any = this.props.notes; if (!highlighters) return; let highlightersByChapter = highlighters.filter((item: NoteModel) => { - return ( - item.chapter === - this.props.rendition.getChapterDoc()[this.props.chapterDocIndex] - .title && item.bookKey === this.props.currentBook.key - ); + if (this.props.currentBook.format !== "PDF") { + return ( + item.chapter === + this.props.rendition.getChapterDoc()[this.props.chapterDocIndex] + .label && item.bookKey === this.props.currentBook.key + ); + } else { + return ( + item.chapterIndex === this.props.chapterDocIndex && + item.bookKey === this.props.currentBook.key + ); + } }); let pageArea = document.getElementById("page-area"); if (!pageArea) return; diff --git a/src/components/selectBook/component.tsx b/src/components/selectBook/component.tsx index 0c88d6e266..929451d2c3 100644 --- a/src/components/selectBook/component.tsx +++ b/src/components/selectBook/component.tsx @@ -10,6 +10,7 @@ import { exportHighlights, exportNotes, } from "../../utils/syncUtils/exportUtil"; +import BookUtil from "../../utils/fileUtils/bookUtil"; class SelectBook extends React.Component<BookListProps, BookListState> { constructor(props: BookListProps) { super(props); @@ -141,6 +142,72 @@ class SelectBook extends React.Component<BookListProps, BookListState> { > <Trans>Export Highlights</Trans> </span> + <span + className="book-manage-title" + onClick={async () => { + if ( + this.props.books.filter( + (item: BookModel) => + this.props.selectedBooks.indexOf(item.key) > -1 + ).length > 0 + ) { + let selectedBooks = this.props.books.filter( + (item: BookModel) => + this.props.selectedBooks.indexOf(item.key) > -1 + ); + if (selectedBooks.length === 0) { + toast(this.props.t("Nothing to precache")); + return; + } + for (let index = 0; index < selectedBooks.length; index++) { + const selectedBook = selectedBooks[index]; + toast(this.props.t("Precaching")); + let result = await BookUtil.fetchBook( + selectedBook.key, + true, + selectedBook.path + ); + let rendition = BookUtil.getRendtion( + result, + selectedBook.format, + "", + selectedBook.charset + ); + let cache = await rendition.preCache(result); + if (cache !== "err") { + BookUtil.addBook("cache-" + selectedBook.key, cache); + toast.success(this.props.t("Precaching Successfully")); + } else { + toast.error(this.props.t("Precaching failed")); + } + } + } else { + toast(this.props.t("Nothing to precache")); + } + }} + > + <Trans>Precache</Trans> + </span> + <span + className="book-manage-title" + onClick={async () => { + let selectedBooks = this.props.books.filter( + (item: BookModel) => + this.props.selectedBooks.indexOf(item.key) > -1 + ); + if (selectedBooks.length === 0) { + toast(this.props.t("Nothing to delete")); + return; + } + for (let index = 0; index < selectedBooks.length; index++) { + const selectedBook = selectedBooks[index]; + await BookUtil.deleteBook("cache-" + selectedBook.key); + toast.success(this.props.t("Delete Successfully")); + } + }} + > + <Trans>Delete Precache</Trans> + </span> <span className="book-manage-title" onClick={() => { diff --git a/src/containers/htmlViewer/component.tsx b/src/containers/htmlViewer/component.tsx index 1b6b6ed7ee..76f77fabb1 100644 --- a/src/containers/htmlViewer/component.tsx +++ b/src/containers/htmlViewer/component.tsx @@ -200,7 +200,7 @@ class Viewer extends React.Component<ViewerProps, ViewerState> { await rendition.goToPosition( JSON.stringify({ text: bookLocation.text || "", - chapterTitle: bookLocation.chapterTitle || chapterDocs[0].title, + chapterTitle: bookLocation.chapterTitle || chapterDocs[0].label, page: bookLocation.page || "", chapterDocIndex: bookLocation.chapterDocIndex || 0, chapterHref: bookLocation.chapterHref || chapterDocs[0].href, @@ -225,7 +225,7 @@ class Viewer extends React.Component<ViewerProps, ViewerState> { let chapter = bookLocation.chapterTitle || (this.props.htmlBook - ? this.props.htmlBook.flattenChapters[0].title + ? this.props.htmlBook.flattenChapters[0].label : "Unknown Chapter"); let chapterDocIndex = 0; if (bookLocation.chapterDocIndex) { @@ -235,7 +235,7 @@ class Viewer extends React.Component<ViewerProps, ViewerState> { bookLocation.chapterTitle && this.props.htmlBook ? window._.findLastIndex( this.props.htmlBook.flattenChapters.map((item) => { - item.title = item.title.trim(); + item.label = item.label.trim(); return item; }), { diff --git a/src/containers/lists/contentList/component.tsx b/src/containers/lists/contentList/component.tsx index e3e5afea7c..6a24775271 100644 --- a/src/containers/lists/contentList/component.tsx +++ b/src/containers/lists/contentList/component.tsx @@ -25,7 +25,7 @@ class ContentList extends React.Component<ContentListProps, ContentListState> { let chapterIndex = window._.findIndex(this.props.htmlBook.flattenChapters, { href, }); - let title = this.props.htmlBook.flattenChapters[chapterIndex].title; + let title = this.props.htmlBook.flattenChapters[chapterIndex].label; let index = this.props.htmlBook.flattenChapters[chapterIndex].index; await this.props.htmlBook.rendition.goToChapter( index.toString(), @@ -71,7 +71,7 @@ class ContentList extends React.Component<ContentListProps, ContentListState> { onClick={this.handleJump} className="book-content-name" > - {item.title} + {item.label} </a> {item.subitems && item.subitems.length > 0 && diff --git a/src/containers/panels/progressPanel/component.tsx b/src/containers/panels/progressPanel/component.tsx index 8aa1d82a11..b3b3e2720c 100644 --- a/src/containers/panels/progressPanel/component.tsx +++ b/src/containers/panels/progressPanel/component.tsx @@ -68,7 +68,7 @@ class ProgressPanel extends React.Component< await this.props.htmlBook.rendition.goToChapter( this.props.htmlBook.flattenChapters[chapterIndex].index.toString(), this.props.htmlBook.flattenChapters[chapterIndex].href, - this.props.htmlBook.flattenChapters[chapterIndex].title + this.props.htmlBook.flattenChapters[chapterIndex].label ); } }; diff --git a/src/model/HtmlBook.ts b/src/model/HtmlBook.ts index 9ed5239cdf..80b24cb988 100644 --- a/src/model/HtmlBook.ts +++ b/src/model/HtmlBook.ts @@ -1,13 +1,13 @@ class HtmlBook { key: string; - chapters: { title: string; id: string; href: string; index: number }[]; - flattenChapters: { title: string; id: string; href: string; index: number }[]; + chapters: { label: string; id: string; href: string; index: number }[]; + flattenChapters: { label: string; id: string; href: string; index: number }[]; rendition: any; constructor( key: string, - chapters: { title: string; id: string; href: string; index: number }[], + chapters: { label: string; id: string; href: string; index: number }[], flattenChapters: { - title: string; + label: string; id: string; href: string; index: number; diff --git a/src/utils/readUtils/linkUtil.tsx b/src/utils/readUtils/linkUtil.tsx index 5b17c824d5..a0b11e154e 100644 --- a/src/utils/readUtils/linkUtil.tsx +++ b/src/utils/readUtils/linkUtil.tsx @@ -29,7 +29,7 @@ export const handleLinkJump = async (event: any, rendition: any = {}) => { await rendition.goToChapter( chapterInfo.index, chapterInfo.href, - chapterInfo.title + chapterInfo.label ); } @@ -40,7 +40,7 @@ export const handleLinkJump = async (event: any, rendition: any = {}) => { await rendition.goToChapter( chapterInfo.index, chapterInfo.href, - chapterInfo.title + chapterInfo.label ); } else if ( href && diff --git a/src/utils/readUtils/sortUtil.tsx b/src/utils/readUtils/sortUtil.tsx index 7c7cf8457c..9b883c3e3d 100644 --- a/src/utils/readUtils/sortUtil.tsx +++ b/src/utils/readUtils/sortUtil.tsx @@ -21,7 +21,8 @@ const getBookIndex = (nameArr: string[], oldNameArr: string[]) => { let indexArr: number[] = []; for (let i = 0; i < nameArr.length; i++) { //如果索引数组已经包含该索引,就把它放在随后一位,取数组长度为索引 - indexArr.push(oldNameArr.indexOf(nameArr[i])); + oldNameArr.indexOf(nameArr[i]) > -1 && + indexArr.push(oldNameArr.indexOf(nameArr[i])); } if (indexArr.length < oldNameArr.length) { oldNameArr.forEach((item) => {