From 82415409ff2f1be0ca9876e9fa565623ccf9e084 Mon Sep 17 00:00:00 2001 From: troyeguo <13820674+troyeguo@users.noreply.github.com> Date: Sun, 6 Apr 2025 10:49:21 +0800 Subject: [PATCH] fix bug --- package.json | 2 +- src/assets/lib/kookit-extra-browser.min.js | 2 +- src/assets/lib/kookit-extra.min.mjs | 2 +- src/assets/lib/kookit.min.js | 2 +- src/pages/login/login.css | 1 + yarn.lock | 25 ++++++---------------- 6 files changed, 11 insertions(+), 23 deletions(-) diff --git a/package.json b/package.json index 2ddd2dae..a657c78b 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,7 @@ "localforage": "^1.10.0", "mammoth": "^1.8.0", "marked": "^15.0.3", - "megajs": "^1.3.5", + "megajs": "^1.3.7", "mhtml2html": "^3.0.0", "node-machine-id": "^1.1.12", "qs": "^6.11.2", diff --git a/src/assets/lib/kookit-extra-browser.min.js b/src/assets/lib/kookit-extra-browser.min.js index 46d0441d..42715d40 100644 --- a/src/assets/lib/kookit-extra-browser.min.js +++ b/src/assets/lib/kookit-extra-browser.min.js @@ -1 +1 @@ -import e from"axios";import{Storage as t}from"megajs";import{Buffer as r}from"buffer";import{createClient as o,AuthType as i}from"webdav/dist/web/index.js";import{isElectron as n}from"react-device-detect";function s(e,t,r,o){return new(r||(r=Promise))((function(i,n){function s(e){try{c(o.next(e))}catch(e){n(e)}}function a(e){try{c(o.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((o=o.apply(e,t||[])).next())}))}const a=e=>"json"===e?"application/json":["jpg","jpeg","png","gif","bmp"].includes(e)?"image/"+e:"zip"===e?"application/zip":"epub"===e?"application/epub+zip":"txt"===e?"text/plain":"pdf"===e?"application/pdf":"mobi"===e?"application/x-mobipocket-ebook":"azw3"===e||"azw"===e?"application/vnd.amazon.ebook":"cbz"===e?"application/x-cbz":"cbr"===e?"application/x-cbr":"cbt"===e?"application/x-cbt":"cb7"===e?"application/x-cb7":"fb2"===e?"application/x-fictionbook+xml":"html"===e?"text/html":"css"===e?"text/css":"js"===e?"application/javascript":"xml"===e?"application/xml":"xhtml"===e?"application/xhtml+xml":"opf"===e?"application/oebps-package+xml":"ncx"===e?"application/x-dtbncx+xml":"mp3"===e?"audio/mpeg":"wav"===e?"audio/wav":"ogg"===e?"audio/ogg":"mp4"===e?"video/mp4":"webm"===e?"video/webm":"avi"===e?"video/x-msvideo":"wmv"===e?"video/x-ms-wmv":"flv"===e?"video/x-flv":"m3u8"===e?"application/x-mpegURL":"ts"===e?"video/MP2T":"3gp"===e?"video/3gpp":"3g2"===e?"video/3gpp2":"db"===e?"application/x-sqlite3":void 0,c=["books","notes","bookmarks","plugins","words"];class l{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.maxConcurrency=e}addTask(e){return s(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,r)=>{const o=()=>s(this,void 0,void 0,(function*(){try{this.runningTasks++;const r=yield e();return this.completedTasks++,t(r),r}catch(e){throw this.completedTasks++,r(e),e}finally{this.runningTasks--,this.runNext()}}));this.runningTasks0&&this.runningTasks{var t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e)),t},base64ToArrayBuffer:e=>{const t=atob(e),r=t.length,o=new Uint8Array(r);for(let e=0;e{let t="";const r=new Uint8Array(e),o=r.byteLength;for(let e=0;ee.toString(16).padStart(2,"0"))).join("")}))},EmailProviders:["gmail.com","qq.com","163.com","yahoo.com","sina.com","126.com","outlook.com","yeah.net","foxmail.com","hotmail.com","protonmail.com","proton.me","icloud.com","mail.com","live.com","aliyun.com"]};const u={publicUrl:"https://api.960960.xyz",cloudUrl:"https://cloud.960960.xyz",devUrl:"http://192.168.28.159:8000"},h={callbackUrl:"https://web.koodoreader.com/",dropboxClientId:"vnc67byrssocvy1",pcloudClientId:"pg8ten0B3vH",boxClientId:"ltimecqanmpxoaicn9qw3es6l3sdl1ya",microsoftClientId:"506df58a-29ab-4020-afc5-6f423dc80f35",googleClientId:"1051055003225-ph1f5fvh328dhv7bco5jitlnfhg6ks2t.apps.googleusercontent.com",facebookClientId:"2845583825559500",githubClientId:"Ov23liJVzfvJMMEEZ8v2",adriveClientId:"a128ae7b9c094545af623de61dc0a1ef"};var p={CloudConfig:u,ThirdpartyConfig:h,LoginAuthRequest:{google:{clientId:h.googleClientId,scopes:["openid"],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{prompt:"consent",scope:"openid"}},microsoft:{clientId:h.microsoftClientId,scopes:["openid","profile","User.Read","offline_access"],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{scope:"openid profile User.Read offline_access"}},facebook:{clientId:h.facebookClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{scope:""}},github:{clientId:h.githubClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{scope:""}},email:{clientId:"",scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{scope:""}}},LoginDiscovery:{microsoft:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"},facebook:{authorizationEndpoint:"https://www.facebook.com/v12.0/dialog/oauth",tokenEndpoint:"https://graph.facebook.com/v12.0/oauth/access_token"},github:{authorizationEndpoint:"https://github.com/login/oauth/authorize",tokenEndpoint:"https://github.com/login/oauth/access_token"},email:{authorizationEndpoint:"",tokenEndpoint:""}},DriveAuthRequest:{dropbox:{clientId:h.dropboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{token_access_type:"offline"}},boxnet:{clientId:h.boxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}},pcloud:{clientId:h.pcloudClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{grant_type:"authorization_code"}},adrive:{clientId:h.adriveClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}},microsoft:{clientId:h.microsoftClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{scope:"files.readwrite.appfolder offline_access"}},google:{clientId:h.googleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{prompt:"consent",scope:"https://www.googleapis.com/auth/drive.appdata",access_type:"offline"}}},DriveDiscovery:{dropbox:{authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",tokenEndpoint:"https://www.dropbox.com/oauth2/token"},boxnet:{authorizationEndpoint:"https://account.box.com/api/oauth2/authorize",tokenEndpoint:"https://api.box.com/oauth2/token"},pcloud:{authorizationEndpoint:"https://my.pcloud.com/oauth2/authorize",tokenEndpoint:"https://api.pcloud.com/oauth2_token"},adrive:{authorizationEndpoint:"https://openapi.alipan.com/oauth/authorize",tokenEndpoint:"https://openapi.alipan.com/oauth/token"},microsoft:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"}}};class f{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new l(1)}retryOperation(e,t=5){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getDriveId(){return s(this,void 0,void 0,(function*(){if(this.driveId)return this.driveId;const t=yield this.refreshToken(),r=yield e.post("https://openapi.alipan.com/adrive/v1.0/user/getDriveInfo",{},{headers:{Authorization:`Bearer ${t}`}});return this.driveId=r.data.default_drive_id,this.driveId}))}getFolderIdByPath(t){return s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=yield this.getDriveId();try{try{const i=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(i.data)return i.data.file_id}catch(i){const n=t.split("/").filter((e=>e));let s="",a="root";for(const t of n){s+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:s},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.file_id}catch(i){a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:o,parent_file_id:a,name:t,type:"folder",check_name_mode:"refuse"},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.file_id}}return a}}catch(e){return console.error("Error getting/creating folder by path:",e),""}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield this.getDriveId(),i=yield this.getFolderIdByPath("/KoodoReader/"+t);return(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:o,parent_file_id:i},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.items.map((e=>e.name))}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield this.getDriveId(),i=yield this.getFolderIdByPath("/KoodoReader/"+t);return!i||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:o,file_id:i},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}checkExists(t){var r;return s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=yield this.getDriveId(),n=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:t},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});(null===(r=n.data)||void 0===r?void 0:r.file_id)&&(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/recyclebin/trash",{drive_id:i,file_id:n.data.file_id},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}))}catch(e){}}))}refreshToken(){return s(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"adrive",refresh_token:e});this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("adrive_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"adrive",redirect_uri:h.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:h.adriveClientId,redirect_uri:h.callbackUrl,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class y extends f{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return new Promise(((o,i)=>s(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken(),n=yield this.getDriveId(),s=r.substring(0,r.lastIndexOf("/")),a=r.substring(r.lastIndexOf("/")+1),c=yield this.getFolderIdByPath("/KoodoReader/"+s),l=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:n,parent_file_id:c,name:a,type:"file",check_name_mode:"ignore"},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),{file_id:d,upload_id:u,part_info_list:h}=l.data;yield e.put(h[0].upload_url,t,{headers:{"Content-Type":"application/octet-stream"}}),yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/complete",{drive_id:n,file_id:d,upload_id:u},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),o(!0)}catch(e){console.error("Error uploading file:",e),o(!1)}}))))}))}downloadFile(t){return new Promise(((r,o)=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=yield this.getDriveId(),n=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:"/KoodoReader/"+t},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}})).data.file_id,s=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:i,file_id:n},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}),a=yield e.get(s.data.url,{responseType:"arraybuffer"});r(a.data)}catch(e){console.error("Error downloading file:",e),r(!1)}}))))}}class g{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getFolderIdByPath(t){return s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=t.split("/");let i="0";for(const t of o){const o=`https://api.box.com/2.0/folders/${i}/items?fields=id,name&type=folder&limit=1000`;try{const n=(yield e.get(o,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(n)i=n.id;else{const o={name:t,parent:{id:i},type:"folder"};i=(yield e.post("https://api.box.com/2.0/folders",o,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}}catch(e){return console.error("Error occurred during folder creation:",e),""}}return i}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=yield this.getFolderIdByPath("KoodoReader/"+t);return(yield e.get(`https://api.box.com/2.0/folders/${o}/items`,{headers:{Authorization:`Bearer ${r}`}})).data.entries.map((e=>e.name))}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=t.substring(0,t.lastIndexOf("/")),i=t.substring(t.lastIndexOf("/")+1),n=yield this.getFolderIdByPath("KoodoReader/"+o);if(!n)return!0;const s=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,a=(yield e.get(s,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));return!a||(yield e.delete(`https://api.box.com/2.0/files/${a.id}`,{headers:{Authorization:`Bearer ${r}`}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return s(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"boxnet",refresh_token:e});this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("boxnet_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"boxnet",redirect_uri:h.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:h.boxClientId,redirect_uri:h.callbackUrl,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class m extends g{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=r.substring(0,r.lastIndexOf("/")),n=r.substring(r.lastIndexOf("/")+1),s=yield this.getFolderIdByPath("KoodoReader/"+i);if(!s)throw new Error("Folder not found");const a=(yield this.listFiles(i)).find((e=>e===n));a&&(yield this.deleteFileWithoutQueue(i+"/"+n));let c=new File([t],n,{lastModified:(new Date).getTime(),type:t.type});const l=new FormData;l.append("file",c),l.append("parent_id",s);const d=yield e.post("https://upload.box.com/api/2.0/files/content",l,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"multipart/form-data"},params:{if_match:"false",fields:"name,id"},maxContentLength:1/0,maxBodyLength:1/0});return!(d.status>=300)||(console.error("Error occurred during file upload:",d),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=t.substring(0,t.lastIndexOf("/")),i=t.substring(t.lastIndexOf("/")+1),n=yield this.getFolderIdByPath("KoodoReader/"+o);if(!n)throw new Error("Folder not found");const s=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,a=(yield e.get(s,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));if(!a)return console.error("File not found:",i),!1;const c=yield e({url:`https://api.box.com/2.0/files/${a.id}/content`,method:"get",headers:{Authorization:`Bearer ${r}`},responseType:"arraybuffer"});return c.status>=300?(console.error("Error occurred during file download:",c),!1):c.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class v{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();return(yield e.post("https://api.dropboxapi.com/2/files/list_folder",{path:"/"+t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.entries.map((e=>e.name))}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();yield e.post("https://api.dropboxapi.com/2/files/delete_v2",{path:"/"+t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return s(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"dropbox",refresh_token:e});return this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dropbox",redirect_uri:h.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${h.dropboxClientId}&redirect_uri=${h.callbackUrl}`}}class k extends v{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken();let i=r.split("/").pop()||"",n=new File([t],i,{lastModified:(new Date).getTime(),type:t.type});const s=yield e.post("https://content.dropboxapi.com/2/files/upload",n,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/octet-stream","Dropbox-API-Arg":JSON.stringify({path:"/"+r,mode:"overwrite",autorename:!0,mute:!1})},maxContentLength:1/0,maxBodyLength:1/0});return!(s.status>=300)||(console.error("Error occurred during file upload:",s),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e({url:"https://content.dropboxapi.com/2/files/download",method:"post",headers:{Authorization:`Bearer ${r}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+t})},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer"});return o.status>=300?(console.error("Error occurred during file download:",o),!1):o.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class b{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getFileId(t,r){return s(this,void 0,void 0,(function*(){const o=yield this.refreshToken(),i=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+'${r}'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=yield e.get(i,{headers:{Authorization:"Bearer "+o}});if(0===t.data.files.length)return"";const r=t.data.files;return r.length>0?r[0].id:null}catch(e){return console.error("Error occurred during file list retrieval:",e),""}}))}checkFolder(t){return s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=yield this.getFolderId(t);if(o)return o;const i={name:t,mimeType:"application/vnd.google-apps.folder",parents:["appDataFolder"]};try{return(yield e.post("https://www.googleapis.com/drive/v3/files",i,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error("Error occurred during folder creation:",e),e}}))}getFolderId(t){return s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+mimeType='application/vnd.google-apps.folder'+and+'appDataFolder'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=(yield e.get(o,{headers:{Authorization:`Bearer ${r}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();const o=`https://www.googleapis.com/drive/v3/files?q='${yield this.checkFolder(t)}'+in+parents&spaces=appDataFolder&fields=files(id,name)`;return(yield e.get(o,{headers:{Authorization:`Bearer ${r}`}})).data.files.map((e=>e.name))}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return s(this,void 0,void 0,(function*(){const r=t.split("/")[1],o=t.split("/")[0],i=yield this.getFolderId(o),n=yield this.refreshToken(),s=yield this.getFileId(r,i);if(""===s)return console.error("File not found:",r),!0;try{const t=yield e.delete(`https://www.googleapis.com/drive/v3/files/${s}`,{headers:{Authorization:`Bearer ${n}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return s(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"google",refresh_token:e});return this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"google",redirect_uri:h.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${h.callbackUrl}&prompt=consent&response_type=code&client_id=${h.googleClientId}&scope=https://www.googleapis.com/auth/drive.appdata&access_type=offline`}}class w extends b{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken();let i=r.split("/").pop()||"",n=new File([t],i,{lastModified:(new Date).getTime(),type:t.type}),s=r.split(".").pop(),c=a(s||""),l=r.split("/")[0],d=yield this.checkFolder(l),u=yield this.getFileId(i||"",d);const h={mimeType:c,name:i,parents:[d]},p=u?`https://www.googleapis.com/upload/drive/v3/files/${u}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",f=(yield e({method:u?"PATCH":"POST",url:p,data:u?null:JSON.stringify(h),headers:{Authorization:"Bearer "+o,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location,y=yield this.getData(n);if(0===Object.keys(y).length)return!1;const g=yield e.put(f,y.data,{headers:{Authorization:"Bearer "+o,"Content-Type":"application/zip","Content-Range":`bytes 0-${y.fileSize-1}/${y.fileSize}`},maxContentLength:1/0,maxBodyLength:1/0});return!(g.status>=300)||(console.error("Error occurred during file download:",g),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=t.split("/").pop(),i=t.split("/")[0],n=yield this.checkFolder(i),s=yield this.getFileId(o||"",n);if(!s)throw new Error("File not found");const a=`https://www.googleapis.com/drive/v3/files/${s}?alt=media`,c=yield e.get(a,{headers:{Authorization:"Bearer "+r},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer"});return c.status>=300?(console.error("Error occurred during file download:",c),!1):c.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getData(e){return s(this,void 0,void 0,(function*(){return e?new Promise(((t,r)=>{const o=new FileReader;o.onload=r=>t({fileName:e.name,mimeType:e.type,fileSize:e.size,data:r.target.result}),o.onerror=e=>r(e),o.readAsArrayBuffer(e)})):{}}))}}class T{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getStorage(){return s(this,void 0,void 0,(function*(){if(this.storage)return this.storage;let{email:e,password:r}=this.config;return this.storage=yield new t({email:e,password:r}).ready,this.storage}))}getRoot(){return s(this,void 0,void 0,(function*(){if(this.root)return this.root;const e=(yield this.getStorage()).root;let t=e.children.find((e=>"KoodoReader"===e.name&&e.directory));return t||(t=yield e.mkdir("KoodoReader")),this.root=t,this.root}))}createFolder(e,t){return s(this,void 0,void 0,(function*(){const r=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(r))return yield this.folderCreationLocks.get(r);const o=(()=>s(this,void 0,void 0,(function*(){try{let r=e.children.find((e=>e.name===t&&e.directory));return r||(r=yield e.mkdir(t),r)}finally{this.folderCreationLocks.delete(r)}})))();return this.folderCreationLocks.set(r,o),yield o}))}listFiles(e){return s(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();if(e){const r=e.split("/").filter((e=>e));for(const e of r){const r=t.children.find((t=>t.name===e&&t.directory));if(!r)return[];t=r}}return t.children.filter((e=>!e.directory)).map((e=>e.name))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return s(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();const r=e.split("/"),o=r.pop();for(const e of r){if(!e)continue;const r=t.children.find((t=>t.name===e&&t.directory));if(!r)return!0;t=r}const i=t.children.find((e=>e.name===o&&!e.directory));return!i||(yield i.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class E extends T{constructor(e){super(e)}uploadFile(e,t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const i=t.split("/"),n=i.pop()||"";for(const e of i){if(!e)continue;let t=o.children.find((t=>t.name===e&&t.directory));t||(t=yield this.createFolder(o,e)),o=t}const s=new File([e],n,{lastModified:(new Date).getTime(),type:e.type}),a=yield e.arrayBuffer(),c=new Uint8Array(a),l=r.from(c),d=o.children.find((e=>e.name===n&&!e.directory));return d&&(yield d.delete()),yield o.upload({name:n,size:s.size},l).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();const r=e.split("/"),o=r.pop()||"";for(const e of r){if(!e)continue;const r=t.children.find((t=>t.name===e&&t.directory));if(!r)return!1;t=r}const i=t.children.find((e=>e.name===o&&!e.directory));if(!i)return!1;return yield i.downloadBuffer()}catch(e){return console.error("Error occurred during MEGA file download:",e),!1}}))))))}))}}class C{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.get(`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/children`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return o.status>=300?[]:o.data.value.map((e=>e.name))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.delete(`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!(o.status>=300)||(console.error("Error deleting file:",o),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return s(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"microsoft",refresh_token:e});return this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"microsoft",redirect_uri:h.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${h.microsoftClientId}&scope=files.readwrite.appfolder offline_access&response_type=code&redirect_uri=${h.callbackUrl}`}}class _ extends C{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken();let i=r.split("/").pop()||"",n=new File([t],i,{lastModified:(new Date).getTime(),type:t.type});const s="https://graph.microsoft.com/v1.0/me/drive/special/approot:/"+r+":/createUploadSession",a=yield e.post(s,null,{headers:{Authorization:"Bearer "+o,"Content-Type":"application/json"},maxContentLength:1/0,maxBodyLength:1/0});let c=n.size;const l=n.type,d=a.data.uploadUrl,u=yield e.put(d,n,{headers:{"Content-Type":l,"Content-Range":`bytes 0-${c-1}/${c}`},maxContentLength:1/0,maxBodyLength:1/0});return!(u.status>=300)||(console.error("Error occurred during file download:",u),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/content`,i=yield e.get(o,{responseType:"arraybuffer",headers:{Authorization:"Bearer "+r},maxContentLength:1/0,maxBodyLength:1/0});return i.status>=300?(console.error("Error occurred during file download:",i),!1):i.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class x{downloadFile(e,t){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}authToken(e){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e("")}))}))}getAuthUrl(){return""}}class R{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new l(3)}retryOperation(e,t=5){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}checkFolderExists(t,r){return s(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(t,r){return s(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/createfolderifnotexists",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error creating folder:",e),!1}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:"/"+t,recursive:0}});return 0!==o.data.result?[]:o.data.metadata.contents.map((e=>e.name))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.get("https://api.pcloud.com/deletefile",{params:{access_token:r,path:"/"+t}});return 0===o.data.result||(console.error("Error deleting file:",o.data),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return s(this,void 0,void 0,(function*(){return this.config.refresh_token}))}authToken(e){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"pcloud",redirect_uri:h.callbackUrl,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${h.pcloudClientId}&response_type=code&redirect_uri=${h.callbackUrl}`}}class S extends R{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=r.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(i,o))){if(!(yield this.createFolder(i,o)))return!1}let n=r.split("/").pop()||"",s=new File([t],n,{lastModified:(new Date).getTime(),type:t.type});const a=new FormData;a.append("file",s);const c=yield e.post("https://api.pcloud.com/uploadfile",a,{params:{access_token:o,path:`/${i}`,renew:1},maxContentLength:1/0,maxBodyLength:1/0});return 0===c.data.result||(console.error("Error uploading file:",c.data),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.get("https://api.pcloud.com/getfilelink",{params:{access_token:r,path:`/${t}`}});if(0!==o.data.result)return console.error("Error getting file link:",o.data),!1;const i=`https://${o.data.hosts[0]}${o.data.path}`,n=yield e.get(i,{responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0});return n.status>=300?(console.error("Error downloading file:",n),!1):n.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class O{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new l(5)}retryOperation(e,t=0){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return s(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:o,accessKeyId:i,secretAccessKey:n,dir:s}=this.config;s||(s="KoodoReader");try{return(yield this.thirdpartyRequest.s3List({bucket_name:o,prefix:s+"/"+e,region:r,endpoint:t,access_key_id:i,secret_access_key:n})).data.contents.map((e=>e.split("/").pop()))}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:o,accessKeyId:i,secretAccessKey:n,dir:s}=this.config;s||(s="KoodoReader");try{let a=yield this.thirdpartyRequest.s3Delete({bucket_name:o,object_key:s+"/"+e,region:r,endpoint:t,access_key_id:i,secret_access_key:n});return 200===a.code||(console.error("Error deleting file:",a),!1)}catch(e){return console.error("Error deleting file:",e),!1}}))}}class A extends O{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){let{endpoint:o,region:i,bucketName:n,accessKeyId:s,secretAccessKey:a,dir:c}=this.config;c||(c="KoodoReader");try{const l=(yield this.thirdpartyRequest.s3Upload({bucket_name:n,object_key:c+"/"+r,region:i,endpoint:o,access_key_id:s,secret_access_key:a})).data.url;let d=r.split("/").pop()||"",u=new File([t],d,{lastModified:(new Date).getTime(),type:t.type});const h=yield e.put(l,u,{headers:{},maxContentLength:1/0,maxBodyLength:1/0});return!(h.status>=300)||(console.error("Error occurred during file upload:",h),!1)}catch(e){return console.error("Error occurred during file upload:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){let{endpoint:r,region:o,bucketName:i,accessKeyId:n,secretAccessKey:s,dir:a}=this.config;a||(a="KoodoReader");try{const c=(yield this.thirdpartyRequest.s3Download({bucket_name:i,object_key:a+"/"+t,region:o,endpoint:r,access_key_id:n,secret_access_key:s})).data.url;return(yield e({url:c,method:"get",headers:{},responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0})).data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class F{constructor(e){let{username:t,password:r,url:n,dir:s}=e;s||(s="KoodoReader"),this.client=o(n,{authType:i.Password,username:t,password:r}),this.username=t,this.password=r,this.dir=s,this.taskQueue=new l(5)}retryOperation(e,t=0){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{!1===(yield this.client.exists(this.dir+"/"+r.substring(0,r.lastIndexOf("/"))))&&(yield this.client.createDirectory(this.dir+"/"+r.substring(0,r.lastIndexOf("/"))));let o=r.split("/").pop()||"",i=new File([t],o,{lastModified:(new Date).getTime(),type:t.type}),n=this.client.getFileUploadLink(this.dir+"/"+r);const s=new URL(n);s.search="",n=s.toString();const a=btoa(this.username+":"+this.password),c=yield e.put(n,i,{headers:{Authorization:"Basic "+a},maxContentLength:1/0,maxBodyLength:1/0});return!(c.status>=300)||(console.error("Error occurred during file upload:",c),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=this.client.getFileDownloadLink(this.dir+"/"+t),o=btoa(this.username+":"+this.password),i=yield e({url:r,method:"get",headers:{Authorization:"Basic "+o},responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0});return i.status>=300?(console.error("Error occurred during file download:",i),!1):i.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return s(this,void 0,void 0,(function*(){try{return(yield this.client.getDirectoryContents(this.dir+"/"+e)).map((e=>e.basename))}catch(t){return t.response&&404===t.response.status&&(yield this.client.createDirectory(this.dir+"/"+e)),console.error("Error listing files:",t),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){try{return yield this.client.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}}const I=["book","config","cover","font"];class L{constructor(e,t,r){this.type=e,this.remote="dropbox"===e?new k(t,r):"microsoft"===e?new _(t,r):"google"===e?new w(t,r):"s3compatible"===e?new A(t,r):"webdav"===e?new F(t):"boxnet"===e?new m(t,r):"mega"===e?new E(t):"adrive"===e?new y(t,r):"pcloud"===e?new S(t,r):new x}downloadFile(e,t){return s(this,void 0,void 0,(function*(){return!!(yield this.listFiles(t)).find((t=>e.indexOf(t)>-1))&&(yield this.remote.downloadFile(t+"/"+e))}))}uploadFile(e,t,r){return s(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(r,t+"/"+e)}))}deleteFile(e,t){return s(this,void 0,void 0,(function*(){return yield this.remote.deleteFile(t+"/"+e)}))}listFiles(e){return s(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}isExist(e,t){return s(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}downloadAllFiles(){return s(this,void 0,void 0,(function*(){for(let e of I){let t=yield this.listFiles(e);for(let r of t)yield this.downloadFile(r,e)}}))}authToken(e){return s(this,void 0,void 0,(function*(){return yield this.remote.authToken(e)}))}getAuthUrl(){return this.remote.getAuthUrl?this.remote.getAuthUrl():""}getStats(){return this.remote.taskQueue.getStats()}resetCounters(){this.remote.taskQueue.resetCounters()}}const M={notes:"SELECT * FROM notes WHERE key = ?",bookmarks:"SELECT * FROM bookmarks WHERE key = ?",books:"SELECT * FROM books WHERE key = ?",plugins:"SELECT * FROM plugins WHERE key = ?",words:"SELECT * FROM words WHERE key = ?"},j={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},B={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function P(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const D={notes:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),t.tag=JSON.parse(e.tag),t},bookmarks:e=>e,books:e=>e,plugins:e=>{let t=Object.assign({},e);return e.autoValue||delete t.autoValue,e.langList?t.langList=JSON.parse(e.langList):delete t.langList,e.voiceList?t.voiceList=JSON.parse(e.voiceList):delete t.voiceList,t.config=JSON.parse(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),t}};var z,$={sqlStatement:{createTableStatement:P({notes:'\n CREATE TABLE IF NOT EXISTS "notes" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "chapter" text,\n "chapterIndex" integer,\n "text" text,\n "cfi" text,\n "range" text,\n "notes" text,\n "percentage" text,\n "color" integer,\n "tag" array\n )\n ',bookmarks:'\n CREATE TABLE IF NOT EXISTS "bookmarks" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "cfi" text,\n "label" text,\n "percentage" text,\n "chapter" text\n );\n ',books:'\n CREATE TABLE IF NOT EXISTS "books" (\n "key" text PRIMARY KEY,\n "name" text,\n "author" text,\n "description" text,\n "md5" text,\n "cover" text,\n "format" text,\n "publisher" text,\n "size" integer,\n "page" integer,\n "path" text,\n "charset" text\n );\n ',plugins:'\n CREATE TABLE IF NOT EXISTS "plugins" (\n "key" text PRIMARY KEY,\n "type" text,\n "displayName" text,\n "icon" text,\n "version" text,\n "config" object,\n "autoValue" string,\n "langList" text,\n "voiceList" text,\n "scriptSHA256" text,\n "script" text\n );\n ',words:'\n CREATE TABLE IF NOT EXISTS "words" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "word" text,\n "chapter" text\n );\n '}),getAllStatement:P({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:P({notes:"INSERT OR REPLACE INTO notes (key, bookKey, chapter, chapterIndex, text, cfi, range, notes, date, percentage, color, tag) VALUES (@key, @bookKey, @chapter, @chapterIndex, @text, @cfi, @range, @notes, @date, @percentage, @color, @tag)",bookmarks:"INSERT OR REPLACE INTO bookmarks (key, bookKey, cfi, label, percentage, chapter) VALUES (@key, @bookKey, @cfi, @label, @percentage, @chapter)",books:"INSERT OR REPLACE INTO books (key, name, author, description, md5, cover, format, publisher, size, page, path, charset) VALUES (@key, @name, @author, @description, @md5, @cover, @format, @publisher, @size, @page, @path, @charset)",plugins:"INSERT OR REPLACE INTO plugins (key, type, displayName, icon, version, config, autoValue, langList, voiceList, scriptSHA256, script) VALUES (@key, @type, @displayName, @icon, @version, @config, @autoValue, @langList, @voiceList, @scriptSHA256, @script)",words:"INSERT OR REPLACE INTO words (key, bookKey, date, word, chapter) VALUES (@key, @bookKey, @date, @word, @chapter)"}),deleteAllStatement:P({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:P({notes:"UPDATE notes SET bookKey = @bookKey, chapter = @chapter, chapterIndex = @chapterIndex, text = @text, cfi = @cfi, range = @range, notes = @notes, date = @date, percentage = @percentage, color = @color, tag = @tag WHERE key = @key",bookmarks:"UPDATE bookmarks SET bookKey = @bookKey, cfi = @cfi, label = @label, percentage = @percentage, chapter = @chapter WHERE key = @key",books:"UPDATE books SET name = @name, author = @author, description = @description, md5 = @md5, cover = @cover, format = @format, publisher = @publisher, size = @size, page = @page, path = @path, charset = @charset WHERE key = @key",plugins:"UPDATE plugins SET type = @type, displayName = @displayName, icon = @icon, version = @version, config = @config, autoValue = @autoValue, langList = @langList, voiceList = @voiceList, scriptSHA256 = @scriptSHA256, script = @script WHERE key = @key",words:"UPDATE words SET bookKey = @bookKey, date = @date, word = @word, chapter = @chapter WHERE key = @key"}),deleteStatement:P({notes:"DELETE FROM notes WHERE key = ?",bookmarks:"DELETE FROM bookmarks WHERE key = ?",books:"DELETE FROM books WHERE key = ?",plugins:"DELETE FROM plugins WHERE key = ?",words:"DELETE FROM words WHERE key = ?"}),dropStatement:P({notes:"DROP TABLE IF EXISTS notes",bookmarks:"DROP TABLE IF EXISTS bookmarks",books:"DROP TABLE IF EXISTS books",plugins:"DROP TABLE IF EXISTS plugins",words:"DROP TABLE IF EXISTS words"}),getStatement:P(M),getByBookKeyStatement:P(j),getByBookKeysStatement:P({notes:e=>`SELECT * FROM notes WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,bookmarks:e=>`SELECT * FROM bookmarks WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,words:e=>`SELECT * FROM words WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")})`}),deleteByBookKeyStatement:P(B)},jsonToSqlite:P({notes:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),t.tag=JSON.stringify(e.tag),t},bookmarks:e=>e,books:e=>{let t=Object.assign({},e);return t.page=e.page||0,t},plugins:e=>{let t=Object.assign({},e);return e.autoValue||(t.autoValue=null),e.langList?t.langList=JSON.stringify(e.langList):t.langList=null,e.voiceList?t.voiceList=JSON.stringify(e.voiceList):t.voiceList=null,t.config=JSON.stringify(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),t}}),sqliteToJson:P(D)};class N{constructor(e,t,r,o,i,n,s,a,c,l,d,u){this.key=e,this.name=t,this.author=r,this.description=o,this.md5=i,this.cover=n,this.format=s,this.publisher=a,this.size=c,this.page=l,this.path=d,this.charset=u}}class q{static generateBook(e,t,r,o,i,n,a){return new Promise(((c,l)=>s(this,void 0,void 0,(function*(){try{let s,l,d,u,h,p,f,y,g="";switch([l,d,h,u,p,f]=[e,"","","","",0],t){case"pdf":case"epub":case"mobi":case"azw":case"azw3":case"fb2":y=yield a.getMetadata(),[l,d,h,u,g]=[y.name||e,y.author||"",y.description||"",y.publisher||"",y.cover||""];break;case"cbr":case"cbt":case"cbz":case"cb7":y=yield a.getMetadata(),g=y.cover;break;case"txt":y=yield a.getMetadata(n),p=y.charset}let m=t.toUpperCase();s=(new Date).getTime()+"",c(new N(s,l,d,h,r,g,m,u,o,f,i,p))}catch(e){console.error(e),l(e)}}))))}}z=q,q.getRendtion=(e,t,r,o,i,n,s,a,c,l)=>{let d;var u,h;return"CACHE"===t?d=new l.CacheRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"MOBI"===t||"AZW3"===t||"AZW"===t?d=new l.MobiRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"EPUB"===t?d=new l.EpubRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"TXT"===t?d=new l.TxtRender(e,{readerMode:r,animation:i,charset:o,convertChinese:n,parserRegex:s,isDarkMode:a,isMobile:c}):"MD"===t?d=new l.MdRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"PDF"===t?d=new l.PdfRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"FB2"===t?d=new l.Fb2Render(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"DOCX"===t?d=new l.DocxRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"HTML"===t||"XHTML"===t||"MHTML"===t||"HTM"===t||"XML"===t?d=new l.HtmlRender(e,{readerMode:r,format:t,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"CBR"!==t&&"CBT"!==t&&"CBZ"!==t&&"CB7"!==t||(d=new l.ComicRender((u=e,h=new ArrayBuffer(u.byteLength),new Uint8Array(h).set(new Uint8Array(u)),h),{readerMode:r,format:t,animation:i,convertChinese:n,isDarkMode:a,isMobile:c})),d},q.initMobileBook=(e,t,r,o,i,n,a,c)=>s(void 0,void 0,void 0,(function*(){try{const s=yield fetch(e);if(!s.ok)throw new Error(`Failed to download book: ${s.status} ${s.statusText}`);const l=yield s.arrayBuffer();window.ReactNativeWebView.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=l;let d=z.getRendtion(l,t,r,o,i,n,a,c,"yes",window.Kookit);window.rendition=d;let u=document.getElementById("page-area");yield window.rendition.renderTo(u),window.rendition.on("rendered",(()=>{let e=window.rendition.getPosition();window.ReactNativeWebView.postMessage(JSON.stringify({event:"content-loaded",bookLocation:e})),window.rendition.tsTransform()})),window.rendition.on("page-changed",(()=>{let e=window.rendition.getPosition();window.ReactNativeWebView.postMessage(JSON.stringify({event:"page-changed",bookLocation:e}))})),window.ReactNativeWebView.postMessage(JSON.stringify({event:"book-inited",chapterList:window.rendition.getChapter()}))}catch(e){window.ReactNativeWebView.postMessage(JSON.stringify({event:"error",message:"Parse book failed"}))}})),q.addMobileBook=(e,t,r,o,i,n,a="")=>s(void 0,void 0,void 0,(function*(){var s;try{const c=yield fetch(e);if(!c.ok)throw new Error(`Failed to download book: ${c.status} ${c.statusText}`);const l=yield c.arrayBuffer();null===(s=window.ReactNativeWebView)||void 0===s||s.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=l;let d=z.getRendtion(l,r.toUpperCase(),"","","","no",a,"no","yes",window.Kookit);window.rendition=d;let u=yield q.generateBook(t,r,o,i,n,l,d);if(!u||!u.key)return;window.ReactNativeWebView.postMessage(JSON.stringify({event:"metadata",bookInfo:u}))}catch(e){window.ReactNativeWebView.postMessage(JSON.stringify({event:"error",message:"Parse book failed"}))}})),q.precacheMobileBook=(e,t)=>s(void 0,void 0,void 0,(function*(){let r=yield window.rendition.preCache(window.file_content);if(""===r)window.ReactNativeWebView.postMessage(JSON.stringify({event:"cache",cacheBase64:"",key:t}));else if("err"!==r){try{const o=`${e}/dav/${"cache-"+t+".zip"}`,i=yield fetch(o,{method:"PUT",headers:{"Content-Type":"application/octet-stream",Overwrite:"T"},body:r});if(!i.ok)throw new Error(`上传失败: ${i.status}`);console.info("文件上传成功")}catch(e){console.error("操作失败:"+e)}window.ReactNativeWebView.postMessage(JSON.stringify({event:"cache",key:t}))}else window.ReactNativeWebView.postMessage(JSON.stringify({event:"error",message:"Parse book failed"}));window.file_content=null,window.rendition=null}));const U=u.devUrl;class W{constructor(e,t){this.processingQueue=!1,this.requestQueue=[],this.TokenService=e,this.ConfigService=t,this.refreshToken="",this.accessToken="",this.streamPromise=null}refreshUserToken(){return s(this,void 0,void 0,(function*(){if(this.refreshToken=yield this.TokenService.getToken("refresh_token"),!this.refreshToken)return{code:401,message:"refresh token not found"};let t=(yield e.post(U+"/api/v1/public/user/refresh_token",{refresh_token:this.refreshToken})).data;return 200===t.code&&(yield this.TokenService.setToken("access_token",t.data.access_token),yield this.TokenService.setToken("refresh_token",t.data.refresh_token),this.accessToken=t.data.access_token,this.refreshToken=t.data.refresh_token),t}))}requestWithRetry(e){return s(this,void 0,void 0,(function*(){return this.requestQueue||(this.requestQueue=[]),new Promise(((t,r)=>{this.requestQueue.push({config:e,resolve:t,reject:r}),this.processingQueue||this.processQueue()}))}))}processQueue(){return s(this,void 0,void 0,(function*(){if(!this.processingQueue){this.processingQueue=!0;try{for(;this.requestQueue.length>0;){const e=this.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{this.processingQueue=!1}}}))}executeRequest(t){return s(this,void 0,void 0,(function*(){try{try{this.accessToken=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let r="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);t.baseURL=U,t.headers?(t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=r):t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":r};let o=(yield e(t)).data;if(402===o.code){let r=yield this.refreshUserToken();if(200===r.code){return t.headers=t.headers||{},t.headers.Authorization="Bearer "+this.accessToken,(yield e(t)).data}return r}return 200!==o.code&&this.ConfigService.setItem("errorLog",JSON.stringify({request:t.data,url:t.url,result:o,requestID:r})),o}catch(e){throw console.error("Request execution error:",e),e}}))}requestWithStream(e,t,r){return s(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>s(this,void 0,void 0,(function*(){try{let o="";try{o=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((n,a)=>{const c=new r(U+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+o,"X-Request-ID":i},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});c.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),c.addEventListener("message",(e=>s(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);r.done?(c.close(),n(r)):(402===r.code&&(yield this.refreshUserToken()),t(r.data))})))),c.addEventListener("error",(e=>{console.error("Error:",e),n({code:500,message:"internal error"}),c.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return s(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>s(this,void 0,void 0,(function*(){try{let r="";try{r=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((i,n)=>s(this,void 0,void 0,(function*(){const n=yield fetch(U+e.url,{method:"POST",headers:{"Content-Type":"text/event-stream",Authorization:"Bearer "+r,"X-Request-ID":o},body:JSON.stringify(e.data)});if(!n.body)throw new Error("Response body is null");const s=n.body.pipeThrough(new TextDecoderStream).getReader();for(;;){const{value:e,done:r}=yield s.read();if(r){t({done:!0});break}if(e)if(e.includes('"code":400')||e.includes('"code":401')||e.includes('"code":402')){let t=JSON.parse(e);402===t.code&&(yield this.refreshUserToken()),i(t)}else e.split("\n").forEach((e=>{if(e.startsWith("data:")){const r=JSON.parse(e.substring(5));t(r.data)}}))}}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}class K extends W{constructor(e,t){super(e,t)}getTransStream(e,t,r){return s(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_trans_stream",data:e};return yield this.requestWithStream(o,t,r)}))}getTransFetch(e,t){return s(this,void 0,void 0,(function*(){const r={method:"post",url:"/api/v1/pro/reader/get_llm_trans_stream",data:e};return yield this.requestWithFetch(r,t)}))}getDictionary(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_dict",data:e};return yield this.requestWithRetry(t)}))}getSummaryStream(e,t,r){return s(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_sum_stream",data:e};return yield this.requestWithStream(o,t,r)}))}getSummaryFetch(e,t){return s(this,void 0,void 0,(function*(){const r={method:"post",url:"/api/v1/pro/reader/get_llm_sum_stream",data:e};return yield this.requestWithFetch(r,t)}))}getGoogleFont(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_google_font",data:e};return yield this.requestWithRetry(t)}))}sendToKindle(e){return s(this,void 0,void 0,(function*(){let t=new FormData;t.append("file",e.file),t.append("email",e.email),t.append("file_name",e.fileName);const r={method:"post",url:"/api/v1/pro/reader/send_to_kindle",headers:{"Content-Type":"multipart/form-data"},data:t};return yield this.requestWithRetry(r)}))}}class Q extends W{constructor(e,t){super(e,t)}encryptToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/encrypt_token",data:e};return yield this.requestWithRetry(t)}))}decryptToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};return yield this.requestWithRetry(t)}))}authThirdToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/auth_token",data:e};return yield this.requestWithRetry(t)}))}refreshThirdToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/refresh_token",data:e};return yield this.requestWithRetry(t)}))}s3Upload(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_upload",data:e};return yield this.executeRequest(t)}))}s3Download(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_download",data:e};return yield this.executeRequest(t)}))}s3List(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_list",data:e};return yield this.executeRequest(t)}))}s3Delete(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_delete",data:e};return yield this.executeRequest(t)}))}getSyncState(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/pro/thirdparty/get_sync_state"})}))}deleteSyncState(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/pro/thirdparty/delete_sync_state"})}))}}class J extends W{constructor(e,t){super(e,t)}loginRegister(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/public/user/login_register",data:e};return yield this.requestWithRetry(t)}))}logout(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/logout"})}))}getLogins(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/get_logins"})}))}addLogin(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/add_login",data:e};return yield this.requestWithRetry(t)}))}removeLogin(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/remove_login",data:e};return yield this.requestWithRetry(t)}))}getUserInfo(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/get_info"})}))}getTempToken(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/member/user/get_temp_token"})}))}sendEmailCode(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/public/user/send_email_code",data:e};return yield this.requestWithRetry(t)}))}checkEmailRegistration(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/public/user/check_email_registration",data:e};return yield this.requestWithRetry(t)}))}redeemCode(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/redeem_code",data:e};return yield this.requestWithRetry(t)}))}}var H={getAuthUrl:(e,t)=>{let r="";if("github"===e?r=`https://github.com/login/oauth/authorize?client_id=${h.githubClientId}&redirect_uri=${h.callbackUrl}&scope=openid`:"google"===e?r=`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${h.callbackUrl}&prompt=consent&response_type=code&client_id=${h.googleClientId}&scope=openid&access_type=offline`:"facebook"===e?r=`https://www.facebook.com/v12.0/dialog/oauth?client_id=${h.facebookClientId}&redirect_uri=${h.callbackUrl}&scope=&response_type=code`:"microsoft"===e&&(r=`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${h.microsoftClientId}&scope=openid profile User.Read offline_access&response_type=code&redirect_uri=${h.callbackUrl}`),"manual"===t)return r;let o=JSON.stringify({deeplink:"desktop"===t?"koodo-reader://callback":"browser"===t?"https://web.koodoreader.com/#/login":"",service:e});return`${r}&state=${"state|"+encodeURIComponent(o)}`}};class V{static CompareDatabase(e,t,r){return s(this,void 0,void 0,(function*(){let o=Object.keys(e).filter((e=>e.startsWith("database.sqlite.books"))),i=Object.keys(e).filter((e=>e.startsWith("database.sqlite.notes"))),n=Object.keys(e).filter((e=>e.startsWith("database.sqlite.bookmarks"))),s=Object.keys(e).filter((e=>e.startsWith("database.sqlite.plugins"))),a=Object.keys(e).filter((e=>e.startsWith("database.sqlite.words"))),c=Object.keys(t).filter((e=>e.startsWith("database.sqlite.books"))),l=Object.keys(t).filter((e=>e.startsWith("database.sqlite.notes"))),d=Object.keys(t).filter((e=>e.startsWith("database.sqlite.bookmarks"))),u=Object.keys(t).filter((e=>e.startsWith("database.sqlite.plugins"))),h=Object.keys(t).filter((e=>e.startsWith("database.sqlite.words"))),p={books:Array.from(new Set(o.concat(c))),notes:Array.from(new Set(i.concat(l))),bookmarks:Array.from(new Set(n.concat(d))),plugins:Array.from(new Set(s.concat(u))),words:Array.from(new Set(a.concat(h)))},f={books:{save:[],update:[],delete:[],conflict:[],upload:[]},notes:{save:[],update:[],delete:[],conflict:[],upload:[]},bookmarks:{save:[],update:[],delete:[],conflict:[],upload:[]},plugins:{save:[],update:[],delete:[],conflict:[],upload:[]},words:{save:[],update:[],delete:[],conflict:[],upload:[]}},y=["books","notes","bookmarks","plugins","words"];for(let o of y)for(let i of p[o]){let n=i.split(".")[3],s=e[i],a=t[i];s?a?("save"===a.operation&&("update"===s.operation||"delete"===s.operation?f[o].upload.push(n):console.info("ignore",a)),"delete"===a.operation&&("save"===s.operation&&(f[o].delete.push(n),e[i]=a),"update"===s.operation&&(s.timea.time?(f[o].conflict.push(n),"cloud"===r?(f[o].delete.push(n),e[i]=a):f[o].upload.push(n)):console.info("ignore",a)),"delete"===s.operation&&console.info("ignore",a)),"update"===a.operation&&("save"===s.operation&&(f[o].update.push(n),e[i]=a),"update"===s.operation&&(s.timea.time?f[o].upload.push(n):console.info("ignore",a)),"delete"===s.operation&&(s.timea.time?f[o].upload.push(n):console.info("ignore",a)))):f[o].upload.push(n):(f[o].save.push(n),e[i]=a)}return{compareResult:f,syncRecords:e}}))}static CompareConfig(e,t,r){return s(this,void 0,void 0,(function*(){let o=Object.keys(e).filter((e=>e.startsWith("config.readerConfig"))),i=Object.keys(e).filter((e=>e.startsWith("config.listConfig"))),n=Object.keys(e).filter((e=>e.startsWith("config.objectConfig"))),s=Object.keys(e).filter((e=>e.startsWith("config.mapConfig"))),a=Object.keys(t).filter((e=>e.startsWith("config.readerConfig"))),c=Object.keys(t).filter((e=>e.startsWith("config.listConfig"))),l=Object.keys(t).filter((e=>e.startsWith("config.objectConfig"))),d=Object.keys(t).filter((e=>e.startsWith("config.mapConfig"))),u={readerConfig:Array.from(new Set(o.concat(a))),listConfig:Array.from(new Set(i.concat(c))),objectConfig:Array.from(new Set(n.concat(l))),mapConfig:Array.from(new Set(s.concat(d)))},h={readerConfig:{update:[],upload:[]},listConfig:{update:[],upload:[]},objectConfig:{update:[],delete:[],conflict:[],upload:[]},mapConfig:{update:[],delete:[],conflict:[],upload:[]}},p=["readerConfig","listConfig"];for(let r of p)for(let o of u[r]){let i=o,n=e[o],s=t[o];n?s?n.times.time?h[r].upload.push(i):console.info("ignore",s):h[r].upload.push(i):(h[r].update.push(i),e[o]=s)}let f=["objectConfig","mapConfig"];for(let o of f)for(let i of u[o]){let n=i,s=e[i],a=t[i];s?a?("delete"===a.operation&&("update"===s.operation&&(s.timea.time?(h[o].conflict.push(n),"cloud"===r?(h[o].delete.push(n),e[i]=a):h[o].upload.push(n)):console.info("ignore",a)),"delete"===s.operation&&console.info("ignore",a)),"update"===a.operation&&("update"===s.operation&&(s.timea.time?h[o].upload.push(n):console.info("ignore",a)),"delete"===s.operation&&(s.timea.time?h[o].upload.push(n):console.info("ignore",a)))):h[o].upload.push(n):(h[o].update.push(n),e[i]=a)}return{compareResult:h,syncRecords:e}}))}static compareAll(e,t,r,o,i){return s(this,void 0,void 0,(function*(){let n="cloud";if("yes"===r.getReaderConfig("isKeepLocal")){n="local";let e=r.getObjectConfig(yield o.getFingerprint(),"cloudSyncTime",{time:0,conflictMode:"cloud"}),t=yield i.getCloudConfig("config"),s=JSON.parse(t.cloudSyncTime||"{}");delete s[yield o.getFingerprint()],Object.values(s).filter((t=>"local"===t.conflictMode&&t.time>e.time)).length>0&&(n="cloud")}let{compareResult:s,syncRecords:a}=yield this.CompareDatabase(e,t,n),{compareResult:c,syncRecords:l}=yield this.CompareConfig(a,t,n),d=Object.assign(Object.assign({},s),c);return r.setAllSyncRecord(l),"local"===n&&(d.books.conflict.length>0||d.notes.conflict.length>0||d.bookmarks.conflict.length>0||d.plugins.conflict.length>0||d.words.conflict.length>0||d.objectConfig.conflict.length>0||d.mapConfig.conflict.length>0)?r.setObjectConfig(yield o.getFingerprint(),{time:(new Date).getTime(),conflictMode:"local"},"cloudSyncTime"):r.setObjectConfig(yield o.getFingerprint(),{time:(new Date).getTime(),conflictMode:"cloud"},"cloudSyncTime"),d}))}static startSync(e,t,r,o,i,n){return s(this,void 0,void 0,(function*(){return[...yield this.syncConfig(e,t,r,i,o),...yield this.syncCover(t,n,i),...yield this.syncBook(t,i)]}))}static syncConfig(e,t,r,o,i){return s(this,void 0,void 0,(function*(){let n=[];for(let t of c){if(e[t].save.length+e[t].update.length>0){let o=yield i.getCloudDatabase(t);for(let i of e[t].save){let e=o.find((e=>e.key===i));e&&(yield r.saveRecord(e,t))}for(let i of e[t].update){let e=o.find((e=>e.key===i));e&&(yield r.updateRecord(e,t,!1))}}if(e[t].delete.length>0)for(let i of e[t].delete)yield r.deleteRecord(i,t),"books"===t&&(yield o.deleteOfflineBook(i))}if(e.readerConfig.update.length>0||e.listConfig.update.length>0||e.objectConfig.update.length>0||e.mapConfig.update.length>0){let r=yield i.getCloudConfig("config");for(let o of e.readerConfig.update){let e=o.split(".")[3];r.readerConfig&&t.setReaderConfig(e,JSON.parse(r.readerConfig)[e],!1)}for(let o of e.listConfig.update){let e=o.split(".")[3];r[e]&&t.setAllListConfig(JSON.parse(r[e]),e,!1)}for(let o of e.objectConfig.update){let e=o.split(".")[3],i=o.split(".")[2];r[i]&&JSON.parse(r[i])&&JSON.parse(r[i])[e]&&t.setObjectConfig(e,JSON.parse(r[i])[e],i,!1)}for(let o of e.mapConfig.update){let e=o.split(".")[3],i=o.split(".")[2];if(r[i]&&JSON.parse(r[i])&&JSON.parse(r[i])[e]){let o=JSON.parse(r[i])[e];t.setOneMapConfig(e,o,i,!1)}}}if(e.objectConfig.delete.length>0||e.mapConfig.delete.length>0){for(let r of e.objectConfig.delete){let e=r.split(".")[3],o=r.split(".")[2];t.deleteObjectConfig(e,o)}for(let r of e.mapConfig.delete){let e=r.split(".")[3],o=r.split(".")[2];t.deleteMapConfig(e,o)}}for(let t of c)e[t].upload.length>0&&n.push((()=>i.uploadDatabase(t)));return n.push((()=>i.uploadConfig("config"))),n.push((()=>i.uploadConfig("sync"))),n}))}static syncCover(e,t,r){return s(this,void 0,void 0,(function*(){let r=yield t.getLocalCoverList(),o=yield t.getCloudCoverList(),i=Array.from(new Set([...r,...o])),n=[];for(let s of i)r.includes(s)&&!o.includes(s)&&n.push((()=>t.uploadCover(s))),!r.includes(s)&&o.includes(s)&&"adrive"!==e.getItem("defaultSyncOption")&&n.push((()=>t.downloadCover(s)));return n}))}static syncBook(e,t){return s(this,void 0,void 0,(function*(){let r=yield t.getLocalBookList(),o=yield t.getCloudBookList(),i=[],n=Array.from(new Set([...r,...o]));for(let s of n){if(s.startsWith("cache"))continue;if(r.includes(s)&&!o.includes(s)){let e=s.split(".")[0],r=s.split(".")[1];i.push((()=>t.uploadBook(e,r)))}let n="yes"===e.getReaderConfig("autoOffline");if(!r.includes(s)&&o.includes(s)&&n&&"adrive"!==e.getItem("defaultSyncOption")){let e=s.split(".")[0],r=s.split(".")[1];i.push((()=>t.offlineBook(e,r.toUpperCase())))}}return i}))}static runTasksWithLimit(e,t,r){return s(this,void 0,void 0,(function*(){if("ftp"!==r&&"adrive"!==r){const r=[],o=[];for(const i of e){const e=i().then((t=>(o.splice(o.indexOf(e),1),t)));r.push(e),o.push(e),o.length>=t&&(yield Promise.race(o))}return Promise.all(r)}for(let t of e)yield t()}))}}const X=(Y=class{static getItem(e){return localStorage.getItem(e)}static setItem(e,t){localStorage.setItem(e,t)}static removeItem(e){localStorage.removeItem(e)}},G="browser",class extends Y{static getReaderConfig(e){return JSON.parse(this.getItem("readerConfig")||"{}")[e]}static setReaderConfig(e,t,r=!0){let o=JSON.parse(this.getItem("readerConfig")||"{}");o[e]=t,this.setItem("readerConfig",JSON.stringify(o)),r&&this.setSyncRecord({type:"config",catergory:"readerConfig",name:G,key:e},{operation:"update",time:Date.now()})}static getAllListConfig(e){return("{}"!==this.getItem(e)&&this.getItem(e)?JSON.parse(this.getItem(e)||""):[])||[]}static deleteListConfig(e,t){let r=this.getAllListConfig(t);const o=r.indexOf(e);o>-1&&r.splice(o,1),this.setAllListConfig(r,t)}static setListConfig(e,t){let r=this.getAllListConfig(t);const o=r.indexOf(e);o>-1?(r.splice(o,1),r.unshift(e)):r.unshift(e),this.setAllListConfig(r,t)}static setAllListConfig(e,t,r=!0){this.setItem(t,JSON.stringify(e)),r&&this.setSyncRecord({type:"config",catergory:"listConfig",name:"general",key:t},{operation:"update",time:Date.now()})}static setObjectConfig(e,t,r,o=!0){let i=this.getAllObjectConfig(r);i[e]=t,o&&this.setSyncRecord({type:"config",catergory:"objectConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllObjectConfig(i,r)}static getObjectConfig(e,t,r){return this.getAllObjectConfig(t)[e]||r}static getAllObjectConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static setAllObjectConfig(e,t){this.setItem(t,JSON.stringify(e))}static deleteObjectConfig(e,t){let r=this.getAllObjectConfig(t);delete r[e],this.setSyncRecord({type:"config",catergory:"objectConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllObjectConfig(r,t)}static getAllMapConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static getMapConfig(e,t){return this.getAllMapConfig(t)[e]||[]}static setAllMapConfig(e,t){this.setItem(t,JSON.stringify(e))}static setMapConfig(e,t,r){let o=this.getAllMapConfig(r);void 0===o[e]&&(o[e]=[]),t&&-1===o[e].indexOf(t)&&o[e].unshift(t),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,r)}static setOneMapConfig(e,t,r,o=!0){let i=this.getAllMapConfig(r);i[e]=t,o&&this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(i,r)}static deleteFromMapConfig(e,t,r){let o=this.getAllMapConfig(r),i=o[e].indexOf(t);o[e].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,r)}static deleteFromAllMapConfig(e,t){let r=this.getAllMapConfig(t);Object.keys(r).forEach((o=>{let i=r[o].indexOf(e);i>-1&&(r[o].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:o},{operation:"update",time:Date.now()}))})),this.setAllMapConfig(r,t)}static deleteMapConfig(e,t){let r=this.getAllMapConfig(t);delete r[e],this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllMapConfig(r,t)}static getFromAllMapConfig(e,t){let r=this.getAllMapConfig(t),o=[];for(let t in r)r[t]&&r[t].indexOf(e)>-1&&o.push(t);return o}static getSyncRecord(e){return JSON.parse(this.getItem("syncRecord")||"{}")[e.type+"."+e.catergory+"."+e.name+"."+e.key]||{operation:"",time:0}}static getAllSyncRecord(){return JSON.parse(this.getItem("syncRecord")||"{}")}static setSyncRecord(e,t){let r=JSON.parse(this.getItem("syncRecord")||"{}");r[e.type+"."+e.catergory+"."+e.name+"."+e.key]=t,this.setItem("syncRecord",JSON.stringify(r))}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}});var Y,G;let Z;const ee=new Uint8Array(16);function te(){if(!Z&&(Z="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Z))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Z(ee)}const re=[];for(let e=0;e<256;++e)re.push((e+256).toString(16).slice(1));var oe={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ie(e,t,r){if(oe.randomUUID&&!t&&!e)return oe.randomUUID();const o=(e=e||{}).random||(e.rng||te)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=o[e];return t}return function(e,t=0){return re[e[t+0]]+re[e[t+1]]+re[e[t+2]]+re[e[t+3]]+"-"+re[e[t+4]]+re[e[t+5]]+"-"+re[e[t+6]]+re[e[t+7]]+"-"+re[e[t+8]]+re[e[t+9]]+"-"+re[e[t+10]]+re[e[t+11]]+re[e[t+12]]+re[e[t+13]]+re[e[t+14]]+re[e[t+15]]}(o)}class ne{static saveAllToken(e){return s(this,void 0,void 0,(function*(){if(e)if(n){const{ipcRenderer:t}=window.require("electron");t.invoke("encrypt-data",{token:e})}else{const t=yield this.encryptString(e);localStorage.setItem("encryptedToken",t)}}))}static getAllToken(){return s(this,void 0,void 0,(function*(){if(n){const{ipcRenderer:e}=window.require("electron");return yield e.invoke("decrypt-data")}{let e=localStorage.getItem("encryptedToken")||"";return e?yield this.decryptString(e):null}}))}static setToken(e,t){return s(this,void 0,void 0,(function*(){const r=JSON.parse((yield this.getAllToken())||"{}");r[e]=t,yield this.saveAllToken(JSON.stringify(r))}))}static getToken(e){return s(this,void 0,void 0,(function*(){return JSON.parse((yield this.getAllToken())||"{}")[e]||null}))}static deleteToken(e){return s(this,void 0,void 0,(function*(){const t=JSON.parse((yield this.getAllToken())||"{}");delete t[e],yield this.saveAllToken(JSON.stringify(t))}))}static encryptString(e){return s(this,void 0,void 0,(function*(){try{let t=yield this.getFingerprint();const r=yield ce(t),o=yield function(e,t,r={alg:"HS256",typ:"JWT"}){return s(this,void 0,void 0,(function*(){const o=se((new TextEncoder).encode(JSON.stringify(r))),i=se((new TextEncoder).encode(JSON.stringify(e))),n=(new TextEncoder).encode(`${o}.${i}`),s=yield crypto.subtle.importKey("raw",(new TextEncoder).encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return`${o}.${i}.${se(yield crypto.subtle.sign("HMAC",s,n))}`}))}(e,r);return o}catch(e){return console.error("Error generating secret:",e),""}}))}static decryptString(e){return s(this,void 0,void 0,(function*(){try{let t=yield this.getFingerprint();const r=yield ce(t),o=yield function(e,t){return s(this,void 0,void 0,(function*(){const[r,o,i]=e.split("."),n=(new TextEncoder).encode(`${r}.${o}`),s=yield ae(i),a=yield crypto.subtle.importKey("raw",(new TextEncoder).encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["verify"]);if(!(yield crypto.subtle.verify("HMAC",a,s,n)))throw new Error("Invalid signature");return JSON.parse((new TextDecoder).decode(ae(o)))}))}(e,r);return o}catch(e){return console.error("Error generating secret:",e),""}}))}static oldDecryptString(e){return s(this,void 0,void 0,(function*(){let t=yield this.getFingerprint();const r=yield crypto.subtle.digest("SHA-256",(new TextEncoder).encode(t)),o=yield crypto.subtle.importKey("raw",r,{name:"AES-GCM",length:256},!1,["decrypt"]),i=new Uint8Array(e.split("").map((e=>e.charCodeAt(0)))),n=i.slice(0,12),s=i.slice(12),a=yield crypto.subtle.decrypt({name:"AES-GCM",iv:n},o,s);return(new TextDecoder).decode(a)}))}static getFingerprint(){return s(this,void 0,void 0,(function*(){if(n){const{ipcRenderer:e}=window.require("electron");return yield e.invoke("get-mac")}{let e=X.getItem("fingerPrint");if(e)return e;let t=ie().replace(/-/g,"");return X.setItem("fingerPrint",t),t}}))}}function se(e){return btoa(String.fromCharCode.apply(null,Array.from(new Uint8Array(e)))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ae(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),o=new Uint8Array(r.length);for(let e=0;e=0&&r<=Se}}function rt(e){return function(t){return null==t?void 0:t[e]}}var ot=rt("byteLength"),it=tt(ot),nt=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;var st=ve?function(e){return Ee?Ee(e)&&!He(e):it(e)&&nt.test(ge.call(e))}:et(!1),at=rt("length");function ct(e,t){t=function(e){for(var t={},r=e.length,o=0;o":">",'"':""","'":"'","`":"`"},Gt=Xt(Yt),Zt=Xt(Ot(Yt)),er=ut.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},tr=/(.)^/,rr={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},or=/\\|'|\r|\n|\u2028|\u2029/g;function ir(e){return"\\"+rr[e]}var nr=/^\s*(\w|\$)+\s*$/;var sr=0;function ar(e,t,r,o,i){if(!(o instanceof t))return e.apply(r,i);var n=jt(e.prototype),s=e.apply(n,i);return Ae(s)?s:n}var cr=Oe((function(e,t){var r=cr.placeholder,o=function(){for(var i=0,n=t.length,s=Array(n),a=0;a1)ur(a,t-1,r,o),i=o.length;else for(var c=0,l=a.length;c0&&(r=t.apply(this,arguments)),e<=1&&(t=null),r}}var mr=cr(gr,2);function vr(e,t,r){t=Qt(t,r);for(var o,i=lt(e),n=0,s=i.length;n0?0:i-1;n>=0&&n0?s=n>=0?n:Math.max(n+a,s):a=n>=0?Math.min(n+1,a):n+a+1;else if(r&&n&&a)return o[n=r(o,i)]===i?n:-1;if(i!=i)return(n=t(ye.call(o,s,a),Ze))>=0?n+s:-1;for(n=e>0?s:a-1;n>=0&&n=3;return function(t,r,o,i){var n=!dr(t)&<(t),s=(n||t).length,a=e>0?0:s-1;for(i||(o=t[n?n[a]:a],a+=e);a>=0&&a=0}var Br=Oe((function(e,t,r){var o,i;return Ue(t)?i=t:(t=Pt(t),o=t.slice(0,-1),t=t[t.length-1]),Sr(e,(function(e){var n=i;if(!n){if(o&&o.length&&(e=Dt(e,o)),null==e)return;n=e[t]}return null==n?n:n.apply(e,r)}))}));function Pr(e,t){return Sr(e,qt(t))}function Dr(e,t,r){var o,i,n=-1/0,s=-1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var a=0,c=(e=dr(e)?e:St(e)).length;an&&(n=o);else t=Qt(t,r),Rr(e,(function(e,r,o){((i=t(e,r,o))>s||i===-1/0&&n===-1/0)&&(n=e,s=i)}));return n}var zr=/[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;function $r(e){return e?Ve(e)?ye.call(e):Me(e)?e.match(zr):dr(e)?Sr(e,$t):St(e):[]}function Nr(e,t,r){if(null==t||r)return dr(e)||(e=St(e)),e[Ht(e.length-1)];var o=$r(e),i=at(o);t=Math.max(Math.min(t,i),0);for(var n=i-1,s=0;s1&&(o=Ut(o,t[1])),t=gt(e)):(o=Jr,t=ur(t,!1,!1),e=Object(e));for(var i=0,n=t.length;i1&&(r=t[1])):(t=Sr(ur(t,!1,!1),String),o=function(e,r){return!jr(t,r)}),Hr(e,o,r)}));function Xr(e,t,r){return ye.call(e,0,Math.max(0,e.length-(null==t||r?1:t)))}function Yr(e,t,r){return null==e||e.length<1?null==t||r?void 0:[]:null==t||r?e[0]:Xr(e,e.length-t)}function Gr(e,t,r){return ye.call(e,null==t||r?1:t)}var Zr=Oe((function(e,t){return t=ur(t,!0,!0),Ir(e,(function(e){return!jr(t,e)}))})),eo=Oe((function(e,t){return Zr(e,t)}));function to(e,t,r,o){Ie(t)||(o=r,r=t,t=!1),null!=r&&(r=Qt(r,o));for(var i=[],n=[],s=0,a=at(e);st?(o&&(clearTimeout(o),o=null),a=l,s=e.apply(i,n),o||(i=n=null)):o||!1===r.trailing||(o=setTimeout(c,d)),s};return l.cancel=function(){clearTimeout(o),a=0,o=i=n=null},l},debounce:function(e,t,r){var o,i,n,s,a,c=function(){var l=Vt()-i;t>l?o=setTimeout(c,t-l):(o=null,r||(s=e.apply(a,n)),o||(n=a=null))},l=Oe((function(l){return a=this,n=l,i=Vt(),o||(o=setTimeout(c,t),r&&(s=e.apply(a,n))),s}));return l.cancel=function(){clearTimeout(o),o=n=a=null},l},wrap:function(e,t){return cr(t,e)},negate:yr,compose:function(){var e=arguments,t=e.length-1;return function(){for(var r=t,o=e[t].apply(this,arguments);r--;)o=e[r].call(this,o);return o}},after:function(e,t){return function(){if(--e<1)return t.apply(this,arguments)}},before:gr,once:mr,findKey:vr,findIndex:br,findLastIndex:wr,sortedIndex:Tr,indexOf:Cr,lastIndexOf:_r,find:xr,detect:xr,findWhere:function(e,t){return xr(e,Nt(t))},each:Rr,forEach:Rr,map:Sr,collect:Sr,reduce:Ar,foldl:Ar,inject:Ar,reduceRight:Fr,foldr:Fr,filter:Ir,select:Ir,reject:function(e,t,r){return Ir(e,yr(Qt(t)),r)},every:Lr,all:Lr,some:Mr,any:Mr,contains:jr,includes:jr,include:jr,invoke:Br,pluck:Pr,where:function(e,t){return Ir(e,Nt(t))},max:Dr,min:function(e,t,r){var o,i,n=1/0,s=1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var a=0,c=(e=dr(e)?e:St(e)).length;ao||void 0===r)return 1;if(re.map((e=>e.name)),uo=e=>e.map((e=>e.key)),ho=(e,t)=>{let r=[];for(let o=0;o-1&&r.push(t.indexOf(e[o]));return r.length{if(-1===e.indexOf(o))for(let e=0;ee-Math.min(...r))))]};class po{static sortBooks(e,t,r){let o=e.map((e=>e.key)),i=(e=>e.getAllListConfig("recentBooks"))(r);if(1===t.sort||0===t.sort)return 1===t.order?ho(i,o).reverse():ho(i,o);if(2===t.sort){let r=lo(e),o=lo(e).sort();return 1===t.order?ho(o,r).reverse():ho(o,r)}if(3===t.sort){let r=[];for(let t=0;t{let t=e.getAllObjectConfig("readingTime");var r=[];for(let e in t)r.push([e,t[e]]);return r.sort((function(e,t){return e[1]-t[1]})),Object.keys(t)})(r),i=uo(e);return 1===t.order?ho(co.union(o,i),i).reverse():ho(co.union(o,i),i)}if(5===t.sort){let r=uo(e),o=(e=>co.sortBy(e.map((e=>({key:e.key,author:e.author}))),"author").map((e=>e.key)))(e);return 1===t.order?ho(o,r).reverse():ho(o,r)}if(6===t.sort){let o=(e=>{let t=e.getAllObjectConfig("recordLocation");var r=[];for(let e in t)r.push([e,t[e].percentage||0]);return r.sort((function(e,t){return e[1]-t[1]})),r.map((e=>e[0]))})(r),i=uo(e);return 1===t.order?ho(o,i).reverse():ho(o,i)}}static sortNotes(e,t,r=[]){if(3===t.sort){let r=co.clone(e).reverse(),o=co.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:e.chapterIndex}))));o=1===t.order?co.sortBy(o,"chapterIndex"):co.sortBy(o,"chapterIndex").reverse();let i=co.uniq(o.map((e=>e.chapter))),n={};return i.forEach((e=>{n[e]=[]})),r.forEach((e=>{n[e.chapter].push(e)})),i.map((e=>({group:e,notes:n[e]})))||[]}if(2===t.sort){let r=co.clone(e).reverse(),o=co.uniq(e.map((e=>e.date.year+"-"+e.date.month+"-"+e.date.day)));1===t.order?o.sort():o.sort().reverse();let i={};return o.forEach((e=>{i[e]=[]})),r.forEach((e=>{o.forEach((t=>{t===e.date.year+"-"+e.date.month+"-"+e.date.day&&i[t].push(e)}))})),i||{}}if(1===t.sort){let o=co.clone(e).reverse(),i=co.uniq(e.map((e=>{let t=co.findLastIndex(r,{key:e.bookKey});return t>-1?r[t].name:""})));1===t.order?i.sort():i.sort().reverse();let n={};return i.forEach((e=>{n[e]=[]})),o.forEach((e=>{i.forEach((t=>{let o=co.findLastIndex(r,{key:e.bookKey});o>-1&&t===r[o].name&&n[t].push(e)}))})),n||{}}}static sortBookmarks(e,t){if(3===t.sort){let r=co.clone(e).reverse(),o=co.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:parseInt(JSON.parse(e.cfi).chapterDocIndex)}))));o=1===t.order?co.sortBy(o,"chapterIndex"):co.sortBy(o,"chapterIndex").reverse();let i=co.uniq(o.map((e=>e.chapter))),n={};return i.forEach((e=>{n[e]=[]})),r.forEach((e=>{n[e.chapter].push(e)})),i.map((e=>({group:e,bookmarks:n[e]})))||[]}}}class fo{static getDefaultCss(e){return`::selection{background:#f3a6a68c}::-moz-selection{background:#f3a6a68c}.kookit-note:hover{cursor:pointer;}img{max-width:100% !important}.kookit-text{${this.getCustomCss(e)}}code,pre{white-space: pre-wrap;}p{margin-block: 0;margin-inline: 0;}${"yes"===e.getReaderConfig("isOverwriteLink")?"a{color: #0066cc !important; text-decoration: underline !important; cursor: pointer !important;}a:hover{color: #004080 !important;}a:visited{color: #6600cc !important;}":""}`}static getCustomCss(e){return`font-size: ${e.getReaderConfig("fontSize")?e.getReaderConfig("fontSize"):"18"}px !important;line-height: ${e.getReaderConfig("lineHeight")||"1.25"} !important;font-family: ${e.getReaderConfig("fontFamily")||""} !important;background-color: transparent;color: ${e.getReaderConfig("textColor")?e.getReaderConfig("textColor"):"rgba(44,47,49,1)"===e.getReaderConfig("backgroundColor")||"night"===e.getReaderConfig("appSkin")||"system"===e.getReaderConfig("appSkin")&&"yes"===e.getReaderConfig("isOSNight")?"white":""} !important;letter-spacing: ${e.getReaderConfig("letterSpacing")}px !important;text-align: ${e.getReaderConfig("textAlign")?e.getReaderConfig("textAlign"):""} !important;font-weight: ${"yes"===e.getReaderConfig("isBold")?"bold !important":""};font-style: ${"yes"===e.getReaderConfig("isItalic")?"italic !important":""};text-shadow: ${"yes"===e.getReaderConfig("isShadow")?"2px 2px 2px #cccccc !important":""};text-indent: ${"yes"===e.getReaderConfig("isIndent")?"2rem":""};text-decoration: ${"yes"===e.getReaderConfig("isUnderline")?"underline !important":""};margin-bottom: ${e.getReaderConfig("paraSpacing")||0}px !important;padding:0px !important;word-wrap: break-word !important; writing-mode: horizontal-tb !important; `}}class yo{static mergeArray(e,t){var r=[];for(let t of e)r.push(t);for(let i of t){var o=!0;for(let t of e)if(i===t){o=!1;break}o&&r.push(i)}return r}static fuzzyQuery(e,t){for(var r=[],o=0;o-1&&r.push(o);return r}static mouseSearch(e){let t=document.querySelector(".header-search-box").value.toLowerCase(),r=[],o=[];if(!e)return[];e.forEach((e=>{r.push(e.name.toLowerCase()),o.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,t),n=this.fuzzyQuery(o,t);return this.mergeArray(i,n)}static keywordSearch(e,t){let r=[],o=[];if(!t)return[];t.forEach((e=>{r.push(e.name.toLowerCase()),o.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,e),n=this.fuzzyQuery(o,e);return this.mergeArray(i,n)}static keySearch(e,t){if(e&&13===e.keyCode){let r=[],o=[];if(!t)return[];t.forEach((e=>{r.push(e.name.toLowerCase()),o.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,e.target.value.toLowerCase()),n=this.fuzzyQuery(o,e.target.value.toLowerCase());return this.mergeArray(i,n)}}static mouseNoteSearch(e){let t=document.querySelector(".header-search-box").value.toLowerCase(),r=[],o=[];e.forEach((e=>{r.push(e.notes.toLowerCase()),o.push(e.text.toLowerCase())}));let i=this.fuzzyQuery(r,t),n=this.fuzzyQuery(o,t);return this.mergeArray(i,n)}static keyNoteSearch(e,t){if(e&&13===e.keyCode){let r=[],o=[];t.forEach((e=>{r.push(e.notes.toLowerCase()),o.push(e.text.toLowerCase())}));let i=this.fuzzyQuery(r,e.target.value.toLowerCase()),n=this.fuzzyQuery(o,e.target.value.toLowerCase());return this.mergeArray(i,n)}}}export{q as BookHelper,d as CommonTool,X as ConfigService,p as KookitConfig,H as LoginHelper,K as ReaderRequest,yo as SearchUtil,po as SortUtil,$ as SqlStatement,fo as StyleHelper,V as SyncHelper,L as SyncUtil,Q as ThirdpartyRequest,ne as TokenService,J as UserRequest}; +import e from"axios";import{Storage as t}from"megajs";import{Buffer as r}from"buffer";import{createClient as o,AuthType as i}from"webdav/dist/web/index.js";import{isElectron as n}from"react-device-detect";function s(e,t,r,o){return new(r||(r=Promise))((function(i,n){function s(e){try{c(o.next(e))}catch(e){n(e)}}function a(e){try{c(o.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((o=o.apply(e,t||[])).next())}))}const a=e=>"json"===e?"application/json":["jpg","jpeg","png","gif","bmp"].includes(e)?"image/"+e:"zip"===e?"application/zip":"epub"===e?"application/epub+zip":"txt"===e?"text/plain":"pdf"===e?"application/pdf":"mobi"===e?"application/x-mobipocket-ebook":"azw3"===e||"azw"===e?"application/vnd.amazon.ebook":"cbz"===e?"application/x-cbz":"cbr"===e?"application/x-cbr":"cbt"===e?"application/x-cbt":"cb7"===e?"application/x-cb7":"fb2"===e?"application/x-fictionbook+xml":"html"===e?"text/html":"css"===e?"text/css":"js"===e?"application/javascript":"xml"===e?"application/xml":"xhtml"===e?"application/xhtml+xml":"opf"===e?"application/oebps-package+xml":"ncx"===e?"application/x-dtbncx+xml":"mp3"===e?"audio/mpeg":"wav"===e?"audio/wav":"ogg"===e?"audio/ogg":"mp4"===e?"video/mp4":"webm"===e?"video/webm":"avi"===e?"video/x-msvideo":"wmv"===e?"video/x-ms-wmv":"flv"===e?"video/x-flv":"m3u8"===e?"application/x-mpegURL":"ts"===e?"video/MP2T":"3gp"===e?"video/3gpp":"3g2"===e?"video/3gpp2":"db"===e?"application/x-sqlite3":void 0,c=["books","notes","bookmarks","plugins","words"];class l{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.maxConcurrency=e}addTask(e){return s(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,r)=>{const o=()=>s(this,void 0,void 0,(function*(){try{this.runningTasks++;const r=yield e();return this.completedTasks++,t(r),r}catch(e){throw this.completedTasks++,r(e),e}finally{this.runningTasks--,this.runNext()}}));this.runningTasks0&&this.runningTasks{var t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e)),t},base64ToArrayBuffer:e=>{const t=atob(e),r=t.length,o=new Uint8Array(r);for(let e=0;e{let t="";const r=new Uint8Array(e),o=r.byteLength;for(let e=0;ee.toString(16).padStart(2,"0"))).join("")}))},EmailProviders:["gmail.com","qq.com","163.com","yahoo.com","sina.com","126.com","outlook.com","yeah.net","foxmail.com","hotmail.com","protonmail.com","proton.me","icloud.com","mail.com","live.com","aliyun.com"]};const u={publicUrl:"https://api.960960.xyz",cloudUrl:"https://cloud.960960.xyz",devUrl:"http://192.168.28.159:8000"},h={callbackUrl:"https://web.koodoreader.com/",dropboxClientId:"vnc67byrssocvy1",pcloudClientId:"pg8ten0B3vH",boxClientId:"ltimecqanmpxoaicn9qw3es6l3sdl1ya",microsoftClientId:"506df58a-29ab-4020-afc5-6f423dc80f35",googleClientId:"1051055003225-ph1f5fvh328dhv7bco5jitlnfhg6ks2t.apps.googleusercontent.com",facebookClientId:"2845583825559500",githubClientId:"Ov23liJVzfvJMMEEZ8v2",adriveClientId:"a128ae7b9c094545af623de61dc0a1ef"};var p={CloudConfig:u,ThirdpartyConfig:h,LoginAuthRequest:{google:{clientId:h.googleClientId,scopes:["openid"],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{prompt:"consent",scope:"openid"}},microsoft:{clientId:h.microsoftClientId,scopes:["openid","profile","User.Read","offline_access"],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{scope:"openid profile User.Read offline_access"}},facebook:{clientId:h.facebookClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{scope:""}},github:{clientId:h.githubClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{scope:""}},email:{clientId:"",scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{scope:""}}},LoginDiscovery:{microsoft:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"},facebook:{authorizationEndpoint:"https://www.facebook.com/v12.0/dialog/oauth",tokenEndpoint:"https://graph.facebook.com/v12.0/oauth/access_token"},github:{authorizationEndpoint:"https://github.com/login/oauth/authorize",tokenEndpoint:"https://github.com/login/oauth/access_token"},email:{authorizationEndpoint:"",tokenEndpoint:""}},DriveAuthRequest:{dropbox:{clientId:h.dropboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{token_access_type:"offline"}},boxnet:{clientId:h.boxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}},pcloud:{clientId:h.pcloudClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{grant_type:"authorization_code"}},adrive:{clientId:h.adriveClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}},microsoft:{clientId:h.microsoftClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{scope:"files.readwrite.appfolder offline_access"}},google:{clientId:h.googleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:h.callbackUrl,extraParams:{prompt:"consent",scope:"https://www.googleapis.com/auth/drive.appdata",access_type:"offline"}}},DriveDiscovery:{dropbox:{authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",tokenEndpoint:"https://www.dropbox.com/oauth2/token"},boxnet:{authorizationEndpoint:"https://account.box.com/api/oauth2/authorize",tokenEndpoint:"https://api.box.com/oauth2/token"},pcloud:{authorizationEndpoint:"https://my.pcloud.com/oauth2/authorize",tokenEndpoint:"https://api.pcloud.com/oauth2_token"},adrive:{authorizationEndpoint:"https://openapi.alipan.com/oauth/authorize",tokenEndpoint:"https://openapi.alipan.com/oauth/token"},microsoft:{authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token"},google:{authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token"}}};class f{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new l(1)}retryOperation(e,t=5){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getDriveId(){return s(this,void 0,void 0,(function*(){if(this.driveId)return this.driveId;const t=yield this.refreshToken(),r=yield e.post("https://openapi.alipan.com/adrive/v1.0/user/getDriveInfo",{},{headers:{Authorization:`Bearer ${t}`}});return this.driveId=r.data.default_drive_id,this.driveId}))}getFolderIdByPath(t){return s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=yield this.getDriveId();try{try{const i=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(i.data)return i.data.file_id}catch(i){const n=t.split("/").filter((e=>e));let s="",a="root";for(const t of n){s+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:s},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.file_id}catch(i){a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:o,parent_file_id:a,name:t,type:"folder",check_name_mode:"refuse"},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.file_id}}return a}}catch(e){return console.error("Error getting/creating folder by path:",e),""}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield this.getDriveId(),i=yield this.getFolderIdByPath("/KoodoReader/"+t);let n=[],s="",a=!0;for(;a;){const t=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:o,parent_file_id:i,marker:s||void 0},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),c=t.data.items||[];n=n.concat(c),s=t.data.next_marker,a=!!s&&100===c.length}return console.log("All items:",n.map((e=>e.name)),n.length),[...new Set(n.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield this.getDriveId(),i=yield this.getFolderIdByPath("/KoodoReader/"+t);return!i||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:o,file_id:i},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}checkExists(t){var r;return s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=yield this.getDriveId(),n=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:t},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});(null===(r=n.data)||void 0===r?void 0:r.file_id)&&(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/recyclebin/trash",{drive_id:i,file_id:n.data.file_id},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}))}catch(e){}}))}refreshToken(){return s(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"adrive",refresh_token:e});this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("adrive_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"adrive",redirect_uri:h.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:h.adriveClientId,redirect_uri:h.callbackUrl,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class y extends f{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return new Promise(((o,i)=>s(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken(),n=yield this.getDriveId(),s=r.substring(0,r.lastIndexOf("/")),a=r.substring(r.lastIndexOf("/")+1),c=yield this.getFolderIdByPath("/KoodoReader/"+s),l=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:n,parent_file_id:c,name:a,type:"file",check_name_mode:"ignore"},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),{file_id:d,upload_id:u,part_info_list:h}=l.data;yield e.put(h[0].upload_url,t,{headers:{"Content-Type":"application/octet-stream"}}),yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/complete",{drive_id:n,file_id:d,upload_id:u},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),o(!0)}catch(e){console.error("Error uploading file:",e),o(!1)}}))))}))}downloadFile(t){return new Promise(((r,o)=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=yield this.getDriveId(),n=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:"/KoodoReader/"+t},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}})).data.file_id,s=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:i,file_id:n},{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}}),a=yield e.get(s.data.url,{responseType:"arraybuffer"});r(a.data)}catch(e){console.error("Error downloading file:",e),r(!1)}}))))}}class g{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getFolderIdByPath(t){return s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=t.split("/");let i="0";for(const t of o){const o=`https://api.box.com/2.0/folders/${i}/items?fields=id,name&type=folder&limit=1000`;try{const n=(yield e.get(o,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(n)i=n.id;else{const o={name:t,parent:{id:i},type:"folder"};i=(yield e.post("https://api.box.com/2.0/folders",o,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}}catch(e){return console.error("Error occurred during folder creation:",e),""}}return i}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=yield this.getFolderIdByPath("KoodoReader/"+t),i=[],n=0,s=!0;const a=1e3;for(;s;){const t=yield e.get(`https://api.box.com/2.0/folders/${o}/items`,{params:{limit:a,offset:n},headers:{Authorization:`Bearer ${r}`}}),c=t.data.entries||[];i=i.concat(c),n+=c.length,s=c.length===a&&t.data.total_count>n}return console.log(i.length,"items"),[...new Set(i.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=t.substring(0,t.lastIndexOf("/")),i=t.substring(t.lastIndexOf("/")+1),n=yield this.getFolderIdByPath("KoodoReader/"+o);if(!n)return!0;const s=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,a=(yield e.get(s,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));return!a||(yield e.delete(`https://api.box.com/2.0/files/${a.id}`,{headers:{Authorization:`Bearer ${r}`}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return s(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"boxnet",refresh_token:e});this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("boxnet_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"boxnet",redirect_uri:h.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:h.boxClientId,redirect_uri:h.callbackUrl,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class m extends g{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=r.substring(0,r.lastIndexOf("/")),n=r.substring(r.lastIndexOf("/")+1),s=yield this.getFolderIdByPath("KoodoReader/"+i);if(!s)throw new Error("Folder not found");const a=(yield this.listFiles(i)).find((e=>e===n));a&&(yield this.deleteFileWithoutQueue(i+"/"+n));let c=new File([t],n,{lastModified:(new Date).getTime(),type:t.type});const l=new FormData;l.append("file",c),l.append("parent_id",s);const d=yield e.post("https://upload.box.com/api/2.0/files/content",l,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"multipart/form-data"},params:{if_match:"false",fields:"name,id"},maxContentLength:1/0,maxBodyLength:1/0});return!(d.status>=300)||(console.error("Error occurred during file upload:",d),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=t.substring(0,t.lastIndexOf("/")),i=t.substring(t.lastIndexOf("/")+1),n=yield this.getFolderIdByPath("KoodoReader/"+o);if(!n)return console.error("Folder not found"),!0;const s=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,a=(yield e.get(s,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));if(!a)return console.error("File not found:",i),!0;const c=yield e({url:`https://api.box.com/2.0/files/${a.id}/content`,method:"get",headers:{Authorization:`Bearer ${r}`},responseType:"arraybuffer"});return c.status>=300?(console.error("Error occurred during file download:",c),!1):c.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class v{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=[],i=!0,n=null;for(;i;){let s;s=n?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:n},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}):yield e.post("https://api.dropboxapi.com/2/files/list_folder",{path:"/"+t,limit:2e3},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});const a=s.data.entries||[];o=o.concat(a),i=s.data.has_more,n=s.data.cursor}return[...new Set(o.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();yield e.post("https://api.dropboxapi.com/2/files/delete_v2",{path:"/"+t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return s(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"dropbox",refresh_token:e});return this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dropbox",redirect_uri:h.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${h.dropboxClientId}&redirect_uri=${h.callbackUrl}`}}class k extends v{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken();let i=r.split("/").pop()||"",n=new File([t],i,{lastModified:(new Date).getTime(),type:t.type});const s=yield e.post("https://content.dropboxapi.com/2/files/upload",n,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/octet-stream","Dropbox-API-Arg":JSON.stringify({path:"/"+r,mode:"overwrite",autorename:!0,mute:!1})},maxContentLength:1/0,maxBodyLength:1/0});return!(s.status>=300)||(console.error("Error occurred during file upload:",s),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e({url:"https://content.dropboxapi.com/2/files/download",method:"post",headers:{Authorization:`Bearer ${r}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+t})},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer"});return o.status>=300?(console.error("Error occurred during file download:",o),!1):o.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class b{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getFileId(t,r){return s(this,void 0,void 0,(function*(){const o=yield this.refreshToken(),i=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+'${r}'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=yield e.get(i,{headers:{Authorization:"Bearer "+o}});if(0===t.data.files.length)return"";const r=t.data.files;return r.length>0?r[0].id:null}catch(e){return console.error("Error occurred during file list retrieval:",e),""}}))}checkFolder(t){return s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=yield this.getFolderId(t);if(o)return o;const i={name:t,mimeType:"application/vnd.google-apps.folder",parents:["appDataFolder"]};try{return(yield e.post("https://www.googleapis.com/drive/v3/files",i,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error("Error occurred during folder creation:",e),e}}))}getFolderId(t){return s(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+mimeType='application/vnd.google-apps.folder'+and+'appDataFolder'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=(yield e.get(o,{headers:{Authorization:`Bearer ${r}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=yield this.checkFolder(t),i=[],n="",s=!0;for(;s;){let t=`https://www.googleapis.com/drive/v3/files?q='${o}'+in+parents&spaces=appDataFolder&fields=nextPageToken,files(id,name)&pageSize=1000`;n&&(t+=`&pageToken=${n}`);const a=yield e.get(t,{headers:{Authorization:`Bearer ${r}`}}),c=a.data.files||[];i=i.concat(c),n=a.data.nextPageToken,s=!!n}return[...new Set(i.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return s(this,void 0,void 0,(function*(){const r=t.split("/")[1],o=t.split("/")[0],i=yield this.getFolderId(o),n=yield this.refreshToken(),s=yield this.getFileId(r,i);if(""===s)return console.error("File not found:",r),!0;try{const t=yield e.delete(`https://www.googleapis.com/drive/v3/files/${s}`,{headers:{Authorization:`Bearer ${n}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return s(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"google",refresh_token:e});return this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"google",redirect_uri:h.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${h.callbackUrl}&prompt=consent&response_type=code&client_id=${h.googleClientId}&scope=https://www.googleapis.com/auth/drive.appdata&access_type=offline`}}class w extends b{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken();let i=r.split("/").pop()||"",n=new File([t],i,{lastModified:(new Date).getTime(),type:t.type}),s=r.split(".").pop(),c=a(s||""),l=r.split("/")[0],d=yield this.checkFolder(l),u=yield this.getFileId(i||"",d);const h={mimeType:c,name:i,parents:[d]},p=u?`https://www.googleapis.com/upload/drive/v3/files/${u}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",f=(yield e({method:u?"PATCH":"POST",url:p,data:u?null:JSON.stringify(h),headers:{Authorization:"Bearer "+o,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location,y=yield this.getData(n);if(0===Object.keys(y).length)return!1;const g=yield e.put(f,y.data,{headers:{Authorization:"Bearer "+o,"Content-Type":"application/zip","Content-Range":`bytes 0-${y.fileSize-1}/${y.fileSize}`},maxContentLength:1/0,maxBodyLength:1/0});return!(g.status>=300)||(console.error("Error occurred during file download:",g),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=t.split("/").pop(),i=t.split("/")[0],n=yield this.checkFolder(i),s=yield this.getFileId(o||"",n);if(!s)return console.error("File not found:",o),!0;const a=`https://www.googleapis.com/drive/v3/files/${s}?alt=media`,c=yield e.get(a,{headers:{Authorization:"Bearer "+r},maxContentLength:1/0,maxBodyLength:1/0,responseType:"arraybuffer"});return c.status>=300?(console.error("Error occurred during file download:",c),!1):c.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getData(e){return s(this,void 0,void 0,(function*(){return e?new Promise(((t,r)=>{const o=new FileReader;o.onload=r=>t({fileName:e.name,mimeType:e.type,fileSize:e.size,data:r.target.result}),o.onerror=e=>r(e),o.readAsArrayBuffer(e)})):{}}))}}class T{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}getStorage(){return s(this,void 0,void 0,(function*(){if(this.storage)return this.storage;let{email:e,password:r}=this.config;return this.storage=yield new t({email:e,password:r}).ready,this.storage}))}getRoot(){return s(this,void 0,void 0,(function*(){if(this.root)return this.root;const e=(yield this.getStorage()).root;let t=e.children.find((e=>"KoodoReader"===e.name&&e.directory));return t||(t=yield e.mkdir("KoodoReader")),this.root=t,this.root}))}createFolder(e,t){return s(this,void 0,void 0,(function*(){const r=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(r))return yield this.folderCreationLocks.get(r);const o=(()=>s(this,void 0,void 0,(function*(){try{let r=e.children.find((e=>e.name===t&&e.directory));return r||(r=yield e.mkdir(t),r)}finally{this.folderCreationLocks.delete(r)}})))();return this.folderCreationLocks.set(r,o),yield o}))}listFiles(e){return s(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();if(e){const r=e.split("/").filter((e=>e));for(const e of r){const r=t.children.find((t=>t.name===e&&t.directory));if(!r)return[];t=r}}return t.children.filter((e=>!e.directory)).map((e=>e.name))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return s(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();const r=e.split("/"),o=r.pop();for(const e of r){if(!e)continue;const r=t.children.find((t=>t.name===e&&t.directory));if(!r)return!0;t=r}const i=t.children.find((e=>e.name===o&&!e.directory));return!i||(yield i.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class E extends T{constructor(e){super(e)}uploadFile(e,t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const i=t.split("/"),n=i.pop()||"";for(const e of i){if(!e)continue;let t=o.children.find((t=>t.name===e&&t.directory));t||(t=yield this.createFolder(o,e)),o=t}const s=new File([e],n,{lastModified:(new Date).getTime(),type:e.type}),a=yield e.arrayBuffer(),c=new Uint8Array(a),l=r.from(c),d=o.children.find((e=>e.name===n&&!e.directory));return d&&(yield d.delete()),yield o.upload({name:n,size:s.size},l).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();const r=e.split("/"),o=r.pop()||"";for(const e of r){if(!e)continue;const r=t.children.find((t=>t.name===e&&t.directory));if(!r)return!0;t=r}const i=t.children.find((e=>e.name===o&&!e.directory));if(!i)return!0;return yield i.downloadBuffer()}catch(e){return console.error("Error occurred during MEGA file download:",e),!1}}))))))}))}}class C{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new l(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let o=[],i=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/children`;for(;i;){const t=yield e.get(i,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(t.status>=300)break;const n=t.data.value||[];o=o.concat(n),i=t.data["@odata.nextLink"]||""}return[...new Set(o.map((e=>e.name)))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.delete(`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!(o.status>=300)||(console.error("Error deleting file:",o),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return s(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>s(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"microsoft",refresh_token:e});return this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"microsoft",redirect_uri:h.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${h.microsoftClientId}&scope=files.readwrite.appfolder offline_access&response_type=code&redirect_uri=${h.callbackUrl}`}}class _ extends C{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken();let i=r.split("/").pop()||"",n=new File([t],i,{lastModified:(new Date).getTime(),type:t.type});const s="https://graph.microsoft.com/v1.0/me/drive/special/approot:/"+r+":/createUploadSession",a=yield e.post(s,null,{headers:{Authorization:"Bearer "+o,"Content-Type":"application/json"},maxContentLength:1/0,maxBodyLength:1/0});let c=n.size;const l=n.type,d=a.data.uploadUrl,u=yield e.put(d,n,{headers:{"Content-Type":l,"Content-Range":`bytes 0-${c-1}/${c}`},maxContentLength:1/0,maxBodyLength:1/0});return!(u.status>=300)||(console.error("Error occurred during file download:",u),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/content`,i=yield e.get(o,{responseType:"arraybuffer",headers:{Authorization:"Bearer "+r},maxContentLength:1/0,maxBodyLength:1/0});return i.status>=300?(console.error("Error occurred during file download:",i),!1):i.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class x{downloadFile(e,t){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}authToken(e){return s(this,void 0,void 0,(function*(){return new Promise((e=>{e("")}))}))}getAuthUrl(){return""}}class S{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new l(3)}retryOperation(e,t=5){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}checkFolderExists(t,r){return s(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(t,r){return s(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/createfolderifnotexists",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error creating folder:",e),!1}}))}listFiles(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:"/"+t,recursive:0}});return 0!==o.data.result?[]:o.data.metadata.contents.map((e=>e.name))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.get("https://api.pcloud.com/deletefile",{params:{access_token:r,path:"/"+t}});return 0===o.data.result||(console.error("Error deleting file:",o.data),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return s(this,void 0,void 0,(function*(){return this.config.refresh_token}))}authToken(e){return s(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"pcloud",redirect_uri:h.callbackUrl,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${h.pcloudClientId}&response_type=code&redirect_uri=${h.callbackUrl}`}}class R extends S{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),i=r.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(i,o))){if(!(yield this.createFolder(i,o)))return!1}let n=r.split("/").pop()||"",s=new File([t],n,{lastModified:(new Date).getTime(),type:t.type});const a=new FormData;a.append("file",s);const c=yield e.post("https://api.pcloud.com/uploadfile",a,{params:{access_token:o,path:`/${i}`,renew:1},maxContentLength:1/0,maxBodyLength:1/0});return 0===c.data.result||(console.error("Error uploading file:",c.data),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield e.get("https://api.pcloud.com/getfilelink",{params:{access_token:r,path:`/${t}`}});if(0!==o.data.result)return console.error("Error getting file link:",o.data),!0;const i=`https://${o.data.hosts[0]}${o.data.path}`,n=yield e.get(i,{responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0});return n.status>=300?(console.error("Error downloading file:",n),!1):n.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class O{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new l(5)}retryOperation(e,t=0){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}listFiles(e){return s(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:o,accessKeyId:i,secretAccessKey:n,dir:s}=this.config;s||(s="KoodoReader");try{return(yield this.thirdpartyRequest.s3List({bucket_name:o,prefix:s+"/"+e,region:r,endpoint:t,access_key_id:i,secret_access_key:n})).data.contents.map((e=>e.split("/").pop()))}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:o,accessKeyId:i,secretAccessKey:n,dir:s}=this.config;s||(s="KoodoReader");try{let a=yield this.thirdpartyRequest.s3Delete({bucket_name:o,object_key:s+"/"+e,region:r,endpoint:t,access_key_id:i,secret_access_key:n});return 200===a.code||(console.error("Error deleting file:",a),!1)}catch(e){return console.error("Error deleting file:",e),!1}}))}}class A extends O{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){let{endpoint:o,region:i,bucketName:n,accessKeyId:s,secretAccessKey:a,dir:c}=this.config;c||(c="KoodoReader");try{const l=(yield this.thirdpartyRequest.s3Upload({bucket_name:n,object_key:c+"/"+r,region:i,endpoint:o,access_key_id:s,secret_access_key:a})).data.url;let d=r.split("/").pop()||"",u=new File([t],d,{lastModified:(new Date).getTime(),type:t.type});const h=yield e.put(l,u,{headers:{},maxContentLength:1/0,maxBodyLength:1/0});return!(h.status>=300)||(console.error("Error occurred during file upload:",h),!1)}catch(e){return console.error("Error occurred during file upload:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){let{endpoint:r,region:o,bucketName:i,accessKeyId:n,secretAccessKey:s,dir:a}=this.config;a||(a="KoodoReader");try{const c=(yield this.thirdpartyRequest.s3Download({bucket_name:i,object_key:a+"/"+t,region:o,endpoint:r,access_key_id:n,secret_access_key:s})).data.url;return(yield e({url:c,method:"get",headers:{},responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0})).data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class F{constructor(e){let{username:t,password:r,url:n,dir:s}=e;s||(s="KoodoReader"),this.client=o(n,{authType:i.Password,username:t,password:r}),this.username=t,this.password=r,this.dir=s,this.taskQueue=new l(5)}retryOperation(e,t=0){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const o=yield e();if(o)return o;if(r>=t)return o;r++;const i=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${i}ms`),yield new Promise((e=>setTimeout(e,i)))}}))}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{!1===(yield this.client.exists(this.dir+"/"+r.substring(0,r.lastIndexOf("/"))))&&(yield this.client.createDirectory(this.dir+"/"+r.substring(0,r.lastIndexOf("/"))));let o=r.split("/").pop()||"",i=new File([t],o,{lastModified:(new Date).getTime(),type:t.type}),n=this.client.getFileUploadLink(this.dir+"/"+r);const s=new URL(n);s.search="",n=s.toString();const a=btoa(this.username+":"+this.password),c=yield e.put(n,i,{headers:{Authorization:"Basic "+a},maxContentLength:1/0,maxBodyLength:1/0});return!(c.status>=300)||(console.error("Error occurred during file upload:",c),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(t){return s(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>s(this,void 0,void 0,(function*(){try{const r=this.client.getFileDownloadLink(this.dir+"/"+t),o=btoa(this.username+":"+this.password),i=yield e({url:r,method:"get",headers:{Authorization:"Basic "+o},responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0});return i.status>=300?(console.error("Error occurred during file download:",i),!1):i.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return s(this,void 0,void 0,(function*(){try{return(yield this.client.getDirectoryContents(this.dir+"/"+e)).map((e=>e.basename))}catch(t){return t.response&&404===t.response.status&&(yield this.client.createDirectory(this.dir+"/"+e)),console.error("Error listing files:",t),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){try{return yield this.client.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}}const I=["book","config","cover","font"];class L{constructor(e,t,r){this.type=e,this.remote="dropbox"===e?new k(t,r):"microsoft"===e?new _(t,r):"google"===e?new w(t,r):"s3compatible"===e?new A(t,r):"webdav"===e?new F(t):"boxnet"===e?new m(t,r):"mega"===e?new E(t):"adrive"===e?new y(t,r):"pcloud"===e?new R(t,r):new x}downloadFile(e,t){return s(this,void 0,void 0,(function*(){return!!(yield this.listFiles(t)).find((t=>e.indexOf(t)>-1))&&(yield this.remote.downloadFile(t+"/"+e))}))}uploadFile(e,t,r){return s(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(r,t+"/"+e)}))}deleteFile(e,t){return s(this,void 0,void 0,(function*(){return yield this.remote.deleteFile(t+"/"+e)}))}listFiles(e){return s(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}isExist(e,t){return s(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}downloadAllFiles(){return s(this,void 0,void 0,(function*(){for(let e of I){let t=yield this.listFiles(e);for(let r of t)yield this.downloadFile(r,e)}}))}authToken(e){return s(this,void 0,void 0,(function*(){return yield this.remote.authToken(e)}))}getAuthUrl(){return this.remote.getAuthUrl?this.remote.getAuthUrl():""}getStats(){return this.remote.taskQueue.getStats()}resetCounters(){this.remote.taskQueue.resetCounters()}}const M={notes:"SELECT * FROM notes WHERE key = ?",bookmarks:"SELECT * FROM bookmarks WHERE key = ?",books:"SELECT * FROM books WHERE key = ?",plugins:"SELECT * FROM plugins WHERE key = ?",words:"SELECT * FROM words WHERE key = ?"},j={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},B={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function P(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const z={notes:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),t.tag=JSON.parse(e.tag),t},bookmarks:e=>e,books:e=>e,plugins:e=>{let t=Object.assign({},e);return e.autoValue||delete t.autoValue,e.langList?t.langList=JSON.parse(e.langList):delete t.langList,e.voiceList?t.voiceList=JSON.parse(e.voiceList):delete t.voiceList,t.config=JSON.parse(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),t}};var D,$={sqlStatement:{createTableStatement:P({notes:'\n CREATE TABLE IF NOT EXISTS "notes" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "chapter" text,\n "chapterIndex" integer,\n "text" text,\n "cfi" text,\n "range" text,\n "notes" text,\n "percentage" text,\n "color" integer,\n "tag" array\n )\n ',bookmarks:'\n CREATE TABLE IF NOT EXISTS "bookmarks" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "cfi" text,\n "label" text,\n "percentage" text,\n "chapter" text\n );\n ',books:'\n CREATE TABLE IF NOT EXISTS "books" (\n "key" text PRIMARY KEY,\n "name" text,\n "author" text,\n "description" text,\n "md5" text,\n "cover" text,\n "format" text,\n "publisher" text,\n "size" integer,\n "page" integer,\n "path" text,\n "charset" text\n );\n ',plugins:'\n CREATE TABLE IF NOT EXISTS "plugins" (\n "key" text PRIMARY KEY,\n "type" text,\n "displayName" text,\n "icon" text,\n "version" text,\n "config" object,\n "autoValue" string,\n "langList" text,\n "voiceList" text,\n "scriptSHA256" text,\n "script" text\n );\n ',words:'\n CREATE TABLE IF NOT EXISTS "words" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "word" text,\n "chapter" text\n );\n '}),getAllStatement:P({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:P({notes:"INSERT OR REPLACE INTO notes (key, bookKey, chapter, chapterIndex, text, cfi, range, notes, date, percentage, color, tag) VALUES (@key, @bookKey, @chapter, @chapterIndex, @text, @cfi, @range, @notes, @date, @percentage, @color, @tag)",bookmarks:"INSERT OR REPLACE INTO bookmarks (key, bookKey, cfi, label, percentage, chapter) VALUES (@key, @bookKey, @cfi, @label, @percentage, @chapter)",books:"INSERT OR REPLACE INTO books (key, name, author, description, md5, cover, format, publisher, size, page, path, charset) VALUES (@key, @name, @author, @description, @md5, @cover, @format, @publisher, @size, @page, @path, @charset)",plugins:"INSERT OR REPLACE INTO plugins (key, type, displayName, icon, version, config, autoValue, langList, voiceList, scriptSHA256, script) VALUES (@key, @type, @displayName, @icon, @version, @config, @autoValue, @langList, @voiceList, @scriptSHA256, @script)",words:"INSERT OR REPLACE INTO words (key, bookKey, date, word, chapter) VALUES (@key, @bookKey, @date, @word, @chapter)"}),deleteAllStatement:P({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:P({notes:"UPDATE notes SET bookKey = @bookKey, chapter = @chapter, chapterIndex = @chapterIndex, text = @text, cfi = @cfi, range = @range, notes = @notes, date = @date, percentage = @percentage, color = @color, tag = @tag WHERE key = @key",bookmarks:"UPDATE bookmarks SET bookKey = @bookKey, cfi = @cfi, label = @label, percentage = @percentage, chapter = @chapter WHERE key = @key",books:"UPDATE books SET name = @name, author = @author, description = @description, md5 = @md5, cover = @cover, format = @format, publisher = @publisher, size = @size, page = @page, path = @path, charset = @charset WHERE key = @key",plugins:"UPDATE plugins SET type = @type, displayName = @displayName, icon = @icon, version = @version, config = @config, autoValue = @autoValue, langList = @langList, voiceList = @voiceList, scriptSHA256 = @scriptSHA256, script = @script WHERE key = @key",words:"UPDATE words SET bookKey = @bookKey, date = @date, word = @word, chapter = @chapter WHERE key = @key"}),deleteStatement:P({notes:"DELETE FROM notes WHERE key = ?",bookmarks:"DELETE FROM bookmarks WHERE key = ?",books:"DELETE FROM books WHERE key = ?",plugins:"DELETE FROM plugins WHERE key = ?",words:"DELETE FROM words WHERE key = ?"}),dropStatement:P({notes:"DROP TABLE IF EXISTS notes",bookmarks:"DROP TABLE IF EXISTS bookmarks",books:"DROP TABLE IF EXISTS books",plugins:"DROP TABLE IF EXISTS plugins",words:"DROP TABLE IF EXISTS words"}),getStatement:P(M),getByBookKeyStatement:P(j),getByBookKeysStatement:P({notes:e=>`SELECT * FROM notes WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,bookmarks:e=>`SELECT * FROM bookmarks WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,words:e=>`SELECT * FROM words WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")})`}),deleteByBookKeyStatement:P(B)},jsonToSqlite:P({notes:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),t.tag=JSON.stringify(e.tag),t},bookmarks:e=>e,books:e=>{let t=Object.assign({},e);return t.page=e.page||0,t},plugins:e=>{let t=Object.assign({},e);return e.autoValue||(t.autoValue=null),e.langList?t.langList=JSON.stringify(e.langList):t.langList=null,e.voiceList?t.voiceList=JSON.stringify(e.voiceList):t.voiceList=null,t.config=JSON.stringify(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),t}}),sqliteToJson:P(z)};class N{constructor(e,t,r,o,i,n,s,a,c,l,d,u){this.key=e,this.name=t,this.author=r,this.description=o,this.md5=i,this.cover=n,this.format=s,this.publisher=a,this.size=c,this.page=l,this.path=d,this.charset=u}}class q{static generateBook(e,t,r,o,i,n,a){return new Promise(((c,l)=>s(this,void 0,void 0,(function*(){try{let s,l,d,u,h,p,f,y,g="";switch([l,d,h,u,p,f]=[e,"","","","",0],t){case"pdf":case"epub":case"mobi":case"azw":case"azw3":case"fb2":y=yield a.getMetadata(),[l,d,h,u,g]=[y.name||e,y.author||"",y.description||"",y.publisher||"",y.cover||""];break;case"cbr":case"cbt":case"cbz":case"cb7":y=yield a.getMetadata(),g=y.cover;break;case"txt":y=yield a.getMetadata(n),p=y.charset}let m=t.toUpperCase();s=(new Date).getTime()+"",c(new N(s,l,d,h,r,g,m,u,o,f,i,p))}catch(e){console.error(e),l(e)}}))))}}D=q,q.getRendtion=(e,t,r,o,i,n,s,a,c,l)=>{let d;var u,h;return"CACHE"===t?d=new l.CacheRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"MOBI"===t||"AZW3"===t||"AZW"===t?d=new l.MobiRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"EPUB"===t?d=new l.EpubRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"TXT"===t?d=new l.TxtRender(e,{readerMode:r,animation:i,charset:o,convertChinese:n,parserRegex:s,isDarkMode:a,isMobile:c}):"MD"===t?d=new l.MdRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"PDF"===t?d=new l.PdfRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"FB2"===t?d=new l.Fb2Render(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"DOCX"===t?d=new l.DocxRender(e,{readerMode:r,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"HTML"===t||"XHTML"===t||"MHTML"===t||"HTM"===t||"XML"===t?d=new l.HtmlRender(e,{readerMode:r,format:t,animation:i,convertChinese:n,isDarkMode:a,isMobile:c}):"CBR"!==t&&"CBT"!==t&&"CBZ"!==t&&"CB7"!==t||(d=new l.ComicRender((u=e,h=new ArrayBuffer(u.byteLength),new Uint8Array(h).set(new Uint8Array(u)),h),{readerMode:r,format:t,animation:i,convertChinese:n,isDarkMode:a,isMobile:c})),d},q.initMobileBook=(e,t,r,o,i,n,a,c)=>s(void 0,void 0,void 0,(function*(){try{const s=yield fetch(e);if(!s.ok)throw new Error(`Failed to download book: ${s.status} ${s.statusText}`);const l=yield s.arrayBuffer();window.ReactNativeWebView.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=l;let d=D.getRendtion(l,t,r,o,i,n,a,c,"yes",window.Kookit);window.rendition=d;let u=document.getElementById("page-area");yield window.rendition.renderTo(u),window.rendition.on("rendered",(()=>{let e=window.rendition.getPosition();window.ReactNativeWebView.postMessage(JSON.stringify({event:"content-loaded",bookLocation:e})),window.rendition.tsTransform()})),window.rendition.on("page-changed",(()=>{let e=window.rendition.getPosition();window.ReactNativeWebView.postMessage(JSON.stringify({event:"page-changed",bookLocation:e}))})),window.ReactNativeWebView.postMessage(JSON.stringify({event:"book-inited",chapterList:window.rendition.getChapter()}))}catch(e){window.ReactNativeWebView.postMessage(JSON.stringify({event:"error",message:"Parse book failed"}))}})),q.addMobileBook=(e,t,r,o,i,n,a="")=>s(void 0,void 0,void 0,(function*(){var s;try{const c=yield fetch(e);if(!c.ok)throw new Error(`Failed to download book: ${c.status} ${c.statusText}`);const l=yield c.arrayBuffer();null===(s=window.ReactNativeWebView)||void 0===s||s.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=l;let d=D.getRendtion(l,r.toUpperCase(),"","","","no",a,"no","yes",window.Kookit);window.rendition=d;let u=yield q.generateBook(t,r,o,i,n,l,d);if(!u||!u.key)return;window.ReactNativeWebView.postMessage(JSON.stringify({event:"metadata",bookInfo:u}))}catch(e){window.ReactNativeWebView.postMessage(JSON.stringify({event:"error",message:"Parse book failed"}))}})),q.precacheMobileBook=(e,t)=>s(void 0,void 0,void 0,(function*(){let r=yield window.rendition.preCache(window.file_content);if(""===r)window.ReactNativeWebView.postMessage(JSON.stringify({event:"cache",cacheBase64:"",key:t}));else if("err"!==r){try{const o=`${e}/dav/${"cache-"+t+".zip"}`,i=yield fetch(o,{method:"PUT",headers:{"Content-Type":"application/octet-stream",Overwrite:"T"},body:r});if(!i.ok)throw new Error(`上传失败: ${i.status}`);console.info("文件上传成功")}catch(e){console.error("操作失败:"+e)}window.ReactNativeWebView.postMessage(JSON.stringify({event:"cache",key:t}))}else window.ReactNativeWebView.postMessage(JSON.stringify({event:"error",message:"Parse book failed"}));window.file_content=null,window.rendition=null}));const U=u.devUrl;class W{constructor(e,t){this.processingQueue=!1,this.requestQueue=[],this.TokenService=e,this.ConfigService=t,this.refreshToken="",this.accessToken="",this.streamPromise=null}refreshUserToken(){return s(this,void 0,void 0,(function*(){if(this.refreshToken=yield this.TokenService.getToken("refresh_token"),!this.refreshToken)return{code:401,message:"refresh token not found"};let t=(yield e.post(U+"/api/v1/public/user/refresh_token",{refresh_token:this.refreshToken})).data;return 200===t.code&&(yield this.TokenService.setToken("access_token",t.data.access_token),yield this.TokenService.setToken("refresh_token",t.data.refresh_token),this.accessToken=t.data.access_token,this.refreshToken=t.data.refresh_token),t}))}requestWithRetry(e){return s(this,void 0,void 0,(function*(){return this.requestQueue||(this.requestQueue=[]),new Promise(((t,r)=>{this.requestQueue.push({config:e,resolve:t,reject:r}),this.processingQueue||this.processQueue()}))}))}processQueue(){return s(this,void 0,void 0,(function*(){if(!this.processingQueue){this.processingQueue=!0;try{for(;this.requestQueue.length>0;){const e=this.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{this.processingQueue=!1}}}))}executeRequest(t){return s(this,void 0,void 0,(function*(){try{try{this.accessToken=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let r="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);t.baseURL=U,t.headers?(t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=r):t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":r};let o=(yield e(t)).data;if(402===o.code){let r=yield this.refreshUserToken();if(200===r.code){return t.headers=t.headers||{},t.headers.Authorization="Bearer "+this.accessToken,(yield e(t)).data}return r}return 200!==o.code&&this.ConfigService.setItem("errorLog",JSON.stringify({request:t.data,url:t.url,result:o,requestID:r})),o}catch(e){throw console.error("Request execution error:",e),e}}))}requestWithStream(e,t,r){return s(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>s(this,void 0,void 0,(function*(){try{let o="";try{o=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((n,a)=>{const c=new r(U+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+o,"X-Request-ID":i},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});c.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),c.addEventListener("message",(e=>s(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);r.done?(c.close(),n(r)):(402===r.code&&(yield this.refreshUserToken()),t(r.data))})))),c.addEventListener("error",(e=>{console.error("Error:",e),n({code:500,message:"internal error"}),c.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return s(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>s(this,void 0,void 0,(function*(){try{let r="";try{r=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((i,n)=>s(this,void 0,void 0,(function*(){const n=yield fetch(U+e.url,{method:"POST",headers:{"Content-Type":"text/event-stream",Authorization:"Bearer "+r,"X-Request-ID":o},body:JSON.stringify(e.data)});if(!n.body)throw new Error("Response body is null");const s=n.body.pipeThrough(new TextDecoderStream).getReader();for(;;){const{value:e,done:r}=yield s.read();if(r){t({done:!0});break}if(e)if(e.includes('"code":400')||e.includes('"code":401')||e.includes('"code":402')){let t=JSON.parse(e);402===t.code&&(yield this.refreshUserToken()),i(t)}else e.split("\n").forEach((e=>{if(e.startsWith("data:")){const r=JSON.parse(e.substring(5));t(r.data)}}))}}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}class K extends W{constructor(e,t){super(e,t)}getTransStream(e,t,r){return s(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_trans_stream",data:e};return yield this.requestWithStream(o,t,r)}))}getTransFetch(e,t){return s(this,void 0,void 0,(function*(){const r={method:"post",url:"/api/v1/pro/reader/get_llm_trans_stream",data:e};return yield this.requestWithFetch(r,t)}))}getDictionary(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_llm_dict",data:e};return yield this.requestWithRetry(t)}))}getSummaryStream(e,t,r){return s(this,void 0,void 0,(function*(){const o={method:"post",url:"/api/v1/pro/reader/get_llm_sum_stream",data:e};return yield this.requestWithStream(o,t,r)}))}getSummaryFetch(e,t){return s(this,void 0,void 0,(function*(){const r={method:"post",url:"/api/v1/pro/reader/get_llm_sum_stream",data:e};return yield this.requestWithFetch(r,t)}))}getGoogleFont(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/reader/get_google_font",data:e};return yield this.requestWithRetry(t)}))}sendToKindle(e){return s(this,void 0,void 0,(function*(){let t=new FormData;t.append("file",e.file),t.append("email",e.email),t.append("file_name",e.fileName);const r={method:"post",url:"/api/v1/pro/reader/send_to_kindle",headers:{"Content-Type":"multipart/form-data"},data:t};return yield this.requestWithRetry(r)}))}}class Q extends W{constructor(e,t){super(e,t)}encryptToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/encrypt_token",data:e};return yield this.requestWithRetry(t)}))}decryptToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};return yield this.requestWithRetry(t)}))}authThirdToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/auth_token",data:e};return yield this.requestWithRetry(t)}))}refreshThirdToken(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/refresh_token",data:e};return yield this.requestWithRetry(t)}))}s3Upload(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_upload",data:e};return yield this.executeRequest(t)}))}s3Download(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_download",data:e};return yield this.executeRequest(t)}))}s3List(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_list",data:e};return yield this.executeRequest(t)}))}s3Delete(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_delete",data:e};return yield this.executeRequest(t)}))}getSyncState(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/pro/thirdparty/get_sync_state"})}))}deleteSyncState(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/pro/thirdparty/delete_sync_state"})}))}}class J extends W{constructor(e,t){super(e,t)}loginRegister(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/public/user/login_register",data:e};return yield this.requestWithRetry(t)}))}logout(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/logout"})}))}getLogins(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/get_logins"})}))}addLogin(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/add_login",data:e};return yield this.requestWithRetry(t)}))}removeLogin(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/remove_login",data:e};return yield this.requestWithRetry(t)}))}getUserInfo(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/member/user/get_info"})}))}getTempToken(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/member/user/get_temp_token"})}))}sendEmailCode(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/public/user/send_email_code",data:e};return yield this.requestWithRetry(t)}))}checkEmailRegistration(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/public/user/check_email_registration",data:e};return yield this.requestWithRetry(t)}))}redeemCode(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/redeem_code",data:e};return yield this.requestWithRetry(t)}))}}var H={getAuthUrl:(e,t)=>{let r="";if("github"===e?r=`https://github.com/login/oauth/authorize?client_id=${h.githubClientId}&redirect_uri=${h.callbackUrl}&scope=openid`:"google"===e?r=`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${h.callbackUrl}&prompt=consent&response_type=code&client_id=${h.googleClientId}&scope=openid&access_type=offline`:"facebook"===e?r=`https://www.facebook.com/v12.0/dialog/oauth?client_id=${h.facebookClientId}&redirect_uri=${h.callbackUrl}&scope=&response_type=code`:"microsoft"===e&&(r=`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${h.microsoftClientId}&scope=openid profile User.Read offline_access&response_type=code&redirect_uri=${h.callbackUrl}`),"manual"===t)return r;let o=JSON.stringify({deeplink:"desktop"===t?"koodo-reader://callback":"browser"===t?"https://web.koodoreader.com/#/login":"",service:e});return`${r}&state=${"state|"+encodeURIComponent(o)}`}};class V{static CompareDatabase(e,t,r){return s(this,void 0,void 0,(function*(){let o=Object.keys(e).filter((e=>e.startsWith("database.sqlite.books"))),i=Object.keys(e).filter((e=>e.startsWith("database.sqlite.notes"))),n=Object.keys(e).filter((e=>e.startsWith("database.sqlite.bookmarks"))),s=Object.keys(e).filter((e=>e.startsWith("database.sqlite.plugins"))),a=Object.keys(e).filter((e=>e.startsWith("database.sqlite.words"))),c=Object.keys(t).filter((e=>e.startsWith("database.sqlite.books"))),l=Object.keys(t).filter((e=>e.startsWith("database.sqlite.notes"))),d=Object.keys(t).filter((e=>e.startsWith("database.sqlite.bookmarks"))),u=Object.keys(t).filter((e=>e.startsWith("database.sqlite.plugins"))),h=Object.keys(t).filter((e=>e.startsWith("database.sqlite.words"))),p={books:Array.from(new Set(o.concat(c))),notes:Array.from(new Set(i.concat(l))),bookmarks:Array.from(new Set(n.concat(d))),plugins:Array.from(new Set(s.concat(u))),words:Array.from(new Set(a.concat(h)))},f={books:{save:[],update:[],delete:[],conflict:[],upload:[]},notes:{save:[],update:[],delete:[],conflict:[],upload:[]},bookmarks:{save:[],update:[],delete:[],conflict:[],upload:[]},plugins:{save:[],update:[],delete:[],conflict:[],upload:[]},words:{save:[],update:[],delete:[],conflict:[],upload:[]}},y=["books","notes","bookmarks","plugins","words"];for(let o of y)for(let i of p[o]){let n=i.split(".")[3],s=e[i],a=t[i];s?a?("save"===a.operation&&("update"===s.operation||"delete"===s.operation?f[o].upload.push(n):console.info("ignore",a)),"delete"===a.operation&&("save"===s.operation&&(f[o].delete.push(n),e[i]=a),"update"===s.operation&&(s.timea.time?(f[o].conflict.push(n),"cloud"===r?(f[o].delete.push(n),e[i]=a):f[o].upload.push(n)):console.info("ignore",a)),"delete"===s.operation&&console.info("ignore",a)),"update"===a.operation&&("save"===s.operation&&(f[o].update.push(n),e[i]=a),"update"===s.operation&&(s.timea.time?f[o].upload.push(n):console.info("ignore",a)),"delete"===s.operation&&(s.timea.time?f[o].upload.push(n):console.info("ignore",a)))):f[o].upload.push(n):(f[o].save.push(n),e[i]=a)}return{compareResult:f,syncRecords:e}}))}static CompareConfig(e,t,r){return s(this,void 0,void 0,(function*(){let o=Object.keys(e).filter((e=>e.startsWith("config.readerConfig"))),i=Object.keys(e).filter((e=>e.startsWith("config.listConfig"))),n=Object.keys(e).filter((e=>e.startsWith("config.objectConfig"))),s=Object.keys(e).filter((e=>e.startsWith("config.mapConfig"))),a=Object.keys(t).filter((e=>e.startsWith("config.readerConfig"))),c=Object.keys(t).filter((e=>e.startsWith("config.listConfig"))),l=Object.keys(t).filter((e=>e.startsWith("config.objectConfig"))),d=Object.keys(t).filter((e=>e.startsWith("config.mapConfig"))),u={readerConfig:Array.from(new Set(o.concat(a))),listConfig:Array.from(new Set(i.concat(c))),objectConfig:Array.from(new Set(n.concat(l))),mapConfig:Array.from(new Set(s.concat(d)))},h={readerConfig:{update:[],upload:[]},listConfig:{update:[],upload:[]},objectConfig:{update:[],delete:[],conflict:[],upload:[]},mapConfig:{update:[],delete:[],conflict:[],upload:[]}},p=["readerConfig","listConfig"];for(let r of p)for(let o of u[r]){let i=o,n=e[o],s=t[o];n?s?n.times.time?h[r].upload.push(i):console.info("ignore",s):h[r].upload.push(i):(h[r].update.push(i),e[o]=s)}let f=["objectConfig","mapConfig"];for(let o of f)for(let i of u[o]){let n=i,s=e[i],a=t[i];s?a?("delete"===a.operation&&("update"===s.operation&&(s.timea.time?(h[o].conflict.push(n),"cloud"===r?(h[o].delete.push(n),e[i]=a):h[o].upload.push(n)):console.info("ignore",a)),"delete"===s.operation&&console.info("ignore",a)),"update"===a.operation&&("update"===s.operation&&(s.timea.time?h[o].upload.push(n):console.info("ignore",a)),"delete"===s.operation&&(s.timea.time?h[o].upload.push(n):console.info("ignore",a)))):h[o].upload.push(n):(h[o].update.push(n),e[i]=a)}return{compareResult:h,syncRecords:e}}))}static compareAll(e,t,r,o,i){return s(this,void 0,void 0,(function*(){let n="cloud";if("yes"===r.getReaderConfig("isKeepLocal")){n="local";let e=r.getObjectConfig(yield o.getFingerprint(),"cloudSyncTime",{time:0,conflictMode:"cloud"}),t=yield i.getCloudConfig("config"),s=JSON.parse(t.cloudSyncTime||"{}");delete s[yield o.getFingerprint()],Object.values(s).filter((t=>"local"===t.conflictMode&&t.time>e.time)).length>0&&(n="cloud")}let{compareResult:s,syncRecords:a}=yield this.CompareDatabase(e,t,n),{compareResult:c,syncRecords:l}=yield this.CompareConfig(a,t,n),d=Object.assign(Object.assign({},s),c);return r.setAllSyncRecord(l),"local"===n&&(d.books.conflict.length>0||d.notes.conflict.length>0||d.bookmarks.conflict.length>0||d.plugins.conflict.length>0||d.words.conflict.length>0||d.objectConfig.conflict.length>0||d.mapConfig.conflict.length>0)?r.setObjectConfig(yield o.getFingerprint(),{time:(new Date).getTime(),conflictMode:"local"},"cloudSyncTime"):r.setObjectConfig(yield o.getFingerprint(),{time:(new Date).getTime(),conflictMode:"cloud"},"cloudSyncTime"),d}))}static startSync(e,t,r,o,i,n){return s(this,void 0,void 0,(function*(){return[...yield this.syncConfig(e,t,r,i,o),...yield this.syncCover(t,n,i),...yield this.syncBook(t,i)]}))}static syncConfig(e,t,r,o,i){return s(this,void 0,void 0,(function*(){let n=[];for(let t of c){if(e[t].save.length+e[t].update.length>0){let o=yield i.getCloudDatabase(t);for(let i of e[t].save){let e=o.find((e=>e.key===i));e&&(yield r.saveRecord(e,t))}for(let i of e[t].update){let e=o.find((e=>e.key===i));e&&(yield r.updateRecord(e,t,!1))}}if(e[t].delete.length>0)for(let i of e[t].delete)yield r.deleteRecord(i,t),"books"===t&&(yield o.deleteOfflineBook(i))}if(e.readerConfig.update.length>0||e.listConfig.update.length>0||e.objectConfig.update.length>0||e.mapConfig.update.length>0){let r=yield i.getCloudConfig("config");for(let o of e.readerConfig.update){let e=o.split(".")[3];r.readerConfig&&t.setReaderConfig(e,JSON.parse(r.readerConfig)[e],!1)}for(let o of e.listConfig.update){let e=o.split(".")[3];r[e]&&t.setAllListConfig(JSON.parse(r[e]),e,!1)}for(let o of e.objectConfig.update){let e=o.split(".")[3],i=o.split(".")[2];r[i]&&JSON.parse(r[i])&&JSON.parse(r[i])[e]&&t.setObjectConfig(e,JSON.parse(r[i])[e],i,!1)}for(let o of e.mapConfig.update){let e=o.split(".")[3],i=o.split(".")[2];if(r[i]&&JSON.parse(r[i])&&JSON.parse(r[i])[e]){let o=JSON.parse(r[i])[e];t.setOneMapConfig(e,o,i,!1)}}}if(e.objectConfig.delete.length>0||e.mapConfig.delete.length>0){for(let r of e.objectConfig.delete){let e=r.split(".")[3],o=r.split(".")[2];t.deleteObjectConfig(e,o)}for(let r of e.mapConfig.delete){let e=r.split(".")[3],o=r.split(".")[2];t.deleteMapConfig(e,o)}}for(let t of c)e[t].upload.length>0&&n.push((()=>i.uploadDatabase(t)));return n.push((()=>i.uploadConfig("config"))),n.push((()=>i.uploadConfig("sync"))),n}))}static syncCover(e,t,r){return s(this,void 0,void 0,(function*(){let r=yield t.getLocalCoverList(),o=yield t.getCloudCoverList(),i=Array.from(new Set([...r,...o])),n=[];for(let s of i)r.includes(s)&&!o.includes(s)&&n.push((()=>t.uploadCover(s))),!r.includes(s)&&o.includes(s)&&"adrive"!==e.getItem("defaultSyncOption")&&n.push((()=>t.downloadCover(s)));return n}))}static syncBook(e,t){return s(this,void 0,void 0,(function*(){let r=yield t.getLocalBookList(),o=yield t.getCloudBookList(),i=[],n=Array.from(new Set([...r,...o]));for(let s of n){if(s.startsWith("cache"))continue;if(r.includes(s)&&!o.includes(s)){let e=s.split(".")[0],r=s.split(".")[1];i.push((()=>t.uploadBook(e,r)))}let n="yes"===e.getReaderConfig("autoOffline");if(!r.includes(s)&&o.includes(s)&&n&&"adrive"!==e.getItem("defaultSyncOption")){let e=s.split(".")[0],r=s.split(".")[1];i.push((()=>t.offlineBook(e,r.toUpperCase())))}}return i}))}static runTasksWithLimit(e,t,r){return s(this,void 0,void 0,(function*(){if("ftp"!==r&&"adrive"!==r){const r=[],o=[];for(const i of e){const e=i().then((t=>(o.splice(o.indexOf(e),1),t)));r.push(e),o.push(e),o.length>=t&&(yield Promise.race(o))}return Promise.all(r)}for(let t of e)yield t()}))}}const X=(Y=class{static getItem(e){return localStorage.getItem(e)}static setItem(e,t){localStorage.setItem(e,t)}static removeItem(e){localStorage.removeItem(e)}},G="browser",class extends Y{static getReaderConfig(e){return JSON.parse(this.getItem("readerConfig")||"{}")[e]}static setReaderConfig(e,t,r=!0){let o=JSON.parse(this.getItem("readerConfig")||"{}");o[e]=t,this.setItem("readerConfig",JSON.stringify(o)),r&&this.setSyncRecord({type:"config",catergory:"readerConfig",name:G,key:e},{operation:"update",time:Date.now()})}static getAllListConfig(e){return("{}"!==this.getItem(e)&&this.getItem(e)?JSON.parse(this.getItem(e)||""):[])||[]}static deleteListConfig(e,t){let r=this.getAllListConfig(t);const o=r.indexOf(e);o>-1&&r.splice(o,1),this.setAllListConfig(r,t)}static setListConfig(e,t){let r=this.getAllListConfig(t);const o=r.indexOf(e);o>-1?(r.splice(o,1),r.unshift(e)):r.unshift(e),this.setAllListConfig(r,t)}static setAllListConfig(e,t,r=!0){this.setItem(t,JSON.stringify(e)),r&&this.setSyncRecord({type:"config",catergory:"listConfig",name:"general",key:t},{operation:"update",time:Date.now()})}static setObjectConfig(e,t,r,o=!0){let i=this.getAllObjectConfig(r);i[e]=t,o&&this.setSyncRecord({type:"config",catergory:"objectConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllObjectConfig(i,r)}static getObjectConfig(e,t,r){return this.getAllObjectConfig(t)[e]||r}static getAllObjectConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static setAllObjectConfig(e,t){this.setItem(t,JSON.stringify(e))}static deleteObjectConfig(e,t){let r=this.getAllObjectConfig(t);delete r[e],this.setSyncRecord({type:"config",catergory:"objectConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllObjectConfig(r,t)}static getAllMapConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static getMapConfig(e,t){return this.getAllMapConfig(t)[e]||[]}static setAllMapConfig(e,t){this.setItem(t,JSON.stringify(e))}static setMapConfig(e,t,r){let o=this.getAllMapConfig(r);void 0===o[e]&&(o[e]=[]),t&&-1===o[e].indexOf(t)&&o[e].unshift(t),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,r)}static setOneMapConfig(e,t,r,o=!0){let i=this.getAllMapConfig(r);i[e]=t,o&&this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(i,r)}static deleteFromMapConfig(e,t,r){let o=this.getAllMapConfig(r),i=o[e].indexOf(t);o[e].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,r)}static deleteFromAllMapConfig(e,t){let r=this.getAllMapConfig(t);Object.keys(r).forEach((o=>{let i=r[o].indexOf(e);i>-1&&(r[o].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:o},{operation:"update",time:Date.now()}))})),this.setAllMapConfig(r,t)}static deleteMapConfig(e,t){let r=this.getAllMapConfig(t);delete r[e],this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllMapConfig(r,t)}static getFromAllMapConfig(e,t){let r=this.getAllMapConfig(t),o=[];for(let t in r)r[t]&&r[t].indexOf(e)>-1&&o.push(t);return o}static getSyncRecord(e){return JSON.parse(this.getItem("syncRecord")||"{}")[e.type+"."+e.catergory+"."+e.name+"."+e.key]||{operation:"",time:0}}static getAllSyncRecord(){return JSON.parse(this.getItem("syncRecord")||"{}")}static setSyncRecord(e,t){let r=JSON.parse(this.getItem("syncRecord")||"{}");r[e.type+"."+e.catergory+"."+e.name+"."+e.key]=t,this.setItem("syncRecord",JSON.stringify(r))}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}});var Y,G;let Z;const ee=new Uint8Array(16);function te(){if(!Z&&(Z="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Z))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Z(ee)}const re=[];for(let e=0;e<256;++e)re.push((e+256).toString(16).slice(1));var oe={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ie(e,t,r){if(oe.randomUUID&&!t&&!e)return oe.randomUUID();const o=(e=e||{}).random||(e.rng||te)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=o[e];return t}return function(e,t=0){return re[e[t+0]]+re[e[t+1]]+re[e[t+2]]+re[e[t+3]]+"-"+re[e[t+4]]+re[e[t+5]]+"-"+re[e[t+6]]+re[e[t+7]]+"-"+re[e[t+8]]+re[e[t+9]]+"-"+re[e[t+10]]+re[e[t+11]]+re[e[t+12]]+re[e[t+13]]+re[e[t+14]]+re[e[t+15]]}(o)}class ne{static saveAllToken(e){return s(this,void 0,void 0,(function*(){if(e)if(n){const{ipcRenderer:t}=window.require("electron");t.invoke("encrypt-data",{token:e})}else{const t=yield this.encryptString(e);localStorage.setItem("encryptedToken",t)}}))}static getAllToken(){return s(this,void 0,void 0,(function*(){if(n){const{ipcRenderer:e}=window.require("electron");return yield e.invoke("decrypt-data")}{let e=localStorage.getItem("encryptedToken")||"";return e?yield this.decryptString(e):null}}))}static setToken(e,t){return s(this,void 0,void 0,(function*(){const r=JSON.parse((yield this.getAllToken())||"{}");r[e]=t,yield this.saveAllToken(JSON.stringify(r))}))}static getToken(e){return s(this,void 0,void 0,(function*(){return JSON.parse((yield this.getAllToken())||"{}")[e]||null}))}static deleteToken(e){return s(this,void 0,void 0,(function*(){const t=JSON.parse((yield this.getAllToken())||"{}");delete t[e],yield this.saveAllToken(JSON.stringify(t))}))}static encryptString(e){return s(this,void 0,void 0,(function*(){try{let t=yield this.getFingerprint();const r=yield ce(t),o=yield function(e,t,r={alg:"HS256",typ:"JWT"}){return s(this,void 0,void 0,(function*(){const o=se((new TextEncoder).encode(JSON.stringify(r))),i=se((new TextEncoder).encode(JSON.stringify(e))),n=(new TextEncoder).encode(`${o}.${i}`),s=yield crypto.subtle.importKey("raw",(new TextEncoder).encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return`${o}.${i}.${se(yield crypto.subtle.sign("HMAC",s,n))}`}))}(e,r);return o}catch(e){return console.error("Error generating secret:",e),""}}))}static decryptString(e){return s(this,void 0,void 0,(function*(){try{let t=yield this.getFingerprint();const r=yield ce(t),o=yield function(e,t){return s(this,void 0,void 0,(function*(){const[r,o,i]=e.split("."),n=(new TextEncoder).encode(`${r}.${o}`),s=yield ae(i),a=yield crypto.subtle.importKey("raw",(new TextEncoder).encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["verify"]);if(!(yield crypto.subtle.verify("HMAC",a,s,n)))throw new Error("Invalid signature");return JSON.parse((new TextDecoder).decode(ae(o)))}))}(e,r);return o}catch(e){return console.error("Error generating secret:",e),""}}))}static oldDecryptString(e){return s(this,void 0,void 0,(function*(){let t=yield this.getFingerprint();const r=yield crypto.subtle.digest("SHA-256",(new TextEncoder).encode(t)),o=yield crypto.subtle.importKey("raw",r,{name:"AES-GCM",length:256},!1,["decrypt"]),i=new Uint8Array(e.split("").map((e=>e.charCodeAt(0)))),n=i.slice(0,12),s=i.slice(12),a=yield crypto.subtle.decrypt({name:"AES-GCM",iv:n},o,s);return(new TextDecoder).decode(a)}))}static getFingerprint(){return s(this,void 0,void 0,(function*(){if(n){const{ipcRenderer:e}=window.require("electron");return yield e.invoke("get-mac")}{let e=X.getItem("fingerPrint");if(e)return e;let t=ie().replace(/-/g,"");return X.setItem("fingerPrint",t),t}}))}}function se(e){return btoa(String.fromCharCode.apply(null,Array.from(new Uint8Array(e)))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ae(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),o=new Uint8Array(r.length);for(let e=0;e=0&&r<=Re}}function rt(e){return function(t){return null==t?void 0:t[e]}}var ot=rt("byteLength"),it=tt(ot),nt=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;var st=ve?function(e){return Ee?Ee(e)&&!He(e):it(e)&&nt.test(ge.call(e))}:et(!1),at=rt("length");function ct(e,t){t=function(e){for(var t={},r=e.length,o=0;o":">",'"':""","'":"'","`":"`"},Gt=Xt(Yt),Zt=Xt(Ot(Yt)),er=ut.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},tr=/(.)^/,rr={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},or=/\\|'|\r|\n|\u2028|\u2029/g;function ir(e){return"\\"+rr[e]}var nr=/^\s*(\w|\$)+\s*$/;var sr=0;function ar(e,t,r,o,i){if(!(o instanceof t))return e.apply(r,i);var n=jt(e.prototype),s=e.apply(n,i);return Ae(s)?s:n}var cr=Oe((function(e,t){var r=cr.placeholder,o=function(){for(var i=0,n=t.length,s=Array(n),a=0;a1)ur(a,t-1,r,o),i=o.length;else for(var c=0,l=a.length;c0&&(r=t.apply(this,arguments)),e<=1&&(t=null),r}}var mr=cr(gr,2);function vr(e,t,r){t=Qt(t,r);for(var o,i=lt(e),n=0,s=i.length;n0?0:i-1;n>=0&&n0?s=n>=0?n:Math.max(n+a,s):a=n>=0?Math.min(n+1,a):n+a+1;else if(r&&n&&a)return o[n=r(o,i)]===i?n:-1;if(i!=i)return(n=t(ye.call(o,s,a),Ze))>=0?n+s:-1;for(n=e>0?s:a-1;n>=0&&n=3;return function(t,r,o,i){var n=!dr(t)&<(t),s=(n||t).length,a=e>0?0:s-1;for(i||(o=t[n?n[a]:a],a+=e);a>=0&&a=0}var Br=Oe((function(e,t,r){var o,i;return Ue(t)?i=t:(t=Pt(t),o=t.slice(0,-1),t=t[t.length-1]),Rr(e,(function(e){var n=i;if(!n){if(o&&o.length&&(e=zt(e,o)),null==e)return;n=e[t]}return null==n?n:n.apply(e,r)}))}));function Pr(e,t){return Rr(e,qt(t))}function zr(e,t,r){var o,i,n=-1/0,s=-1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var a=0,c=(e=dr(e)?e:Rt(e)).length;an&&(n=o);else t=Qt(t,r),Sr(e,(function(e,r,o){((i=t(e,r,o))>s||i===-1/0&&n===-1/0)&&(n=e,s=i)}));return n}var Dr=/[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;function $r(e){return e?Ve(e)?ye.call(e):Me(e)?e.match(Dr):dr(e)?Rr(e,$t):Rt(e):[]}function Nr(e,t,r){if(null==t||r)return dr(e)||(e=Rt(e)),e[Ht(e.length-1)];var o=$r(e),i=at(o);t=Math.max(Math.min(t,i),0);for(var n=i-1,s=0;s1&&(o=Ut(o,t[1])),t=gt(e)):(o=Jr,t=ur(t,!1,!1),e=Object(e));for(var i=0,n=t.length;i1&&(r=t[1])):(t=Rr(ur(t,!1,!1),String),o=function(e,r){return!jr(t,r)}),Hr(e,o,r)}));function Xr(e,t,r){return ye.call(e,0,Math.max(0,e.length-(null==t||r?1:t)))}function Yr(e,t,r){return null==e||e.length<1?null==t||r?void 0:[]:null==t||r?e[0]:Xr(e,e.length-t)}function Gr(e,t,r){return ye.call(e,null==t||r?1:t)}var Zr=Oe((function(e,t){return t=ur(t,!0,!0),Ir(e,(function(e){return!jr(t,e)}))})),eo=Oe((function(e,t){return Zr(e,t)}));function to(e,t,r,o){Ie(t)||(o=r,r=t,t=!1),null!=r&&(r=Qt(r,o));for(var i=[],n=[],s=0,a=at(e);st?(o&&(clearTimeout(o),o=null),a=l,s=e.apply(i,n),o||(i=n=null)):o||!1===r.trailing||(o=setTimeout(c,d)),s};return l.cancel=function(){clearTimeout(o),a=0,o=i=n=null},l},debounce:function(e,t,r){var o,i,n,s,a,c=function(){var l=Vt()-i;t>l?o=setTimeout(c,t-l):(o=null,r||(s=e.apply(a,n)),o||(n=a=null))},l=Oe((function(l){return a=this,n=l,i=Vt(),o||(o=setTimeout(c,t),r&&(s=e.apply(a,n))),s}));return l.cancel=function(){clearTimeout(o),o=n=a=null},l},wrap:function(e,t){return cr(t,e)},negate:yr,compose:function(){var e=arguments,t=e.length-1;return function(){for(var r=t,o=e[t].apply(this,arguments);r--;)o=e[r].call(this,o);return o}},after:function(e,t){return function(){if(--e<1)return t.apply(this,arguments)}},before:gr,once:mr,findKey:vr,findIndex:br,findLastIndex:wr,sortedIndex:Tr,indexOf:Cr,lastIndexOf:_r,find:xr,detect:xr,findWhere:function(e,t){return xr(e,Nt(t))},each:Sr,forEach:Sr,map:Rr,collect:Rr,reduce:Ar,foldl:Ar,inject:Ar,reduceRight:Fr,foldr:Fr,filter:Ir,select:Ir,reject:function(e,t,r){return Ir(e,yr(Qt(t)),r)},every:Lr,all:Lr,some:Mr,any:Mr,contains:jr,includes:jr,include:jr,invoke:Br,pluck:Pr,where:function(e,t){return Ir(e,Nt(t))},max:zr,min:function(e,t,r){var o,i,n=1/0,s=1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var a=0,c=(e=dr(e)?e:Rt(e)).length;ao||void 0===r)return 1;if(re.map((e=>e.name)),uo=e=>e.map((e=>e.key)),ho=(e,t)=>{let r=[];for(let o=0;o-1&&r.push(t.indexOf(e[o]));return r.length{if(-1===e.indexOf(o))for(let e=0;ee-Math.min(...r))))]};class po{static sortBooks(e,t,r){let o=e.map((e=>e.key)),i=(e=>e.getAllListConfig("recentBooks"))(r);if(1===t.sort||0===t.sort)return 1===t.order?ho(i,o).reverse():ho(i,o);if(2===t.sort){let r=lo(e),o=lo(e).sort();return 1===t.order?ho(o,r).reverse():ho(o,r)}if(3===t.sort){let r=[];for(let t=0;t{let t=e.getAllObjectConfig("readingTime");var r=[];for(let e in t)r.push([e,t[e]]);return r.sort((function(e,t){return e[1]-t[1]})),Object.keys(t)})(r),i=uo(e);return 1===t.order?ho(co.union(o,i),i).reverse():ho(co.union(o,i),i)}if(5===t.sort){let r=uo(e),o=(e=>co.sortBy(e.map((e=>({key:e.key,author:e.author}))),"author").map((e=>e.key)))(e);return 1===t.order?ho(o,r).reverse():ho(o,r)}if(6===t.sort){let o=(e=>{let t=e.getAllObjectConfig("recordLocation");var r=[];for(let e in t)r.push([e,t[e].percentage||0]);return r.sort((function(e,t){return e[1]-t[1]})),r.map((e=>e[0]))})(r),i=uo(e);return 1===t.order?ho(o,i).reverse():ho(o,i)}}static sortNotes(e,t,r=[]){if(3===t.sort){let r=co.clone(e).reverse(),o=co.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:e.chapterIndex}))));o=1===t.order?co.sortBy(o,"chapterIndex"):co.sortBy(o,"chapterIndex").reverse();let i=co.uniq(o.map((e=>e.chapter))),n={};return i.forEach((e=>{n[e]=[]})),r.forEach((e=>{n[e.chapter].push(e)})),i.map((e=>({group:e,notes:n[e]})))||[]}if(2===t.sort){let r=co.clone(e).reverse(),o=co.uniq(e.map((e=>e.date.year+"-"+e.date.month+"-"+e.date.day)));1===t.order?o.sort():o.sort().reverse();let i={};return o.forEach((e=>{i[e]=[]})),r.forEach((e=>{o.forEach((t=>{t===e.date.year+"-"+e.date.month+"-"+e.date.day&&i[t].push(e)}))})),i||{}}if(1===t.sort){let o=co.clone(e).reverse(),i=co.uniq(e.map((e=>{let t=co.findLastIndex(r,{key:e.bookKey});return t>-1?r[t].name:""})));1===t.order?i.sort():i.sort().reverse();let n={};return i.forEach((e=>{n[e]=[]})),o.forEach((e=>{i.forEach((t=>{let o=co.findLastIndex(r,{key:e.bookKey});o>-1&&t===r[o].name&&n[t].push(e)}))})),n||{}}}static sortBookmarks(e,t){if(3===t.sort){let r=co.clone(e).reverse(),o=co.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:parseInt(JSON.parse(e.cfi).chapterDocIndex)}))));o=1===t.order?co.sortBy(o,"chapterIndex"):co.sortBy(o,"chapterIndex").reverse();let i=co.uniq(o.map((e=>e.chapter))),n={};return i.forEach((e=>{n[e]=[]})),r.forEach((e=>{n[e.chapter].push(e)})),i.map((e=>({group:e,bookmarks:n[e]})))||[]}}}class fo{static getDefaultCss(e){return`::selection{background:#f3a6a68c}::-moz-selection{background:#f3a6a68c}.kookit-note:hover{cursor:pointer;}img{max-width:100% !important}.kookit-text{${this.getCustomCss(e)}}code,pre{white-space: pre-wrap;}p{margin-block: 0;margin-inline: 0;}${"yes"===e.getReaderConfig("isOverwriteLink")?"a{color: #0066cc !important; text-decoration: underline !important; cursor: pointer !important;}a:hover{color: #004080 !important;}a:visited{color: #6600cc !important;}":""}${"yes"===e.getReaderConfig("isMergeWord")?`h1{font-size: ${e.getReaderConfig("fontSize")||18}px !important;}`:""}`}static getCustomCss(e){return`font-size: ${e.getReaderConfig("fontSize")?e.getReaderConfig("fontSize"):"18"}px !important;line-height: ${e.getReaderConfig("lineHeight")||"1.25"} !important;font-family: ${e.getReaderConfig("fontFamily")||""} !important;background-color: transparent;color: ${e.getReaderConfig("textColor")?e.getReaderConfig("textColor"):"rgba(44,47,49,1)"===e.getReaderConfig("backgroundColor")||"night"===e.getReaderConfig("appSkin")||"system"===e.getReaderConfig("appSkin")&&"yes"===e.getReaderConfig("isOSNight")?"white":""} !important;letter-spacing: ${e.getReaderConfig("letterSpacing")}px !important;text-align: ${e.getReaderConfig("textAlign")?e.getReaderConfig("textAlign"):""} !important;font-weight: ${"yes"===e.getReaderConfig("isBold")?"bold !important":""};font-style: ${"yes"===e.getReaderConfig("isItalic")?"italic !important":""};text-shadow: ${"yes"===e.getReaderConfig("isShadow")?"2px 2px 2px #cccccc !important":""};text-indent: ${"yes"===e.getReaderConfig("isIndent")?"2rem":""};text-decoration: ${"yes"===e.getReaderConfig("isUnderline")?"underline !important":""};margin-bottom: ${e.getReaderConfig("paraSpacing")||0}px !important;padding:0px !important;word-wrap: break-word !important; writing-mode: horizontal-tb !important; `}}class yo{static mergeArray(e,t){var r=[];for(let t of e)r.push(t);for(let i of t){var o=!0;for(let t of e)if(i===t){o=!1;break}o&&r.push(i)}return r}static fuzzyQuery(e,t){for(var r=[],o=0;o-1&&r.push(o);return r}static mouseSearch(e){let t=document.querySelector(".header-search-box").value.toLowerCase(),r=[],o=[];if(!e)return[];e.forEach((e=>{r.push(e.name.toLowerCase()),o.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,t),n=this.fuzzyQuery(o,t);return this.mergeArray(i,n)}static keywordSearch(e,t){let r=[],o=[];if(!t)return[];t.forEach((e=>{r.push(e.name.toLowerCase()),o.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,e),n=this.fuzzyQuery(o,e);return this.mergeArray(i,n)}static keySearch(e,t){if(e&&13===e.keyCode){let r=[],o=[];if(!t)return[];t.forEach((e=>{r.push(e.name.toLowerCase()),o.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,e.target.value.toLowerCase()),n=this.fuzzyQuery(o,e.target.value.toLowerCase());return this.mergeArray(i,n)}}static mouseNoteSearch(e){let t=document.querySelector(".header-search-box").value.toLowerCase(),r=[],o=[];e.forEach((e=>{r.push(e.notes.toLowerCase()),o.push(e.text.toLowerCase())}));let i=this.fuzzyQuery(r,t),n=this.fuzzyQuery(o,t);return this.mergeArray(i,n)}static keyNoteSearch(e,t){if(e&&13===e.keyCode){let r=[],o=[];t.forEach((e=>{r.push(e.notes.toLowerCase()),o.push(e.text.toLowerCase())}));let i=this.fuzzyQuery(r,e.target.value.toLowerCase()),n=this.fuzzyQuery(o,e.target.value.toLowerCase());return this.mergeArray(i,n)}}}export{q as BookHelper,d as CommonTool,X as ConfigService,p as KookitConfig,H as LoginHelper,K as ReaderRequest,yo as SearchUtil,po as SortUtil,$ as SqlStatement,fo as StyleHelper,V as SyncHelper,L as SyncUtil,Q as ThirdpartyRequest,ne as TokenService,J as UserRequest}; diff --git a/src/assets/lib/kookit-extra.min.mjs b/src/assets/lib/kookit-extra.min.mjs index 2a16c983..f61929ca 100644 --- a/src/assets/lib/kookit-extra.min.mjs +++ b/src/assets/lib/kookit-extra.min.mjs @@ -1 +1 @@ -import e from"axios";import t from"fs";import r from"path";import{promisify as i}from"util";import o from"stream";import{Client as n}from"basic-ftp";import{S3Client as s,PutObjectCommand as a,GetObjectCommand as d,ListObjectsV2Command as c,DeleteObjectCommand as l}from"@aws-sdk/client-s3";import{createClient as h,AuthType as u}from"webdav";import p from"ssh2-sftp-client";import f from"form-data";import{Storage as y}from"megajs";import g from"electron-store";import m from"node-machine-id";function v(e,t,r,i){return new(r||(r=Promise))((function(o,n){function s(e){try{d(i.next(e))}catch(e){n(e)}}function a(e){try{d(i.throw(e))}catch(e){n(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}d((i=i.apply(e,t||[])).next())}))}const k=e=>"json"===e?"application/json":["jpg","jpeg","png","gif","bmp"].includes(e)?"image/"+e:"zip"===e?"application/zip":"epub"===e?"application/epub+zip":"txt"===e?"text/plain":"pdf"===e?"application/pdf":"mobi"===e?"application/x-mobipocket-ebook":"azw3"===e||"azw"===e?"application/vnd.amazon.ebook":"cbz"===e?"application/x-cbz":"cbr"===e?"application/x-cbr":"cbt"===e?"application/x-cbt":"cb7"===e?"application/x-cb7":"fb2"===e?"application/x-fictionbook+xml":"html"===e?"text/html":"css"===e?"text/css":"js"===e?"application/javascript":"xml"===e?"application/xml":"xhtml"===e?"application/xhtml+xml":"opf"===e?"application/oebps-package+xml":"ncx"===e?"application/x-dtbncx+xml":"mp3"===e?"audio/mpeg":"wav"===e?"audio/wav":"ogg"===e?"audio/ogg":"mp4"===e?"video/mp4":"webm"===e?"video/webm":"avi"===e?"video/x-msvideo":"wmv"===e?"video/x-ms-wmv":"flv"===e?"video/x-flv":"m3u8"===e?"application/x-mpegURL":"ts"===e?"video/MP2T":"3gp"===e?"video/3gpp":"3g2"===e?"video/3gpp2":"db"===e?"application/x-sqlite3":void 0;class T{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.maxConcurrency=e}addTask(e){return v(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,r)=>{const i=()=>v(this,void 0,void 0,(function*(){try{this.runningTasks++;const r=yield e();return this.completedTasks++,t(r),r}catch(e){throw this.completedTasks++,r(e),e}finally{this.runningTasks--,this.runNext()}}));this.runningTasks0&&this.runningTasks=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();return(yield e.post("https://api.dropboxapi.com/2/files/list_folder",{path:"/"+t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.entries.map((e=>e.name))}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();yield e.post("https://api.dropboxapi.com/2/files/delete_v2",{path:"/"+t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return v(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"dropbox",refresh_token:e});return this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dropbox",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${w}&redirect_uri=${E}`}}const O=i(o.pipeline);class C extends x{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=t.createReadStream(r.join(this.storagePath,i));return yield e.post("https://content.dropboxapi.com/2/files/upload",s,{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/octet-stream","Dropbox-API-Arg":JSON.stringify({path:"/"+o,mode:"overwrite",autorename:!0,mute:!1})},maxContentLength:1/0,maxBodyLength:1/0}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=t.createWriteStream(r.join(this.storagePath,o)),a=yield e({url:"https://content.dropboxapi.com/2/files/download",method:"GET",responseType:"stream",headers:{Authorization:`Bearer ${n}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+i})},maxContentLength:1/0,maxBodyLength:1/0});return yield O(a.data,s),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class A{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new T(1)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getClient(){return v(this,void 0,void 0,(function*(){if(this.client)return this.client;let{url:e,username:t,password:r,dir:i,ssl:o,port:s}=this.config;const a=new n;return a.ftp.verbose=!0,yield a.access({host:e,port:parseInt(s),user:t,password:r,secure:"1"===o}),this.client=a,a}))}uploadFile(e,t){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:i}=this.config;i||(i="KoodoReader");const o=yield this.getClient(),n=()=>v(this,void 0,void 0,(function*(){yield o.uploadFrom(r.join(this.storagePath,e),i+"/"+t)}));try{return yield n(),!0}catch(e){return console.error(e),!1}}))))))}))}downloadFile(e,t){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:i}=this.config;i||(i="KoodoReader");const o=yield this.getClient(),n=()=>v(this,void 0,void 0,(function*(){yield o.downloadTo(r.join(this.storagePath,t),i+"/"+e)}));try{return yield n(),!0}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");const r=yield this.getClient(),i=()=>v(this,void 0,void 0,(function*(){return yield r.list(t+"/"+e)}));try{return(yield i()).map((e=>e.name))}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");const r=yield this.getClient(),i=()=>v(this,void 0,void 0,(function*(){yield r.remove(t+"/"+e)}));try{return yield i(),!0}catch(e){return console.error(e),!1}}))}}class P{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.get(`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/children`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return i.status>=300?[]:i.data.value.map((e=>e.name))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.delete(`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!(i.status>=300)||(console.error("Error deleting file:",i),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return v(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"microsoft",refresh_token:e});return this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"microsoft",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${S}&scope=files.readwrite.appfolder offline_access&response_type=code&redirect_uri=${E}`}}class I extends P{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken();let s=o.split(".").pop(),a=k(s||"");const d="https://graph.microsoft.com/v1.0/me/drive/special/approot:/"+o+":/createUploadSession",c=(yield e.post(d,null,{headers:{Authorization:"Bearer "+n,"Content-Type":"application/json"},maxContentLength:1/0,maxBodyLength:1/0})).data.uploadUrl,l=t.readFileSync(r.join(this.storagePath,i));let h=yield this.getFileSize(r.join(this.storagePath,i));yield e.put(c,l,{headers:{"Content-Type":a,"Content-Range":`bytes 0-${h-1}/${h}`},maxContentLength:1/0,maxBodyLength:1/0});return!0}catch(e){return console.error("Error occurred during file upload:",e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),n=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${e}:/content`;let s=(yield fetch(n,{headers:{Authorization:"Bearer "+o},redirect:"manual"})).headers.get("location");if(s){const e=yield fetch(s,{headers:{}}),o=yield e.arrayBuffer();return t.writeFileSync(r.join(this.storagePath,i),Buffer.from(o)),!0}return!1}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return v(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class L{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getFileId(t,r){return v(this,void 0,void 0,(function*(){const i=yield this.refreshToken(),o=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+'${r}'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=yield e.get(o,{headers:{Authorization:"Bearer "+i}});if(0===t.data.files.length)return"";const r=t.data.files;return r.length>0?r[0].id:null}catch(e){return console.error("Error occurred during file list retrieval:",e),""}}))}checkFolder(t){return v(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),i=yield this.getFolderId(t);if(i)return i;const o={name:t,mimeType:"application/vnd.google-apps.folder",parents:["appDataFolder"]};try{return(yield e.post("https://www.googleapis.com/drive/v3/files",o,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error("Error occurred during folder creation:",e),e}}))}getFolderId(t){return v(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),i=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+mimeType='application/vnd.google-apps.folder'+and+'appDataFolder'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=(yield e.get(i,{headers:{Authorization:`Bearer ${r}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();const i=`https://www.googleapis.com/drive/v3/files?q='${yield this.checkFolder(t)}'+in+parents&spaces=appDataFolder&fields=files(id,name)`;return(yield e.get(i,{headers:{Authorization:`Bearer ${r}`}})).data.files.map((e=>e.name))}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return v(this,void 0,void 0,(function*(){const r=t.split("/")[1],i=t.split("/")[0],o=yield this.getFolderId(i),n=yield this.refreshToken(),s=yield this.getFileId(r,o);if(""===s)return console.error("File not found:",r),!0;try{const t=yield e.delete(`https://www.googleapis.com/drive/v3/files/${s}`,{headers:{Authorization:`Bearer ${n}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return v(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"google",refresh_token:e});return this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"google",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${E}&prompt=consent&response_type=code&client_id=${F}&scope=https://www.googleapis.com/auth/drive.appdata&access_type=offline`}}class $ extends L{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken();let s=i.split("/").pop(),a=o.split(".").pop(),d=k(a||""),c=o.split("/")[0],l=yield this.checkFolder(c),h=yield this.getFileId(s||"",l);const u={mimeType:d,name:s,parents:[l]},p=h?`https://www.googleapis.com/upload/drive/v3/files/${h}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",f=(yield e({method:h?"PATCH":"POST",url:p,data:h?null:JSON.stringify(u),headers:{Authorization:"Bearer "+n,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location;let y=yield this.getFileSize(r.join(this.storagePath,i));const g=t.createReadStream(r.join(this.storagePath,i));yield e.put(f,g,{headers:{Authorization:"Bearer "+n,"Content-Type":"application/zip","Content-Range":`bytes 0-${y-1}/${y}`},maxContentLength:1/0,maxBodyLength:1/0});return!0}catch(e){return console.error("Error occurred during upload:",e),!1}}))))))}))}downloadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken();let s=i.split("/").pop(),a=i.split("/")[0],d=yield this.checkFolder(a),c=yield this.getFileId(s||"",d);if(!c)return console.error("File not found"),!1;const l=`https://www.googleapis.com/drive/v3/files/${c}?alt=media`;return new Promise((i=>{const s=t.createWriteStream(r.join(this.storagePath,o));e({url:l,method:"GET",responseType:"stream",headers:{Authorization:"Bearer "+n},maxContentLength:1/0,maxBodyLength:1/0}).then((e=>{e.data.pipe(s),s.on("finish",(()=>{i(!0)})),s.on("error",(()=>{i(!1)}))})).catch((()=>{i(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return v(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class j{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new T(5)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}uploadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{endpoint:o,region:n,bucketName:d,accessKeyId:c,secretAccessKey:l,dir:h}=this.config;const u=new s({endpoint:o,region:n,credentials:{accessKeyId:c,secretAccessKey:l}});h||(h="KoodoReader");try{let o=yield u.send(new a({Bucket:d,Key:h+"/"+i,Body:t.createReadStream(r.join(this.storagePath,e))}));return 200===o.$metadata.httpStatusCode||(console.error("Error uploading file:",o),!1)}catch(e){return console.error("Error: ",e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{endpoint:o,region:n,bucketName:a,accessKeyId:c,secretAccessKey:l,dir:h}=this.config;h||(h="KoodoReader");const u=()=>new Promise(((u,p)=>{const f=new s({region:n,endpoint:o,credentials:{accessKeyId:c,secretAccessKey:l}});let y=t.createWriteStream(r.join(this.storagePath,i));(function(e,t,r,i){return new Promise(((o,n)=>v(this,void 0,void 0,(function*(){const n=yield e.send(new d({Bucket:t,Key:r}));n.Body?(n.Body.pipe(i),i.on("finish",(e=>{e&&o(!1),o(!0)}))):o(!1)}))))})(f,a,h+"/"+e,y).then((e=>{u(!0)})).catch((e=>{console.error(e),u(!1)}))}));try{return yield u()}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:i,accessKeyId:o,secretAccessKey:n,dir:a}=this.config;a||(a="KoodoReader");const d=new s({endpoint:t,region:r,credentials:{accessKeyId:o,secretAccessKey:n}});try{const t=yield d.send(new c({Bucket:i,Prefix:a+"/"+e}));return t.Contents?t.Contents.map((t=>{var r;return null===(r=t.Key)||void 0===r?void 0:r.substring((a+"/"+e).length+1)})):[]}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:i,accessKeyId:o,secretAccessKey:n,dir:a}=this.config;a||(a="KoodoReader");const d=new s({endpoint:t,region:r,credentials:{accessKeyId:o,secretAccessKey:n}});try{return yield d.send(new l({Bucket:i,Key:a+"/"+e})),!0}catch(e){return console.error(e),!1}}))}}class B{constructor(e,t){this.storagePath=t;let{username:r,password:i,url:o,dir:n}=e;n||(n="KoodoReader"),this.client=h(o,{authType:u.Password,username:r,password:i}),this.username=r,this.password=i,this.dir=n,this.taskQueue=new T(5)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}uploadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{!1===(yield this.client.exists(r.dirname(this.dir+"/"+i)))&&(yield this.client.createDirectory(r.dirname(this.dir+"/"+i)));let o=this.client.createWriteStream(this.dir+"/"+i);return t.createReadStream(r.join(this.storagePath,e)).pipe(o),new Promise(((e,t)=>{o.on("finish",(()=>{e(!0)})),o.on("error",(t=>{console.error(t),e(!1)}))}))}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{if(!1===(yield this.client.exists(this.dir+"/"+e)))return!1;let o=t.createWriteStream(r.join(this.storagePath,i));return this.client.createReadStream(this.dir+"/"+e).pipe(o),new Promise(((e,t)=>{o.on("finish",(()=>{e(!0)})),o.on("error",(t=>{e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){try{return(yield this.client.getDirectoryContents(this.dir+"/"+e)).map((e=>e.basename))}catch(t){return console.error("Error listing files:",t),t.response&&404===t.response.status&&(yield this.client.createDirectory(this.dir+"/"+e)),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){try{return yield this.client.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}}class M{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new T(5)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getClient(){return v(this,void 0,void 0,(function*(){if(this.client)return this.client;let{url:e,username:t,password:r,dir:i,port:o}=this.config;const n=new p;return yield n.connect({host:e,port:o,username:t,password:r}),this.client=n,n}))}uploadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:o}=this.config;o||(o="KoodoReader");let n=yield this.getClient();const s=()=>new Promise(((s,a)=>{let d=t.createReadStream(r.join(this.storagePath,e)),c="/"+o+"/"+i;n.put(d,c).then((()=>{s(!0)})).catch((e=>{console.error(e.message),s(!1)}))}));try{return yield s()}catch(e){return console.error(e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:o}=this.config;o||(o="KoodoReader");let n=yield this.getClient();const s=()=>new Promise(((s,a)=>{let d="/"+o+"/"+e,c=t.createWriteStream(r.join(this.storagePath,i));n.get(d,c).then((()=>{s(!0)})).catch((e=>{console.error(e.message),s(!1)}))}));try{return yield s()}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");let r=yield this.getClient();try{return yield new Promise(((i,o)=>{let n="/"+t+"/"+e;r.list(n).then((e=>{i(e.map((e=>e.name)))})).catch((e=>{console.error(e.message),i([])}))}))}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");let r=yield this.getClient();try{return yield new Promise(((i,o)=>{let n="/"+t+"/"+e;r.delete(n).then((()=>{i(!0)})).catch((e=>{console.error(e.message),i(!1)}))}))}catch(e){return console.error(e),!1}}))}}class K{downloadFile(e,t){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}authToken(e){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e("")}))}))}getAuthUrl(){return""}}class D{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getFolderIdByPath(t){return v(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),i=t.split("/");let o="0";for(const t of i){const i=`https://api.box.com/2.0/folders/${o}/items?fields=id,name&type=folder&limit=1000`;try{const n=(yield e.get(i,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(n)o=n.id;else{const i={name:t,parent:{id:o},type:"folder"};o=(yield e.post("https://api.box.com/2.0/folders",i,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}}catch(e){return console.error("Error occurred during folder creation:",e),""}}return o}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=yield this.getFolderIdByPath("KoodoReader/"+t);return(yield e.get(`https://api.box.com/2.0/folders/${i}/items`,{headers:{Authorization:`Bearer ${r}`}})).data.entries.map((e=>e.name))}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=t.substring(0,t.lastIndexOf("/")),o=t.substring(t.lastIndexOf("/")+1),n=yield this.getFolderIdByPath("KoodoReader/"+i);if(!n)return!0;const s=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,a=(yield e.get(s,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===o&&"file"===e.type));return!a||(yield e.delete(`https://api.box.com/2.0/files/${a.id}`,{headers:{Authorization:`Bearer ${r}`}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return v(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"boxnet",refresh_token:e});this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("boxnet_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"boxnet",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:R,redirect_uri:E,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class N extends D{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=o.substring(0,o.lastIndexOf("/")),a=o.substring(o.lastIndexOf("/")+1),d=yield this.getFolderIdByPath("KoodoReader/"+s);if(!d)throw new Error("Folder not found");const c=yield this.listFiles(s);c.find((e=>e===a))&&(yield this.deleteFileWithoutQueue(s+"/"+a));const l=new f,h=JSON.stringify({name:a,parent:{id:d}});l.append("attributes",h),l.append("file",t.createReadStream(r.join(this.storagePath,i)));const u=yield e.post("https://upload.box.com/api/2.0/files/content",l,{headers:Object.assign({Authorization:`Bearer ${n}`},l.getHeaders()),maxContentLength:1/0,maxBodyLength:1/0});return!(u.status>=300)||(console.error("Error occurred during file upload:",u),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=i.substring(0,i.lastIndexOf("/")),a=i.substring(i.lastIndexOf("/")+1),d=yield this.getFolderIdByPath("KoodoReader/"+s);if(!d)return console.error("Folder not found"),!1;const c=`https://api.box.com/2.0/folders/${d}/items?fields=id,name&type=file&limit=1000`,l=(yield e.get(c,{headers:{Authorization:`Bearer ${n}`}})).data.entries.find((e=>e.name===a&&"file"===e.type));if(!l)return console.error("File not found:",a),!1;const h=yield e({url:`https://api.box.com/2.0/files/${l.id}/content`,method:"get",responseType:"stream",headers:{Authorization:`Bearer ${n}`}});return yield new Promise(((e,i)=>{const n=t.createWriteStream(r.join(this.storagePath,o));h.data.pipe(n),n.on("finish",e),n.on("error",i)})),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class z{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getStorage(){return v(this,void 0,void 0,(function*(){if(this.storage)return this.storage;let{email:e,password:t}=this.config;return this.storage=yield new y({email:e,password:t}).ready,this.storage}))}getRoot(){return v(this,void 0,void 0,(function*(){if(this.root)return this.root;const e=(yield this.getStorage()).root;let t=e.children.find((e=>"KoodoReader"===e.name&&e.directory));return t||(t=yield e.mkdir("KoodoReader")),this.root=t,this.root}))}createFolder(e,t){return v(this,void 0,void 0,(function*(){const r=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(r))return yield this.folderCreationLocks.get(r);const i=(()=>v(this,void 0,void 0,(function*(){try{let r=e.children.find((e=>e.name===t&&e.directory));return r||(r=yield e.mkdir(t),r)}finally{this.folderCreationLocks.delete(r)}})))();return this.folderCreationLocks.set(r,i),yield i}))}listFiles(e){return v(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();if(e){const r=e.split("/").filter((e=>e));for(const e of r){const r=t.children.find((t=>t.name===e&&t.directory));if(!r)return[];t=r}}return t.children.filter((e=>!e.directory)).map((e=>e.name))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return v(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();const r=e.split("/"),i=r.pop();for(const e of r){if(!e)continue;const r=t.children.find((t=>t.name===e&&t.directory));if(!r)return!0;t=r}const o=t.children.find((e=>e.name===i&&!e.directory));return!o||(yield o.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class Q extends z{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const n=i.split("/"),s=n.pop()||"";for(const e of n){if(!e)continue;let t=o.children.find((t=>t.name===e&&t.directory));t||(t=yield this.createFolder(o,e)),o=t}const a=o.children.find((e=>e.name===s&&!e.directory));a&&(yield a.delete());const d=t.createReadStream(r.join(this.storagePath,e)),c=t.statSync(r.join(this.storagePath,e)).size;return yield o.upload({name:s,size:c},d).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const n=e.split("/"),s=n.pop()||"";for(const e of n){if(!e)continue;const t=o.children.find((t=>t.name===e&&t.directory));if(!t)return!1;o=t}const a=o.children.find((e=>e.name===s&&!e.directory));if(!a)return!1;const d=t.createWriteStream(r.join(this.storagePath,i));return new Promise((e=>{a.download().pipe(d),d.on("finish",(()=>e(!0))),d.on("error",(t=>{console.error("Error writing file:",t),e(!1)}))}))}catch(e){return console.error("Error occurred during MEGA file download:",e),!1}}))))))}))}}class q{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new T(1)}retryOperation(e,t=5){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getDriveId(){return v(this,void 0,void 0,(function*(){if(this.driveId)return this.driveId;const t=yield this.refreshToken(),r=yield e.post("https://openapi.alipan.com/adrive/v1.0/user/getDriveInfo",{},{headers:{Authorization:`Bearer ${t}`}});return this.driveId=r.data.default_drive_id,this.driveId}))}getFolderIdByPath(t){return v(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),i=yield this.getDriveId();try{try{const o=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(o.data)return o.data.file_id}catch(o){const n=t.split("/").filter((e=>e));let s="",a="root";for(const t of n){s+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:s},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.file_id}catch(o){a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:i,parent_file_id:a,name:t,type:"folder",check_name_mode:"refuse"},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.file_id}}return a}}catch(e){return console.error("Error getting/creating folder by path:",e),""}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield this.getDriveId(),o=yield this.getFolderIdByPath("/KoodoReader/"+t);return(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:i,parent_file_id:o},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.items.map((e=>e.name))}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield this.getDriveId(),o=yield this.getFolderIdByPath("/KoodoReader/"+t);return!o||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:i,file_id:o},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}checkExists(t){var r;return v(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken(),o=yield this.getDriveId(),n=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:t},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});(null===(r=n.data)||void 0===r?void 0:r.file_id)&&(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/recyclebin/trash",{drive_id:o,file_id:n.data.file_id},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}))}catch(e){}}))}refreshToken(){return v(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"adrive",refresh_token:e});this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("adrive_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"adrive",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:_,redirect_uri:E,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class W extends q{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=yield this.getDriveId(),a=o.substring(0,o.lastIndexOf("/")),d=o.substring(o.lastIndexOf("/")+1);yield this.deleteFileWithoutQueue(o);const c=yield this.getFolderIdByPath("/KoodoReader/"+a),l=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:s,parent_file_id:c,name:d,type:"file",check_name_mode:"ignore"},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}}),{file_id:h,upload_id:u,part_info_list:p}=l.data,f=yield t.promises.readFile(r.join(this.storagePath,i));return yield fetch(p[0].upload_url,{method:"PUT",body:f,headers:{"Content-Length":t.statSync(r.join(this.storagePath,i)).size.toString()}}),yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/complete",{drive_id:s,file_id:h,upload_id:u},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=yield this.getDriveId(),a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:s,file_path:"/KoodoReader/"+i},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}})).data.file_id,d=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:s,file_id:a},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}}),c=yield e({url:d.data.url,method:"get",responseType:"stream"}),l=t.createWriteStream(r.join(this.storagePath,o));return c.data.pipe(l),new Promise((e=>{l.on("finish",(()=>{e(!0)})),l.on("error",(t=>{console.error("Error occurred during file download:",t),e(!1)}))}))}catch(e){return console.error("Error downloading file:",e),!1}}))))))}))}}class J{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new T(3)}retryOperation(e,t=5){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}checkFolderExists(t,r){return v(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(t,r){return v(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/createfolderifnotexists",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error creating folder:",e),!1}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:"/"+t,recursive:0}});return 0!==i.data.result?[]:i.data.metadata.contents.map((e=>e.name))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.get("https://api.pcloud.com/deletefile",{params:{access_token:r,path:"/"+t}});return 0===i.data.result||(console.error("Error deleting file:",i.data),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return v(this,void 0,void 0,(function*(){return this.config.refresh_token}))}authToken(e){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"pcloud",redirect_uri:E,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${b}&response_type=code&redirect_uri=${E}`}}class H extends J{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=o.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(s,n))){if(!(yield this.createFolder(s,n)))return!1}const a=r.join(this.storagePath,i),d=t.createReadStream(a),c=t.statSync(a),l=r.basename(i),h=yield e({method:"put",url:"https://api.pcloud.com/uploadfile",params:{access_token:n,path:`/${s}`,renew:1,filename:l},data:d,headers:{"Content-Length":c.size,"Content-Type":"application/octet-stream"},maxContentLength:1/0,maxBodyLength:1/0});return 0===h.data.result||(console.error("Error uploading file:",h.data),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=yield e.get("https://api.pcloud.com/getfilelink",{params:{access_token:n,path:`/${i}`}});if(0!==s.data.result)return console.error("Error getting file link:",s.data),!1;const a=r.join(this.storagePath,o),d=t.createWriteStream(a),c=`https://${s.data.hosts[0]}${s.data.path}`,l=yield e({method:"get",url:c,responseType:"stream",maxContentLength:1/0,maxBodyLength:1/0});return new Promise((e=>{l.data.pipe(d),d.on("finish",(()=>{e(!0)})),d.on("error",(t=>{console.error("Error writing file:",t),e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}const U=["book","config","cover","font"];class V{constructor(e,t,r,i){this.type=e,this.storagePath=r,this.remote="dropbox"===e?new C(t,r,i):"microsoft"===e?new I(t,r,i):"google"===e?new $(t,r,i):"s3compatible"===e?new j(t,r):"webdav"===e?new B(t,r):"ftp"===e?new A(t,r):"sftp"===e?new M(t,r):"boxnet"===e?new N(t,r,i):"mega"===e?new Q(t,r):"adrive"===e?new W(t,r,i):"pcloud"===e?new H(t,r,i):new K}downloadFile(e,i,o){return v(this,void 0,void 0,(function*(){return t.existsSync(r.join(this.storagePath+"/"+o))||t.mkdirSync(r.join(this.storagePath+"/"+o)),!!(yield this.listFiles(o)).find((t=>e.indexOf(t)>-1))&&(yield this.remote.downloadFile(o+"/"+e,o+"/"+i))}))}uploadFile(e,t,r){return v(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(r+"/"+e,r+"/"+t)}))}deleteFile(e,t){return v(this,void 0,void 0,(function*(){return yield this.remote.deleteFile(t+"/"+e)}))}isExist(e,t){return v(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}listFiles(e){return v(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}downloadAllFiles(){return v(this,void 0,void 0,(function*(){for(let e of U){let t=yield this.listFiles(e);for(let r of t)yield this.downloadFile(r,r,e)}}))}authToken(e){return v(this,void 0,void 0,(function*(){return yield this.remote.authToken(e)}))}getAuthUrl(){return this.remote.getAuthUrl()}getStats(){return this.remote.taskQueue.getStats()}resetCounters(){this.remote.taskQueue.resetCounters()}}const X={notes:"SELECT * FROM notes WHERE key = ?",bookmarks:"SELECT * FROM bookmarks WHERE key = ?",books:"SELECT * FROM books WHERE key = ?",plugins:"SELECT * FROM plugins WHERE key = ?",words:"SELECT * FROM words WHERE key = ?"},Y={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},G={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function Z(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const ee={notes:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),t.tag=JSON.parse(e.tag),t},bookmarks:e=>e,books:e=>e,plugins:e=>{let t=Object.assign({},e);return e.autoValue||delete t.autoValue,e.langList?t.langList=JSON.parse(e.langList):delete t.langList,e.voiceList?t.voiceList=JSON.parse(e.voiceList):delete t.voiceList,t.config=JSON.parse(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),t}};var te={sqlStatement:{createTableStatement:Z({notes:'\n CREATE TABLE IF NOT EXISTS "notes" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "chapter" text,\n "chapterIndex" integer,\n "text" text,\n "cfi" text,\n "range" text,\n "notes" text,\n "percentage" text,\n "color" integer,\n "tag" array\n )\n ',bookmarks:'\n CREATE TABLE IF NOT EXISTS "bookmarks" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "cfi" text,\n "label" text,\n "percentage" text,\n "chapter" text\n );\n ',books:'\n CREATE TABLE IF NOT EXISTS "books" (\n "key" text PRIMARY KEY,\n "name" text,\n "author" text,\n "description" text,\n "md5" text,\n "cover" text,\n "format" text,\n "publisher" text,\n "size" integer,\n "page" integer,\n "path" text,\n "charset" text\n );\n ',plugins:'\n CREATE TABLE IF NOT EXISTS "plugins" (\n "key" text PRIMARY KEY,\n "type" text,\n "displayName" text,\n "icon" text,\n "version" text,\n "config" object,\n "autoValue" string,\n "langList" text,\n "voiceList" text,\n "scriptSHA256" text,\n "script" text\n );\n ',words:'\n CREATE TABLE IF NOT EXISTS "words" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "word" text,\n "chapter" text\n );\n '}),getAllStatement:Z({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:Z({notes:"INSERT OR REPLACE INTO notes (key, bookKey, chapter, chapterIndex, text, cfi, range, notes, date, percentage, color, tag) VALUES (@key, @bookKey, @chapter, @chapterIndex, @text, @cfi, @range, @notes, @date, @percentage, @color, @tag)",bookmarks:"INSERT OR REPLACE INTO bookmarks (key, bookKey, cfi, label, percentage, chapter) VALUES (@key, @bookKey, @cfi, @label, @percentage, @chapter)",books:"INSERT OR REPLACE INTO books (key, name, author, description, md5, cover, format, publisher, size, page, path, charset) VALUES (@key, @name, @author, @description, @md5, @cover, @format, @publisher, @size, @page, @path, @charset)",plugins:"INSERT OR REPLACE INTO plugins (key, type, displayName, icon, version, config, autoValue, langList, voiceList, scriptSHA256, script) VALUES (@key, @type, @displayName, @icon, @version, @config, @autoValue, @langList, @voiceList, @scriptSHA256, @script)",words:"INSERT OR REPLACE INTO words (key, bookKey, date, word, chapter) VALUES (@key, @bookKey, @date, @word, @chapter)"}),deleteAllStatement:Z({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:Z({notes:"UPDATE notes SET bookKey = @bookKey, chapter = @chapter, chapterIndex = @chapterIndex, text = @text, cfi = @cfi, range = @range, notes = @notes, date = @date, percentage = @percentage, color = @color, tag = @tag WHERE key = @key",bookmarks:"UPDATE bookmarks SET bookKey = @bookKey, cfi = @cfi, label = @label, percentage = @percentage, chapter = @chapter WHERE key = @key",books:"UPDATE books SET name = @name, author = @author, description = @description, md5 = @md5, cover = @cover, format = @format, publisher = @publisher, size = @size, page = @page, path = @path, charset = @charset WHERE key = @key",plugins:"UPDATE plugins SET type = @type, displayName = @displayName, icon = @icon, version = @version, config = @config, autoValue = @autoValue, langList = @langList, voiceList = @voiceList, scriptSHA256 = @scriptSHA256, script = @script WHERE key = @key",words:"UPDATE words SET bookKey = @bookKey, date = @date, word = @word, chapter = @chapter WHERE key = @key"}),deleteStatement:Z({notes:"DELETE FROM notes WHERE key = ?",bookmarks:"DELETE FROM bookmarks WHERE key = ?",books:"DELETE FROM books WHERE key = ?",plugins:"DELETE FROM plugins WHERE key = ?",words:"DELETE FROM words WHERE key = ?"}),dropStatement:Z({notes:"DROP TABLE IF EXISTS notes",bookmarks:"DROP TABLE IF EXISTS bookmarks",books:"DROP TABLE IF EXISTS books",plugins:"DROP TABLE IF EXISTS plugins",words:"DROP TABLE IF EXISTS words"}),getStatement:Z(X),getByBookKeyStatement:Z(Y),getByBookKeysStatement:Z({notes:e=>`SELECT * FROM notes WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,bookmarks:e=>`SELECT * FROM bookmarks WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,words:e=>`SELECT * FROM words WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")})`}),deleteByBookKeyStatement:Z(G)},jsonToSqlite:Z({notes:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),t.tag=JSON.stringify(e.tag),t},bookmarks:e=>e,books:e=>{let t=Object.assign({},e);return t.page=e.page||0,t},plugins:e=>{let t=Object.assign({},e);return e.autoValue||(t.autoValue=null),e.langList?t.langList=JSON.stringify(e.langList):t.langList=null,e.voiceList?t.voiceList=JSON.stringify(e.voiceList):t.voiceList=null,t.config=JSON.stringify(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),t}}),sqliteToJson:Z(ee)};const re="http://192.168.28.159:8000";class ie{constructor(e,t){this.processingQueue=!1,this.requestQueue=[],this.TokenService=e,this.ConfigService=t,this.refreshToken="",this.accessToken="",this.streamPromise=null}refreshUserToken(){return v(this,void 0,void 0,(function*(){if(this.refreshToken=yield this.TokenService.getToken("refresh_token"),!this.refreshToken)return{code:401,message:"refresh token not found"};let t=(yield e.post(re+"/api/v1/public/user/refresh_token",{refresh_token:this.refreshToken})).data;return 200===t.code&&(yield this.TokenService.setToken("access_token",t.data.access_token),yield this.TokenService.setToken("refresh_token",t.data.refresh_token),this.accessToken=t.data.access_token,this.refreshToken=t.data.refresh_token),t}))}requestWithRetry(e){return v(this,void 0,void 0,(function*(){return this.requestQueue||(this.requestQueue=[]),new Promise(((t,r)=>{this.requestQueue.push({config:e,resolve:t,reject:r}),this.processingQueue||this.processQueue()}))}))}processQueue(){return v(this,void 0,void 0,(function*(){if(!this.processingQueue){this.processingQueue=!0;try{for(;this.requestQueue.length>0;){const e=this.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{this.processingQueue=!1}}}))}executeRequest(t){return v(this,void 0,void 0,(function*(){try{try{this.accessToken=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let r="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);t.baseURL=re,t.headers?(t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=r):t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":r};let i=(yield e(t)).data;if(402===i.code){let r=yield this.refreshUserToken();if(200===r.code){return t.headers=t.headers||{},t.headers.Authorization="Bearer "+this.accessToken,(yield e(t)).data}return r}return 200!==i.code&&this.ConfigService.setItem("errorLog",JSON.stringify({request:t.data,url:t.url,result:i,requestID:r})),i}catch(e){throw console.error("Request execution error:",e),e}}))}requestWithStream(e,t,r){return v(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>v(this,void 0,void 0,(function*(){try{let i="";try{i=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((n,s)=>{const a=new r(re+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+i,"X-Request-ID":o},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});a.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),a.addEventListener("message",(e=>v(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);r.done?(a.close(),n(r)):(402===r.code&&(yield this.refreshUserToken()),t(r.data))})))),a.addEventListener("error",(e=>{console.error("Error:",e),n({code:500,message:"internal error"}),a.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return v(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>v(this,void 0,void 0,(function*(){try{let r="";try{r=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((o,n)=>v(this,void 0,void 0,(function*(){const n=yield fetch(re+e.url,{method:"POST",headers:{"Content-Type":"text/event-stream",Authorization:"Bearer "+r,"X-Request-ID":i},body:JSON.stringify(e.data)});if(!n.body)throw new Error("Response body is null");const s=n.body.pipeThrough(new TextDecoderStream).getReader();for(;;){const{value:e,done:r}=yield s.read();if(r){t({done:!0});break}if(e)if(e.includes('"code":400')||e.includes('"code":401')||e.includes('"code":402')){let t=JSON.parse(e);402===t.code&&(yield this.refreshUserToken()),o(t)}else e.split("\n").forEach((e=>{if(e.startsWith("data:")){const r=JSON.parse(e.substring(5));t(r.data)}}))}}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}class oe extends ie{constructor(e,t){super(e,t)}encryptToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/encrypt_token",data:e};return yield this.requestWithRetry(t)}))}decryptToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};return yield this.requestWithRetry(t)}))}authThirdToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/auth_token",data:e};return yield this.requestWithRetry(t)}))}refreshThirdToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/refresh_token",data:e};return yield this.requestWithRetry(t)}))}s3Upload(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_upload",data:e};return yield this.executeRequest(t)}))}s3Download(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_download",data:e};return yield this.executeRequest(t)}))}s3List(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_list",data:e};return yield this.executeRequest(t)}))}s3Delete(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_delete",data:e};return yield this.executeRequest(t)}))}getSyncState(){return v(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/pro/thirdparty/get_sync_state"})}))}deleteSyncState(){return v(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/pro/thirdparty/delete_sync_state"})}))}}const ne=new g;class se{static encrypt(e,t){let r="";for(let i=0;i-1&&r.splice(i,1),this.setAllListConfig(r,t)}static setListConfig(e,t){let r=this.getAllListConfig(t);const i=r.indexOf(e);i>-1?(r.splice(i,1),r.unshift(e)):r.unshift(e),this.setAllListConfig(r,t)}static setAllListConfig(e,t,r=!0){this.setItem(t,JSON.stringify(e)),r&&this.setSyncRecord({type:"config",catergory:"listConfig",name:"general",key:t},{operation:"update",time:Date.now()})}static setObjectConfig(e,t,r,i=!0){let o=this.getAllObjectConfig(r);o[e]=t,i&&this.setSyncRecord({type:"config",catergory:"objectConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllObjectConfig(o,r)}static getObjectConfig(e,t,r){return this.getAllObjectConfig(t)[e]||r}static getAllObjectConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static setAllObjectConfig(e,t){this.setItem(t,JSON.stringify(e))}static deleteObjectConfig(e,t){let r=this.getAllObjectConfig(t);delete r[e],this.setSyncRecord({type:"config",catergory:"objectConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllObjectConfig(r,t)}static getAllMapConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static getMapConfig(e,t){return this.getAllMapConfig(t)[e]||[]}static setAllMapConfig(e,t){this.setItem(t,JSON.stringify(e))}static setMapConfig(e,t,r){let i=this.getAllMapConfig(r);void 0===i[e]&&(i[e]=[]),t&&-1===i[e].indexOf(t)&&i[e].unshift(t),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(i,r)}static setOneMapConfig(e,t,r,i=!0){let o=this.getAllMapConfig(r);o[e]=t,i&&this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,r)}static deleteFromMapConfig(e,t,r){let i=this.getAllMapConfig(r),o=i[e].indexOf(t);i[e].splice(o,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(i,r)}static deleteFromAllMapConfig(e,t){let r=this.getAllMapConfig(t);Object.keys(r).forEach((i=>{let o=r[i].indexOf(e);o>-1&&(r[i].splice(o,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:i},{operation:"update",time:Date.now()}))})),this.setAllMapConfig(r,t)}static deleteMapConfig(e,t){let r=this.getAllMapConfig(t);delete r[e],this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllMapConfig(r,t)}static getFromAllMapConfig(e,t){let r=this.getAllMapConfig(t),i=[];for(let t in r)r[t]&&r[t].indexOf(e)>-1&&i.push(t);return i}static getSyncRecord(e){return JSON.parse(this.getItem("syncRecord")||"{}")[e.type+"."+e.catergory+"."+e.name+"."+e.key]||{operation:"",time:0}}static getAllSyncRecord(){return JSON.parse(this.getItem("syncRecord")||"{}")}static setSyncRecord(e,t){let r=JSON.parse(this.getItem("syncRecord")||"{}");r[e.type+"."+e.catergory+"."+e.name+"."+e.key]=t,this.setItem("syncRecord",JSON.stringify(r))}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}});var ce,le;export{de as ConfigService,te as SqlStatement,V as SyncUtil,oe as ThirdpartyRequest,se as TokenService}; +import e from"axios";import t from"fs";import r from"path";import{promisify as i}from"util";import o from"stream";import{Client as n}from"basic-ftp";import{S3Client as s,PutObjectCommand as a,GetObjectCommand as d,ListObjectsV2Command as c,DeleteObjectCommand as l}from"@aws-sdk/client-s3";import{createClient as h,AuthType as u}from"webdav";import p from"ssh2-sftp-client";import f from"form-data";import{Storage as y}from"megajs";import g from"electron-store";import m from"node-machine-id";function v(e,t,r,i){return new(r||(r=Promise))((function(o,n){function s(e){try{d(i.next(e))}catch(e){n(e)}}function a(e){try{d(i.throw(e))}catch(e){n(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}d((i=i.apply(e,t||[])).next())}))}const k=e=>"json"===e?"application/json":["jpg","jpeg","png","gif","bmp"].includes(e)?"image/"+e:"zip"===e?"application/zip":"epub"===e?"application/epub+zip":"txt"===e?"text/plain":"pdf"===e?"application/pdf":"mobi"===e?"application/x-mobipocket-ebook":"azw3"===e||"azw"===e?"application/vnd.amazon.ebook":"cbz"===e?"application/x-cbz":"cbr"===e?"application/x-cbr":"cbt"===e?"application/x-cbt":"cb7"===e?"application/x-cb7":"fb2"===e?"application/x-fictionbook+xml":"html"===e?"text/html":"css"===e?"text/css":"js"===e?"application/javascript":"xml"===e?"application/xml":"xhtml"===e?"application/xhtml+xml":"opf"===e?"application/oebps-package+xml":"ncx"===e?"application/x-dtbncx+xml":"mp3"===e?"audio/mpeg":"wav"===e?"audio/wav":"ogg"===e?"audio/ogg":"mp4"===e?"video/mp4":"webm"===e?"video/webm":"avi"===e?"video/x-msvideo":"wmv"===e?"video/x-ms-wmv":"flv"===e?"video/x-flv":"m3u8"===e?"application/x-mpegURL":"ts"===e?"video/MP2T":"3gp"===e?"video/3gpp":"3g2"===e?"video/3gpp2":"db"===e?"application/x-sqlite3":void 0;class T{constructor(e){this.queue=[],this.runningTasks=0,this.totalTasks=0,this.completedTasks=0,this.maxConcurrency=e}addTask(e){return v(this,void 0,void 0,(function*(){return this.totalTasks++,new Promise(((t,r)=>{const i=()=>v(this,void 0,void 0,(function*(){try{this.runningTasks++;const r=yield e();return this.completedTasks++,t(r),r}catch(e){throw this.completedTasks++,r(e),e}finally{this.runningTasks--,this.runNext()}}));this.runningTasks0&&this.runningTasks=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=[],o=!0,n=null;for(;o;){let s;s=n?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:n},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}):yield e.post("https://api.dropboxapi.com/2/files/list_folder",{path:"/"+t,limit:2e3},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});const a=s.data.entries||[];i=i.concat(a),o=s.data.has_more,n=s.data.cursor}return[...new Set(i.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();yield e.post("https://api.dropboxapi.com/2/files/delete_v2",{path:"/"+t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return v(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"dropbox",refresh_token:e});return this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"dropbox",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${w}&redirect_uri=${E}`}}const O=i(o.pipeline);class C extends F{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=t.createReadStream(r.join(this.storagePath,i));return yield e.post("https://content.dropboxapi.com/2/files/upload",s,{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/octet-stream","Dropbox-API-Arg":JSON.stringify({path:"/"+o,mode:"overwrite",autorename:!0,mute:!1})},maxContentLength:1/0,maxBodyLength:1/0}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=t.createWriteStream(r.join(this.storagePath,o)),a=yield e({url:"https://content.dropboxapi.com/2/files/download",method:"GET",responseType:"stream",headers:{Authorization:`Bearer ${n}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+i})},maxContentLength:1/0,maxBodyLength:1/0});return yield O(a.data,s),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class A{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new T(1)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getClient(){return v(this,void 0,void 0,(function*(){if(this.client)return this.client;let{url:e,username:t,password:r,dir:i,ssl:o,port:s}=this.config;const a=new n;return a.ftp.verbose=!0,yield a.access({host:e,port:parseInt(s),user:t,password:r,secure:"1"===o}),this.client=a,a}))}uploadFile(e,t){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:i}=this.config;i||(i="KoodoReader");const o=yield this.getClient(),n=()=>v(this,void 0,void 0,(function*(){yield o.uploadFrom(r.join(this.storagePath,e),i+"/"+t)}));try{return yield n(),!0}catch(e){return console.error(e),!1}}))))))}))}downloadFile(e,t){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:i}=this.config;i||(i="KoodoReader");const o=yield this.getClient(),n=()=>v(this,void 0,void 0,(function*(){yield o.downloadTo(r.join(this.storagePath,t),i+"/"+e)}));try{return yield n(),!0}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");const r=yield this.getClient(),i=()=>v(this,void 0,void 0,(function*(){return yield r.list(t+"/"+e)}));try{return(yield i()).map((e=>e.name))}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");const r=yield this.getClient(),i=()=>v(this,void 0,void 0,(function*(){yield r.remove(t+"/"+e)}));try{return yield i(),!0}catch(e){return console.error(e),!1}}))}}class P{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=[],o=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/children`;for(;o;){const t=yield e.get(o,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(t.status>=300)break;const n=t.data.value||[];i=i.concat(n),o=t.data["@odata.nextLink"]||""}return[...new Set(i.map((e=>e.name)))]}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.delete(`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!(i.status>=300)||(console.error("Error deleting file:",i),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return v(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"microsoft",refresh_token:e});return this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"microsoft",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${R}&scope=files.readwrite.appfolder offline_access&response_type=code&redirect_uri=${E}`}}class I extends P{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken();let s=o.split(".").pop(),a=k(s||"");const d="https://graph.microsoft.com/v1.0/me/drive/special/approot:/"+o+":/createUploadSession",c=(yield e.post(d,null,{headers:{Authorization:"Bearer "+n,"Content-Type":"application/json"},maxContentLength:1/0,maxBodyLength:1/0})).data.uploadUrl,l=t.readFileSync(r.join(this.storagePath,i));let h=yield this.getFileSize(r.join(this.storagePath,i));yield e.put(c,l,{headers:{"Content-Type":a,"Content-Range":`bytes 0-${h-1}/${h}`},maxContentLength:1/0,maxBodyLength:1/0});return!0}catch(e){return console.error("Error occurred during file upload:",e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),n=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${e}:/content`;let s=(yield fetch(n,{headers:{Authorization:"Bearer "+o},redirect:"manual"})).headers.get("location");if(s){const e=yield fetch(s,{headers:{}}),o=yield e.arrayBuffer();return t.writeFileSync(r.join(this.storagePath,i),Buffer.from(o)),!0}return!1}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return v(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class L{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getFileId(t,r){return v(this,void 0,void 0,(function*(){const i=yield this.refreshToken(),o=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+'${r}'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=yield e.get(o,{headers:{Authorization:"Bearer "+i}});if(0===t.data.files.length)return"";const r=t.data.files;return r.length>0?r[0].id:null}catch(e){return console.error("Error occurred during file list retrieval:",e),""}}))}checkFolder(t){return v(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),i=yield this.getFolderId(t);if(i)return i;const o={name:t,mimeType:"application/vnd.google-apps.folder",parents:["appDataFolder"]};try{return(yield e.post("https://www.googleapis.com/drive/v3/files",o,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}catch(e){throw console.error("Error occurred during folder creation:",e),e}}))}getFolderId(t){return v(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),i=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+mimeType='application/vnd.google-apps.folder'+and+'appDataFolder'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=(yield e.get(i,{headers:{Authorization:`Bearer ${r}`}})).data.files;return t.length>0?t[0].id:null}catch(e){throw console.error("Error occurred during fetching folder ID:",e),e}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=yield this.checkFolder(t),o=[],n="",s=!0;for(;s;){let t=`https://www.googleapis.com/drive/v3/files?q='${i}'+in+parents&spaces=appDataFolder&fields=nextPageToken,files(id,name)&pageSize=1000`;n&&(t+=`&pageToken=${n}`);const a=yield e.get(t,{headers:{Authorization:`Bearer ${r}`}}),d=a.data.files||[];o=o.concat(d),n=a.data.nextPageToken,s=!!n}return[...new Set(o.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQue(e)}))))))}))}deleteFileWithoutQue(t){return v(this,void 0,void 0,(function*(){const r=t.split("/")[1],i=t.split("/")[0],o=yield this.getFolderId(i),n=yield this.refreshToken(),s=yield this.getFileId(r,o);if(""===s)return console.error("File not found:",r),!0;try{const t=yield e.delete(`https://www.googleapis.com/drive/v3/files/${s}`,{headers:{Authorization:`Bearer ${n}`}});return console.error("File deleted:",t),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return v(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"google",refresh_token:e});return this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"google",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${E}&prompt=consent&response_type=code&client_id=${_}&scope=https://www.googleapis.com/auth/drive.appdata&access_type=offline`}}class $ extends L{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken();let s=i.split("/").pop(),a=o.split(".").pop(),d=k(a||""),c=o.split("/")[0],l=yield this.checkFolder(c),h=yield this.getFileId(s||"",l);const u={mimeType:d,name:s,parents:[l]},p=h?`https://www.googleapis.com/upload/drive/v3/files/${h}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",f=(yield e({method:h?"PATCH":"POST",url:p,data:h?null:JSON.stringify(u),headers:{Authorization:"Bearer "+n,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location;let y=yield this.getFileSize(r.join(this.storagePath,i));const g=t.createReadStream(r.join(this.storagePath,i));yield e.put(f,g,{headers:{Authorization:"Bearer "+n,"Content-Type":"application/zip","Content-Range":`bytes 0-${y-1}/${y}`},maxContentLength:1/0,maxBodyLength:1/0});return!0}catch(e){return console.error("Error occurred during upload:",e),!1}}))))))}))}downloadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken();let s=i.split("/").pop(),a=i.split("/")[0],d=yield this.checkFolder(a),c=yield this.getFileId(s||"",d);if(!c)return console.error("File not found"),!0;const l=`https://www.googleapis.com/drive/v3/files/${c}?alt=media`;return new Promise((i=>{const s=t.createWriteStream(r.join(this.storagePath,o));e({url:l,method:"GET",responseType:"stream",headers:{Authorization:"Bearer "+n},maxContentLength:1/0,maxBodyLength:1/0}).then((e=>{e.data.pipe(s),s.on("finish",(()=>{i(!0)})),s.on("error",(()=>{i(!1)}))})).catch((()=>{i(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}getFileSize(e){return v(this,void 0,void 0,(function*(){try{return(yield t.promises.stat(e)).size}catch(e){throw e}}))}}class j{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new T(5)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}uploadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{endpoint:o,region:n,bucketName:d,accessKeyId:c,secretAccessKey:l,dir:h}=this.config;const u=new s({endpoint:o,region:n,credentials:{accessKeyId:c,secretAccessKey:l}});h||(h="KoodoReader");try{let o=yield u.send(new a({Bucket:d,Key:h+"/"+i,Body:t.createReadStream(r.join(this.storagePath,e))}));return 200===o.$metadata.httpStatusCode||(console.error("Error uploading file:",o),!1)}catch(e){return console.error("Error: ",e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{endpoint:o,region:n,bucketName:a,accessKeyId:c,secretAccessKey:l,dir:h}=this.config;h||(h="KoodoReader");const u=()=>new Promise(((u,p)=>{const f=new s({region:n,endpoint:o,credentials:{accessKeyId:c,secretAccessKey:l}});let y=t.createWriteStream(r.join(this.storagePath,i));(function(e,t,r,i){return new Promise(((o,n)=>v(this,void 0,void 0,(function*(){const n=yield e.send(new d({Bucket:t,Key:r}));n.Body?(n.Body.pipe(i),i.on("finish",(e=>{e&&o(!1),o(!0)}))):o(!1)}))))})(f,a,h+"/"+e,y).then((e=>{u(!0)})).catch((e=>{console.error(e),u(!1)}))}));try{return yield u()}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:i,accessKeyId:o,secretAccessKey:n,dir:a}=this.config;a||(a="KoodoReader");const d=new s({endpoint:t,region:r,credentials:{accessKeyId:o,secretAccessKey:n}});try{let t,r=[],o=!0;for(;o;){const n=yield d.send(new c({Bucket:i,Prefix:a+"/"+e,ContinuationToken:t}));n.Contents&&(r=r.concat(n.Contents)),t=n.NextContinuationToken,o=!!t}return 0===r.length?[]:[...new Set(r.map((t=>{var r;return null===(r=t.Key)||void 0===r?void 0:r.substring((a+"/"+e).length+1)})).filter((e=>e&&e.length>0)))]}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:i,accessKeyId:o,secretAccessKey:n,dir:a}=this.config;a||(a="KoodoReader");const d=new s({endpoint:t,region:r,credentials:{accessKeyId:o,secretAccessKey:n}});try{return yield d.send(new l({Bucket:i,Key:a+"/"+e})),!0}catch(e){return console.error(e),!1}}))}}class B{constructor(e,t){this.storagePath=t;let{username:r,password:i,url:o,dir:n}=e;n||(n="KoodoReader"),this.client=h(o,{authType:u.Password,username:r,password:i}),this.username=r,this.password=i,this.dir=n,this.taskQueue=new T(5)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}uploadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{!1===(yield this.client.exists(r.dirname(this.dir+"/"+i)))&&(yield this.client.createDirectory(r.dirname(this.dir+"/"+i)));let o=this.client.createWriteStream(this.dir+"/"+i);return t.createReadStream(r.join(this.storagePath,e)).pipe(o),new Promise(((e,t)=>{o.on("finish",(()=>{e(!0)})),o.on("error",(t=>{console.error(t),e(!1)}))}))}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{if(!1===(yield this.client.exists(this.dir+"/"+e)))return!0;let o=t.createWriteStream(r.join(this.storagePath,i));return this.client.createReadStream(this.dir+"/"+e).pipe(o),new Promise(((e,t)=>{o.on("finish",(()=>{e(!0)})),o.on("error",(t=>{e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){try{return(yield this.client.getDirectoryContents(this.dir+"/"+e)).map((e=>e.basename))}catch(t){return console.error("Error listing files:",t),t.response&&404===t.response.status&&(yield this.client.createDirectory(this.dir+"/"+e)),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){try{return yield this.client.deleteFile(this.dir+"/"+e),!0}catch(e){return console.error("Error deleting file:",e),!1}}))}}class M{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new T(5)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getClient(){return v(this,void 0,void 0,(function*(){if(this.client)return this.client;let{url:e,username:t,password:r,dir:i,port:o}=this.config;const n=new p;return yield n.connect({host:e,port:o,username:t,password:r}),this.client=n,n}))}uploadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:o}=this.config;o||(o="KoodoReader");let n=yield this.getClient();const s=()=>new Promise(((s,a)=>{let d=t.createReadStream(r.join(this.storagePath,e)),c="/"+o+"/"+i;n.put(d,c).then((()=>{s(!0)})).catch((e=>{console.error(e.message),s(!1)}))}));try{return yield s()}catch(e){return console.error(e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){let{dir:o}=this.config;o||(o="KoodoReader");let n=yield this.getClient();const s=()=>new Promise(((s,a)=>{let d="/"+o+"/"+e,c=t.createWriteStream(r.join(this.storagePath,i));n.get(d,c).then((()=>{s(!0)})).catch((e=>{console.error(e.message),s(!1)}))}));try{return yield s()}catch(e){return console.error(e),!1}}))))))}))}listFiles(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");let r=yield this.getClient();try{return yield new Promise(((i,o)=>{let n="/"+t+"/"+e;r.list(n).then((e=>{i(e.map((e=>e.name)))})).catch((e=>{console.error(e.message),i([])}))}))}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t||(t="KoodoReader");let r=yield this.getClient();try{return yield new Promise(((i,o)=>{let n="/"+t+"/"+e;r.delete(n).then((()=>{i(!0)})).catch((e=>{console.error(e.message),i(!1)}))}))}catch(e){return console.error(e),!1}}))}}class K{downloadFile(e,t){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}uploadFile(e,t){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e(!0)}))}))}listFiles(e){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e([])}))}))}authToken(e){return v(this,void 0,void 0,(function*(){return new Promise((e=>{e("")}))}))}getAuthUrl(){return""}}class z{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getFolderIdByPath(t){return v(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),i=t.split("/");let o="0";for(const t of i){const i=`https://api.box.com/2.0/folders/${o}/items?fields=id,name&type=folder&limit=1000`;try{const n=(yield e.get(i,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(n)o=n.id;else{const i={name:t,parent:{id:o},type:"folder"};o=(yield e.post("https://api.box.com/2.0/folders",i,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.id}}catch(e){return console.error("Error occurred during folder creation:",e),""}}return o}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken();let i=yield this.getFolderIdByPath("KoodoReader/"+t),o=[],n=0,s=!0;const a=1e3;for(;s;){const t=yield e.get(`https://api.box.com/2.0/folders/${i}/items`,{params:{limit:a,offset:n},headers:{Authorization:`Bearer ${r}`}}),d=t.data.entries||[];o=o.concat(d),n+=d.length,s=d.length===a&&t.data.total_count>n}return console.log(o.length,"items"),[...new Set(o.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=t.substring(0,t.lastIndexOf("/")),o=t.substring(t.lastIndexOf("/")+1),n=yield this.getFolderIdByPath("KoodoReader/"+i);if(!n)return!0;const s=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,a=(yield e.get(s,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===o&&"file"===e.type));return!a||(yield e.delete(`https://api.box.com/2.0/files/${a.id}`,{headers:{Authorization:`Bearer ${r}`}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}refreshToken(){return v(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"boxnet",refresh_token:e});this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("boxnet_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"boxnet",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:b,redirect_uri:E,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class N extends z{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=o.substring(0,o.lastIndexOf("/")),a=o.substring(o.lastIndexOf("/")+1),d=yield this.getFolderIdByPath("KoodoReader/"+s);if(!d)throw new Error("Folder not found");const c=yield this.listFiles(s);c.find((e=>e===a))&&(yield this.deleteFileWithoutQueue(s+"/"+a));const l=new f,h=JSON.stringify({name:a,parent:{id:d}});l.append("attributes",h),l.append("file",t.createReadStream(r.join(this.storagePath,i)));const u=yield e.post("https://upload.box.com/api/2.0/files/content",l,{headers:Object.assign({Authorization:`Bearer ${n}`},l.getHeaders()),maxContentLength:1/0,maxBodyLength:1/0});return!(u.status>=300)||(console.error("Error occurred during file upload:",u),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=i.substring(0,i.lastIndexOf("/")),a=i.substring(i.lastIndexOf("/")+1),d=yield this.getFolderIdByPath("KoodoReader/"+s);if(!d)return console.error("Folder not found"),!0;const c=`https://api.box.com/2.0/folders/${d}/items?fields=id,name&type=file&limit=1000`,l=(yield e.get(c,{headers:{Authorization:`Bearer ${n}`}})).data.entries.find((e=>e.name===a&&"file"===e.type));if(!l)return console.error("File not found:",a),!0;const h=yield e({url:`https://api.box.com/2.0/files/${l.id}/content`,method:"get",responseType:"stream",headers:{Authorization:`Bearer ${n}`}});return yield new Promise(((e,i)=>{const n=t.createWriteStream(r.join(this.storagePath,o));h.data.pipe(n),n.on("finish",e),n.on("error",i)})),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class D{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new T(3)}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getStorage(){return v(this,void 0,void 0,(function*(){if(this.storage)return this.storage;let{email:e,password:t}=this.config;return this.storage=yield new y({email:e,password:t}).ready,this.storage}))}getRoot(){return v(this,void 0,void 0,(function*(){if(this.root)return this.root;const e=(yield this.getStorage()).root;let t=e.children.find((e=>"KoodoReader"===e.name&&e.directory));return t||(t=yield e.mkdir("KoodoReader")),this.root=t,this.root}))}createFolder(e,t){return v(this,void 0,void 0,(function*(){const r=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(r))return yield this.folderCreationLocks.get(r);const i=(()=>v(this,void 0,void 0,(function*(){try{let r=e.children.find((e=>e.name===t&&e.directory));return r||(r=yield e.mkdir(t),r)}finally{this.folderCreationLocks.delete(r)}})))();return this.folderCreationLocks.set(r,i),yield i}))}listFiles(e){return v(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();if(e){const r=e.split("/").filter((e=>e));for(const e of r){const r=t.children.find((t=>t.name===e&&t.directory));if(!r)return[];t=r}}return t.children.filter((e=>!e.directory)).map((e=>e.name))}catch(e){return console.error("Error listing MEGA files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(e){return v(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();const r=e.split("/"),i=r.pop();for(const e of r){if(!e)continue;const r=t.children.find((t=>t.name===e&&t.directory));if(!r)return!0;t=r}const o=t.children.find((e=>e.name===i&&!e.directory));return!o||(yield o.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class Q extends D{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const n=i.split("/"),s=n.pop()||"";for(const e of n){if(!e)continue;let t=o.children.find((t=>t.name===e&&t.directory));t||(t=yield this.createFolder(o,e)),o=t}const a=o.children.find((e=>e.name===s&&!e.directory));a&&(yield a.delete());const d=t.createReadStream(r.join(this.storagePath,e)),c=t.statSync(r.join(this.storagePath,e)).size;return yield o.upload({name:s,size:c},d).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e,i){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{let o=yield this.getRoot();const n=e.split("/"),s=n.pop()||"";for(const e of n){if(!e)continue;const t=o.children.find((t=>t.name===e&&t.directory));if(!t)return!0;o=t}const a=o.children.find((e=>e.name===s&&!e.directory));if(!a)return!0;const d=t.createWriteStream(r.join(this.storagePath,i));return new Promise((e=>{a.download().pipe(d),d.on("finish",(()=>e(!0))),d.on("error",(t=>{console.error("Error writing file:",t),e(!1)}))}))}catch(e){return console.error("Error occurred during MEGA file download:",e),!1}}))))))}))}}class q{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new T(1)}retryOperation(e,t=5){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getDriveId(){return v(this,void 0,void 0,(function*(){if(this.driveId)return this.driveId;const t=yield this.refreshToken(),r=yield e.post("https://openapi.alipan.com/adrive/v1.0/user/getDriveInfo",{},{headers:{Authorization:`Bearer ${t}`}});return this.driveId=r.data.default_drive_id,this.driveId}))}getFolderIdByPath(t){return v(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),i=yield this.getDriveId();try{try{const o=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(o.data)return o.data.file_id}catch(o){const n=t.split("/").filter((e=>e));let s="",a="root";for(const t of n){s+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:s},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.file_id}catch(o){a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:i,parent_file_id:a,name:t,type:"folder",check_name_mode:"refuse"},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).data.file_id}}return a}}catch(e){return console.error("Error getting/creating folder by path:",e),""}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield this.getDriveId(),o=yield this.getFolderIdByPath("/KoodoReader/"+t);let n=[],s="",a=!0;for(;a;){const t=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:i,parent_file_id:o,marker:s||void 0},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),d=t.data.items||[];n=n.concat(d),s=t.data.next_marker,a=!!s&&100===d.length}return console.log("All items:",n.map((e=>e.name)),n.length),[...new Set(n.map((e=>e.name)))]}catch(e){return console.error("Error listing files:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield this.getDriveId(),o=yield this.getFolderIdByPath("/KoodoReader/"+t);return!o||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:i,file_id:o},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}checkExists(t){var r;return v(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken(),o=yield this.getDriveId(),n=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:o,file_path:t},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});(null===(r=n.data)||void 0===r?void 0:r.file_id)&&(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/recyclebin/trash",{drive_id:o,file_id:n.data.file_id},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}))}catch(e){}}))}refreshToken(){return v(this,void 0,void 0,(function*(){return this.config.access_token&&this.config.expires_at>(new Date).getTime()?this.config.access_token:(this.refreshTokenPromise||(this.refreshTokenPromise=(()=>v(this,void 0,void 0,(function*(){try{let e=this.config.refresh_token,t=yield this.thirdpartyRequest.refreshThirdToken({provider:"adrive",refresh_token:e});this.config.access_token=t.data.access_token,this.config.expires_at=(new Date).getTime()+1e3*t.data.expires_in,this.config.refresh_token=t.data.refresh_token;let r=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token})});return 200===r.code&&(yield this.thirdpartyRequest.TokenService.setToken("adrive_token",r.data.encrypted_token)),t.data.access_token}finally{this.refreshTokenPromise=null}})))()),this.refreshTokenPromise)}))}authToken(e){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"adrive",redirect_uri:E,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:x,redirect_uri:E,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class W extends q{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=yield this.getDriveId(),a=o.substring(0,o.lastIndexOf("/")),d=o.substring(o.lastIndexOf("/")+1);yield this.deleteFileWithoutQueue(o);const c=yield this.getFolderIdByPath("/KoodoReader/"+a),l=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:s,parent_file_id:c,name:d,type:"file",check_name_mode:"ignore"},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}}),{file_id:h,upload_id:u,part_info_list:p}=l.data,f=yield t.promises.readFile(r.join(this.storagePath,i));return yield fetch(p[0].upload_url,{method:"PUT",body:f,headers:{"Content-Length":t.statSync(r.join(this.storagePath,i)).size.toString()}}),yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/complete",{drive_id:s,file_id:h,upload_id:u},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=yield this.getDriveId(),a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:s,file_path:"/KoodoReader/"+i},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}})).data.file_id,d=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:s,file_id:a},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}}),c=yield e({url:d.data.url,method:"get",responseType:"stream"}),l=t.createWriteStream(r.join(this.storagePath,o));return c.data.pipe(l),new Promise((e=>{l.on("finish",(()=>{e(!0)})),l.on("error",(t=>{console.error("Error occurred during file download:",t),e(!1)}))}))}catch(e){return console.error("Error downloading file:",e),!1}}))))))}))}}class J{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new T(3)}retryOperation(e,t=5){return v(this,void 0,void 0,(function*(){let r=0;for(;;){const i=yield e();if(i)return i;if(r>=t)return i;r++;const o=1e3*Math.pow(2,r);console.info(`Retry attempt ${r} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}checkFolderExists(t,r){return v(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(t,r){return v(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/createfolderifnotexists",{params:{access_token:r,path:`/${t}`}})).data.result}catch(e){return console.error("Error creating folder:",e),!1}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:"/"+t,recursive:0}});return 0!==i.data.result?[]:i.data.metadata.contents.map((e=>e.name))}catch(e){return console.error("Error occurred during file list:",e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){return yield this.deleteFileWithoutQueue(e)}))))))}))}deleteFileWithoutQueue(t){return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),i=yield e.get("https://api.pcloud.com/deletefile",{params:{access_token:r,path:"/"+t}});return 0===i.data.result||(console.error("Error deleting file:",i.data),!0)}catch(e){return console.error("Error occurred during file delete:",e),!1}}))}refreshToken(){return v(this,void 0,void 0,(function*(){return this.config.refresh_token}))}authToken(e){return v(this,void 0,void 0,(function*(){return(yield this.thirdpartyRequest.authThirdToken({provider:"pcloud",redirect_uri:E,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${S}&response_type=code&redirect_uri=${E}`}}class H extends J{constructor(e,t,r){super(e,r),this.storagePath=t}uploadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=o.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(s,n))){if(!(yield this.createFolder(s,n)))return!1}const a=r.join(this.storagePath,i),d=t.createReadStream(a),c=t.statSync(a),l=r.basename(i),h=yield e({method:"put",url:"https://api.pcloud.com/uploadfile",params:{access_token:n,path:`/${s}`,renew:1,filename:l},data:d,headers:{"Content-Length":c.size,"Content-Type":"application/octet-stream"},maxContentLength:1/0,maxBodyLength:1/0});return 0===h.data.result||(console.error("Error uploading file:",h.data),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(i,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),s=yield e.get("https://api.pcloud.com/getfilelink",{params:{access_token:n,path:`/${i}`}});if(0!==s.data.result)return console.error("Error getting file link:",s.data),!0;const a=r.join(this.storagePath,o),d=t.createWriteStream(a),c=`https://${s.data.hosts[0]}${s.data.path}`,l=yield e({method:"get",url:c,responseType:"stream",maxContentLength:1/0,maxBodyLength:1/0});return new Promise((e=>{l.data.pipe(d),d.on("finish",(()=>{e(!0)})),d.on("error",(t=>{console.error("Error writing file:",t),e(!1)}))}))}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}const U=["book","config","cover","font"];class V{constructor(e,t,r,i){this.type=e,this.storagePath=r,this.remote="dropbox"===e?new C(t,r,i):"microsoft"===e?new I(t,r,i):"google"===e?new $(t,r,i):"s3compatible"===e?new j(t,r):"webdav"===e?new B(t,r):"ftp"===e?new A(t,r):"sftp"===e?new M(t,r):"boxnet"===e?new N(t,r,i):"mega"===e?new Q(t,r):"adrive"===e?new W(t,r,i):"pcloud"===e?new H(t,r,i):new K}downloadFile(e,i,o){return v(this,void 0,void 0,(function*(){return t.existsSync(r.join(this.storagePath+"/"+o))||t.mkdirSync(r.join(this.storagePath+"/"+o)),!!(yield this.listFiles(o)).find((t=>e.indexOf(t)>-1))&&(yield this.remote.downloadFile(o+"/"+e,o+"/"+i))}))}uploadFile(e,t,r){return v(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(r+"/"+e,r+"/"+t)}))}deleteFile(e,t){return v(this,void 0,void 0,(function*(){return yield this.remote.deleteFile(t+"/"+e)}))}isExist(e,t){return v(this,void 0,void 0,(function*(){return(yield this.listFiles(t)).find((t=>-1!==t.indexOf(e)))}))}listFiles(e){return v(this,void 0,void 0,(function*(){return yield this.remote.listFiles(e)}))}downloadAllFiles(){return v(this,void 0,void 0,(function*(){for(let e of U){let t=yield this.listFiles(e);for(let r of t)yield this.downloadFile(r,r,e)}}))}authToken(e){return v(this,void 0,void 0,(function*(){return yield this.remote.authToken(e)}))}getAuthUrl(){return this.remote.getAuthUrl()}getStats(){return this.remote.taskQueue.getStats()}resetCounters(){this.remote.taskQueue.resetCounters()}}const X={notes:"SELECT * FROM notes WHERE key = ?",bookmarks:"SELECT * FROM bookmarks WHERE key = ?",books:"SELECT * FROM books WHERE key = ?",plugins:"SELECT * FROM plugins WHERE key = ?",words:"SELECT * FROM words WHERE key = ?"},Y={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},G={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function Z(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const ee={notes:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),t.tag=JSON.parse(e.tag),t},bookmarks:e=>e,books:e=>e,plugins:e=>{let t=Object.assign({},e);return e.autoValue||delete t.autoValue,e.langList?t.langList=JSON.parse(e.langList):delete t.langList,e.voiceList?t.voiceList=JSON.parse(e.voiceList):delete t.voiceList,t.config=JSON.parse(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.parse(e.date),t}};var te={sqlStatement:{createTableStatement:Z({notes:'\n CREATE TABLE IF NOT EXISTS "notes" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "chapter" text,\n "chapterIndex" integer,\n "text" text,\n "cfi" text,\n "range" text,\n "notes" text,\n "percentage" text,\n "color" integer,\n "tag" array\n )\n ',bookmarks:'\n CREATE TABLE IF NOT EXISTS "bookmarks" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "cfi" text,\n "label" text,\n "percentage" text,\n "chapter" text\n );\n ',books:'\n CREATE TABLE IF NOT EXISTS "books" (\n "key" text PRIMARY KEY,\n "name" text,\n "author" text,\n "description" text,\n "md5" text,\n "cover" text,\n "format" text,\n "publisher" text,\n "size" integer,\n "page" integer,\n "path" text,\n "charset" text\n );\n ',plugins:'\n CREATE TABLE IF NOT EXISTS "plugins" (\n "key" text PRIMARY KEY,\n "type" text,\n "displayName" text,\n "icon" text,\n "version" text,\n "config" object,\n "autoValue" string,\n "langList" text,\n "voiceList" text,\n "scriptSHA256" text,\n "script" text\n );\n ',words:'\n CREATE TABLE IF NOT EXISTS "words" (\n "key" text PRIMARY KEY,\n "bookKey" text,\n "date" object,\n "word" text,\n "chapter" text\n );\n '}),getAllStatement:Z({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:Z({notes:"INSERT OR REPLACE INTO notes (key, bookKey, chapter, chapterIndex, text, cfi, range, notes, date, percentage, color, tag) VALUES (@key, @bookKey, @chapter, @chapterIndex, @text, @cfi, @range, @notes, @date, @percentage, @color, @tag)",bookmarks:"INSERT OR REPLACE INTO bookmarks (key, bookKey, cfi, label, percentage, chapter) VALUES (@key, @bookKey, @cfi, @label, @percentage, @chapter)",books:"INSERT OR REPLACE INTO books (key, name, author, description, md5, cover, format, publisher, size, page, path, charset) VALUES (@key, @name, @author, @description, @md5, @cover, @format, @publisher, @size, @page, @path, @charset)",plugins:"INSERT OR REPLACE INTO plugins (key, type, displayName, icon, version, config, autoValue, langList, voiceList, scriptSHA256, script) VALUES (@key, @type, @displayName, @icon, @version, @config, @autoValue, @langList, @voiceList, @scriptSHA256, @script)",words:"INSERT OR REPLACE INTO words (key, bookKey, date, word, chapter) VALUES (@key, @bookKey, @date, @word, @chapter)"}),deleteAllStatement:Z({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:Z({notes:"UPDATE notes SET bookKey = @bookKey, chapter = @chapter, chapterIndex = @chapterIndex, text = @text, cfi = @cfi, range = @range, notes = @notes, date = @date, percentage = @percentage, color = @color, tag = @tag WHERE key = @key",bookmarks:"UPDATE bookmarks SET bookKey = @bookKey, cfi = @cfi, label = @label, percentage = @percentage, chapter = @chapter WHERE key = @key",books:"UPDATE books SET name = @name, author = @author, description = @description, md5 = @md5, cover = @cover, format = @format, publisher = @publisher, size = @size, page = @page, path = @path, charset = @charset WHERE key = @key",plugins:"UPDATE plugins SET type = @type, displayName = @displayName, icon = @icon, version = @version, config = @config, autoValue = @autoValue, langList = @langList, voiceList = @voiceList, scriptSHA256 = @scriptSHA256, script = @script WHERE key = @key",words:"UPDATE words SET bookKey = @bookKey, date = @date, word = @word, chapter = @chapter WHERE key = @key"}),deleteStatement:Z({notes:"DELETE FROM notes WHERE key = ?",bookmarks:"DELETE FROM bookmarks WHERE key = ?",books:"DELETE FROM books WHERE key = ?",plugins:"DELETE FROM plugins WHERE key = ?",words:"DELETE FROM words WHERE key = ?"}),dropStatement:Z({notes:"DROP TABLE IF EXISTS notes",bookmarks:"DROP TABLE IF EXISTS bookmarks",books:"DROP TABLE IF EXISTS books",plugins:"DROP TABLE IF EXISTS plugins",words:"DROP TABLE IF EXISTS words"}),getStatement:Z(X),getByBookKeyStatement:Z(Y),getByBookKeysStatement:Z({notes:e=>`SELECT * FROM notes WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,bookmarks:e=>`SELECT * FROM bookmarks WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,words:e=>`SELECT * FROM words WHERE bookKey IN (${e.map((()=>"?")).join(",")})`,books:e=>`SELECT * FROM books WHERE key IN (${e.map((()=>"?")).join(",")})`}),deleteByBookKeyStatement:Z(G)},jsonToSqlite:Z({notes:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),t.tag=JSON.stringify(e.tag),t},bookmarks:e=>e,books:e=>{let t=Object.assign({},e);return t.page=e.page||0,t},plugins:e=>{let t=Object.assign({},e);return e.autoValue||(t.autoValue=null),e.langList?t.langList=JSON.stringify(e.langList):t.langList=null,e.voiceList?t.voiceList=JSON.stringify(e.voiceList):t.voiceList=null,t.config=JSON.stringify(e.config),t},words:e=>{let t=Object.assign({},e);return t.date=JSON.stringify(e.date),t}}),sqliteToJson:Z(ee)};const re="http://192.168.28.159:8000";class ie{constructor(e,t){this.processingQueue=!1,this.requestQueue=[],this.TokenService=e,this.ConfigService=t,this.refreshToken="",this.accessToken="",this.streamPromise=null}refreshUserToken(){return v(this,void 0,void 0,(function*(){if(this.refreshToken=yield this.TokenService.getToken("refresh_token"),!this.refreshToken)return{code:401,message:"refresh token not found"};let t=(yield e.post(re+"/api/v1/public/user/refresh_token",{refresh_token:this.refreshToken})).data;return 200===t.code&&(yield this.TokenService.setToken("access_token",t.data.access_token),yield this.TokenService.setToken("refresh_token",t.data.refresh_token),this.accessToken=t.data.access_token,this.refreshToken=t.data.refresh_token),t}))}requestWithRetry(e){return v(this,void 0,void 0,(function*(){return this.requestQueue||(this.requestQueue=[]),new Promise(((t,r)=>{this.requestQueue.push({config:e,resolve:t,reject:r}),this.processingQueue||this.processQueue()}))}))}processQueue(){return v(this,void 0,void 0,(function*(){if(!this.processingQueue){this.processingQueue=!0;try{for(;this.requestQueue.length>0;){const e=this.requestQueue.shift();try{let t=yield this.executeRequest(e.config);e.resolve(t)}catch(t){e.reject(t)}}}finally{this.processingQueue=!1}}}))}executeRequest(t){return v(this,void 0,void 0,(function*(){try{try{this.accessToken=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let r="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);t.baseURL=re,t.headers?(t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=r):t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":r};let i=(yield e(t)).data;if(402===i.code){let r=yield this.refreshUserToken();if(200===r.code){return t.headers=t.headers||{},t.headers.Authorization="Bearer "+this.accessToken,(yield e(t)).data}return r}return 200!==i.code&&this.ConfigService.setItem("errorLog",JSON.stringify({request:t.data,url:t.url,result:i,requestID:r})),i}catch(e){throw console.error("Request execution error:",e),e}}))}requestWithStream(e,t,r){return v(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>v(this,void 0,void 0,(function*(){try{let i="";try{i=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((n,s)=>{const a=new r(re+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+i,"X-Request-ID":o},method:e.method,body:JSON.stringify(e.data),pollingInterval:0});a.addEventListener("open",(()=>{console.info("Connection to OpenAI established.")})),a.addEventListener("message",(e=>v(this,void 0,void 0,(function*(){if(!e.data)return;const r=JSON.parse(e.data);r.done?(a.close(),n(r)):(402===r.code&&(yield this.refreshUserToken()),t(r.data))})))),a.addEventListener("error",(e=>{console.error("Error:",e),n({code:500,message:"internal error"}),a.close()}))}))}finally{this.streamPromise=null}})))()),this.streamPromise}))}requestWithFetch(e,t){return v(this,void 0,void 0,(function*(){return this.streamPromise||(this.streamPromise=(()=>v(this,void 0,void 0,(function*(){try{let r="";try{r=(yield this.TokenService.getToken("access_token"))||""}catch(e){console.error("Error get Token:",e)}let i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((o,n)=>v(this,void 0,void 0,(function*(){const n=yield fetch(re+e.url,{method:"POST",headers:{"Content-Type":"text/event-stream",Authorization:"Bearer "+r,"X-Request-ID":i},body:JSON.stringify(e.data)});if(!n.body)throw new Error("Response body is null");const s=n.body.pipeThrough(new TextDecoderStream).getReader();for(;;){const{value:e,done:r}=yield s.read();if(r){t({done:!0});break}if(e)if(e.includes('"code":400')||e.includes('"code":401')||e.includes('"code":402')){let t=JSON.parse(e);402===t.code&&(yield this.refreshUserToken()),o(t)}else e.split("\n").forEach((e=>{if(e.startsWith("data:")){const r=JSON.parse(e.substring(5));t(r.data)}}))}}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}class oe extends ie{constructor(e,t){super(e,t)}encryptToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/encrypt_token",data:e};return yield this.requestWithRetry(t)}))}decryptToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/decrypt_token",data:e};return yield this.requestWithRetry(t)}))}authThirdToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/auth_token",data:e};return yield this.requestWithRetry(t)}))}refreshThirdToken(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/refresh_token",data:e};return yield this.requestWithRetry(t)}))}s3Upload(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_upload",data:e};return yield this.executeRequest(t)}))}s3Download(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_download",data:e};return yield this.executeRequest(t)}))}s3List(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_list",data:e};return yield this.executeRequest(t)}))}s3Delete(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/s3_delete",data:e};return yield this.executeRequest(t)}))}getSyncState(){return v(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/pro/thirdparty/get_sync_state"})}))}deleteSyncState(){return v(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"post",url:"/api/v1/pro/thirdparty/delete_sync_state"})}))}}const ne=new g;class se{static encrypt(e,t){let r="";for(let i=0;i-1&&r.splice(i,1),this.setAllListConfig(r,t)}static setListConfig(e,t){let r=this.getAllListConfig(t);const i=r.indexOf(e);i>-1?(r.splice(i,1),r.unshift(e)):r.unshift(e),this.setAllListConfig(r,t)}static setAllListConfig(e,t,r=!0){this.setItem(t,JSON.stringify(e)),r&&this.setSyncRecord({type:"config",catergory:"listConfig",name:"general",key:t},{operation:"update",time:Date.now()})}static setObjectConfig(e,t,r,i=!0){let o=this.getAllObjectConfig(r);o[e]=t,i&&this.setSyncRecord({type:"config",catergory:"objectConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllObjectConfig(o,r)}static getObjectConfig(e,t,r){return this.getAllObjectConfig(t)[e]||r}static getAllObjectConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static setAllObjectConfig(e,t){this.setItem(t,JSON.stringify(e))}static deleteObjectConfig(e,t){let r=this.getAllObjectConfig(t);delete r[e],this.setSyncRecord({type:"config",catergory:"objectConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllObjectConfig(r,t)}static getAllMapConfig(e){let t=this.getItem(e);return JSON.parse(t)||{}}static getMapConfig(e,t){return this.getAllMapConfig(t)[e]||[]}static setAllMapConfig(e,t){this.setItem(t,JSON.stringify(e))}static setMapConfig(e,t,r){let i=this.getAllMapConfig(r);void 0===i[e]&&(i[e]=[]),t&&-1===i[e].indexOf(t)&&i[e].unshift(t),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(i,r)}static setOneMapConfig(e,t,r,i=!0){let o=this.getAllMapConfig(r);o[e]=t,i&&this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,r)}static deleteFromMapConfig(e,t,r){let i=this.getAllMapConfig(r),o=i[e].indexOf(t);i[e].splice(o,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(i,r)}static deleteFromAllMapConfig(e,t){let r=this.getAllMapConfig(t);Object.keys(r).forEach((i=>{let o=r[i].indexOf(e);o>-1&&(r[i].splice(o,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:i},{operation:"update",time:Date.now()}))})),this.setAllMapConfig(r,t)}static deleteMapConfig(e,t){let r=this.getAllMapConfig(t);delete r[e],this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllMapConfig(r,t)}static getFromAllMapConfig(e,t){let r=this.getAllMapConfig(t),i=[];for(let t in r)r[t]&&r[t].indexOf(e)>-1&&i.push(t);return i}static getSyncRecord(e){return JSON.parse(this.getItem("syncRecord")||"{}")[e.type+"."+e.catergory+"."+e.name+"."+e.key]||{operation:"",time:0}}static getAllSyncRecord(){return JSON.parse(this.getItem("syncRecord")||"{}")}static setSyncRecord(e,t){let r=JSON.parse(this.getItem("syncRecord")||"{}");r[e.type+"."+e.catergory+"."+e.name+"."+e.key]=t,this.setItem("syncRecord",JSON.stringify(r))}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}});var ce,le;export{de as ConfigService,te as SqlStatement,V as SyncUtil,oe as ThirdpartyRequest,se as TokenService}; diff --git a/src/assets/lib/kookit.min.js b/src/assets/lib/kookit.min.js index e23406db..833a84c0 100644 --- a/src/assets/lib/kookit.min.js +++ b/src/assets/lib/kookit.min.js @@ -1 +1 @@ -import e from"chinese-s2t";import t from"underscore";import i from"rangy/lib/rangy-core.js";import"rangy/lib/rangy-textrange";import r from"jszip";import{unzlibSync as n}from"fflate";import o from"chardet";import s from"js-untar";import a from"mammoth";import{marked as l}from"marked";import c from"mhtml2html";function d(e,t,i,r){return new(i||(i=Promise))((function(n,o){function s(e){try{l(r.next(e))}catch(e){o(e)}}function a(e){try{l(r.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}l((r=r.apply(e,t||[])).next())}))}const h=e=>e?parseFloat(e+""):0,u=(e,t)=>d(void 0,void 0,void 0,(function*(){let i="";if(e.load){let t=yield fetch(yield e.load()).then((e=>e.blob()));i=yield t.text()}return t||(e.loadAsset&&(i=yield p(i,e.loadAsset)),i=g(i)),i})),f=e=>Array.from(e.querySelectorAll("img, image")),p=(e,t)=>d(void 0,void 0,void 0,(function*(){let i=(new DOMParser).parseFromString(e,"text/html"),r=f(i);for(let e=0;e{var t;let i=(new DOMParser).parseFromString(e,"text/html"),r=f(i);if(0===r.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)},y=(e,t)=>({totalPage:"scroll"===e?1:"single"===e?Math.round(parseFloat(t.body.scrollWidth/t.body.clientWidth+"")):2*Math.round(parseFloat(t.body.scrollWidth/t.body.clientWidth+"")),currentPage:Math.round(parseFloat(h(t.body.scrollLeft)/t.body.clientWidth+""))+1}),b=e=>{let t=e.querySelectorAll("a, article, cite, div, li, p, span, pre, table, bold, font");for(let e=0;ed(void 0,void 0,void 0,(function*(){const t=new Image;t.src=e;try{yield t.decode()}catch(e){console.error(e)}return t})),v=(e,t,i,r)=>d(void 0,void 0,void 0,(function*(){let n=Math.floor(e.clientWidth/12),o=n%2==0?n:n-1,s=r.querySelectorAll("img, image");for(let n of s){let s=n.parentElement,a=0,l=0,c=n.naturalWidth,d=n.naturalHeight;if("image"===n.tagName){let e=yield w(n.getAttribute("xlink:href"));c=e.naturalWidth,d=e.naturalHeight}if(i.startsWith("CB")&&"scroll"===t)l=s.offsetWidth;else if(i.startsWith("CB")&&"single"===t)a=e.clientHeight,l=e.clientWidth;else if(s&&c&&d){d/c>s.clientHeight/s.clientWidth?(a=s.clientHeight,l=parseInt(a*c/d+"")):(l=s.clientWidth,a=parseInt(l*d/c+"")),a>r.body.clientHeight&&(l=parseInt(l*(r.body.clientHeight/a)+""),a=r.body.clientHeight)}else s&&s.clientWidth&&s.clientWidth>0?(l=s.clientWidth,a=s.clientHeight):(l=e.clientWidth,a=e.clientHeight);l=l?Math.min("scroll"===t||"single"===t?e.clientWidth:(e.clientWidth-o)/2,l):"scroll"===t||"single"===t?e.clientWidth:(e.clientWidth-o)/2,c&&d&&(c>d||a/l>d/c?a=l*(d/c):l=a*(c/d)),(l||a)&&n.setAttribute("style",(n.getAttribute("style")?n.getAttribute("style"):"")+";"+`max-width: ${l>0?l+"px":""};max-height:${a>0?a+"px":""}; margin: 0 auto; ${i.startsWith("CB")?`margin-left: calc(100% - ${n.clientWidth}px);`:""}`),i.startsWith("CB")&&"scroll"===t&&n.setAttribute("style",(n.getAttribute("style")?n.getAttribute("style"):"")+";margin-left: 0px; width: 100%;"),i.startsWith("CB")&&"scroll"!==t&&n.setAttribute("style",(n.getAttribute("style")?n.getAttribute("style"):"")+`;margin-left: calc(50% - ${n.getBoundingClientRect().width/2}px);`)}})),x=(e,t,i)=>{let r=i.createElement("style");if(r.id="default-style",r.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}",i.head.appendChild(r),"scroll"===t)return;let n="double"===t?2:1,o=Math.floor(e.clientWidth/12),s=o%2==0?o:o-1;i.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;touch-action: pan-y; overscroll-behavior: none;max-width: inherit;column-fill: auto;column-gap: ${s}px; column-width: ${(e.clientWidth-s)/n}px;`)};const C=e=>"string"==typeof e||e instanceof String;class L{constructor(e){this.book=e,this.chapterList=[],this.flattenChapters=[],this.chapterDocList=[]}unescapeHtml(e){if(!e)return"";return(new DOMParser).parseFromString(e,"text/html").documentElement.textContent||""}getChapter(e){return d(this,void 0,void 0,(function*(){return this.chapterList=e?yield Promise.all(e.map((e=>d(this,void 0,void 0,(function*(){let t=-1;try{t=e.href&&(yield this.book.resolveHref(e.href))?(yield this.book.resolveHref(e.href)).index:-1}catch(e){console.error(e)}return{label:this.unescapeHtml(e.label)?this.unescapeHtml(e.label):t+"",href:e.href?e.href:"title"+t,index:t,subitems:e.subitems?yield this.getChapter(e.subitems):[]}}))))):yield Promise.all(this.book.sections.map(((e,t)=>d(this,void 0,void 0,(function*(){return{label:this.unescapeHtml(e.label)?this.unescapeHtml(e.label):t+"",href:e.href?e.href:"title"+t,index:t,subitems:e.subitems?yield this.getChapter(e.subitems):[]}}))))),this.flattenChapters=this.flatChapter(this.chapterList),this.chapterList}))}getChapterDoc(){return d(this,void 0,void 0,(function*(){const e=this.flattenChapters.map((e=>e.index));return this.book.sections.map(((t,i)=>e.indexOf(i)>-1?{label:this.unescapeHtml(this.flattenChapters[e.indexOf(i)].label),href:this.flattenChapters[e.indexOf(i)].href,text:t}:{label:"",href:"",text:t}))}))}flatChapter(e){let t=[];for(let i=0;i0?(t.push(e[i]),t=t.concat(this.flatChapter(e[i].subitems))):t.push(e[i]);return t}getMetadata(){return new Promise(((e,t)=>d(this,void 0,void 0,(function*(){const i=this.book.metadata;let r=i.author&&i.author[0]&&i.author[0].name&&C(i.author[0].name)?i.author[0].name:i.author&&i.author[0]&&C(i.author[0])?i.author[0]:i.author&&C(i.author)?i.author:"";try{const t=yield this.book.getCover();var n=new FileReader;n.readAsDataURL(t),n.onloadend=()=>{e({name:i.title,author:r,description:i.description,publisher:i.publisher,cover:n.result})}}catch(n){console.error(n);try{e({name:i.title,author:r,description:i.description,publisher:i.publisher,cover:""})}catch(e){console.error(e),t(e)}}}))))}}const T=(e,t)=>[-1,...t,e.length].reduce((({xs:t,a:i},r)=>({xs:t?.concat([e.slice(i+1,r)])??[],a:r})),{}).xs,S=/\d/,M=/^epubcfi\((.*)\)$/,A=e=>e.replace(/[\^[\](),;=]/g,"^$&"),k=(e,t)=>{return i=([e])=>e===t,e.map(((e,t,r)=>i(e,t,r)?t:null)).filter((e=>null!=e));var i},E=e=>{const t=[];let i;for(const[r,n]of e){if("/"===r)t.push({index:n});else{const e=t[t.length-1];if(":"===r)e.offset=n;else if("~"===r)e.temporal=n;else if("@"===r)e.spatial=(e.spatial??[]).concat(n);else if(";s"===r)e.side=n;else if("["===r){if("/"!==i||!n){e.text=(e.text??[]).concat(n);continue}e.id=n}}i=r}return t},D=e=>T(e,k(e,"!")).map(E),R=e=>{const t=(e=>{const t=[];let i,r,n="";const o=e=>(t.push(e),i=null,n=""),s=e=>(n+=e,r=!1);for(const t of Array.from(e.trim()).concat(""))if("^"!==t||r){if("!"===i)o(["!"]);else if(","===i)o([","]);else if("/"===i||":"===i){if(S.test(t)){s(t);continue}o([i,parseInt(n)])}else if("~"===i){if(S.test(t)||"."===t){s(t);continue}o(["~",parseFloat(n)])}else if("@"===i){if(":"===t){o(["@",parseFloat(n)]),i="@";continue}if(S.test(t)||"."===t){s(t);continue}o(["@",parseFloat(n)])}else{if("["===i){";"!==t||r?","!==t||r?"]"!==t||r?s(t):o(["[",n]):(o(["[",n]),i="["):(o(["[",n]),i=";");continue}if(i?.startsWith(";")){"="!==t||r?";"!==t||r?"]"!==t||r?s(t):o([i,n]):(o([i,n]),i=";"):(i=`;${n}`,n="");continue}}"/"!==t&&":"!==t&&"~"!==t&&"@"!==t&&"["!==t&&"!"!==t&&","!==t||(i=t)}else r=!0;return t})((i=e,i.match(M)?.[1]??i));var i;const r=k(t,",");if(!r.length)return D(t);const[n,o,s]=T(t,r).map(D);return{parent:n,start:o,end:s}},I=({index:e,id:t,offset:i,temporal:r,spatial:n,text:o,side:s})=>{const a=s?`;s=${s}`:"";return`/${e}`+(t?`[${A(t)}${a}]`:"")+(null!=i&&e%2?`:${i}`:"")+(r?`~${r}`:"")+(n?`@${n.join(":")}`:"")+(o||!t&&s?"["+(o?.map(A)?.join(",")??"")+a+"]":"")},N=e=>e.parent?[e.parent,e.start,e.end].map(N).join(","):e.map((e=>e.map(I).join(""))).join("!"),B=e=>{return t=N(e),M.test(t)?t:`epubcfi(${t})`;var t},O=(e,t)=>{return"string"==typeof e?B(O(R(e),t)):e.parent?(i=e.parent,r=e[t?"end":"start"],i.slice(0,-1).concat([i[i.length-1].concat(r[0])]).concat(r.slice(1))):e;var i,r},H=({nodeType:e})=>3===e||4===e,P=({nodeType:e})=>1===e,F=e=>{const t=Array.from(e.childNodes).filter((e=>H(e)||P(e))).reduce(((e,t)=>{let i=e[e.length-1];return i?H(t)?Array.isArray(i)?i.push(t):H(i)?e[e.length-1]=[i,t]:e.push(t):P(i)?e.push(null,t):e.push(t):e.push(t),e}),[]);return P(t[0])&&t.unshift("first"),P(t[t.length-1])&&t.push("last"),t.unshift("before"),t.push("after"),t},$=(e,t)=>e?F(e)[t]:null,U=(e,t)=>{const{id:i}=t[t.length-1];if(i){const t=e.ownerDocument.getElementById(i);if(t)return{node:t,offset:0}}for(const{index:i}of t){const t=$(e,i);if("first"===t)return{node:e.firstChild??e};if("last"===t)return{node:e.lastChild??e};if("before"===t)return{node:e,before:!0};if("after"===t)return{node:e,after:!0};e=t}const{offset:r}=t[t.length-1];if(!Array.isArray(e))return{node:e,offset:r};let n=0;for(const t of e){const{length:e}=t.nodeValue;if(n+e>=r)return{node:t,offset:r-n};n+=e}},j=(e,t)=>{const{parentNode:i,id:r}=e,n=F(i),o=n.findIndex((t=>Array.isArray(t)?t.some((t=>t===e)):t===e)),s=n[o];if(Array.isArray(s)){let i=0;for(const r of s){if(r===e){i+=t;break}i+=r.nodeValue.length}t=i}const a={id:r,index:o,offset:t};return i!==e.ownerDocument.documentElement?j(i).concat(a):[a]},W=(e,t)=>U(e.documentElement,O(t)).node,q="urn:oasis:names:tc:opendocument:xmlns:container",z="http://www.w3.org/1999/xhtml",X="http://www.idpf.org/2007/opf",V="http://www.idpf.org/2007/ops",J="http://purl.org/dc/elements/1.1/",G="http://www.w3.org/2001/04/xmlenc#",Z="http://www.daisy.org/z3986/2005/ncx/",_="http://www.w3.org/1999/xlink",Y="http://www.w3.org/ns/SMIL",K={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)/},Q=e=>e.toLowerCase().replace(/[-:](.)/g,((e,t)=>t.toUpperCase())),ee=(e,t,i)=>i?i=>i.getAttribute(e)?.split(/\s/)?.includes(t):"function"==typeof t?i=>t(i.getAttribute(e)):i=>i.getAttribute(e)===t,te=(...e)=>t=>t?Object.fromEntries(e.map((e=>[Q(e),t.getAttribute(e)]))):null,ie=e=>{return t=e?.textContent,t?t.trim().replace(/\s{2,}/g," "):"";var t},re=(e,t)=>{const i=e.lookupNamespaceURI(null)===t||e.lookupPrefix(t),r=i?(e,i)=>e=>e.namespaceURI===t&&e.localName===i:(e,t)=>e=>e.localName===t;return{$:(e,t)=>[...e.children].find(r(e,t)),$$:(e,t)=>[...e.children].filter(r(e,t)),$$$:i?(e,i)=>[...e.getElementsByTagNameNS(t,i)]:(e,i)=>[...e.getElementsByTagName(t,i)]}},ne=(e,t)=>{try{if(t.includes(":"))return new URL(e,t);const i="whatever://whatever/";return decodeURI(new URL(e,i+t).href.replace(i,""))}catch(t){return console.warn(t),e}},oe=e=>/^(?!blob)\w+:/i.test(e),se=async(e,t,i)=>{const r=[];e.replace(t,((...e)=>(r.push(e),null)));const n=[];for(const e of r)n.push(await i(...e));return e.replace(t,(()=>n.shift()))},ae=e=>e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),le={attrs:["dir","xml:lang"]},ce={name:"alternate-script",many:!0,...le,props:["file-as"]},de={many:!0,...le,props:[{name:"role",many:!0,attrs:["scheme"]},"file-as",ce]},he=[{name:"title",many:!0,...le,props:["title-type","display-seq","file-as",ce]},{name:"identifier",many:!0,props:[{name:"identifier-type",attrs:["scheme"]}]},{name:"language",many:!0},{name:"creator",...de},{name:"contributor",...de},{name:"publisher",...le,props:["file-as",ce]},{name:"description",...le,props:[ce]},{name:"rights",...le,props:[ce]},{name:"date"},{name:"dcterms:modified",type:"meta"},{name:"subject",many:!0,...le,props:["term","authority",ce]},{name:"belongs-to-collection",type:"meta",many:!0,...le,props:["collection-type","group-position","dcterms:identifier","file-as",ce,{name:"belongs-to-collection",recursive:!0}]}],ue=(e,t=e=>e)=>{const{$:i,$$:r,$$$:n}=re(e,z),o=e=>r=>{const n=i(r,"a")??i(r,"span"),o=i(r,"ol"),a=(e=>e?decodeURI(t(e)):null)(n?.getAttribute("href")),l={label:ie(n)||n?.getAttribute("title"),href:a,subitems:s(o)};return e&&(l.type=n?.getAttributeNS(V,"type")?.split(/\s/)),l},s=(e,t)=>e?r(e,"li").map(o(t)):null,a=(e,t)=>s(i(e,"ol"),t),l=n(e,"nav");let c=null,d=null,h=null,u=[];for(const e of l){const t=e.getAttributeNS(V,"type")?.split(/\s/)??[];t.includes("toc")?c??=a(e):t.includes("page-list")?d??=a(e):t.includes("landmarks")?h??=a(e,!0):u.push({label:ie(e.firstElementChild),type:t,list:a(e)})}return{toc:c,pageList:d,landmarks:h,others:u}},fe=(e,t=e=>e)=>{const{$:i,$$:r}=re(e,Z),n=e=>{const o=i(e,"navLabel"),s=i(e,"content"),a=ie(o),l=(e=>e?decodeURI(t(e)):null)(s.getAttribute("src"));if("navPoint"===e.localName){const t=r(e,"navPoint");return{label:a,href:l,subitems:t.length?t.map(n):null}}return{label:a,href:l}},o=(e,t)=>r(e,t).map(n),s=(t,r)=>{const n=i(e.documentElement,t);return n?o(n,r):null};return{toc:s("navMap","navPoint"),pageList:s("pageList","pageTarget"),others:r(e.documentElement,"navList").map((e=>({label:ie(i(e,"navLabel")),list:o(e,"navTarget")})))}},pe=e=>{if(!e)return;const t=e.split(":").map((e=>parseFloat(e)));if(3===t.length){const[e,i,r]=t;return 60*e*60+60*i+r}if(2===t.length){const[e,i]=t;return 60*e+i}const[i,r]=e.split(/(?=[^\d.])/);return parseFloat(i)*("h"===r?3600:"min"===r?60:"ms"===r?.001:1)},ge=/([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/,me=e=>ie(e.getElementById(e.documentElement.getAttribute("unique-identifier"))??e.getElementsByTagNameNS(J,"identifier")[0]),ye=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{const t=(new TextEncoder).encode(e),i=await globalThis.crypto.subtle.digest("SHA-1",t);return new Uint8Array(i)},we=(e=be)=>({"http://www.idpf.org/2008/embedding":{key:t=>e(me(t).replaceAll(/[\u0020\u0009\u000d\u000a]/g,"")),decode:(e,t)=>ye(e,1040,t)},"http://ns.adobe.com/pdf/enc#RC":{key:e=>{const t=(e=>{for(const t of e.getElementsByTagNameNS(J,"identifier")){const[e]=ie(t).split(":").slice(-1);if(ge.test(e))return e}return""})(e).replaceAll("-","");return Uint8Array.from({length:16},((e,i)=>parseInt(t.slice(2*i,2*i+2),16)))},decode:(e,t)=>ye(e,1024,t)}});class ve{#e=new Map;#t=new Map;#i;constructor(e){this.#i=e}async init(e,t){if(!e)return;const i=Array.from(e.getElementsByTagNameNS(G,"EncryptedData"),(e=>({algorithm:e.getElementsByTagNameNS(G,"EncryptionMethod")[0]?.getAttribute("Algorithm"),uri:e.getElementsByTagNameNS(G,"CipherReference")[0]?.getAttribute("URI")})));for(const{algorithm:e,uri:r}of i){if(!this.#t.has(e)){const i=this.#i[e];if(!i){console.warn("Unknown encryption algorithm");continue}const r=await i.key(t);this.#t.set(e,(e=>i.decode(r,e)))}this.#e.set(r,e)}}getDecoder(e){return this.#t.get(this.#e.get(e))??(e=>e)}}class xe{constructor({opf:e,resolveHref:t}){this.opf=e;const{$:i,$$:r,$$$:n}=re(e,X),o=i(e.documentElement,"manifest"),s=i(e.documentElement,"spine"),a=r(s,"itemref");this.manifest=r(o,"item").map(te("href","id","media-type","properties","media-overlay")).map((e=>(e.href=t(e.href),e.properties=e.properties?.split(/\s/),e))),this.spine=a.map(te("idref","id","linear","properties")).map((e=>(e.properties=e.properties?.split(/\s/),e))),this.pageProgressionDirection=s.getAttribute("page-progression-direction"),this.navPath=this.getItemByProperty("nav")?.href,this.ncxPath=(this.getItemByID(s.getAttribute("toc"))??this.manifest.find((e=>e.mediaType===K.NCX)))?.href;const l=i(e.documentElement,"guide");l&&(this.guide=r(l,"reference").map(te("type","title","href")).map((({type:e,title:i,href:r})=>({label:i,type:e.split(/\s/),href:t(r)})))),console.log(this),this.cover=this.getItemByProperty("cover-image")??this.getItemByID("cover-image")??this.getItemByID(n(e,"meta").find(ee("name","cover"))?.getAttribute("content"))??this.getItemByID("cover")??this.getItemByHref(this.guide?.find((e=>e.type.includes("cover")&&!e.href.includes("html")&&!e.href.includes("xml")))?.href),this.cfis=(e=>{const t=[],{parentNode:i}=e[0],r=j(i);for(const[n,o]of F(i).entries()){const i=e[t.length];o===i&&t.push(B([r.concat({id:i.id,index:n})]))}return t})(a)}getItemByID(e){return this.manifest.find((t=>t.id===e))}getItemByHref(e){return this.manifest.find((t=>t.href===e))}getItemByProperty(e){return this.manifest.find((t=>t.properties?.includes(e)))}resolveCFI(e){const t=R(e),i=(t.parent??t).shift();let r=W(this.opf,i);r&&"idref"!==r.nodeName&&(i.at(-1).id=null,r=W(this.opf,i));const n=r?.getAttribute("idref");return{index:this.spine.findIndex((e=>e.idref===n)),anchor:e=>((e,t)=>{const i=O(t),r=O(t,!0),n=e.documentElement,o=U(n,i[0]),s=U(n,r[0]),a=e.createRange();return o.before?a.setStartBefore(o.node):o.after?a.setStartAfter(o.node):a.setStart(o.node,o.offset),s.before?a.setEndBefore(s.node):s.after?a.setEndAfter(s.node):a.setEnd(s.node,s.offset),a})(e,t)}}}class Ce{#r=new Map;#n=new Map;#o=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"";const n=URL.createObjectURL(new Blob([t],{type:i}));if(this.#r.set(e,n),this.#o.set(e,1),r){const t=this.#n.get(r);t?t.push(e):this.#n.set(r,[e])}return n}ref(e,t){const i=this.#n.get(t);return i?.includes(e)||(this.#o.set(e,this.#o.get(e)+1),i?i.push(e):this.#n.set(t,[e])),this.#r.get(e)}unref(e){if(!this.#o.has(e))return;const t=this.#o.get(e)-1;if(t<1){URL.revokeObjectURL(this.#r.get(e)),this.#r.delete(e),this.#o.delete(e);const t=this.#n.get(e);if(t)for(;t.length;)this.unref(t.pop());this.#n.delete(e)}else this.#o.set(e,t)}async loadItem(e,t=[]){if(!e)return null;const{href:i,mediaType:r}=e,n=K.JS.test(e.mediaType);if(n&&!this.allowScript)return null;const o=t.at(-1);if(this.#r.has(i))return this.ref(i,o);return(n||[K.XHTML,K.HTML,K.CSS,K.SVG].includes(r))&&t.every((e=>e!==i))?this.loadReplaced(e,t):this.createURL(i,await this.loadBlob(i),r,o)}async loadHref(e,t,i=[]){if(oe(e))return e;const r=ne(e,t);let n=this.manifest.find((e=>e.href===r));return n||(n={href:r,mediaType:""}),this.loadItem(n,i.concat(t))}async loadReplaced(e,t=[]){const{href:i,mediaType:r}=e,n=t.at(-1),o=await this.loadText(i);if(!o)return null;if([K.XHTML,K.HTML,K.SVG].includes(r)){let s=(new DOMParser).parseFromString(o,r);if(r===K.XHTML&&s.querySelector("parsererror")&&(console.warn(s.querySelector("parsererror").innerText),e.mediaType=K.HTML,s=(new DOMParser).parseFromString(o,e.mediaType)),[K.XHTML,K.SVG].includes(e.mediaType)){let e=s.firstChild;for(;e instanceof ProcessingInstruction;){if(e.data){const r=await se(e.data,/(?:^|\s*)(href\s*=\s*['"])([^'"]*)(['"])/i,((e,r,n,o)=>this.loadHref(n,i,t).then((e=>`${r}${e}${o}`))));e.replaceWith(s.createProcessingInstruction(e.target,r))}e=e.nextSibling}}const a=async(e,r)=>e.setAttribute(r,await this.loadHref(e.getAttribute(r),i,t));for(const e of s.querySelectorAll("link[href]"))await a(e,"href");for(const e of s.querySelectorAll("[src]"))await a(e,"src");for(const e of s.querySelectorAll("[poster]"))await a(e,"poster");for(const e of s.querySelectorAll("object[data]"))await a(e,"data");for(const e of s.querySelectorAll("[*|href]:not([href]"))e.setAttributeNS(_,"href",await this.loadHref(e.getAttributeNS(_,"href"),i,t));for(const e of s.querySelectorAll("style"))e.textContent&&(e.textContent=await this.replaceCSS(e.textContent,i,t));for(const e of s.querySelectorAll("[style]"))e.setAttribute("style",await this.replaceCSS(e.getAttribute("style"),i,t));const l=(new XMLSerializer).serializeToString(s);return this.createURL(i,l,e.mediaType,n)}const s=r===K.CSS?await this.replaceCSS(o,i,t):await this.replaceString(o,i,t);return this.createURL(i,s,r,n)}async replaceCSS(e,t,i=[]){const r=await se(e,/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,((e,r)=>this.loadHref(r,t,i).then((e=>`url("${e}")`)))),n=await se(r,/@import\s*["']([^"'\n]*?)["']/gi,((e,r)=>this.loadHref(r,t,i).then((e=>`@import "${e}"`)))),o=window?.innerWidth??800,s=window?.innerHeight??600;return n.replace(/-epub-/gi,"").replace(/(\d*\.?\d+)vw/gi,((e,t)=>parseFloat(t)*o/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,t,i=[]){const r=new Map,n=this.assets.map((e=>{if(e.href===t)return;const i=((e,t)=>{if(!e)return t;const i=e.replace(/\/$/,"").split("/"),r=t.replace(/\/$/,"").split("/"),n=(i.length>r.length?i:r).findIndex(((e,t)=>i[t]!==r[t]));return n<0?"":Array(i.length-n).fill("..").concat(r.slice(n)).join("/")})((e=>e.slice(0,e.lastIndexOf("/")+1))(t),e.href),n=encodeURI(i),o="/"+e.href,s=encodeURI(o),a=new Set([i,n,o,s]);for(const t of a)r.set(t,e);return Array.from(a)})).flat().filter((e=>e));if(!n.length)return e;const o=new RegExp(n.map(ae).join("|"),"g");return se(e,o,(async e=>this.loadItem(r.get(e.replace(/^\//,"")),i.concat(t))))}unloadItem(e){this.unref(e?.href)}}const Le=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"}};class Te{parser=new DOMParser;#s;constructor({loadText:e,loadBlob:t,getSize:i,sha1:r}){this.loadText=e,this.loadBlob=t,this.getSize=i,this.#s=new ve(we(r))}#a(e){return e&&e.includes("opf:scheme")&&(e=e.replaceAll("opf:scheme","scheme")),e?this.parser.parseFromString(e,K.XML):null}async#l(e){return this.#a(await this.loadText(e))}async init(){const e=await this.#l("META-INF/container.xml");if(!e)throw new Error("Failed to load container file");const t=Array.from(e.getElementsByTagNameNS(q,"rootfile"),te("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,r=await this.#l(i);if(!r)throw new Error("Failed to load package document");const n=await this.#l("META-INF/encryption.xml");await this.#s.init(n,r),this.resources=new xe({opf:r,resolveHref:e=>ne(e,i)});const o=new Ce({loadText:this.loadText,loadBlob:e=>Promise.resolve(this.loadBlob(e)).then(this.#s.getDecoder(e)),resources:this.resources});this.sections=this.resources.spine.map(((e,t)=>{const{idref:i,linear:r,properties:n=[]}=e,s=this.resources.getItemByID(i);return s?{id:this.resources.getItemByID(i)?.href,load:()=>o.loadItem(s),unload:()=>o.unloadItem(s),createDocument:()=>this.loadDocument(s),size:this.getSize(s.href),cfi:this.resources.cfis[t],linear:r,pageSpread:Le(n),resolveHref:e=>ne(e,s.href),loadMediaOverlay:()=>this.loadMediaOverlay(s)}:(console.warn(`Could not find item with ID "${i}" in manifest`),null)})).filter((e=>e));const{navPath:s,ncxPath:a}=this.resources;if(s)try{const e=e=>ne(e,s),t=ue(await this.#l(s),e);this.toc=t.toc,this.pageList=t.pageList,this.landmarks=t.landmarks}catch(e){console.warn(e)}if((!this.toc||0===this.toc.length)&&a)try{const e=e=>ne(e,a),t=fe(await this.#l(a),e);this.toc=t.toc,this.pageList=t.pageList}catch(e){console.warn(e)}this.landmarks??=this.resources.guide;const{metadata:l,rendition:c,media:d}=(e=>{const{$:t,$$:i}=re(e,X),r=t(e.documentElement,"metadata"),n=Array.from(r.children),o=(e,t)=>{if(!t)return null;const{props:i=[],attrs:r=[]}=e,s=ie(t);if(!i.length&&!r.length)return s;const a=t.getAttribute("id"),l=a?n.filter(ee("refines","#"+a)):[];return Object.fromEntries([["value",s]].concat(i.map((t=>{const{many:i,recursive:r}=t,n="string"==typeof t?t:t.name,s=ee("property",n),a=r?e:t;return[Q(n),i?l.filter(s).map((e=>o(a,e))):o(a,l.find(s))]}))).concat(r.map((e=>[Q(e),t.getAttribute(e)]))))},s=n.filter(ee("refines",null)),a=e=>Object.fromEntries(i(r,"meta").filter(ee("property",(t=>t?.startsWith(e)))).map((t=>[t.getAttribute("property").replace(e,""),ie(t)])));return{metadata:Object.fromEntries(he.map((e=>{const{type:t,name:i,many:r}=e,n="meta"===t?e=>e.namespaceURI===X&&e.getAttribute("property")===i:e=>e.namespaceURI===J&&e.localName===i;return[Q(i),r?s.filter(n).map((t=>o(e,t))):o(e,s.find(n))]}))),rendition:a("rendition:"),media:a("media:")}})(r);this.rendition=c,this.media=d,d.duration=pe(d.duration),this.dir=this.resources.pageProgressionDirection,this.rawMetadata=l;const h=l?.title?.[0];this.metadata={title:h?.value,sortAs:h?.fileAs,language:l?.language,identifier:me(r),description:l?.description?.value,publisher:l?.publisher?.value,published:l?.date,modified:l?.dctermsModified,subject:l?.subject?.filter((({value:e,code:t})=>e||t))?.map((({value:e,code:t,scheme:i})=>({name:e,code:t,scheme:i}))),rights:l?.rights?.value};const u={art:"artist",aut:"author",bkp:"producer",clr:"colorist",edt:"editor",ill:"illustrator",trl:"translator",pbl:"publisher"},f=e=>t=>{const i=[...new Set(t.role?.map((({value:t,scheme:i})=>(i&&"marc:relators"!==i?null:u[t])??e)))],r={name:t.value,sortAs:t.fileAs};return[i?.length?i:[e],r]};return l?.creator?.map(f("author"))?.concat(l?.contributor?.map?.(f("contributor")))?.forEach((([e,t])=>e.forEach((e=>{this.metadata[e]?this.metadata[e].push(t):this.metadata[e]=[t]})))),this}async loadDocument(e){const t=await this.loadText(e.href);return this.parser.parseFromString(t,e.mediaType)}async loadMediaOverlay(e){const t=e.mediaOverlay;if(!t)return null;const i=this.resources.getItemByID(t),r=((e,t=e=>e)=>{const{$:i,$$$:r}=re(e,Y);return r(e,"par").map((e=>{const r=i(e,"text")?.getAttribute("src")?.split("#")?.[1],n=i(e,"audio");return n?{id:r,audio:{src:(o=n.getAttribute("src"),o?decodeURI(t(o)):null),clipBegin:pe(n.getAttribute("clipBegin")),clipEnd:pe(n.getAttribute("clipEnd"))}}:{id:r};var o}))})(await this.#l(i.href),(e=>ne(e,i.href)));return r}resolveCFI(e){return this.resources.resolveCFI(e)}resolveHref(e){const[t,i]=e.split("#"),r=this.resources.getItemByHref(decodeURI(t));if(!r)return null;return{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}}splitTOCHref(e){return e?.split("#")??[]}getTOCFragment(e,t){return e.getElementById(t)??e.querySelector(`[name="${CSS.escape(t)}"]`)}isExternal(e){return oe(e)}async getCover(){const 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"),t="encoding=json+base64:";if(e?.startsWith(t)){const t=atob(e.slice(21));return JSON.parse(t)}}}const Se=(e,t=!1,i="")=>{const r=(new DOMParser).parseFromString(t?$e(e,i):e,"text/html");let n=De(r);0===n.length&&(n=We(r));for(let e=0;e""};return l.sections=a.map((e=>({id:e.index,load:()=>{return t=e.index,d(void 0,void 0,void 0,(function*(){return URL.createObjectURL(new Blob([a[t].text],{type:"text/html"}))}));var t},unload:()=>{e.index}}))),l.toc=a.map((e=>({label:e.label,href:"title"+e.index}))).filter((e=>""!==e.label)),l.rendition={layout:"pre-paginated"},l.resolveHref=e=>({index:parseInt(e.substring(5,e.length))}),l.splitTOCHref=e=>[e,null],l.getTOCFragment=e=>e.documentElement,l};let Me=["章","节","回","節","卷","部","輯","辑","話","集","话","篇"," "," "],Ae=[],ke=["CHAPTER","Chapter","序章","前言","声明","写在前面的话","后记","楔子","后序","章节目录","尾声"],Ee=[" "," ","、","·",".",":",":"];const De=e=>Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,title")),Re=e=>e.trim().replace(/(\r\n|\n|\r|\t)/gm,"").substring(0,100).split("").filter((e=>"="!==e&&"-"!==e&&"_"!==e&&"+"!==e)).join(""),Ie=(e,t="")=>t?new RegExp(t).test(e):e&&e.length<40&&!Ne(e)&&(Be(e)||e.startsWith("第")&&He(e)||e.startsWith("卷")&&Pe(e)||e.indexOf("第")>-1&&e.lastIndexOf("第")<4&&He(e.substr(e.indexOf("第")))||Oe(e)),Ne=e=>Ae.filter((t=>e.indexOf(t)>-1)).length>0,Be=t=>ke.filter((i=>t.startsWith(i)||t.startsWith(e.s2t(i))||t.startsWith(e.t2s(i)))).length>0,Oe=e=>Ee.filter((t=>e.indexOf(t)>-1&&(/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(0,e.indexOf(t)))||/^\d+$/.test(e.substring(0,e.indexOf(t)))))).length>0,He=e=>{let t=!1;for(let i=0;i!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(1,e.indexOf(" ")))&&!/^\d+$/.test(e.substring(1,e.indexOf(" "))))||(!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(1,e.indexOf(" ")))&&!/^\d+$/.test(e.substring(1,e.indexOf(" "))))||!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(1))&&!/^\d+$/.test(e.substring(1)))),Fe=e=>{let t=[],i=e.split("
").filter((e=>""!==e.trim())),r=i.map((e=>Ue(e)||je(e)));return t=i.map(((e,t)=>({index:t,label:r[t],text:e,href:"title"+t}))),t},$e=(e,t)=>{let i="",r=e.split("\n");1===r.length&&(r=e.split("\r"));for(let e of r)Re(e)&&Ie(Re(e),t)?i+=`

${Re(e)}

`:i+=`

${e}

`;return i||`

Title

${e}

`},Ue=e=>{var t;const i=(new DOMParser).parseFromString(e,"text/html").querySelector("h1, h2, h3, h4, h5, h6");return i&&(null===(t=i.textContent)||void 0===t?void 0:t.trim())||""},je=e=>{var t;const i=(new DOMParser).parseFromString(e,"text/html").querySelector("title");return i&&(null===(t=i.textContent)||void 0===t?void 0:t.trim())||""},We=e=>{let t=e.getElementsByTagName("*"),i=Array.from(t).filter((e=>1===e.childNodes.length&&e.childNodes[0].nodeType===Node.TEXT_NODE&&Ie(Re(e.textContent)))),r=[];for(let e=0;eArray.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address")),Xe=(e,t,i,r,n,o,s)=>d(void 0,void 0,void 0,(function*(){let a=Math.floor(e.clientWidth/12),l=a%2==0?a:a-1;const c=e.clientWidth;if("mimical"===t&&"yes"!==s){let e=document.getElementById("book");e&&(e.style.display="block",i>0?o():i<0&&n(),setTimeout((()=>{if(!e)return{};e.style.display="none"}),1e3))}i>0?r.body.scrollBy({top:0,left:-c-l,behavior:"sliding"===t&&"yes"!==s?"smooth":"auto"}):i<0&&r.body.scrollBy({top:0,left:c+l,behavior:"sliding"===t&&"yes"!==s?"smooth":"auto"})})),Ve=(e,i,r,n)=>{let o=t.findLastIndex(r,(e=>e.href===i||e.href&&e.href.includes("#")&&e.href.includes(i)));return i&&t.findLastIndex(r,(e=>e.href===i||e.href&&e.href.includes("#")&&e.href.includes(i)))>-1||(o=e),"prev"===n?Object.assign(Object.assign({},r[o-1]),{index:o-1}):Object.assign(Object.assign({},r[o+1]),{index:o+1})},Je=(e,t,i,r,n,o,s,a)=>d(void 0,void 0,void 0,(function*(){let t=parseInt(o.chapterDocIndex||"0"),l=o.chapterHref||"";if(0===t)return;let c=Ve(t,l,i,"prev");c&&(o.text="prevChapter",o.page="",yield Ze(c.index,c.label,c.href,i,e,r,n,o,s,a))})),Ge=(e,t,i,r)=>d(void 0,void 0,void 0,(function*(){let{width:n,height:o}=yield i[r].text.getDimension(),s="double"===t?2:1,a=Math.floor(e.clientWidth/12),l=a%2==0?a:a-1,c=(e.clientWidth-l)/s;"single"===t&&(c=e.clientWidth);let d=e.clientHeight,h=Math.min(c/n,d/o);return"scroll"===t&&(h=c/n),h})),Ze=(e,i,r,n,o,s,a,l,c,h)=>d(void 0,void 0,void 0,(function*(){if(c.body.innerHTML="",h.height="0px",c.body.scrollTo(0,0),i&&!e||n[e]&&n[e].label&&i&&i!==n[e].label&&-1===r.indexOf("#")){let r=t.findLastIndex(n,{label:i});-1!==r&&(e=r)}if(-1===e&&r.indexOf("#")>-1){let i=r.split("#")[0],o=t.findLastIndex(n,(e=>e.href===i||e.href&&e.href.includes("#")&&e.href.includes(i)));-1!==o&&(e=o)}if((-1===e||e>n.length-1)&&(e=0),c.body.innerHTML=yield u(n[e].text,!1),"PDF"===a){let t=yield Ge(o,s,n,e);yield n[e].text.render(c,t,s)}yield _e(c),l.chapterTitle=i,l.chapterHref=r,l.chapterDocIndex=e+"",l.percentage=e/n.length+"",l.text="",yield((e,t,i,r,n)=>d(void 0,void 0,void 0,(function*(){if(yield Promise.all(Array.from([...n.images,...n.querySelectorAll("image")]).map((e=>e.complete?Promise.resolve(0!==e.naturalHeight):new Promise((t=>{e.addEventListener("load",(()=>t(!0))),e.addEventListener("error",(()=>t(!1)))}))))).then((e=>{e.every((e=>e))?console.info("all images loaded successfully!!"):console.error("some images failed to load, all finished loading")})),yield v(e,t,i,n),"PDF"!==i&&b(n),"scroll"!==t){if(r.height=e.clientHeight+"px","double"===t){let t=Math.floor(e.clientWidth/12),i=t%2==0?t:t-1,r=(e.clientWidth+i)/2;if((n.body.scrollWidth-n.body.clientWidth)/r%2==1){let e=document.createElement("div");e.setAttribute("style","height: "+n.body.clientHeight+"px; display: inline-block; width: "+(r-i)+"px"),n.body.appendChild(e)}}}else if("PDF"===i){let e=n.querySelector(".koodoPDFLayer");if(!e)return;r.height=e.getBoundingClientRect().height+100+"px"}else r.height=n.body.scrollHeight+"px",r.height=n.body.scrollHeight+300+"px"})))(o,s,a,h,c),yield Ye(o,s,"","","","",c)})),_e=e=>d(void 0,void 0,void 0,(function*(){let t=Array.from(e.getElementsByTagName("link"));if(0===t.length)return;for(let e=0;e{console.info("finished")}}let i=[];for(let e=0;e{r.addEventListener("load",e)})))}try{yield Promise.race([Promise.all(i),new Promise(((e,t)=>{setTimeout((()=>{console.info("css load timeout"),e("css load timeout")}),1e3)}))])}catch(e){console.error(e)}})),Ye=(t,i,r,n,o,s,a)=>d(void 0,void 0,void 0,(function*(){let l=0,c=a.body;if(s&&"scroll"!==i){let e=Math.floor(t.clientWidth/12),i=e%2==0?e:e-1;l=((d=getComputedStyle(t).width,parseFloat(d.substring(0,d.length-2)))+i)*(parseInt(s)-1)}else if(r){let o=ze(a.body).filter(((t,i)=>Re(t.textContent)&&(Re(t.textContent)===Re(r)||Re(t.textContent)===e.t2s(Re(r))||Re(t.textContent)===e.s2t(Re(r)))&&(Math.abs(i-parseInt(n))<2||"search"===n||"ignore"===n||"next"===n)));if(0===o.length)return void console.info("failed");c=Ke(o[0],t,i),l=c?h(c.offsetLeft)-h(c.marginLeft||parseFloat(getComputedStyle(c).marginLeft)):"prevChapter"===r?a.body.scrollWidth:0,c&&(h(c.offsetTop),h(c.marginTop||parseFloat(getComputedStyle(c).marginTop)))}else if(o&&o.indexOf("#")>-1){let e=CSS.escape(o.split("#").reverse()[0]);if(!a.body.querySelector("#"+e))return;c=Ke(a.body.querySelector("#"+e)||a.body,t,i),l=c?h(c.offsetLeft)-h(c.marginLeft||parseFloat(getComputedStyle(c).marginLeft)):0,c&&(h(c.offsetTop),h(c.marginTop||parseFloat(getComputedStyle(c).marginTop)))}var d;"scroll"!==i?a.body.scrollTo(l,0):c.scrollIntoView()})),Ke=(e,t,i)=>{let r=Math.floor(t.clientWidth/12),n=r%2==0?r:r-1,o=h(e.offsetLeft)-h(e.marginLeft||parseFloat(getComputedStyle(e).marginLeft));return"scroll"===i||"scroll"!==i&&Qe(parseInt(o+""),(t.clientWidth+n)/2)?e:e.parentElement?Ke(e.parentElement,t,i):e},Qe=(e,t)=>{for(let i=e-10;i<=e+10;i++)if(i%t==0)return!0;return!1},et=(e,t,i,r,n,o,s)=>d(void 0,void 0,void 0,(function*(){var a;if(qe)return;let l=ze(o.body),c=l.filter((i=>st(e,i,t)&&(i.textContent||"").trim())),d=c[0];s&&(d=s);let h=0;for(let i=0;i{qe=!1}),100)})),tt=(e,t,i)=>{let r=Math.floor(t.clientWidth/12),n=r%2==0?r:r-1;return Math.abs(e.offsetLeft-Ke(e,t,i).offsetLeft)>(t.clientWidth+n)/2},it=(e,i,r)=>{let n=r.chapterHref||"",o=n.lastIndexOf("#"),s="";s=-1===o?n:n.substring(0,o);for(let n=0;n-1&&(r.chapterHref=e,r.chapterTitle=i[n].label)}}},rt=(e,t,i,r,n,o,s,a)=>d(void 0,void 0,void 0,(function*(){let t=parseInt(o.chapterDocIndex||"0"),l=o.chapterHref||"";if(t>=i.length-1)return void(o.percentage="1");let c=Ve(t,l,i,"next");c&&(o.page="",yield Ze(c.index,c.label,c.href,i,e,r,n,o,s,a))})),nt=(e,t,i)=>ze(i.body).filter((e=>!ot(e))).filter((i=>st(e,i,t)&&(i.textContent||"").trim())).filter((e=>"img"!==e.textContent)).map((e=>e.textContent)),ot=e=>{var t=e.children;let i=!1;var r=/^(address|section|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;if(Array.from(t).filter((e=>r.test(e.nodeName))).length<3)return!1;for(var n=0;n{var r=!1,n=t.getBoundingClientRect();if("scroll"!==i&&t.textContent&&t.textContent.trim()){let t=n.left;r=t>-10&&t<=e.clientWidth}else if("scroll"===i&&t.textContent&&t.textContent.trim()){let t=n.top;r=t>=e.scrollTop&&t<=e.scrollTop+e.clientHeight}else if("scroll"!==i){let t=n.left;r=t>=0&&t<=e.clientWidth}return r},at=(e,t,r,n,o,s)=>{var a;let l=t.contentWindow||(null===(a=t.contentDocument)||void 0===a?void 0:a.defaultView),c=0,h=0,u=0,f=0;let p=Math.floor(r.clientWidth/12),g=p%2==0?p:p-1,m=function(t){return d(this,void 0,void 0,(function*(){let a=(new Date).getTime();if(a-f<=300)return void t.preventDefault();f=a;const d=t.changedTouches[0],p=Date.now(),m=d.clientX,y=d.clientY,w=p-c,v=m-h,x=y-u;if(b&&"mimical"===o)return b=!1,s.mouseUpHandler(t),d.screenX{let e=document.getElementById("book");e&&(e.style.display="none")}),400);if(b&&"sliding"===o){window.scrollAnimationId&&cancelAnimationFrame(window.scrollAnimationId),e.body.style.transform="";let S,M=r.clientWidth+g,A=e.body.scrollLeft;const k=Math.round(A/M),E=Math.abs(v)/window.screen.width,D=.1;S=v>0&&E>D?(k-1)*M:v<0&&E>D?(k+1)*M:k*M,S=Math.max(0,Math.min(S,e.body.scrollWidth-M)),e.body.scrollWidth-S1-Math.pow(1-e,3);function H(t){const i=t-R;if(i>=B)return e.body.scrollLeft=S,e.body.style.willChange="auto",s.record(),void(b=!1);const r=O(i/B),n=I+N*r;e.body.scrollLeft=n,window.scrollAnimationId=requestAnimationFrame(H)}return void(window.scrollAnimationId=requestAnimationFrame(H))}const C=l.getSelection().toString().trim();if(C){var L=l.getSelection().getRangeAt(0).getBoundingClientRect(),T={top:L.top-r.scrollTop,left:L.left,width:L.width,height:L.height,screenWidth:window.innerWidth,screenHeight:window.innerHeight};i.init();let P=yield s.getHightlightCoords();window.ReactNativeWebView.postMessage(JSON.stringify({event:"select-text",selectedText:C,position:T,range:P}))}else if(w<500&&Math.abs(v)<30&&Math.abs(x)<30){const F=document.documentElement.clientWidth;document.documentElement.clientHeight;const $=Math.min(Math.max(m,0),F);let U="";const j=F/3,W=Math.min(Math.floor($/j),2);0===W?U="left":1===W?U="center":2===W&&(U="right"),window.ReactNativeWebView.postMessage(JSON.stringify({event:U}))}else(Math.abs(v)>=30||Math.abs(x)>=30)&&(window.ReactNativeWebView.postMessage(JSON.stringify({event:"swipe"})),"scroll"===n&&Math.abs(r.scrollHeight-r.scrollTop-r.clientHeight)<10&&window.ReactNativeWebView.postMessage(JSON.stringify({event:"scroll-bottom"})),"scroll"===n&&0===r.scrollTop&&window.ReactNativeWebView.postMessage(JSON.stringify({event:"scroll-top"})))}))},y=function(e){const t=e.target;if(!t)return;if("IMG"===t.tagName){const e=t.src||t.getAttribute("xlink:href");window.ReactNativeWebView.postMessage(JSON.stringify({event:"view-image",imgSrc:e}))}e.touches.length>1&&e.preventDefault();const i=e.touches[0];c=Date.now(),h=i.clientX,u=i.clientY},b=!1,w=0,v=function(t){const i=l.getSelection().toString().trim();if(!b&&Math.abs(t.touches[0].screenX-h)<=10||i)return;t.preventDefault();const n=t.touches[0],a=n.screenX,c=n.screenY,d=a-h,f=c-u;if(!b&&Math.abs(d)>Math.abs(f)&&Math.abs(d)>10){if(b=!0,w=a,e.body.style.transform="translateZ(0)","mimical"===o){window.ReactNativeWebView.postMessage(JSON.stringify({event:"swipe-start"}));let e=document.getElementById("book");e&&(e.style.display="block",s.mouseDownHandler(t))}}else if(b&&"mimical"===o&&s.mouseMoveHandler(t),b&&"sliding"===o){const t=a-w;if(Math.abs(e.body.scrollWidth-e.body.scrollLeft-r.clientWidth)<10&&t<0)return x&&clearTimeout(x),void(x=setTimeout((()=>{s.next()}),300));if(0===e.body.scrollLeft&&t>0)return x&&clearTimeout(x),void(x=setTimeout((()=>{s.prev()}),300));const i=e.body.scrollLeft;e.body.scrollLeft=i-t,w=a,requestAnimationFrame((()=>{}))}};e.body.ontouchend=m,e.body.ontouchstart=y,e.body.ontouchmove=v,l.ontouchend=m,l.ontouchstart=y,l.ontouchmove=v;let x=null;e.addEventListener("touchmove",(e=>{}),!1),e.body.oncontextmenu=function(e){return e.preventDefault(),e.stopPropagation(),!1}};class lt{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;return this.resolveNames(e).forEach((function(e){const r=i.resolveName(e);i.callbacks[r.namespace]instanceof Object||(i.callbacks[r.namespace]={}),i.callbacks[r.namespace][r.value]instanceof Array||(i.callbacks[r.namespace][r.value]=[]),i.callbacks[r.namespace][r.value].push(t)})),this}off(e){const t=this;if(void 0===e||""===e)return console.warn("wrong name"),!1;return this.resolveNames(e).forEach((function(e){const i=t.resolveName(e);if("base"!==i.namespace&&""===i.value)delete t.callbacks[i.namespace];else if("base"===i.namespace)for(const e in t.callbacks)t.callbacks[e]instanceof Object&&t.callbacks[e][i.value]instanceof Array&&(delete t.callbacks[e][i.value],0===Object.keys(t.callbacks[e]).length&&delete t.callbacks[e]);else t.callbacks[i.namespace]instanceof Object&&t.callbacks[i.namespace][i.value]instanceof Array&&(delete t.callbacks[i.namespace][i.value],0===Object.keys(t.callbacks[i.namespace]).length&&delete t.callbacks[i.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={},i=e.split(".");return t.original=e,t.value=i[0],t.namespace="base",i.length>1&&""!==i[1]&&(t.namespace=i[1]),t}}const ct=Node.ELEMENT_NODE,dt=Node.TEXT_NODE,ht=Node.CDATA_SECTION_NODE;function ut(e,t,i){let r,n,o,s=0,a=0,l=!0;for(n=0;nthis.compare(e,t)))}static compare(e,t){let i=e.get(),r=t.get();if(e.isRange||t.isRange){if(e.isRange&&t.isRange){const e=this.comparePath(i.from,r.from);return e||this.comparePath(i.to,r.to)}return e.isRange&&(i=i.from),t.isRange&&(r=r.from),this.comparePath(i,r)}return this.comparePath(i,r)}static compareParts(e,t){const i=Math.max(e.length,t.length);let r,n,o,s;for(r=0;r=i)return"img"===a.tagName.toLowerCase()&&r?{node:a,offset:r}:{node:a,offset:0}}else{if(l+=1,l===i)return"img"===a.tagName.toLowerCase()&&r?{node:a,offset:r}:{node:a,offset:0};if(l>i)return o?{node:o,offset:this.trueLength(e,o.textContent)}:{node:t,offset:0}}o=a;break;case dt:case ht:if(0!==l&&l%2!=0||(l+=1),l===i){const t=this.trueLength(e,a.textContent);if(!(r>=t))return{node:a,offset:r};r-=t}o=a;break;default:continue}if(i>l){const i={relativeToNode:"after",offset:0};return i.node=o||t,this.isTextNode(i.node)&&(i.offset=this.trueLength(e,i.node.textContent.length)),i}}isTextNode(e){return!!e&&(e.nodeType===dt||e.nodeType===ht)}correctOffset(e,t,i,r){let n,o=t;if("string"==typeof r?n=this.decodeEntities(e,r):(r.pre=this.decodeEntities(e,r.pre),r.post=this.decodeEntities(e,r.post),n=r.pre+"."+r.post),!this.isTextNode(t))return{node:t,offset:0};for(;this.isTextNode(o.previousSibling);)o=o.previousSibling;const s=o;let a;const l=[];let c="",d=0;for(;this.isTextNode(o)&&(a=this.decodeEntities(e,o.textContent),l[d]=a.length,c+=a,o.nextSibling);)o=o.nextSibling,d++;const h=r.pre?r.pre.length:0,u=function(e,t,i){i=i||0;const r=[];let n,o=0;do{if(n=e.match(t),!n)break;r.push(n.index+i),o+=n.index+n.length,e=e.slice(n.index+n.length)}while(o=l[d];){if(f-=l[d],f<0)return{node:t,offset:i};const e=[];if(!o.nextSibling||d+1>=e.length)return{node:t,offset:i};d++,o=o.nextSibling}return{node:o,offset:f}}resolveNode(e,t,i,r){if(r=Object.assign({},r||{}),!i)throw new Error("Missing DOM argument");let n;if(0===e&&(n=i.querySelector("package")),!n)for(const e of i.childNodes)if(e.nodeType===ct){n=e;break}if(n=i,!n)throw new Error("Document incompatible with CFIs");let o,s,a=n,l=0;for(o=t.length-1;o>=0;o--)if(s=t[o],!r.ignoreIDs&&s.nodeID&&(a=i.getElementById(s.nodeID))){l=o+1;break}a||(a=n);let c={node:a,offset:0};for(o=l;othis.parts.length-2)throw new Error("index is out of bounds");const r=this.parts[e];if(!r)throw new Error("Missing CFI part for index: "+e);let n=this.resolveNode(e,r,t,i).node;const o=n.tagName.toLowerCase();if("itemref"===o&&"spine"===n.parentNode.tagName.toLowerCase()){const e=n.getAttribute("idref");if(!e)throw new Error("Referenced node had not 'idref' attribute");if(n=t.getElementById(e),!n)throw new Error("Specified node is missing from manifest");const i=n.getAttribute("href");if(!i)throw new Error("Manifest item is missing href attribute");return i}if("iframe"===o||"embed"===o){const e=n.getAttribute("src");if(!e)throw new Error(o+" element is missing 'src' attribute");return e}if("object"===o){const e=n.getAttribute("data");if(!e)throw new Error(o+" element is missing 'data' attribute");return e}if("image"===o||"use"===o){const e=n.getAttribute("xlink:href");if(!e)throw new Error(o+" element is missing 'xlink:href' attribute");return e}throw new Error("No URI found")}deepClone(e){return JSON.parse(JSON.stringify(e))}resolveLocation(e,t){const i=t.length-1,r=t[i];if(!r)throw new Error("Missing CFI part for index: "+i);const n=this.resolveNode(i,r,e),o=this.deepClone(r[r.length-1]);return delete o.nodeIndex,o.offset||delete n.offset,Object.assign(Object.assign({},o),n)}resolveLast(e,t){if(t=Object.assign({range:!1},t||{}),!this.isRange)return this.resolveLocation(e,this.parts);if(t.range){const t=e.createRange(),i=this.getFrom();"before"===i.relativeToNode?t.setStartBefore(i.node,i.offset):"after"===i.relativeToNode?t.setStartAfter(i.node,i.offset):t.setStart(i.node,i.offset);const r=this.getTo();return"before"===r.relativeToNode?t.setEndBefore(r.node,r.offset):"after"===r.relativeToNode?t.setEndAfter(r.node,r.offset):t.setEnd(r.node,r.offset),t}return{from:this.resolveLocation(e,this.getFrom()),to:this.resolveLocation(e,this.getTo()),isRange:!0}}resolve(e,t){return this.resolveLast(e,t)}}const mt=["color-0","color-1","color-2","color-3","line-0","line-1","line-2","line-3"],yt=["#FEF3CD","#FBFACC","#CEFACD","#CDE9FA"],bt=["#FF0000","#000080","#0000FF","#2EFF2E"],wt=["#fac106","#ebe702","#0be603","#0493e6"],vt=(e,t,r,n,o,s)=>{var a,l;i.init();let c=mt[t],d=s.contentWindow||(null===(a=s.contentDocument)||void 0===a?void 0:a.defaultView),h=e;h=[h],i.getSelection(s).restoreCharacterRanges(o,h);let u=o.getSelection();if(!u)return;let f=u.getRangeAt(0);for(var p=St(f),g=0;g{let a=mt[t],l=s.querySelector(".noteLayer"),c=s.querySelector("#koodoPDFLayer");var d=n.getViewport({scale:o});e.coords.forEach((e=>{var t=d.convertToViewportRectangle(e),n=document.createElement("div");c&&(null==n||n.setAttribute("style","position: absolute;"+(a.indexOf("color")>-1?"background-color: ":"border-bottom: ")+(a.indexOf("color")>-1?wt[a.split("-")[1]]:`2px solid ${bt[a.split("-")[1]]}`)+"; left:"+(Math.min(t[0],t[2])+parseFloat(getComputedStyle(c).marginLeft))+"px; top:"+Math.min(t[1],t[3])+"px;width:"+Math.abs(t[0]-t[2])+"px; height:"+Math.abs(t[1]-t[3])+"px; z-index: 1;opacity: "+(a.indexOf("color")>-1?.3:1)+";"),null==n||n.setAttribute("data-key",i),null==n||n.setAttribute("class","kookit-note"),null==n||n.addEventListener("click",(e=>{e&&e.target&&e.target.dataset&&e.target.dataset.key&&r(e)})),n.ontouchend=e=>{e&&e.target&&e.target.dataset&&e.target.dataset.key&&r(e),e.preventDefault(),e.stopPropagation()},l.appendChild(n))}))},Ct=e=>{const t=e.querySelectorAll(".kookit-note");for(let e=0;e{const o=Tt(e.getClientRects());for(let e=0;e-1?"background-color: ":"border-bottom: ")+(t.indexOf("color")>-1?yt[t.split("-")[1]]+";opacity: 1":`2px solid ${bt[t.split("-")[1]]}`)+";left:"+(Math.min(l.left,l.x)+n.body.scrollLeft)+"px; top:"+(Math.min(l.top,l.y)+n.body.scrollTop)+"px;width:"+l.width+"px; height:"+l.height+"px; z-index:-1;"),s.setAttribute("class"," kookit-note"),s.setAttribute("data-key",i),n.body.appendChild(s);var a=document.createElement("span");null==a||a.setAttribute("style","position: absolute;left:"+(Math.min(l.left,l.x)+n.body.scrollLeft)+"px; top:"+(Math.min(l.top,l.y)+n.body.scrollTop)+"px;width:"+l.width+"px; height:"+l.height+"px; z-index:1;"),a.setAttribute("class"," kookit-note"),a.setAttribute("data-key",i),a.addEventListener("click",(e=>{e&&e.target&&e.target.dataset&&e.target.dataset.key&&r(e)})),a.ontouchend=e=>{e&&e.target&&e.target.dataset&&e.target.dataset.key&&r(e),e.preventDefault(),e.stopPropagation()},n.body.appendChild(a)}},Tt=e=>{let t=[];for(let i=0;i{var t=e.commonAncestorContainer,i=new Array(0),r=new Array(0);if(e.startContainer!==t)for(let r=e.startContainer;r!==t;r=r.parentNode)i.push(r);if(i.length>0)for(let t=0;t0)for(let t=0;t0&&o.length>0))return[e];var c=document.createRange();return c.setStartAfter(i[i.length-1]),c.setEndBefore(o[o.length-1]),r.push(c),r.concat(s)};const Mt=(e,t,i)=>{!function(e){let t=document.getElementById("book");t&&t.remove();const i=document.createElement("div");i.id="book";const r=document.createElement("canvas");r.id="pageflip-canvas";const n=document.createElement("div");n.id="pages";for(let t=0;t{console.info("flipToNextPage"),d+1{console.info("flipToPrevPage"),d-1>=0&&(p[d-1].target=1,d=Math.max(d-1,0))},mouseDownHandler:v,mouseUpHandler:x,mouseMoveHandler:w}}}function w(e){if(!g)return;const t=e.touches[0],i=t.screenX,r=t.screenY;f.x=i-g.offsetLeft-o/2,f.y=r-g.offsetTop}function v(e){const t=e.touches[0];t.screenX=0?p[d-1].dragging=!0:t.screenX>window.screen.width/2&&d+1{let t=this.getDocument();t&&("Simplified To Traditional"===this.convertChinese?t.querySelectorAll("h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address").forEach((t=>{t.innerHTML=t.innerHTML.split("").map((t=>e.s2t(t))).join("")})):"Traditional To Simplified"===this.convertChinese&&t.querySelectorAll("h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address").forEach((t=>{t.innerHTML=t.innerHTML.split("").map((t=>e.t2s(t))).join("")})))},this.addPageAnimation=e=>{if("mimical"===this.animation){let t=this.getProgress();if(!t)return;const i=Mt(t.totalPage,this.isDarkMode,e);i&&(this.flipToNextPage=i.flipToNextPage,this.flipToPrevPage=i.flipToPrevPage,this.mouseDownHandler=i.mouseDownHandler,this.mouseUpHandler=i.mouseUpHandler,this.mouseMoveHandler=i.mouseMoveHandler)}},this.readerMode=t.readerMode,this.animation=t.animation,this.format=t.format,this.convertChinese=t.convertChinese,this.isDarkMode=t.isDarkMode,this.isMobile=t.isMobile,this.chapterList=[],this.chapterDocList=[],this.flattenChapters=[],this.book="",this.element="",this.tempLocation={},this.flipToNextPage=()=>{},this.flipToPrevPage=()=>{},this.mouseDownHandler=()=>{},this.mouseUpHandler=()=>{},this.mouseMoveHandler=e=>{}}getPageSize(){let e="double"===this.readerMode?2:1,t=Math.floor(this.element.clientWidth/12),i=t%2==0?t:t-1;return{width:this.element.clientWidth,height:this.element.clientHeight,left:this.element.offsetLeft,top:this.element.offsetTop,scrollTop:this.element.scrollTop,sectionWidth:(this.element.clientWidth-i)/e,gap:i}}resolveChapter(e){let t=e,i=-1;for(let e=0;e-1)return this.flattenChapters[i];{let r=e.split("#")[0];for(let e=0;e-1)return this.flattenChapters[i];for(let e=0;e-1?{label:"",href:"",index:i}:null}}flatChapter(e){let t=[];for(let i=0;i0?(t.push(e[i]),t=t.concat(this.flatChapter(e[i].subitems))):t.push(e[i]);return this.flattenChapters=t,t}getChapter(){return this.chapterList}getChapterDoc(){return this.chapterDocList}goToPercentage(e){return d(this,void 0,void 0,(function*(){if(this.flattenChapters.length>0){let t=1===e?this.flattenChapters.length-1:Math.floor(this.flattenChapters.length*e);yield this.goToChapter(this.flattenChapters[t].index.toString(),this.flattenChapters[t].href,this.flattenChapters[t].label)}}))}goToChapterIndex(e){return d(this,void 0,void 0,(function*(){this.flattenChapters.length>0&&(yield this.goToChapter(this.flattenChapters[e].index,this.flattenChapters[e].href,this.flattenChapters[e].label))}))}goToChapter(e,t,i){return d(this,void 0,void 0,(function*(){let r=this.getDocument(),n=this.getIframe();r&&n&&(yield Ze(parseInt(e),i,t,this.chapterDocList,this.element,this.readerMode,this.format,this.tempLocation,r,n),t&&t.indexOf("#")>-1&&(yield Ye(this.element,this.readerMode,"","",t,"",r)),yield this.record(),this.trigger("rendered"))}))}goToPosition(e){return d(this,void 0,void 0,(function*(){let t=this.getDocument(),i=this.getIframe();if(!t||!i)return;let r=JSON.parse(e);this.tempLocation={text:r.text,chapterTitle:r.chapterTitle,chapterDocIndex:r.chapterDocIndex,chapterHref:r.chapterHref,count:r.count,page:r.page};let{text:n,chapterTitle:o,chapterDocIndex:s,chapterHref:a,count:l,page:c,cfi:d}=r;if(yield Ze(parseInt(s),o,a,this.chapterDocList,this.element,this.readerMode,this.format,this.tempLocation,t,i),d){const e=new gt(d,{});let t=this.getDocument();if(!t)return;const{node:i,offset:r}=e.resolve(t,{});if(i){let e=null,t=i;for(;t;){const i=t;if(i.tagName&&"h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address".indexOf(i.tagName.toLowerCase())>-1){e=i;break}t=t.parentNode}e&&(l="ignore",n=e.textContent)}}yield Ye(this.element,this.readerMode,n,l,"",c,t),yield this.record(),this.trigger("rendered")}))}getDocument(){let e=document.getElementById("page-area");if(!e)return null;let t=e.getElementsByTagName("iframe")[0];if(!t)return null;let i=t.contentDocument;return i||null}getIframe(){let e=document.getElementById("page-area");if(!e)return null;let t=e.getElementsByTagName("iframe")[0];return t||null}goToNode(e){return d(this,void 0,void 0,(function*(){let t=this.getDocument();if(!t)return;let i=Ke(e,this.element,this.readerMode),r=i?h(i.offsetLeft)-h(i.marginLeft||parseFloat(getComputedStyle(i).marginLeft)):0,n=i?h(i.offsetTop)-h(i.marginTop||parseFloat(getComputedStyle(i).marginTop)):0;"scroll"!==this.readerMode?t.body.scrollTo(r,0):this.element.scrollTo(0,n),yield this.record(),this.trigger("rendered")}))}removeContent(){this.element.innerHTML=""}prev(){return d(this,void 0,void 0,(function*(){let e=this.getDocument(),t=this.getIframe();if(e&&t){if("scroll"===this.readerMode&&0===h(this.element.scrollTop)||"scroll"!==this.readerMode&&0===h(e.body.scrollLeft)){if("0"===this.tempLocation.chapterDocIndex)return;yield Je(this.element,this.flatChapter(this.chapterList),this.chapterDocList,this.readerMode,this.format,this.tempLocation,e,t),parseInt(this.tempLocation.chapterDocIndex||"-1")>-1&&("scroll"===this.readerMode?this.element.scrollTo(0,e.body.scrollHeight):e.body.scrollTo(e.body.scrollWidth,0)),this.trigger("rendered")}else"scroll"===this.readerMode?this.element.scrollBy({left:0,top:-(this.element.clientHeight-50),behavior:"smooth"}):yield Xe(this.element,this.animation,1,e,this.flipToNextPage,this.flipToPrevPage,this.isMobile);yield this.record()}}))}next(){return d(this,void 0,void 0,(function*(){let e=this.getDocument(),t=this.getIframe();e&&t&&(Math.abs(e.body.scrollWidth-h(e.body.scrollLeft)-e.body.clientWidth)<10&&"scroll"!==this.readerMode||Math.abs(this.element.scrollHeight-h(this.element.scrollTop)-this.element.clientHeight)<10&&"scroll"===this.readerMode?(yield rt(this.element,this.flatChapter(this.chapterList),this.chapterDocList,this.readerMode,this.format,this.tempLocation,e,t),this.trigger("rendered")):"scroll"===this.readerMode?this.element.scrollBy({left:0,top:this.element.clientHeight-50,behavior:"smooth"}):yield Xe(this.element,this.animation,-1,e,this.flipToNextPage,this.flipToPrevPage,this.isMobile),yield this.record())}))}prevChapter(){return d(this,void 0,void 0,(function*(){let e=this.getDocument(),t=this.getIframe();e&&t&&(yield Je(this.element,this.flatChapter(this.chapterList),this.chapterDocList,this.readerMode,this.format,this.tempLocation,e,t),yield this.record(),this.trigger("rendered"))}))}nextChapter(){return d(this,void 0,void 0,(function*(){let e=this.getDocument(),t=this.getIframe();e&&t&&(yield rt(this.element,this.flatChapter(this.chapterList),this.chapterDocList,this.readerMode,this.format,this.tempLocation,e,t),yield this.record(),this.trigger("rendered"))}))}visibleText(){let e=this.getDocument();return e?nt(this.element,this.readerMode,e):""}audioText(){let e=this.getDocument();return e?((e,t,i)=>{let r=ze(i.body).filter((e=>!ot(e))).filter((e=>(e.textContent||"").trim())).filter((e=>"img"!==e.textContent)).map((e=>e.textContent)),n=0,o=nt(e,t,i);if(o&&o.length>0){let e=o[0];n=r.indexOf(e)}return r.slice(n)})(this.element,this.readerMode,e):""}chapterText(){let e=this.getDocument();return e?e.body.innerText:""}highlightNode(e,t){let i=this.getDocument();i&&((e,t,i)=>{let r=ze(i.body).filter((i=>(i.getAttribute("style")===t&&i.setAttribute("style",""),(i.textContent||"").trim()&&i.textContent===e)));r.length>0&&r[0].setAttribute("style",t)})(e,t,i)}doSearch(e){return d(this,void 0,void 0,(function*(){return yield((e,i)=>d(void 0,void 0,void 0,(function*(){var r;let n=[];for(let t=0;t!ot(e)));for(let o=0;o-1&&n.push({excerpt:(null===(r=s[o].textContent)||void 0===r?void 0:r.substring(a-100,a+100))||"",cfi:JSON.stringify({text:s[o].textContent,chapterTitle:i[t].label,chapterDocIndex:t,chapterHref:i[t].href,count:"search",percentage:t/i.length})})}}return t.uniq(n,"excerpt")})))(e,this.chapterDocList)}))}getProgress(){let e=this.getDocument();if(e)return y(this.readerMode,e)}record(){return d(this,void 0,void 0,(function*(){""!==this.animation&&(yield new Promise((e=>setTimeout(e,1e3))));let e=this.getDocument();e&&(yield et(this.element,this.readerMode,this.flatChapter(this.chapterList),this.chapterDocList,this.tempLocation,e,null),this.trigger("page-changed"))}))}getPosition(){return this.tempLocation}getNotePosition(){return d(this,void 0,void 0,(function*(){let e=this.getDocument();if(!e)return;let t=function(e){const t=e.getSelection();if(!t)return null;if(t.rangeCount>0)return t.getRangeAt(0).startContainer.parentElement;return null}(e);return t?(yield et(this.element,this.readerMode,this.flatChapter(this.chapterList),this.chapterDocList,this.tempLocation,e,t),this.tempLocation):void 0}))}setStyle(e){let t=this.getDocument();if(t){var i=document.createElement("style");i.innerHTML=e,t.head.appendChild(i)}}getHightlightCoords(){return d(this,void 0,void 0,(function*(){i.init();let e=this.getDocument(),t=this.getIframe();if(e&&t)return i.getSelection(t).saveCharacterRanges(e.body)[0]}))}renderHighlighters(e,t){return d(this,void 0,void 0,(function*(){let i=this.getDocument(),r=this.getIframe();if(i&&r){Ct(i);for(let n=0;n{var a;let l=t.contentWindow||(null===(a=t.contentDocument)||void 0===a?void 0:a.defaultView),c=0,h=0,u=0,f=0,p=Math.floor(r.clientWidth/12),g=p%2==0?p:p-1,m=function(t){console.info("touchend");let i=(new Date).getTime();if(i-f<=300)return void t.preventDefault();f=i;const a=t.changedTouches[0],d=Date.now(),p=a.screenX,m=a.screenY,y=d-c,w=p-h,v=m-u;if(b&&"mimical"===o)return b=!1,s.mouseUpHandler(t),a.screenX{let e=document.getElementById("book");e&&(e.style.display="none")}),400);if(b&&"sliding"===o){window.scrollAnimationId&&cancelAnimationFrame(window.scrollAnimationId),e.body.style.transform="";let A,k=r.clientWidth+g,E=e.body.scrollLeft;const D=Math.round(E/k),R=Math.abs(w)/window.screen.width,I=.1;A=w>0&&R>I?(D-1)*k:w<0&&R>I?(D+1)*k:D*k,A=Math.max(0,Math.min(A,e.body.scrollWidth-k)),e.body.scrollWidth-A1-Math.pow(1-e,3);function F(t){const i=t-N;if(i>=H)return e.body.scrollLeft=A,e.body.style.willChange="auto",s.record(),void(b=!1);const r=P(i/H),n=B+O*r;e.body.scrollLeft=n,window.scrollAnimationId=requestAnimationFrame(F)}window.scrollAnimationId=requestAnimationFrame(F)}else{var x=l.getSelection().toString();if(x)window.ReactNativeWebView.postMessage(JSON.stringify({event:"select-text-after-touch",selectedText:x}));else if(y<500&&Math.abs(w)<30&&Math.abs(v)<30){var C=window.screen.width/3,L=window.screen.height/3,T=Math.floor(p/C),S=Math.floor(m/L),M="";0===S&&(0===T||1===T)||1===S&&0===T||2===S&&0===T||0===S&&1===T?M="left":1===S&&1===T?M="center":(0===S&&2===T||1===S&&2===T||2===S&&2===T||2===S&&1===T)&&(M="right"),window.ReactNativeWebView.postMessage(JSON.stringify({event:M}))}else(Math.abs(w)>=30||Math.abs(v)>=30)&&(console.info("Swipe detected"),window.ReactNativeWebView.postMessage(JSON.stringify({event:"swipe"})),"scroll"===n&&Math.abs(r.scrollHeight-r.scrollTop-r.clientHeight)<10&&window.ReactNativeWebView.postMessage(JSON.stringify({event:"scroll-bottom"})),"scroll"===n&&0===r.scrollTop&&window.ReactNativeWebView.postMessage(JSON.stringify({event:"scroll-top"})))}},y=function(e){const t=e.target;if(!t)return;if("IMG"===t.tagName){const e=t.src||t.getAttribute("xlink:href");window.ReactNativeWebView.postMessage(JSON.stringify({event:"view-image",imgSrc:e}))}e.touches.length>1&&e.preventDefault();const i=e.touches[0];c=Date.now(),h=i.screenX,u=i.screenY},b=!1,w=0,v=function(t){if(!b&&Math.abs(t.touches[0].screenX-h)<=10)return;t.preventDefault();const i=t.touches[0],n=i.screenX,a=i.screenY,l=n-h,c=a-u;if(!b&&Math.abs(l)>Math.abs(c)&&Math.abs(l)>10){if(b=!0,w=n,e.body.style.transform="translateZ(0)","mimical"===o){window.ReactNativeWebView.postMessage(JSON.stringify({event:"swipe-start"}));let e=document.getElementById("book");e&&(e.style.display="block",s.mouseDownHandler(t))}}else if(b&&"mimical"===o&&s.mouseMoveHandler(t),b&&"sliding"===o){const t=n-w;if(Math.abs(e.body.scrollWidth-e.body.scrollLeft-r.clientWidth)<10&&t<0)return x&&clearTimeout(x),void(x=setTimeout((()=>{s.next()}),300));if(0===e.body.scrollLeft&&t>0)return x&&clearTimeout(x),void(x=setTimeout((()=>{s.prev()}),300));const i=e.body.scrollLeft;e.body.scrollLeft=i-t,w=n,requestAnimationFrame((()=>{}))}};e.body.ontouchend=m,e.body.ontouchstart=y,e.body.ontouchmove=v,l.ontouchend=m,l.ontouchstart=y,l.ontouchmove=v;let x=null;e.body.oncontextmenu=function(e){return e.preventDefault(),e.stopPropagation(),!1};let C=0;e.addEventListener("selectstart",(t=>{"scroll"!==n&&(C=e.body.scrollLeft)}),!1),e.addEventListener("selectionchange",(t=>{C>0&&(e.body.scrollLeft=C),x&&clearTimeout(x),x=setTimeout((()=>d(void 0,void 0,void 0,(function*(){const e=l.getSelection().toString().trim();if(e){var t=l.getSelection().getRangeAt(0).getBoundingClientRect(),n={top:t.top-r.scrollTop,left:t.left,width:t.width,height:t.height,screenWidth:window.innerWidth,screenHeight:window.innerHeight};i.init();let o=yield s.getHightlightCoords();window.ReactNativeWebView.postMessage(JSON.stringify({event:"select-text",selectedText:e,position:n,range:o}))}}))),500)}),!1)})(t,r,this.element,this.readerMode,this.animation,this):at(t,r,this.element,this.readerMode,this.animation,this))}clearSelection(){var e,t;let i=this.getIframe();if(!i)return;let r=i.contentWindow||(null===(e=i.contentDocument)||void 0===e?void 0:e.defaultView);r&&r.getSelection()&&(null===(t=r.getSelection())||void 0===t||t.empty())}clearSelectionKeepHighlight(){var e,t;let r=this.getDocument(),n=this.getIframe();if(!r||!n)return;let o=n.contentWindow||(null===(e=n.contentDocument)||void 0===e?void 0:e.defaultView);if(!o||!o.getSelection())return;let s=r.getSelection();if(!s)return;let a=s.getRangeAt(0);for(var l=St(a),c=0;c{var t;null===(t=e.parentNode)||void 0===t||t.removeChild(e)}));let t=this.getIframe();if(!t)return;i.init();let r=window.charRange;r&&i.getSelection(t).restoreCharacterRanges(e,[r])}}const kt={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"},Et={"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"},Dt=e=>d(void 0,void 0,void 0,(function*(){let i=yield r.loadAsync(e);var n=i.file("toc.json");let o=[];n&&(o=JSON.parse(yield n.async("string")));var s=i.file("sections.json");let a=[];s&&(a=JSON.parse(yield s.async("string")));const l={getCover:()=>""};return l.sections=a.map(((e,t)=>({id:e.href,load:()=>(e=>d(void 0,void 0,void 0,(function*(){var t=i.file("chapters/"+e+".html");let r="";return t&&(r=yield t.async("string")),URL.createObjectURL(new Blob([r],{type:"text/html"}))})))(t),unload:()=>{},loadAsset:e=>(e=>d(void 0,void 0,void 0,(function*(){var t=i.file(e);let r;return t&&(r=yield t.async("arraybuffer")),URL.createObjectURL(new Blob([r],{type:kt[e.split(".").reverse()[0]]}))})))(e)}))),l.toc=o.map((e=>({label:e.label,href:e.href,subitems:e.subitems}))),l.rendition={layout:"pre-paginated"},l.resolveHref=e=>({index:t.findLastIndex(a,{href:e})}),l.splitTOCHref=e=>[e,null],l.getTOCFragment=e=>e.documentElement,l})),Rt=e=>new Promise(((t,i)=>d(void 0,void 0,void 0,(function*(){let i=new L(e),n=yield i.getChapter(e.toc),o=yield i.getChapterDoc(),s=n,a=o.map((e=>({href:e.href,label:e.label}))),l=yield Promise.all(o.map((e=>d(void 0,void 0,void 0,(function*(){let t="";if(e.text.load){let i=yield fetch(yield e.text.load()).then((e=>e.blob()));t=yield i.text()}return t}))))),c=new r;c.file("toc.json",JSON.stringify(s)),c.file("sections.json",JSON.stringify(a));let h=[];for(let e=0;ee.blob()));r.file(t+"."+Et[o.type],o);let s="imgs/"+e+"/"+t+"."+Et[o.type];i[t].src=s,i[t].getAttribute("xlink:href")&&i[t].setAttribute("xlink:href",s)}catch(e){console.error(e)}}let r=Array.from(t.getElementsByTagName("link"));for(let t=0;te.blob()));n.file(t+"."+Et[r.type],r),i.href="css/"+e+"/"+t+"."+Et[r.type]}catch(e){console.error(e)}}h.push(t.documentElement.innerHTML)}let u=c.folder("chapters");if(u){for(let e=0;ed(void 0,void 0,void 0,(function*(){t(yield new Response(e).arrayBuffer())})))).catch((e=>{t("err")}))}}))));class It extends At{constructor(e,t){super(Object.assign({format:"EPUB"},t)),this.epubBuffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){let e=new Blob([this.epubBuffer]),t=new File([e],"book",{lastModified:(new Date).getTime(),type:e.type});try{const e=yield this.makeZipLoader(t);this.book=yield new Te(e).init()}catch(e){throw console.error(e),e}}))}preCache(){return d(this,void 0,void 0,(function*(){try{return this.book||(yield this.parse()),yield Rt(this.book)}catch(e){return""}}))}makeZipLoader(e){return d(this,void 0,void 0,(function*(){let t=yield r.loadAsync(e);const i=t.files;return{entries:Object.values(i).map((e=>({filename:e.name}))),loadText:e=>d(this,void 0,void 0,(function*(){let i=t.file(e);return i?i.async("string"):""})),loadBlob:e=>d(this,void 0,void 0,(function*(){let i=t.file(e);if(i){let e=yield i.async("arraybuffer");return new Blob([e])}return new Blob([new ArrayBuffer(0)])})),getSize:e=>0}}))}getMetadata(){return d(this,void 0,void 0,(function*(){try{this.book||(yield this.parse());let e=new L(this.book);return yield e.getMetadata()}catch(e){throw console.error(e,"error"),e}}))}}const Nt=e=>{if(!e)return"";const t=document.createElement("textarea");return t.innerHTML=e,t.value},Bt={XML:"application/xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml"},Ot={name:[0,32,"string"],type:[60,4,"string"],creator:[64,4,"string"],numRecords:[76,2,"uint"]},Ht={compression:[0,2,"uint"],numTextRecords:[8,2,"uint"],recordSize:[10,2,"uint"],encryption:[12,2,"uint"]},Pt={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"]},Ft={resourceStart:[108,4,"uint"],fdst:[192,4,"uint"],numFdst:[196,4,"uint"],frag:[248,4,"uint"],skel:[252,4,"uint"],guide:[260,4,"uint"]},$t={magic:[0,4,"string"],length:[4,4,"uint"],count:[8,4,"uint"]},Ut={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"]},jt={magic:[0,4,"string"],length:[4,4,"uint"],numControlBytes:[8,4,"uint"]},Wt={magic:[0,4,"string"],offset1:[8,4,"uint"],offset2:[12,4,"uint"]},qt={magic:[0,4,"string"],length:[4,4,"uint"],numEntries:[8,4,"uint"],codeLength:[12,4,"uint"]},zt={magic:[0,4,"string"],numEntries:[8,4,"uint"]},Xt={flags:[8,4,"uint"],dataStart:[12,4,"uint"],keyLength:[16,4,"uint"],keyStart:[20,4,"uint"]},Vt={1252:"windows-1252",65001:"utf-8"},Jt={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"]},Gt={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"]},Zt=(e,t)=>{const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},_t=(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},Yt=new TextDecoder,Kt=e=>Yt.decode(e),Qt=e=>{if(!e)return;const t=e.byteLength,i=4===t?"getUint32":2===t?"getUint16":"getUint8";return new DataView(e)[i](0)},ei=(e,t)=>Object.fromEntries(Array.from(Object.entries(e)).map((([e,[i,r,n]])=>[e,("string"===n?Kt:Qt)(t.slice(i,i+r))]))),ti=e=>new TextDecoder(Vt[e]),ii=(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}},ri=e=>{let t=0;for(const i of e.subarray(-4))128&i&&(t=0),t=t<<7|127&i;return t},ni=e=>{let t=0;for(;e>0;e>>=1)1&~e||t++;return t},oi=e=>{let t=0;for(;!(1&e);)e>>=1,t++;return t},si=e=>{let t=[];for(let i=0;i>>3,s=3+(7&n);for(let e=0;e{const i=t+32,r=i>>3;let n=0n;for(let i=t>>3;i<=r;i++)n=n<<8n|BigInt(e[i]??0);return n>>8n-BigInt(7&i)&0xffffffffn},li=async(e,t)=>{const i=await t(e),r=ei(Ut,i);if("INDX"!==r.magic)throw new Error("Invalid INDX record");const n=ti(r.encoding),o=i.slice(r.length),s=ei(jt,o);if("TAGX"!==s.magic)throw new Error("Invalid TAGX section");const a=(s.length-12)/4,l=Array.from({length:a},((e,t)=>new Uint8Array(o.slice(12+4*t,12+4*t+4)))),c={};let d=0;for(let i=0;i1){const{value:i,length:r}=ii(n,p);d.push([e,null,i,t]),p+=r}else d.push([e,1,null,t]);else d.push([e,a>>oi(i),null,t])}const g={};for(const[e,t,i,r]of d){const o=[];if(null!=t)for(let e=0;eQt(i.slice(8*t,8*t+4)))).map(((e,t,i)=>[e,i[t+1]]))}loadRecord(e){const t=this.#d[e];if(!t)throw new RangeError("Record index out of bounds");return this.#c.slice(...t).arrayBuffer()}async loadMagic(e){const t=this.#d[e][0];return Kt(await this.#c.slice(t,t+4).arrayBuffer())}}class di extends ci{#h=0;#u;#f;#p;#g;#m;constructor({unzlib:e}){super(),this.unzlib=e}async open(e){await super.open(e),this.headers=this.#y(await super.loadRecord(0)),this.#u=this.headers.mobi.resourceStart;let t=this.headers.mobi.version>=8;if(!t){const e=this.headers.exth?.boundary;if(e<4294967295)try{this.headers=this.#y(await super.loadRecord(e)),this.#h=e,t=!0}catch(e){console.warn(e),console.warn("Failed to open KF8; falling back to MOBI")}}return await this.#b(),t?new vi(this).init():new fi(this).init()}#y(e){const t=ei(Ht,e),i=ei(Pt,e);if("MOBI"!==i.magic)throw new Error("Missing MOBI header");const{titleOffset:r,titleLength:n,localeLanguage:o,localeRegion:s}=i;i.title=e.slice(r,r+n);const a=Gt[o];i.language=a?.[s>>2]??a?.[0];const l=64&i.exthFlag?((e,t)=>{const{magic:i,count:r}=ei($t,e);if("EXTH"!==i)throw new Error("Invalid EXTH header");const n=ti(t),o={};let s=12;for(let t=0;t=8?ei(Ft,e):null}}async#b(){const{palmdoc:e,mobi:t}=this.headers;this.#f=ti(t.encoding),this.#p=new TextEncoder;const{compression:i}=e;if(this.#g=1===i?e=>e:2===i?si:17480===i?await(async(e,t)=>{const i=await t(e.huffcdic),{magic:r,offset1:n,offset2:o}=ei(Wt,i);if("HUFF"!==r)throw new Error("Invalid HUFF record");const s=Array.from({length:256},((e,t)=>n+4*t)).map((e=>Qt(i.slice(e,e+4)))).map((e=>[128&e,31&e,e>>>8])),a=[null].concat(Array.from({length:32},((e,t)=>o+8*t)).map((e=>[Qt(i.slice(e,e+4)),Qt(i.slice(e+4,e+8))]))),l=[];for(let i=1;i{let t=new Uint8Array;const i=8*e.byteLength;for(let r=0;r>>24];if(!o){for(;n>>>32-di)break;const u=h-(n>>>32-d);let[f,p]=l[u];p||(f=c(f),l[u]=[f,!0]),t=Zt(t,f)}return t};return c})(t,this.loadRecord.bind(this)):null,!this.#g)throw new Error("Unknown compression type");const{trailingFlags:r}=t,n=1&r,o=ni(r>>>1);this.#m=e=>{for(let t=0;tnew Uint8Array(e))).then(this.#m).then(this.#g)}async loadResource(e){const t=await super.loadRecord(this.#u+e),i=Kt(t.slice(0,4));return"FONT"===i?(async(e,t)=>{const{flags:i,dataStart:r,keyLength:n,keyStart:o}=ei(Xt,e),s=new Uint8Array(e.slice(r));if(2&i){const t=16===n?1024:1040,i=new Uint8Array(e.slice(o,o+n)),r=Math.min(t,s.length);for(var a=0;a{const{table:i,cncx:r}=await li(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]}))),o=e=>(null==e.firstChild||(e.children=n.filter((t=>t.parent===e.index)).map(o)),e);return n.filter((e=>0===e.headingLevel)).map(o)})(e,this.loadRecord.bind(this))}getMetadata(){const{mobi:e,exth:t}=this.headers;return{identifier:e.uid.toString(),title:Nt(t?.title||this.decode(e.title)),author:t?.creator?.map(Nt),publisher:Nt(t?.publisher),language:t?.language??e.language,published:t?.date,description:Nt(t?.description),subject:t?.subject?.map(Nt),rights:Nt(t?.rights)}}async getCover(){const{exth:e}=this.headers,t=e?.coverOffset<4294967295?e?.coverOffset:e?.thumbnailOffset<4294967295?e?.thumbnailOffset:null;if(null!=t){const e=await this.loadResource(t);return new Blob([e])}}}const hi=/<\s*(?:mbp:)?pagebreak[^>]*>/gi,ui=/<[^<>]+filepos=['"]{0,1}(\d+)[^<>]*>/gi;class fi{parser=new DOMParser;serializer=new XMLSerializer;#w=new Map;#v=new Map;#r=new Map;#x;#C=[];#L=Bt.HTML;constructor(e){this.mobi=e}async init(){let e=new Uint8Array;for(let t=0;tString.fromCharCode(e))).join("");this.#x=[0].concat(Array.from(t.matchAll(hi),(e=>e.index))).map(((e,i,r)=>t.slice(e,r[i+1]))).map((e=>Uint8Array.from(e,(e=>e.charCodeAt(0))))).map((e=>({book:this,raw:e}))).reduce(((e,t)=>{const i=e[e.length-1];return t.start=i?.end??0,t.end=t.start+t.raw.byteLength,e.concat(t)}),[]),this.sections=this.#x.map(((e,t)=>({id:t,load:()=>this.loadSection(e),createDocument:()=>this.createDocument(e),size:e.end-e.start})));try{this.landmarks=await this.getGuide();const e=this.landmarks.find((({type:e})=>e?.includes("toc")))?.href;if(e){const{index:t}=this.resolveHref(e),i=await this.sections[t].createDocument();let r,n=0,o=0;const s=new Map,a=new Map;this.toc=Array.from(i.querySelectorAll("a[filepos]")).reduce(((e,t)=>{const i=(e=>{let t=0;for(;e;){const i=e.parentElement;if(i){const e=i.tagName.toLowerCase();"p"===e?t+=1.5:"blockquote"===e&&(t+=2)}e=i}return t})(t),l={label:t.innerText?.trim(),href:`filepos:${t.getAttribute("filepos")}`},c=i>o?n+1:i===o?n:s.get(i)??Math.max(0,n-1);if(c>n)r?(r.subitems??=[],r.subitems.push(l),a.set(c,r)):e.push(l);else{const t=a.get(c);t?t.subitems.push(l):e.push(l)}return r=l,n=c,o=i,s.set(i,c),e}),[])}}catch(e){console.warn(e)}return this.#C=[...new Set(Array.from(t.matchAll(ui),(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.#x[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.#w.has(e))return this.#w.get(e);const t=await this.mobi.loadResource(e),i=URL.createObjectURL(new Blob([t]));return this.#w.set(e,i),i}async loadRecindex(e){return this.loadResource(Number(e)-1)}async replaceResources(e){for(const t of e.querySelectorAll("img[recindex]")){const e=t.getAttribute("recindex");try{t.src=await this.loadRecindex(e)}catch(t){console.warn(`Failed to load image ${e}`)}}for(const t of e.querySelectorAll("[mediarecindex]")){const e=t.getAttribute("mediarecindex"),i=t.getAttribute("recindex");try{t.src=await this.loadRecindex(e),i&&(t.poster=await this.loadRecindex(i))}catch(t){console.warn(`Failed to load media ${e}`)}}for(const t of e.querySelectorAll("[filepos]")){const e=t.getAttribute("filepos");t.href=`filepos:${e}`}}async loadText(e){if(this.#v.has(e))return this.#v.get(e);const{raw:t}=e,i=this.#C.filter((({number:t})=>t>=e.start&&t({...t,offset:t.number-e.start})));let r=t;i.length&&(r=t.subarray(0,i[0].offset),i.forEach((({filepos:e,offset:n},o)=>{const s=i[o+1],a=this.mobi.encode(``);r=_t(r,a,t.subarray(n,s?.offset))})));const n=this.mobi.decode(r).replaceAll(hi,"");return this.#v.set(e,n),n}async createDocument(e){const t=await this.loadText(e);return this.parser.parseFromString(t,this.#L)}async loadSection(e){if(this.#r.has(e))return this.#r.get(e);const t=await this.createDocument(e),i=t.createElement("style");t.head.append(i),i.append(t.createTextNode("blockquote {\n margin-block-start: 0;\n margin-block-end: 0;\n margin-inline-start: 1em;\n margin-inline-end: 0;\n }")),await this.replaceResources(t);const r=this.serializer.serializeToString(t),n=URL.createObjectURL(new Blob([r],{type:this.#L}));return this.#r.set(e,n),n}resolveHref(e){const t=e.match(/filepos:(.*)/)[1],i=Number(t);return{index:this.#x.findIndex((e=>e.end>i)),anchor:e=>e.getElementById(`filepos${t}`)}}splitTOCHref(e){const t=e.match(/filepos:(.*)/)[1],i=Number(t);return[this.#x.findIndex((e=>e.end>i)),`filepos${t}`]}getTOCFragment(e,t){return e.getElementById(t)}isExternal(e){return/^(?!blob|filepos)\w+:/i.test(e)}destroy(){for(const e of this.#w.values())URL.revokeObjectURL(e);for(const e of this.#r.values())URL.revokeObjectURL(e)}}const pi=/kindle:(flow|embed):(\w+)(?:\?mime=(\w+\/[-+.\w]+))?/,gi=/kindle:pos:fid:(\w+):off:(\w+)/,mi=e=>{const[t,i]=e.match(gi).slice(1);return{fid:parseInt(t,32),off:parseInt(i,32)}},yi=(e=0,t=0)=>`kindle:pos:fid:${e.toString(32).toUpperCase().padStart(4,"0")}:off:${t.toString(32).toUpperCase().padStart(10,"0")}`,bi=e=>{const t=e.match(/\s(id|name|aid)\s*=\s*['"]([^'"]*)['"]/i);if(!t)return;const[,i,r]=t;return`[${i}="${CSS.escape(r)}"]`},wi=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"}};class vi{parser=new DOMParser;serializer=new XMLSerializer;#r=new Map;#T=new Map;#S=new Map;#M={};#x;#A;#k=new Uint8Array;#E=new Uint8Array;#D=-1;#R=-1;#L=Bt.XHTML;#I=new Map;constructor(e){this.mobi=e}async init(){const e=this.mobi.loadRecord.bind(this.mobi),{kf8:t}=this.mobi.headers;try{const i=await e(t.fdst),r=ei(zt,i);if("FDST"!==r.magic)throw new Error("Missing FDST record");const n=Array.from({length:r.numEntries},((e,t)=>12+8*t)).map((e=>[Qt(i.slice(e,e+4)),Qt(i.slice(e+4,e+8))]));this.#M.fdstTable=n,this.#A=n[n.length-1][1]}catch{}const i=(await li(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]}))),r=await li(t.frag,e),n=r.table.map((({name:e,tagMap:t})=>({insertOffset:parseInt(e),selector:r.cncx[t[2][0]],index:t[4][0],offset:t[6][0],length:t[6][1]})));this.#M.skelTable=i,this.#M.fragTable=n,this.#x=i.reduce(((e,t)=>{const i=e[e.length-1],r=i?.fragEnd??0,o=r+t.numFrag,s=n.slice(r,o),a=t.length+s.map((e=>e.length)).reduce(((e,t)=>e+t)),l=(i?.totalLength??0)+a;return e.concat({skel:t,frags:s,fragEnd:o,length:a,totalLength:l})}),[]);const o=await this.getResourcesByMagic(["RESC","PAGE"]),s=new Map;if(o.RESC){const e=await this.mobi.loadRecord(o.RESC),t=this.mobi.decode(e.slice(16)).replace(/\0/g,""),i=t.search(/\?>/),r=`${t.slice(i)}`,n=this.parser.parseFromString(r,Bt.XML);for(const e of n.querySelectorAll("spine > itemref")){const t=parseInt(e.getAttribute("skelid"));s.set(t,wi(e.getAttribute("properties")?.split(" ")??[]))}}this.sections=this.#x.map(((e,t)=>e.frags.length?{id:t,load:()=>this.loadSection(e),createDocument:()=>this.createDocument(e),size:e.length,pageSpread:s.get(t)}:{linear:"no"}));try{const e=await this.mobi.getNCX(),t=({label:e,pos:i,children:r})=>{const[n,o]=i,s=yi(n,o),a=this.#T.get(n);return a?a.push(o):this.#T.set(n,[o]),{label:Nt(e),href:s,subitems:r?.map(t)}};this.toc=e?.map(t),this.landmarks=await this.getGuide()}catch(e){console.warn(e)}const{exth:a}=this.mobi.headers;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(e){const t={},i=this.mobi.headers.kf8.resourceStart,r=this.mobi.pdb.numRecords;for(let n=i;ne===i));r&&(t[r]=n)}catch{}return t}async getGuide(){const e=this.mobi.headers.kf8.guide;if(e<4294967295){const t=this.mobi.loadRecord.bind(this.mobi),{table:i,cncx:r}=await li(e,t);return i.map((({name:e,tagMap:t})=>({label:r[t[1][0]]??"",type:e?.split(/\s/),href:yi(t[6]?.[0]??t[3]?.[0])})))}}async loadResourceBlob(e){const{resourceType:t,id:i,type:r}=(e=>{const[t,i,r]=e.match(pi).slice(1);return{resourceType:t,id:parseInt(i,32),type:r}})(e),n="flow"===t?await this.loadFlow(i):await this.mobi.loadResource(i-1),o=[Bt.XHTML,Bt.HTML,Bt.CSS,Bt.SVG].includes(r)?await this.replaceResources(this.mobi.decode(n)):n,s=r===Bt.SVG?this.parser.parseFromString(o,r):null;return[new Blob([o],{type:r}),s?.getElementsByTagNameNS("http://www.w3.org/2000/svg","image")?.length?s.documentElement:null]}async loadResource(e){if(this.#r.has(e))return this.#r.get(e);const[t,i]=await this.loadResourceBlob(e),r=i?e:URL.createObjectURL(t);return i&&this.#I.set(r,i),this.#r.set(e,r),r}replaceResources(e){return(async(e,t,i)=>{const r=[];e.replace(t,((...e)=>(r.push(e),null)));const n=[];for(const e of r)n.push(await i(...e));return e.replace(t,(()=>n.shift()))})(e,new RegExp(pi,"g"),this.loadResource.bind(this))}async loadRaw(e,t){const i=t-this.#k.length,r=null==this.#A?1/0:this.#A-this.#E.length-e;if(i<0||ie;){const e=this.mobi.headers.palmdoc.numTextRecords-1-++this.#R,t=await this.mobi.loadText(e);this.#E=Zt(t,this.#E)}const n=this.#A-this.#E.length;return this.#E.slice(e-n,t-n)}loadFlow(e){if(e<4294967295)return this.loadRaw(...this.#M.fdstTable[e])}async loadText(e){const{skel:t,frags:i,length:r}=e,n=await this.loadRaw(t.offset,t.offset+r);let o=n.slice(0,t.length);for(const e of i){const i=e.insertOffset-t.offset,r=t.length+e.offset,s=n.slice(r,r+e.length);o=_t(o.slice(0,i),s,o.slice(i));const a=this.#T.get(e.index);if(a)for(const t of a){const i=this.mobi.decode(s).slice(t),r=bi(i);this.#N(e.index,t,r)}}return this.mobi.decode(o)}async createDocument(e){const t=await this.loadText(e);return this.parser.parseFromString(t,this.#L)}async loadSection(e){if(this.#r.has(e))return this.#r.get(e);const t=await this.loadText(e),i=await this.replaceResources(t);let r=this.parser.parseFromString(i,this.#L);r.querySelector("parsererror")&&(this.#L=Bt.HTML,r=this.parser.parseFromString(i,this.#L));for(const[e,t]of this.#I)for(const i of r.querySelectorAll(`img[src="${e}"]`))i.replaceWith(t);const n=URL.createObjectURL(new Blob([this.serializer.serializeToString(r)],{type:this.#L}));return this.#r.set(e,n),n}getIndexByFID(e){return this.#x.findIndex((t=>t.frags.some((t=>t.index===e))))}#N(e,t,i){const r=this.#S.get(e);if(r)r.set(t,i);else{const r=new Map;this.#S.set(e,r),r.set(t,i)}}async resolveHref(e){const{fid:t,off:i}=mi(e),r=this.getIndexByFID(t);if(r<0)return;const n=this.#S.get(t)?.get(i);if(n)return{index:r,anchor:e=>e.querySelector(n)};const{skel:o,frags:s}=this.#x[r],a=s.find((e=>e.index===t)),l=o.offset+o.length+a.offset,c=await this.loadRaw(l,l+a.length),d=this.mobi.decode(c).slice(i),h=bi(d);this.#N(t,i,h);return{index:r,anchor:e=>e.querySelector(h)}}splitTOCHref(e){const t=mi(e);return[this.getIndexByFID(t.fid),t]}getTOCFragment(e,{fid:t,off:i}){const r=this.#S.get(t)?.get(i);return e.querySelector(r)}isExternal(e){return/^(?!blob|kindle)\w+:/i.test(e)}destroy(){for(const e of this.#r.values())URL.revokeObjectURL(e)}}class xi extends At{constructor(e,t){super(Object.assign({format:"MOBI"},t)),this.mobiBuffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){try{let e=new Blob([this.mobiBuffer]),t=new File([e],"book",{lastModified:(new Date).getTime(),type:e.type});(yield(async e=>"BOOKMOBI"===Kt(await e.slice(60,68).arrayBuffer()))(t))&&(this.book=yield new di({unzlib:n}).open(t))}catch(e){throw console.error(e),e}}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield Rt(this.book)}))}getMetadata(){return d(this,void 0,void 0,(function*(){try{this.book||(yield this.parse());let e=new L(this.book);return yield e.getMetadata()}catch(e){throw console.error(e),e}}))}}const Ci=e=>`${Si()?".":""}/lib/pdfjs/${e}`,Li=window.pdfjsLib,Ti=async e=>await(await fetch(e)).text(),Si=()=>"undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type||(!("undefined"==typeof process||"object"!=typeof process.versions||!process.versions.electron)||"object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0),Mi=async()=>await Ti(Ci("text_layer_builder.css")),Ai=async()=>await Ti(Ci("annotation_layer_builder.css")),ki=async(e,t)=>{const i=e.getViewport({scale:1});if(t){const t=document.createElement("canvas");t.height=i.height,t.width=i.width;const r=t.getContext("2d");return await e.render({canvasContext:r,viewport:i}).promise,new Promise((e=>t.toBlob(e)))}return URL.createObjectURL(new Blob([`\n \n \n \n \n \n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n\n `],{type:"text/html"}))},Ei=e=>({label:e.title,href:e.dest?JSON.stringify(e.dest):null,subitems:e.items.length?e.items.map(Ei):null}),Di=async(e,t)=>{const i=new Li.PDFDataRangeTransport(e.size,[]);i.requestDataRange=(t,r)=>{e.slice(t,r).arrayBuffer().then((e=>{i.onDataRange(t,e)}))},console.log(Ci("cmaps/"));const r=await Li.getDocument({range:i,cMapUrl:Ci("cmaps/"),standardFontDataUrl:Ci("standard_fonts/"),isEvalSupported:!1}).promise,n={rendition:{layout:"pre-paginated"}},{metadata:o,info:s}=await r.getMetadata()??{};n.metadata={title:o?.get("dc:title")??s?.Title,author:o?.get("dc:creator")??s?.Author,contributor:o?.get("dc:contributor"),description:o?.get("dc:description")??s?.Subject,language:o?.get("dc:language"),publisher:o?.get("dc:publisher"),subject:o?.get("dc:subject"),identifier:o?.get("dc:identifier"),source:o?.get("dc:source"),rights:o?.get("dc:rights")};const a=await r.getOutline();n.toc=a?.map(Ei).filter(((e,i)=>"double"!==t||i%2==0));const l=new Map;return n.sections=Array.from({length:r.numPages}).map(((e,i)=>({id:i,load:async()=>{const e=l.get(i);if(e)return e;const t=await ki(await r.getPage(i+1));return l.set(i,t),t},unload:async()=>{(await r.getPage(i+1)).cleanup()},render:async(e,n)=>{await(async(e,t,i)=>{const r=i*devicePixelRatio;let n=t.querySelector("#koodoPDFLayer");n.style.visibility="hidden",n.style.transform=`scale(${1/devicePixelRatio})`,n.style.transformOrigin="top left",n.style.setProperty("--scale-factor",r);const o=e.getViewport({scale:r}),s=document.createElement("canvas");n.style.width=`${o.width}px`,n.style.height=`${o.height}px`,s.height=o.height,s.width=o.width;const a=s.getContext("2d");await e.render({canvasContext:a,viewport:o,background:"rgba(0,0,0,0)"}).promise,t.querySelector("#canvas").replaceChildren(t.adoptNode(s)),n.style.overflow="hidden";const l=t.querySelector("#textLayer"),c=new Li.TextLayer({textContentSource:await e.streamTextContent(),container:l,viewport:o});await c.render();for(const e of document.querySelectorAll(".hiddenCanvasElement"))Object.assign(e.style,{position:"absolute",top:"0",left:"0",width:"0",height:"0",display:"none"});const d=document.createElement("div");d.className="endOfContent",l.append(d),l.onpointerdown=()=>l.classList.add("selecting"),l.onpointerup=()=>l.classList.remove("selecting");const h=t.querySelector("#annotationLayer");await new Li.AnnotationLayer({page:e,viewport:o,div:h}).render({annotations:await e.getAnnotations(),linkService:{goToDestination:()=>{},getDestinationHash:e=>JSON.stringify(e),addLinkAttributes:(e,t)=>e.href=t}}),n.style.marginLeft=`calc(50% - ${n.getBoundingClientRect().width/2}px)`,n.style.visibility="visible"})(await r.getPage(i+1),e,n),"double"===t&&await(async(e,t,i)=>{const r=i*devicePixelRatio;let n=t.querySelector("#koodoPDFLayerExtra");n.style.display="block",n.style.visibility="hidden",n.style.transform=`scale(${1/devicePixelRatio})`,n.style.transformOrigin="top left",n.style.setProperty("--scale-factor",r);const o=e.getViewport({scale:r}),s=document.createElement("canvas");n.style.width=`${o.width}px`,n.style.height=`${o.height}px`,s.height=o.height,s.width=o.width;const a=s.getContext("2d");await e.render({canvasContext:a,viewport:o,background:"rgba(0,0,0,0)"}).promise,t.querySelector("#canvasExtra").replaceChildren(t.adoptNode(s)),n.style.overflow="hidden";const l=t.querySelector("#textLayerExtra"),c=new Li.TextLayer({textContentSource:await e.streamTextContent(),container:l,viewport:o});await c.render();for(const e of document.querySelectorAll(".hiddenCanvasElement"))Object.assign(e.style,{position:"absolute",top:"0",left:"0",width:"0",height:"0",display:"none"});const d=document.createElement("div");d.className="endOfContent",l.append(d),l.onpointerdown=()=>l.classList.add("selecting"),l.onpointerup=()=>l.classList.remove("selecting");const h=t.querySelector("#annotationLayerExtra");await new Li.AnnotationLayer({page:e,viewport:o,div:h}).render({annotations:await e.getAnnotations(),linkService:{goToDestination:()=>{},getDestinationHash:e=>JSON.stringify(e),addLinkAttributes:(e,t)=>e.href=t}}),n.style.marginLeft=`calc(50% - ${n.getBoundingClientRect().width/2}px)`,n.style.visibility="visible"})(await r.getPage(i+2),e,n)},size:1e3,getDimension:async()=>{let e=(await r.getPage(i+1)).getViewport({scale:1});return{width:e.width,height:e.height}},getPage:async()=>await r.getPage(i+1)}))).filter(((e,i)=>"double"!==t||i%2==0)),n.isExternal=e=>/^\w+:/i.test(e),n.resolveHref=async e=>{const t=JSON.parse(e),i="string"==typeof t?await r.getDestination(t):t;return{index:await r.getPageIndex(i[0])}},n.splitTOCHref=async e=>{const t=JSON.parse(e),i="string"==typeof t?await r.getDestination(t):t;return[await r.getPageIndex(i[0]),null]},n.getTOCFragment=e=>e.documentElement,n.getCover=async()=>ki(await r.getPage(1),!0),n.destroy=()=>r.destroy(),n};class Ri extends At{constructor(e,t){super(Object.assign(Object.assign({format:"PDF"},t),{convertChinese:"Default"})),this.pdfBuffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){try{let e=new Blob([this.pdfBuffer]),t=new File([e],"book",{lastModified:(new Date).getTime(),type:e.type});(yield(async e=>{const t=new Uint8Array(await e.slice(0,5).arrayBuffer());return 37===t[0]&&80===t[1]&&68===t[2]&&70===t[3]&&45===t[4]})(t))&&(this.book=yield Di(t,this.readerMode))}catch(e){throw console.error(e),e}}))}preCache(){return d(this,void 0,void 0,(function*(){return""}))}getMetadata(){return d(this,void 0,void 0,(function*(){try{this.book||(yield this.parse());let e=new L(this.book);return yield e.getMetadata()}catch(e){throw console.error(e),e}}))}getHightlightCoords(){return d(this,void 0,void 0,(function*(){let e=this.tempLocation.chapterDocIndex,t=this.getDocument();if(!t)return;var i=t.getSelection().getRangeAt(0).getClientRects();let r=yield this.chapterDocList[e].text.getPage(),n=yield Ge(this.element,this.readerMode,this.chapterDocList,e);var o=r.getViewport({scale:n});let s=t.querySelector("canvas");var a=null==s?void 0:s.getClientRects()[0];let l=[];for(let e=0;ei[e].left&&(l[l.length-1].left=i[e].left),l[l.length-1].rightd(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){try{const e=new TextDecoder(this.charset),t=new Uint8Array(this.txtBuffer);let i=e.decode(t);this.book=Se(i,!0,this.parserRegex)}catch(e){throw console.error(e),e}}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield Rt(this.book)}))}getMetadata(e){return d(this,void 0,void 0,(function*(){try{const t=new Uint8Array(e);let i=o.detect(t);return this.charset=i||"utf8",{charset:i||"utf8"}}catch(e){throw console.error(e),e}}))}}const Ni=({entries:e,loadBlob:t,getSize:i},r,n)=>{const o=new Map,s=new Map,a=async(e,i)=>{if(o.has(e))return o.get(e);if(i){const r=URL.createObjectURL(await t(e)),n=URL.createObjectURL(await t(i)),a=URL.createObjectURL(new Blob([`
`],{type:"text/html"}));return s.set(e,[r,a]),o.set(e,a),a}{const i=URL.createObjectURL(await t(e)),r=URL.createObjectURL(new Blob([`
`],{type:"text/html"}));return s.set(e,[i,r]),o.set(e,r),r}},l=[".jpg",".jpeg",".png",".gif",".bmp",".webp",".svg"],c=e.map((e=>e.filename)).filter((e=>l.some((t=>e.endsWith(t))))).sort(),d={getCover:()=>t(c[0])};return d.metadata={title:r.name},d.sections=c.map(((e,t)=>({id:e,load:()=>{if("double"===n){const i=c[t+1];return a(e,i)}return a(e)},unload:()=>(e=>{s.get(e)?.forEach?.((e=>URL.revokeObjectURL(e))),s.delete(e),o.delete(e)})(e),size:i(e)}))).filter(((e,t)=>"double"!==n||t%2==0)),d.toc=c.map((e=>({label:e,href:e}))).filter(((e,t)=>"double"!==n||t%2==0)),d.rendition={layout:"pre-paginated"},d.resolveHref=e=>({index:d.sections.findIndex((t=>t.id===e))}),d.splitTOCHref=e=>[e,null],d.getTOCFragment=e=>e.documentElement,d};class Bi extends At{constructor(e,t){super(t),this.comicBuffer=e,this.readerMode=t.readerMode,this.format=t.format,this.chapterList=[],this.chapterDocList=[],this.book="",this.element="",this.rpc}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){if(this.element=e,m(e),!this.book)try{yield this.parse()}catch(e){console.error(e),i(e)}let r=new L(this.book);this.chapterList=yield r.getChapter(this.book.toc),this.chapterDocList=yield r.getChapterDoc();let n=this.getDocument();n&&(x(e,this.readerMode,n),t())}))))}parse(){return d(this,void 0,void 0,(function*(){try{let e=new Blob([this.comicBuffer]),t=new File([e],"book."+this.format.toLocaleLowerCase(),{lastModified:(new Date).getTime(),type:e.type});if("CBZ"===this.format){const e=yield this.makeZipLoader(t);this.book=Ni(e,t,this.readerMode)}else if("CBT"===this.format){const e=yield this.makeTarLoader();this.book=Ni(e,t,this.readerMode)}else if("CBR"===this.format){this.rpc=yield window.RPC.new("./lib/libunrar/worker.js",{loaded:function(){console.info("loaded")},progressShow:function(e,t,i){console.info(i)}}),yield new Promise((e=>setTimeout(e,200)));const e=yield this.makeRarLoader();this.book=Ni(e,t,this.readerMode)}else if("CB7"===this.format){const e=yield this.make7zLoader();this.book=Ni(e,t,this.readerMode)}}catch(e){throw console.error(e),e}}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield Rt(this.book)}))}makeZipLoader(e){return d(this,void 0,void 0,(function*(){let t=yield r.loadAsync(e);const i=t.files;return{entries:Object.values(i).map((e=>({filename:e.name}))),loadText:e=>d(this,void 0,void 0,(function*(){let i=t.file(e);return i?i.async("string"):""})),loadBlob:e=>d(this,void 0,void 0,(function*(){let i=t.file(e);if(i){let e=yield i.async("arraybuffer");return new Blob([e])}return new Blob([new ArrayBuffer(0)])})),getSize:e=>0}}))}makeTarLoader(){return d(this,void 0,void 0,(function*(){const e=yield s(this.comicBuffer),t=new Map(e.map((e=>[e.name,e]))),i=e=>(i,...r)=>t.has(i)?e(t.get(i),...r):null,r=i((e=>e.readAsString())),n=i(((e,t)=>e.blob));return{entries:e.map((e=>({filename:e.name}))),loadText:r,loadBlob:n,getSize:e=>{var i,r;return null!==(r=null===(i=t.get(e))||void 0===i?void 0:i.size)&&void 0!==r?r:0}}}))}makeRarLoader(){return d(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{var i=[this.comicBuffer],r=[{name:"book.rar",content:this.comicBuffer}];this.rpc.transferables=i,this.rpc.unrar(r,null,0).then((t=>{let i=this.getRarEntries(t.ls);const r=new Map(Object.values(i).map((e=>[e.fullFileName,e]))),n=e=>(t,...i)=>r.has(t)?e(r.get(t),...i):null,o=n((e=>e.fullFileName)),s=n(((e,t)=>new Blob([e.fileContent])));e({entries:Object.values(i).map((e=>({filename:e.fullFileName}))),loadText:o,loadBlob:s,getSize:e=>{var t,i;return null!==(i=null===(t=r.get(e))||void 0===t?void 0:t.fileSize)&&void 0!==i?i:0}})})).catch((e=>{console.error(e),t(e)}))}))}))}make7zLoader(){return d(this,void 0,void 0,(function*(){const e="./lib/7z-wasm/7zz.wasm";if(!window.wasmBinary){const t=yield fetch(e,{credentials:"same-origin"});if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";window.wasmBinary=yield t.arrayBuffer()}const t=yield window.SevenZip({wasmBinary:window.wasmBinary}),i=new Uint8Array(this.comicBuffer),r="archive.cb7",n=t.FS.open(r,"w+");t.FS.write(n,i,0,i.length),t.FS.close(n),t.callMain(["x",r]);const o=t.FS,s=this.get7zEntries(o.lookupPath("/").node),a=new Map(s.map((e=>[e.name,e]))),l=e=>(t,...i)=>a.has(t)?e(a.get(t),...i):null,c=l((e=>e.name)),d=l(((e,t)=>new Blob([e.buffer])));return{entries:s.map((e=>({filename:e.name}))),loadText:c,loadBlob:d,getSize:e=>{var t,i;return null!==(i=null===(t=a.get(e))||void 0===t?void 0:t.packSize)&&void 0!==i?i:0}}}))}getRarEntries(e){const t=Object.keys(e);let i=[];for(let r=0;r"archive.cb7"!=e&&"dev"!=e&&"home"!=e&&"proc"!=e&&"tmp"!=e));let r=[];for(let e=0;ed(this,void 0,void 0,(function*(){try{this.book||(yield this.parse());const t=yield this.book.getCover();var i=new FileReader;i.readAsDataURL(t),i.onloadend=()=>{e({cover:i.result})}}catch(e){console.error(e),t(e)}}))))}))}}const Oi=e=>e?.trim()?.replace(/\s{2,}/g," "),Hi=e=>Oi(e?.textContent),Pi={XLINK:"http://www.w3.org/1999/xlink",EPUB:"http://www.idpf.org/2007/ops"},Fi="application/xml",$i="application/xhtml+xml",Ui={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"},ji={epigraph:["blockquote"],subtitle:["h2",Ui],"text-author":["p",Ui],date:["p",Ui],stanza:"stanza"},Wi={title:["header",{p:["h1",Ui],"empty-line":["br"]}],epigraph:["blockquote","self"],image:"image",annotation:["aside"],section:["section","self"],p:["p",Ui],poem:["blockquote",ji],subtitle:["h2",Ui],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",Ui]};ji.epigraph.push(Wi);const qi={image:"image",title:["section",{p:["h1",Ui],"empty-line":["br"]}],epigraph:["section",Wi],section:["section",Wi]},zi=e=>{const t=e.getAttributeNS(Pi.XLINK,"href"),[,i]=t.split("#"),r=e.getRootNode().getElementById(i);return r?`data:${r.getAttribute("content-type")};base64,${r.textContent}`:t};class Xi{constructor(e){this.fb2=e,this.doc=document.implementation.createDocument(Pi.XHTML,"html")}image(e){const t=this.doc.createElement("img");return t.alt=e.getAttribute("alt"),t.title=e.getAttribute("title"),t.setAttribute("src",zi(e)),t}anchor(e){const t=this.convert(e,{a:["a",Ui]});return t.setAttribute("href",e.getAttributeNS(Pi.XLINK,"href")),"note"===e.getAttribute("type")&&t.setAttributeNS(Pi.EPUB,"epub:type","noteref"),t}stanza(e){const t=this.convert(e,{stanza:["p",{title:["header",{p:["strong",Ui],"empty-line":["br"]}],subtitle:["p",Ui]}]});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);const i=t?.[e.nodeName];if(!i)return null;if("string"==typeof i)return this[i](e);const[r,n]=i,o=this.doc.createElement(r);if(e.id&&(o.id=e.id),o.classList.add(e.nodeName),Array.isArray(n))for(const t of n)o.setAttribute(t,e.getAttribute(t));const s="self"===n?t:Array.isArray(n)?null:n;let a=e.firstChild;for(;a;){const e=this.convert(a,s);e&&o.append(e),a=a.nextSibling}return o}}const Vi=URL.createObjectURL(new Blob(['\n@namespace epub "http://www.idpf.org/2007/ops";\nbody > img, section > img {\n display: block;\n margin: auto;\n}\n.title {\n text-align: center;\n}\nbody > section > .title, body.notesBodyType > .title {\n margin: 3em 0;\n}\nbody.notesBodyType > section .title {\n text-align: left;\n margin: 1em 0;\n}\np {\n text-indent: 1em;\n margin: 0;\n}\n:not(p) + p, p:first-child {\n text-indent: 0;\n}\n.poem p {\n text-indent: 0;\n margin: 1em 0;\n}\n.text-author, .date {\n text-align: end;\n}\n.text-author:before {\n content: "—";\n}\ntable {\n border-collapse: collapse;\n}\ntd, th {\n padding: .25em;\n}\na[epub|type~="noteref"] {\n font-size: .75em;\n vertical-align: super;\n}\nbody:not(.notesBodyType) > .title, body:not(.notesBodyType) > .epigraph {\n margin: 3em 0;\n}\n'],{type:"text/css"})),Ji="data-foliate-id",Gi=async e=>{const t={},i=await(async e=>{const t=await e.arrayBuffer(),i=new TextDecoder("utf-8").decode(t),r=new DOMParser,n=r.parseFromString(i,Fi),o=n.xmlEncoding||i.match(/^<\?xml\s+version\s*=\s*["']1.\d+"\s+encoding\s*=\s*["']([A-Za-z0-9._-]*)["']/)?.[1];if(o&&"utf-8"!==o.toLowerCase()){const e=new TextDecoder(o).decode(t);return r.parseFromString(e,Fi)}return n})(e),r=new Xi(i),n=e=>i.querySelector(e),o=e=>[...i.querySelectorAll(e)],s=e=>{const t=Hi(e.querySelector("nickname"));if(t)return t;const i=Hi(e.querySelector("first-name")),r=Hi(e.querySelector("middle-name")),n=Hi(e.querySelector("last-name"));return{name:[i,r,n].filter((e=>e)).join(" "),sortAs:n?[n,[i,r].filter((e=>e)).join(" ")].join(", "):null}},a=e=>e?.getAttribute("value")??Hi(e),l=n("title-info annotation");t.metadata={title:Hi(n("title-info book-title")),identifier:Hi(n("document-info id")),language:Hi(n("title-info lang")),author:o("title-info author").map(s),translator:o("title-info translator").map(s),producer:o("document-info author").map(s).concat(o("document-info program-used").map(Hi)),publisher:Hi(n("publish-info publisher")),published:a(n("title-info date")),modified:a(n("document-info date")),description:l?r.convert(l,{annotation:["div",Wi]}).innerHTML:null,subject:o("title-info genre").map(Hi)},t.getCover=()=>fetch(zi(n("coverpage image"))).then((e=>e.blob()));const c=Array.from(i.querySelectorAll("body"),(e=>{const t=r.convert(e,{body:["body",qi]});return[Array.from(t.children,(e=>{const t=[e,...e.querySelectorAll("[id]")].map((e=>e.id));return{el:e,ids:t}})),t]})),d=c[0][0].map((({el:e,ids:t})=>({ids:t,titles:Array.from(e.querySelectorAll(":scope > section > .title"),((e,t)=>(e.setAttribute(Ji,t),{title:Hi(e),index:t}))),el:e}))).concat(c.slice(1).map((([e,t])=>{const i=e.map((e=>e.ids)).flat();return t.classList.add("notesBodyType"),{ids:i,el:t,linear:"no"}}))).map((({ids:e,titles:t,el:i,linear:r})=>{const n=(o=i.outerHTML,`\n\n \n ${o}\n`);var o;const s=new Blob([n],{type:$i}),a=URL.createObjectURL(s);return{ids:e,title:Oi(i.querySelector(".title, .subtitle, p")?.textContent??(i.classList.contains("title")?i.textContent:"")),titles:t,load:()=>a,createDocument:()=>(new DOMParser).parseFromString(n,$i),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=d.map(((e,t)=>{const{ids:i,load:r,createDocument:n,size:o,linear:s}=e;for(const e of i)e&&h.set(e,t);return{id:t,load:r,createDocument:n,size:o,linear:s}})),t.toc=d.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(`[${Ji}="${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(`[${Ji}="${t}"]`),t};class Zi extends At{constructor(e,t){super(Object.assign({format:"FB2"},t)),this.fb2Buffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){try{let e=new Blob([this.fb2Buffer]);this.book=yield Gi(e)}catch(e){throw console.error(e),e}}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield Rt(this.book)}))}getMetadata(){return d(this,void 0,void 0,(function*(){try{this.book||(yield this.parse());let e=new L(this.book);return yield e.getMetadata()}catch(e){throw console.error(e),e}}))}}class _i extends At{constructor(e,t){super(Object.assign({format:"CACHE"},t)),this.cacheBuffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book=yield Dt(this.cacheBuffer);let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}}class Yi extends At{constructor(e,t){super(Object.assign({format:"DOCX"},t)),this.docxBuffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{try{a.convertToHtml({arrayBuffer:this.docxBuffer}).then((t=>d(this,void 0,void 0,(function*(){this.book=Se(t.value,!1),e()}))))}catch(e){console.error(e),t(e)}}))}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield Rt(this.book)}))}}class Ki extends At{constructor(e,t){super(Object.assign({format:"MD"},t)),this.mdBuffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{try{var i=new Blob([this.mdBuffer],{type:"text/plain"}),r=new FileReader;r.onload=t=>d(this,void 0,void 0,(function*(){var i;let r=yield l(null===(i=t.target)||void 0===i?void 0:i.result);this.book=Se(r,!1),e()})),r.readAsText(i,"UTF-8")}catch(e){console.error(e),t(e)}}))}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield Rt(this.book)}))}}class Qi extends At{constructor(e,t){super(t),this.htmlBuffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{try{var i=new Blob([this.htmlBuffer],{type:kt[this.format.toLocaleLowerCase()]}),r=new FileReader;r.onload=t=>d(this,void 0,void 0,(function*(){var i;let r=null===(i=t.target)||void 0===i?void 0:i.result;"MHTML"===this.format&&(r=c.convert(r).window.document.documentElement.innerHTML),this.book=Se(r,!1),e()})),r.readAsText(i,"UTF-8")}catch(e){console.error(e),t(e)}}))}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield Rt(this.book)}))}}export{_i as CacheRender,Bi as ComicRender,Yi as DocxRender,It as EpubRender,Zi as Fb2Render,Qi as HtmlRender,Ki as MdRender,xi as MobiRender,Ri as PdfRender,Ii as TxtRender}; +import e from"chinese-s2t";import t from"underscore";import i from"rangy/lib/rangy-core.js";import"rangy/lib/rangy-textrange";import r from"jszip";import{unzlibSync as n}from"fflate";import o from"chardet";import s from"js-untar";import a from"mammoth";import{marked as l}from"marked";import c from"mhtml2html";function d(e,t,i,r){return new(i||(i=Promise))((function(n,o){function s(e){try{l(r.next(e))}catch(e){o(e)}}function a(e){try{l(r.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}l((r=r.apply(e,t||[])).next())}))}const h=e=>e?parseFloat(e+""):0,u=(e,t)=>d(void 0,void 0,void 0,(function*(){let i="";if(e.load){let t=yield fetch(yield e.load()).then((e=>e.blob()));i=yield t.text()}return t||(e.loadAsset&&(i=yield p(i,e.loadAsset)),i=g(i)),i})),f=e=>Array.from(e.querySelectorAll("img, image")),p=(e,t)=>d(void 0,void 0,void 0,(function*(){let i=(new DOMParser).parseFromString(e,"text/html"),r=f(i);for(let e=0;e{var t;let i=(new DOMParser).parseFromString(e,"text/html"),r=f(i);if(0===r.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)},y=(e,t)=>({totalPage:"scroll"===e?1:"single"===e?Math.round(parseFloat(t.body.scrollWidth/t.body.clientWidth+"")):2*Math.round(parseFloat(t.body.scrollWidth/t.body.clientWidth+"")),currentPage:Math.round(parseFloat(h(t.body.scrollLeft)/t.body.clientWidth+""))+1}),b=e=>{let t=e.querySelectorAll("a, article, cite, div, li, p, span, pre, table, bold, font");for(let e=0;ed(void 0,void 0,void 0,(function*(){const t=new Image;t.src=e;try{yield t.decode()}catch(e){console.error(e)}return t})),v=(e,t,i,r)=>d(void 0,void 0,void 0,(function*(){let n=Math.floor(e.clientWidth/12),o=n%2==0?n:n-1,s=r.querySelectorAll("img, image");for(let n of s){let s=n.parentElement,a=0,l=0,c=n.naturalWidth,d=n.naturalHeight;if("image"===n.tagName){let e=yield w(n.getAttribute("xlink:href"));c=e.naturalWidth,d=e.naturalHeight}if(i.startsWith("CB")&&"scroll"===t)l=s.offsetWidth;else if(i.startsWith("CB")&&"single"===t)a=e.clientHeight,l=e.clientWidth;else if(s&&c&&d){d/c>s.clientHeight/s.clientWidth?(a=s.clientHeight,l=parseInt(a*c/d+"")):(l=s.clientWidth,a=parseInt(l*d/c+"")),a>r.body.clientHeight&&(l=parseInt(l*(r.body.clientHeight/a)+""),a=r.body.clientHeight)}else s&&s.clientWidth&&s.clientWidth>0?(l=s.clientWidth,a=s.clientHeight):(l=e.clientWidth,a=e.clientHeight);l=l?Math.min("scroll"===t||"single"===t?e.clientWidth:(e.clientWidth-o)/2,l):"scroll"===t||"single"===t?e.clientWidth:(e.clientWidth-o)/2,c&&d&&(c>d||a/l>d/c?a=l*(d/c):l=a*(c/d)),(l||a)&&n.setAttribute("style",(n.getAttribute("style")?n.getAttribute("style"):"")+";"+`max-width: ${l>0?l+"px":""};max-height:${a>0?a+"px":""}; margin: 0 auto; ${i.startsWith("CB")?`margin-left: calc(100% - ${n.clientWidth}px);`:""}`),i.startsWith("CB")&&"scroll"===t&&n.setAttribute("style",(n.getAttribute("style")?n.getAttribute("style"):"")+";margin-left: 0px; width: 100%;"),i.startsWith("CB")&&"scroll"!==t&&n.setAttribute("style",(n.getAttribute("style")?n.getAttribute("style"):"")+`;margin-left: calc(50% - ${n.getBoundingClientRect().width/2}px);`)}})),x=(e,t,i)=>{let r=i.createElement("style");if(r.id="default-style",r.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}",i.head.appendChild(r),"scroll"===t)return;let n="double"===t?2:1,o=Math.floor(e.clientWidth/12),s=o%2==0?o:o-1;i.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;touch-action: pan-y; overscroll-behavior: none;max-width: inherit;column-fill: auto;column-gap: ${s}px; column-width: ${(e.clientWidth-s)/n}px;`)};const C=e=>"string"==typeof e||e instanceof String;class L{constructor(e){this.book=e,this.chapterList=[],this.flattenChapters=[],this.chapterDocList=[]}unescapeHtml(e){if(!e)return"";return(new DOMParser).parseFromString(e,"text/html").documentElement.textContent||""}getChapter(e){return d(this,void 0,void 0,(function*(){return this.chapterList=e?yield Promise.all(e.map((e=>d(this,void 0,void 0,(function*(){let t=-1;try{t=e.href&&(yield this.book.resolveHref(e.href))?(yield this.book.resolveHref(e.href)).index:-1}catch(e){console.error(e)}return{label:this.unescapeHtml(e.label)?this.unescapeHtml(e.label):t+"",href:e.href?e.href:"title"+t,index:t,subitems:e.subitems?yield this.getChapter(e.subitems):[]}}))))):yield Promise.all(this.book.sections.map(((e,t)=>d(this,void 0,void 0,(function*(){return{label:this.unescapeHtml(e.label)?this.unescapeHtml(e.label):t+"",href:e.href?e.href:"title"+t,index:t,subitems:e.subitems?yield this.getChapter(e.subitems):[]}}))))),this.flattenChapters=this.flatChapter(this.chapterList),this.chapterList}))}getChapterDoc(){return d(this,void 0,void 0,(function*(){const e=this.flattenChapters.map((e=>e.index));return this.book.sections.map(((t,i)=>e.indexOf(i)>-1?{label:this.unescapeHtml(this.flattenChapters[e.indexOf(i)].label),href:this.flattenChapters[e.indexOf(i)].href,text:t}:{label:"",href:"",text:t}))}))}flatChapter(e){let t=[];for(let i=0;i0?(t.push(e[i]),t=t.concat(this.flatChapter(e[i].subitems))):t.push(e[i]);return t}getMetadata(){return new Promise(((e,t)=>d(this,void 0,void 0,(function*(){const i=this.book.metadata;let r=i.author&&i.author[0]&&i.author[0].name&&C(i.author[0].name)?i.author[0].name:i.author&&i.author[0]&&C(i.author[0])?i.author[0]:i.author&&C(i.author)?i.author:"";try{const t=yield this.book.getCover();var n=new FileReader;n.readAsDataURL(t),n.onloadend=()=>{e({name:i.title,author:r,description:i.description,publisher:i.publisher,cover:n.result})}}catch(n){console.error(n);try{e({name:i.title,author:r,description:i.description,publisher:i.publisher,cover:""})}catch(e){console.error(e),t(e)}}}))))}}const T=(e,t)=>[-1,...t,e.length].reduce((({xs:t,a:i},r)=>({xs:t?.concat([e.slice(i+1,r)])??[],a:r})),{}).xs,S=/\d/,M=/^epubcfi\((.*)\)$/,A=e=>e.replace(/[\^[\](),;=]/g,"^$&"),k=(e,t)=>{return i=([e])=>e===t,e.map(((e,t,r)=>i(e,t,r)?t:null)).filter((e=>null!=e));var i},E=e=>{const t=[];let i;for(const[r,n]of e){if("/"===r)t.push({index:n});else{const e=t[t.length-1];if(":"===r)e.offset=n;else if("~"===r)e.temporal=n;else if("@"===r)e.spatial=(e.spatial??[]).concat(n);else if(";s"===r)e.side=n;else if("["===r){if("/"!==i||!n){e.text=(e.text??[]).concat(n);continue}e.id=n}}i=r}return t},D=e=>T(e,k(e,"!")).map(E),R=e=>{const t=(e=>{const t=[];let i,r,n="";const o=e=>(t.push(e),i=null,n=""),s=e=>(n+=e,r=!1);for(const t of Array.from(e.trim()).concat(""))if("^"!==t||r){if("!"===i)o(["!"]);else if(","===i)o([","]);else if("/"===i||":"===i){if(S.test(t)){s(t);continue}o([i,parseInt(n)])}else if("~"===i){if(S.test(t)||"."===t){s(t);continue}o(["~",parseFloat(n)])}else if("@"===i){if(":"===t){o(["@",parseFloat(n)]),i="@";continue}if(S.test(t)||"."===t){s(t);continue}o(["@",parseFloat(n)])}else{if("["===i){";"!==t||r?","!==t||r?"]"!==t||r?s(t):o(["[",n]):(o(["[",n]),i="["):(o(["[",n]),i=";");continue}if(i?.startsWith(";")){"="!==t||r?";"!==t||r?"]"!==t||r?s(t):o([i,n]):(o([i,n]),i=";"):(i=`;${n}`,n="");continue}}"/"!==t&&":"!==t&&"~"!==t&&"@"!==t&&"["!==t&&"!"!==t&&","!==t||(i=t)}else r=!0;return t})((i=e,i.match(M)?.[1]??i));var i;const r=k(t,",");if(!r.length)return D(t);const[n,o,s]=T(t,r).map(D);return{parent:n,start:o,end:s}},I=({index:e,id:t,offset:i,temporal:r,spatial:n,text:o,side:s})=>{const a=s?`;s=${s}`:"";return`/${e}`+(t?`[${A(t)}${a}]`:"")+(null!=i&&e%2?`:${i}`:"")+(r?`~${r}`:"")+(n?`@${n.join(":")}`:"")+(o||!t&&s?"["+(o?.map(A)?.join(",")??"")+a+"]":"")},N=e=>e.parent?[e.parent,e.start,e.end].map(N).join(","):e.map((e=>e.map(I).join(""))).join("!"),B=e=>{return t=N(e),M.test(t)?t:`epubcfi(${t})`;var t},O=(e,t)=>{return"string"==typeof e?B(O(R(e),t)):e.parent?(i=e.parent,r=e[t?"end":"start"],i.slice(0,-1).concat([i[i.length-1].concat(r[0])]).concat(r.slice(1))):e;var i,r},H=({nodeType:e})=>3===e||4===e,P=({nodeType:e})=>1===e,F=e=>{const t=Array.from(e.childNodes).filter((e=>H(e)||P(e))).reduce(((e,t)=>{let i=e[e.length-1];return i?H(t)?Array.isArray(i)?i.push(t):H(i)?e[e.length-1]=[i,t]:e.push(t):P(i)?e.push(null,t):e.push(t):e.push(t),e}),[]);return P(t[0])&&t.unshift("first"),P(t[t.length-1])&&t.push("last"),t.unshift("before"),t.push("after"),t},$=(e,t)=>e?F(e)[t]:null,U=(e,t)=>{const{id:i}=t[t.length-1];if(i){const t=e.ownerDocument.getElementById(i);if(t)return{node:t,offset:0}}for(const{index:i}of t){const t=$(e,i);if("first"===t)return{node:e.firstChild??e};if("last"===t)return{node:e.lastChild??e};if("before"===t)return{node:e,before:!0};if("after"===t)return{node:e,after:!0};e=t}const{offset:r}=t[t.length-1];if(!Array.isArray(e))return{node:e,offset:r};let n=0;for(const t of e){const{length:e}=t.nodeValue;if(n+e>=r)return{node:t,offset:r-n};n+=e}},j=(e,t)=>{const{parentNode:i,id:r}=e,n=F(i),o=n.findIndex((t=>Array.isArray(t)?t.some((t=>t===e)):t===e)),s=n[o];if(Array.isArray(s)){let i=0;for(const r of s){if(r===e){i+=t;break}i+=r.nodeValue.length}t=i}const a={id:r,index:o,offset:t};return i!==e.ownerDocument.documentElement?j(i).concat(a):[a]},W=(e,t)=>U(e.documentElement,O(t)).node,q="urn:oasis:names:tc:opendocument:xmlns:container",z="http://www.w3.org/1999/xhtml",X="http://www.idpf.org/2007/opf",V="http://www.idpf.org/2007/ops",J="http://purl.org/dc/elements/1.1/",G="http://www.w3.org/2001/04/xmlenc#",Z="http://www.daisy.org/z3986/2005/ncx/",_="http://www.w3.org/1999/xlink",Y="http://www.w3.org/ns/SMIL",K={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)/},Q=e=>e.toLowerCase().replace(/[-:](.)/g,((e,t)=>t.toUpperCase())),ee=(e,t,i)=>i?i=>i.getAttribute(e)?.split(/\s/)?.includes(t):"function"==typeof t?i=>t(i.getAttribute(e)):i=>i.getAttribute(e)===t,te=(...e)=>t=>t?Object.fromEntries(e.map((e=>[Q(e),t.getAttribute(e)]))):null,ie=e=>{return t=e?.textContent,t?t.trim().replace(/\s{2,}/g," "):"";var t},re=(e,t)=>{const i=e.lookupNamespaceURI(null)===t||e.lookupPrefix(t),r=i?(e,i)=>e=>e.namespaceURI===t&&e.localName===i:(e,t)=>e=>e.localName===t;return{$:(e,t)=>[...e.children].find(r(e,t)),$$:(e,t)=>[...e.children].filter(r(e,t)),$$$:i?(e,i)=>[...e.getElementsByTagNameNS(t,i)]:(e,i)=>[...e.getElementsByTagName(t,i)]}},ne=(e,t)=>{try{if(t.includes(":"))return new URL(e,t);const i="whatever://whatever/";return decodeURI(new URL(e,i+t).href.replace(i,""))}catch(t){return console.warn(t),e}},oe=e=>/^(?!blob)\w+:/i.test(e),se=async(e,t,i)=>{const r=[];e.replace(t,((...e)=>(r.push(e),null)));const n=[];for(const e of r)n.push(await i(...e));return e.replace(t,(()=>n.shift()))},ae=e=>e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),le={attrs:["dir","xml:lang"]},ce={name:"alternate-script",many:!0,...le,props:["file-as"]},de={many:!0,...le,props:[{name:"role",many:!0,attrs:["scheme"]},"file-as",ce]},he=[{name:"title",many:!0,...le,props:["title-type","display-seq","file-as",ce]},{name:"identifier",many:!0,props:[{name:"identifier-type",attrs:["scheme"]}]},{name:"language",many:!0},{name:"creator",...de},{name:"contributor",...de},{name:"publisher",...le,props:["file-as",ce]},{name:"description",...le,props:[ce]},{name:"rights",...le,props:[ce]},{name:"date"},{name:"dcterms:modified",type:"meta"},{name:"subject",many:!0,...le,props:["term","authority",ce]},{name:"belongs-to-collection",type:"meta",many:!0,...le,props:["collection-type","group-position","dcterms:identifier","file-as",ce,{name:"belongs-to-collection",recursive:!0}]}],ue=(e,t=e=>e)=>{const{$:i,$$:r,$$$:n}=re(e,z),o=e=>r=>{const n=i(r,"a")??i(r,"span"),o=i(r,"ol"),a=(e=>e?decodeURI(t(e)):null)(n?.getAttribute("href")),l={label:ie(n)||n?.getAttribute("title"),href:a,subitems:s(o)};return e&&(l.type=n?.getAttributeNS(V,"type")?.split(/\s/)),l},s=(e,t)=>e?r(e,"li").map(o(t)):null,a=(e,t)=>s(i(e,"ol"),t),l=n(e,"nav");let c=null,d=null,h=null,u=[];for(const e of l){const t=e.getAttributeNS(V,"type")?.split(/\s/)??[];t.includes("toc")?c??=a(e):t.includes("page-list")?d??=a(e):t.includes("landmarks")?h??=a(e,!0):u.push({label:ie(e.firstElementChild),type:t,list:a(e)})}return{toc:c,pageList:d,landmarks:h,others:u}},fe=(e,t=e=>e)=>{const{$:i,$$:r}=re(e,Z),n=e=>{const o=i(e,"navLabel"),s=i(e,"content"),a=ie(o),l=(e=>e?decodeURI(t(e)):null)(s.getAttribute("src"));if("navPoint"===e.localName){const t=r(e,"navPoint");return{label:a,href:l,subitems:t.length?t.map(n):null}}return{label:a,href:l}},o=(e,t)=>r(e,t).map(n),s=(t,r)=>{const n=i(e.documentElement,t);return n?o(n,r):null};return{toc:s("navMap","navPoint"),pageList:s("pageList","pageTarget"),others:r(e.documentElement,"navList").map((e=>({label:ie(i(e,"navLabel")),list:o(e,"navTarget")})))}},pe=e=>{if(!e)return;const t=e.split(":").map((e=>parseFloat(e)));if(3===t.length){const[e,i,r]=t;return 60*e*60+60*i+r}if(2===t.length){const[e,i]=t;return 60*e+i}const[i,r]=e.split(/(?=[^\d.])/);return parseFloat(i)*("h"===r?3600:"min"===r?60:"ms"===r?.001:1)},ge=/([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/,me=e=>ie(e.getElementById(e.documentElement.getAttribute("unique-identifier"))??e.getElementsByTagNameNS(J,"identifier")[0]),ye=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{const t=(new TextEncoder).encode(e),i=await globalThis.crypto.subtle.digest("SHA-1",t);return new Uint8Array(i)},we=(e=be)=>({"http://www.idpf.org/2008/embedding":{key:t=>e(me(t).replaceAll(/[\u0020\u0009\u000d\u000a]/g,"")),decode:(e,t)=>ye(e,1040,t)},"http://ns.adobe.com/pdf/enc#RC":{key:e=>{const t=(e=>{for(const t of e.getElementsByTagNameNS(J,"identifier")){const[e]=ie(t).split(":").slice(-1);if(ge.test(e))return e}return""})(e).replaceAll("-","");return Uint8Array.from({length:16},((e,i)=>parseInt(t.slice(2*i,2*i+2),16)))},decode:(e,t)=>ye(e,1024,t)}});class ve{#e=new Map;#t=new Map;#i;constructor(e){this.#i=e}async init(e,t){if(!e)return;const i=Array.from(e.getElementsByTagNameNS(G,"EncryptedData"),(e=>({algorithm:e.getElementsByTagNameNS(G,"EncryptionMethod")[0]?.getAttribute("Algorithm"),uri:e.getElementsByTagNameNS(G,"CipherReference")[0]?.getAttribute("URI")})));for(const{algorithm:e,uri:r}of i){if(!this.#t.has(e)){const i=this.#i[e];if(!i){console.warn("Unknown encryption algorithm");continue}const r=await i.key(t);this.#t.set(e,(e=>i.decode(r,e)))}this.#e.set(r,e)}}getDecoder(e){return this.#t.get(this.#e.get(e))??(e=>e)}}class xe{constructor({opf:e,resolveHref:t}){this.opf=e;const{$:i,$$:r,$$$:n}=re(e,X),o=i(e.documentElement,"manifest"),s=i(e.documentElement,"spine"),a=r(s,"itemref");this.manifest=r(o,"item").map(te("href","id","media-type","properties","media-overlay")).map((e=>(e.href=t(e.href),e.properties=e.properties?.split(/\s/),e))),this.spine=a.map(te("idref","id","linear","properties")).map((e=>(e.properties=e.properties?.split(/\s/),e))),this.pageProgressionDirection=s.getAttribute("page-progression-direction"),this.navPath=this.getItemByProperty("nav")?.href,this.ncxPath=(this.getItemByID(s.getAttribute("toc"))??this.manifest.find((e=>e.mediaType===K.NCX)))?.href;const l=i(e.documentElement,"guide");l&&(this.guide=r(l,"reference").map(te("type","title","href")).map((({type:e,title:i,href:r})=>({label:i,type:e.split(/\s/),href:t(r)})))),this.cover=this.getItemByProperty("cover-image")??this.getItemByID("cover-image")??this.getItemByID(n(e,"meta").find(ee("name","cover"))?.getAttribute("content"))??this.getItemByID("cover")??this.getItemByHref(this.guide?.find((e=>e.type.includes("cover")&&!e.href.includes("html")&&!e.href.includes("xml")))?.href),this.cfis=(e=>{const t=[],{parentNode:i}=e[0],r=j(i);for(const[n,o]of F(i).entries()){const i=e[t.length];o===i&&t.push(B([r.concat({id:i.id,index:n})]))}return t})(a)}getItemByID(e){return this.manifest.find((t=>t.id===e))}getItemByHref(e){return this.manifest.find((t=>t.href===e))}getItemByProperty(e){return this.manifest.find((t=>t.properties?.includes(e)))}resolveCFI(e){const t=R(e),i=(t.parent??t).shift();let r=W(this.opf,i);r&&"idref"!==r.nodeName&&(i.at(-1).id=null,r=W(this.opf,i));const n=r?.getAttribute("idref");return{index:this.spine.findIndex((e=>e.idref===n)),anchor:e=>((e,t)=>{const i=O(t),r=O(t,!0),n=e.documentElement,o=U(n,i[0]),s=U(n,r[0]),a=e.createRange();return o.before?a.setStartBefore(o.node):o.after?a.setStartAfter(o.node):a.setStart(o.node,o.offset),s.before?a.setEndBefore(s.node):s.after?a.setEndAfter(s.node):a.setEnd(s.node,s.offset),a})(e,t)}}}class Ce{#r=new Map;#n=new Map;#o=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"";const n=URL.createObjectURL(new Blob([t],{type:i}));if(this.#r.set(e,n),this.#o.set(e,1),r){const t=this.#n.get(r);t?t.push(e):this.#n.set(r,[e])}return n}ref(e,t){const i=this.#n.get(t);return i?.includes(e)||(this.#o.set(e,this.#o.get(e)+1),i?i.push(e):this.#n.set(t,[e])),this.#r.get(e)}unref(e){if(!this.#o.has(e))return;const t=this.#o.get(e)-1;if(t<1){URL.revokeObjectURL(this.#r.get(e)),this.#r.delete(e),this.#o.delete(e);const t=this.#n.get(e);if(t)for(;t.length;)this.unref(t.pop());this.#n.delete(e)}else this.#o.set(e,t)}async loadItem(e,t=[]){if(!e)return null;const{href:i,mediaType:r}=e,n=K.JS.test(e.mediaType);if(n&&!this.allowScript)return null;const o=t.at(-1);if(this.#r.has(i))return this.ref(i,o);return(n||[K.XHTML,K.HTML,K.CSS,K.SVG].includes(r))&&t.every((e=>e!==i))?this.loadReplaced(e,t):this.createURL(i,await this.loadBlob(i),r,o)}async loadHref(e,t,i=[]){if(oe(e))return e;const r=ne(e,t);let n=this.manifest.find((e=>e.href===r));return n||(n={href:r,mediaType:""}),this.loadItem(n,i.concat(t))}async loadReplaced(e,t=[]){const{href:i,mediaType:r}=e,n=t.at(-1),o=await this.loadText(i);if(!o)return null;if([K.XHTML,K.HTML,K.SVG].includes(r)){let s=(new DOMParser).parseFromString(o,r);if(r===K.XHTML&&s.querySelector("parsererror")&&(console.warn(s.querySelector("parsererror").innerText),e.mediaType=K.HTML,s=(new DOMParser).parseFromString(o,e.mediaType)),[K.XHTML,K.SVG].includes(e.mediaType)){let e=s.firstChild;for(;e instanceof ProcessingInstruction;){if(e.data){const r=await se(e.data,/(?:^|\s*)(href\s*=\s*['"])([^'"]*)(['"])/i,((e,r,n,o)=>this.loadHref(n,i,t).then((e=>`${r}${e}${o}`))));e.replaceWith(s.createProcessingInstruction(e.target,r))}e=e.nextSibling}}const a=async(e,r)=>e.setAttribute(r,await this.loadHref(e.getAttribute(r),i,t));for(const e of s.querySelectorAll("link[href]"))await a(e,"href");for(const e of s.querySelectorAll("[src]"))await a(e,"src");for(const e of s.querySelectorAll("[poster]"))await a(e,"poster");for(const e of s.querySelectorAll("object[data]"))await a(e,"data");for(const e of s.querySelectorAll("[*|href]:not([href]"))e.setAttributeNS(_,"href",await this.loadHref(e.getAttributeNS(_,"href"),i,t));for(const e of s.querySelectorAll("style"))e.textContent&&(e.textContent=await this.replaceCSS(e.textContent,i,t));for(const e of s.querySelectorAll("[style]"))e.setAttribute("style",await this.replaceCSS(e.getAttribute("style"),i,t));const l=(new XMLSerializer).serializeToString(s);return this.createURL(i,l,e.mediaType,n)}const s=r===K.CSS?await this.replaceCSS(o,i,t):await this.replaceString(o,i,t);return this.createURL(i,s,r,n)}async replaceCSS(e,t,i=[]){const r=await se(e,/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,((e,r)=>this.loadHref(r,t,i).then((e=>`url("${e}")`)))),n=await se(r,/@import\s*["']([^"'\n]*?)["']/gi,((e,r)=>this.loadHref(r,t,i).then((e=>`@import "${e}"`)))),o=window?.innerWidth??800,s=window?.innerHeight??600;return n.replace(/-epub-/gi,"").replace(/(\d*\.?\d+)vw/gi,((e,t)=>parseFloat(t)*o/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,t,i=[]){const r=new Map,n=this.assets.map((e=>{if(e.href===t)return;const i=((e,t)=>{if(!e)return t;const i=e.replace(/\/$/,"").split("/"),r=t.replace(/\/$/,"").split("/"),n=(i.length>r.length?i:r).findIndex(((e,t)=>i[t]!==r[t]));return n<0?"":Array(i.length-n).fill("..").concat(r.slice(n)).join("/")})((e=>e.slice(0,e.lastIndexOf("/")+1))(t),e.href),n=encodeURI(i),o="/"+e.href,s=encodeURI(o),a=new Set([i,n,o,s]);for(const t of a)r.set(t,e);return Array.from(a)})).flat().filter((e=>e));if(!n.length)return e;const o=new RegExp(n.map(ae).join("|"),"g");return se(e,o,(async e=>this.loadItem(r.get(e.replace(/^\//,"")),i.concat(t))))}unloadItem(e){this.unref(e?.href)}}const Le=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"}};class Te{parser=new DOMParser;#s;constructor({loadText:e,loadBlob:t,getSize:i,sha1:r}){this.loadText=e,this.loadBlob=t,this.getSize=i,this.#s=new ve(we(r))}#a(e){return e&&e.includes("opf:scheme")&&(e=e.replaceAll("opf:scheme","scheme")),e?this.parser.parseFromString(e,K.XML):null}async#l(e){return this.#a(await this.loadText(e))}async init(){const e=await this.#l("META-INF/container.xml");if(!e)throw new Error("Failed to load container file");const t=Array.from(e.getElementsByTagNameNS(q,"rootfile"),te("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,r=await this.#l(i);if(!r)throw new Error("Failed to load package document");const n=await this.#l("META-INF/encryption.xml");await this.#s.init(n,r),this.resources=new xe({opf:r,resolveHref:e=>ne(e,i)});const o=new Ce({loadText:this.loadText,loadBlob:e=>Promise.resolve(this.loadBlob(e)).then(this.#s.getDecoder(e)),resources:this.resources});this.sections=this.resources.spine.map(((e,t)=>{const{idref:i,linear:r,properties:n=[]}=e,s=this.resources.getItemByID(i);return s?{id:this.resources.getItemByID(i)?.href,load:()=>o.loadItem(s),unload:()=>o.unloadItem(s),createDocument:()=>this.loadDocument(s),size:this.getSize(s.href),cfi:this.resources.cfis[t],linear:r,pageSpread:Le(n),resolveHref:e=>ne(e,s.href),loadMediaOverlay:()=>this.loadMediaOverlay(s)}:(console.warn(`Could not find item with ID "${i}" in manifest`),null)})).filter((e=>e));const{navPath:s,ncxPath:a}=this.resources;if(s)try{const e=e=>ne(e,s),t=ue(await this.#l(s),e);this.toc=t.toc,this.pageList=t.pageList,this.landmarks=t.landmarks}catch(e){console.warn(e)}if((!this.toc||0===this.toc.length)&&a)try{const e=e=>ne(e,a),t=fe(await this.#l(a),e);this.toc=t.toc,this.pageList=t.pageList}catch(e){console.warn(e)}this.landmarks??=this.resources.guide;const{metadata:l,rendition:c,media:d}=(e=>{const{$:t,$$:i}=re(e,X),r=t(e.documentElement,"metadata"),n=Array.from(r.children),o=(e,t)=>{if(!t)return null;const{props:i=[],attrs:r=[]}=e,s=ie(t);if(!i.length&&!r.length)return s;const a=t.getAttribute("id"),l=a?n.filter(ee("refines","#"+a)):[];return Object.fromEntries([["value",s]].concat(i.map((t=>{const{many:i,recursive:r}=t,n="string"==typeof t?t:t.name,s=ee("property",n),a=r?e:t;return[Q(n),i?l.filter(s).map((e=>o(a,e))):o(a,l.find(s))]}))).concat(r.map((e=>[Q(e),t.getAttribute(e)]))))},s=n.filter(ee("refines",null)),a=e=>Object.fromEntries(i(r,"meta").filter(ee("property",(t=>t?.startsWith(e)))).map((t=>[t.getAttribute("property").replace(e,""),ie(t)])));return{metadata:Object.fromEntries(he.map((e=>{const{type:t,name:i,many:r}=e,n="meta"===t?e=>e.namespaceURI===X&&e.getAttribute("property")===i:e=>e.namespaceURI===J&&e.localName===i;return[Q(i),r?s.filter(n).map((t=>o(e,t))):o(e,s.find(n))]}))),rendition:a("rendition:"),media:a("media:")}})(r);this.rendition=c,this.media=d,d.duration=pe(d.duration),this.dir=this.resources.pageProgressionDirection,this.rawMetadata=l;const h=l?.title?.[0];this.metadata={title:h?.value,sortAs:h?.fileAs,language:l?.language,identifier:me(r),description:l?.description?.value,publisher:l?.publisher?.value,published:l?.date,modified:l?.dctermsModified,subject:l?.subject?.filter((({value:e,code:t})=>e||t))?.map((({value:e,code:t,scheme:i})=>({name:e,code:t,scheme:i}))),rights:l?.rights?.value};const u={art:"artist",aut:"author",bkp:"producer",clr:"colorist",edt:"editor",ill:"illustrator",trl:"translator",pbl:"publisher"},f=e=>t=>{const i=[...new Set(t.role?.map((({value:t,scheme:i})=>(i&&"marc:relators"!==i?null:u[t])??e)))],r={name:t.value,sortAs:t.fileAs};return[i?.length?i:[e],r]};return l?.creator?.map(f("author"))?.concat(l?.contributor?.map?.(f("contributor")))?.forEach((([e,t])=>e.forEach((e=>{this.metadata[e]?this.metadata[e].push(t):this.metadata[e]=[t]})))),this}async loadDocument(e){const t=await this.loadText(e.href);return this.parser.parseFromString(t,e.mediaType)}async loadMediaOverlay(e){const t=e.mediaOverlay;if(!t)return null;const i=this.resources.getItemByID(t),r=((e,t=e=>e)=>{const{$:i,$$$:r}=re(e,Y);return r(e,"par").map((e=>{const r=i(e,"text")?.getAttribute("src")?.split("#")?.[1],n=i(e,"audio");return n?{id:r,audio:{src:(o=n.getAttribute("src"),o?decodeURI(t(o)):null),clipBegin:pe(n.getAttribute("clipBegin")),clipEnd:pe(n.getAttribute("clipEnd"))}}:{id:r};var o}))})(await this.#l(i.href),(e=>ne(e,i.href)));return r}resolveCFI(e){return this.resources.resolveCFI(e)}resolveHref(e){const[t,i]=e.split("#"),r=this.resources.getItemByHref(decodeURI(t));if(!r)return null;return{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}}splitTOCHref(e){return e?.split("#")??[]}getTOCFragment(e,t){return e.getElementById(t)??e.querySelector(`[name="${CSS.escape(t)}"]`)}isExternal(e){return oe(e)}async getCover(){const 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"),t="encoding=json+base64:";if(e?.startsWith(t)){const t=atob(e.slice(21));return JSON.parse(t)}}}const Se=(e,t=!1,i="")=>{const r=(new DOMParser).parseFromString(t?$e(e,i):e,"text/html");let n=De(r);0===n.length&&(n=We(r));for(let e=0;e""};return l.sections=a.map((e=>({id:e.index,load:()=>{return t=e.index,d(void 0,void 0,void 0,(function*(){return URL.createObjectURL(new Blob([a[t].text],{type:"text/html"}))}));var t},unload:()=>{e.index}}))),l.toc=a.map((e=>({label:e.label,href:"title"+e.index}))).filter((e=>""!==e.label)),l.rendition={layout:"pre-paginated"},l.resolveHref=e=>({index:parseInt(e.substring(5,e.length))}),l.splitTOCHref=e=>[e,null],l.getTOCFragment=e=>e.documentElement,l};let Me=["章","节","回","節","卷","部","輯","辑","話","集","话","篇"," "," "],Ae=[],ke=["CHAPTER","Chapter","序章","前言","声明","写在前面的话","后记","楔子","后序","章节目录","尾声"],Ee=[" "," ","、","·",".",":",":"];const De=e=>Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,title")),Re=e=>e.trim().replace(/(\r\n|\n|\r|\t)/gm,"").substring(0,100).split("").filter((e=>"="!==e&&"-"!==e&&"_"!==e&&"+"!==e)).join(""),Ie=(e,t="")=>t?new RegExp(t).test(e):e&&e.length<40&&!Ne(e)&&(Be(e)||e.startsWith("第")&&He(e)||e.startsWith("卷")&&Pe(e)||e.indexOf("第")>-1&&e.lastIndexOf("第")<4&&He(e.substr(e.indexOf("第")))||Oe(e)),Ne=e=>Ae.filter((t=>e.indexOf(t)>-1)).length>0,Be=t=>ke.filter((i=>t.startsWith(i)||t.startsWith(e.s2t(i))||t.startsWith(e.t2s(i)))).length>0,Oe=e=>Ee.filter((t=>e.indexOf(t)>-1&&(/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(0,e.indexOf(t)))||/^\d+$/.test(e.substring(0,e.indexOf(t)))))).length>0,He=e=>{let t=!1;for(let i=0;i!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(1,e.indexOf(" ")))&&!/^\d+$/.test(e.substring(1,e.indexOf(" "))))||(!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(1,e.indexOf(" ")))&&!/^\d+$/.test(e.substring(1,e.indexOf(" "))))||!(!/^[\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u842c\u96f6]+$/.test(e.substring(1))&&!/^\d+$/.test(e.substring(1)))),Fe=e=>{let t=[],i=e.split("
").filter((e=>""!==e.trim())),r=i.map((e=>Ue(e)||je(e)));return t=i.map(((e,t)=>({index:t,label:r[t],text:e,href:"title"+t}))),t},$e=(e,t)=>{let i="",r=e.split("\n");1===r.length&&(r=e.split("\r"));for(let e of r)Re(e)&&Ie(Re(e),t)?i+=`

${Re(e)}

`:i+=`

${e}

`;return i||`

Title

${e}

`},Ue=e=>{var t;const i=(new DOMParser).parseFromString(e,"text/html").querySelector("h1, h2, h3, h4, h5, h6");return i&&(null===(t=i.textContent)||void 0===t?void 0:t.trim())||""},je=e=>{var t;const i=(new DOMParser).parseFromString(e,"text/html").querySelector("title");return i&&(null===(t=i.textContent)||void 0===t?void 0:t.trim())||""},We=e=>{let t=e.getElementsByTagName("*"),i=Array.from(t).filter((e=>1===e.childNodes.length&&e.childNodes[0].nodeType===Node.TEXT_NODE&&Ie(Re(e.textContent)))),r=[];for(let e=0;eArray.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address")),Xe=(e,t,i,r,n,o,s)=>d(void 0,void 0,void 0,(function*(){let a=Math.floor(e.clientWidth/12),l=a%2==0?a:a-1;const c=e.clientWidth;if("mimical"===t&&"yes"!==s){let e=document.getElementById("book");e&&(e.style.display="block",i>0?o():i<0&&n(),setTimeout((()=>{if(!e)return{};e.style.display="none"}),1e3))}i>0?r.body.scrollBy({top:0,left:-c-l,behavior:"sliding"===t&&"yes"!==s?"smooth":"auto"}):i<0&&r.body.scrollBy({top:0,left:c+l,behavior:"sliding"===t&&"yes"!==s?"smooth":"auto"})})),Ve=(e,i,r,n)=>{let o=t.findLastIndex(r,(e=>e.href===i||e.href&&e.href.includes("#")&&e.href.includes(i)));return i&&t.findLastIndex(r,(e=>e.href===i||e.href&&e.href.includes("#")&&e.href.includes(i)))>-1||(o=e),"prev"===n?Object.assign(Object.assign({},r[o-1]),{index:o-1}):Object.assign(Object.assign({},r[o+1]),{index:o+1})},Je=(e,t,i,r,n,o,s,a)=>d(void 0,void 0,void 0,(function*(){let t=parseInt(o.chapterDocIndex||"0"),l=o.chapterHref||"";if(0===t)return;let c=Ve(t,l,i,"prev");c&&(o.text="prevChapter",o.page="",yield Ze(c.index,c.label,c.href,i,e,r,n,o,s,a))})),Ge=(e,t,i,r)=>d(void 0,void 0,void 0,(function*(){let{width:n,height:o}=yield i[r].text.getDimension(),s="double"===t?2:1,a=Math.floor(e.clientWidth/12),l=a%2==0?a:a-1,c=(e.clientWidth-l)/s;"single"===t&&(c=e.clientWidth);let d=e.clientHeight,h=Math.min(c/n,d/o);return"scroll"===t&&(h=c/n),h})),Ze=(e,i,r,n,o,s,a,l,c,h)=>d(void 0,void 0,void 0,(function*(){if(c.body.innerHTML="",h.height="0px",c.body.scrollTo(0,0),i&&!e||n[e]&&n[e].label&&i&&i!==n[e].label&&-1===r.indexOf("#")){let r=t.findLastIndex(n,{label:i});-1!==r&&(e=r)}if(-1===e&&r.indexOf("#")>-1){let i=r.split("#")[0],o=t.findLastIndex(n,(e=>e.href===i||e.href&&e.href.includes("#")&&e.href.includes(i)));-1!==o&&(e=o)}if((-1===e||e>n.length-1)&&(e=0),c.body.innerHTML=yield u(n[e].text,!1),"PDF"===a){let t=yield Ge(o,s,n,e);yield n[e].text.render(c,t,s)}yield _e(c),l.chapterTitle=i,l.chapterHref=r,l.chapterDocIndex=e+"",l.percentage=e/n.length+"",l.text="",yield((e,t,i,r,n)=>d(void 0,void 0,void 0,(function*(){if(yield Promise.all(Array.from([...n.images,...n.querySelectorAll("image")]).map((e=>e.complete?Promise.resolve(0!==e.naturalHeight):new Promise((t=>{e.addEventListener("load",(()=>t(!0))),e.addEventListener("error",(()=>t(!1)))}))))).then((e=>{e.every((e=>e))?console.info("all images loaded successfully!!"):console.error("some images failed to load, all finished loading")})),yield v(e,t,i,n),"PDF"!==i&&b(n),"scroll"!==t){if(r.height=e.clientHeight+"px","double"===t){let t=Math.floor(e.clientWidth/12),i=t%2==0?t:t-1,r=(e.clientWidth+i)/2;if((n.body.scrollWidth-n.body.clientWidth)/r%2==1){let e=document.createElement("div");e.setAttribute("style","height: "+n.body.clientHeight+"px; display: inline-block; width: "+(r-i)+"px"),n.body.appendChild(e)}}}else if("PDF"===i){let e=n.querySelector(".koodoPDFLayer");if(!e)return;r.height=e.getBoundingClientRect().height+100+"px"}else r.height=n.body.scrollHeight+"px",r.height=n.body.scrollHeight+300+"px"})))(o,s,a,h,c),yield Ye(o,s,"","","","",c)})),_e=e=>d(void 0,void 0,void 0,(function*(){let t=Array.from(e.getElementsByTagName("link"));if(0===t.length)return;for(let e=0;e{console.info("finished")}}let i=[];for(let e=0;e{r.addEventListener("load",e)})))}try{yield Promise.race([Promise.all(i),new Promise(((e,t)=>{setTimeout((()=>{console.info("css load timeout"),e("css load timeout")}),1e3)}))])}catch(e){console.error(e)}})),Ye=(t,i,r,n,o,s,a)=>d(void 0,void 0,void 0,(function*(){let l=0,c=a.body;if(s&&"scroll"!==i){let e=Math.floor(t.clientWidth/12),i=e%2==0?e:e-1;l=((d=getComputedStyle(t).width,parseFloat(d.substring(0,d.length-2)))+i)*(parseInt(s)-1)}else if(r){let o=ze(a.body).filter(((t,i)=>Re(t.textContent)&&(Re(t.textContent)===Re(r)||Re(t.textContent)===e.t2s(Re(r))||Re(t.textContent)===e.s2t(Re(r)))&&(Math.abs(i-parseInt(n))<2||"search"===n||"ignore"===n||"next"===n)));if(0===o.length)return void console.info("failed");c=Ke(o[0],t,i),l=c?h(c.offsetLeft)-h(c.marginLeft||parseFloat(getComputedStyle(c).marginLeft)):"prevChapter"===r?a.body.scrollWidth:0,c&&(h(c.offsetTop),h(c.marginTop||parseFloat(getComputedStyle(c).marginTop)))}else if(o&&o.indexOf("#")>-1){let e=CSS.escape(o.split("#").reverse()[0]);if(!a.body.querySelector("#"+e))return;c=Ke(a.body.querySelector("#"+e)||a.body,t,i),l=c?h(c.offsetLeft)-h(c.marginLeft||parseFloat(getComputedStyle(c).marginLeft)):0,c&&(h(c.offsetTop),h(c.marginTop||parseFloat(getComputedStyle(c).marginTop)))}var d;"scroll"!==i?a.body.scrollTo(l,0):c.scrollIntoView()})),Ke=(e,t,i)=>{let r=Math.floor(t.clientWidth/12),n=r%2==0?r:r-1,o=h(e.offsetLeft)-h(e.marginLeft||parseFloat(getComputedStyle(e).marginLeft));return"scroll"===i||"scroll"!==i&&Qe(parseInt(o+""),(t.clientWidth+n)/2)?e:e.parentElement?Ke(e.parentElement,t,i):e},Qe=(e,t)=>{for(let i=e-10;i<=e+10;i++)if(i%t==0)return!0;return!1},et=(e,t,i,r,n,o,s)=>d(void 0,void 0,void 0,(function*(){var a;if(qe)return;let l=ze(o.body),c=l.filter((i=>st(e,i,t)&&(i.textContent||"").trim())),d=c[0];s&&(d=s);let h=0;for(let i=0;i{qe=!1}),100)})),tt=(e,t,i)=>{let r=Math.floor(t.clientWidth/12),n=r%2==0?r:r-1;return Math.abs(e.offsetLeft-Ke(e,t,i).offsetLeft)>(t.clientWidth+n)/2},it=(e,i,r)=>{let n=r.chapterHref||"",o=n.lastIndexOf("#"),s="";s=-1===o?n:n.substring(0,o);for(let n=0;n-1&&(r.chapterHref=e,r.chapterTitle=i[n].label)}}},rt=(e,t,i,r,n,o,s,a)=>d(void 0,void 0,void 0,(function*(){let t=parseInt(o.chapterDocIndex||"0"),l=o.chapterHref||"";if(t>=i.length-1)return void(o.percentage="1");let c=Ve(t,l,i,"next");c&&(o.page="",yield Ze(c.index,c.label,c.href,i,e,r,n,o,s,a))})),nt=(e,t,i)=>ze(i.body).filter((e=>!ot(e))).filter((i=>st(e,i,t)&&(i.textContent||"").trim())).filter((e=>"img"!==e.textContent)).map((e=>e.textContent)),ot=e=>{var t=e.children;let i=!1;var r=/^(address|section|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;if(Array.from(t).filter((e=>r.test(e.nodeName))).length<3)return!1;for(var n=0;n{var r=!1,n=t.getBoundingClientRect();if("scroll"!==i&&t.textContent&&t.textContent.trim()){let t=n.left;r=t>-10&&t<=e.clientWidth}else if("scroll"===i&&t.textContent&&t.textContent.trim()){let t=n.top;r=t>=e.scrollTop&&t<=e.scrollTop+e.clientHeight}else if("scroll"!==i){let t=n.left;r=t>=0&&t<=e.clientWidth}return r},at=(e,t,r,n,o,s)=>{var a;let l=t.contentWindow||(null===(a=t.contentDocument)||void 0===a?void 0:a.defaultView),c=0,h=0,u=0,f=0;let p=Math.floor(r.clientWidth/12),g=p%2==0?p:p-1,m=function(t){return d(this,void 0,void 0,(function*(){let a=(new Date).getTime();if(a-f<=300)return void t.preventDefault();f=a;const d=t.changedTouches[0],p=Date.now(),m=d.clientX,y=d.clientY,w=p-c,v=m-h,x=y-u;if(b&&"mimical"===o)return b=!1,s.mouseUpHandler(t),d.screenX{let e=document.getElementById("book");e&&(e.style.display="none")}),400);if(b&&"sliding"===o){window.scrollAnimationId&&cancelAnimationFrame(window.scrollAnimationId),e.body.style.transform="";let S,M=r.clientWidth+g,A=e.body.scrollLeft;const k=Math.round(A/M),E=Math.abs(v)/window.screen.width,D=.1;S=v>0&&E>D?(k-1)*M:v<0&&E>D?(k+1)*M:k*M,S=Math.max(0,Math.min(S,e.body.scrollWidth-M)),e.body.scrollWidth-S1-Math.pow(1-e,3);function H(t){const i=t-R;if(i>=B)return e.body.scrollLeft=S,e.body.style.willChange="auto",s.record(),void(b=!1);const r=O(i/B),n=I+N*r;e.body.scrollLeft=n,window.scrollAnimationId=requestAnimationFrame(H)}return void(window.scrollAnimationId=requestAnimationFrame(H))}const C=l.getSelection().toString().trim();if(C){var L=l.getSelection().getRangeAt(0).getBoundingClientRect(),T={top:L.top-r.scrollTop,left:L.left,width:L.width,height:L.height,screenWidth:window.innerWidth,screenHeight:window.innerHeight};i.init();let P=yield s.getHightlightCoords();window.ReactNativeWebView.postMessage(JSON.stringify({event:"select-text",selectedText:C,position:T,range:P}))}else if(w<500&&Math.abs(v)<30&&Math.abs(x)<30){const F=document.documentElement.clientWidth;document.documentElement.clientHeight;const $=Math.min(Math.max(m,0),F);let U="";const j=F/3,W=Math.min(Math.floor($/j),2);0===W?U="left":1===W?U="center":2===W&&(U="right"),window.ReactNativeWebView.postMessage(JSON.stringify({event:U}))}else(Math.abs(v)>=30||Math.abs(x)>=30)&&(window.ReactNativeWebView.postMessage(JSON.stringify({event:"swipe"})),"scroll"===n&&Math.abs(r.scrollHeight-r.scrollTop-r.clientHeight)<10&&window.ReactNativeWebView.postMessage(JSON.stringify({event:"scroll-bottom"})),"scroll"===n&&0===r.scrollTop&&window.ReactNativeWebView.postMessage(JSON.stringify({event:"scroll-top"})))}))},y=function(e){const t=e.target;if(!t)return;if("IMG"===t.tagName){const e=t.src||t.getAttribute("xlink:href");window.ReactNativeWebView.postMessage(JSON.stringify({event:"view-image",imgSrc:e}))}e.touches.length>1&&e.preventDefault();const i=e.touches[0];c=Date.now(),h=i.clientX,u=i.clientY},b=!1,w=0,v=function(t){const i=l.getSelection().toString().trim();if(!b&&Math.abs(t.touches[0].screenX-h)<=10||i)return;t.preventDefault();const n=t.touches[0],a=n.screenX,c=n.screenY,d=a-h,f=c-u;if(!b&&Math.abs(d)>Math.abs(f)&&Math.abs(d)>10){if(b=!0,w=a,e.body.style.transform="translateZ(0)","mimical"===o){window.ReactNativeWebView.postMessage(JSON.stringify({event:"swipe-start"}));let e=document.getElementById("book");e&&(e.style.display="block",s.mouseDownHandler(t))}}else if(b&&"mimical"===o&&s.mouseMoveHandler(t),b&&"sliding"===o){const t=a-w;if(Math.abs(e.body.scrollWidth-e.body.scrollLeft-r.clientWidth)<10&&t<0)return x&&clearTimeout(x),void(x=setTimeout((()=>{s.next()}),300));if(0===e.body.scrollLeft&&t>0)return x&&clearTimeout(x),void(x=setTimeout((()=>{s.prev()}),300));const i=e.body.scrollLeft;e.body.scrollLeft=i-t,w=a,requestAnimationFrame((()=>{}))}};e.body.ontouchend=m,e.body.ontouchstart=y,e.body.ontouchmove=v,l.ontouchend=m,l.ontouchstart=y,l.ontouchmove=v;let x=null;e.addEventListener("touchmove",(e=>{}),!1),e.body.oncontextmenu=function(e){return e.preventDefault(),e.stopPropagation(),!1}};class lt{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;return this.resolveNames(e).forEach((function(e){const r=i.resolveName(e);i.callbacks[r.namespace]instanceof Object||(i.callbacks[r.namespace]={}),i.callbacks[r.namespace][r.value]instanceof Array||(i.callbacks[r.namespace][r.value]=[]),i.callbacks[r.namespace][r.value].push(t)})),this}off(e){const t=this;if(void 0===e||""===e)return console.warn("wrong name"),!1;return this.resolveNames(e).forEach((function(e){const i=t.resolveName(e);if("base"!==i.namespace&&""===i.value)delete t.callbacks[i.namespace];else if("base"===i.namespace)for(const e in t.callbacks)t.callbacks[e]instanceof Object&&t.callbacks[e][i.value]instanceof Array&&(delete t.callbacks[e][i.value],0===Object.keys(t.callbacks[e]).length&&delete t.callbacks[e]);else t.callbacks[i.namespace]instanceof Object&&t.callbacks[i.namespace][i.value]instanceof Array&&(delete t.callbacks[i.namespace][i.value],0===Object.keys(t.callbacks[i.namespace]).length&&delete t.callbacks[i.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={},i=e.split(".");return t.original=e,t.value=i[0],t.namespace="base",i.length>1&&""!==i[1]&&(t.namespace=i[1]),t}}const ct=Node.ELEMENT_NODE,dt=Node.TEXT_NODE,ht=Node.CDATA_SECTION_NODE;function ut(e,t,i){let r,n,o,s=0,a=0,l=!0;for(n=0;nthis.compare(e,t)))}static compare(e,t){let i=e.get(),r=t.get();if(e.isRange||t.isRange){if(e.isRange&&t.isRange){const e=this.comparePath(i.from,r.from);return e||this.comparePath(i.to,r.to)}return e.isRange&&(i=i.from),t.isRange&&(r=r.from),this.comparePath(i,r)}return this.comparePath(i,r)}static compareParts(e,t){const i=Math.max(e.length,t.length);let r,n,o,s;for(r=0;r=i)return"img"===a.tagName.toLowerCase()&&r?{node:a,offset:r}:{node:a,offset:0}}else{if(l+=1,l===i)return"img"===a.tagName.toLowerCase()&&r?{node:a,offset:r}:{node:a,offset:0};if(l>i)return o?{node:o,offset:this.trueLength(e,o.textContent)}:{node:t,offset:0}}o=a;break;case dt:case ht:if(0!==l&&l%2!=0||(l+=1),l===i){const t=this.trueLength(e,a.textContent);if(!(r>=t))return{node:a,offset:r};r-=t}o=a;break;default:continue}if(i>l){const i={relativeToNode:"after",offset:0};return i.node=o||t,this.isTextNode(i.node)&&(i.offset=this.trueLength(e,i.node.textContent.length)),i}}isTextNode(e){return!!e&&(e.nodeType===dt||e.nodeType===ht)}correctOffset(e,t,i,r){let n,o=t;if("string"==typeof r?n=this.decodeEntities(e,r):(r.pre=this.decodeEntities(e,r.pre),r.post=this.decodeEntities(e,r.post),n=r.pre+"."+r.post),!this.isTextNode(t))return{node:t,offset:0};for(;this.isTextNode(o.previousSibling);)o=o.previousSibling;const s=o;let a;const l=[];let c="",d=0;for(;this.isTextNode(o)&&(a=this.decodeEntities(e,o.textContent),l[d]=a.length,c+=a,o.nextSibling);)o=o.nextSibling,d++;const h=r.pre?r.pre.length:0,u=function(e,t,i){i=i||0;const r=[];let n,o=0;do{if(n=e.match(t),!n)break;r.push(n.index+i),o+=n.index+n.length,e=e.slice(n.index+n.length)}while(o=l[d];){if(f-=l[d],f<0)return{node:t,offset:i};const e=[];if(!o.nextSibling||d+1>=e.length)return{node:t,offset:i};d++,o=o.nextSibling}return{node:o,offset:f}}resolveNode(e,t,i,r){if(r=Object.assign({},r||{}),!i)throw new Error("Missing DOM argument");let n;if(0===e&&(n=i.querySelector("package")),!n)for(const e of i.childNodes)if(e.nodeType===ct){n=e;break}if(n=i,!n)throw new Error("Document incompatible with CFIs");let o,s,a=n,l=0;for(o=t.length-1;o>=0;o--)if(s=t[o],!r.ignoreIDs&&s.nodeID&&(a=i.getElementById(s.nodeID))){l=o+1;break}a||(a=n);let c={node:a,offset:0};for(o=l;othis.parts.length-2)throw new Error("index is out of bounds");const r=this.parts[e];if(!r)throw new Error("Missing CFI part for index: "+e);let n=this.resolveNode(e,r,t,i).node;const o=n.tagName.toLowerCase();if("itemref"===o&&"spine"===n.parentNode.tagName.toLowerCase()){const e=n.getAttribute("idref");if(!e)throw new Error("Referenced node had not 'idref' attribute");if(n=t.getElementById(e),!n)throw new Error("Specified node is missing from manifest");const i=n.getAttribute("href");if(!i)throw new Error("Manifest item is missing href attribute");return i}if("iframe"===o||"embed"===o){const e=n.getAttribute("src");if(!e)throw new Error(o+" element is missing 'src' attribute");return e}if("object"===o){const e=n.getAttribute("data");if(!e)throw new Error(o+" element is missing 'data' attribute");return e}if("image"===o||"use"===o){const e=n.getAttribute("xlink:href");if(!e)throw new Error(o+" element is missing 'xlink:href' attribute");return e}throw new Error("No URI found")}deepClone(e){return JSON.parse(JSON.stringify(e))}resolveLocation(e,t){const i=t.length-1,r=t[i];if(!r)throw new Error("Missing CFI part for index: "+i);const n=this.resolveNode(i,r,e),o=this.deepClone(r[r.length-1]);return delete o.nodeIndex,o.offset||delete n.offset,Object.assign(Object.assign({},o),n)}resolveLast(e,t){if(t=Object.assign({range:!1},t||{}),!this.isRange)return this.resolveLocation(e,this.parts);if(t.range){const t=e.createRange(),i=this.getFrom();"before"===i.relativeToNode?t.setStartBefore(i.node,i.offset):"after"===i.relativeToNode?t.setStartAfter(i.node,i.offset):t.setStart(i.node,i.offset);const r=this.getTo();return"before"===r.relativeToNode?t.setEndBefore(r.node,r.offset):"after"===r.relativeToNode?t.setEndAfter(r.node,r.offset):t.setEnd(r.node,r.offset),t}return{from:this.resolveLocation(e,this.getFrom()),to:this.resolveLocation(e,this.getTo()),isRange:!0}}resolve(e,t){return this.resolveLast(e,t)}}const mt=["color-0","color-1","color-2","color-3","line-0","line-1","line-2","line-3"],yt=["#FEF3CD","#FBFACC","#CEFACD","#CDE9FA"],bt=["#FF0000","#000080","#0000FF","#2EFF2E"],wt=["#fac106","#ebe702","#0be603","#0493e6"],vt=(e,t,r,n,o,s)=>{var a,l;i.init();let c=mt[t],d=s.contentWindow||(null===(a=s.contentDocument)||void 0===a?void 0:a.defaultView),h=e;h=[h],i.getSelection(s).restoreCharacterRanges(o,h);let u=o.getSelection();if(!u)return;let f=u.getRangeAt(0);for(var p=St(f),g=0;g{let a=mt[t],l=s.querySelector(".noteLayer"),c=s.querySelector("#koodoPDFLayer");var d=n.getViewport({scale:o});e.coords.forEach((e=>{var t=d.convertToViewportRectangle(e),n=document.createElement("div");c&&(null==n||n.setAttribute("style","position: absolute;"+(a.indexOf("color")>-1?"background-color: ":"border-bottom: ")+(a.indexOf("color")>-1?wt[a.split("-")[1]]:`2px solid ${bt[a.split("-")[1]]}`)+"; left:"+(Math.min(t[0],t[2])+parseFloat(getComputedStyle(c).marginLeft))+"px; top:"+Math.min(t[1],t[3])+"px;width:"+Math.abs(t[0]-t[2])+"px; height:"+Math.abs(t[1]-t[3])+"px; z-index: 1;opacity: "+(a.indexOf("color")>-1?.3:1)+";"),null==n||n.setAttribute("data-key",i),null==n||n.setAttribute("class","kookit-note"),null==n||n.addEventListener("click",(e=>{e&&e.target&&e.target.dataset&&e.target.dataset.key&&r(e)})),n.ontouchend=e=>{e&&e.target&&e.target.dataset&&e.target.dataset.key&&r(e),e.preventDefault(),e.stopPropagation()},l.appendChild(n))}))},Ct=e=>{const t=e.querySelectorAll(".kookit-note");for(let e=0;e{const o=Tt(e.getClientRects());for(let e=0;e-1?"background-color: ":"border-bottom: ")+(t.indexOf("color")>-1?yt[t.split("-")[1]]+";opacity: 1":`2px solid ${bt[t.split("-")[1]]}`)+";left:"+(Math.min(l.left,l.x)+n.body.scrollLeft)+"px; top:"+(Math.min(l.top,l.y)+n.body.scrollTop)+"px;width:"+l.width+"px; height:"+l.height+"px; z-index:-1;"),s.setAttribute("class"," kookit-note"),s.setAttribute("data-key",i),n.body.appendChild(s);var a=document.createElement("span");null==a||a.setAttribute("style","position: absolute;left:"+(Math.min(l.left,l.x)+n.body.scrollLeft)+"px; top:"+(Math.min(l.top,l.y)+n.body.scrollTop)+"px;width:"+l.width+"px; height:"+l.height+"px; z-index:1;"),a.setAttribute("class"," kookit-note"),a.setAttribute("data-key",i),a.addEventListener("click",(e=>{e&&e.target&&e.target.dataset&&e.target.dataset.key&&r(e)})),a.ontouchend=e=>{e&&e.target&&e.target.dataset&&e.target.dataset.key&&r(e),e.preventDefault(),e.stopPropagation()},n.body.appendChild(a)}},Tt=e=>{let t=[];for(let i=0;i{var t=e.commonAncestorContainer,i=new Array(0),r=new Array(0);if(e.startContainer!==t)for(let r=e.startContainer;r!==t;r=r.parentNode)i.push(r);if(i.length>0)for(let t=0;t0)for(let t=0;t0&&o.length>0))return[e];var c=document.createRange();return c.setStartAfter(i[i.length-1]),c.setEndBefore(o[o.length-1]),r.push(c),r.concat(s)};const Mt=(e,t,i)=>{!function(e){let t=document.getElementById("book");t&&t.remove();const i=document.createElement("div");i.id="book";const r=document.createElement("canvas");r.id="pageflip-canvas";const n=document.createElement("div");n.id="pages";for(let t=0;t{console.info("flipToNextPage"),d+1{console.info("flipToPrevPage"),d-1>=0&&(p[d-1].target=1,d=Math.max(d-1,0))},mouseDownHandler:v,mouseUpHandler:x,mouseMoveHandler:w}}}function w(e){if(!g)return;const t=e.touches[0],i=t.screenX,r=t.screenY;f.x=i-g.offsetLeft-o/2,f.y=r-g.offsetTop}function v(e){const t=e.touches[0];t.screenX=0?p[d-1].dragging=!0:t.screenX>window.screen.width/2&&d+1{let t=this.getDocument();t&&("Simplified To Traditional"===this.convertChinese?t.querySelectorAll("h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address").forEach((t=>{t.innerHTML=t.innerHTML.split("").map((t=>e.s2t(t))).join("")})):"Traditional To Simplified"===this.convertChinese&&t.querySelectorAll("h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address").forEach((t=>{t.innerHTML=t.innerHTML.split("").map((t=>e.t2s(t))).join("")})))},this.addPageAnimation=e=>{if("mimical"===this.animation){let t=this.getProgress();if(!t)return;const i=Mt(t.totalPage,this.isDarkMode,e);i&&(this.flipToNextPage=i.flipToNextPage,this.flipToPrevPage=i.flipToPrevPage,this.mouseDownHandler=i.mouseDownHandler,this.mouseUpHandler=i.mouseUpHandler,this.mouseMoveHandler=i.mouseMoveHandler)}},this.readerMode=t.readerMode,this.animation=t.animation,this.format=t.format,this.convertChinese=t.convertChinese,this.isDarkMode=t.isDarkMode,this.isMobile=t.isMobile,this.chapterList=[],this.chapterDocList=[],this.flattenChapters=[],this.book="",this.element="",this.tempLocation={},this.flipToNextPage=()=>{},this.flipToPrevPage=()=>{},this.mouseDownHandler=()=>{},this.mouseUpHandler=()=>{},this.mouseMoveHandler=e=>{}}getPageSize(){let e="double"===this.readerMode?2:1,t=Math.floor(this.element.clientWidth/12),i=t%2==0?t:t-1;return{width:this.element.clientWidth,height:this.element.clientHeight,left:this.element.offsetLeft,top:this.element.offsetTop,scrollTop:this.element.scrollTop,sectionWidth:(this.element.clientWidth-i)/e,gap:i}}resolveChapter(e){let t=e,i=-1;for(let e=0;e-1)return this.flattenChapters[i];{let r=e.split("#")[0];for(let e=0;e-1)return this.flattenChapters[i];for(let e=0;e-1?{label:"",href:"",index:i}:null}}flatChapter(e){let t=[];for(let i=0;i0?(t.push(e[i]),t=t.concat(this.flatChapter(e[i].subitems))):t.push(e[i]);return this.flattenChapters=t,t}getChapter(){return this.chapterList}getChapterDoc(){return this.chapterDocList}goToPercentage(e){return d(this,void 0,void 0,(function*(){if(this.flattenChapters.length>0){let t=1===e?this.flattenChapters.length-1:Math.floor(this.flattenChapters.length*e);yield this.goToChapter(this.flattenChapters[t].index.toString(),this.flattenChapters[t].href,this.flattenChapters[t].label)}}))}goToChapterIndex(e){return d(this,void 0,void 0,(function*(){this.flattenChapters.length>0&&(yield this.goToChapter(this.flattenChapters[e].index,this.flattenChapters[e].href,this.flattenChapters[e].label))}))}goToChapter(e,t,i){return d(this,void 0,void 0,(function*(){let r=this.getDocument(),n=this.getIframe();r&&n&&(yield Ze(parseInt(e),i,t,this.chapterDocList,this.element,this.readerMode,this.format,this.tempLocation,r,n),t&&t.indexOf("#")>-1&&(yield Ye(this.element,this.readerMode,"","",t,"",r)),yield this.record(),this.trigger("rendered"))}))}goToPosition(e){return d(this,void 0,void 0,(function*(){let t=this.getDocument(),i=this.getIframe();if(!t||!i)return;let r=JSON.parse(e);this.tempLocation={text:r.text,chapterTitle:r.chapterTitle,chapterDocIndex:r.chapterDocIndex,chapterHref:r.chapterHref,count:r.count,page:r.page};let{text:n,chapterTitle:o,chapterDocIndex:s,chapterHref:a,count:l,page:c,cfi:d}=r;if(yield Ze(parseInt(s),o,a,this.chapterDocList,this.element,this.readerMode,this.format,this.tempLocation,t,i),d){const e=new gt(d,{});let t=this.getDocument();if(!t)return;const{node:i,offset:r}=e.resolve(t,{});if(i){let e=null,t=i;for(;t;){const i=t;if(i.tagName&&"h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address".indexOf(i.tagName.toLowerCase())>-1){e=i;break}t=t.parentNode}e&&(l="ignore",n=e.textContent)}}yield Ye(this.element,this.readerMode,n,l,"",c,t),yield this.record(),this.trigger("rendered")}))}getDocument(){let e=document.getElementById("page-area");if(!e)return null;let t=e.getElementsByTagName("iframe")[0];if(!t)return null;let i=t.contentDocument;return i||null}getIframe(){let e=document.getElementById("page-area");if(!e)return null;let t=e.getElementsByTagName("iframe")[0];return t||null}goToNode(e){return d(this,void 0,void 0,(function*(){let t=this.getDocument();if(!t)return;let i=Ke(e,this.element,this.readerMode),r=i?h(i.offsetLeft)-h(i.marginLeft||parseFloat(getComputedStyle(i).marginLeft)):0,n=i?h(i.offsetTop)-h(i.marginTop||parseFloat(getComputedStyle(i).marginTop)):0;"scroll"!==this.readerMode?t.body.scrollTo(r,0):this.element.scrollTo(0,n),yield this.record(),this.trigger("rendered")}))}removeContent(){this.element.innerHTML=""}prev(){return d(this,void 0,void 0,(function*(){let e=this.getDocument(),t=this.getIframe();if(e&&t){if("scroll"===this.readerMode&&0===h(this.element.scrollTop)||"scroll"!==this.readerMode&&0===h(e.body.scrollLeft)){if("0"===this.tempLocation.chapterDocIndex)return;yield Je(this.element,this.flatChapter(this.chapterList),this.chapterDocList,this.readerMode,this.format,this.tempLocation,e,t),parseInt(this.tempLocation.chapterDocIndex||"-1")>-1&&("scroll"===this.readerMode?this.element.scrollTo(0,e.body.scrollHeight):e.body.scrollTo(e.body.scrollWidth,0)),this.trigger("rendered")}else"scroll"===this.readerMode?this.element.scrollBy({left:0,top:-(this.element.clientHeight-50),behavior:"smooth"}):yield Xe(this.element,this.animation,1,e,this.flipToNextPage,this.flipToPrevPage,this.isMobile);yield this.record()}}))}next(){return d(this,void 0,void 0,(function*(){let e=this.getDocument(),t=this.getIframe();e&&t&&(Math.abs(e.body.scrollWidth-h(e.body.scrollLeft)-e.body.clientWidth)<10&&"scroll"!==this.readerMode||Math.abs(this.element.scrollHeight-h(this.element.scrollTop)-this.element.clientHeight)<10&&"scroll"===this.readerMode?(yield rt(this.element,this.flatChapter(this.chapterList),this.chapterDocList,this.readerMode,this.format,this.tempLocation,e,t),this.trigger("rendered")):"scroll"===this.readerMode?this.element.scrollBy({left:0,top:this.element.clientHeight-50,behavior:"smooth"}):yield Xe(this.element,this.animation,-1,e,this.flipToNextPage,this.flipToPrevPage,this.isMobile),yield this.record())}))}prevChapter(){return d(this,void 0,void 0,(function*(){let e=this.getDocument(),t=this.getIframe();e&&t&&(yield Je(this.element,this.flatChapter(this.chapterList),this.chapterDocList,this.readerMode,this.format,this.tempLocation,e,t),yield this.record(),this.trigger("rendered"))}))}nextChapter(){return d(this,void 0,void 0,(function*(){let e=this.getDocument(),t=this.getIframe();e&&t&&(yield rt(this.element,this.flatChapter(this.chapterList),this.chapterDocList,this.readerMode,this.format,this.tempLocation,e,t),yield this.record(),this.trigger("rendered"))}))}visibleText(){let e=this.getDocument();return e?nt(this.element,this.readerMode,e):""}audioText(){let e=this.getDocument();return e?((e,t,i)=>{let r=ze(i.body).filter((e=>!ot(e))).filter((e=>(e.textContent||"").trim())).filter((e=>"img"!==e.textContent)).map((e=>e.textContent)),n=0,o=nt(e,t,i);if(o&&o.length>0){let e=o[0];n=r.indexOf(e)}return r.slice(n)})(this.element,this.readerMode,e):""}chapterText(){let e=this.getDocument();return e?e.body.innerText:""}highlightNode(e,t){let i=this.getDocument();i&&((e,t,i)=>{let r=ze(i.body).filter((i=>(i.getAttribute("style")===t&&i.setAttribute("style",""),(i.textContent||"").trim()&&i.textContent===e)));r.length>0&&r[0].setAttribute("style",t)})(e,t,i)}doSearch(e){return d(this,void 0,void 0,(function*(){return yield((e,i)=>d(void 0,void 0,void 0,(function*(){var r;let n=[];for(let t=0;t!ot(e)));for(let o=0;o-1&&n.push({excerpt:(null===(r=s[o].textContent)||void 0===r?void 0:r.substring(a-100,a+100))||"",cfi:JSON.stringify({text:s[o].textContent,chapterTitle:i[t].label,chapterDocIndex:t,chapterHref:i[t].href,count:"search",percentage:t/i.length})})}}return t.uniq(n,"excerpt")})))(e,this.chapterDocList)}))}getProgress(){let e=this.getDocument();if(e)return y(this.readerMode,e)}record(){return d(this,void 0,void 0,(function*(){""!==this.animation&&(yield new Promise((e=>setTimeout(e,1e3))));let e=this.getDocument();e&&(yield et(this.element,this.readerMode,this.flatChapter(this.chapterList),this.chapterDocList,this.tempLocation,e,null),this.trigger("page-changed"))}))}getPosition(){return this.tempLocation}getNotePosition(){return d(this,void 0,void 0,(function*(){let e=this.getDocument();if(!e)return;let t=function(e){const t=e.getSelection();if(!t)return null;if(t.rangeCount>0)return t.getRangeAt(0).startContainer.parentElement;return null}(e);return t?(yield et(this.element,this.readerMode,this.flatChapter(this.chapterList),this.chapterDocList,this.tempLocation,e,t),this.tempLocation):void 0}))}setStyle(e){let t=this.getDocument();if(t){var i=document.createElement("style");i.innerHTML=e,t.head.appendChild(i)}}getHightlightCoords(){return d(this,void 0,void 0,(function*(){i.init();let e=this.getDocument(),t=this.getIframe();if(e&&t)return i.getSelection(t).saveCharacterRanges(e.body)[0]}))}renderHighlighters(e,t){return d(this,void 0,void 0,(function*(){let i=this.getDocument(),r=this.getIframe();if(i&&r){Ct(i);for(let n=0;n{var a;let l=t.contentWindow||(null===(a=t.contentDocument)||void 0===a?void 0:a.defaultView),c=0,h=0,u=0,f=0,p=Math.floor(r.clientWidth/12),g=p%2==0?p:p-1,m=function(t){console.info("touchend");let i=(new Date).getTime();if(i-f<=300)return void t.preventDefault();f=i;const a=t.changedTouches[0],d=Date.now(),p=a.screenX,m=a.screenY,y=d-c,w=p-h,v=m-u;if(b&&"mimical"===o)return b=!1,s.mouseUpHandler(t),a.screenX{let e=document.getElementById("book");e&&(e.style.display="none")}),400);if(b&&"sliding"===o){window.scrollAnimationId&&cancelAnimationFrame(window.scrollAnimationId),e.body.style.transform="";let A,k=r.clientWidth+g,E=e.body.scrollLeft;const D=Math.round(E/k),R=Math.abs(w)/window.screen.width,I=.1;A=w>0&&R>I?(D-1)*k:w<0&&R>I?(D+1)*k:D*k,A=Math.max(0,Math.min(A,e.body.scrollWidth-k)),e.body.scrollWidth-A1-Math.pow(1-e,3);function F(t){const i=t-N;if(i>=H)return e.body.scrollLeft=A,e.body.style.willChange="auto",s.record(),void(b=!1);const r=P(i/H),n=B+O*r;e.body.scrollLeft=n,window.scrollAnimationId=requestAnimationFrame(F)}window.scrollAnimationId=requestAnimationFrame(F)}else{var x=l.getSelection().toString();if(x)window.ReactNativeWebView.postMessage(JSON.stringify({event:"select-text-after-touch",selectedText:x}));else if(y<500&&Math.abs(w)<30&&Math.abs(v)<30){var C=window.screen.width/3,L=window.screen.height/3,T=Math.floor(p/C),S=Math.floor(m/L),M="";0===S&&(0===T||1===T)||1===S&&0===T||2===S&&0===T||0===S&&1===T?M="left":1===S&&1===T?M="center":(0===S&&2===T||1===S&&2===T||2===S&&2===T||2===S&&1===T)&&(M="right"),window.ReactNativeWebView.postMessage(JSON.stringify({event:M}))}else(Math.abs(w)>=30||Math.abs(v)>=30)&&(console.info("Swipe detected"),window.ReactNativeWebView.postMessage(JSON.stringify({event:"swipe"})),"scroll"===n&&Math.abs(r.scrollHeight-r.scrollTop-r.clientHeight)<10&&window.ReactNativeWebView.postMessage(JSON.stringify({event:"scroll-bottom"})),"scroll"===n&&0===r.scrollTop&&window.ReactNativeWebView.postMessage(JSON.stringify({event:"scroll-top"})))}},y=function(e){const t=e.target;if(!t)return;if("IMG"===t.tagName){const e=t.src||t.getAttribute("xlink:href");window.ReactNativeWebView.postMessage(JSON.stringify({event:"view-image",imgSrc:e}))}e.touches.length>1&&e.preventDefault();const i=e.touches[0];c=Date.now(),h=i.screenX,u=i.screenY},b=!1,w=0,v=function(t){if(!b&&Math.abs(t.touches[0].screenX-h)<=10)return;t.preventDefault();const i=t.touches[0],n=i.screenX,a=i.screenY,l=n-h,c=a-u;if(!b&&Math.abs(l)>Math.abs(c)&&Math.abs(l)>10){if(b=!0,w=n,e.body.style.transform="translateZ(0)","mimical"===o){window.ReactNativeWebView.postMessage(JSON.stringify({event:"swipe-start"}));let e=document.getElementById("book");e&&(e.style.display="block",s.mouseDownHandler(t))}}else if(b&&"mimical"===o&&s.mouseMoveHandler(t),b&&"sliding"===o){const t=n-w;if(Math.abs(e.body.scrollWidth-e.body.scrollLeft-r.clientWidth)<10&&t<0)return x&&clearTimeout(x),void(x=setTimeout((()=>{s.next()}),300));if(0===e.body.scrollLeft&&t>0)return x&&clearTimeout(x),void(x=setTimeout((()=>{s.prev()}),300));const i=e.body.scrollLeft;e.body.scrollLeft=i-t,w=n,requestAnimationFrame((()=>{}))}};e.body.ontouchend=m,e.body.ontouchstart=y,e.body.ontouchmove=v,l.ontouchend=m,l.ontouchstart=y,l.ontouchmove=v;let x=null;e.body.oncontextmenu=function(e){return e.preventDefault(),e.stopPropagation(),!1};let C=0;e.addEventListener("selectstart",(t=>{"scroll"!==n&&(C=e.body.scrollLeft)}),!1),e.addEventListener("selectionchange",(t=>{C>0&&(e.body.scrollLeft=C),x&&clearTimeout(x),x=setTimeout((()=>d(void 0,void 0,void 0,(function*(){const e=l.getSelection().toString().trim();if(e){var t=l.getSelection().getRangeAt(0).getBoundingClientRect(),n={top:t.top-r.scrollTop,left:t.left,width:t.width,height:t.height,screenWidth:window.innerWidth,screenHeight:window.innerHeight};i.init();let o=yield s.getHightlightCoords();window.ReactNativeWebView.postMessage(JSON.stringify({event:"select-text",selectedText:e,position:n,range:o}))}}))),500)}),!1)})(t,r,this.element,this.readerMode,this.animation,this):at(t,r,this.element,this.readerMode,this.animation,this))}clearSelection(){var e,t;let i=this.getIframe();if(!i)return;let r=i.contentWindow||(null===(e=i.contentDocument)||void 0===e?void 0:e.defaultView);r&&r.getSelection()&&(null===(t=r.getSelection())||void 0===t||t.empty())}clearSelectionKeepHighlight(){var e,t;let r=this.getDocument(),n=this.getIframe();if(!r||!n)return;let o=n.contentWindow||(null===(e=n.contentDocument)||void 0===e?void 0:e.defaultView);if(!o||!o.getSelection())return;let s=r.getSelection();if(!s)return;let a=s.getRangeAt(0);for(var l=St(a),c=0;c{var t;null===(t=e.parentNode)||void 0===t||t.removeChild(e)}));let t=this.getIframe();if(!t)return;i.init();let r=window.charRange;r&&i.getSelection(t).restoreCharacterRanges(e,[r])}}const kt={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"},Et={"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"},Dt=e=>d(void 0,void 0,void 0,(function*(){let i=yield r.loadAsync(e);var n=i.file("toc.json");let o=[];n&&(o=JSON.parse(yield n.async("string")));var s=i.file("sections.json");let a=[];s&&(a=JSON.parse(yield s.async("string")));const l={getCover:()=>""};return l.sections=a.map(((e,t)=>({id:e.href,load:()=>(e=>d(void 0,void 0,void 0,(function*(){var t=i.file("chapters/"+e+".html");let r="";return t&&(r=yield t.async("string")),URL.createObjectURL(new Blob([r],{type:"text/html"}))})))(t),unload:()=>{},loadAsset:e=>(e=>d(void 0,void 0,void 0,(function*(){var t=i.file(e);let r;return t&&(r=yield t.async("arraybuffer")),URL.createObjectURL(new Blob([r],{type:kt[e.split(".").reverse()[0]]}))})))(e)}))),l.toc=o.map((e=>({label:e.label,href:e.href,subitems:e.subitems}))),l.rendition={layout:"pre-paginated"},l.resolveHref=e=>({index:t.findLastIndex(a,{href:e})}),l.splitTOCHref=e=>[e,null],l.getTOCFragment=e=>e.documentElement,l})),Rt=e=>new Promise(((t,i)=>d(void 0,void 0,void 0,(function*(){let i=new L(e),n=yield i.getChapter(e.toc),o=yield i.getChapterDoc(),s=n,a=o.map((e=>({href:e.href,label:e.label}))),l=yield Promise.all(o.map((e=>d(void 0,void 0,void 0,(function*(){let t="";if(e.text.load){let i=yield fetch(yield e.text.load()).then((e=>e.blob()));t=yield i.text()}return t}))))),c=new r;c.file("toc.json",JSON.stringify(s)),c.file("sections.json",JSON.stringify(a));let h=[];for(let e=0;ee.blob()));r.file(t+"."+Et[o.type],o);let s="imgs/"+e+"/"+t+"."+Et[o.type];i[t].src=s,i[t].getAttribute("xlink:href")&&i[t].setAttribute("xlink:href",s)}catch(e){console.error(e)}}let r=Array.from(t.getElementsByTagName("link"));for(let t=0;te.blob()));n.file(t+"."+Et[r.type],r),i.href="css/"+e+"/"+t+"."+Et[r.type]}catch(e){console.error(e)}}h.push(t.documentElement.innerHTML)}let u=c.folder("chapters");if(u){for(let e=0;ed(void 0,void 0,void 0,(function*(){t(yield new Response(e).arrayBuffer())})))).catch((e=>{t("err")}))}}))));class It extends At{constructor(e,t){super(Object.assign({format:"EPUB"},t)),this.epubBuffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){let e=new Blob([this.epubBuffer]),t=new File([e],"book",{lastModified:(new Date).getTime(),type:e.type});try{const e=yield this.makeZipLoader(t);this.book=yield new Te(e).init()}catch(e){throw console.error(e),e}}))}preCache(){return d(this,void 0,void 0,(function*(){try{return this.book||(yield this.parse()),yield Rt(this.book)}catch(e){return""}}))}makeZipLoader(e){return d(this,void 0,void 0,(function*(){let t=yield r.loadAsync(e);const i=t.files;return{entries:Object.values(i).map((e=>({filename:e.name}))),loadText:e=>d(this,void 0,void 0,(function*(){let i=t.file(e);return i?i.async("string"):""})),loadBlob:e=>d(this,void 0,void 0,(function*(){let i=t.file(e);if(i){let e=yield i.async("arraybuffer");return new Blob([e])}return new Blob([new ArrayBuffer(0)])})),getSize:e=>0}}))}getMetadata(){return d(this,void 0,void 0,(function*(){try{this.book||(yield this.parse());let e=new L(this.book);return yield e.getMetadata()}catch(e){throw console.error(e,"error"),e}}))}}const Nt=e=>{if(!e)return"";const t=document.createElement("textarea");return t.innerHTML=e,t.value},Bt={XML:"application/xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml"},Ot={name:[0,32,"string"],type:[60,4,"string"],creator:[64,4,"string"],numRecords:[76,2,"uint"]},Ht={compression:[0,2,"uint"],numTextRecords:[8,2,"uint"],recordSize:[10,2,"uint"],encryption:[12,2,"uint"]},Pt={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"]},Ft={resourceStart:[108,4,"uint"],fdst:[192,4,"uint"],numFdst:[196,4,"uint"],frag:[248,4,"uint"],skel:[252,4,"uint"],guide:[260,4,"uint"]},$t={magic:[0,4,"string"],length:[4,4,"uint"],count:[8,4,"uint"]},Ut={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"]},jt={magic:[0,4,"string"],length:[4,4,"uint"],numControlBytes:[8,4,"uint"]},Wt={magic:[0,4,"string"],offset1:[8,4,"uint"],offset2:[12,4,"uint"]},qt={magic:[0,4,"string"],length:[4,4,"uint"],numEntries:[8,4,"uint"],codeLength:[12,4,"uint"]},zt={magic:[0,4,"string"],numEntries:[8,4,"uint"]},Xt={flags:[8,4,"uint"],dataStart:[12,4,"uint"],keyLength:[16,4,"uint"],keyStart:[20,4,"uint"]},Vt={1252:"windows-1252",65001:"utf-8"},Jt={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"]},Gt={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"]},Zt=(e,t)=>{const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},_t=(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},Yt=new TextDecoder,Kt=e=>Yt.decode(e),Qt=e=>{if(!e)return;const t=e.byteLength,i=4===t?"getUint32":2===t?"getUint16":"getUint8";return new DataView(e)[i](0)},ei=(e,t)=>Object.fromEntries(Array.from(Object.entries(e)).map((([e,[i,r,n]])=>[e,("string"===n?Kt:Qt)(t.slice(i,i+r))]))),ti=e=>new TextDecoder(Vt[e]),ii=(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}},ri=e=>{let t=0;for(const i of e.subarray(-4))128&i&&(t=0),t=t<<7|127&i;return t},ni=e=>{let t=0;for(;e>0;e>>=1)1&~e||t++;return t},oi=e=>{let t=0;for(;!(1&e);)e>>=1,t++;return t},si=e=>{let t=[];for(let i=0;i>>3,s=3+(7&n);for(let e=0;e{const i=t+32,r=i>>3;let n=0n;for(let i=t>>3;i<=r;i++)n=n<<8n|BigInt(e[i]??0);return n>>8n-BigInt(7&i)&0xffffffffn},li=async(e,t)=>{const i=await t(e),r=ei(Ut,i);if("INDX"!==r.magic)throw new Error("Invalid INDX record");const n=ti(r.encoding),o=i.slice(r.length),s=ei(jt,o);if("TAGX"!==s.magic)throw new Error("Invalid TAGX section");const a=(s.length-12)/4,l=Array.from({length:a},((e,t)=>new Uint8Array(o.slice(12+4*t,12+4*t+4)))),c={};let d=0;for(let i=0;i1){const{value:i,length:r}=ii(n,p);d.push([e,null,i,t]),p+=r}else d.push([e,1,null,t]);else d.push([e,a>>oi(i),null,t])}const g={};for(const[e,t,i,r]of d){const o=[];if(null!=t)for(let e=0;eQt(i.slice(8*t,8*t+4)))).map(((e,t,i)=>[e,i[t+1]]))}loadRecord(e){const t=this.#d[e];if(!t)throw new RangeError("Record index out of bounds");return this.#c.slice(...t).arrayBuffer()}async loadMagic(e){const t=this.#d[e][0];return Kt(await this.#c.slice(t,t+4).arrayBuffer())}}class di extends ci{#h=0;#u;#f;#p;#g;#m;constructor({unzlib:e}){super(),this.unzlib=e}async open(e){await super.open(e),this.headers=this.#y(await super.loadRecord(0)),this.#u=this.headers.mobi.resourceStart;let t=this.headers.mobi.version>=8;if(!t){const e=this.headers.exth?.boundary;if(e<4294967295)try{this.headers=this.#y(await super.loadRecord(e)),this.#h=e,t=!0}catch(e){console.warn(e),console.warn("Failed to open KF8; falling back to MOBI")}}return await this.#b(),t?new vi(this).init():new fi(this).init()}#y(e){const t=ei(Ht,e),i=ei(Pt,e);if("MOBI"!==i.magic)throw new Error("Missing MOBI header");const{titleOffset:r,titleLength:n,localeLanguage:o,localeRegion:s}=i;i.title=e.slice(r,r+n);const a=Gt[o];i.language=a?.[s>>2]??a?.[0];const l=64&i.exthFlag?((e,t)=>{const{magic:i,count:r}=ei($t,e);if("EXTH"!==i)throw new Error("Invalid EXTH header");const n=ti(t),o={};let s=12;for(let t=0;t=8?ei(Ft,e):null}}async#b(){const{palmdoc:e,mobi:t}=this.headers;this.#f=ti(t.encoding),this.#p=new TextEncoder;const{compression:i}=e;if(this.#g=1===i?e=>e:2===i?si:17480===i?await(async(e,t)=>{const i=await t(e.huffcdic),{magic:r,offset1:n,offset2:o}=ei(Wt,i);if("HUFF"!==r)throw new Error("Invalid HUFF record");const s=Array.from({length:256},((e,t)=>n+4*t)).map((e=>Qt(i.slice(e,e+4)))).map((e=>[128&e,31&e,e>>>8])),a=[null].concat(Array.from({length:32},((e,t)=>o+8*t)).map((e=>[Qt(i.slice(e,e+4)),Qt(i.slice(e+4,e+8))]))),l=[];for(let i=1;i{let t=new Uint8Array;const i=8*e.byteLength;for(let r=0;r>>24];if(!o){for(;n>>>32-di)break;const u=h-(n>>>32-d);let[f,p]=l[u];p||(f=c(f),l[u]=[f,!0]),t=Zt(t,f)}return t};return c})(t,this.loadRecord.bind(this)):null,!this.#g)throw new Error("Unknown compression type");const{trailingFlags:r}=t,n=1&r,o=ni(r>>>1);this.#m=e=>{for(let t=0;tnew Uint8Array(e))).then(this.#m).then(this.#g)}async loadResource(e){const t=await super.loadRecord(this.#u+e),i=Kt(t.slice(0,4));return"FONT"===i?(async(e,t)=>{const{flags:i,dataStart:r,keyLength:n,keyStart:o}=ei(Xt,e),s=new Uint8Array(e.slice(r));if(2&i){const t=16===n?1024:1040,i=new Uint8Array(e.slice(o,o+n)),r=Math.min(t,s.length);for(var a=0;a{const{table:i,cncx:r}=await li(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]}))),o=e=>(null==e.firstChild||(e.children=n.filter((t=>t.parent===e.index)).map(o)),e);return n.filter((e=>0===e.headingLevel)).map(o)})(e,this.loadRecord.bind(this))}getMetadata(){const{mobi:e,exth:t}=this.headers;return{identifier:e.uid.toString(),title:Nt(t?.title||this.decode(e.title)),author:t?.creator?.map(Nt),publisher:Nt(t?.publisher),language:t?.language??e.language,published:t?.date,description:Nt(t?.description),subject:t?.subject?.map(Nt),rights:Nt(t?.rights)}}async getCover(){const{exth:e}=this.headers,t=e?.coverOffset<4294967295?e?.coverOffset:e?.thumbnailOffset<4294967295?e?.thumbnailOffset:null;if(null!=t){const e=await this.loadResource(t);return new Blob([e])}}}const hi=/<\s*(?:mbp:)?pagebreak[^>]*>/gi,ui=/<[^<>]+filepos=['"]{0,1}(\d+)[^<>]*>/gi;class fi{parser=new DOMParser;serializer=new XMLSerializer;#w=new Map;#v=new Map;#r=new Map;#x;#C=[];#L=Bt.HTML;constructor(e){this.mobi=e}async init(){let e=new Uint8Array;for(let t=0;tString.fromCharCode(e))).join("");this.#x=[0].concat(Array.from(t.matchAll(hi),(e=>e.index))).map(((e,i,r)=>t.slice(e,r[i+1]))).map((e=>Uint8Array.from(e,(e=>e.charCodeAt(0))))).map((e=>({book:this,raw:e}))).reduce(((e,t)=>{const i=e[e.length-1];return t.start=i?.end??0,t.end=t.start+t.raw.byteLength,e.concat(t)}),[]),this.sections=this.#x.map(((e,t)=>({id:t,load:()=>this.loadSection(e),createDocument:()=>this.createDocument(e),size:e.end-e.start})));try{this.landmarks=await this.getGuide();const e=this.landmarks.find((({type:e})=>e?.includes("toc")))?.href;if(e){const{index:t}=this.resolveHref(e),i=await this.sections[t].createDocument();let r,n=0,o=0;const s=new Map,a=new Map;this.toc=Array.from(i.querySelectorAll("a[filepos]")).reduce(((e,t)=>{const i=(e=>{let t=0;for(;e;){const i=e.parentElement;if(i){const e=i.tagName.toLowerCase();"p"===e?t+=1.5:"blockquote"===e&&(t+=2)}e=i}return t})(t),l={label:t.innerText?.trim(),href:`filepos:${t.getAttribute("filepos")}`},c=i>o?n+1:i===o?n:s.get(i)??Math.max(0,n-1);if(c>n)r?(r.subitems??=[],r.subitems.push(l),a.set(c,r)):e.push(l);else{const t=a.get(c);t?t.subitems.push(l):e.push(l)}return r=l,n=c,o=i,s.set(i,c),e}),[])}}catch(e){console.warn(e)}return this.#C=[...new Set(Array.from(t.matchAll(ui),(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.#x[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.#w.has(e))return this.#w.get(e);const t=await this.mobi.loadResource(e),i=URL.createObjectURL(new Blob([t]));return this.#w.set(e,i),i}async loadRecindex(e){return this.loadResource(Number(e)-1)}async replaceResources(e){for(const t of e.querySelectorAll("img[recindex]")){const e=t.getAttribute("recindex");try{t.src=await this.loadRecindex(e)}catch(t){console.warn(`Failed to load image ${e}`)}}for(const t of e.querySelectorAll("[mediarecindex]")){const e=t.getAttribute("mediarecindex"),i=t.getAttribute("recindex");try{t.src=await this.loadRecindex(e),i&&(t.poster=await this.loadRecindex(i))}catch(t){console.warn(`Failed to load media ${e}`)}}for(const t of e.querySelectorAll("[filepos]")){const e=t.getAttribute("filepos");t.href=`filepos:${e}`}}async loadText(e){if(this.#v.has(e))return this.#v.get(e);const{raw:t}=e,i=this.#C.filter((({number:t})=>t>=e.start&&t({...t,offset:t.number-e.start})));let r=t;i.length&&(r=t.subarray(0,i[0].offset),i.forEach((({filepos:e,offset:n},o)=>{const s=i[o+1],a=this.mobi.encode(``);r=_t(r,a,t.subarray(n,s?.offset))})));const n=this.mobi.decode(r).replaceAll(hi,"");return this.#v.set(e,n),n}async createDocument(e){const t=await this.loadText(e);return this.parser.parseFromString(t,this.#L)}async loadSection(e){if(this.#r.has(e))return this.#r.get(e);const t=await this.createDocument(e),i=t.createElement("style");t.head.append(i),i.append(t.createTextNode("blockquote {\n margin-block-start: 0;\n margin-block-end: 0;\n margin-inline-start: 1em;\n margin-inline-end: 0;\n }")),await this.replaceResources(t);const r=this.serializer.serializeToString(t),n=URL.createObjectURL(new Blob([r],{type:this.#L}));return this.#r.set(e,n),n}resolveHref(e){const t=e.match(/filepos:(.*)/)[1],i=Number(t);return{index:this.#x.findIndex((e=>e.end>i)),anchor:e=>e.getElementById(`filepos${t}`)}}splitTOCHref(e){const t=e.match(/filepos:(.*)/)[1],i=Number(t);return[this.#x.findIndex((e=>e.end>i)),`filepos${t}`]}getTOCFragment(e,t){return e.getElementById(t)}isExternal(e){return/^(?!blob|filepos)\w+:/i.test(e)}destroy(){for(const e of this.#w.values())URL.revokeObjectURL(e);for(const e of this.#r.values())URL.revokeObjectURL(e)}}const pi=/kindle:(flow|embed):(\w+)(?:\?mime=(\w+\/[-+.\w]+))?/,gi=/kindle:pos:fid:(\w+):off:(\w+)/,mi=e=>{const[t,i]=e.match(gi).slice(1);return{fid:parseInt(t,32),off:parseInt(i,32)}},yi=(e=0,t=0)=>`kindle:pos:fid:${e.toString(32).toUpperCase().padStart(4,"0")}:off:${t.toString(32).toUpperCase().padStart(10,"0")}`,bi=e=>{const t=e.match(/\s(id|name|aid)\s*=\s*['"]([^'"]*)['"]/i);if(!t)return;const[,i,r]=t;return`[${i}="${CSS.escape(r)}"]`},wi=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"}};class vi{parser=new DOMParser;serializer=new XMLSerializer;#r=new Map;#T=new Map;#S=new Map;#M={};#x;#A;#k=new Uint8Array;#E=new Uint8Array;#D=-1;#R=-1;#L=Bt.XHTML;#I=new Map;constructor(e){this.mobi=e}async init(){const e=this.mobi.loadRecord.bind(this.mobi),{kf8:t}=this.mobi.headers;try{const i=await e(t.fdst),r=ei(zt,i);if("FDST"!==r.magic)throw new Error("Missing FDST record");const n=Array.from({length:r.numEntries},((e,t)=>12+8*t)).map((e=>[Qt(i.slice(e,e+4)),Qt(i.slice(e+4,e+8))]));this.#M.fdstTable=n,this.#A=n[n.length-1][1]}catch{}const i=(await li(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]}))),r=await li(t.frag,e),n=r.table.map((({name:e,tagMap:t})=>({insertOffset:parseInt(e),selector:r.cncx[t[2][0]],index:t[4][0],offset:t[6][0],length:t[6][1]})));this.#M.skelTable=i,this.#M.fragTable=n,this.#x=i.reduce(((e,t)=>{const i=e[e.length-1],r=i?.fragEnd??0,o=r+t.numFrag,s=n.slice(r,o),a=t.length+s.map((e=>e.length)).reduce(((e,t)=>e+t)),l=(i?.totalLength??0)+a;return e.concat({skel:t,frags:s,fragEnd:o,length:a,totalLength:l})}),[]);const o=await this.getResourcesByMagic(["RESC","PAGE"]),s=new Map;if(o.RESC){const e=await this.mobi.loadRecord(o.RESC),t=this.mobi.decode(e.slice(16)).replace(/\0/g,""),i=t.search(/\?>/),r=`${t.slice(i)}`,n=this.parser.parseFromString(r,Bt.XML);for(const e of n.querySelectorAll("spine > itemref")){const t=parseInt(e.getAttribute("skelid"));s.set(t,wi(e.getAttribute("properties")?.split(" ")??[]))}}this.sections=this.#x.map(((e,t)=>e.frags.length?{id:t,load:()=>this.loadSection(e),createDocument:()=>this.createDocument(e),size:e.length,pageSpread:s.get(t)}:{linear:"no"}));try{const e=await this.mobi.getNCX(),t=({label:e,pos:i,children:r})=>{const[n,o]=i,s=yi(n,o),a=this.#T.get(n);return a?a.push(o):this.#T.set(n,[o]),{label:Nt(e),href:s,subitems:r?.map(t)}};this.toc=e?.map(t),this.landmarks=await this.getGuide()}catch(e){console.warn(e)}const{exth:a}=this.mobi.headers;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(e){const t={},i=this.mobi.headers.kf8.resourceStart,r=this.mobi.pdb.numRecords;for(let n=i;ne===i));r&&(t[r]=n)}catch{}return t}async getGuide(){const e=this.mobi.headers.kf8.guide;if(e<4294967295){const t=this.mobi.loadRecord.bind(this.mobi),{table:i,cncx:r}=await li(e,t);return i.map((({name:e,tagMap:t})=>({label:r[t[1][0]]??"",type:e?.split(/\s/),href:yi(t[6]?.[0]??t[3]?.[0])})))}}async loadResourceBlob(e){const{resourceType:t,id:i,type:r}=(e=>{const[t,i,r]=e.match(pi).slice(1);return{resourceType:t,id:parseInt(i,32),type:r}})(e),n="flow"===t?await this.loadFlow(i):await this.mobi.loadResource(i-1),o=[Bt.XHTML,Bt.HTML,Bt.CSS,Bt.SVG].includes(r)?await this.replaceResources(this.mobi.decode(n)):n,s=r===Bt.SVG?this.parser.parseFromString(o,r):null;return[new Blob([o],{type:r}),s?.getElementsByTagNameNS("http://www.w3.org/2000/svg","image")?.length?s.documentElement:null]}async loadResource(e){if(this.#r.has(e))return this.#r.get(e);const[t,i]=await this.loadResourceBlob(e),r=i?e:URL.createObjectURL(t);return i&&this.#I.set(r,i),this.#r.set(e,r),r}replaceResources(e){return(async(e,t,i)=>{const r=[];e.replace(t,((...e)=>(r.push(e),null)));const n=[];for(const e of r)n.push(await i(...e));return e.replace(t,(()=>n.shift()))})(e,new RegExp(pi,"g"),this.loadResource.bind(this))}async loadRaw(e,t){const i=t-this.#k.length,r=null==this.#A?1/0:this.#A-this.#E.length-e;if(i<0||ie;){const e=this.mobi.headers.palmdoc.numTextRecords-1-++this.#R,t=await this.mobi.loadText(e);this.#E=Zt(t,this.#E)}const n=this.#A-this.#E.length;return this.#E.slice(e-n,t-n)}loadFlow(e){if(e<4294967295)return this.loadRaw(...this.#M.fdstTable[e])}async loadText(e){const{skel:t,frags:i,length:r}=e,n=await this.loadRaw(t.offset,t.offset+r);let o=n.slice(0,t.length);for(const e of i){const i=e.insertOffset-t.offset,r=t.length+e.offset,s=n.slice(r,r+e.length);o=_t(o.slice(0,i),s,o.slice(i));const a=this.#T.get(e.index);if(a)for(const t of a){const i=this.mobi.decode(s).slice(t),r=bi(i);this.#N(e.index,t,r)}}return this.mobi.decode(o)}async createDocument(e){const t=await this.loadText(e);return this.parser.parseFromString(t,this.#L)}async loadSection(e){if(this.#r.has(e))return this.#r.get(e);const t=await this.loadText(e),i=await this.replaceResources(t);let r=this.parser.parseFromString(i,this.#L);r.querySelector("parsererror")&&(this.#L=Bt.HTML,r=this.parser.parseFromString(i,this.#L));for(const[e,t]of this.#I)for(const i of r.querySelectorAll(`img[src="${e}"]`))i.replaceWith(t);const n=URL.createObjectURL(new Blob([this.serializer.serializeToString(r)],{type:this.#L}));return this.#r.set(e,n),n}getIndexByFID(e){return this.#x.findIndex((t=>t.frags.some((t=>t.index===e))))}#N(e,t,i){const r=this.#S.get(e);if(r)r.set(t,i);else{const r=new Map;this.#S.set(e,r),r.set(t,i)}}async resolveHref(e){const{fid:t,off:i}=mi(e),r=this.getIndexByFID(t);if(r<0)return;const n=this.#S.get(t)?.get(i);if(n)return{index:r,anchor:e=>e.querySelector(n)};const{skel:o,frags:s}=this.#x[r],a=s.find((e=>e.index===t)),l=o.offset+o.length+a.offset,c=await this.loadRaw(l,l+a.length),d=this.mobi.decode(c).slice(i),h=bi(d);this.#N(t,i,h);return{index:r,anchor:e=>e.querySelector(h)}}splitTOCHref(e){const t=mi(e);return[this.getIndexByFID(t.fid),t]}getTOCFragment(e,{fid:t,off:i}){const r=this.#S.get(t)?.get(i);return e.querySelector(r)}isExternal(e){return/^(?!blob|kindle)\w+:/i.test(e)}destroy(){for(const e of this.#r.values())URL.revokeObjectURL(e)}}class xi extends At{constructor(e,t){super(Object.assign({format:"MOBI"},t)),this.mobiBuffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){try{let e=new Blob([this.mobiBuffer]),t=new File([e],"book",{lastModified:(new Date).getTime(),type:e.type});(yield(async e=>"BOOKMOBI"===Kt(await e.slice(60,68).arrayBuffer()))(t))&&(this.book=yield new di({unzlib:n}).open(t))}catch(e){throw console.error(e),e}}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield Rt(this.book)}))}getMetadata(){return d(this,void 0,void 0,(function*(){try{this.book||(yield this.parse());let e=new L(this.book);return yield e.getMetadata()}catch(e){throw console.error(e),e}}))}}const Ci=e=>`${Si()?".":""}/lib/pdfjs/${e}`,Li=window.pdfjsLib,Ti=async e=>await(await fetch(e)).text(),Si=()=>"undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type||(!("undefined"==typeof process||"object"!=typeof process.versions||!process.versions.electron)||"object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0),Mi=async()=>await Ti(Ci("text_layer_builder.css")),Ai=async()=>await Ti(Ci("annotation_layer_builder.css")),ki=async(e,t)=>{const i=e.getViewport({scale:1});if(t){const t=document.createElement("canvas");t.height=i.height,t.width=i.width;const r=t.getContext("2d");return await e.render({canvasContext:r,viewport:i}).promise,new Promise((e=>t.toBlob(e)))}return URL.createObjectURL(new Blob([`\n \n \n \n \n \n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n\n `],{type:"text/html"}))},Ei=e=>({label:e.title,href:e.dest?JSON.stringify(e.dest):null,subitems:e.items.length?e.items.map(Ei):null}),Di=async(e,t)=>{const i=new Li.PDFDataRangeTransport(e.size,[]);i.requestDataRange=(t,r)=>{e.slice(t,r).arrayBuffer().then((e=>{i.onDataRange(t,e)}))},console.log(Ci("cmaps/"));const r=await Li.getDocument({range:i,cMapUrl:Ci("cmaps/"),standardFontDataUrl:Ci("standard_fonts/"),isEvalSupported:!1}).promise,n={rendition:{layout:"pre-paginated"}},{metadata:o,info:s}=await r.getMetadata()??{};n.metadata={title:o?.get("dc:title")??s?.Title,author:o?.get("dc:creator")??s?.Author,contributor:o?.get("dc:contributor"),description:o?.get("dc:description")??s?.Subject,language:o?.get("dc:language"),publisher:o?.get("dc:publisher"),subject:o?.get("dc:subject"),identifier:o?.get("dc:identifier"),source:o?.get("dc:source"),rights:o?.get("dc:rights")};const a=await r.getOutline();n.toc=a?.map(Ei).filter(((e,i)=>"double"!==t||i%2==0));const l=new Map;return n.sections=Array.from({length:r.numPages}).map(((e,i)=>({id:i,load:async()=>{const e=l.get(i);if(e)return e;const t=await ki(await r.getPage(i+1));return l.set(i,t),t},unload:async()=>{(await r.getPage(i+1)).cleanup()},render:async(e,n)=>{await(async(e,t,i)=>{const r=i*devicePixelRatio;let n=t.querySelector("#koodoPDFLayer");n.style.visibility="hidden",n.style.transform=`scale(${1/devicePixelRatio})`,n.style.transformOrigin="top left",n.style.setProperty("--scale-factor",r);const o=e.getViewport({scale:r}),s=document.createElement("canvas");n.style.width=`${o.width}px`,n.style.height=`${o.height}px`,s.height=o.height,s.width=o.width;const a=s.getContext("2d");await e.render({canvasContext:a,viewport:o,background:"rgba(0,0,0,0)"}).promise,t.querySelector("#canvas").replaceChildren(t.adoptNode(s)),n.style.overflow="hidden";const l=t.querySelector("#textLayer"),c=new Li.TextLayer({textContentSource:await e.streamTextContent(),container:l,viewport:o});await c.render();for(const e of document.querySelectorAll(".hiddenCanvasElement"))Object.assign(e.style,{position:"absolute",top:"0",left:"0",width:"0",height:"0",display:"none"});const d=document.createElement("div");d.className="endOfContent",l.append(d),l.onpointerdown=()=>l.classList.add("selecting"),l.onpointerup=()=>l.classList.remove("selecting");const h=t.querySelector("#annotationLayer");await new Li.AnnotationLayer({page:e,viewport:o,div:h}).render({annotations:await e.getAnnotations(),linkService:{goToDestination:()=>{},getDestinationHash:e=>JSON.stringify(e),addLinkAttributes:(e,t)=>e.href=t}}),n.style.marginLeft=`calc(50% - ${n.getBoundingClientRect().width/2}px)`,n.style.visibility="visible"})(await r.getPage(i+1),e,n),"double"===t&&await(async(e,t,i)=>{const r=i*devicePixelRatio;let n=t.querySelector("#koodoPDFLayerExtra");n.style.display="block",n.style.visibility="hidden",n.style.transform=`scale(${1/devicePixelRatio})`,n.style.transformOrigin="top left",n.style.setProperty("--scale-factor",r);const o=e.getViewport({scale:r}),s=document.createElement("canvas");n.style.width=`${o.width}px`,n.style.height=`${o.height}px`,s.height=o.height,s.width=o.width;const a=s.getContext("2d");await e.render({canvasContext:a,viewport:o,background:"rgba(0,0,0,0)"}).promise,t.querySelector("#canvasExtra").replaceChildren(t.adoptNode(s)),n.style.overflow="hidden";const l=t.querySelector("#textLayerExtra"),c=new Li.TextLayer({textContentSource:await e.streamTextContent(),container:l,viewport:o});await c.render();for(const e of document.querySelectorAll(".hiddenCanvasElement"))Object.assign(e.style,{position:"absolute",top:"0",left:"0",width:"0",height:"0",display:"none"});const d=document.createElement("div");d.className="endOfContent",l.append(d),l.onpointerdown=()=>l.classList.add("selecting"),l.onpointerup=()=>l.classList.remove("selecting");const h=t.querySelector("#annotationLayerExtra");await new Li.AnnotationLayer({page:e,viewport:o,div:h}).render({annotations:await e.getAnnotations(),linkService:{goToDestination:()=>{},getDestinationHash:e=>JSON.stringify(e),addLinkAttributes:(e,t)=>e.href=t}}),n.style.marginLeft=`calc(50% - ${n.getBoundingClientRect().width/2}px)`,n.style.visibility="visible"})(await r.getPage(i+2),e,n)},size:1e3,getDimension:async()=>{let e=(await r.getPage(i+1)).getViewport({scale:1});return{width:e.width,height:e.height}},getPage:async()=>await r.getPage(i+1)}))).filter(((e,i)=>"double"!==t||i%2==0)),n.isExternal=e=>/^\w+:/i.test(e),n.resolveHref=async e=>{const t=JSON.parse(e),i="string"==typeof t?await r.getDestination(t):t;return{index:await r.getPageIndex(i[0])}},n.splitTOCHref=async e=>{const t=JSON.parse(e),i="string"==typeof t?await r.getDestination(t):t;return[await r.getPageIndex(i[0]),null]},n.getTOCFragment=e=>e.documentElement,n.getCover=async()=>ki(await r.getPage(1),!0),n.destroy=()=>r.destroy(),n};class Ri extends At{constructor(e,t){super(Object.assign(Object.assign({format:"PDF"},t),{convertChinese:"Default"})),this.pdfBuffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){try{let e=new Blob([this.pdfBuffer]),t=new File([e],"book",{lastModified:(new Date).getTime(),type:e.type});(yield(async e=>{const t=new Uint8Array(await e.slice(0,5).arrayBuffer());return 37===t[0]&&80===t[1]&&68===t[2]&&70===t[3]&&45===t[4]})(t))&&(this.book=yield Di(t,this.readerMode))}catch(e){throw console.error(e),e}}))}preCache(){return d(this,void 0,void 0,(function*(){return""}))}getMetadata(){return d(this,void 0,void 0,(function*(){try{this.book||(yield this.parse());let e=new L(this.book);return yield e.getMetadata()}catch(e){throw console.error(e),e}}))}getProgress(){return{totalPage:this.chapterDocList.length,currentPage:this.tempLocation.chapterDocIndex}}getHightlightCoords(){return d(this,void 0,void 0,(function*(){let e=this.tempLocation.chapterDocIndex,t=this.getDocument();if(!t)return;var i=t.getSelection().getRangeAt(0).getClientRects();let r=yield this.chapterDocList[e].text.getPage(),n=yield Ge(this.element,this.readerMode,this.chapterDocList,e);var o=r.getViewport({scale:n});let s=t.querySelector("canvas");var a=null==s?void 0:s.getClientRects()[0];let l=[];for(let e=0;ei[e].left&&(l[l.length-1].left=i[e].left),l[l.length-1].rightd(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){try{const e=new TextDecoder(this.charset),t=new Uint8Array(this.txtBuffer);let i=e.decode(t);this.book=Se(i,!0,this.parserRegex)}catch(e){throw console.error(e),e}}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield Rt(this.book)}))}getMetadata(e){return d(this,void 0,void 0,(function*(){try{const t=new Uint8Array(e);let i=o.detect(t);return this.charset=i||"utf8",{charset:i||"utf8"}}catch(e){throw console.error(e),e}}))}}const Ni=({entries:e,loadBlob:t,getSize:i},r,n)=>{const o=new Map,s=new Map,a=async(e,i)=>{if(o.has(e))return o.get(e);if(i){const r=URL.createObjectURL(await t(e)),n=URL.createObjectURL(await t(i)),a=URL.createObjectURL(new Blob([`
`],{type:"text/html"}));return s.set(e,[r,a]),o.set(e,a),a}{const i=URL.createObjectURL(await t(e)),r=URL.createObjectURL(new Blob([`
`],{type:"text/html"}));return s.set(e,[i,r]),o.set(e,r),r}},l=[".jpg",".jpeg",".png",".gif",".bmp",".webp",".svg"],c=e.map((e=>e.filename)).filter((e=>l.some((t=>e.endsWith(t))))).sort(),d={getCover:()=>t(c[0])};return d.metadata={title:r.name},d.sections=c.map(((e,t)=>({id:e,load:()=>{if("double"===n){const i=c[t+1];return a(e,i)}return a(e)},unload:()=>(e=>{s.get(e)?.forEach?.((e=>URL.revokeObjectURL(e))),s.delete(e),o.delete(e)})(e),size:i(e)}))).filter(((e,t)=>"double"!==n||t%2==0)),d.toc=c.map((e=>({label:e,href:e}))).filter(((e,t)=>"double"!==n||t%2==0)),d.rendition={layout:"pre-paginated"},d.resolveHref=e=>({index:d.sections.findIndex((t=>t.id===e))}),d.splitTOCHref=e=>[e,null],d.getTOCFragment=e=>e.documentElement,d};class Bi extends At{constructor(e,t){super(t),this.comicBuffer=e,this.readerMode=t.readerMode,this.format=t.format,this.chapterList=[],this.chapterDocList=[],this.book="",this.element="",this.rpc}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){if(this.element=e,m(e),!this.book)try{yield this.parse()}catch(e){console.error(e),i(e)}let r=new L(this.book);this.chapterList=yield r.getChapter(this.book.toc),this.chapterDocList=yield r.getChapterDoc();let n=this.getDocument();n&&(x(e,this.readerMode,n),t())}))))}parse(){return d(this,void 0,void 0,(function*(){try{let e=new Blob([this.comicBuffer]),t=new File([e],"book."+this.format.toLocaleLowerCase(),{lastModified:(new Date).getTime(),type:e.type});if("CBZ"===this.format){const e=yield this.makeZipLoader(t);this.book=Ni(e,t,this.readerMode)}else if("CBT"===this.format){const e=yield this.makeTarLoader();this.book=Ni(e,t,this.readerMode)}else if("CBR"===this.format){this.rpc=yield window.RPC.new("./lib/libunrar/worker.js",{loaded:function(){console.info("loaded")},progressShow:function(e,t,i){console.info(i)}}),yield new Promise((e=>setTimeout(e,200)));const e=yield this.makeRarLoader();this.book=Ni(e,t,this.readerMode)}else if("CB7"===this.format){const e=yield this.make7zLoader();this.book=Ni(e,t,this.readerMode)}}catch(e){throw console.error(e),e}}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield Rt(this.book)}))}makeZipLoader(e){return d(this,void 0,void 0,(function*(){let t=yield r.loadAsync(e);const i=t.files;return{entries:Object.values(i).map((e=>({filename:e.name}))),loadText:e=>d(this,void 0,void 0,(function*(){let i=t.file(e);return i?i.async("string"):""})),loadBlob:e=>d(this,void 0,void 0,(function*(){let i=t.file(e);if(i){let e=yield i.async("arraybuffer");return new Blob([e])}return new Blob([new ArrayBuffer(0)])})),getSize:e=>0}}))}makeTarLoader(){return d(this,void 0,void 0,(function*(){const e=yield s(this.comicBuffer),t=new Map(e.map((e=>[e.name,e]))),i=e=>(i,...r)=>t.has(i)?e(t.get(i),...r):null,r=i((e=>e.readAsString())),n=i(((e,t)=>e.blob));return{entries:e.map((e=>({filename:e.name}))),loadText:r,loadBlob:n,getSize:e=>{var i,r;return null!==(r=null===(i=t.get(e))||void 0===i?void 0:i.size)&&void 0!==r?r:0}}}))}makeRarLoader(){return d(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{var i=[this.comicBuffer],r=[{name:"book.rar",content:this.comicBuffer}];this.rpc.transferables=i,this.rpc.unrar(r,null,0).then((t=>{let i=this.getRarEntries(t.ls);const r=new Map(Object.values(i).map((e=>[e.fullFileName,e]))),n=e=>(t,...i)=>r.has(t)?e(r.get(t),...i):null,o=n((e=>e.fullFileName)),s=n(((e,t)=>new Blob([e.fileContent])));e({entries:Object.values(i).map((e=>({filename:e.fullFileName}))),loadText:o,loadBlob:s,getSize:e=>{var t,i;return null!==(i=null===(t=r.get(e))||void 0===t?void 0:t.fileSize)&&void 0!==i?i:0}})})).catch((e=>{console.error(e),t(e)}))}))}))}make7zLoader(){return d(this,void 0,void 0,(function*(){const e="./lib/7z-wasm/7zz.wasm";if(!window.wasmBinary){const t=yield fetch(e,{credentials:"same-origin"});if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";window.wasmBinary=yield t.arrayBuffer()}const t=yield window.SevenZip({wasmBinary:window.wasmBinary}),i=new Uint8Array(this.comicBuffer),r="archive.cb7",n=t.FS.open(r,"w+");t.FS.write(n,i,0,i.length),t.FS.close(n),t.callMain(["x",r]);const o=t.FS,s=this.get7zEntries(o.lookupPath("/").node),a=new Map(s.map((e=>[e.name,e]))),l=e=>(t,...i)=>a.has(t)?e(a.get(t),...i):null,c=l((e=>e.name)),d=l(((e,t)=>new Blob([e.buffer])));return{entries:s.map((e=>({filename:e.name}))),loadText:c,loadBlob:d,getSize:e=>{var t,i;return null!==(i=null===(t=a.get(e))||void 0===t?void 0:t.packSize)&&void 0!==i?i:0}}}))}getRarEntries(e){const t=Object.keys(e);let i=[];for(let r=0;r"archive.cb7"!=e&&"dev"!=e&&"home"!=e&&"proc"!=e&&"tmp"!=e));let r=[];for(let e=0;ed(this,void 0,void 0,(function*(){try{this.book||(yield this.parse());const t=yield this.book.getCover();var i=new FileReader;i.readAsDataURL(t),i.onloadend=()=>{e({cover:i.result})}}catch(e){console.error(e),t(e)}}))))}))}}const Oi=e=>e?.trim()?.replace(/\s{2,}/g," "),Hi=e=>Oi(e?.textContent),Pi={XLINK:"http://www.w3.org/1999/xlink",EPUB:"http://www.idpf.org/2007/ops"},Fi="application/xml",$i="application/xhtml+xml",Ui={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"},ji={epigraph:["blockquote"],subtitle:["h2",Ui],"text-author":["p",Ui],date:["p",Ui],stanza:"stanza"},Wi={title:["header",{p:["h1",Ui],"empty-line":["br"]}],epigraph:["blockquote","self"],image:"image",annotation:["aside"],section:["section","self"],p:["p",Ui],poem:["blockquote",ji],subtitle:["h2",Ui],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",Ui]};ji.epigraph.push(Wi);const qi={image:"image",title:["section",{p:["h1",Ui],"empty-line":["br"]}],epigraph:["section",Wi],section:["section",Wi]},zi=e=>{const t=e.getAttributeNS(Pi.XLINK,"href"),[,i]=t.split("#"),r=e.getRootNode().getElementById(i);return r?`data:${r.getAttribute("content-type")};base64,${r.textContent}`:t};class Xi{constructor(e){this.fb2=e,this.doc=document.implementation.createDocument(Pi.XHTML,"html")}image(e){const t=this.doc.createElement("img");return t.alt=e.getAttribute("alt"),t.title=e.getAttribute("title"),t.setAttribute("src",zi(e)),t}anchor(e){const t=this.convert(e,{a:["a",Ui]});return t.setAttribute("href",e.getAttributeNS(Pi.XLINK,"href")),"note"===e.getAttribute("type")&&t.setAttributeNS(Pi.EPUB,"epub:type","noteref"),t}stanza(e){const t=this.convert(e,{stanza:["p",{title:["header",{p:["strong",Ui],"empty-line":["br"]}],subtitle:["p",Ui]}]});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);const i=t?.[e.nodeName];if(!i)return null;if("string"==typeof i)return this[i](e);const[r,n]=i,o=this.doc.createElement(r);if(e.id&&(o.id=e.id),o.classList.add(e.nodeName),Array.isArray(n))for(const t of n)o.setAttribute(t,e.getAttribute(t));const s="self"===n?t:Array.isArray(n)?null:n;let a=e.firstChild;for(;a;){const e=this.convert(a,s);e&&o.append(e),a=a.nextSibling}return o}}const Vi=URL.createObjectURL(new Blob(['\n@namespace epub "http://www.idpf.org/2007/ops";\nbody > img, section > img {\n display: block;\n margin: auto;\n}\n.title {\n text-align: center;\n}\nbody > section > .title, body.notesBodyType > .title {\n margin: 3em 0;\n}\nbody.notesBodyType > section .title {\n text-align: left;\n margin: 1em 0;\n}\np {\n text-indent: 1em;\n margin: 0;\n}\n:not(p) + p, p:first-child {\n text-indent: 0;\n}\n.poem p {\n text-indent: 0;\n margin: 1em 0;\n}\n.text-author, .date {\n text-align: end;\n}\n.text-author:before {\n content: "—";\n}\ntable {\n border-collapse: collapse;\n}\ntd, th {\n padding: .25em;\n}\na[epub|type~="noteref"] {\n font-size: .75em;\n vertical-align: super;\n}\nbody:not(.notesBodyType) > .title, body:not(.notesBodyType) > .epigraph {\n margin: 3em 0;\n}\n'],{type:"text/css"})),Ji="data-foliate-id",Gi=async e=>{const t={},i=await(async e=>{const t=await e.arrayBuffer(),i=new TextDecoder("utf-8").decode(t),r=new DOMParser,n=r.parseFromString(i,Fi),o=n.xmlEncoding||i.match(/^<\?xml\s+version\s*=\s*["']1.\d+"\s+encoding\s*=\s*["']([A-Za-z0-9._-]*)["']/)?.[1];if(o&&"utf-8"!==o.toLowerCase()){const e=new TextDecoder(o).decode(t);return r.parseFromString(e,Fi)}return n})(e),r=new Xi(i),n=e=>i.querySelector(e),o=e=>[...i.querySelectorAll(e)],s=e=>{const t=Hi(e.querySelector("nickname"));if(t)return t;const i=Hi(e.querySelector("first-name")),r=Hi(e.querySelector("middle-name")),n=Hi(e.querySelector("last-name"));return{name:[i,r,n].filter((e=>e)).join(" "),sortAs:n?[n,[i,r].filter((e=>e)).join(" ")].join(", "):null}},a=e=>e?.getAttribute("value")??Hi(e),l=n("title-info annotation");t.metadata={title:Hi(n("title-info book-title")),identifier:Hi(n("document-info id")),language:Hi(n("title-info lang")),author:o("title-info author").map(s),translator:o("title-info translator").map(s),producer:o("document-info author").map(s).concat(o("document-info program-used").map(Hi)),publisher:Hi(n("publish-info publisher")),published:a(n("title-info date")),modified:a(n("document-info date")),description:l?r.convert(l,{annotation:["div",Wi]}).innerHTML:null,subject:o("title-info genre").map(Hi)},t.getCover=()=>fetch(zi(n("coverpage image"))).then((e=>e.blob()));const c=Array.from(i.querySelectorAll("body"),(e=>{const t=r.convert(e,{body:["body",qi]});return[Array.from(t.children,(e=>{const t=[e,...e.querySelectorAll("[id]")].map((e=>e.id));return{el:e,ids:t}})),t]})),d=c[0][0].map((({el:e,ids:t})=>({ids:t,titles:Array.from(e.querySelectorAll(":scope > section > .title"),((e,t)=>(e.setAttribute(Ji,t),{title:Hi(e),index:t}))),el:e}))).concat(c.slice(1).map((([e,t])=>{const i=e.map((e=>e.ids)).flat();return t.classList.add("notesBodyType"),{ids:i,el:t,linear:"no"}}))).map((({ids:e,titles:t,el:i,linear:r})=>{const n=(o=i.outerHTML,`\n\n \n ${o}\n`);var o;const s=new Blob([n],{type:$i}),a=URL.createObjectURL(s);return{ids:e,title:Oi(i.querySelector(".title, .subtitle, p")?.textContent??(i.classList.contains("title")?i.textContent:"")),titles:t,load:()=>a,createDocument:()=>(new DOMParser).parseFromString(n,$i),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=d.map(((e,t)=>{const{ids:i,load:r,createDocument:n,size:o,linear:s}=e;for(const e of i)e&&h.set(e,t);return{id:t,load:r,createDocument:n,size:o,linear:s}})),t.toc=d.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(`[${Ji}="${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(`[${Ji}="${t}"]`),t};class Zi extends At{constructor(e,t){super(Object.assign({format:"FB2"},t)),this.fb2Buffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){try{let e=new Blob([this.fb2Buffer]);this.book=yield Gi(e)}catch(e){throw console.error(e),e}}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield Rt(this.book)}))}getMetadata(){return d(this,void 0,void 0,(function*(){try{this.book||(yield this.parse());let e=new L(this.book);return yield e.getMetadata()}catch(e){throw console.error(e),e}}))}}class _i extends At{constructor(e,t){super(Object.assign({format:"CACHE"},t)),this.cacheBuffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book=yield Dt(this.cacheBuffer);let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}}class Yi extends At{constructor(e,t){super(Object.assign({format:"DOCX"},t)),this.docxBuffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{try{a.convertToHtml({arrayBuffer:this.docxBuffer}).then((t=>d(this,void 0,void 0,(function*(){this.book=Se(t.value,!1),e()}))))}catch(e){console.error(e),t(e)}}))}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield Rt(this.book)}))}}class Ki extends At{constructor(e,t){super(Object.assign({format:"MD"},t)),this.mdBuffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{try{var i=new Blob([this.mdBuffer],{type:"text/plain"}),r=new FileReader;r.onload=t=>d(this,void 0,void 0,(function*(){var i;let r=yield l(null===(i=t.target)||void 0===i?void 0:i.result);this.book=Se(r,!1),e()})),r.readAsText(i,"UTF-8")}catch(e){console.error(e),t(e)}}))}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield Rt(this.book)}))}}class Qi extends At{constructor(e,t){super(t),this.htmlBuffer=e}renderTo(e){return new Promise(((t,i)=>d(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse());let i=new L(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);let r=this.getDocument();r&&(x(e,this.readerMode,r),t())}))))}parse(){return d(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{try{var i=new Blob([this.htmlBuffer],{type:kt[this.format.toLocaleLowerCase()]}),r=new FileReader;r.onload=t=>d(this,void 0,void 0,(function*(){var i;let r=null===(i=t.target)||void 0===i?void 0:i.result;"MHTML"===this.format&&(r=c.convert(r).window.document.documentElement.innerHTML),this.book=Se(r,!1),e()})),r.readAsText(i,"UTF-8")}catch(e){console.error(e),t(e)}}))}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield Rt(this.book)}))}}export{_i as CacheRender,Bi as ComicRender,Yi as DocxRender,It as EpubRender,Zi as Fb2Render,Qi as HtmlRender,Ki as MdRender,xi as MobiRender,Ri as PdfRender,Ii as TxtRender}; diff --git a/src/pages/login/login.css b/src/pages/login/login.css index e8050a27..d6eb7def 100644 --- a/src/pages/login/login.css +++ b/src/pages/login/login.css @@ -142,6 +142,7 @@ } .login-sync-text { font-size: 12px; + line-height: 1.25; color: #585858; font-weight: bold; text-align: left; diff --git a/yarn.lock b/yarn.lock index 12738721..cd707bfa 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2648,9 +2648,9 @@ optionalDependencies: global-agent "^3.0.0" -"@electron/node-gyp@git+https://github.com/electron/node-gyp.git#06b29aafb7708acef8b3669835c8a7857ebc92d2": +"@electron/node-gyp@https://github.com/electron/node-gyp#06b29aafb7708acef8b3669835c8a7857ebc92d2": version "10.2.0-electron.1" - resolved "git+https://github.com/electron/node-gyp.git#06b29aafb7708acef8b3669835c8a7857ebc92d2" + resolved "https://github.com/electron/node-gyp#06b29aafb7708acef8b3669835c8a7857ebc92d2" dependencies: env-paths "^2.2.0" exponential-backoff "^3.1.1" @@ -4631,13 +4631,6 @@ abbrev@1, abbrev@^1.0.0: resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8" integrity sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q== -abort-controller@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/abort-controller/-/abort-controller-3.0.0.tgz#eaf54d53b62bae4138e809ca225c8439a6efb392" - integrity sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg== - dependencies: - event-target-shim "^5.0.0" - accepts@~1.3.4, accepts@~1.3.5, accepts@~1.3.8: version "1.3.8" resolved "https://registry.yarnpkg.com/accepts/-/accepts-1.3.8.tgz#0bf0be125b67014adcb0b0921e62db7bffe16b2e" @@ -7705,11 +7698,6 @@ etag@~1.8.1: resolved "https://registry.yarnpkg.com/etag/-/etag-1.8.1.tgz#41ae2eeb65efa62268aebfea83ac7d79299b0887" integrity sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg== -event-target-shim@^5.0.0: - version "5.0.1" - resolved "https://registry.yarnpkg.com/event-target-shim/-/event-target-shim-5.0.1.tgz#5d4d3ebdf9583d63a5333ce2deb7480ab2b05789" - integrity sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ== - eventemitter3@^4.0.0: version "4.0.7" resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-4.0.7.tgz#2de9b68f6528d5644ef5c59526a1b4a07306169f" @@ -10600,12 +10588,11 @@ media-typer@0.3.0: resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748" integrity sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ== -megajs@^1.3.5: - version "1.3.5" - resolved "https://registry.yarnpkg.com/megajs/-/megajs-1.3.5.tgz#870803cf7e51674a715cd554c6fc4cd233c081e8" - integrity sha512-bLbN/jwV0+GmRYuSg7ViE5QnxrBwYzJQWIg4l1S1iC9d1wsTLQjRIvqLxNhVVT4SkNAvTFwM+A544frtrsxqZQ== +megajs@^1.3.7: + version "1.3.7" + resolved "https://registry.yarnpkg.com/megajs/-/megajs-1.3.7.tgz#cc8f1ff10c0386bb5a4e01340becbd0e2f93e25d" + integrity sha512-DqEkY8UaFGAcsyh0oxGe+llQuiPIJFdrt1iaxVvq/2HjozNJeF13FXEcq6/7aJlfs8IUYrHcv8I8G6Q40jD2Ug== dependencies: - abort-controller "^3.0.0" pumpify "^2.0.1" stream-skip "^1.0.3"