diff --git a/package.json b/package.json index 4df61287..e04056df 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "koodo-reader", "main": "main.js", - "version": "1.9.7", + "version": "1.9.8", "description": "Koodo Reader is a cross-platform ebook reader", "author": { "name": "App by Troye", diff --git a/src/assets/lib/kookit-extra-browser.min.js b/src/assets/lib/kookit-extra-browser.min.js index 26b39b28..2c4f0294 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 n,AuthType as i}from"webdav/dist/web/index.js";import{isElectron as o}from"react-device-detect";function s(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(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((n=n.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"],u=e=>{const t=atob(e),r=t.length,n=new Uint8Array(r);for(let e=0;e{let t="";const r=new Uint8Array(e),n=r.byteLength;for(let e=0;ee>>>t|e<<32-t,n=(e,t,r)=>e&t^~e&r,i=(e,t,r)=>e&t^e&r^t&r,o=e=>r(e,2)^r(e,13)^r(e,22),s=e=>r(e,6)^r(e,11)^r(e,25),a=e=>r(e,7)^r(e,18)^e>>>3,c=e=>r(e,17)^r(e,19)^e>>>10,u=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],d=8*e.length,l=(960-(8*e.length+1)%512)%512,h=e.length+Math.ceil((l+1)/8)+8,f=new Uint8Array(h);f.set(e),f[e.length]=128;new DataView(f.buffer,f.byteLength-8).setBigUint64(0,BigInt(d),!1);for(let e=0;e>>0;let[l,h,p,g,m,y,v,b]=u;for(let e=0;e<64;e++){const r=b+s(m)+n(m,y,v)+t[e]+d[e]>>>0,a=o(l)+i(l,h,p)>>>0;b=v,v=y,y=m,m=g+r>>>0,g=p,p=h,h=l,l=r+a>>>0}u[0]=u[0]+l>>>0,u[1]=u[1]+h>>>0,u[2]=u[2]+p>>>0,u[3]=u[3]+g>>>0,u[4]=u[4]+m>>>0,u[5]=u[5]+y>>>0,u[6]=u[6]+v>>>0,u[7]=u[7]+b>>>0}const p=new ArrayBuffer(32),g=new DataView(p);return u.forEach(((e,t)=>{g.setUint32(4*t,e,!1)})),p}class h{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 n=()=>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"application/json"===e?"json":e.startsWith("image/")?e.split("/")[1]:"application/zip"===e?"zip":"application/epub+zip"===e?"epub":"text/plain"===e?"txt":"application/pdf"===e?"pdf":"application/x-mobipocket-ebook"===e?"mobi":"application/vnd.amazon.ebook"===e?"azw3":"application/x-cbz"===e?"cbz":"application/x-cbr"===e?"cbr":"application/x-cbt"===e?"cbt":"application/x-cb7"===e?"cb7":"application/x-fictionbook+xml"===e?"fb2":"text/html"===e?"html":"text/css"===e?"css":"application/javascript"===e?"js":"application/xml"===e?"xml":"application/xhtml+xml"===e?"xhtml":"application/oebps-package+xml"===e?"opf":"application/x-dtbncx+xml"===e?"ncx":"audio/mpeg"===e?"mp3":"audio/wav"===e?"wav":"audio/ogg"===e?"ogg":"video/mp4"===e?"mp4":"video/webm"===e?"webm":"video/x-msvideo"===e?"avi":"video/x-ms-wmv"===e?"wmv":"video/x-flv"===e?"flv":"application/x-mpegURL"===e?"m3u8":"video/MP2T"===e?"ts":"video/3gpp"===e?"3gp":"video/3gpp2"===e?"3g2":"application/x-sqlite3"===e?"db":"",databaseList:c,configList:["themeColors","readingTime","cloudSyncTime","recentBooks","recentAdd","deletedBooks","favoriteBooks","shelfList","txtParsers","noteTags","recordLocation","sortedShelfList","kindleDeviceList"],copyArrayBuffer:e=>{var t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e)),t},base64ToArrayBuffer:u,arrayBufferToBase64:d,generateSHA256Hash:function(e){return s(this,void 0,void 0,(function*(){const t=(new TextEncoder).encode(e),r="undefined"!=typeof crypto&&crypto.subtle?yield crypto.subtle.digest("SHA-256",t):l(t),n=Array.from(new Uint8Array(r)).map((e=>e.toString(16).padStart(2,"0"))).join("");return n}))},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 p={publicUrl:"https://api.960960.xyz",cloudUrl:"https://cloud.960960.xyz",devUrl:"http://192.168.28.159:8000"},g={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 m={CloudConfig:p,ThirdpartyConfig:g,LoginAuthRequest:{google:{clientId:g.googleClientId,scopes:["openid"],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{prompt:"consent",scope:"openid"}},microsoft:{clientId:g.microsoftClientId,scopes:["openid","profile","User.Read","offline_access"],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{scope:"openid profile User.Read offline_access"}},facebook:{clientId:g.facebookClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{scope:""}},github:{clientId:g.githubClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{scope:""}},email:{clientId:"",scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.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:g.dropboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{token_access_type:"offline"}},boxnet:{clientId:g.boxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}},pcloud:{clientId:g.pcloudClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{grant_type:"authorization_code"}},adrive:{clientId:g.adriveClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}},microsoft:{clientId:g.microsoftClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{scope:"files.readwrite.appfolder offline_access"}},google:{clientId:g.googleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.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 y{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new h(1),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=5){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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(),n=yield this.getDriveId();try{try{const i=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:n,file_path:t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(i.data)return i.data.file_id}catch(i){const o=t.split("/").filter((e=>e));let s="",a="root";for(const t of o){s+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:n,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:n,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(),n=yield this.getDriveId(),i=yield this.getFolderIdByPath(this.baseFolder+"/"+t);let o=[],s="",a=!0;for(;a;){const t=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:n,parent_file_id:i,marker:s||void 0},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),c=t.data.items||[];o=o.concat(c),s=t.data.next_marker,a=!!s&&100===c.length}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(),n=yield this.getDriveId(),i=yield this.getFolderIdByPath(this.baseFolder+"/"+t);return!i||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:n,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 n=yield this.refreshToken(),i=yield this.getDriveId(),o=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:t},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}});(null===(r=o.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:o.data.file_id},{headers:{Authorization:`Bearer ${n}`,"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:g.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:g.adriveClientId,redirect_uri:g.callbackUrl,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class v extends y{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return new Promise(((n,i)=>s(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken(),o=yield this.getDriveId(),s=r.substring(0,r.lastIndexOf("/")),a=r.substring(r.lastIndexOf("/")+1),c=yield this.getFolderIdByPath(this.baseFolder+"/"+s),u=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:o,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:l,part_info_list:h}=u.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:o,file_id:d,upload_id:l},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),n(!0)}catch(e){console.error("Error uploading file:",e),n(!1)}}))))}))}downloadFile(t){return new Promise(((r,n)=>s(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),i=yield this.getDriveId(),o=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:this.baseFolder+"/"+t},{headers:{Authorization:`Bearer ${n}`,"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:o},{headers:{Authorization:`Bearer ${n}`,"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 b{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new h(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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*(){if(""==t)return"0";const r=yield this.refreshToken(),n=t.split("/");let i="0";for(const t of n){const n=`https://api.box.com/2.0/folders/${i}/items?fields=id,name&type=folder&limit=1000`;try{const o=(yield e.get(n,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(o)i=o.id;else{const n={name:t,parent:{id:i},type:"folder"};i=(yield e.post("https://api.box.com/2.0/folders",n,{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 n=this.baseFolder+"/"+t;for(;n.startsWith("/");)n=n.substring(1);let i=yield this.getFolderIdByPath(n),o=[],s=0,a=!0;const c=1e3;for(;a;){const t=yield e.get(`https://api.box.com/2.0/folders/${i}/items`,{params:{limit:c,offset:s},headers:{Authorization:`Bearer ${r}`}}),n=t.data.entries||[];o=o.concat(n),s+=n.length,a=n.length===c&&t.data.total_count>s}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(),n=t.substring(0,t.lastIndexOf("/")),i=t.substring(t.lastIndexOf("/")+1);let o=this.baseFolder+"/"+n;for(;o.startsWith("/");)o=o.substring(1);const s=yield this.getFolderIdByPath(o);if(!s)return!0;const a=`https://api.box.com/2.0/folders/${s}/items?fields=id,name&type=file&limit=1000`,c=(yield e.get(a,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));return!c||(yield e.delete(`https://api.box.com/2.0/files/${c.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:g.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:g.boxClientId,redirect_uri:g.callbackUrl,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}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 n=yield this.refreshToken(),i=r.substring(0,r.lastIndexOf("/")),o=r.substring(r.lastIndexOf("/")+1);let s=this.baseFolder+"/"+i;for(;s.startsWith("/");)s=s.substring(1);const a=yield this.getFolderIdByPath(s);if(!a)throw new Error("Folder not found");const c=(yield this.listFiles(i)).find((e=>e===o));c&&(yield this.deleteFileWithoutQueue(i+"/"+o));let u=new File([t],o,{lastModified:(new Date).getTime(),type:t.type});const d=new FormData;d.append("file",u),d.append("parent_id",a);const l=yield e.post("https://upload.box.com/api/2.0/files/content",d,{headers:{Authorization:`Bearer ${n}`,"Content-Type":"multipart/form-data"},params:{if_match:"false",fields:"name,id"},maxContentLength:1/0,maxBodyLength:1/0});return!(l.status>=300)||(console.error("Error occurred during file upload:",l),!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(),n=t.substring(0,t.lastIndexOf("/")),i=t.substring(t.lastIndexOf("/")+1);let o=this.baseFolder+"/"+n;for(;o.startsWith("/");)o=o.substring(1);const s=yield this.getFolderIdByPath(o);if(!s)return console.error("Folder not found"),!0;const a=`https://api.box.com/2.0/folders/${s}/items?fields=id,name&type=file&limit=1000`,c=(yield e.get(a,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));if(!c)return console.error("File not found:",i),!0;const u=yield e({url:`https://api.box.com/2.0/files/${c.id}/content`,method:"get",headers:{Authorization:`Bearer ${r}`},responseType:"arraybuffer"});return u.status>=300?(console.error("Error occurred during file download:",u),!1):u.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class k{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new h(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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 n=[],i=!0,o=null;for(;i;){let s;s=o?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:o},{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||[];n=n.concat(a),i=s.data.has_more,o=s.data.cursor}return[...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();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:g.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${g.dropboxClientId}&redirect_uri=${g.callbackUrl}`}}class S extends k{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 n=yield this.refreshToken();let i=r.split("/").pop()||"",o=new File([t],i,{lastModified:(new Date).getTime(),type:t.type});const s=yield e.post("https://content.dropboxapi.com/2/files/upload",o,{headers:{Authorization:`Bearer ${n}`,"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(),n=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 n.status>=300?(console.error("Error occurred during file download:",n),!1):n.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class E{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new h(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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 n=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 "+n}});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(),n=yield this.getFolderId(t);if(n)return n;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(),n=`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(n,{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 n=yield this.checkFolder(t),i=[],o="",s=!0;for(;s;){let t=`https://www.googleapis.com/drive/v3/files?q='${n}'+in+parents&spaces=appDataFolder&fields=nextPageToken,files(id,name)&pageSize=1000`;o&&(t+=`&pageToken=${o}`);const a=yield e.get(t,{headers:{Authorization:`Bearer ${r}`}}),c=a.data.files||[];i=i.concat(c),o=a.data.nextPageToken,s=!!o}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],n=t.split("/")[0],i=yield this.getFolderId(n),o=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 ${o}`}});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:g.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${g.callbackUrl}&prompt=consent&response_type=code&client_id=${g.googleClientId}&scope=https://www.googleapis.com/auth/drive.appdata&access_type=offline`}}class x extends E{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 n=yield this.refreshToken();let i=r.split("/").pop()||"",o=new File([t],i,{lastModified:(new Date).getTime(),type:t.type}),s=r.split(".").pop(),c=a(s||""),u=r.split("/")[0],d=yield this.checkFolder(u),l=yield this.getFileId(i||"",d);const h={mimeType:c,name:i,parents:[d]},f=l?`https://www.googleapis.com/upload/drive/v3/files/${l}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",p=(yield e({method:l?"PATCH":"POST",url:f,data:l?null:JSON.stringify(h),headers:{Authorization:"Bearer "+n,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location,g=yield this.getData(o);if(0===Object.keys(g).length)return!1;const m=yield e.put(p,g.data,{headers:{Authorization:"Bearer "+n,"Content-Type":"application/zip","Content-Range":`bytes 0-${g.fileSize-1}/${g.fileSize}`},maxContentLength:1/0,maxBodyLength:1/0});return!(m.status>=300)||(console.error("Error occurred during file download:",m),!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 n=t.split("/").pop(),i=t.split("/")[0],o=yield this.checkFolder(i),s=yield this.getFileId(n||"",o);if(!s)return console.error("File not found:",n),!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 n=new FileReader;n.onload=r=>t({fileName:e.name,mimeType:e.type,fileSize:e.size,data:r.target.result}),n.onerror=e=>r(e),n.readAsArrayBuffer(e)})):{}}))}}class A{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new h(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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;if(""===this.baseFolder)return this.root=e,this.root;let t=e.children.find((e=>e.name===this.baseFolder&&e.directory));return t||(t=yield e.mkdir(this.baseFolder)),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 n=(()=>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,n),yield n}))}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}}const r=t.children.map((e=>e.name));return r}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("/"),n=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===n&&!e.directory));return!i||(yield i.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class T extends A{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 n=yield this.getRoot();const i=t.split("/"),o=i.pop()||"";for(const e of i){if(!e)continue;let t=n.children.find((t=>t.name===e&&t.directory));t||(t=yield this.createFolder(n,e)),n=t}const s=new File([e],o,{lastModified:(new Date).getTime(),type:e.type}),a=yield e.arrayBuffer(),c=new Uint8Array(a),u=r.from(c),d=n.children.find((e=>e.name===o&&!e.directory));return d&&(yield d.delete()),yield n.upload({name:o,size:s.size},u).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("/"),n=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===n&&!e.directory));if(!i)return!0;return(yield i.downloadBuffer()).buffer}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 h(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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 n=[],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 o=t.data.value||[];n=n.concat(o),i=t.data["@odata.nextLink"]||""}return[...new Set(n.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(),n=yield e.delete(`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!(n.status>=300)||(console.error("Error deleting file:",n),!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:g.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${g.microsoftClientId}&scope=files.readwrite.appfolder offline_access&response_type=code&redirect_uri=${g.callbackUrl}`}}class R 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 n=yield this.refreshToken();let i=r.split("/").pop()||"",o=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 "+n,"Content-Type":"application/json"},maxContentLength:1/0,maxBodyLength:1/0});let c=o.size;const u=o.type,d=a.data.uploadUrl,l=yield e.put(d,o,{headers:{"Content-Type":u,"Content-Range":`bytes 0-${c-1}/${c}`},maxContentLength:1/0,maxBodyLength:1/0});return!(l.status>=300)||(console.error("Error occurred during file download:",l),!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(),n=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/content`,i=yield e.get(n,{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 O{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 P{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new h(3)}retryOperation(e,t=5){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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(),n=yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:"/"+t,recursive:0}});return 0!==n.data.result?[]:n.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(),n=yield e.get("https://api.pcloud.com/deletefile",{params:{access_token:r,path:"/"+t}});return 0===n.data.result||(console.error("Error deleting file:",n.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:g.callbackUrl,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${g.pcloudClientId}&response_type=code&redirect_uri=${g.callbackUrl}`}}class _ extends P{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 n=yield this.refreshToken(),i=r.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(i,n))){if(!(yield this.createFolder(i,n)))return!1}let o=r.split("/").pop()||"",s=new File([t],o,{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:n,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(),n=yield e.get("https://api.pcloud.com/getfilelink",{params:{access_token:r,path:`/${t}`}});if(0!==n.data.result)return console.error("Error getting file link:",n.data),!0;const i=`https://${n.data.hosts[0]}${n.data.path}`,o=yield e.get(i,{responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0});return o.status>=300?(console.error("Error downloading file:",o),!1):o.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}const M=e=>{let t=e.httpHandler;return{setHttpHandler(e){t=e},httpHandler:()=>t,updateHttpClientConfig(e,r){t.updateHttpClientConfig(e,r)},httpHandlerConfigs:()=>t.httpHandlerConfigs()}};var I,N,F,$,U;!function(e){e.HEADER="header",e.QUERY="query"}(I||(I={})),function(e){e.HEADER="header",e.QUERY="query"}(N||(N={})),function(e){e.HTTP="http",e.HTTPS="https"}(F||(F={})),function(e){e.MD5="md5",e.CRC32="crc32",e.CRC32C="crc32c",e.SHA1="sha1",e.SHA256="sha256"}($||($={})),function(e){e[e.HEADER=0]="HEADER",e[e.TRAILER=1]="TRAILER"}(U||(U={}));const L="__smithy_context";var B,D;!function(e){e.PROFILE="profile",e.SSO_SESSION="sso-session",e.SERVICES="services"}(B||(B={})),function(e){e.HTTP_0_9="http/0.9",e.HTTP_1_0="http/1.0",e.TDS_8_0="tds/8.0"}(D||(D={}));class j{constructor(e){this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?":"!==e.protocol.slice(-1)?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?"/"!==e.path.charAt(0)?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){const t=new j({...e,headers:{...e.headers}});var r;return t.query&&(t.query=(r=t.query,Object.keys(r).reduce(((e,t)=>{const n=r[t];return{...e,[t]:Array.isArray(n)?[...n]:n}}),{}))),t}static isInstance(e){if(!e)return!1;const t=e;return"method"in t&&"protocol"in t&&"hostname"in t&&"path"in t&&"object"==typeof t.query&&"object"==typeof t.headers}clone(){return j.clone(this)}}class z{constructor(e){this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){if(!e)return!1;const t=e;return"number"==typeof t.statusCode&&"object"==typeof t.headers}}const q={step:"build",tags:["SET_EXPECT_HEADER","EXPECT_HEADER"],name:"addExpectContinueMiddleware",override:!0},H=e=>({applyToStack:t=>{t.add(function(e){return t=>async r=>{const{request:n}=r;return j.isInstance(n)&&n.body&&"node"===e.runtime&&"FetchHttpHandler"!==e.requestHandler?.constructor?.name&&(n.headers={...n.headers,Expect:"100-continue"}),t({...r,request:n})}}(e),q)}}),W="WHEN_SUPPORTED",K=W,V=W;var G,Q;!function(e){e.MD5="MD5",e.CRC32="CRC32",e.CRC32C="CRC32C",e.SHA1="SHA1",e.SHA256="SHA256"}(G||(G={})),function(e){e.HEADER="header",e.TRAILER="trailer"}(Q||(Q={}));const J=G.MD5,X=G.CRC32;var Z;function Y(e,t,r){e.__aws_sdk_context?e.__aws_sdk_context.features||(e.__aws_sdk_context.features={}):e.__aws_sdk_context={features:{}},e.__aws_sdk_context.features[t]=r}!function(e){e.ENV="env",e.CONFIG="shared config entry"}(Z||(Z={}));const ee=e=>z.isInstance(e)?e.headers?.date??e.headers?.Date:void 0,te=e=>new Date(Date.now()+e),re=(e,t)=>{const r=Date.parse(e);return((e,t)=>Math.abs(te(t).getTime()-e)>=3e5)(r,t)?r-Date.now():t},ne=(e,t)=>{if(!t)throw new Error(`Property \`${e}\` is not resolved for AWS SDK SigV4Auth`);return t},ie=async e=>{const t=ne("context",e.context),r=ne("config",e.config),n=t.endpointV2?.properties?.authSchemes?.[0],i=ne("signer",r.signer),o=await i(n),s=e?.signingRegion,a=e?.signingRegionSet,c=e?.signingName;return{config:r,signer:o,signingRegion:s,signingRegionSet:a,signingName:c}};class oe{async sign(e,t,r){if(!j.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const n=await ie(r),{config:i,signer:o}=n;let{signingRegion:s,signingName:a}=n;const c=r.context;if(c?.authSchemes?.length){const[e,t]=c.authSchemes;"sigv4a"===e?.name&&"sigv4"===t?.name&&(s=t?.signingRegion??s,a=t?.signingName??a)}return await o.sign(e,{signingDate:te(i.systemClockOffset),signingRegion:s,signingService:a})}errorHandler(e){return t=>{const r=t.ServerTime??ee(t.$response);if(r){const n=ne("config",e.config),i=n.systemClockOffset;n.systemClockOffset=re(r,n.systemClockOffset);n.systemClockOffset!==i&&t.$metadata&&(t.$metadata.clockSkewCorrected=!0)}throw t}}successHandler(e,t){const r=ee(e);if(r){const e=ne("config",t.config);e.systemClockOffset=re(r,e.systemClockOffset)}}}class se extends oe{async sign(e,t,r){if(!j.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const{config:n,signer:i,signingRegion:o,signingRegionSet:s,signingName:a}=await ie(r),c=(await(n.sigv4aSigningRegionSet?.())??s??[o]).join(",");return await i.sign(e,{signingDate:te(n.systemClockOffset),signingRegion:c,signingService:a})}}const ae=e=>e[L]||(e[L]={}),ce=e=>{if("function"==typeof e)return e;const t=Promise.resolve(e);return()=>t};const ue=(e,t)=>(r,n)=>async i=>{const o=e.httpAuthSchemeProvider(await t.httpAuthSchemeParametersProvider(e,n,i.input)),s=function(e){const t=new Map;for(const r of e)t.set(r.schemeId,r);return t}(e.httpAuthSchemes),a=ae(n),c=[];for(const r of o){const i=s.get(r.schemeId);if(!i){c.push(`HttpAuthScheme \`${r.schemeId}\` was not enabled for this service.`);continue}const o=i.identityProvider(await t.identityProviderConfigProvider(e));if(!o){c.push(`HttpAuthScheme \`${r.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties:u={},signingProperties:d={}}=r.propertiesExtractor?.(e,n)||{};r.identityProperties=Object.assign(r.identityProperties||{},u),r.signingProperties=Object.assign(r.signingProperties||{},d),a.selectedHttpAuthScheme={httpAuthOption:r,identity:await o(r.identityProperties),signer:i.signer};break}if(!a.selectedHttpAuthScheme)throw new Error(c.join("\n"));return r(i)},de={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},le={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},he={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function fe(e,t,r){return{applyToStack:n=>{n.add(((e,t)=>r=>async n=>{const{response:i}=await r(n);try{return{response:i,output:await t(i,e)}}catch(e){if(Object.defineProperty(e,"$response",{value:i}),!("$metadata"in e)){const t="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";e.message+="\n "+t,void 0!==e.$responseBodyText&&e.$response&&(e.$response.body=e.$responseBodyText)}throw e}})(e,r),le),n.add(((e,t)=>(r,n)=>async i=>{const o=n.endpointV2?.url&&e.urlParser?async()=>e.urlParser(n.endpointV2.url):e.endpoint;if(!o)throw new Error("No valid endpoint provider available.");const s=await t(i.input,{...e,endpoint:o});return r({...i,request:s})})(e,t),he)}}}const pe=e=>e=>{throw e},ge=(e,t)=>{},me={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},ye=e=>({applyToStack:e=>{e.addRelativeTo(((e,t)=>async r=>{if(!j.isInstance(r.request))return e(r);const n=ae(t).selectedHttpAuthScheme;if(!n)throw new Error("No HttpAuthScheme was selected: unable to sign request");const{httpAuthOption:{signingProperties:i={}},identity:o,signer:s}=n,a=await e({...r,request:await s.sign(r.request,o,i)}).catch((s.errorHandler||pe)(i));return(s.successHandler||ge)(a.response,i),a}),me)}}),ve=e=>{if("function"==typeof e)return e;const t=Promise.resolve(e);return()=>t},be={},we=new Array(64);for(let e=0,t="A".charCodeAt(0),r="Z".charCodeAt(0);e+t<=r;e++){const r=String.fromCharCode(e+t);be[r]=e,we[e]=r}for(let e=0,t="a".charCodeAt(0),r="z".charCodeAt(0);e+t<=r;e++){const r=String.fromCharCode(e+t),n=e+26;be[r]=n,we[n]=r}for(let e=0;e<10;e++){be[e.toString(10)]=e+52;const t=e.toString(10),r=e+52;be[t]=r,we[r]=t}be["+"]=62,we[62]="+",be["/"]=63,we[63]="/";const ke=e=>{let t=e.length/4*3;"=="===e.slice(-2)?t-=2:"="===e.slice(-1)&&t--;const r=new ArrayBuffer(t),n=new DataView(r);for(let t=0;t>=6;const o=t/4*3;r>>=i%8;const s=Math.floor(i/8);for(let e=0;e>t)}}return new Uint8Array(r)},Se=e=>(new TextEncoder).encode(e),Ee=e=>"string"==typeof e?Se(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e),xe=e=>{if("string"==typeof e)return e;if("object"!=typeof e||"number"!=typeof e.byteOffset||"number"!=typeof e.byteLength)throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(e)};function Ae(e){let t;t="string"==typeof e?Se(e):e;const r="object"==typeof t&&"number"==typeof t.length,n="object"==typeof t&&"number"==typeof t.byteOffset&&"number"==typeof t.byteLength;if(!r&&!n)throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let i="";for(let e=0;e>t]}i+="==".slice(0,4-o)}return i}class Te extends Uint8Array{static fromString(e,t="utf-8"){if("string"==typeof e)return function(e,t){return"base64"===t?Te.mutate(ke(e)):Te.mutate(Se(e))}(e,t);throw new Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,Te.prototype),e}transformToString(e="utf-8"){return function(e,t="utf-8"){return"base64"===t?Ae(e):xe(e)}(this,e)}}const Ce=(e,t)=>{const{base64Encoder:r,bodyLengthChecker:n,checksumAlgorithmFn:i,checksumLocationName:o,streamHasher:s}=t,a=void 0!==r&&void 0!==n&&void 0!==i&&void 0!==o&&void 0!==s,c=a?s(i,e):void 0,u=e.getReader();return new ReadableStream({async pull(e){const{value:t,done:i}=await u.read();if(i){if(e.enqueue("0\r\n"),a){const t=r(await c);e.enqueue(`${o}:${t}\r\n`),e.enqueue("\r\n")}e.close()}else e.enqueue(`${(n(t)||0).toString(16)}\r\n${t}\r\n`)}})},Re=e=>encodeURIComponent(e).replace(/[!'()*]/g,Oe),Oe=e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`;function Pe(e,t){return new Request(e,t)}function _e(e=0){return new Promise(((t,r)=>{e&&setTimeout((()=>{const t=new Error(`Request did not complete within ${e} ms`);t.name="TimeoutError",r(t)}),e)}))}const Me={supported:void 0};class Ie{static create(e){return"function"==typeof e?.handle?e:new Ie(e)}constructor(e){"function"==typeof e?this.configProvider=e().then((e=>e||{})):(this.config=e??{},this.configProvider=Promise.resolve(this.config)),void 0===Me.supported&&(Me.supported=Boolean("undefined"!=typeof Request&&"keepalive"in Pe("https://[::1]")))}destroy(){}async handle(e,{abortSignal:t}={}){this.config||(this.config=await this.configProvider);const r=this.config.requestTimeout,n=!0===this.config.keepAlive,i=this.config.credentials;if(t?.aborted){const e=new Error("Request aborted");return e.name="AbortError",Promise.reject(e)}let o=e.path;const s=function(e){const t=[];for(let r of Object.keys(e).sort()){const n=e[r];if(r=Re(r),Array.isArray(n))for(let e=0,i=n.length;e{};const p=Pe(d,h),g=[fetch(p).then((e=>{const t=e.headers,r={};for(const e of t.entries())r[e[0]]=e[1];return null!=e.body?{response:new z({headers:r,reason:e.statusText,statusCode:e.status,body:e.body})}:e.blob().then((t=>({response:new z({headers:r,reason:e.statusText,statusCode:e.status,body:t})})))})),_e(r)];return t&&g.push(new Promise(((e,r)=>{const n=()=>{const e=new Error("Request aborted");e.name="AbortError",r(e)};if("function"==typeof t.addEventListener){const e=t;e.addEventListener("abort",n,{once:!0}),f=()=>e.removeEventListener("abort",n)}else t.onabort=n}))),Promise.race(g).finally(f)}updateHttpClientConfig(e,t){this.config=void 0,this.configProvider=this.configProvider.then((r=>(r[e]=t,r)))}httpHandlerConfigs(){return this.config??{}}}const Ne=async e=>"function"==typeof Blob&&e instanceof Blob||"Blob"===e.constructor?.name?new Uint8Array(await e.arrayBuffer()):async function(e){const t=[],r=e.getReader();let n=!1,i=0;for(;!n;){const{done:e,value:o}=await r.read();o&&(t.push(o),i+=o.length),n=e}const o=new Uint8Array(i);let s=0;for(const e of t)o.set(e,s),s+=e.length;return o}(e);const Fe={},$e={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();1===t.length&&(t=`0${t}`),Fe[e]=t,$e[t]=e}function Ue(e){if(e.length%2!=0)throw new Error("Hex encoded strings must have an even number length");const t=new Uint8Array(e.length/2);for(let r=0;r"function"==typeof ReadableStream&&(e?.constructor?.name===ReadableStream.name||e instanceof ReadableStream),De="The stream has already been transformed.",je=e=>{if(!ze(e)&&!Be(e)){throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${e?.__proto__?.constructor?.name||e}`)}let t=!1;const r=async()=>{if(t)throw new Error(De);return t=!0,await Ne(e)};return Object.assign(e,{transformToByteArray:r,transformToString:async e=>{const t=await r();if("base64"===e)return Ae(t);if("hex"===e)return Le(t);if(void 0===e||"utf8"===e||"utf-8"===e)return xe(t);if("function"==typeof TextDecoder)return new TextDecoder(e).decode(t);throw new Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(t)throw new Error(De);if(t=!0,ze(e))return(e=>{if("function"!=typeof e.stream)throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body");return e.stream()})(e);if(Be(e))return e;throw new Error(`Cannot transform payload to web stream, got ${e}`)}})},ze=e=>"function"==typeof Blob&&e instanceof Blob;const qe="function"==typeof ReadableStream?ReadableStream:function(){};class He extends qe{}const We=({expectedChecksum:e,checksum:t,source:r,checksumSourceLocation:n,base64Encoder:i})=>{if(!Be(r))throw new Error(`@smithy/util-stream: unsupported source type ${r?.constructor?.name??r} in ChecksumStream.`);const o=i??Ae;if("function"!=typeof TransformStream)throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");const s=new TransformStream({start(){},async transform(e,r){t.update(e),r.enqueue(e)},async flush(r){const i=await t.digest(),s=o(i);if(e!==s){const t=new Error(`Checksum mismatch: expected "${e}" but received "${s}" in response header "${n}".`);r.error(t)}else r.terminate()}});r.pipeThrough(s);const a=s.readable;return Object.setPrototypeOf(a,He.prototype),a},Ke=async(e=new Uint8Array,t)=>{if(e instanceof Uint8Array)return Te.mutate(e);if(!e)return Te.mutate(new Uint8Array);const r=t.streamCollector(e);return Te.mutate(await r)};function Ve(e){return encodeURIComponent(e).replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function Ge(e,t){return new Qe(e,t)}class Qe{constructor(e,t){this.input=e,this.context=t,this.query={},this.method="",this.headers={},this.path="",this.body=null,this.hostname="",this.resolvePathStack=[]}async build(){const{hostname:e,protocol:t="https",port:r,path:n}=await this.context.endpoint();this.path=n;for(const e of this.resolvePathStack)e(this.path);return new j({protocol:t,hostname:this.hostname||e,port:r,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(e){return this.hostname=e,this}bp(e){return this.resolvePathStack.push((t=>{this.path=`${t?.endsWith("/")?t.slice(0,-1):t||""}`+e})),this}p(e,t,r,n){return this.resolvePathStack.push((i=>{this.path=((e,t,r,n,i,o)=>{if(null==t||void 0===t[r])throw new Error("No value provided for input HTTP label: "+r+".");{const t=n();if(t.length<=0)throw new Error("Empty value provided for input HTTP label: "+r+".");e=e.replace(i,o?t.split("/").map((e=>Ve(e))).join("/"):Ve(t))}return e})(i,this.input,e,t,r,n)})),this}h(e){return this.headers=e,this}q(e){return this.query=e,this}b(e){return this.body=e,this}m(e){return this.method=e,this}}class Je{constructor(e){this.authSchemes=new Map;for(const[t,r]of Object.entries(e))void 0!==r&&this.authSchemes.set(t,r)}getIdentityProvider(e){return this.authSchemes.get(e)}}const Xe=(Ze=3e5,e=>Ye(e)&&e.expiration.getTime()-Date.now()void 0!==e.expiration,et="X-Amz-Date",tt="X-Amz-Signature",rt="X-Amz-Security-Token",nt="authorization",it=et.toLowerCase(),ot=[nt,it,"date"],st=tt.toLowerCase(),at="x-amz-content-sha256",ct=rt.toLowerCase(),ut={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},dt=/^proxy-/,lt=/^sec-/,ht="AWS4-HMAC-SHA256",ft="AWS4-HMAC-SHA256-PAYLOAD",pt="aws4_request",gt={},mt=[],yt=(e,t,r)=>`${e}/${t}/${r}/${pt}`,vt=(e,t,r)=>{const n=new e(t);return n.update(Ee(r)),n.digest()},bt=({headers:e},t,r)=>{const n={};for(const i of Object.keys(e).sort()){if(null==e[i])continue;const o=i.toLowerCase();(o in ut||t?.has(o)||dt.test(o)||lt.test(o))&&(!r||r&&!r.has(o))||(n[o]=e[i].trim().replace(/\s+/g," "))}return n},wt=e=>"function"==typeof ArrayBuffer&&e instanceof ArrayBuffer||"[object ArrayBuffer]"===Object.prototype.toString.call(e),kt=async({headers:e,body:t},r)=>{for(const t of Object.keys(e))if(t.toLowerCase()===at)return e[t];if(null==t)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if("string"==typeof t||ArrayBuffer.isView(t)||wt(t)){const e=new r;return e.update(Ee(t)),Le(await e.digest())}return"UNSIGNED-PAYLOAD"};class St{format(e){const t=[];for(const r of Object.keys(e)){const n=Se(r);t.push(Uint8Array.from([n.byteLength]),n,this.formatHeaderValue(e[r]))}const r=new Uint8Array(t.reduce(((e,t)=>e+t.byteLength),0));let n=0;for(const e of t)r.set(e,n),n+=e.byteLength;return r}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":const t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":const r=new DataView(new ArrayBuffer(5));return r.setUint8(0,4),r.setInt32(1,e.value,!1),new Uint8Array(r.buffer);case"long":const n=new Uint8Array(9);return n[0]=5,n.set(e.value.bytes,1),n;case"binary":const i=new DataView(new ArrayBuffer(3+e.value.byteLength));i.setUint8(0,6),i.setUint16(1,e.value.byteLength,!1);const o=new Uint8Array(i.buffer);return o.set(e.value,3),o;case"string":const s=Se(e.value),a=new DataView(new ArrayBuffer(3+s.byteLength));a.setUint8(0,7),a.setUint16(1,s.byteLength,!1);const c=new Uint8Array(a.buffer);return c.set(s,3),c;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(At.fromNumber(e.value.valueOf()).bytes,1),u;case"uuid":if(!xt.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(Ue(e.value.replace(/\-/g,"")),1),d}}}var Et;!function(e){e[e.boolTrue=0]="boolTrue",e[e.boolFalse=1]="boolFalse",e[e.byte=2]="byte",e[e.short=3]="short",e[e.integer=4]="integer",e[e.long=5]="long",e[e.byteArray=6]="byteArray",e[e.string=7]="string",e[e.timestamp=8]="timestamp",e[e.uuid=9]="uuid"}(Et||(Et={}));const xt=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class At{constructor(e){if(this.bytes=e,8!==e.byteLength)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>0x8000000000000000||e<-0x8000000000000000)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);const t=new Uint8Array(8);for(let r=7,n=Math.abs(Math.round(e));r>-1&&n>0;r--,n/=256)t[r]=n;return e<0&&Tt(t),new At(t)}valueOf(){const e=this.bytes.slice(0),t=128&e[0];return t&&Tt(e),parseInt(Le(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function Tt(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,0===e[t]);t--);}const Ct=e=>{e=j.clone(e);for(const t of Object.keys(e.headers))ot.indexOf(t.toLowerCase())>-1&&delete e.headers[t];return e},Rt=e=>"number"==typeof e?new Date(1e3*e):"string"==typeof e?Number(e)?new Date(1e3*Number(e)):new Date(e):e;class Ot{constructor({applyChecksum:e,credentials:t,region:r,service:n,sha256:i,uriEscapePath:o=!0}){this.headerFormatter=new St,this.service=n,this.sha256=i,this.uriEscapePath=o,this.applyChecksum="boolean"!=typeof e||e,this.regionProvider=ce(r),this.credentialProvider=ce(t)}async presign(e,t={}){const{signingDate:r=new Date,expiresIn:n=3600,unsignableHeaders:i,unhoistableHeaders:o,signableHeaders:s,hoistableHeaders:a,signingRegion:c,signingService:u}=t,d=await this.credentialProvider();this.validateResolvedCredentials(d);const l=c??await this.regionProvider(),{longDate:h,shortDate:f}=Pt(r);if(n>604800)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");const p=yt(f,l,u??this.service),g=((e,t={})=>{const{headers:r,query:n={}}=j.clone(e);for(const e of Object.keys(r)){const i=e.toLowerCase();("x-amz-"===i.slice(0,6)&&!t.unhoistableHeaders?.has(i)||t.hoistableHeaders?.has(i))&&(n[e]=r[e],delete r[e])}return{...e,headers:r,query:n}})(Ct(e),{unhoistableHeaders:o,hoistableHeaders:a});d.sessionToken&&(g.query[rt]=d.sessionToken),g.query["X-Amz-Algorithm"]=ht,g.query["X-Amz-Credential"]=`${d.accessKeyId}/${p}`,g.query[et]=h,g.query["X-Amz-Expires"]=n.toString(10);const m=bt(g,i,s);return g.query["X-Amz-SignedHeaders"]=_t(m),g.query[tt]=await this.getSignature(h,p,this.getSigningKey(d,l,f,u),this.createCanonicalRequest(g,m,await kt(e,this.sha256))),g}async sign(e,t){return"string"==typeof e?this.signString(e,t):e.headers&&e.payload?this.signEvent(e,t):e.message?this.signMessage(e,t):this.signRequest(e,t)}async signEvent({headers:e,payload:t},{signingDate:r=new Date,priorSignature:n,signingRegion:i,signingService:o}){const s=i??await this.regionProvider(),{shortDate:a,longDate:c}=Pt(r),u=yt(a,s,o??this.service),d=await kt({headers:{},body:t},this.sha256),l=new this.sha256;l.update(e);const h=Le(await l.digest()),f=[ft,c,u,n,h,d].join("\n");return this.signString(f,{signingDate:r,signingRegion:s,signingService:o})}async signMessage(e,{signingDate:t=new Date,signingRegion:r,signingService:n}){return this.signEvent({headers:this.headerFormatter.format(e.message.headers),payload:e.message.body},{signingDate:t,signingRegion:r,signingService:n,priorSignature:e.priorSignature}).then((t=>({message:e.message,signature:t})))}async signString(e,{signingDate:t=new Date,signingRegion:r,signingService:n}={}){const i=await this.credentialProvider();this.validateResolvedCredentials(i);const o=r??await this.regionProvider(),{shortDate:s}=Pt(t),a=new this.sha256(await this.getSigningKey(i,o,s,n));return a.update(Ee(e)),Le(await a.digest())}async signRequest(e,{signingDate:t=new Date,signableHeaders:r,unsignableHeaders:n,signingRegion:i,signingService:o}={}){const s=await this.credentialProvider();this.validateResolvedCredentials(s);const a=i??await this.regionProvider(),c=Ct(e),{longDate:u,shortDate:d}=Pt(t),l=yt(d,a,o??this.service);c.headers[it]=u,s.sessionToken&&(c.headers[ct]=s.sessionToken);const h=await kt(c,this.sha256);!((e,t)=>{e=e.toLowerCase();for(const r of Object.keys(t))if(e===r.toLowerCase())return!0;return!1})(at,c.headers)&&this.applyChecksum&&(c.headers[at]=h);const f=bt(c,n,r),p=await this.getSignature(u,l,this.getSigningKey(s,a,d,o),this.createCanonicalRequest(c,f,h));return c.headers[nt]=`${ht} Credential=${s.accessKeyId}/${l}, SignedHeaders=${_t(f)}, Signature=${p}`,c}createCanonicalRequest(e,t,r){const n=Object.keys(t).sort();return`${e.method}\n${this.getCanonicalPath(e)}\n${(({query:e={}})=>{const t=[],r={};for(const n of Object.keys(e)){if(n.toLowerCase()===st)continue;const i=Re(n);t.push(i);const o=e[n];"string"==typeof o?r[i]=`${i}=${Re(o)}`:Array.isArray(o)&&(r[i]=o.slice(0).reduce(((e,t)=>e.concat([`${i}=${Re(t)}`])),[]).sort().join("&"))}return t.sort().map((e=>r[e])).filter((e=>e)).join("&")})(e)}\n${n.map((e=>`${e}:${t[e]}`)).join("\n")}\n\n${n.join(";")}\n${r}`}async createStringToSign(e,t,r){const n=new this.sha256;n.update(Ee(r));const i=await n.digest();return`${ht}\n${e}\n${t}\n${Le(i)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){const t=[];for(const r of e.split("/"))0!==r?.length&&"."!==r&&(".."===r?t.pop():t.push(r));const r=`${e?.startsWith("/")?"/":""}${t.join("/")}${t.length>0&&e?.endsWith("/")?"/":""}`;return Re(r).replace(/%2F/g,"/")}return e}async getSignature(e,t,r,n){const i=await this.createStringToSign(e,t,n),o=new this.sha256(await r);return o.update(Ee(i)),Le(await o.digest())}getSigningKey(e,t,r,n){return(async(e,t,r,n,i)=>{const o=`${r}:${n}:${i}:${Le(await vt(e,t.secretAccessKey,t.accessKeyId))}:${t.sessionToken}`;if(o in gt)return gt[o];for(mt.push(o);mt.length>50;)delete gt[mt.shift()];let s=`AWS4${t.secretAccessKey}`;for(const t of[r,n,i,pt])s=await vt(e,s,t);return gt[o]=s})(this.sha256,e,r,t,n||this.service)}validateResolvedCredentials(e){if("object"!=typeof e||"string"!=typeof e.accessKeyId||"string"!=typeof e.secretAccessKey)throw new Error("Resolved credential object is not valid")}}const Pt=e=>{const t=(r=e,Rt(r).toISOString().replace(/\.\d{3}Z$/,"Z")).replace(/[\-:]/g,"");var r;return{longDate:t,shortDate:t.slice(0,8)}},_t=e=>Object.keys(e).sort().join(";"),Mt=e=>{let t,r=!1;e.credentials&&(r=!0,t=((e,t,r)=>{if(void 0===e)return;const n="function"!=typeof e?async()=>Promise.resolve(e):e;let i,o,s,a=!1;const c=async e=>{o||(o=n(e));try{i=await o,s=!0,a=!1}finally{o=void 0}return i};return void 0===t?async e=>(s&&!e?.forceRefresh||(i=await c(e)),i):async e=>(s&&!e?.forceRefresh||(i=await c(e)),a?i:r(i)?t(i)?(await c(e),i):i:(a=!0,i))})(e.credentials,Xe,Ye)),t||(t=e.credentialDefaultProvider?ve(e.credentialDefaultProvider(Object.assign({},e,{parentClientConfig:e}))):async()=>{throw new Error("`credentials` is missing")});const{signingEscapePath:n=!0,systemClockOffset:i=e.systemClockOffset||0,sha256:o}=e;let s;return s=e.signer?ve(e.signer):e.regionInfoProvider?()=>ve(e.region)().then((async t=>[await e.regionInfoProvider(t,{useFipsEndpoint:await e.useFipsEndpoint(),useDualstackEndpoint:await e.useDualstackEndpoint()})||{},t])).then((([r,i])=>{const{signingRegion:s,signingService:a}=r;e.signingRegion=e.signingRegion||s||i,e.signingName=e.signingName||a||e.serviceId;const c={...e,credentials:t,region:e.signingRegion,service:e.signingName,sha256:o,uriEscapePath:n};return new(e.signerConstructor||Ot)(c)})):async r=>{const i=(r=Object.assign({},{name:"sigv4",signingName:e.signingName||e.defaultSigningName,signingRegion:await ve(e.region)(),properties:{}},r)).signingRegion,s=r.signingName;e.signingRegion=e.signingRegion||i,e.signingName=e.signingName||s||e.serviceId;const a={...e,credentials:t,region:e.signingRegion,service:e.signingName,sha256:o,uriEscapePath:n};return new(e.signerConstructor||Ot)(a)},{...e,systemClockOffset:i,signingEscapePath:n,credentials:r?async()=>t().then((e=>{return r="CREDENTIALS_CODE",n="e",(t=e).$source||(t.$source={}),t.$source[r]=n,t;var t,r,n})):t,signer:s}},It=(e,t)=>{const r=[];if(e&&r.push(e),t)for(const e of t)r.push(e);return r},Nt=(e,t)=>`${e||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`,Ft=()=>{let e=[],t=[],r=!1;const n=new Set,i=r=>(e.forEach((e=>{r.add(e.middleware,{...e})})),t.forEach((e=>{r.addRelativeTo(e.middleware,{...e})})),r.identifyOnResolve?.(a.identifyOnResolve()),r),o=e=>{const t=[];return e.before.forEach((e=>{0===e.before.length&&0===e.after.length?t.push(e):t.push(...o(e))})),t.push(e),e.after.reverse().forEach((e=>{0===e.before.length&&0===e.after.length?t.push(e):t.push(...o(e))})),t},s=(r=!1)=>{const n=[],i=[],s={};e.forEach((e=>{const t={...e,before:[],after:[]};for(const e of It(t.name,t.aliases))s[e]=t;n.push(t)})),t.forEach((e=>{const t={...e,before:[],after:[]};for(const e of It(t.name,t.aliases))s[e]=t;i.push(t)})),i.forEach((e=>{if(e.toMiddleware){const t=s[e.toMiddleware];if(void 0===t){if(r)return;throw new Error(`${e.toMiddleware} is not found when adding ${Nt(e.name,e.aliases)} middleware ${e.relation} ${e.toMiddleware}`)}"after"===e.relation&&t.after.push(e),"before"===e.relation&&t.before.push(e)}}));const a=(c=n,c.sort(((e,t)=>$t[t.step]-$t[e.step]||Ut[t.priority||"normal"]-Ut[e.priority||"normal"]))).map(o).reduce(((e,t)=>(e.push(...t),e)),[]);var c;return a},a={add:(t,r={})=>{const{name:i,override:o,aliases:s}=r,a={step:"initialize",priority:"normal",middleware:t,...r},c=It(i,s);if(c.length>0){if(c.some((e=>n.has(e)))){if(!o)throw new Error(`Duplicate middleware name '${Nt(i,s)}'`);for(const t of c){const r=e.findIndex((e=>e.name===t||e.aliases?.some((e=>e===t))));if(-1===r)continue;const n=e[r];if(n.step!==a.step||a.priority!==n.priority)throw new Error(`"${Nt(n.name,n.aliases)}" middleware with ${n.priority} priority in ${n.step} step cannot be overridden by "${Nt(i,s)}" middleware with ${a.priority} priority in ${a.step} step.`);e.splice(r,1)}}for(const e of c)n.add(e)}e.push(a)},addRelativeTo:(e,r)=>{const{name:i,override:o,aliases:s}=r,a={middleware:e,...r},c=It(i,s);if(c.length>0){if(c.some((e=>n.has(e)))){if(!o)throw new Error(`Duplicate middleware name '${Nt(i,s)}'`);for(const e of c){const r=t.findIndex((t=>t.name===e||t.aliases?.some((t=>t===e))));if(-1===r)continue;const n=t[r];if(n.toMiddleware!==a.toMiddleware||n.relation!==a.relation)throw new Error(`"${Nt(n.name,n.aliases)}" middleware ${n.relation} "${n.toMiddleware}" middleware cannot be overridden by "${Nt(i,s)}" middleware ${a.relation} "${a.toMiddleware}" middleware.`);t.splice(r,1)}}for(const e of c)n.add(e)}t.push(a)},clone:()=>i(Ft()),use:e=>{e.applyToStack(a)},remove:r=>"string"==typeof r?(r=>{let i=!1;const o=e=>{const t=It(e.name,e.aliases);if(t.includes(r)){i=!0;for(const e of t)n.delete(e);return!1}return!0};return e=e.filter(o),t=t.filter(o),i})(r):(r=>{let i=!1;const o=e=>{if(e.middleware===r){i=!0;for(const t of It(e.name,e.aliases))n.delete(t);return!1}return!0};return e=e.filter(o),t=t.filter(o),i})(r),removeByTag:r=>{let i=!1;const o=e=>{const{tags:t,name:o,aliases:s}=e;if(t&&t.includes(r)){const e=It(o,s);for(const t of e)n.delete(t);return i=!0,!1}return!0};return e=e.filter(o),t=t.filter(o),i},concat:e=>{const t=i(Ft());return t.use(e),t.identifyOnResolve(r||t.identifyOnResolve()||(e.identifyOnResolve?.()??!1)),t},applyToStack:i,identify:()=>s(!0).map((e=>{const t=e.step??e.relation+" "+e.toMiddleware;return Nt(e.name,e.aliases)+" - "+t})),identifyOnResolve:e=>("boolean"==typeof e&&(r=e),r),resolve:(e,t)=>{for(const r of s().map((e=>e.middleware)).reverse())e=r(e,t);return r&&console.log(a.identify()),e}};return a},$t={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},Ut={high:3,normal:2,low:1};class Lt{constructor(e){this.config=e,this.middlewareStack=Ft()}send(e,t,r){const n="function"!=typeof t?t:void 0,i="function"==typeof t?t:r;let o;if(void 0===n&&!0===this.config.cacheMiddleware){this.handlers||(this.handlers=new WeakMap);const t=this.handlers;t.has(e.constructor)?o=t.get(e.constructor):(o=e.resolveMiddleware(this.middlewareStack,this.config,n),t.set(e.constructor,o))}else delete this.handlers,o=e.resolveMiddleware(this.middlewareStack,this.config,n);if(!i)return o(e).then((e=>e.output));o(e).then((e=>i(null,e.output)),(e=>i(e))).catch((()=>{}))}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}class Bt{constructor(){this.middlewareStack=Ft()}static classBuilder(){return new Dt}resolveMiddlewareWithContext(e,t,r,{middlewareFn:n,clientName:i,commandName:o,inputFilterSensitiveLog:s,outputFilterSensitiveLog:a,smithyContext:c,additionalContext:u,CommandCtor:d}){for(const i of n.bind(this)(d,e,t,r))this.middlewareStack.use(i);const l=e.concat(this.middlewareStack),{logger:h}=t,f={logger:h,clientName:i,commandName:o,inputFilterSensitiveLog:s,outputFilterSensitiveLog:a,[L]:{commandInstance:this,...c},...u},{requestHandler:p}=t;return l.resolve((e=>p.handle(e.request,r||{})),f)}}class Dt{constructor(){this._init=()=>{},this._ep={},this._middlewareFn=()=>[],this._commandName="",this._clientName="",this._additionalContext={},this._smithyContext={},this._inputFilterSensitiveLog=e=>e,this._outputFilterSensitiveLog=e=>e,this._serializer=null,this._deserializer=null}init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,t,r={}){return this._smithyContext={service:e,operation:t,...r},this}c(e={}){return this._additionalContext=e,this}n(e,t){return this._clientName=e,this._commandName=t,this}f(e=e=>e,t=e=>e){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=t,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}build(){const e=this;let t;return t=class extends Bt{static getEndpointParameterInstructions(){return e._ep}constructor(...[t]){super(),this.serialize=e._serializer,this.deserialize=e._deserializer,this.input=t??{},e._init(this)}resolveMiddleware(r,n,i){return this.resolveMiddlewareWithContext(r,n,i,{CommandCtor:t,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog,outputFilterSensitiveLog:e._outputFilterSensitiveLog,smithyContext:e._smithyContext,additionalContext:e._additionalContext})}}}}const jt="***SensitiveInformation***",zt=e=>{switch(e){case"true":return!0;case"false":return!1;default:throw new Error(`Unable to parse boolean value "${e}"`)}},qt=Math.ceil(2**127*(2-2**-23)),Ht=e=>{const t=(e=>{if(null!=e){if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return String(t)!==String(e)&&sr.warn(or(`Expected number but observed string: ${e}`)),t}if("number"==typeof e)return e;throw new TypeError(`Expected number, got ${typeof e}: ${e}`)}})(e);if(void 0!==t&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0&&Math.abs(t)>qt)throw new TypeError(`Expected 32-bit float, got ${e}`);return t},Wt=e=>{if(null!=e){if(Number.isInteger(e)&&!Number.isNaN(e))return e;throw new TypeError(`Expected integer, got ${typeof e}: ${e}`)}},Kt=e=>Qt(e,32),Vt=e=>Qt(e,16),Gt=e=>Qt(e,8),Qt=(e,t)=>{const r=Wt(e);if(void 0!==r&&Jt(r,t)!==r)throw new TypeError(`Expected ${t}-bit integer, got ${e}`);return r},Jt=(e,t)=>{switch(t){case 32:return Int32Array.of(e)[0];case 16:return Int16Array.of(e)[0];case 8:return Int8Array.of(e)[0]}},Xt=(e,t)=>{if(null==e){if(t)throw new TypeError(`Expected a non-null value for ${t}`);throw new TypeError("Expected a non-null value")}return e},Zt=e=>{if(null==e)return;if("object"==typeof e&&!Array.isArray(e))return e;const t=Array.isArray(e)?"array":typeof e;throw new TypeError(`Expected object, got ${t}: ${e}`)},Yt=e=>{if(null!=e){if("string"==typeof e)return e;if(["boolean","number","bigint"].includes(typeof e))return sr.warn(or(`Expected string, got ${typeof e}: ${e}`)),String(e);throw new TypeError(`Expected string, got ${typeof e}: ${e}`)}},er=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,tr=e=>{const t=e.match(er);if(null===t||t[0].length!==e.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(e)},rr=e=>Wt("string"==typeof e?tr(e):e),nr=e=>Kt("string"==typeof e?tr(e):e),ir=e=>Vt("string"==typeof e?tr(e):e),or=e=>String(new TypeError(e).stack||e).split("\n").slice(0,5).filter((e=>!e.includes("stackTraceWarning"))).join("\n"),sr={warn:console.warn},ar=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],cr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ur(e){const t=e.getUTCFullYear(),r=e.getUTCMonth(),n=e.getUTCDay(),i=e.getUTCDate(),o=e.getUTCHours(),s=e.getUTCMinutes(),a=e.getUTCSeconds(),c=o<10?`0${o}`:`${o}`,u=s<10?`0${s}`:`${s}`,d=a<10?`0${a}`:`${a}`;return`${ar[n]}, ${i<10?`0${i}`:`${i}`} ${cr[r]} ${t} ${c}:${u}:${d} GMT`}const dr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),lr=e=>{if(null==e)return;if("string"!=typeof e)throw new TypeError("RFC-3339 date-times must be expressed as strings");const t=dr.exec(e);if(!t)throw new TypeError("Invalid RFC-3339 date-time value");const[r,n,i,o,s,a,c,u,d]=t,l=ir(Tr(n)),h=Er(i,"month",1,12),f=Er(o,"day",1,31),p=mr(l,h,f,{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u});return"Z"!=d.toUpperCase()&&p.setTime(p.getTime()-Ar(d)),p},hr=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),fr=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),pr=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),gr=e=>{if(null==e)return;if("string"!=typeof e)throw new TypeError("RFC-7231 date-times must be expressed as strings");let t=hr.exec(e);if(t){const[e,r,n,i,o,s,a,c]=t;return mr(ir(Tr(i)),br(n),Er(r,"day",1,31),{hours:o,minutes:s,seconds:a,fractionalMilliseconds:c})}if(t=fr.exec(e),t){const[e,r,n,i,o,s,a,c]=t;return vr(mr(yr(i),br(n),Er(r,"day",1,31),{hours:o,minutes:s,seconds:a,fractionalMilliseconds:c}))}if(t=pr.exec(e),t){const[e,r,n,i,o,s,a,c]=t;return mr(ir(Tr(c)),br(r),Er(n.trimLeft(),"day",1,31),{hours:i,minutes:o,seconds:s,fractionalMilliseconds:a})}throw new TypeError("Invalid RFC-7231 date-time value")},mr=(e,t,r,n)=>{const i=t-1;return kr(e,i,r),new Date(Date.UTC(e,i,r,Er(n.hours,"hour",0,23),Er(n.minutes,"minute",0,59),Er(n.seconds,"seconds",0,60),xr(n.fractionalMilliseconds)))},yr=e=>{const t=(new Date).getUTCFullYear(),r=100*Math.floor(t/100)+ir(Tr(e));return re.getTime()-(new Date).getTime()>15768e8?new Date(Date.UTC(e.getUTCFullYear()-100,e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())):e,br=e=>{const t=cr.indexOf(e);if(t<0)throw new TypeError(`Invalid month: ${e}`);return t+1},wr=[31,28,31,30,31,30,31,31,30,31,30,31],kr=(e,t,r)=>{let n=wr[t];if(1===t&&Sr(e)&&(n=29),r>n)throw new TypeError(`Invalid day for ${cr[t]} in ${e}: ${r}`)},Sr=e=>e%4==0&&(e%100!=0||e%400==0),Er=(e,t,r,n)=>{const i=(e=>Gt("string"==typeof e?tr(e):e))(Tr(e));if(in)throw new TypeError(`${t} must be between ${r} and ${n}, inclusive`);return i},xr=e=>null==e?0:1e3*(e=>Ht("string"==typeof e?tr(e):e))("0."+e),Ar=e=>{const t=e[0];let r=1;if("+"==t)r=1;else{if("-"!=t)throw new TypeError(`Offset direction, ${t}, must be "+" or "-"`);r=-1}return r*(60*Number(e.substring(1,3))+Number(e.substring(4,6)))*60*1e3},Tr=e=>{let t=0;for(;t{Object.entries(t).filter((([,e])=>void 0!==e)).forEach((([t,r])=>{null!=e[t]&&""!==e[t]||(e[t]=r)}));const r=e.message||e.Message||"UnknownError";return e.message=r,delete e.Message,e},Or=e=>({httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}),Pr=e=>{switch(e){case"standard":case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}},_r=e=>{const t=[];for(const r in $){const n=$[r];void 0!==e[n]&&t.push({algorithmId:()=>n,checksumConstructor:()=>e[n]})}return{_checksumAlgorithms:t,addChecksumAlgorithm(e){this._checksumAlgorithms.push(e)},checksumAlgorithms(){return this._checksumAlgorithms}}},Mr=e=>{const t={};return e.checksumAlgorithms().forEach((e=>{t[e.algorithmId()]=e.checksumConstructor()})),t},Ir=e=>{let t=e.retryStrategy;return{setRetryStrategy(e){t=e},retryStrategy:()=>t}},Nr=e=>{const t={};return t.retryStrategy=e.retryStrategy(),t},Fr=e=>({..._r(e),...Ir(e)}),$r=e=>({...Mr(e),...Nr(e)}),Ur=e=>Array.isArray(e)?e:[e],Lr=e=>{const t="#text";for(const r in e)e.hasOwnProperty(r)&&void 0!==e[r][t]?e[r]=e[r][t]:"object"==typeof e[r]&&null!==e[r]&&(e[r]=Lr(e[r]));return e},Br=e=>null!=e,Dr=function(){const e=Object.getPrototypeOf(this).constructor,t=new(Function.bind.apply(String,[null,...arguments]));return Object.setPrototypeOf(t,e.prototype),t};Dr.prototype=Object.create(String.prototype,{constructor:{value:Dr,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(Dr,String);class jr{trace(){}debug(){}info(){}warn(){}error(){}}function zr(e,t,r){let n,i,o;if(void 0===t&&void 0===r)n={},o=e;else{if(n=e,"function"==typeof t)return i=t,o=r,qr(n,i,o);o=t}for(const e of Object.keys(o))Array.isArray(o[e])?Hr(n,null,o,e):n[e]=o[e];return n}const qr=(e,t,r)=>zr(e,Object.entries(r).reduce(((e,[r,n])=>(Array.isArray(n)?e[r]=n:e[r]="function"==typeof n?[t,n()]:[t,n],e)),{})),Hr=(e,t,r,n)=>{if(null!==t){let i=r[n];"function"==typeof i&&(i=[,i]);const[o=Wr,s=Kr,a=n]=i;return void(("function"==typeof o&&o(t[a])||"function"!=typeof o&&o)&&(e[n]=s(t[a])))}let[i,o]=r[n];if("function"==typeof o){let t;const r=void 0===i&&null!=(t=o()),s="function"==typeof i&&!!i(void 0)||"function"!=typeof i&&!!i;r?e[n]=t:s&&(e[n]=o())}else{const t=void 0===i&&null!=o,r="function"==typeof i&&!!i(o)||"function"!=typeof i&&!!i;(t||r)&&(e[n]=o)}},Wr=e=>null!=e,Kr=e=>e;function Vr(e){return(e.includes(",")||e.includes('"'))&&(e=`"${e.replace(/"/g,'\\"')}"`),e}function Gr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Qr={},Jr={};!function(e){const t=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",r="["+t+"]["+(t+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040")+"]*",n=new RegExp("^"+r+"$");e.isExist=function(e){return void 0!==e},e.isEmptyObject=function(e){return 0===Object.keys(e).length},e.merge=function(e,t,r){if(t){const n=Object.keys(t),i=n.length;for(let o=0;o5&&"xml"===n)return un("InvalidXml","XML declaration allowed only at the start of the document.",ln(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}}return t}function tn(e,t){if(e.length>t+5&&"-"===e[t+1]&&"-"===e[t+2]){for(t+=3;t"===e[t+2]){t+=2;break}}else if(e.length>t+8&&"D"===e[t+1]&&"O"===e[t+2]&&"C"===e[t+3]&&"T"===e[t+4]&&"Y"===e[t+5]&&"P"===e[t+6]&&"E"===e[t+7]){let r=1;for(t+=8;t"===e[t]&&(r--,0===r))break}else if(e.length>t+9&&"["===e[t+1]&&"C"===e[t+2]&&"D"===e[t+3]&&"A"===e[t+4]&&"T"===e[t+5]&&"A"===e[t+6]&&"["===e[t+7])for(t+=8;t"===e[t+2]){t+=2;break}return t}Qr.validate=function(e,t){t=Object.assign({},Zr,t);const r=[];let n=!1,i=!1;"\ufeff"===e[0]&&(e=e.substr(1));for(let s=0;s"!==e[s]&&" "!==e[s]&&"\t"!==e[s]&&"\n"!==e[s]&&"\r"!==e[s];s++)u+=e[s];if(u=u.trim(),"/"===u[u.length-1]&&(u=u.substring(0,u.length-1),s--),o=u,!Xr.isName(o)){let t;return t=0===u.trim().length?"Invalid space after '<'.":"Tag '"+u+"' is an invalid name.",un("InvalidTag",t,ln(e,s))}const d=on(e,s);if(!1===d)return un("InvalidAttr","Attributes for '"+u+"' have open quote.",ln(e,s));let l=d.value;if(s=d.index,"/"===l[l.length-1]){const r=s-l.length;l=l.substring(0,l.length-1);const i=an(l,t);if(!0!==i)return un(i.err.code,i.err.msg,ln(e,r+i.err.line));n=!0}else if(c){if(!d.tagClosed)return un("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",ln(e,s));if(l.trim().length>0)return un("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",ln(e,a));if(0===r.length)return un("InvalidTag","Closing tag '"+u+"' has not been opened.",ln(e,a));{const t=r.pop();if(u!==t.tagName){let r=ln(e,t.tagStartPos);return un("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+r.line+", col "+r.col+") instead of closing tag '"+u+"'.",ln(e,a))}0==r.length&&(i=!0)}}else{const o=an(l,t);if(!0!==o)return un(o.err.code,o.err.msg,ln(e,s-l.length+o.err.line));if(!0===i)return un("InvalidXml","Multiple possible root nodes found.",ln(e,s));-1!==t.unpairedTags.indexOf(u)||r.push({tagName:u,tagStartPos:a}),n=!0}for(s++;s0)||un("InvalidXml","Invalid '"+JSON.stringify(r.map((e=>e.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):un("InvalidXml","Start tag expected.",1)};const rn='"',nn="'";function on(e,t){let r="",n="",i=!1;for(;t"===e[t]&&""===n){i=!0;break}r+=e[t]}return""===n&&{value:r,index:t,tagClosed:i}}const sn=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function an(e,t){const r=Xr.getAllMatches(e,sn),n={};for(let e=0;e!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,r){return e}};fn.buildOptions=function(e){return Object.assign({},pn,e)},fn.defaultOptions=pn;var gn=class{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}add(e,t){"__proto__"===e&&(e="#__proto__"),this.child.push({[e]:t})}addChild(e){"__proto__"===e.tagname&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child})}};const mn=Jr;function yn(e,t){let r="";for(;t"===e[t]){if(o?"-"===e[t-1]&&"-"===e[t-2]&&(o=!1,n--):n--,0===n)break}else"["===e[t]?i=!0:s+=e[t];else{if(i&&bn(e,t))t+=7,[entityName,val,t]=yn(e,t+1),-1===val.indexOf("&")&&(r[En(entityName)]={regx:RegExp(`&${entityName};`,"g"),val:val});else if(i&&wn(e,t))t+=8;else if(i&&kn(e,t))t+=8;else if(i&&Sn(e,t))t+=9;else{if(!vn)throw new Error("Invalid DOCTYPE");o=!0}n++,s=""}if(0!==n)throw new Error("Unclosed DOCTYPE")}return{entities:r,i:t}};const An=/^[-+]?0x[a-fA-F0-9]+$/,Tn=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);const Cn={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};const Rn=Jr,On=gn,Pn=xn,_n=function(e,t={}){if(t=Object.assign({},Cn,t),!e||"string"!=typeof e)return e;let r=e.trim();if(void 0!==t.skipLike&&t.skipLike.test(r))return e;if(t.hex&&An.test(r))return Number.parseInt(r,16);{const n=Tn.exec(r);if(n){const i=n[1],o=n[2];let s=function(e){if(e&&-1!==e.indexOf("."))return"."===(e=e.replace(/0+$/,""))?e="0":"."===e[0]?e="0"+e:"."===e[e.length-1]&&(e=e.substr(0,e.length-1)),e;return e}(n[3]);const a=n[4]||n[6];if(!t.leadingZeros&&o.length>0&&i&&"."!==r[2])return e;if(!t.leadingZeros&&o.length>0&&!i&&"."!==r[1])return e;{const n=Number(r),c=""+n;return-1!==c.search(/[eE]/)||a?t.eNotation?n:e:-1!==r.indexOf(".")?"0"===c&&""===s||c===s||i&&c==="-"+s?n:e:o?s===c||i+s===c?n:e:r===c||r===i+c?n:e}}return e}};function Mn(e){const t=Object.keys(e);for(let r=0;r0)){s||(e=this.replaceEntitiesValue(e));const n=this.options.tagValueProcessor(t,e,r,i,o);if(null==n)return e;if(typeof n!=typeof e||n!==e)return n;if(this.options.trimValues)return Wn(e,this.options.parseTagValue,this.options.numberParseOptions);return e.trim()===e?Wn(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function Nn(e){if(this.options.removeNSPrefix){const t=e.split(":"),r="/"===e.charAt(0)?"/":"";if("xmlns"===t[0])return"";2===t.length&&(e=r+t[1])}return e}const Fn=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function $n(e,t,r){if(!this.options.ignoreAttributes&&"string"==typeof e){const r=Rn.getAllMatches(e,Fn),n=r.length,i={};for(let e=0;e",o,"Closing Tag is not closed.");let s=e.substring(o+2,t).trim();if(this.options.removeNSPrefix){const e=s.indexOf(":");-1!==e&&(s=s.substr(e+1))}this.options.transformTagName&&(s=this.options.transformTagName(s)),r&&(n=this.saveTextToParentTag(n,r,i));const a=i.substring(i.lastIndexOf(".")+1);if(s&&-1!==this.options.unpairedTags.indexOf(s))throw new Error(`Unpaired tag can not be used as closing tag: `);let c=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(c=i.lastIndexOf(".",i.lastIndexOf(".")-1),this.tagsNodeStack.pop()):c=i.lastIndexOf("."),i=i.substring(0,c),r=this.tagsNodeStack.pop(),n="",o=t}else if("?"===e[o+1]){let t=qn(e,o,!1,"?>");if(!t)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,r,i),this.options.ignoreDeclaration&&"?xml"===t.tagName||this.options.ignorePiTags);else{const e=new On(t.tagName);e.add(this.options.textNodeName,""),t.tagName!==t.tagExp&&t.attrExpPresent&&(e[":@"]=this.buildAttributesMap(t.tagExp,i,t.tagName)),this.addChild(r,e,i)}o=t.closeIndex+1}else if("!--"===e.substr(o+1,3)){const t=zn(e,"--\x3e",o+4,"Comment is not closed.");if(this.options.commentPropName){const s=e.substring(o+4,t-2);n=this.saveTextToParentTag(n,r,i),r.add(this.options.commentPropName,[{[this.options.textNodeName]:s}])}o=t}else if("!D"===e.substr(o+1,2)){const t=Pn(e,o);this.docTypeEntities=t.entities,o=t.i}else if("!["===e.substr(o+1,2)){const t=zn(e,"]]>",o,"CDATA is not closed.")-2,s=e.substring(o+9,t);n=this.saveTextToParentTag(n,r,i);let a=this.parseTextData(s,r.tagname,i,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?r.add(this.options.cdataPropName,[{[this.options.textNodeName]:s}]):r.add(this.options.textNodeName,a),o=t+2}else{let s=qn(e,o,this.options.removeNSPrefix),a=s.tagName;const c=s.rawTagName;let u=s.tagExp,d=s.attrExpPresent,l=s.closeIndex;this.options.transformTagName&&(a=this.options.transformTagName(a)),r&&n&&"!xml"!==r.tagname&&(n=this.saveTextToParentTag(n,r,i,!1));const h=r;if(h&&-1!==this.options.unpairedTags.indexOf(h.tagname)&&(r=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf("."))),a!==t.tagname&&(i+=i?"."+a:a),this.isItStopNode(this.options.stopNodes,i,a)){let t="";if(u.length>0&&u.lastIndexOf("/")===u.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),i=i.substr(0,i.length-1),u=a):u=u.substr(0,u.length-1),o=s.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))o=s.closeIndex;else{const r=this.readStopNodeData(e,c,l+1);if(!r)throw new Error(`Unexpected end of ${c}`);o=r.i,t=r.tagContent}const n=new On(a);a!==u&&d&&(n[":@"]=this.buildAttributesMap(u,i,a)),t&&(t=this.parseTextData(t,a,i,!0,d,!0,!0)),i=i.substr(0,i.lastIndexOf(".")),n.add(this.options.textNodeName,t),this.addChild(r,n,i)}else{if(u.length>0&&u.lastIndexOf("/")===u.length-1){"/"===a[a.length-1]?(a=a.substr(0,a.length-1),i=i.substr(0,i.length-1),u=a):u=u.substr(0,u.length-1),this.options.transformTagName&&(a=this.options.transformTagName(a));const e=new On(a);a!==u&&d&&(e[":@"]=this.buildAttributesMap(u,i,a)),this.addChild(r,e,i),i=i.substr(0,i.lastIndexOf("."))}else{const e=new On(a);this.tagsNodeStack.push(r),a!==u&&d&&(e[":@"]=this.buildAttributesMap(u,i,a)),this.addChild(r,e,i),r=e}n="",o=l}}else n+=e[o]}return t.child};function Ln(e,t,r){const n=this.options.updateTag(t.tagname,r,t[":@"]);!1===n||("string"==typeof n?(t.tagname=n,e.addChild(t)):e.addChild(t))}const Bn=function(e){if(this.options.processEntities){for(let t in this.docTypeEntities){const r=this.docTypeEntities[t];e=e.replace(r.regx,r.val)}for(let t in this.lastEntities){const r=this.lastEntities[t];e=e.replace(r.regex,r.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){const r=this.htmlEntities[t];e=e.replace(r.regex,r.val)}e=e.replace(this.ampEntity.regex,this.ampEntity.val)}return e};function Dn(e,t,r,n){return e&&(void 0===n&&(n=0===Object.keys(t.child).length),void 0!==(e=this.parseTextData(e,t.tagname,r,!1,!!t[":@"]&&0!==Object.keys(t[":@"]).length,n))&&""!==e&&t.add(this.options.textNodeName,e),e=""),e}function jn(e,t,r){const n="*."+r;for(const r in e){const i=e[r];if(n===i||t===i)return!0}return!1}function zn(e,t,r,n){const i=e.indexOf(t,r);if(-1===i)throw new Error(n);return i+t.length-1}function qn(e,t,r,n=">"){const i=function(e,t,r=">"){let n,i="";for(let o=t;o",r,`${t} is not closed`);if(e.substring(r+2,o).trim()===t&&(i--,0===i))return{tagContent:e.substring(n,r),i:o};r=o}else if("?"===e[r+1]){r=zn(e,"?>",r+1,"StopNode is not closed.")}else if("!--"===e.substr(r+1,3)){r=zn(e,"--\x3e",r+3,"StopNode is not closed.")}else if("!["===e.substr(r+1,2)){r=zn(e,"]]>",r,"StopNode is not closed.")-2}else{const n=qn(e,r,">");if(n){(n&&n.tagName)===t&&"/"!==n.tagExp[n.tagExp.length-1]&&i++,r=n.closeIndex}}}function Wn(e,t,r){if(t&&"string"==typeof e){const t=e.trim();return"true"===t||"false"!==t&&_n(e,r)}return Rn.isExist(e)?e:""}var Kn=class{constructor(e){this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,t)=>String.fromCharCode(Number.parseInt(t,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,t)=>String.fromCharCode(Number.parseInt(t,16))}},this.addExternalEntities=Mn,this.parseXml=Un,this.parseTextData=In,this.resolveNameSpace=Nn,this.buildAttributesMap=$n,this.isItStopNode=jn,this.replaceEntitiesValue=Bn,this.readStopNodeData=Hn,this.saveTextToParentTag=Dn,this.addChild=Ln}},Vn={};function Gn(e,t,r){let n;const i={};for(let o=0;o0&&(i[t.textNodeName]=n):void 0!==n&&(i[t.textNodeName]=n),i}function Qn(e){const t=Object.keys(e);for(let e=0;e`,o=!1;continue}if(c===t.commentPropName){i+=n+`\x3c!--${a[c][0][t.textNodeName]}--\x3e`,o=!0;continue}if("?"===c[0]){const e=oi(a[":@"],t),r="?xml"===c?"":n;let s=a[c][0][t.textNodeName];s=0!==s.length?" "+s:"",i+=r+`<${c}${s}${e}?>`,o=!0;continue}let d=n;""!==d&&(d+=t.indentBy);const l=n+`<${c}${oi(a[":@"],t)}`,h=ni(a[c],t,u,d);-1!==t.unpairedTags.indexOf(c)?t.suppressUnpairedNode?i+=l+">":i+=l+"/>":h&&0!==h.length||!t.suppressEmptyNode?h&&h.endsWith(">")?i+=l+`>${h}${n}`:(i+=l+">",h&&""!==n&&(h.includes("/>")||h.includes("`):i+=l+"/>",o=!0}return i}function ii(e){const t=Object.keys(e);for(let r=0;r0&&t.processEntities)for(let r=0;r0&&(r="\n"),ni(e,t,"",r)},ui={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function di(e){this.options=Object.assign({},ui,e),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=fi),this.processTextOrObjNode=li,this.options.format?(this.indentate=hi,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function li(e,t,r){const n=this.j2x(e,r+1);return void 0!==e[this.options.textNodeName]&&1===Object.keys(e).length?this.buildTextValNode(e[this.options.textNodeName],t,n.attrStr,r):this.buildObjectNode(n.val,t,n.attrStr,r)}function hi(e){return this.options.indentBy.repeat(e)}function fi(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}di.prototype.build=function(e){return this.options.preserveOrder?ci(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0).val)},di.prototype.j2x=function(e,t){let r="",n="";for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i))if(void 0===e[i])this.isAttribute(i)&&(n+="");else if(null===e[i])this.isAttribute(i)?n+="":"?"===i[0]?n+=this.indentate(t)+"<"+i+"?"+this.tagEndChar:n+=this.indentate(t)+"<"+i+"/"+this.tagEndChar;else if(e[i]instanceof Date)n+=this.buildTextValNode(e[i],i,"",t);else if("object"!=typeof e[i]){const o=this.isAttribute(i);if(o)r+=this.buildAttrPairStr(o,""+e[i]);else if(i===this.options.textNodeName){let t=this.options.tagValueProcessor(i,""+e[i]);n+=this.replaceEntitiesValue(t)}else n+=this.buildTextValNode(e[i],i,"",t)}else if(Array.isArray(e[i])){const r=e[i].length;let o="",s="";for(let a=0;a"+e+i}},di.prototype.closeTag=function(e){let t="";return-1!==this.options.unpairedTags.indexOf(e)?this.options.suppressUnpairedNode||(t="/"):t=this.options.suppressEmptyNode?"/":`>`+this.newLine;if(!1!==this.options.commentPropName&&t===this.options.commentPropName)return this.indentate(n)+`\x3c!--${e}--\x3e`+this.newLine;if("?"===t[0])return this.indentate(n)+"<"+t+r+"?"+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),""===i?this.indentate(n)+"<"+t+r+this.closeTag(t)+this.tagEndChar:this.indentate(n)+"<"+t+r+">"+i+"0&&this.options.processEntities)for(let t=0;t((e,t)=>Ke(e,t).then((e=>t.utf8Encoder(e))))(e,t).then((e=>{if(e.length){const t=new pi.XMLParser({attributeNamePrefix:"",htmlEntities:!0,ignoreAttributes:!1,ignoreDeclaration:!0,parseTagValue:!1,trimValues:!1,tagValueProcessor:(e,t)=>""===t.trim()&&t.includes("\n")?"":void 0});let r;t.addEntity("#xD","\r"),t.addEntity("#10","\n");try{r=t.parse(e,!0)}catch(t){throw t&&"object"==typeof t&&Object.defineProperty(t,"$responseBodyText",{value:e}),t}const n="#text",i=Object.keys(r)[0],o=r[i];return o[n]&&(o[i]=o[n],delete o[n]),Lr(o)}return{}})),mi=async(e,t)=>{const r=await gi(e,t);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r},yi=[G.CRC32,G.CRC32C,G.SHA1,G.SHA256],vi=[G.SHA256,G.SHA1,G.CRC32,G.CRC32C],bi=e=>e===G.MD5?"content-md5":`x-amz-checksum-${e.toLowerCase()}`,wi=e=>void 0!==e&&"string"!=typeof e&&!ArrayBuffer.isView(e)&&!wt(e);function ki(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(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((n=n.apply(e,t||[])).next())}))}function Si(e,t){var r,n,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1](new TextEncoder).encode(e);function xi(e){return e instanceof Uint8Array?e:"string"==typeof e?Ei(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}function Ai(e){return"string"==typeof e?0===e.length:0===e.byteLength}function Ti(e){return new Uint8Array([(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e])}function Ci(e){if(!Uint32Array.from){for(var t=new Uint32Array(e.length),r=0;r=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),i=n.next();!i.done;i=n.next()){var o=i.value;this.checksum=this.checksum>>>8^Pi[255&(this.checksum^o)]}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}return this},e.prototype.digest=function(){return(4294967295^this.checksum)>>>0},e}(),Pi=Ci([0,4067132163,3778769143,324072436,3348797215,904991772,648144872,3570033899,2329499855,2024987596,1809983544,2575936315,1296289744,3207089363,2893594407,1578318884,274646895,3795141740,4049975192,51262619,3619967088,632279923,922689671,3298075524,2592579488,1760304291,2075979607,2312596564,1562183871,2943781820,3156637768,1313733451,549293790,3537243613,3246849577,871202090,3878099393,357341890,102525238,4101499445,2858735121,1477399826,1264559846,3107202533,1845379342,2677391885,2361733625,2125378298,820201905,3263744690,3520608582,598981189,4151959214,85089709,373468761,3827903834,3124367742,1213305469,1526817161,2842354314,2107672161,2412447074,2627466902,1861252501,1098587580,3004210879,2688576843,1378610760,2262928035,1955203488,1742404180,2511436119,3416409459,969524848,714683780,3639785095,205050476,4266873199,3976438427,526918040,1361435347,2739821008,2954799652,1114974503,2529119692,1691668175,2005155131,2247081528,3690758684,697762079,986182379,3366744552,476452099,3993867776,4250756596,255256311,1640403810,2477592673,2164122517,1922457750,2791048317,1412925310,1197962378,3037525897,3944729517,427051182,170179418,4165941337,746937522,3740196785,3451792453,1070968646,1905808397,2213795598,2426610938,1657317369,3053634322,1147748369,1463399397,2773627110,4215344322,153784257,444234805,3893493558,1021025245,3467647198,3722505002,797665321,2197175160,1889384571,1674398607,2443626636,1164749927,3070701412,2757221520,1446797203,137323447,4198817972,3910406976,461344835,3484808360,1037989803,781091935,3705997148,2460548119,1623424788,1939049696,2180517859,1429367560,2807687179,3020495871,1180866812,410100952,3927582683,4182430767,186734380,3756733383,763408580,1053836080,3434856499,2722870694,1344288421,1131464017,2971354706,1708204729,2545590714,2229949006,1988219213,680717673,3673779818,3383336350,1002577565,4010310262,493091189,238226049,4233660802,2987750089,1082061258,1395524158,2705686845,1972364758,2279892693,2494862625,1725896226,952904198,3399985413,3656866545,731699698,4283874585,222117402,510512622,3959836397,3280807620,837199303,582374963,3504198960,68661723,4135334616,3844915500,390545967,1230274059,3141532936,2825850620,1510247935,2395924756,2091215383,1878366691,2644384480,3553878443,565732008,854102364,3229815391,340358836,3861050807,4117890627,119113024,1493875044,2875275879,3090270611,1247431312,2660249211,1828433272,2141937292,2378227087,3811616794,291187481,34330861,4032846830,615137029,3603020806,3314634738,939183345,1776939221,2609017814,2295496738,2058945313,2926798794,1545135305,1330124605,3173225534,4084100981,17165430,307568514,3762199681,888469610,3332340585,3587147933,665062302,2042050490,2346497209,2559330125,1793573966,3190661285,1279665062,1595330642,2910671697]);function _i(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(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((n=n.apply(e,t||[])).next())}))}function Mi(e,t){var r,n,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),i=n.next();!i.done;i=n.next()){var o=i.value;this.checksum=this.checksum>>>8^Fi[255&(this.checksum^o)]}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}return this},e.prototype.digest=function(){return(4294967295^this.checksum)>>>0},e}(),Fi=Ci([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);const $i=(e,t)=>({[G.MD5]:t.md5,[G.CRC32]:Ii,[G.CRC32C]:Ri,[G.SHA1]:t.sha1,[G.SHA256]:t.sha256}[e]),Ui=(e,t)=>{const r=new e;return r.update(Ee(t||"")),r.digest()},Li={name:"flexibleChecksumsMiddleware",step:"build",tags:["BODY_CHECKSUM"],override:!0},Bi=(e,t)=>(r,n)=>async i=>{if(!j.isInstance(i.request))return r(i);const{request:o,input:s}=i,{body:a,headers:c}=o,{base64Encoder:u,streamHasher:d}=e,{requestChecksumRequired:l,requestAlgorithmMember:h}=t,f=((e,{requestChecksumRequired:t,requestAlgorithmMember:r},n)=>{const i=n?X:J;if(!r||!e[r])return t?i:void 0;const o=e[r];if(!yi.includes(o))throw new Error(`The checksum algorithm "${o}" is not supported by the client. Select one of ${yi}.`);return o})(s,{requestChecksumRequired:l,requestAlgorithmMember:h},!!n.isS3ExpressBucket);let p=a,g=c;if(f){switch(f){case G.CRC32:Y(n,"FLEXIBLE_CHECKSUMS_REQ_CRC32","U");break;case G.CRC32C:Y(n,"FLEXIBLE_CHECKSUMS_REQ_CRC32C","V");break;case G.SHA1:Y(n,"FLEXIBLE_CHECKSUMS_REQ_SHA1","X");break;case G.SHA256:Y(n,"FLEXIBLE_CHECKSUMS_REQ_SHA256","Y")}const t=bi(f),r=$i(f,e);if(wi(a)){const{getAwsChunkedEncodingStream:n,bodyLengthChecker:i}=e;p=n(a,{base64Encoder:u,bodyLengthChecker:i,checksumLocationName:t,checksumAlgorithmFn:r,streamHasher:d}),g={...c,"content-encoding":c["content-encoding"]?`${c["content-encoding"]},aws-chunked`:"aws-chunked","transfer-encoding":"chunked","x-amz-decoded-content-length":c["content-length"],"x-amz-content-sha256":"STREAMING-UNSIGNED-PAYLOAD-TRAILER","x-amz-trailer":t},delete g["content-length"]}else if(!((e,t)=>{const r=e.toLowerCase();for(const e of Object.keys(t))if(r===e.toLowerCase())return!0;return!1})(t,c)){const e=await Ui(r,a);g={...c,[t]:u(e)}}}return await r({...i,request:{...o,headers:g,body:p}})},Di=(e=[])=>{const t=[];for(const r of vi)e.includes(r)&&yi.includes(r)&&t.push(r);return t};function ji(e){return new Blob([e]).stream()}const zi=async(e,{checksumAlgorithmFn:t,base64Encoder:r})=>r(await Ui(t,e)),qi={name:"flexibleChecksumsResponseMiddleware",toMiddleware:"deserializerMiddleware",relation:"after",tags:["BODY_CHECKSUM"],override:!0},Hi=(e,t)=>(r,n)=>async i=>{if(!j.isInstance(i.request))return r(i);const o=i.input,s=await r(i),a=s.response;let c;const{requestValidationModeMember:u,responseAlgorithms:d}=t;if(u&&"ENABLED"===o[u]){const{clientName:t,commandName:r}=n;if("S3Client"===t&&"GetObjectCommand"===r&&Di(d).every((e=>{const t=bi(e),r=a.headers[t];return!r||(e=>{const t=e.lastIndexOf("-");if(-1!==t){const r=e.slice(t+1);if(!r.startsWith("0")){const e=parseInt(r,10);if(!isNaN(e)&&e>=1&&e<=1e4)return!0}}return!1})(r)})))return s;const i=wi(a.body);i&&(c=await e.streamCollector(a.body),a.body=ji(c)),await(async(e,{config:t,responseAlgorithms:r})=>{const n=Di(r),{body:i,headers:o}=e;for(const r of n){const n=bi(r),s=o[n];if(s){const o=$i(r,t),{base64Encoder:a}=t;if(wi(i))return void(e.body=We({expectedChecksum:s,checksumSourceLocation:n,checksum:new o,source:i,base64Encoder:a}));const c=await zi(i,{checksumAlgorithmFn:o,base64Encoder:a});if(c===s)break;throw new Error(`Checksum mismatch: expected "${c}" but received "${s}" in response header "${n}".`)}}})(s.response,{config:e,responseAlgorithms:d}),i&&c&&(a.body=ji(c))}return s},Wi=(e,t)=>({applyToStack:r=>{r.add(Bi(e,t),Li),r.addRelativeTo(Hi(e,t),qi)}});const Ki={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},Vi=e=>({applyToStack:t=>{t.add((e=>t=>async r=>{if(!j.isInstance(r.request))return t(r);const{request:n}=r,{handlerProtocol:i=""}=e.requestHandler.metadata||{};if(i.indexOf("h2")>=0&&!n.headers[":authority"])delete n.headers.host,n.headers[":authority"]=n.hostname+(n.port?":"+n.port:"");else if(!n.headers.host){let e=n.hostname;null!=n.port&&(e+=`:${n.port}`),n.headers.host=e}return t(r)})(e),Ki)}}),Gi={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},Qi="X-Amzn-Trace-Id",Ji={step:"build",tags:["RECURSION_DETECTION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},Xi=e=>({applyToStack:t=>{t.add((e=>t=>async r=>{const{request:n}=r;if(!j.isInstance(n)||"node"!==e.runtime||n.headers.hasOwnProperty(Qi))return t(r);const i=process.env.AWS_LAMBDA_FUNCTION_NAME,o=process.env._X_AMZN_TRACE_ID,s=e=>"string"==typeof e&&e.length>0;return s(i)&&s(o)&&(n.headers[Qi]=o),t({...r,request:n})})(e),Ji)}});const Zi={step:"finalizeRequest",tags:["CHECK_CONTENT_LENGTH_HEADER"],name:"getCheckContentLengthHeaderPlugin",override:!0},Yi=e=>({applyToStack:e=>{e.add(((e,t)=>async r=>{const{request:n}=r;if(j.isInstance(n)&&!("content-length"in n.headers)){const e="Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from @aws-sdk/lib-storage.";"function"!=typeof t?.logger?.warn||t.logger instanceof jr?console.warn(e):t.logger.warn(e)}return e({...r})}),Zi)}}),eo={tags:["REGION_REDIRECT","S3"],name:"regionRedirectEndpointMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"};const to={step:"initialize",tags:["REGION_REDIRECT","S3"],name:"regionRedirectMiddleware",override:!0},ro=e=>({applyToStack:t=>{t.add(function(e){return(t,r)=>async n=>{try{return await t(n)}catch(i){if(e.followRegionRedirects&&(301===i?.$metadata?.httpStatusCode||400===i?.$metadata?.httpStatusCode&&"IllegalLocationConstraintException"===i?.name)){try{const t=i.$response.headers["x-amz-bucket-region"];r.logger?.debug(`Redirecting from ${await e.region()} to ${t}`),r.__s3RegionRedirect=t}catch(e){throw new Error("Region redirect failed: "+e)}return t(n)}throw i}}}(e),to),t.addRelativeTo((e=>(t,r)=>async n=>{const i=await e.region(),o=e.region;let s=()=>{};r.__s3RegionRedirect&&(Object.defineProperty(e,"region",{writable:!1,value:async()=>r.__s3RegionRedirect}),s=()=>Object.defineProperty(e,"region",{writable:!0,value:o}));try{const o=await t(n);if(r.__s3RegionRedirect&&(s(),i!==await e.region()))throw new Error("Region was not restored following S3 region redirect.");return o}catch(e){throw s(),e}})(e),eo)}}),no={tags:["S3"],name:"s3ExpiresMiddleware",override:!0,relation:"after",toMiddleware:"deserializerMiddleware"},io=e=>({applyToStack:e=>{e.addRelativeTo(((e,t)=>async r=>{const n=await e(r),{response:i}=n;if(z.isInstance(i)&&i.headers.expires){i.headers.expiresstring=i.headers.expires;try{gr(i.headers.expires)}catch(e){t.logger?.warn(`AWS SDK Warning for ${t.clientName}::${t.commandName} response parsing (${i.headers.expires}): ${e}`),delete i.headers.expires}}return n}),no)}});class oo{constructor(e={}){this.data=e,this.lastPurgeTime=Date.now()}get(e){const t=this.data[e];if(t)return t}set(e,t){return this.data[e]=t,t}delete(e){delete this.data[e]}async purgeExpired(){const e=Date.now();if(!(this.lastPurgeTime+oo.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS>e))for(const t in this.data){const r=this.data[t];if(!r.isRefreshing){const n=await r.identity;n.expiration&&n.expiration.getTime(){if((e.expiration?.getTime()??0){n.set(r,new so(Promise.resolve(e)))}))),e})):n.set(r,new so(this.getIdentity(r))).identity}async getIdentity(e){await this.cache.purgeExpired().catch((e=>{console.warn("Error while clearing expired entries in S3ExpressIdentityCache: \n"+e)}));const t=await this.createSessionFn(e);if(!t.Credentials?.AccessKeyId||!t.Credentials?.SecretAccessKey)throw new Error("s3#createSession response credential missing AccessKeyId or SecretAccessKey.");return{accessKeyId:t.Credentials.AccessKeyId,secretAccessKey:t.Credentials.SecretAccessKey,sessionToken:t.Credentials.SessionToken,expiration:t.Credentials.Expiration?new Date(t.Credentials.Expiration):void 0}}}var co;ao.REFRESH_WINDOW_MS=6e4,function(e){e.ENV="env",e.CONFIG="shared config entry"}(co||(co={}));const uo="X-Amz-S3session-Token",lo=uo.toLowerCase();class ho extends Ot{async signWithCredentials(e,t,r){const n=fo(t);e.headers[lo]=t.sessionToken;return po(this,n),this.signRequest(e,r??{})}async presignWithCredentials(e,t,r){const n=fo(t);delete e.headers[lo],e.headers[uo]=t.sessionToken,e.query=e.query??{},e.query[uo]=t.sessionToken;return po(this,n),this.presign(e,r)}}function fo(e){return{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,expiration:e.expiration}}function po(e,t){const r=setTimeout((()=>{throw new Error("SignatureV4S3Express credential override was created but not called.")}),10),n=e.credentialProvider;e.credentialProvider=()=>(clearTimeout(r),e.credentialProvider=n,Promise.resolve(t))}const go={name:"s3ExpressMiddleware",step:"build",tags:["S3","S3_EXPRESS"],override:!0},mo=e=>({applyToStack:t=>{t.add((e=>(t,r)=>async n=>{if(r.endpointV2){const t=r.endpointV2,i="sigv4-s3express"===t.properties?.authSchemes?.[0]?.name;if(("S3Express"===t.properties?.backend||"Directory"===t.properties?.bucketType)&&(Y(r,"S3_EXPRESS_BUCKET","J"),r.isS3ExpressBucket=!0),i){const t=n.input.Bucket;if(t){const i=await e.s3ExpressIdentityProvider.getS3ExpressIdentity(await e.credentials(),{Bucket:t});r.s3ExpressIdentity=i,j.isInstance(n.request)&&i.sessionToken&&(n.request.headers[lo]=i.sessionToken)}}}return t(n)})(e),go)}}),yo=e=>e=>{throw e},vo=(e,t)=>{},bo=e=>(t,r)=>async n=>{if(!j.isInstance(n.request))return t(n);const i=ae(r).selectedHttpAuthScheme;if(!i)throw new Error("No HttpAuthScheme was selected: unable to sign request");const{httpAuthOption:{signingProperties:o={}},identity:s,signer:a}=i;let c;c=r.s3ExpressIdentity?await(async(e,t,r,n)=>{const i=await n.signWithCredentials(r,e,{});if(i.headers["X-Amz-Security-Token"]||i.headers["x-amz-security-token"])throw new Error("X-Amz-Security-Token must not be set for s3-express requests.");return i})(r.s3ExpressIdentity,0,n.request,await e.signer()):await a.sign(n.request,s,o);const u=await t({...n,request:c}).catch((a.errorHandler||yo)(o));return(a.successHandler||vo)(u.response,o),u},wo={CopyObjectCommand:!0,UploadPartCopyCommand:!0,CompleteMultipartUploadCommand:!0},ko=e=>(t,r)=>async n=>{const i=await t(n),{response:o}=i;if(!z.isInstance(o))return i;const{statusCode:s,body:a}=o;if(s<200||s>=300)return i;if(!("function"==typeof a?.stream||"function"==typeof a?.pipe||"function"==typeof a?.tee))return i;let c=a,u=a;!a||"object"!=typeof a||a instanceof Uint8Array||([c,u]=await async function(e){return"function"==typeof e.stream&&(e=e.stream()),e.tee()}(a)),o.body=u;const d=await So(c,{streamCollector:async e=>async function(e,t){let r=0;const n=[],i=e.getReader();let o=!1;for(;!o;){const{done:e,value:s}=await i.read();if(s&&(n.push(s),r+=s?.byteLength??0),r>=t)break;o=e}i.releaseLock();const s=new Uint8Array(Math.min(t,r));let a=0;for(const e of n){if(e.byteLength>s.byteLength-a){s.set(e.subarray(0,s.byteLength-a),a);break}s.set(e,a),a+=e.length}return s}(e,3e3)});"function"==typeof c?.destroy&&c.destroy();const l=e.utf8Encoder(d.subarray(d.length-16));if(0===d.length&&wo[r.commandName]){const e=new Error("S3 aborted request");throw e.name="InternalError",e}return l&&l.endsWith("")&&(o.statusCode=400),i},So=(e=new Uint8Array,t)=>e instanceof Uint8Array?Promise.resolve(e):t.streamCollector(e)||Promise.resolve(new Uint8Array),Eo={relation:"after",toMiddleware:"deserializerMiddleware",tags:["THROW_200_EXCEPTIONS","S3"],name:"throw200ExceptionsMiddleware",override:!0},xo=e=>({applyToStack:t=>{t.addRelativeTo(ko(e),Eo)}});const Ao={name:"bucketEndpointMiddleware",override:!0,relation:"after",toMiddleware:"endpointV2Middleware"};const To={step:"initialize",tags:["VALIDATE_BUCKET_NAME"],name:"validateBucketNameMiddleware",override:!0},Co=e=>({applyToStack:t=>{t.add(function({bucketEndpoint:e}){return t=>async r=>{const{input:{Bucket:n}}=r;if(!e&&"string"==typeof n&&!("string"==typeof(i=n)&&0===i.indexOf("arn:")&&i.split(":").length>=6)&&n.indexOf("/")>=0){const e=new Error(`Bucket name shouldn't contain '/', received '${n}'`);throw e.name="InvalidBucketName",e}var i;return t({...r})}}(e),To),t.addRelativeTo(function(e){return(t,r)=>async n=>{if(e.bucketEndpoint){const e=r.endpointV2;if(e){const t=n.input.Bucket;if("string"==typeof t)try{const n=new URL(t);r.endpointV2={...e,url:n}}catch(e){const n=`@aws-sdk/middleware-sdk-s3: bucketEndpoint=true was set but Bucket=${t} could not be parsed as URL.`;throw"NoOpLogger"===r.logger?.constructor?.name?console.warn(n):r.logger?.warn?.(n),e}}}return t(n)}}(e),Ao)}});const Ro=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),Oo=e=>Ro.test(e)||e.startsWith("[")&&e.endsWith("]"),Po=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),_o=(e,t=!1)=>{if(!t)return Po.test(e);const r=e.split(".");for(const e of r)if(!_o(e))return!1;return!0},Mo={},Io="endpoints";function No(e){return"object"!=typeof e||null==e?e:"ref"in e?`$${No(e.ref)}`:"fn"in e?`${e.fn}(${(e.argv||[]).map(No).join(", ")})`:JSON.stringify(e,null,2)}class Fo extends Error{constructor(e){super(e),this.name="EndpointError"}}const $o=(e,t)=>(e=>{const t=e.split("."),r=[];for(const n of t){const t=n.indexOf("[");if(-1!==t){if(n.indexOf("]")!==n.length-1)throw new Fo(`Path: '${e}' does not end with ']'`);const i=n.slice(t+1,-1);if(Number.isNaN(parseInt(i)))throw new Fo(`Invalid array index: '${i}' in path: '${e}'`);0!==t&&r.push(n.slice(0,t)),r.push(i)}else r.push(n)}return r})(t).reduce(((r,n)=>{if("object"!=typeof r)throw new Fo(`Index '${n}' in '${t}' not found in '${JSON.stringify(e)}'`);return Array.isArray(r)?r[parseInt(n)]:r[n]}),e),Uo={[F.HTTP]:80,[F.HTTPS]:443},Lo={booleanEquals:(e,t)=>e===t,getAttr:$o,isSet:e=>null!=e,isValidHostLabel:_o,not:e=>!e,parseURL:e=>{const t=(()=>{try{if(e instanceof URL)return e;if("object"==typeof e&&"hostname"in e){const{hostname:t,port:r,protocol:n="",path:i="",query:o={}}=e,s=new URL(`${n}//${t}${r?`:${r}`:""}${i}`);return s.search=Object.entries(o).map((([e,t])=>`${e}=${t}`)).join("&"),s}return new URL(e)}catch(e){return null}})();if(!t)return console.error(`Unable to parse ${JSON.stringify(e)} as a whatwg URL.`),null;const r=t.href,{host:n,hostname:i,pathname:o,protocol:s,search:a}=t;if(a)return null;const c=s.slice(0,-1);if(!Object.values(F).includes(c))return null;const u=Oo(i);return{scheme:c,authority:`${n}${r.includes(`${n}:${Uo[c]}`)||"string"==typeof e&&e.includes(`${n}:${Uo[c]}`)?`:${Uo[c]}`:""}`,path:o,normalizedPath:o.endsWith("/")?o:`${o}/`,isIp:u}},stringEquals:(e,t)=>e===t,substring:(e,t,r,n)=>t>=r||e.lengthencodeURIComponent(e).replace(/[!*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))},Bo=(e,t)=>{const r=[],n={...t.endpointParams,...t.referenceRecord};let i=0;for(;i{if("string"==typeof e)return Bo(e,r);if(e.fn)return jo(e,r);if(e.ref)return(({ref:e},t)=>({...t.endpointParams,...t.referenceRecord}[e]))(e,r);throw new Fo(`'${t}': ${String(e)} is not a string, function or reference.`)},jo=({fn:e,argv:t},r)=>{const n=t.map((e=>["boolean","number"].includes(typeof e)?e:Do(e,"arg",r))),i=e.split(".");return i[0]in Mo&&null!=i[1]?Mo[i[0]][i[1]](...n):Lo[e](...n)},zo=({assign:e,...t},r)=>{if(e&&e in r.referenceRecord)throw new Fo(`'${e}' is already defined in Reference Record.`);const n=jo(t,r);return r.logger?.debug?.(`${Io} evaluateCondition: ${No(t)} = ${No(n)}`),{result:""===n||!!n,...null!=e&&{toAssign:{name:e,value:n}}}},qo=(e=[],t)=>{const r={};for(const n of e){const{result:e,toAssign:i}=zo(n,{...t,referenceRecord:{...t.referenceRecord,...r}});if(!e)return{result:e};i&&(r[i.name]=i.value,t.logger?.debug?.(`${Io} assign: ${i.name} := ${No(i.value)}`))}return{result:!0,referenceRecord:r}},Ho=(e,t)=>Object.entries(e).reduce(((e,[r,n])=>({...e,[r]:n.map((e=>{const n=Do(e,"Header value entry",t);if("string"!=typeof n)throw new Fo(`Header '${r}' value '${n}' is not a string`);return n}))})),{}),Wo=(e,t)=>{if(Array.isArray(e))return e.map((e=>Wo(e,t)));switch(typeof e){case"string":return Bo(e,t);case"object":if(null===e)throw new Fo(`Unexpected endpoint property: ${e}`);return Ko(e,t);case"boolean":return e;default:throw new Fo("Unexpected endpoint property type: "+typeof e)}},Ko=(e,t)=>Object.entries(e).reduce(((e,[r,n])=>({...e,[r]:Wo(n,t)})),{}),Vo=(e,t)=>{const r=Do(e,"Endpoint URL",t);if("string"==typeof r)try{return new URL(r)}catch(e){throw console.error(`Failed to construct URL with ${r}`,e),e}throw new Fo("Endpoint URL must be a string, got "+typeof r)},Go=(e,t)=>{const{conditions:r,endpoint:n}=e,{result:i,referenceRecord:o}=qo(r,t);if(!i)return;const s={...t,referenceRecord:{...t.referenceRecord,...o}},{url:a,properties:c,headers:u}=n;return t.logger?.debug?.(`${Io} Resolving endpoint from template: ${No(n)}`),{...null!=u&&{headers:Ho(u,s)},...null!=c&&{properties:Ko(c,s)},url:Vo(a,s)}},Qo=(e,t)=>{const{conditions:r,error:n}=e,{result:i,referenceRecord:o}=qo(r,t);if(i)throw new Fo(Do(n,"Error",{...t,referenceRecord:{...t.referenceRecord,...o}}))},Jo=(e,t)=>{const{conditions:r,rules:n}=e,{result:i,referenceRecord:o}=qo(r,t);if(i)return Xo(n,{...t,referenceRecord:{...t.referenceRecord,...o}})},Xo=(e,t)=>{for(const r of e)if("endpoint"===r.type){const e=Go(r,t);if(e)return e}else if("error"===r.type)Qo(r,t);else{if("tree"!==r.type)throw new Fo(`Unknown endpoint rule: ${r}`);{const e=Jo(r,t);if(e)return e}}throw new Fo("Rules evaluation failed")},Zo=(e,t=!1)=>{if(t){for(const t of e.split("."))if(!Zo(t))return!1;return!0}return!!_o(e)&&(!(e.length<3||e.length>63)&&(e===e.toLowerCase()&&!Oo(e)))};let Yo={partitions:[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"aws-global":{description:"AWS Standard global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"AWS China global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"AWS GovCloud (US) global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"c2s.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"AWS ISO (US) global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"sc2s.sgov.gov",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"AWS ISOB (US) global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"cloud.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"csp.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{}}],version:"1.1"};const es={isVirtualHostableS3Bucket:Zo,parseArn:e=>{const t=e.split(":");if(t.length<6)return null;const[r,n,i,o,s,...a]=t;if("arn"!==r||""===n||""===i||""===a.join(":"))return null;return{partition:n,service:i,region:o,accountId:s,resourceId:a.map((e=>e.split("/"))).flat()}},partition:e=>{const{partitions:t}=Yo;for(const r of t){const{regions:t,outputs:n}=r;for(const[r,i]of Object.entries(t))if(r===e)return{...n,...i}}for(const r of t){const{regionRegex:t,outputs:n}=r;if(new RegExp(t).test(e))return{...n}}const r=t.find((e=>"aws"===e.id));if(!r)throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...r.outputs}}};Mo.aws=es;const ts=/\d{12}\.ddb/;const rs="user-agent",ns="x-amz-user-agent",is=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g,os=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;const ss=e=>(t,r)=>async n=>{const{request:i}=n;if(!j.isInstance(i))return t(n);const{headers:o}=i,s=r?.userAgent?.map(as)||[],a=(await e.defaultUserAgentProvider()).map(as);await async function(e,t,r){const n=r.request;if("rpc-v2-cbor"===n?.headers?.["smithy-protocol"]&&Y(e,"PROTOCOL_RPC_V2_CBOR","M"),"function"==typeof t.retryStrategy){const r=await t.retryStrategy();"function"==typeof r.acquireInitialRetryToken?r.constructor?.name?.includes("Adaptive")?Y(e,"RETRY_MODE_ADAPTIVE","F"):Y(e,"RETRY_MODE_STANDARD","E"):Y(e,"RETRY_MODE_LEGACY","D")}if("function"==typeof t.accountIdEndpointMode){const r=e.endpointV2;switch(String(r?.url?.hostname).match(ts)&&Y(e,"ACCOUNT_ID_ENDPOINT","O"),await(t.accountIdEndpointMode?.())){case"disabled":Y(e,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":Y(e,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":Y(e,"ACCOUNT_ID_MODE_REQUIRED","R")}}const i=e.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){const t=i;t.accountId&&Y(e,"RESOLVED_ACCOUNT_ID","T");for(const[r,n]of Object.entries(t.$source??{}))Y(e,r,n)}}(r,e,n);const c=r;a.push(`m/${function(e){let t="";for(const r in e){const n=e[r];if(!(t.length+n.length+1<=1024))break;t.length?t+=","+n:t+=n}return t}(Object.assign({},r.__smithy_context?.features,c.__aws_sdk_context?.features))}`);const u=e?.customUserAgent?.map(as)||[],d=await e.userAgentAppId();d&&a.push(as([`app/${d}`]));const l=[].concat([...a,...s,...u]).join(" "),h=[...a.filter((e=>e.startsWith("aws-sdk-"))),...u].join(" ");return"browser"!==e.runtime?(h&&(o[ns]=o[ns]?`${o[rs]} ${h}`:h),o[rs]=l):o[ns]=l,t({...n,request:i})},as=e=>{const t=e[0].split("/").map((e=>e.replace(is,"-"))).join("/"),r=e[1]?.replace(os,"-"),n=t.indexOf("/"),i=t.substring(0,n);let o=t.substring(n+1);return"api"===i&&(o=o.toLowerCase()),[i,o,r].filter((e=>e&&e.length>0)).reduce(((e,t,r)=>{switch(r){case 0:return t;case 1:return`${e}/${t}`;default:return`${e}#${t}`}}),"")},cs={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},us=e=>"string"==typeof e&&(e.startsWith("fips-")||e.endsWith("-fips")),ds=e=>us(e)?["fips-aws-global","aws-fips"].includes(e)?"us-east-1":e.replace(/fips-(dkr-|prod-)?|-fips/,""):e,ls="content-length";const hs={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},fs=e=>({applyToStack:t=>{var r;t.add((r=e.bodyLengthChecker,e=>async t=>{const n=t.request;if(j.isInstance(n)){const{body:e,headers:t}=n;if(e&&-1===Object.keys(t).map((e=>e.toLowerCase())).indexOf(ls))try{const t=r(e);n.headers={...n.headers,[ls]:String(t)}}catch(e){}}return e({...t,request:n})}),hs)}}),ps=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,gs=/(\d+\.){3}\d+/,ms=/\.\./,ys=e=>ps.test(e)&&!gs.test(e)&&!ms.test(e),vs=e=>{const[t,r,n,,,i]=e.split(":"),o="arn"===t&&e.split(":").length>=6,s=Boolean(o&&r&&n&&i);if(o&&!s)throw new Error(`Invalid ARN: ${e} was an invalid ARN.`);return s},bs=(e,t,r)=>{const n=async()=>{const n=r[e]??r[t];return"function"==typeof n?n():n};return"credentialScope"===e||"CredentialScope"===t?async()=>{const e="function"==typeof r.credentials?await r.credentials():r.credentials;return e?.credentialScope??e?.CredentialScope}:"accountId"===e||"AccountId"===t?async()=>{const e="function"==typeof r.credentials?await r.credentials():r.credentials;return e?.accountId??e?.AccountId}:"endpoint"===e||"endpoint"===t?async()=>{const e=await n();if(e&&"object"==typeof e){if("url"in e)return e.url.href;if("hostname"in e){const{protocol:t,hostname:r,port:n,path:i}=e;return`${t}//${r}${n?":"+n:""}${i}`}}return e}:n},ws=async e=>{};const ks=e=>{if("string"==typeof e)return ks(new URL(e));const{hostname:t,pathname:r,port:n,protocol:i,search:o}=e;let s;return o&&(s=function(e){const t={};if(e=e.replace(/^\?/,""))for(const r of e.split("&")){let[e,n=null]=r.split("=");e=decodeURIComponent(e),n&&(n=decodeURIComponent(n)),e in t?Array.isArray(t[e])?t[e].push(n):t[e]=[t[e],n]:t[e]=n}return t}(o)),{hostname:t,port:n?parseInt(n):void 0,protocol:i,path:r,query:s}},Ss=e=>"object"==typeof e?"url"in e?ks(e.url):e:ks(e),Es=async(e,t,r)=>{const n={},i=t?.getEndpointParameterInstructions?.()||{};for(const[t,o]of Object.entries(i))switch(o.type){case"staticContextParams":n[t]=o.value;break;case"contextParams":n[t]=e[o.name];break;case"clientContextParams":case"builtInParams":n[t]=await bs(o.name,t,r)();break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(o))}return 0===Object.keys(i).length&&Object.assign(n,r),"s3"===String(r.serviceId).toLowerCase()&&await(async e=>{const t=e?.Bucket||"";if("string"==typeof e.Bucket&&(e.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),vs(t)){if(!0===e.ForcePathStyle)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!ys(t)||-1!==t.indexOf(".")&&!String(e.Endpoint).startsWith("http:")||t.toLowerCase()!==t||t.length<3)&&(e.ForcePathStyle=!0);return e.DisableMultiRegionAccessPoints&&(e.disableMultiRegionAccessPoints=!0,e.DisableMRAP=!0),e})(n),n},xs=({config:e,instructions:t})=>(r,n)=>async i=>{e.endpoint&&function(e,t,r){e.__smithy_context?e.__smithy_context.features||(e.__smithy_context.features={}):e.__smithy_context={features:{}},e.__smithy_context.features[t]=r}(n,"ENDPOINT_OVERRIDE","N");const o=await(async(e,t,r,n)=>{if(!r.endpoint){let e;e=r.serviceConfiguredEndpoint?await r.serviceConfiguredEndpoint():await ws(r.serviceId),e&&(r.endpoint=()=>Promise.resolve(Ss(e)))}const i=await Es(e,t,r);if("function"!=typeof r.endpointProvider)throw new Error("config.endpointProvider is not set.");return r.endpointProvider(i,n)})(i.input,{getEndpointParameterInstructions:()=>t},{...e},n);n.endpointV2=o,n.authSchemes=o.properties?.authSchemes;const s=n.authSchemes?.[0];if(s){n.signing_region=s.signingRegion,n.signing_service=s.signingName;const e=ae(n),t=e?.selectedHttpAuthScheme?.httpAuthOption;t&&(t.signingProperties=Object.assign(t.signingProperties||{},{signing_region:s.signingRegion,signingRegion:s.signingRegion,signing_service:s.signingName,signingName:s.signingName,signingRegionSet:s.signingRegionSet},s.properties))}return r({...i})},As={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:he.name},Ts=(e,t)=>({applyToStack:r=>{r.addRelativeTo(xs({config:e,instructions:t}),As)}});var Cs;!function(e){e.STANDARD="standard",e.ADAPTIVE="adaptive"}(Cs||(Cs={}));const Rs=Cs.STANDARD,Os=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],Ps=["TimeoutError","RequestTimeout","RequestTimeoutException"],_s=[500,502,503,504],Ms=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],Is=e=>429===e.$metadata?.httpStatusCode||Os.includes(e.name)||1==e.$retryable?.throttling,Ns=e=>(e=>e.$metadata?.clockSkewCorrected)(e)||Ps.includes(e.name)||Ms.includes(e?.code||"")||_s.includes(e.$metadata?.httpStatusCode||0);class Fs{constructor(e){this.currentCapacity=0,this.enabled=!1,this.lastMaxRate=0,this.measuredTxRate=0,this.requestCount=0,this.lastTimestamp=0,this.timeWindow=0,this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8;const t=this.getCurrentTimeInSeconds();this.lastThrottleTime=t,this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}getCurrentTimeInSeconds(){return Date.now()/1e3}async getSendToken(){return this.acquireTokenBucket(1)}async acquireTokenBucket(e){if(this.enabled){if(this.refillTokenBucket(),e>this.currentCapacity){const t=(e-this.currentCapacity)/this.fillRate*1e3;await new Promise((e=>Fs.setTimeoutFn(e,t)))}this.currentCapacity=this.currentCapacity-e}}refillTokenBucket(){const e=this.getCurrentTimeInSeconds();if(!this.lastTimestamp)return void(this.lastTimestamp=e);const t=(e-this.lastTimestamp)*this.fillRate;this.currentCapacity=Math.min(this.maxCapacity,this.currentCapacity+t),this.lastTimestamp=e}updateClientSendingRate(e){let t;if(this.updateMeasuredRate(),Is(e)){const e=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=e,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(e),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());const r=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(r)}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(e){return this.getPrecise(e*this.beta)}cubicSuccess(e){return this.getPrecise(this.scaleConstant*Math.pow(e-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(e){this.refillTokenBucket(),this.fillRate=Math.max(e,this.minFillRate),this.maxCapacity=Math.max(e,this.minCapacity),this.currentCapacity=Math.min(this.currentCapacity,this.maxCapacity)}updateMeasuredRate(){const e=this.getCurrentTimeInSeconds(),t=Math.floor(2*e)/2;if(this.requestCount++,t>this.lastTxRateBucket){const e=this.requestCount/(t-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(e*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=t}}getPrecise(e){return parseFloat(e.toFixed(8))}}Fs.setTimeoutFn=setTimeout;const $s=({retryDelay:e,retryCount:t,retryCost:r})=>({getRetryCount:()=>t,getRetryDelay:()=>Math.min(2e4,e),getRetryCost:()=>r});class Us{constructor(e){this.maxAttempts=e,this.mode=Cs.STANDARD,this.capacity=500,this.retryBackoffStrategy=(()=>{let e=100;return{computeNextBackoffDelay:t=>Math.floor(Math.min(2e4,Math.random()*2**t*e)),setDelayBase:t=>{e=t}}})(),this.maxAttemptsProvider="function"==typeof e?e:async()=>e}async acquireInitialRetryToken(e){return $s({retryDelay:100,retryCount:0})}async refreshRetryTokenForRetry(e,t){const r=await this.getMaxAttempts();if(this.shouldRetry(e,t,r)){const r=t.errorType;this.retryBackoffStrategy.setDelayBase("THROTTLING"===r?500:100);const n=this.retryBackoffStrategy.computeNextBackoffDelay(e.getRetryCount()),i=t.retryAfterHint?Math.max(t.retryAfterHint.getTime()-Date.now()||0,n):n,o=this.getCapacityCost(r);return this.capacity-=o,$s({retryDelay:i,retryCount:e.getRetryCount()+1,retryCost:o})}throw new Error("No retry token available")}recordSuccess(e){this.capacity=Math.max(500,this.capacity+(e.getRetryCost()??1))}getCapacity(){return this.capacity}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(e){return console.warn("Max attempts provider could not resolve. Using default of 3"),3}}shouldRetry(e,t,r){return e.getRetryCount()+1=this.getCapacityCost(t.errorType)&&this.isRetryableError(t.errorType)}getCapacityCost(e){return"TRANSIENT"===e?10:5}isRetryableError(e){return"THROTTLING"===e||"TRANSIENT"===e}}class Ls{constructor(e,t){this.maxAttemptsProvider=e,this.mode=Cs.ADAPTIVE;const{rateLimiter:r}=t??{};this.rateLimiter=r??new Fs,this.standardRetryStrategy=new Us(e)}async acquireInitialRetryToken(e){return await this.rateLimiter.getSendToken(),this.standardRetryStrategy.acquireInitialRetryToken(e)}async refreshRetryTokenForRetry(e,t){return this.rateLimiter.updateClientSendingRate(t),this.standardRetryStrategy.refreshRetryTokenForRetry(e,t)}recordSuccess(e){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(e)}}let Bs;const Ds=new Uint8Array(16);function js(){if(!Bs&&(Bs="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Bs))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Bs(Ds)}const zs=[];for(let e=0;e<256;++e)zs.push((e+256).toString(16).slice(1));var qs={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Hs(e,t,r){if(qs.randomUUID&&!t&&!e)return qs.randomUUID();const n=(e=e||{}).random||(e.rng||js)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=n[e];return t}return function(e,t=0){return zs[e[t+0]]+zs[e[t+1]]+zs[e[t+2]]+zs[e[t+3]]+"-"+zs[e[t+4]]+zs[e[t+5]]+"-"+zs[e[t+6]]+zs[e[t+7]]+"-"+zs[e[t+8]]+zs[e[t+9]]+"-"+zs[e[t+10]]+zs[e[t+11]]+zs[e[t+12]]+zs[e[t+13]]+zs[e[t+14]]+zs[e[t+15]]}(n)}const Ws=e=>e?.body instanceof ReadableStream,Ks=e=>void 0!==e.acquireInitialRetryToken&&void 0!==e.refreshRetryTokenForRetry&&void 0!==e.recordSuccess,Vs=e=>{const t={error:e,errorType:Gs(e)},r=Xs(e.$response);return r&&(t.retryAfterHint=r),t},Gs=e=>Is(e)?"THROTTLING":Ns(e)?"TRANSIENT":(e=>{if(void 0!==e.$metadata?.httpStatusCode){const t=e.$metadata.httpStatusCode;return 500<=t&&t<=599&&!Ns(e)}return!1})(e)?"SERVER_ERROR":"CLIENT_ERROR",Qs={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0},Js=e=>({applyToStack:t=>{t.add((e=>(t,r)=>async n=>{let i=await e.retryStrategy();const o=await e.maxAttempts();if(!Ks(i))return i?.mode&&(r.userAgent=[...r.userAgent||[],["cfg/retry-mode",i.mode]]),i.retry(t,n);{let e=await i.acquireInitialRetryToken(r.partition_id),a=new Error,c=0,u=0;const{request:d}=n,l=j.isInstance(d);for(l&&(d.headers["amz-sdk-invocation-id"]=Hs());;)try{l&&(d.headers["amz-sdk-request"]=`attempt=${c+1}; max=${o}`);const{response:r,output:s}=await t(n);return i.recordSuccess(e),s.$metadata.attempts=c+1,s.$metadata.totalRetryDelay=u,{response:r,output:s}}catch(t){const n=Vs(t);if(a=(s=t)instanceof Error?s:s instanceof Object?Object.assign(new Error,s):"string"==typeof s?new Error(s):new Error(`AWS SDK error wrapper for ${s}`),l&&Ws(d))throw(r.logger instanceof jr?console:r.logger)?.warn("An error was encountered in a non-retryable streaming request."),a;try{e=await i.refreshRetryTokenForRetry(e,n)}catch(e){throw a.$metadata||(a.$metadata={}),a.$metadata.attempts=c+1,a.$metadata.totalRetryDelay=u,a}c=e.getRetryCount();const o=e.getRetryDelay();u+=o,await new Promise((e=>setTimeout(e,o)))}}var s})(e),Qs)}}),Xs=e=>{if(!z.isInstance(e))return;const t=Object.keys(e.headers).find((e=>"retry-after"===e.toLowerCase()));if(!t)return;const r=e.headers[t],n=Number(r);if(!Number.isNaN(n))return new Date(1e3*n);return new Date(r)},Zs=null;class Ys{constructor(e){this.sigv4Signer=new ho(e),this.signerOptions=e}async sign(e,t={}){if("*"===t.signingRegion){if("node"!==this.signerOptions.runtime)throw new Error("This request requires signing with SigV4Asymmetric algorithm. It's only available in Node.js");return this.getSigv4aSigner().sign(e,t)}return this.sigv4Signer.sign(e,t)}async signWithCredentials(e,t,r={}){if("*"===r.signingRegion){if("node"!==this.signerOptions.runtime)throw new Error("This request requires signing with SigV4Asymmetric algorithm. It's only available in Node.js");return this.getSigv4aSigner().signWithCredentials(e,t,r)}return this.sigv4Signer.signWithCredentials(e,t,r)}async presign(e,t={}){if("*"===t.signingRegion){if("node"!==this.signerOptions.runtime)throw new Error("This request requires signing with SigV4Asymmetric algorithm. It's only available in Node.js");return this.getSigv4aSigner().presign(e,t)}return this.sigv4Signer.presign(e,t)}async presignWithCredentials(e,t,r={}){if("*"===r.signingRegion)throw new Error("Method presignWithCredentials is not supported for [signingRegion=*].");return this.sigv4Signer.presignWithCredentials(e,t,r)}getSigv4aSigner(){if(!this.sigv4aSigner){let e=null;try{if(e=Zs,"function"!=typeof e)throw new Error}catch(e){throw e.message=`${e.message}\nPlease check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. \nYou must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. \nFor more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`,e}this.sigv4aSigner=new e({...this.signerOptions,signingAlgorithm:1})}return this.sigv4aSigner}}const ea="required",ta="type",ra="conditions",na="fn",ia="argv",oa="ref",sa="assign",aa="url",ca="properties",ua="backend",da="authSchemes",la="disableDoubleEncoding",ha="signingName",fa="signingRegion",pa="headers",ga="signingRegionSet",ma=!0,ya="isSet",va="booleanEquals",ba="error",wa="aws.partition",ka="stringEquals",Sa="getAttr",Ea="name",xa="substring",Aa="bucketSuffix",Ta="parseURL",Ca="{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",Ra="endpoint",Oa="tree",Pa="aws.isVirtualHostableS3Bucket",_a="{url#scheme}://{Bucket}.{url#authority}{url#path}",Ma="not",Ia="{url#scheme}://{url#authority}{url#path}",Na="hardwareType",Fa="regionPrefix",$a="bucketAliasSuffix",Ua="outpostId",La="isValidHostLabel",Ba="sigv4a",Da="s3-outposts",ja="s3",za="{url#scheme}://{url#authority}{url#normalizedPath}{Bucket}",qa="https://{Bucket}.s3-accelerate.{partitionResult#dnsSuffix}",Ha="https://{Bucket}.s3.{partitionResult#dnsSuffix}",Wa="aws.parseArn",Ka="bucketArn",Va="arnType",Ga="s3-object-lambda",Qa="accesspoint",Ja="accessPointName",Xa="{url#scheme}://{accessPointName}-{bucketArn#accountId}.{url#authority}{url#path}",Za="mrapPartition",Ya="outpostType",ec="arnPrefix",tc="{url#scheme}://{url#authority}{url#normalizedPath}{uri_encoded_bucket}",rc="https://s3.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",nc="https://s3.{partitionResult#dnsSuffix}",ic={[ea]:!1,[ta]:"String"},oc={[ea]:!0,default:!1,[ta]:"Boolean"},sc={[ea]:!1,[ta]:"Boolean"},ac={[na]:va,[ia]:[{[oa]:"Accelerate"},!0]},cc={[na]:va,[ia]:[{[oa]:"UseFIPS"},!0]},uc={[na]:va,[ia]:[{[oa]:"UseDualStack"},!0]},dc={[na]:ya,[ia]:[{[oa]:"Endpoint"}]},lc={[na]:wa,[ia]:[{[oa]:"Region"}],[sa]:"partitionResult"},hc={[na]:ka,[ia]:[{[na]:Sa,[ia]:[{[oa]:"partitionResult"},Ea]},"aws-cn"]},fc={[na]:ya,[ia]:[{[oa]:"Bucket"}]},pc={[oa]:"Bucket"},gc={[na]:Ta,[ia]:[{[oa]:"Endpoint"}],[sa]:"url"},mc={[na]:va,[ia]:[{[na]:Sa,[ia]:[{[oa]:"url"},"isIp"]},!0]},yc={[oa]:"url"},vc={[na]:"uriEncode",[ia]:[pc],[sa]:"uri_encoded_bucket"},bc={[ua]:"S3Express",[da]:[{[la]:!0,[Ea]:"sigv4",[ha]:"s3express",[fa]:"{Region}"}]},wc={},kc={[na]:Pa,[ia]:[pc,!1]},Sc={[ba]:"S3Express bucket name is not a valid virtual hostable name.",[ta]:ba},Ec={[ua]:"S3Express",[da]:[{[la]:!0,[Ea]:"sigv4-s3express",[ha]:"s3express",[fa]:"{Region}"}]},xc={[na]:ya,[ia]:[{[oa]:"UseS3ExpressControlEndpoint"}]},Ac={[na]:va,[ia]:[{[oa]:"UseS3ExpressControlEndpoint"},!0]},Tc={[na]:Ma,[ia]:[dc]},Cc={[ba]:"Unrecognized S3Express bucket name format.",[ta]:ba},Rc={[na]:Ma,[ia]:[fc]},Oc={[oa]:Na},Pc={[ra]:[Tc],[ba]:"Expected a endpoint to be specified but no endpoint was found",[ta]:ba},_c={[da]:[{[la]:!0,[Ea]:Ba,[ha]:Da,[ga]:["*"]},{[la]:!0,[Ea]:"sigv4",[ha]:Da,[fa]:"{Region}"}]},Mc={[na]:va,[ia]:[{[oa]:"ForcePathStyle"},!1]},Ic={[oa]:"ForcePathStyle"},Nc={[na]:va,[ia]:[{[oa]:"Accelerate"},!1]},Fc={[na]:ka,[ia]:[{[oa]:"Region"},"aws-global"]},$c={[da]:[{[la]:!0,[Ea]:"sigv4",[ha]:ja,[fa]:"us-east-1"}]},Uc={[na]:Ma,[ia]:[Fc]},Lc={[na]:va,[ia]:[{[oa]:"UseGlobalEndpoint"},!0]},Bc={[aa]:"https://{Bucket}.s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[ca]:{[da]:[{[la]:!0,[Ea]:"sigv4",[ha]:ja,[fa]:"{Region}"}]},[pa]:{}},Dc={[da]:[{[la]:!0,[Ea]:"sigv4",[ha]:ja,[fa]:"{Region}"}]},jc={[na]:va,[ia]:[{[oa]:"UseGlobalEndpoint"},!1]},zc={[na]:va,[ia]:[{[oa]:"UseDualStack"},!1]},qc={[aa]:"https://{Bucket}.s3-fips.{Region}.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Hc={[na]:va,[ia]:[{[oa]:"UseFIPS"},!1]},Wc={[aa]:"https://{Bucket}.s3-accelerate.dualstack.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Kc={[aa]:"https://{Bucket}.s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Vc={[na]:va,[ia]:[{[na]:Sa,[ia]:[yc,"isIp"]},!1]},Gc={[aa]:za,[ca]:Dc,[pa]:{}},Qc={[aa]:_a,[ca]:Dc,[pa]:{}},Jc={[Ra]:Qc,[ta]:Ra},Xc={[aa]:qa,[ca]:Dc,[pa]:{}},Zc={[aa]:"https://{Bucket}.s3.{Region}.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Yc={[ba]:"Invalid region: region was not a valid DNS name.",[ta]:ba},eu={[oa]:Ka},tu={[oa]:Va},ru={[na]:Sa,[ia]:[eu,"service"]},nu={[oa]:Ja},iu={[ra]:[uc],[ba]:"S3 Object Lambda does not support Dual-stack",[ta]:ba},ou={[ra]:[ac],[ba]:"S3 Object Lambda does not support S3 Accelerate",[ta]:ba},su={[ra]:[{[na]:ya,[ia]:[{[oa]:"DisableAccessPoints"}]},{[na]:va,[ia]:[{[oa]:"DisableAccessPoints"},!0]}],[ba]:"Access points are not supported for this operation",[ta]:ba},au={[ra]:[{[na]:ya,[ia]:[{[oa]:"UseArnRegion"}]},{[na]:va,[ia]:[{[oa]:"UseArnRegion"},!1]},{[na]:Ma,[ia]:[{[na]:ka,[ia]:[{[na]:Sa,[ia]:[eu,"region"]},"{Region}"]}]}],[ba]:"Invalid configuration: region from ARN `{bucketArn#region}` does not match client region `{Region}` and UseArnRegion is `false`",[ta]:ba},cu={[na]:Sa,[ia]:[{[oa]:"bucketPartition"},Ea]},uu={[na]:Sa,[ia]:[eu,"accountId"]},du={[da]:[{[la]:!0,[Ea]:"sigv4",[ha]:Ga,[fa]:"{bucketArn#region}"}]},lu={[ba]:"Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `{accessPointName}`",[ta]:ba},hu={[ba]:"Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `{bucketArn#accountId}`",[ta]:ba},fu={[ba]:"Invalid region in ARN: `{bucketArn#region}` (invalid DNS name)",[ta]:ba},pu={[ba]:"Client was configured for partition `{partitionResult#name}` but ARN (`{Bucket}`) has `{bucketPartition#name}`",[ta]:ba},gu={[ba]:"Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.",[ta]:ba},mu={[ba]:"Invalid ARN: Expected a resource of the format `accesspoint:` but no name was provided",[ta]:ba},yu={[da]:[{[la]:!0,[Ea]:"sigv4",[ha]:ja,[fa]:"{bucketArn#region}"}]},vu={[da]:[{[la]:!0,[Ea]:Ba,[ha]:Da,[ga]:["*"]},{[la]:!0,[Ea]:"sigv4",[ha]:Da,[fa]:"{bucketArn#region}"}]},bu={[na]:Wa,[ia]:[pc]},wu={[aa]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ca]:Dc,[pa]:{}},ku={[aa]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ca]:Dc,[pa]:{}},Su={[aa]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ca]:Dc,[pa]:{}},Eu={[aa]:tc,[ca]:Dc,[pa]:{}},xu={[aa]:"https://s3.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ca]:Dc,[pa]:{}},Au={[oa]:"UseObjectLambdaEndpoint"},Tu={[da]:[{[la]:!0,[Ea]:"sigv4",[ha]:Ga,[fa]:"{Region}"}]},Cu={[aa]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Ru={[aa]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Ou={[aa]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Pu={[aa]:Ia,[ca]:Dc,[pa]:{}},_u={[aa]:"https://s3.{Region}.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Mu=[{[oa]:"Region"}],Iu=[{[oa]:"Endpoint"}],Nu=[pc],Fu=[uc],$u=[ac],Uu=[dc,gc],Lu=[{[na]:ya,[ia]:[{[oa]:"DisableS3ExpressSessionAuth"}]},{[na]:va,[ia]:[{[oa]:"DisableS3ExpressSessionAuth"},!0]}],Bu=[mc],Du=[vc],ju=[kc],zu=[cc],qu=[{[na]:xa,[ia]:[pc,6,14,!0],[sa]:"s3expressAvailabilityZoneId"},{[na]:xa,[ia]:[pc,14,16,!0],[sa]:"s3expressAvailabilityZoneDelim"},{[na]:ka,[ia]:[{[oa]:"s3expressAvailabilityZoneDelim"},"--"]}],Hu=[{[ra]:[cc],[Ra]:{[aa]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[ca]:bc,[pa]:{}},[ta]:Ra},{[Ra]:{[aa]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[ca]:bc,[pa]:{}},[ta]:Ra}],Wu=[{[na]:xa,[ia]:[pc,6,15,!0],[sa]:"s3expressAvailabilityZoneId"},{[na]:xa,[ia]:[pc,15,17,!0],[sa]:"s3expressAvailabilityZoneDelim"},{[na]:ka,[ia]:[{[oa]:"s3expressAvailabilityZoneDelim"},"--"]}],Ku=[{[ra]:[cc],[Ra]:{[aa]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[ca]:Ec,[pa]:{}},[ta]:Ra},{[Ra]:{[aa]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[ca]:Ec,[pa]:{}},[ta]:Ra}],Vu=[fc],Gu=[{[na]:La,[ia]:[{[oa]:Ua},!1]}],Qu=[{[na]:ka,[ia]:[{[oa]:Fa},"beta"]}],Ju=[lc],Xu=[{[na]:La,[ia]:[{[oa]:"Region"},!1]}],Zu=[{[na]:ka,[ia]:[{[oa]:"Region"},"us-east-1"]}],Yu=[{[na]:ka,[ia]:[tu,Qa]}],ed=[{[na]:Sa,[ia]:[eu,"resourceId[1]"],[sa]:Ja},{[na]:Ma,[ia]:[{[na]:ka,[ia]:[nu,""]}]}],td=[eu,"resourceId[1]"],rd=[{[na]:Ma,[ia]:[{[na]:ka,[ia]:[{[na]:Sa,[ia]:[eu,"region"]},""]}]}],nd=[{[na]:Ma,[ia]:[{[na]:ya,[ia]:[{[na]:Sa,[ia]:[eu,"resourceId[2]"]}]}]}],id=[eu,"resourceId[2]"],od=[{[na]:wa,[ia]:[{[na]:Sa,[ia]:[eu,"region"]}],[sa]:"bucketPartition"}],sd=[{[na]:ka,[ia]:[cu,{[na]:Sa,[ia]:[{[oa]:"partitionResult"},Ea]}]}],ad=[{[na]:La,[ia]:[{[na]:Sa,[ia]:[eu,"region"]},!0]}],cd=[{[na]:La,[ia]:[uu,!1]}],ud=[{[na]:La,[ia]:[nu,!1]}],dd=[{[na]:La,[ia]:[{[oa]:"Region"},!0]}],ld={version:"1.0",parameters:{Bucket:ic,Region:ic,UseFIPS:oc,UseDualStack:oc,Endpoint:ic,ForcePathStyle:oc,Accelerate:oc,UseGlobalEndpoint:oc,UseObjectLambdaEndpoint:sc,Key:ic,Prefix:ic,CopySource:ic,DisableAccessPoints:sc,DisableMultiRegionAccessPoints:oc,UseArnRegion:sc,UseS3ExpressControlEndpoint:sc,DisableS3ExpressSessionAuth:sc},rules:[{[ra]:[{[na]:ya,[ia]:Mu}],rules:[{[ra]:[ac,cc],error:"Accelerate cannot be used with FIPS",[ta]:ba},{[ra]:[uc,dc],error:"Cannot set dual-stack in combination with a custom endpoint.",[ta]:ba},{[ra]:[dc,cc],error:"A custom endpoint cannot be combined with FIPS",[ta]:ba},{[ra]:[dc,ac],error:"A custom endpoint cannot be combined with S3 Accelerate",[ta]:ba},{[ra]:[cc,lc,hc],error:"Partition does not support FIPS",[ta]:ba},{[ra]:[fc,{[na]:xa,[ia]:[pc,0,6,ma],[sa]:Aa},{[na]:ka,[ia]:[{[oa]:Aa},"--x-s3"]}],rules:[{[ra]:Fu,error:"S3Express does not support Dual-stack.",[ta]:ba},{[ra]:$u,error:"S3Express does not support S3 Accelerate.",[ta]:ba},{[ra]:Uu,rules:[{[ra]:Lu,rules:[{[ra]:Bu,rules:[{[ra]:Du,rules:[{endpoint:{[aa]:Ca,[ca]:bc,[pa]:wc},[ta]:Ra}],[ta]:Oa}],[ta]:Oa},{[ra]:ju,rules:[{endpoint:{[aa]:_a,[ca]:bc,[pa]:wc},[ta]:Ra}],[ta]:Oa},Sc],[ta]:Oa},{[ra]:Bu,rules:[{[ra]:Du,rules:[{endpoint:{[aa]:Ca,[ca]:Ec,[pa]:wc},[ta]:Ra}],[ta]:Oa}],[ta]:Oa},{[ra]:ju,rules:[{endpoint:{[aa]:_a,[ca]:Ec,[pa]:wc},[ta]:Ra}],[ta]:Oa},Sc],[ta]:Oa},{[ra]:[xc,Ac],rules:[{[ra]:[vc,Tc],rules:[{[ra]:zu,endpoint:{[aa]:"https://s3express-control-fips.{Region}.amazonaws.com/{uri_encoded_bucket}",[ca]:bc,[pa]:wc},[ta]:Ra},{endpoint:{[aa]:"https://s3express-control.{Region}.amazonaws.com/{uri_encoded_bucket}",[ca]:bc,[pa]:wc},[ta]:Ra}],[ta]:Oa}],[ta]:Oa},{[ra]:ju,rules:[{[ra]:Lu,rules:[{[ra]:qu,rules:Hu,[ta]:Oa},{[ra]:Wu,rules:Hu,[ta]:Oa},Cc],[ta]:Oa},{[ra]:qu,rules:Ku,[ta]:Oa},{[ra]:Wu,rules:Ku,[ta]:Oa},Cc],[ta]:Oa},Sc],[ta]:Oa},{[ra]:[Rc,xc,Ac],rules:[{[ra]:Uu,endpoint:{[aa]:Ia,[ca]:bc,[pa]:wc},[ta]:Ra},{[ra]:zu,endpoint:{[aa]:"https://s3express-control-fips.{Region}.amazonaws.com",[ca]:bc,[pa]:wc},[ta]:Ra},{endpoint:{[aa]:"https://s3express-control.{Region}.amazonaws.com",[ca]:bc,[pa]:wc},[ta]:Ra}],[ta]:Oa},{[ra]:[fc,{[na]:xa,[ia]:[pc,49,50,ma],[sa]:Na},{[na]:xa,[ia]:[pc,8,12,ma],[sa]:Fa},{[na]:xa,[ia]:[pc,0,7,ma],[sa]:$a},{[na]:xa,[ia]:[pc,32,49,ma],[sa]:Ua},{[na]:wa,[ia]:Mu,[sa]:"regionPartition"},{[na]:ka,[ia]:[{[oa]:$a},"--op-s3"]}],rules:[{[ra]:Gu,rules:[{[ra]:[{[na]:ka,[ia]:[Oc,"e"]}],rules:[{[ra]:Qu,rules:[Pc,{[ra]:Uu,endpoint:{[aa]:"https://{Bucket}.ec2.{url#authority}",[ca]:_c,[pa]:wc},[ta]:Ra}],[ta]:Oa},{endpoint:{[aa]:"https://{Bucket}.ec2.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[ca]:_c,[pa]:wc},[ta]:Ra}],[ta]:Oa},{[ra]:[{[na]:ka,[ia]:[Oc,"o"]}],rules:[{[ra]:Qu,rules:[Pc,{[ra]:Uu,endpoint:{[aa]:"https://{Bucket}.op-{outpostId}.{url#authority}",[ca]:_c,[pa]:wc},[ta]:Ra}],[ta]:Oa},{endpoint:{[aa]:"https://{Bucket}.op-{outpostId}.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[ca]:_c,[pa]:wc},[ta]:Ra}],[ta]:Oa},{error:'Unrecognized hardware type: "Expected hardware type o or e but got {hardwareType}"',[ta]:ba}],[ta]:Oa},{error:"Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`.",[ta]:ba}],[ta]:Oa},{[ra]:Vu,rules:[{[ra]:[dc,{[na]:Ma,[ia]:[{[na]:ya,[ia]:[{[na]:Ta,[ia]:Iu}]}]}],error:"Custom endpoint `{Endpoint}` was not a valid URI",[ta]:ba},{[ra]:[Mc,kc],rules:[{[ra]:Ju,rules:[{[ra]:Xu,rules:[{[ra]:[ac,hc],error:"S3 Accelerate cannot be used in this region",[ta]:ba},{[ra]:[uc,cc,Nc,Tc,Fc],endpoint:{[aa]:"https://{Bucket}.s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[uc,cc,Nc,Tc,Uc,Lc],rules:[{endpoint:Bc,[ta]:Ra}],[ta]:Oa},{[ra]:[uc,cc,Nc,Tc,Uc,jc],endpoint:Bc,[ta]:Ra},{[ra]:[zc,cc,Nc,Tc,Fc],endpoint:{[aa]:"https://{Bucket}.s3-fips.us-east-1.{partitionResult#dnsSuffix}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,cc,Nc,Tc,Uc,Lc],rules:[{endpoint:qc,[ta]:Ra}],[ta]:Oa},{[ra]:[zc,cc,Nc,Tc,Uc,jc],endpoint:qc,[ta]:Ra},{[ra]:[uc,Hc,ac,Tc,Fc],endpoint:{[aa]:"https://{Bucket}.s3-accelerate.dualstack.us-east-1.{partitionResult#dnsSuffix}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[uc,Hc,ac,Tc,Uc,Lc],rules:[{endpoint:Wc,[ta]:Ra}],[ta]:Oa},{[ra]:[uc,Hc,ac,Tc,Uc,jc],endpoint:Wc,[ta]:Ra},{[ra]:[uc,Hc,Nc,Tc,Fc],endpoint:{[aa]:"https://{Bucket}.s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[uc,Hc,Nc,Tc,Uc,Lc],rules:[{endpoint:Kc,[ta]:Ra}],[ta]:Oa},{[ra]:[uc,Hc,Nc,Tc,Uc,jc],endpoint:Kc,[ta]:Ra},{[ra]:[zc,Hc,Nc,dc,gc,mc,Fc],endpoint:{[aa]:za,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,Hc,Nc,dc,gc,Vc,Fc],endpoint:{[aa]:_a,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,Hc,Nc,dc,gc,mc,Uc,Lc],rules:[{[ra]:Zu,endpoint:Gc,[ta]:Ra},{endpoint:Gc,[ta]:Ra}],[ta]:Oa},{[ra]:[zc,Hc,Nc,dc,gc,Vc,Uc,Lc],rules:[{[ra]:Zu,endpoint:Qc,[ta]:Ra},Jc],[ta]:Oa},{[ra]:[zc,Hc,Nc,dc,gc,mc,Uc,jc],endpoint:Gc,[ta]:Ra},{[ra]:[zc,Hc,Nc,dc,gc,Vc,Uc,jc],endpoint:Qc,[ta]:Ra},{[ra]:[zc,Hc,ac,Tc,Fc],endpoint:{[aa]:qa,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,Hc,ac,Tc,Uc,Lc],rules:[{[ra]:Zu,endpoint:Xc,[ta]:Ra},{endpoint:Xc,[ta]:Ra}],[ta]:Oa},{[ra]:[zc,Hc,ac,Tc,Uc,jc],endpoint:Xc,[ta]:Ra},{[ra]:[zc,Hc,Nc,Tc,Fc],endpoint:{[aa]:Ha,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,Hc,Nc,Tc,Uc,Lc],rules:[{[ra]:Zu,endpoint:{[aa]:Ha,[ca]:Dc,[pa]:wc},[ta]:Ra},{endpoint:Zc,[ta]:Ra}],[ta]:Oa},{[ra]:[zc,Hc,Nc,Tc,Uc,jc],endpoint:Zc,[ta]:Ra}],[ta]:Oa},Yc],[ta]:Oa}],[ta]:Oa},{[ra]:[dc,gc,{[na]:ka,[ia]:[{[na]:Sa,[ia]:[yc,"scheme"]},"http"]},{[na]:Pa,[ia]:[pc,ma]},Mc,Hc,zc,Nc],rules:[{[ra]:Ju,rules:[{[ra]:Xu,rules:[Jc],[ta]:Oa},Yc],[ta]:Oa}],[ta]:Oa},{[ra]:[Mc,{[na]:Wa,[ia]:Nu,[sa]:Ka}],rules:[{[ra]:[{[na]:Sa,[ia]:[eu,"resourceId[0]"],[sa]:Va},{[na]:Ma,[ia]:[{[na]:ka,[ia]:[tu,""]}]}],rules:[{[ra]:[{[na]:ka,[ia]:[ru,Ga]}],rules:[{[ra]:Yu,rules:[{[ra]:ed,rules:[iu,ou,{[ra]:rd,rules:[su,{[ra]:nd,rules:[au,{[ra]:od,rules:[{[ra]:Ju,rules:[{[ra]:sd,rules:[{[ra]:ad,rules:[{[ra]:[{[na]:ka,[ia]:[uu,""]}],error:"Invalid ARN: Missing account id",[ta]:ba},{[ra]:cd,rules:[{[ra]:ud,rules:[{[ra]:Uu,endpoint:{[aa]:Xa,[ca]:du,[pa]:wc},[ta]:Ra},{[ra]:zu,endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ca]:du,[pa]:wc},[ta]:Ra},{endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ca]:du,[pa]:wc},[ta]:Ra}],[ta]:Oa},lu],[ta]:Oa},hu],[ta]:Oa},fu],[ta]:Oa},pu],[ta]:Oa}],[ta]:Oa}],[ta]:Oa},gu],[ta]:Oa},{error:"Invalid ARN: bucket ARN is missing a region",[ta]:ba}],[ta]:Oa},mu],[ta]:Oa},{error:"Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `{arnType}`",[ta]:ba}],[ta]:Oa},{[ra]:Yu,rules:[{[ra]:ed,rules:[{[ra]:rd,rules:[{[ra]:Yu,rules:[{[ra]:rd,rules:[su,{[ra]:nd,rules:[au,{[ra]:od,rules:[{[ra]:Ju,rules:[{[ra]:[{[na]:ka,[ia]:[cu,"{partitionResult#name}"]}],rules:[{[ra]:ad,rules:[{[ra]:[{[na]:ka,[ia]:[ru,ja]}],rules:[{[ra]:cd,rules:[{[ra]:ud,rules:[{[ra]:$u,error:"Access Points do not support S3 Accelerate",[ta]:ba},{[ra]:[cc,uc],endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ca]:yu,[pa]:wc},[ta]:Ra},{[ra]:[cc,zc],endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ca]:yu,[pa]:wc},[ta]:Ra},{[ra]:[Hc,uc],endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ca]:yu,[pa]:wc},[ta]:Ra},{[ra]:[Hc,zc,dc,gc],endpoint:{[aa]:Xa,[ca]:yu,[pa]:wc},[ta]:Ra},{[ra]:[Hc,zc],endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ca]:yu,[pa]:wc},[ta]:Ra}],[ta]:Oa},lu],[ta]:Oa},hu],[ta]:Oa},{error:"Invalid ARN: The ARN was not for the S3 service, found: {bucketArn#service}",[ta]:ba}],[ta]:Oa},fu],[ta]:Oa},pu],[ta]:Oa}],[ta]:Oa}],[ta]:Oa},gu],[ta]:Oa}],[ta]:Oa}],[ta]:Oa},{[ra]:[{[na]:La,[ia]:[nu,ma]}],rules:[{[ra]:Fu,error:"S3 MRAP does not support dual-stack",[ta]:ba},{[ra]:zu,error:"S3 MRAP does not support FIPS",[ta]:ba},{[ra]:$u,error:"S3 MRAP does not support S3 Accelerate",[ta]:ba},{[ra]:[{[na]:va,[ia]:[{[oa]:"DisableMultiRegionAccessPoints"},ma]}],error:"Invalid configuration: Multi-Region Access Point ARNs are disabled.",[ta]:ba},{[ra]:[{[na]:wa,[ia]:Mu,[sa]:Za}],rules:[{[ra]:[{[na]:ka,[ia]:[{[na]:Sa,[ia]:[{[oa]:Za},Ea]},{[na]:Sa,[ia]:[eu,"partition"]}]}],rules:[{endpoint:{[aa]:"https://{accessPointName}.accesspoint.s3-global.{mrapPartition#dnsSuffix}",[ca]:{[da]:[{[la]:ma,name:Ba,[ha]:ja,[ga]:["*"]}]},[pa]:wc},[ta]:Ra}],[ta]:Oa},{error:"Client was configured for partition `{mrapPartition#name}` but bucket referred to partition `{bucketArn#partition}`",[ta]:ba}],[ta]:Oa}],[ta]:Oa},{error:"Invalid Access Point Name",[ta]:ba}],[ta]:Oa},mu],[ta]:Oa},{[ra]:[{[na]:ka,[ia]:[ru,Da]}],rules:[{[ra]:Fu,error:"S3 Outposts does not support Dual-stack",[ta]:ba},{[ra]:zu,error:"S3 Outposts does not support FIPS",[ta]:ba},{[ra]:$u,error:"S3 Outposts does not support S3 Accelerate",[ta]:ba},{[ra]:[{[na]:ya,[ia]:[{[na]:Sa,[ia]:[eu,"resourceId[4]"]}]}],error:"Invalid Arn: Outpost Access Point ARN contains sub resources",[ta]:ba},{[ra]:[{[na]:Sa,[ia]:td,[sa]:Ua}],rules:[{[ra]:Gu,rules:[au,{[ra]:od,rules:[{[ra]:Ju,rules:[{[ra]:sd,rules:[{[ra]:ad,rules:[{[ra]:cd,rules:[{[ra]:[{[na]:Sa,[ia]:id,[sa]:Ya}],rules:[{[ra]:[{[na]:Sa,[ia]:[eu,"resourceId[3]"],[sa]:Ja}],rules:[{[ra]:[{[na]:ka,[ia]:[{[oa]:Ya},Qa]}],rules:[{[ra]:Uu,endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.{url#authority}",[ca]:vu,[pa]:wc},[ta]:Ra},{endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.s3-outposts.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ca]:vu,[pa]:wc},[ta]:Ra}],[ta]:Oa},{error:"Expected an outpost type `accesspoint`, found {outpostType}",[ta]:ba}],[ta]:Oa},{error:"Invalid ARN: expected an access point name",[ta]:ba}],[ta]:Oa},{error:"Invalid ARN: Expected a 4-component resource",[ta]:ba}],[ta]:Oa},hu],[ta]:Oa},fu],[ta]:Oa},pu],[ta]:Oa}],[ta]:Oa}],[ta]:Oa},{error:"Invalid ARN: The outpost Id may only contain a-z, A-Z, 0-9 and `-`. Found: `{outpostId}`",[ta]:ba}],[ta]:Oa},{error:"Invalid ARN: The Outpost Id was not set",[ta]:ba}],[ta]:Oa},{error:"Invalid ARN: Unrecognized format: {Bucket} (type: {arnType})",[ta]:ba}],[ta]:Oa},{error:"Invalid ARN: No ARN type specified",[ta]:ba}],[ta]:Oa},{[ra]:[{[na]:xa,[ia]:[pc,0,4,!1],[sa]:ec},{[na]:ka,[ia]:[{[oa]:ec},"arn:"]},{[na]:Ma,[ia]:[{[na]:ya,[ia]:[bu]}]}],error:"Invalid ARN: `{Bucket}` was not a valid ARN",[ta]:ba},{[ra]:[{[na]:va,[ia]:[Ic,ma]},bu],error:"Path-style addressing cannot be used with ARN buckets",[ta]:ba},{[ra]:Du,rules:[{[ra]:Ju,rules:[{[ra]:[Nc],rules:[{[ra]:[uc,Tc,cc,Fc],endpoint:{[aa]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[uc,Tc,cc,Uc,Lc],rules:[{endpoint:wu,[ta]:Ra}],[ta]:Oa},{[ra]:[uc,Tc,cc,Uc,jc],endpoint:wu,[ta]:Ra},{[ra]:[zc,Tc,cc,Fc],endpoint:{[aa]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,Tc,cc,Uc,Lc],rules:[{endpoint:ku,[ta]:Ra}],[ta]:Oa},{[ra]:[zc,Tc,cc,Uc,jc],endpoint:ku,[ta]:Ra},{[ra]:[uc,Tc,Hc,Fc],endpoint:{[aa]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[uc,Tc,Hc,Uc,Lc],rules:[{endpoint:Su,[ta]:Ra}],[ta]:Oa},{[ra]:[uc,Tc,Hc,Uc,jc],endpoint:Su,[ta]:Ra},{[ra]:[zc,dc,gc,Hc,Fc],endpoint:{[aa]:tc,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,dc,gc,Hc,Uc,Lc],rules:[{[ra]:Zu,endpoint:Eu,[ta]:Ra},{endpoint:Eu,[ta]:Ra}],[ta]:Oa},{[ra]:[zc,dc,gc,Hc,Uc,jc],endpoint:Eu,[ta]:Ra},{[ra]:[zc,Tc,Hc,Fc],endpoint:{[aa]:rc,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,Tc,Hc,Uc,Lc],rules:[{[ra]:Zu,endpoint:{[aa]:rc,[ca]:Dc,[pa]:wc},[ta]:Ra},{endpoint:xu,[ta]:Ra}],[ta]:Oa},{[ra]:[zc,Tc,Hc,Uc,jc],endpoint:xu,[ta]:Ra}],[ta]:Oa},{error:"Path-style addressing cannot be used with S3 Accelerate",[ta]:ba}],[ta]:Oa}],[ta]:Oa}],[ta]:Oa},{[ra]:[{[na]:ya,[ia]:[Au]},{[na]:va,[ia]:[Au,ma]}],rules:[{[ra]:Ju,rules:[{[ra]:dd,rules:[iu,ou,{[ra]:Uu,endpoint:{[aa]:Ia,[ca]:Tu,[pa]:wc},[ta]:Ra},{[ra]:zu,endpoint:{[aa]:"https://s3-object-lambda-fips.{Region}.{partitionResult#dnsSuffix}",[ca]:Tu,[pa]:wc},[ta]:Ra},{endpoint:{[aa]:"https://s3-object-lambda.{Region}.{partitionResult#dnsSuffix}",[ca]:Tu,[pa]:wc},[ta]:Ra}],[ta]:Oa},Yc],[ta]:Oa}],[ta]:Oa},{[ra]:[Rc],rules:[{[ra]:Ju,rules:[{[ra]:dd,rules:[{[ra]:[cc,uc,Tc,Fc],endpoint:{[aa]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[cc,uc,Tc,Uc,Lc],rules:[{endpoint:Cu,[ta]:Ra}],[ta]:Oa},{[ra]:[cc,uc,Tc,Uc,jc],endpoint:Cu,[ta]:Ra},{[ra]:[cc,zc,Tc,Fc],endpoint:{[aa]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[cc,zc,Tc,Uc,Lc],rules:[{endpoint:Ru,[ta]:Ra}],[ta]:Oa},{[ra]:[cc,zc,Tc,Uc,jc],endpoint:Ru,[ta]:Ra},{[ra]:[Hc,uc,Tc,Fc],endpoint:{[aa]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[Hc,uc,Tc,Uc,Lc],rules:[{endpoint:Ou,[ta]:Ra}],[ta]:Oa},{[ra]:[Hc,uc,Tc,Uc,jc],endpoint:Ou,[ta]:Ra},{[ra]:[Hc,zc,dc,gc,Fc],endpoint:{[aa]:Ia,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[Hc,zc,dc,gc,Uc,Lc],rules:[{[ra]:Zu,endpoint:Pu,[ta]:Ra},{endpoint:Pu,[ta]:Ra}],[ta]:Oa},{[ra]:[Hc,zc,dc,gc,Uc,jc],endpoint:Pu,[ta]:Ra},{[ra]:[Hc,zc,Tc,Fc],endpoint:{[aa]:nc,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[Hc,zc,Tc,Uc,Lc],rules:[{[ra]:Zu,endpoint:{[aa]:nc,[ca]:Dc,[pa]:wc},[ta]:Ra},{endpoint:_u,[ta]:Ra}],[ta]:Oa},{[ra]:[Hc,zc,Tc,Uc,jc],endpoint:_u,[ta]:Ra}],[ta]:Oa},Yc],[ta]:Oa}],[ta]:Oa}],[ta]:Oa},{error:"A region must be set when sending requests to S3.",[ta]:ba}]},hd=new class{constructor({size:e,params:t}){this.data=new Map,this.parameters=[],this.capacity=e??50,t&&(this.parameters=t)}get(e,t){const r=this.hash(e);if(!1===r)return t();if(!this.data.has(r)){if(this.data.size>this.capacity+10){const e=this.data.keys();let t=0;for(;;){const{value:r,done:n}=e.next();if(this.data.delete(r),n||++t>10)break}}this.data.set(r,t())}return this.data.get(r)}size(){return this.data.size}hash(e){let t="";const{parameters:r}=this;if(0===r.length)return!1;for(const n of r){const r=String(e[n]??"");if(r.includes("|;"))return!1;t+=r+"|;"}return t}}({size:50,params:["Accelerate","Bucket","DisableAccessPoints","DisableMultiRegionAccessPoints","DisableS3ExpressSessionAuth","Endpoint","ForcePathStyle","Region","UseArnRegion","UseDualStack","UseFIPS","UseGlobalEndpoint","UseObjectLambdaEndpoint","UseS3ExpressControlEndpoint"]}),fd=(e,t={})=>hd.get(e,(()=>((e,t)=>{const{endpointParams:r,logger:n}=t,{parameters:i,rules:o}=e;t.logger?.debug?.(`${Io} Initial EndpointParams: ${No(r)}`);const s=Object.entries(i).filter((([,e])=>null!=e.default)).map((([e,t])=>[e,t.default]));if(s.length>0)for(const[e,t]of s)r[e]=r[e]??t;const a=Object.entries(i).filter((([,e])=>e.required)).map((([e])=>e));for(const e of a)if(null==r[e])throw new Fo(`Missing required parameter: '${e}'`);const c=Xo(o,{endpointParams:r,logger:n,referenceRecord:{}});return t.logger?.debug?.(`${Io} Resolved endpoint: ${No(c)}`),c})(ld,{endpointParams:e,logger:t.logger})));Mo.aws=es;const pd=(gd=async(e,t,r)=>({operation:ae(t).operation,region:await ce(e.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()}),async(e,t,r)=>{if(!r)throw new Error("Could not find `input` for `defaultEndpointRuleSetHttpAuthSchemeParametersProvider`");const n=await gd(e,t,r),i=ae(t)?.commandInstance?.constructor?.getEndpointParameterInstructions;if(!i)throw new Error(`getEndpointParameterInstructions() is not defined on \`${t.commandName}\``);const o=await Es(r,{getEndpointParameterInstructions:i},e);return Object.assign(n,o)});var gd;function md(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"s3",region:e.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}function yd(e){return{schemeId:"aws.auth#sigv4a",signingProperties:{name:"s3",region:e.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}const vd=((e,t,r)=>n=>{const i=e(n),o=i.properties?.authSchemes;if(!o)return t(n);const s=[];for(const e of o){const{name:t,properties:i={},...a}=e,c=t.toLowerCase();let u;if(t!==c&&console.warn(`HttpAuthScheme has been normalized with lowercasing: \`${t}\` to \`${c}\``),"sigv4a"===c){u="aws.auth#sigv4a";const e=o.find((e=>{const t=e.name.toLowerCase();return"sigv4a"!==t&&t.startsWith("sigv4")}));if(e)continue}else{if(!c.startsWith("sigv4"))throw new Error(`Unknown HttpAuthScheme found in \`@smithy.rules#endpointRuleSet\`: \`${c}\``);u="aws.auth#sigv4"}const d=r[u];if(!d)throw new Error(`Could not find HttpAuthOption create function for \`${u}\``);const l=d(n);l.schemeId=u,l.signingProperties={...l.signingProperties||{},...a,...i},s.push(l)}return s})(fd,(e=>{const t=[];return e.operation,t.push(md(e)),t.push(yd(e)),t}),{"aws.auth#sigv4":md,"aws.auth#sigv4a":yd}),bd=e=>{const t=(e=>(e.sigv4aSigningRegionSet=ve(e.sigv4aSigningRegionSet),e))(Mt(e));return{...t}},wd={ForcePathStyle:{type:"clientContextParams",name:"forcePathStyle"},UseArnRegion:{type:"clientContextParams",name:"useArnRegion"},DisableMultiRegionAccessPoints:{type:"clientContextParams",name:"disableMultiregionAccessPoints"},Accelerate:{type:"clientContextParams",name:"useAccelerateEndpoint"},DisableS3ExpressSessionAuth:{type:"clientContextParams",name:"disableS3ExpressSessionAuth"},UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};class kd extends Cr{constructor(e){super(e),Object.setPrototypeOf(this,kd.prototype)}}class Sd extends kd{constructor(e){super({name:"NoSuchUpload",$fault:"client",...e}),this.name="NoSuchUpload",this.$fault="client",Object.setPrototypeOf(this,Sd.prototype)}}class Ed extends kd{constructor(e){super({name:"ObjectNotInActiveTierError",$fault:"client",...e}),this.name="ObjectNotInActiveTierError",this.$fault="client",Object.setPrototypeOf(this,Ed.prototype)}}class xd extends kd{constructor(e){super({name:"BucketAlreadyExists",$fault:"client",...e}),this.name="BucketAlreadyExists",this.$fault="client",Object.setPrototypeOf(this,xd.prototype)}}class Ad extends kd{constructor(e){super({name:"BucketAlreadyOwnedByYou",$fault:"client",...e}),this.name="BucketAlreadyOwnedByYou",this.$fault="client",Object.setPrototypeOf(this,Ad.prototype)}}class Td extends kd{constructor(e){super({name:"NoSuchBucket",$fault:"client",...e}),this.name="NoSuchBucket",this.$fault="client",Object.setPrototypeOf(this,Td.prototype)}}var Cd,Rd;!function(e){e.visit=(e,t)=>void 0!==e.Prefix?t.Prefix(e.Prefix):void 0!==e.Tag?t.Tag(e.Tag):void 0!==e.And?t.And(e.And):t._(e.$unknown[0],e.$unknown[1])}(Cd||(Cd={})),function(e){e.visit=(e,t)=>void 0!==e.Prefix?t.Prefix(e.Prefix):void 0!==e.Tag?t.Tag(e.Tag):void 0!==e.AccessPointArn?t.AccessPointArn(e.AccessPointArn):void 0!==e.And?t.And(e.And):t._(e.$unknown[0],e.$unknown[1])}(Rd||(Rd={}));class Od extends kd{constructor(e){super({name:"InvalidObjectState",$fault:"client",...e}),this.name="InvalidObjectState",this.$fault="client",Object.setPrototypeOf(this,Od.prototype),this.StorageClass=e.StorageClass,this.AccessTier=e.AccessTier}}class Pd extends kd{constructor(e){super({name:"NoSuchKey",$fault:"client",...e}),this.name="NoSuchKey",this.$fault="client",Object.setPrototypeOf(this,Pd.prototype)}}class _d extends kd{constructor(e){super({name:"NotFound",$fault:"client",...e}),this.name="NotFound",this.$fault="client",Object.setPrototypeOf(this,_d.prototype)}}const Md=e=>({...e,...e.SecretAccessKey&&{SecretAccessKey:jt},...e.SessionToken&&{SessionToken:jt}}),Id=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:jt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:jt},...e.Credentials&&{Credentials:Md(e.Credentials)}}),Nd=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:jt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:jt}}),Fd=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:jt}}),$d=e=>({...e,...e.SSECustomerKey&&{SSECustomerKey:jt}});class Ud extends kd{constructor(e){super({name:"EncryptionTypeMismatch",$fault:"client",...e}),this.name="EncryptionTypeMismatch",this.$fault="client",Object.setPrototypeOf(this,Ud.prototype)}}class Ld extends kd{constructor(e){super({name:"InvalidRequest",$fault:"client",...e}),this.name="InvalidRequest",this.$fault="client",Object.setPrototypeOf(this,Ld.prototype)}}class Bd extends kd{constructor(e){super({name:"InvalidWriteOffset",$fault:"client",...e}),this.name="InvalidWriteOffset",this.$fault="client",Object.setPrototypeOf(this,Bd.prototype)}}class Dd extends kd{constructor(e){super({name:"TooManyParts",$fault:"client",...e}),this.name="TooManyParts",this.$fault="client",Object.setPrototypeOf(this,Dd.prototype)}}class jd extends kd{constructor(e){super({name:"ObjectAlreadyInActiveTierError",$fault:"client",...e}),this.name="ObjectAlreadyInActiveTierError",this.$fault="client",Object.setPrototypeOf(this,jd.prototype)}}var zd;!function(e){e.visit=(e,t)=>void 0!==e.Records?t.Records(e.Records):void 0!==e.Stats?t.Stats(e.Stats):void 0!==e.Progress?t.Progress(e.Progress):void 0!==e.Cont?t.Cont(e.Cont):void 0!==e.End?t.End(e.End):t._(e.$unknown[0],e.$unknown[1])}(zd||(zd={}));const qd=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:jt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:jt}}),Hd=e=>({...e,...e.SSECustomerKey&&{SSECustomerKey:jt},...e.SSEKMSKeyId&&{SSEKMSKeyId:jt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:jt}}),Wd=async(e,t)=>{const r=Ge(e,t),n=zr({},Br,{[Zf]:e[Qh],[Sp]:e[Jh],[Ep]:e[tf],[Ap]:e[ef],[xp]:[()=>Br(e[Ol]),()=>e[Ol].toString()]});r.bp("/"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1);const i=zr({[zf]:[,""]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Kd=async(e,t)=>{const r=Ge(e,t),n=zr({},Br,{[cp]:e[wh],[vp]:e[zh],[Kf]:[()=>Br(e[Rl]),()=>e[Rl].toString()],[tp]:e[Zl],[Tf]:e[uh],[sp]:[()=>Br(e[dh]),()=>ur(e[dh]).toString()],[ap]:[()=>Br(e[lh]),()=>e[lh].toString()]});r.bp("/{Key+}"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1),r.p("Key",(()=>e.Key),"{Key+}",!0);const i=zr({[Np]:[,"DeleteObject"],[Hf]:[,e[af]]});return r.m("DELETE").h(n).q(i).b(undefined),r.build()},Vd=async(e,t)=>{const r=Ge(e,t),n=zr({},Br,{[Tf]:e[uh],[Cf]:[()=>Br(e[hh]),()=>ur(e[hh]).toString()],[Rf]:e[fh],[Of]:[()=>Br(e[mh]),()=>ur(e[mh]).toString()],[Ff]:e[Ih],[Tp]:e[Xh],[Cp]:e[Zh],[Rp]:e[Yh],[vp]:e[zh],[tp]:e[Zl],[Qf]:e[Bl]});r.bp("/{Key+}"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1),r.p("Key",(()=>e.Key),"{Key+}",!0);const i=zr({[Np]:[,"GetObject"],[$f]:[,e[Fh]],[Uf]:[,e[$h]],[Lf]:[,e[Uh]],[Bf]:[,e[Lh]],[Df]:[,e[Bh]],[jf]:[()=>void 0!==e.ResponseExpires,()=>ur(e[Dh]).toString()],[Hf]:[,e[af]],[If]:[()=>void 0!==e.PartNumber,()=>e[Mh].toString()]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Gd=async(e,t)=>{const r=Ge(e,t),n=zr({},Br,{[vp]:e[zh],[tp]:e[Zl],[pp]:[()=>Br(e[Oh]),()=>(e[Oh]||[]).map(Vr).join(", ")]});r.bp("/"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1);const i=zr({[_f]:[,"2"],[wf]:[,e[Gl]],[Sf]:[,e[eh]],[Mf]:[()=>void 0!==e.MaxKeys,()=>e[kh].toString()],[Nf]:[,e[Ph]],[bf]:[,e[Kl]],[Af]:[()=>void 0!==e.FetchOwner,()=>e[nh].toString()],[qf]:[,e[Kh]]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Qd=async(e,t)=>{const r=Ge(e,t),n=zr({},Br,{[vf]:e[Wl]||"application/octet-stream",[Wf]:e[xl],[lf]:e[Ml],[hf]:e[Fl],[ff]:e[$l],[pf]:e[Ul],[gf]:[()=>Br(e[Ll]),()=>e[Ll].toString()],[mf]:e[Dl],[kp]:e[_l],[Vf]:e[Il],[Gf]:e[Nl],[Jf]:e[ql],[Xf]:e[Hl],[kf]:[()=>Br(e[Xl]),()=>ur(e[Xl]).toString()],[Tf]:e[uh],[Rf]:e[fh],[rp]:e[ih],[np]:e[oh],[ip]:e[sh],[op]:e[ah],[Mp]:[()=>Br(e[cf]),()=>e[cf].toString()],[Sp]:e[Jh],[wp]:e[Gh],[Ip]:e[uf],[Tp]:e[Xh],[Cp]:e[Zh],[Rp]:e[Yh],[Ep]:e[tf],[Ap]:e[ef],[xp]:[()=>Br(e[Ol]),()=>e[Ol].toString()],[vp]:e[zh],[Op]:e[of],[hp]:e[Ch],[fp]:[()=>Br(e[Rh]),()=>{return(t=e[Rh],t.toISOString().replace(".000Z","Z")).toString();var t}],[lp]:e[Th],[tp]:e[Zl],...void 0!==e.Metadata&&Object.keys(e.Metadata).reduce(((t,r)=>(t[`x-amz-meta-${r.toLowerCase()}`]=e.Metadata[r],t)),{})});r.bp("/{Key+}"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1),r.p("Key",(()=>e.Key),"{Key+}",!0);const i=zr({[Np]:[,"PutObject"]});let o,s;return void 0!==e.Body&&(s=e.Body,o=s),r.m("PUT").h(n).q(i).b(o),r.build()},Jd=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return tl(e,t);const r=zr({$metadata:El(e),[Jh]:[,e.headers[Sp]],[tf]:[,e.headers[Ep]],[ef]:[,e.headers[Ap]],[Ol]:[()=>void 0!==e.headers[xp],()=>zt(e.headers[xp])]}),n=Xt(Zt(await gi(e.body,t)),"body");return null!=n[Pl]&&(r[Pl]=Sl(n[Pl])),r},Xd=async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return tl(e,t);const r=zr({$metadata:El(e),[Ql]:[()=>void 0!==e.headers[Yf],()=>zt(e.headers[Yf])],[af]:[,e.headers[_p]],[Nh]:[,e.headers[yp]]});return await Ke(e.body,t),r},Zd=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return tl(e,t);const r=zr({$metadata:El(e),[Ql]:[()=>void 0!==e.headers[Yf],()=>zt(e.headers[Yf])],[Tl]:[,e.headers[df]],[rh]:[,e.headers[ep]],[Wh]:[,e.headers[mp]],[bh]:[()=>void 0!==e.headers[Pf],()=>Xt(gr(e.headers[Pf]))],[Ll]:[()=>void 0!==e.headers[gf],()=>rr(e.headers[gf])],[th]:[,e.headers[Ef]],[Il]:[,e.headers[Vf]],[Nl]:[,e.headers[Gf]],[ql]:[,e.headers[Jf]],[Hl]:[,e.headers[Xf]],[Sh]:[()=>void 0!==e.headers[up],()=>nr(e.headers[up])],[af]:[,e.headers[_p]],[Ml]:[,e.headers[lf]],[Fl]:[,e.headers[hf]],[$l]:[,e.headers[ff]],[Ul]:[,e.headers[pf]],[zl]:[,e.headers[yf]],[Wl]:[,e.headers[vf]],[Xl]:[()=>void 0!==e.headers[kf],()=>Xt(gr(e.headers[kf]))],[Yl]:[,e.headers[xf]],[uf]:[,e.headers[Ip]],[Jh]:[,e.headers[Sp]],[Xh]:[,e.headers[Tp]],[Yh]:[,e.headers[Rp]],[tf]:[,e.headers[Ep]],[Ol]:[()=>void 0!==e.headers[xp],()=>zt(e.headers[xp])],[Gh]:[,e.headers[wp]],[Nh]:[,e.headers[yp]],[qh]:[,e.headers[bp]],[_h]:[()=>void 0!==e.headers[dp],()=>nr(e.headers[dp])],[sf]:[()=>void 0!==e.headers[Pp],()=>nr(e.headers[Pp])],[Ch]:[,e.headers[hp]],[Rh]:[()=>void 0!==e.headers[fp],()=>Xt(lr(e.headers[fp]))],[Th]:[,e.headers[lp]],Metadata:[,Object.keys(e.headers).filter((e=>e.startsWith("x-amz-meta-"))).reduce(((t,r)=>(t[r.substring(11)]=e.headers[r],t)),{})]}),n=e.body;return t.sdkStreamMixin(n),r.Body=n,r},Yd=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return tl(e,t);const r=zr({$metadata:El(e),[Nh]:[,e.headers[yp]]}),n=Xt(Zt(await gi(e.body,t)),"body");return""===n.CommonPrefixes?r[jl]=[]:null!=n[jl]&&(r[jl]=yl(Ur(n[jl]))),""===n.Contents?r[Vl]=[]:null!=n[Vl]&&(r[Vl]=bl(Ur(n[Vl]))),null!=n[Kl]&&(r[Kl]=Yt(n[Kl])),null!=n[Gl]&&(r[Gl]=Yt(n[Gl])),null!=n[eh]&&(r[eh]=Yt(n[eh])),null!=n[gh]&&(r[gh]=zt(n[gh])),null!=n[vh]&&(r[vh]=nr(n[vh])),null!=n[kh]&&(r[kh]=nr(n[kh])),null!=n[Eh]&&(r[Eh]=Yt(n[Eh])),null!=n[xh]&&(r[xh]=Yt(n[xh])),null!=n[Ph]&&(r[Ph]=Yt(n[Ph])),null!=n[Kh]&&(r[Kh]=Yt(n[Kh])),r},el=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return tl(e,t);const r=zr({$metadata:El(e),[rh]:[,e.headers[ep]],[th]:[,e.headers[Ef]],[Il]:[,e.headers[Vf]],[Nl]:[,e.headers[Gf]],[ql]:[,e.headers[Jf]],[Hl]:[,e.headers[Xf]],[Jh]:[,e.headers[Sp]],[af]:[,e.headers[_p]],[Xh]:[,e.headers[Tp]],[Yh]:[,e.headers[Rp]],[tf]:[,e.headers[Ep]],[ef]:[,e.headers[Ap]],[Ol]:[()=>void 0!==e.headers[xp],()=>zt(e.headers[xp])],[nf]:[()=>void 0!==e.headers[gp],()=>rr(e.headers[gp])],[Nh]:[,e.headers[yp]]});return await Ke(e.body,t),r},tl=async(e,t)=>{const r={...e,body:await mi(e.body,t)},n=((e,t)=>void 0!==t?.Error?.Code?t.Error.Code:void 0!==t?.Code?t.Code:404==e.statusCode?"NotFound":void 0)(e,r.body);switch(n){case"NoSuchUpload":case"com.amazonaws.s3#NoSuchUpload":throw await hl(r,t);case"ObjectNotInActiveTierError":case"com.amazonaws.s3#ObjectNotInActiveTierError":throw await gl(r,t);case"BucketAlreadyExists":case"com.amazonaws.s3#BucketAlreadyExists":throw await il(r,t);case"BucketAlreadyOwnedByYou":case"com.amazonaws.s3#BucketAlreadyOwnedByYou":throw await ol(r,t);case"NoSuchBucket":case"com.amazonaws.s3#NoSuchBucket":throw await dl(r,t);case"InvalidObjectState":case"com.amazonaws.s3#InvalidObjectState":throw await al(r,t);case"NoSuchKey":case"com.amazonaws.s3#NoSuchKey":throw await ll(r,t);case"NotFound":case"com.amazonaws.s3#NotFound":throw await fl(r,t);case"EncryptionTypeMismatch":case"com.amazonaws.s3#EncryptionTypeMismatch":throw await sl(r,t);case"InvalidRequest":case"com.amazonaws.s3#InvalidRequest":throw await cl(r,t);case"InvalidWriteOffset":case"com.amazonaws.s3#InvalidWriteOffset":throw await ul(r,t);case"TooManyParts":case"com.amazonaws.s3#TooManyParts":throw await ml(r,t);case"ObjectAlreadyInActiveTierError":case"com.amazonaws.s3#ObjectAlreadyInActiveTierError":throw await pl(r,t);default:const i=r.body;return rl({output:e,parsedBody:i,errorCode:n})}},rl=(nl=kd,({output:e,parsedBody:t,errorCode:r})=>{(({output:e,parsedBody:t,exceptionCtor:r,errorCode:n})=>{const i=Or(e),o=i.httpStatusCode?i.httpStatusCode+"":void 0,s=new r({name:t?.code||t?.Code||n||o||"UnknownError",$fault:"client",$metadata:i});throw Rr(s,t)})({output:e,parsedBody:t,exceptionCtor:nl,errorCode:r})});var nl;const il=async(e,t)=>{const r=zr({});e.body;const n=new xd({$metadata:El(e),...r});return Rr(n,e.body)},ol=async(e,t)=>{const r=zr({});e.body;const n=new Ad({$metadata:El(e),...r});return Rr(n,e.body)},sl=async(e,t)=>{const r=zr({});e.body;const n=new Ud({$metadata:El(e),...r});return Rr(n,e.body)},al=async(e,t)=>{const r=zr({}),n=e.body;null!=n[Cl]&&(r[Cl]=Yt(n[Cl])),null!=n[Gh]&&(r[Gh]=Yt(n[Gh]));const i=new Od({$metadata:El(e),...r});return Rr(i,e.body)},cl=async(e,t)=>{const r=zr({});e.body;const n=new Ld({$metadata:El(e),...r});return Rr(n,e.body)},ul=async(e,t)=>{const r=zr({});e.body;const n=new Bd({$metadata:El(e),...r});return Rr(n,e.body)},dl=async(e,t)=>{const r=zr({});e.body;const n=new Td({$metadata:El(e),...r});return Rr(n,e.body)},ll=async(e,t)=>{const r=zr({});e.body;const n=new Pd({$metadata:El(e),...r});return Rr(n,e.body)},hl=async(e,t)=>{const r=zr({});e.body;const n=new Sd({$metadata:El(e),...r});return Rr(n,e.body)},fl=async(e,t)=>{const r=zr({});e.body;const n=new _d({$metadata:El(e),...r});return Rr(n,e.body)},pl=async(e,t)=>{const r=zr({});e.body;const n=new jd({$metadata:El(e),...r});return Rr(n,e.body)},gl=async(e,t)=>{const r=zr({});e.body;const n=new Ed({$metadata:El(e),...r});return Rr(n,e.body)},ml=async(e,t)=>{const r=zr({});e.body;const n=new Dd({$metadata:El(e),...r});return Rr(n,e.body)},yl=(e,t)=>(e||[]).filter((e=>null!=e)).map((e=>(e=>{const t={};return null!=e[Ph]&&(t[Ph]=Yt(e[Ph])),t})(e))),vl=(e,t)=>{const r={};return null!=e[yh]&&(r[yh]=Yt(e[yh])),null!=e[bh]&&(r[bh]=Xt(lr(e[bh]))),null!=e[th]&&(r[th]=Yt(e[th])),""===e.ChecksumAlgorithm?r[_l]=[]:null!=e[_l]&&(r[_l]=(e=>(e||[]).filter((e=>null!=e)).map((e=>Yt(e))))(Ur(e[_l]))),null!=e[nf]&&(r[nf]=rr(e[nf])),null!=e[Gh]&&(r[Gh]=Yt(e[Gh])),null!=e[Ah]&&(r[Ah]=wl(e[Ah])),null!=e[Hh]&&(r[Hh]=kl(e[Hh])),r},bl=(e,t)=>(e||[]).filter((e=>null!=e)).map((e=>vl(e))),wl=(e,t)=>{const r={};return null!=e[Jl]&&(r[Jl]=Yt(e[Jl])),null!=e[ch]&&(r[ch]=Yt(e[ch])),r},kl=(e,t)=>{const r={};return null!=e[ph]&&(r[ph]=zt(e[ph])),null!=e[jh]&&(r[jh]=Xt(lr(e[jh]))),r},Sl=(e,t)=>{const r={};return null!=e[Al]&&(r[Al]=Yt(e[Al])),null!=e[Vh]&&(r[Vh]=Yt(e[Vh])),null!=e[rf]&&(r[rf]=Yt(e[rf])),null!=e[rh]&&(r[rh]=Xt(lr(e[rh]))),r},El=e=>({httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}),xl="ACL",Al="AccessKeyId",Tl="AcceptRanges",Cl="AccessTier",Rl="BypassGovernanceRetention",Ol="BucketKeyEnabled",Pl="Credentials",_l="ChecksumAlgorithm",Ml="CacheControl",Il="ChecksumCRC32",Nl="ChecksumCRC32C",Fl="ContentDisposition",$l="ContentEncoding",Ul="ContentLanguage",Ll="ContentLength",Bl="ChecksumMode",Dl="ContentMD5",jl="CommonPrefixes",zl="ContentRange",ql="ChecksumSHA1",Hl="ChecksumSHA256",Wl="ContentType",Kl="ContinuationToken",Vl="Contents",Gl="Delimiter",Ql="DeleteMarker",Jl="DisplayName",Xl="Expires",Zl="ExpectedBucketOwner",Yl="ExpiresString",eh="EncodingType",th="ETag",rh="Expiration",nh="FetchOwner",ih="GrantFullControl",oh="GrantRead",sh="GrantReadACP",ah="GrantWriteACP",ch="ID",uh="IfMatch",dh="IfMatchLastModifiedTime",lh="IfMatchSize",hh="IfModifiedSince",fh="IfNoneMatch",ph="IsRestoreInProgress",gh="IsTruncated",mh="IfUnmodifiedSince",yh="Key",vh="KeyCount",bh="LastModified",wh="MFA",kh="MaxKeys",Sh="MissingMeta",Eh="Name",xh="NextContinuationToken",Ah="Owner",Th="ObjectLockLegalHoldStatus",Ch="ObjectLockMode",Rh="ObjectLockRetainUntilDate",Oh="OptionalObjectAttributes",Ph="Prefix",_h="PartsCount",Mh="PartNumber",Ih="Range",Nh="RequestCharged",Fh="ResponseCacheControl",$h="ResponseContentDisposition",Uh="ResponseContentEncoding",Lh="ResponseContentLanguage",Bh="ResponseContentType",Dh="ResponseExpires",jh="RestoreExpiryDate",zh="RequestPayer",qh="ReplicationStatus",Hh="RestoreStatus",Wh="Restore",Kh="StartAfter",Vh="SecretAccessKey",Gh="StorageClass",Qh="SessionMode",Jh="ServerSideEncryption",Xh="SSECustomerAlgorithm",Zh="SSECustomerKey",Yh="SSECustomerKeyMD5",ef="SSEKMSEncryptionContext",tf="SSEKMSKeyId",rf="SessionToken",nf="Size",of="Tagging",sf="TagCount",af="VersionId",cf="WriteOffsetBytes",uf="WebsiteRedirectLocation",df="accept-ranges",lf="cache-control",hf="content-disposition",ff="content-encoding",pf="content-language",gf="content-length",mf="content-md5",yf="content-range",vf="content-type",bf="continuation-token",wf="delimiter",kf="expires",Sf="encoding-type",Ef="etag",xf="expiresstring",Af="fetch-owner",Tf="if-match",Cf="if-modified-since",Rf="if-none-match",Of="if-unmodified-since",Pf="last-modified",_f="list-type",Mf="max-keys",If="partNumber",Nf="prefix",Ff="range",$f="response-cache-control",Uf="response-content-disposition",Lf="response-content-encoding",Bf="response-content-language",Df="response-content-type",jf="response-expires",zf="session",qf="start-after",Hf="versionId",Wf="x-amz-acl",Kf="x-amz-bypass-governance-retention",Vf="x-amz-checksum-crc32",Gf="x-amz-checksum-crc32c",Qf="x-amz-checksum-mode",Jf="x-amz-checksum-sha1",Xf="x-amz-checksum-sha256",Zf="x-amz-create-session-mode",Yf="x-amz-delete-marker",ep="x-amz-expiration",tp="x-amz-expected-bucket-owner",rp="x-amz-grant-full-control",np="x-amz-grant-read",ip="x-amz-grant-read-acp",op="x-amz-grant-write-acp",sp="x-amz-if-match-last-modified-time",ap="x-amz-if-match-size",cp="x-amz-mfa",up="x-amz-missing-meta",dp="x-amz-mp-parts-count",lp="x-amz-object-lock-legal-hold",hp="x-amz-object-lock-mode",fp="x-amz-object-lock-retain-until-date",pp="x-amz-optional-object-attributes",gp="x-amz-object-size",mp="x-amz-restore",yp="x-amz-request-charged",vp="x-amz-request-payer",bp="x-amz-replication-status",wp="x-amz-storage-class",kp="x-amz-sdk-checksum-algorithm",Sp="x-amz-server-side-encryption",Ep="x-amz-server-side-encryption-aws-kms-key-id",xp="x-amz-server-side-encryption-bucket-key-enabled",Ap="x-amz-server-side-encryption-context",Tp="x-amz-server-side-encryption-customer-algorithm",Cp="x-amz-server-side-encryption-customer-key",Rp="x-amz-server-side-encryption-customer-key-md5",Op="x-amz-tagging",Pp="x-amz-tagging-count",_p="x-amz-version-id",Mp="x-amz-write-offset-bytes",Ip="x-amz-website-redirect-location",Np="x-id";class Fp extends(Bt.classBuilder().ep({...wd,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(e,t,r,n){return[fe(r,this.serialize,this.deserialize),Ts(r,e.getEndpointParameterInstructions()),xo(r)]})).s("AmazonS3","CreateSession",{}).n("S3Client","CreateSessionCommand").f(Nd,Id).ser(Wd).de(Jd).build()){}var $p="3.701.0";function Up(e){return"string"==typeof e?0===e.length:0===e.byteLength}var Lp={name:"SHA-1"},Bp={name:"HMAC",hash:Lp},Dp=new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]);const jp={};function zp(){return"undefined"!=typeof window?window:"undefined"!=typeof self?self:jp}var qp=function(){function e(e){this.toHash=new Uint8Array(0),void 0!==e&&(this.key=new Promise((function(t,r){zp().crypto.subtle.importKey("raw",Hp(e),Bp,!1,["sign"]).then(t,r)})),this.key.catch((function(){})))}return e.prototype.update=function(e){if(!Up(e)){var t=Hp(e),r=new Uint8Array(this.toHash.byteLength+t.byteLength);r.set(this.toHash,0),r.set(t,this.toHash.byteLength),this.toHash=r}},e.prototype.digest=function(){var e=this;return this.key?this.key.then((function(t){return zp().crypto.subtle.sign(Bp,t,e.toHash).then((function(e){return new Uint8Array(e)}))})):Up(this.toHash)?Promise.resolve(Dp):Promise.resolve().then((function(){return zp().crypto.subtle.digest(Lp,e.toHash)})).then((function(e){return Promise.resolve(new Uint8Array(e))}))},e.prototype.reset=function(){this.toHash=new Uint8Array(0)},e}();function Hp(e){return"string"==typeof e?(t=e,(new TextEncoder).encode(t)):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e);var t}var Wp=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function Kp(e){return!(!function(e){if("object"==typeof e&&"object"==typeof e.crypto){return"function"==typeof e.crypto.getRandomValues}return!1}(e)||"object"!=typeof e.crypto.subtle)&&function(e){return e&&Wp.every((function(t){return"function"==typeof e[t]}))}(e.crypto.subtle)}var Vp=function(){function e(e){if(!Kp(zp()))throw new Error("SHA1 not supported");this.hash=new qp(e)}return e.prototype.update=function(e,t){this.hash.update(xi(e))},e.prototype.digest=function(){return this.hash.digest()},e.prototype.reset=function(){this.hash.reset()},e}(),Gp={name:"SHA-256"},Qp={name:"HMAC",hash:Gp},Jp=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85]),Xp=function(){function e(e){this.toHash=new Uint8Array(0),this.secret=e,this.reset()}return e.prototype.update=function(e){if(!Ai(e)){var t=xi(e),r=new Uint8Array(this.toHash.byteLength+t.byteLength);r.set(this.toHash,0),r.set(t,this.toHash.byteLength),this.toHash=r}},e.prototype.digest=function(){var e=this;return this.key?this.key.then((function(t){return zp().crypto.subtle.sign(Qp,t,e.toHash).then((function(e){return new Uint8Array(e)}))})):Ai(this.toHash)?Promise.resolve(Jp):Promise.resolve().then((function(){return zp().crypto.subtle.digest(Gp,e.toHash)})).then((function(e){return Promise.resolve(new Uint8Array(e))}))},e.prototype.reset=function(){var e=this;this.toHash=new Uint8Array(0),this.secret&&void 0!==this.secret&&(this.key=new Promise((function(t,r){zp().crypto.subtle.importKey("raw",xi(e.secret),Qp,!1,["sign"]).then(t,r)})),this.key.catch((function(){})))},e}();function Zp(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(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((n=n.apply(e,t||[])).next())}))}function Yp(e,t){var r,n,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]ng)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;r>0;)this.buffer[this.bufferLength++]=e[t++],r--,this.bufferLength===eg&&(this.hashBuffer(),this.bufferLength=0)},e.prototype.digest=function(){if(!this.finished){var e=8*this.bytesHashed,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),r=this.bufferLength;if(t.setUint8(this.bufferLength++,128),r%eg>=56){for(var n=this.bufferLength;n>>24&255,i[4*n+1]=this.state[n]>>>16&255,i[4*n+2]=this.state[n]>>>8&255,i[4*n+3]=this.state[n]>>>0&255;return i},e.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,r=t[0],n=t[1],i=t[2],o=t[3],s=t[4],a=t[5],c=t[6],u=t[7],d=0;d>>17|l<<15)^(l>>>19|l<<13)^l>>>10,f=((l=this.temp[d-15])>>>7|l<<25)^(l>>>18|l<<14)^l>>>3;this.temp[d]=(h+this.temp[d-7]|0)+(f+this.temp[d-16]|0)}var p=(((s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7))+(s&a^~s&c)|0)+(u+(tg[d]+this.temp[d]|0)|0)|0,g=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&n^r&i^n&i)|0;u=c,c=a,a=s,s=o+p|0,o=i,i=n,n=r,r=p+g|0}t[0]+=r,t[1]+=n,t[2]+=i,t[3]+=o,t[4]+=s,t[5]+=a,t[6]+=c,t[7]+=u},e}(),og=function(){function e(e){this.secret=e,this.hash=new ig,this.reset()}return e.prototype.update=function(e){if(!Ai(e)&&!this.error)try{this.hash.update(xi(e))}catch(e){this.error=e}},e.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},e.prototype.digest=function(){return Zp(this,void 0,void 0,(function(){return Yp(this,(function(e){return[2,this.digestSync()]}))}))},e.prototype.reset=function(){if(this.hash=new ig,this.secret){this.outer=new ig;var e=function(e){var t=xi(e);if(t.byteLength>eg){var r=new ig;r.update(t),t=r.digest()}var n=new Uint8Array(eg);return n.set(t),n}(this.secret),t=new Uint8Array(eg);t.set(e);for(var r=0;r0&&r[1]||""},e.getSecondMatch=function(e,t){var r=t.match(e);return r&&r.length>1&&r[2]||""},e.matchAndReturnConst=function(e,t,r){if(e.test(t))return r},e.getWindowsVersionName=function(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e.getMacOSVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}},e.getAndroidVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0},e.getVersionPrecision=function(e){return e.split(".").length},e.compareVersions=function(t,r,n){void 0===n&&(n=!1);var i=e.getVersionPrecision(t),o=e.getVersionPrecision(r),s=Math.max(i,o),a=0,c=e.map([t,r],(function(t){var r=s-e.getVersionPrecision(t),n=t+new Array(r+1).join(".0");return e.map(n.split("."),(function(e){return new Array(20-e.length).join("0")+e})).reverse()}));for(n&&(a=s-Math.min(i,o)),s-=1;s>=a;){if(c[0][s]>c[1][s])return 1;if(c[0][s]===c[1][s]){if(s===a)return 0;s-=1}else if(c[0][s]1?i-1:0),s=1;s0){var s=Object.keys(r),c=a.default.find(s,(function(e){return t.isOS(e)}));if(c){var u=this.satisfies(r[c]);if(void 0!==u)return u}var d=a.default.find(s,(function(e){return t.isPlatform(e)}));if(d){var l=this.satisfies(r[d]);if(void 0!==l)return l}}if(o>0){var h=Object.keys(i),f=a.default.find(h,(function(e){return t.isBrowser(e,!0)}));if(void 0!==f)return this.compareVersion(i[f])}},t.isBrowser=function(e,t){void 0===t&&(t=!1);var r=this.getBrowserName().toLowerCase(),n=e.toLowerCase(),i=a.default.getBrowserTypeByAlias(n);return t&&i&&(n=i.toLowerCase()),n===r},t.compareVersion=function(e){var t=[0],r=e,n=!1,i=this.getBrowserVersion();if("string"==typeof i)return">"===e[0]||"<"===e[0]?(r=e.substr(1),"="===e[1]?(n=!0,r=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?r=e.substr(1):"~"===e[0]&&(n=!0,r=e.substr(1)),t.indexOf(a.default.compareVersions(i,r,n))>-1},t.isOS=function(e){return this.getOSName(!0)===String(e).toLowerCase()},t.isPlatform=function(e){return this.getPlatformType(!0)===String(e).toLowerCase()},t.isEngine=function(e){return this.getEngineName(!0)===String(e).toLowerCase()},t.is=function(e,t){return void 0===t&&(t=!1),this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)},t.some=function(e){var t=this;return void 0===e&&(e=[]),e.some((function(e){return t.is(e)}))},e}();t.default=u,e.exports=t.default},92:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},o=/version\/(\d+(\.?_?\d+)+)/i,s=[{test:[/googlebot/i],describe:function(e){var t={name:"Googlebot"},r=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/opera/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opr\/|opios/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:"Samsung Internet for Android"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Whale/i],describe:function(e){var t={name:"NAVER Whale Browser"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MZBrowser/i],describe:function(e){var t={name:"MZ Browser"},r=i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/focus/i],describe:function(e){var t={name:"Focus"},r=i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/swing/i],describe:function(e){var t={name:"Swing"},r=i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/coast/i],describe:function(e){var t={name:"Opera Coast"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(e){var t={name:"Opera Touch"},r=i.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/yabrowser/i],describe:function(e){var t={name:"Yandex Browser"},r=i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:"UC Browser"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Maxthon|mxios/i],describe:function(e){var t={name:"Maxthon"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/epiphany/i],describe:function(e){var t={name:"Epiphany"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/puffin/i],describe:function(e){var t={name:"Puffin"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sleipnir/i],describe:function(e){var t={name:"Sleipnir"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/k-meleon/i],describe:function(e){var t={name:"K-Meleon"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/micromessenger/i],describe:function(e){var t={name:"WeChat"},r=i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/qqbrowser/i],describe:function(e){var t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},r=i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/msie|trident/i],describe:function(e){var t={name:"Internet Explorer"},r=i.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/\sedg\//i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/edg([ea]|ios)/i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/vivaldi/i],describe:function(e){var t={name:"Vivaldi"},r=i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/seamonkey/i],describe:function(e){var t={name:"SeaMonkey"},r=i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sailfish/i],describe:function(e){var t={name:"Sailfish"},r=i.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return r&&(t.version=r),t}},{test:[/silk/i],describe:function(e){var t={name:"Amazon Silk"},r=i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/phantom/i],describe:function(e){var t={name:"PhantomJS"},r=i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/slimerjs/i],describe:function(e){var t={name:"SlimerJS"},r=i.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t={name:"BlackBerry"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t={name:"WebOS Browser"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/bada/i],describe:function(e){var t={name:"Bada"},r=i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/tizen/i],describe:function(e){var t={name:"Tizen"},r=i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/qupzilla/i],describe:function(e){var t={name:"QupZilla"},r=i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/firefox|iceweasel|fxios/i],describe:function(e){var t={name:"Firefox"},r=i.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/electron/i],describe:function(e){var t={name:"Electron"},r=i.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MiuiBrowser/i],describe:function(e){var t={name:"Miui"},r=i.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/chromium/i],describe:function(e){var t={name:"Chromium"},r=i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/chrome|crios|crmo/i],describe:function(e){var t={name:"Chrome"},r=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/GSA/i],describe:function(e){var t={name:"Google Search"},r=i.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t={name:"Android Browser"},r=i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/playstation 4/i],describe:function(e){var t={name:"PlayStation 4"},r=i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:"Safari"},r=i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/.*/i],describe:function(e){var t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:i.default.getFirstMatch(t,e),version:i.default.getSecondMatch(t,e)}}}];t.default=s,e.exports=t.default},93:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},o=r(18),s=[{test:[/Roku\/DVP/],describe:function(e){var t=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:o.OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe:function(e){var t=i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:o.OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe:function(e){var t=i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),r=i.default.getWindowsVersionName(t);return{name:o.OS_MAP.Windows,version:t,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e){var t={name:o.OS_MAP.iOS},r=i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return r&&(t.version=r),t}},{test:[/macintosh/i],describe:function(e){var t=i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),r=i.default.getMacOSVersionName(t),n={name:o.OS_MAP.MacOS,version:t};return r&&(n.versionName=r),n}},{test:[/(ipod|iphone|ipad)/i],describe:function(e){var t=i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:o.OS_MAP.iOS,version:t}}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t=i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),r=i.default.getAndroidVersionName(t),n={name:o.OS_MAP.Android,version:t};return r&&(n.versionName=r),n}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t=i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),r={name:o.OS_MAP.WebOS};return t&&t.length&&(r.version=t),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t=i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||i.default.getFirstMatch(/\bbb(\d+)/i,e);return{name:o.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:o.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:o.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return{name:o.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:o.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:o.OS_MAP.PlayStation4,version:t}}}];t.default=s,e.exports=t.default},94:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},o=r(18),s=[{test:[/googlebot/i],describe:function(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe:function(e){var t=i.default.getFirstMatch(/(can-l01)/i,e)&&"Nova",r={type:o.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(r.model=t),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet}}},{test:function(e){var t=e.test(/ipod|iphone/i),r=e.test(/like (ipod|iphone)/i);return t&&!r},describe:function(e){var t=i.default.getFirstMatch(/(ipod|iphone)/i,e);return{type:o.PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:o.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return{type:o.PLATFORMS_MAP.mobile}}},{test:function(e){return"blackberry"===e.getBrowserName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e){return"bada"===e.getBrowserName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.mobile}}},{test:function(e){return"windows phone"===e.getBrowserName()},describe:function(){return{type:o.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e){var t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:function(){return{type:o.PLATFORMS_MAP.tablet}}},{test:function(e){return"android"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.mobile}}},{test:function(e){return"macos"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e){return"windows"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.desktop}}},{test:function(e){return"linux"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.desktop}}},{test:function(e){return"playstation 4"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.tv}}},{test:function(e){return"roku"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.tv}}}];t.default=s,e.exports=t.default},95:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},o=r(18),s=[{test:function(e){return"microsoft edge"===e.getBrowserName(!0)},describe:function(e){if(/\sedg\//i.test(e))return{name:o.ENGINE_MAP.Blink};var t=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:o.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:o.ENGINE_MAP.Trident},r=i.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){return e.test(/presto/i)},describe:function(e){var t={name:o.ENGINE_MAP.Presto},r=i.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=e.test(/gecko/i),r=e.test(/like gecko/i);return t&&!r},describe:function(e){var t={name:o.ENGINE_MAP.Gecko},r=i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:o.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:o.ENGINE_MAP.WebKit},r=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}}];t.default=s,e.exports=t.default}});var cg=Gr(ag.exports);const ug=({serviceId:e,clientVersion:t})=>async r=>{const n="undefined"!=typeof window&&window?.navigator?.userAgent?cg.parse(window.navigator.userAgent):void 0,i=[["aws-sdk-js",t],["ua","2.1"],[`os/${n?.os?.name||"other"}`,n?.os?.version],["lang/js"],["md/browser",`${n?.browser?.name??"unknown"}_${n?.browser?.version??"unknown"}`]];e&&i.push([`api/${e}`,t]);const o=await(r?.userAgentAppId?.());return o&&i.push([`app/${o}`]),i};class dg{constructor(e){if(this.bytes=e,8!==e.byteLength)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>0x8000000000000000||e<-0x8000000000000000)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);const t=new Uint8Array(8);for(let r=7,n=Math.abs(Math.round(e));r>-1&&n>0;r--,n/=256)t[r]=n;return e<0&&lg(t),new dg(t)}valueOf(){const e=this.bytes.slice(0),t=128&e[0];return t&&lg(e),parseInt(Le(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function lg(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,0===e[t]);t--);}class hg{constructor(e,t){this.toUtf8=e,this.fromUtf8=t}format(e){const t=[];for(const r of Object.keys(e)){const n=this.fromUtf8(r);t.push(Uint8Array.from([n.byteLength]),n,this.formatHeaderValue(e[r]))}const r=new Uint8Array(t.reduce(((e,t)=>e+t.byteLength),0));let n=0;for(const e of t)r.set(e,n),n+=e.byteLength;return r}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":const t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":const r=new DataView(new ArrayBuffer(5));return r.setUint8(0,4),r.setInt32(1,e.value,!1),new Uint8Array(r.buffer);case"long":const n=new Uint8Array(9);return n[0]=5,n.set(e.value.bytes,1),n;case"binary":const i=new DataView(new ArrayBuffer(3+e.value.byteLength));i.setUint8(0,6),i.setUint16(1,e.value.byteLength,!1);const o=new Uint8Array(i.buffer);return o.set(e.value,3),o;case"string":const s=this.fromUtf8(e.value),a=new DataView(new ArrayBuffer(3+s.byteLength));a.setUint8(0,7),a.setUint16(1,s.byteLength,!1);const c=new Uint8Array(a.buffer);return c.set(s,3),c;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(dg.fromNumber(e.value.valueOf()).bytes,1),u;case"uuid":if(!Eg.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(Ue(e.value.replace(/\-/g,"")),1),d}}parse(e){const t={};let r=0;for(;re,isEndOfStream:()=>t}}getAvailableMessages(){const e=this.messageBuffer;this.messageBuffer=[];const t=this.isEndOfStream;return{getMessages:()=>e,isEndOfStream:()=>t}}encode({headers:e,body:t}){const r=this.headerMarshaller.format(e),n=r.byteLength+t.byteLength+16,i=new Uint8Array(n),o=new DataView(i.buffer,i.byteOffset,i.byteLength),s=new Ni;return o.setUint32(0,n,!1),o.setUint32(4,r.byteLength,!1),o.setUint32(8,s.update(i.subarray(0,8)).digest(),!1),i.set(r,12),i.set(t,r.byteLength+12),o.setUint32(n-4,s.update(i.subarray(8,n-4)).digest(),!1),i}decode(e){const{headers:t,body:r}=function({byteLength:e,byteOffset:t,buffer:r}){if(e<16)throw new Error("Provided message too short to accommodate event stream message overhead");const n=new DataView(r,t,e),i=n.getUint32(0,!1);if(e!==i)throw new Error("Reported message length does not match received message length");const o=n.getUint32(4,!1),s=n.getUint32(8,!1),a=n.getUint32(e-4,!1),c=(new Ni).update(new Uint8Array(r,t,8));if(s!==c.digest())throw new Error(`The prelude checksum specified in the message (${s}) does not match the calculated CRC32 checksum (${c.digest()})`);if(c.update(new Uint8Array(r,t+8,e-12)),a!==c.digest())throw new Error(`The message checksum (${c.digest()}) did not match the expected value of ${a}`);return{headers:new DataView(r,t+8+4,o),body:new Uint8Array(r,t+8+4+o,i-o-16)}}(e);return{headers:this.headerMarshaller.parse(t),body:r}}formatHeaders(e){return this.headerMarshaller.format(e)}}class Ag{constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.inputStream){const t=this.options.decoder.decode(e);yield t}}}class Tg{constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.messageStream){const t=this.options.encoder.encode(e);yield t}this.options.includeEndFrame&&(yield new Uint8Array(0))}}class Cg{constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.messageStream){const t=await this.options.deserializer(e);void 0!==t&&(yield t)}}}class Rg{constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.inputStream){const t=this.options.serializer(e);yield t}}}function Og(e,t){return async function(r){const{value:n}=r.headers[":message-type"];if("error"===n){const e=new Error(r.headers[":error-message"].value||"UnknownError");throw e.name=r.headers[":error-code"].value,e}if("exception"===n){const n=r.headers[":exception-type"].value,i={[n]:r},o=await e(i);if(o.$unknown){const e=new Error(t(r.body));throw e.name=n,e}throw o[n]}if("event"===n){const t={[r.headers[":event-type"].value]:r},n=await e(t);if(n.$unknown)return;return n}throw Error(`Unrecognizable event type: ${r.headers[":event-type"].value}`)}}class Pg{constructor({utf8Encoder:e,utf8Decoder:t}){this.eventStreamCodec=new xg(e,t),this.utfEncoder=e}deserialize(e,t){const r=function(e){let t=0,r=0,n=null,i=null;const o=e=>{if("number"!=typeof e)throw new Error("Attempted to allocate an event message where size was not a number: "+e);t=e,r=4,n=new Uint8Array(e),new DataView(n.buffer).setUint32(0,e,!1)};return{[Symbol.asyncIterator]:async function*(){const s=e[Symbol.asyncIterator]();for(;;){const{value:e,done:a}=await s.next();if(a){if(!t)return;if(t!==r)throw new Error("Truncated event message received.");return void(yield n)}const c=e.length;let u=0;for(;u{const t=e[Symbol.asyncIterator]();return new ReadableStream({async pull(e){const{done:r,value:n}=await t.next();if(r)return e.close();e.enqueue(n)}})})(r):r}}const Mg=e=>"function"==typeof ReadableStream&&e instanceof ReadableStream,Ig=e=>new _g(e);const Ng=async function(e,t){const r=new e;return await async function(e,t,r=1048576){const n=e.size;let i=0;for(;i{r.update(e)})),r.digest()},Fg=64,$g=[1732584193,4023233417,2562383102,271733878];class Ug{constructor(){this.reset()}update(e){if(function(e){if("string"==typeof e)return 0===e.length;return 0===e.byteLength}(e))return;if(this.finished)throw new Error("Attempted to update an already finished hash.");const t=function(e){if("string"==typeof e)return Se(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(e)}(e);let r=0,{byteLength:n}=t;for(this.bytesHashed+=n;n>0;)this.buffer.setUint8(this.bufferLength++,t[r++]),n--,this.bufferLength===Fg&&(this.hashBuffer(),this.bufferLength=0)}async digest(){if(!this.finished){const{buffer:e,bufferLength:t,bytesHashed:r}=this,n=8*r;if(e.setUint8(this.bufferLength++,128),t%Fg>=56){for(let t=this.bufferLength;t>>0,!0),e.setUint32(60,Math.floor(n/4294967296),!0),this.hashBuffer(),this.finished=!0}const e=new DataView(new ArrayBuffer(16));for(let t=0;t<4;t++)e.setUint32(4*t,this.state[t],!0);return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}hashBuffer(){const{buffer:e,state:t}=this;let r=t[0],n=t[1],i=t[2],o=t[3];r=Bg(r,n,i,o,e.getUint32(0,!0),7,3614090360),o=Bg(o,r,n,i,e.getUint32(4,!0),12,3905402710),i=Bg(i,o,r,n,e.getUint32(8,!0),17,606105819),n=Bg(n,i,o,r,e.getUint32(12,!0),22,3250441966),r=Bg(r,n,i,o,e.getUint32(16,!0),7,4118548399),o=Bg(o,r,n,i,e.getUint32(20,!0),12,1200080426),i=Bg(i,o,r,n,e.getUint32(24,!0),17,2821735955),n=Bg(n,i,o,r,e.getUint32(28,!0),22,4249261313),r=Bg(r,n,i,o,e.getUint32(32,!0),7,1770035416),o=Bg(o,r,n,i,e.getUint32(36,!0),12,2336552879),i=Bg(i,o,r,n,e.getUint32(40,!0),17,4294925233),n=Bg(n,i,o,r,e.getUint32(44,!0),22,2304563134),r=Bg(r,n,i,o,e.getUint32(48,!0),7,1804603682),o=Bg(o,r,n,i,e.getUint32(52,!0),12,4254626195),i=Bg(i,o,r,n,e.getUint32(56,!0),17,2792965006),n=Bg(n,i,o,r,e.getUint32(60,!0),22,1236535329),r=Dg(r,n,i,o,e.getUint32(4,!0),5,4129170786),o=Dg(o,r,n,i,e.getUint32(24,!0),9,3225465664),i=Dg(i,o,r,n,e.getUint32(44,!0),14,643717713),n=Dg(n,i,o,r,e.getUint32(0,!0),20,3921069994),r=Dg(r,n,i,o,e.getUint32(20,!0),5,3593408605),o=Dg(o,r,n,i,e.getUint32(40,!0),9,38016083),i=Dg(i,o,r,n,e.getUint32(60,!0),14,3634488961),n=Dg(n,i,o,r,e.getUint32(16,!0),20,3889429448),r=Dg(r,n,i,o,e.getUint32(36,!0),5,568446438),o=Dg(o,r,n,i,e.getUint32(56,!0),9,3275163606),i=Dg(i,o,r,n,e.getUint32(12,!0),14,4107603335),n=Dg(n,i,o,r,e.getUint32(32,!0),20,1163531501),r=Dg(r,n,i,o,e.getUint32(52,!0),5,2850285829),o=Dg(o,r,n,i,e.getUint32(8,!0),9,4243563512),i=Dg(i,o,r,n,e.getUint32(28,!0),14,1735328473),n=Dg(n,i,o,r,e.getUint32(48,!0),20,2368359562),r=jg(r,n,i,o,e.getUint32(20,!0),4,4294588738),o=jg(o,r,n,i,e.getUint32(32,!0),11,2272392833),i=jg(i,o,r,n,e.getUint32(44,!0),16,1839030562),n=jg(n,i,o,r,e.getUint32(56,!0),23,4259657740),r=jg(r,n,i,o,e.getUint32(4,!0),4,2763975236),o=jg(o,r,n,i,e.getUint32(16,!0),11,1272893353),i=jg(i,o,r,n,e.getUint32(28,!0),16,4139469664),n=jg(n,i,o,r,e.getUint32(40,!0),23,3200236656),r=jg(r,n,i,o,e.getUint32(52,!0),4,681279174),o=jg(o,r,n,i,e.getUint32(0,!0),11,3936430074),i=jg(i,o,r,n,e.getUint32(12,!0),16,3572445317),n=jg(n,i,o,r,e.getUint32(24,!0),23,76029189),r=jg(r,n,i,o,e.getUint32(36,!0),4,3654602809),o=jg(o,r,n,i,e.getUint32(48,!0),11,3873151461),i=jg(i,o,r,n,e.getUint32(60,!0),16,530742520),n=jg(n,i,o,r,e.getUint32(8,!0),23,3299628645),r=zg(r,n,i,o,e.getUint32(0,!0),6,4096336452),o=zg(o,r,n,i,e.getUint32(28,!0),10,1126891415),i=zg(i,o,r,n,e.getUint32(56,!0),15,2878612391),n=zg(n,i,o,r,e.getUint32(20,!0),21,4237533241),r=zg(r,n,i,o,e.getUint32(48,!0),6,1700485571),o=zg(o,r,n,i,e.getUint32(12,!0),10,2399980690),i=zg(i,o,r,n,e.getUint32(40,!0),15,4293915773),n=zg(n,i,o,r,e.getUint32(4,!0),21,2240044497),r=zg(r,n,i,o,e.getUint32(32,!0),6,1873313359),o=zg(o,r,n,i,e.getUint32(60,!0),10,4264355552),i=zg(i,o,r,n,e.getUint32(24,!0),15,2734768916),n=zg(n,i,o,r,e.getUint32(52,!0),21,1309151649),r=zg(r,n,i,o,e.getUint32(16,!0),6,4149444226),o=zg(o,r,n,i,e.getUint32(44,!0),10,3174756917),i=zg(i,o,r,n,e.getUint32(8,!0),15,718787259),n=zg(n,i,o,r,e.getUint32(36,!0),21,3951481745),t[0]=r+t[0]&4294967295,t[1]=n+t[1]&4294967295,t[2]=i+t[2]&4294967295,t[3]=o+t[3]&4294967295}reset(){this.state=Uint32Array.from($g),this.buffer=new DataView(new ArrayBuffer(Fg)),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}}function Lg(e,t,r,n,i,o){return((t=(t+e&4294967295)+(n+o&4294967295)&4294967295)<>>32-i)+r&4294967295}function Bg(e,t,r,n,i,o,s){return Lg(t&r|~t&n,e,t,i,o,s)}function Dg(e,t,r,n,i,o,s){return Lg(t&n|r&~n,e,t,i,o,s)}function jg(e,t,r,n,i,o,s){return Lg(t^r^n,e,t,i,o,s)}function zg(e,t,r,n,i,o,s){return Lg(r^(t|~n),e,t,i,o,s)}const qg="function"==typeof TextEncoder?new TextEncoder:null,Hg=e=>{if("string"==typeof e){if(qg)return qg.encode(e).byteLength;let t=e.length;for(let r=t-1;r>=0;r--){const n=e.charCodeAt(r);n>127&&n<=2047?t++:n>2047&&n<=65535&&(t+=2),n>=56320&&n<=57343&&r--}return t}if("number"==typeof e.byteLength)return e.byteLength;if("number"==typeof e.size)return e.size;throw new Error(`Body Length computation failed for ${e}`)},Wg=["in-region","cross-region","mobile","standard","legacy"],Kg=()=>{const e="undefined"!=typeof window&&window?.navigator?.userAgent?cg.parse(window.navigator.userAgent):void 0,t=e?.platform?.type;return"tablet"===t||"mobile"===t},Vg=e=>{const t=(({defaultsMode:e}={})=>((e,t,r)=>{let n,i,o,s=!1;const a=async()=>{i||(i=e());try{n=await i,o=!0,s=!1}finally{i=void 0}return n};return void 0===t?async e=>(o&&!e?.forceRefresh||(n=await a()),n):async e=>(o&&!e?.forceRefresh||(n=await a()),s?n:r&&!r(n)?(s=!0,n):t(n)?(await a(),n):n)})((async()=>{const t="function"==typeof e?await e():e;switch(t?.toLowerCase()){case"auto":return Promise.resolve(Kg()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(t?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${Wg.join(", ")}, got ${t}`)}})))(e),r=()=>t().then(Pr),n=(e=>({apiVersion:"2006-03-01",base64Decoder:e?.base64Decoder??ke,base64Encoder:e?.base64Encoder??Ae,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??fd,extensions:e?.extensions??[],getAwsChunkedEncodingStream:e?.getAwsChunkedEncodingStream??Ce,httpAuthSchemeProvider:e?.httpAuthSchemeProvider??vd,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new oe},{schemeId:"aws.auth#sigv4a",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4a"),signer:new se}],logger:e?.logger??new jr,sdkStreamMixin:e?.sdkStreamMixin??je,serviceId:e?.serviceId??"S3",signerConstructor:e?.signerConstructor??Ys,signingEscapePath:e?.signingEscapePath??!1,urlParser:e?.urlParser??ks,useArnRegion:e?.useArnRegion??!1,utf8Decoder:e?.utf8Decoder??Se,utf8Encoder:e?.utf8Encoder??xe}))(e);return{...n,...e,runtime:"browser",defaultsMode:t,bodyLengthChecker:e?.bodyLengthChecker??Hg,credentialDefaultProvider:e?.credentialDefaultProvider??(e=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:e?.defaultUserAgentProvider??ug({serviceId:n.serviceId,clientVersion:$p}),eventStreamSerdeProvider:e?.eventStreamSerdeProvider??Ig,maxAttempts:e?.maxAttempts??3,md5:e?.md5??Ug,region:e?.region??(i="Region is missing",()=>Promise.reject(i)),requestHandler:Ie.create(e?.requestHandler??r),retryMode:e?.retryMode??(async()=>(await r()).retryMode||Rs),sha1:e?.sha1??Vp,sha256:e?.sha256??sg,streamCollector:e?.streamCollector??Ne,streamHasher:e?.streamHasher??Ng,useDualstackEndpoint:e?.useDualstackEndpoint??(()=>Promise.resolve(false)),useFipsEndpoint:e?.useFipsEndpoint??(()=>Promise.resolve(false))};var i},Gg=e=>{let t=async()=>{if(void 0===e.region)throw new Error("Region is missing from runtimeConfig");const t=e.region;return"string"==typeof t?t:t()};return{setRegion(e){t=e},region:()=>t}},Qg=e=>{const t=e.httpAuthSchemes;let r=e.httpAuthSchemeProvider,n=e.credentials;return{setHttpAuthScheme(e){const r=t.findIndex((t=>t.schemeId===e.schemeId));-1===r?t.push(e):t.splice(r,1,e)},httpAuthSchemes:()=>t,setHttpAuthSchemeProvider(e){r=e},httpAuthSchemeProvider:()=>r,setCredentials(e){n=e},credentials:()=>n}},Jg=e=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()});class Xg extends Lt{constructor(...[e]){const t=Vg(e||{});var r;const n=function(e){const t=ve(e.userAgentAppId??void 0);return{...e,customUserAgent:"string"==typeof e.customUserAgent?[[e.customUserAgent]]:e.customUserAgent,userAgentAppId:async()=>{const r=await t();if(!function(e){return void 0===e||"string"==typeof e&&e.length<=50}(r)){const t="NoOpLogger"!==e.logger?.constructor?.name&&e.logger?e.logger:console;"string"!=typeof r?t?.warn("userAgentAppId must be a string or undefined."):r.length>50&&t?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return r}}}((r=t,{...r,useFipsEndpoint:r.useFipsEndpoint??!1,useDualstackEndpoint:r.useDualstackEndpoint??!1,forcePathStyle:r.forcePathStyle??!1,useAccelerateEndpoint:r.useAccelerateEndpoint??!1,useGlobalEndpoint:r.useGlobalEndpoint??!1,disableMultiregionAccessPoints:r.disableMultiregionAccessPoints??!1,defaultSigningName:"s3"}));var i;const o=(e=>({...e,eventStreamMarshaller:e.eventStreamSerdeProvider(e)}))((e=>{const t=e.tls??!0,{endpoint:r}=e,n=null!=r?async()=>Ss(await ce(r)()):void 0,i=!!r,o={...e,endpoint:n,tls:t,isCustomEndpoint:i,useDualstackEndpoint:ce(e.useDualstackEndpoint??!1),useFipsEndpoint:ce(e.useFipsEndpoint??!1)};let s;return o.serviceConfiguredEndpoint=async()=>(e.serviceId&&!s&&(s=ws(e.serviceId)),s),o})((e=>{const{region:t,useFipsEndpoint:r}=e;if(!t)throw new Error("Region is missing");return{...e,region:async()=>{if("string"==typeof t)return ds(t);const e=await t();return ds(e)},useFipsEndpoint:async()=>{const e="string"==typeof t?t:await t();return!!us(e)||("function"!=typeof r?Promise.resolve(!!r):r())}}})((e=>{const{retryStrategy:t}=e,r=ce(e.maxAttempts??3);return{...e,maxAttempts:r,retryStrategy:async()=>t||(await ce(e.retryMode)()===Cs.ADAPTIVE?new Ls(r):new Us(r))}})((i=n,{...i,requestChecksumCalculation:ce(i.requestChecksumCalculation??K),responseChecksumValidation:ce(i.responseChecksumValidation??V)}))))),s=((e,{session:t})=>{const[r,n]=t;return{...e,forcePathStyle:e.forcePathStyle??!1,useAccelerateEndpoint:e.useAccelerateEndpoint??!1,disableMultiregionAccessPoints:e.disableMultiregionAccessPoints??!1,followRegionRedirects:e.followRegionRedirects??!1,s3ExpressIdentityProvider:e.s3ExpressIdentityProvider??new ao((async e=>r().send(new n({Bucket:e,SessionMode:"ReadWrite"})))),bucketEndpoint:e.bucketEndpoint??!1}})(bd(o),{session:[()=>this,Fp]}),a=((e,t)=>{const r={...Gg(e),...Fr(e),...M(e),...Qg(e)};return t.forEach((e=>e.configure(r))),{...e,...(i=r,{region:i.region()}),...$r(r),...(n=r,{httpHandler:n.httpHandler()}),...Jg(r)};var n,i})(s,e?.extensions||[]);super(a),this.config=a,this.middlewareStack.use((e=>({applyToStack:t=>{t.add(ss(e),cs)}}))(this.config)),this.middlewareStack.use(Js(this.config)),this.middlewareStack.use(fs(this.config)),this.middlewareStack.use(Vi(this.config)),this.middlewareStack.use((this.config,{applyToStack:e=>{e.add(((e,t)=>async r=>{try{const n=await e(r),{clientName:i,commandName:o,logger:s,dynamoDbDocumentClientOptions:a={}}=t,{overrideInputFilterSensitiveLog:c,overrideOutputFilterSensitiveLog:u}=a,d=c??t.inputFilterSensitiveLog,l=u??t.outputFilterSensitiveLog,{$metadata:h,...f}=n.output;return s?.info?.({clientName:i,commandName:o,input:d(r.input),output:l(f),metadata:h}),n}catch(e){const{clientName:n,commandName:i,logger:o,dynamoDbDocumentClientOptions:s={}}=t,{overrideInputFilterSensitiveLog:a}=s,c=a??t.inputFilterSensitiveLog;throw o?.error?.({clientName:n,commandName:i,input:c(r.input),error:e,metadata:e.$metadata}),e}}),Gi)}})),this.middlewareStack.use(Xi(this.config)),this.middlewareStack.use(((e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(ue(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r}),de)}}))(this.config,{httpAuthSchemeParametersProvider:pd,identityProviderConfigProvider:async e=>new Je({"aws.auth#sigv4":e.credentials,"aws.auth#sigv4a":e.credentials})})),this.middlewareStack.use(ye(this.config)),this.middlewareStack.use(Co(this.config)),this.middlewareStack.use(H(this.config)),this.middlewareStack.use(ro(this.config)),this.middlewareStack.use(mo(this.config)),this.middlewareStack.use((e=>({applyToStack:t=>{t.addRelativeTo(bo(e),me)}}))(this.config))}destroy(){super.destroy()}}const Zg={name:"ssecMiddleware",step:"initialize",tags:["SSE"],override:!0},Yg=e=>({applyToStack:t=>{var r;t.add((r=e,e=>async t=>{const n={...t.input},i=[{target:"SSECustomerKey",hash:"SSECustomerKeyMD5"},{target:"CopySourceSSECustomerKey",hash:"CopySourceSSECustomerKeyMD5"}];for(const e of i){const t=n[e.target];if(t){let i;"string"==typeof t?em(t,r)?i=r.base64Decoder(t):(i=r.utf8Decoder(t),n[e.target]=r.base64Encoder(i)):(i=ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),n[e.target]=r.base64Encoder(i));const o=new r.md5;o.update(i),n[e.hash]=r.base64Encoder(await o.digest())}}return e({...t,input:n})}),Zg)}});function em(e,t){if(!/^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return!1;try{return 32===t.base64Decoder(e).length}catch{return!1}}class tm extends(Bt.classBuilder().ep({...wd,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[fe(r,this.serialize,this.deserialize),Ts(r,e.getEndpointParameterInstructions()),xo(r)]})).s("AmazonS3","DeleteObject",{}).n("S3Client","DeleteObjectCommand").f(void 0,void 0).ser(Kd).de(Xd).build()){}class rm extends(Bt.classBuilder().ep({...wd,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[fe(r,this.serialize,this.deserialize),Ts(r,e.getEndpointParameterInstructions()),Wi(r,{requestChecksumRequired:!1,requestValidationModeMember:"ChecksumMode",responseAlgorithms:["CRC32","CRC32C","SHA256","SHA1"]}),Yg(r),io()]})).s("AmazonS3","GetObject",{}).n("S3Client","GetObjectCommand").f($d,Fd).ser(Vd).de(Zd).build()){}class nm extends(Bt.classBuilder().ep({...wd,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m((function(e,t,r,n){return[fe(r,this.serialize,this.deserialize),Ts(r,e.getEndpointParameterInstructions()),xo(r)]})).s("AmazonS3","ListObjectsV2",{}).n("S3Client","ListObjectsV2Command").f(void 0,void 0).ser(Gd).de(Yd).build()){}class im extends(Bt.classBuilder().ep({...wd,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[fe(r,this.serialize,this.deserialize),Ts(r,e.getEndpointParameterInstructions()),Wi(r,{requestAlgorithmMember:"ChecksumAlgorithm",requestAlgorithmMemberHttpHeader:"x-amz-sdk-checksum-algorithm",requestChecksumRequired:!1}),Yi(),xo(r),Yg(r)]})).s("AmazonS3","PutObject",{}).n("S3Client","PutObjectCommand").f(Hd,qd).ser(Qd).de(el).build()){}class om{constructor(e){this.config=e,this.taskQueue=new h(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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:n,accessKeyId:i,secretAccessKey:o,dir:s}=this.config;s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder;let a=s+"/"+e;for(;a.startsWith("/");)a=a.substring(1);const c=new Xg({endpoint:t,region:r,credentials:{accessKeyId:i,secretAccessKey:o}});try{let e,t=[],r=!0;for(;r;){const i=yield c.send(new nm({Bucket:n,Prefix:a,ContinuationToken:e}));i.Contents&&(t=t.concat(i.Contents)),e=i.NextContinuationToken,r=!!e}if(0===t.length)return[];const i=new Set;""===a||a.endsWith("/")||(a+="/");let o=t.map((e=>e.Key));for(const e of o){const t=e.substring(a.length).split("/")[0];i.add(t)}return console.log("List result:",i),Array.from(i)}catch(e){return console.error(e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:n,accessKeyId:i,secretAccessKey:o,dir:s}=this.config;s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder;const a=new Xg({endpoint:t,region:r,credentials:{accessKeyId:i,secretAccessKey:o}});let c=s+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{return yield a.send(new tm({Bucket:n,Key:c})),!0}catch(e){return console.error(e),!1}}))}}class sm extends om{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*(){let{endpoint:r,region:n,bucketName:i,accessKeyId:o,secretAccessKey:s,dir:a}=this.config;const c=new Xg({endpoint:r,region:n,credentials:{accessKeyId:o,secretAccessKey:s}});a=a&&"KoodoReader"===this.baseFolder?a:this.baseFolder;let u=a+"/"+t;for(;u.startsWith("/");)u=u.substring(1);try{let t=yield c.send(new im({Bucket:i,Key:u,Body:e}));return console.log("Upload result:",t),200===t.$metadata.httpStatusCode||(console.error("Error uploading file:",t),!1)}catch(e){return console.error("Error: ",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*(){let{endpoint:t,region:r,bucketName:n,accessKeyId:i,secretAccessKey:o,dir:s}=this.config;s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder;const a=new Xg({endpoint:t,region:r,credentials:{accessKeyId:i,secretAccessKey:o}});let c=s+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{const e=yield a.send(new rm({Bucket:n,Key:c}));if(console.log("Download result:",e),!e.Body)return console.error("No response body"),!1;return(yield e.Body.transformToByteArray()).buffer}catch(t){return console.error("Error downloading file:",t,e),!1}}))))))}))}}class am{constructor(e){let{username:t,password:r,url:o,dir:s}=e;void 0===e.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=e.baseFolder,s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder,this.client=n(o,{authType:i.Password,username:t,password:r}),this.username=t,this.password=r,this.dir=s,this.taskQueue=new h(5)}retryOperation(e,t=0){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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 n=r.split("/").pop()||"",i=new File([t],n,{lastModified:(new Date).getTime(),type:t.type}),o=this.client.getFileUploadLink(this.dir+"/"+r);const s=new URL(o);s.search="",o=s.toString();const a=btoa(this.username+":"+this.password),c=yield e.put(o,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),n=btoa(this.username+":"+this.password),i=yield e({url:r,method:"get",headers:{Authorization:"Basic "+n},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 cm=["book","config","cover","font"];class um{constructor(e,t,r){this.type=e,this.remote="dropbox"===e?new S(t,r):"microsoft"===e?new R(t,r):"google"===e?new x(t,r):"s3compatible"===e?new sm(t):"webdav"===e?new am(t):"boxnet"===e?new w(t,r):"mega"===e?new T(t):"adrive"===e?new v(t,r):"pcloud"===e?new _(t,r):new O}downloadFile(e,t){return s(this,void 0,void 0,(function*(){if("cover"!==t){if(!(yield this.listFiles(t)).find((t=>e.indexOf(t)>-1)))return!1}return 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.listFiles(t)).find((t=>e.indexOf(t)>-1))||(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 cm){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 dm={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 = ?"},lm={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},hm={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function fm(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const pm={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 gm,mm={sqlStatement:{createTableStatement:fm({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:fm({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:fm({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:fm({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:fm({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:fm({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:fm({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:fm(dm),getByBookKeyStatement:fm(lm),getByBookKeysStatement:fm({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:fm(hm)},jsonToSqlite:fm({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:fm(pm)};class ym{constructor(e,t,r,n,i,o,s,a,c,u,d,l){this.key=e,this.name=t,this.author=r,this.description=n,this.md5=i,this.cover=o,this.format=s,this.publisher=a,this.size=c,this.page=u,this.path=d,this.charset=l}}const vm={queue:[],processing:!1,addMessage(e){this.queue.push(e),this.processing||this.processQueue()},processQueue(){if(0===this.queue.length)return void(this.processing=!1);this.processing=!0;const e=this.queue.shift();try{window.ReactNativeWebView.postMessage(e)}catch(e){console.error("Error posting message:",e)}setTimeout((()=>this.processQueue()),10)}};class bm{static generateBook(e,t,r,n,i,o,a){return new Promise(((c,u)=>s(this,void 0,void 0,(function*(){try{let s,u,d,l,h,f,p,g,m="";switch([u,d,h,l,f,p]=[e,"","","","",0],t){case"pdf":case"epub":case"mobi":case"azw":case"azw3":case"fb2":g=yield a.getMetadata(),[u,d,h,l,m]=[g.name||e,g.author||"",g.description||"",g.publisher||"",g.cover||""];break;case"cbr":case"cbt":case"cbz":case"cb7":g=yield a.getMetadata(),m=g.cover;break;case"txt":g=yield a.getMetadata(o),f=g.charset}let y=t.toUpperCase();s=(new Date).getTime()+"",c(new ym(s,u,d,h,r,m,y,l,n,p,i,f))}catch(e){console.error(e),u(e)}}))))}}gm=bm,bm.getRendtion=(e,t,r,n,i,o,s,a,c,u)=>{let d;var l,h;return"CACHE"===t?d=new u.CacheRender(e,{readerMode:r,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"MOBI"===t||"AZW3"===t||"AZW"===t?d=new u.MobiRender(e,{readerMode:r,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"EPUB"===t?d=new u.EpubRender(e,{readerMode:r,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"TXT"===t?d=new u.TxtRender(e,{readerMode:r,animation:i,charset:n,convertChinese:o,parserRegex:s,isDarkMode:a,isMobile:c}):"MD"===t?d=new u.MdRender(e,{readerMode:r,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"PDF"===t?d=new u.PdfRender(e,{readerMode:r,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"FB2"===t?d=new u.Fb2Render(e,{readerMode:r,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"DOCX"===t?d=new u.DocxRender(e,{readerMode:r,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"HTML"===t||"XHTML"===t||"MHTML"===t||"HTM"===t||"XML"===t?d=new u.HtmlRender(e,{readerMode:r,format:t,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"CBR"!==t&&"CBT"!==t&&"CBZ"!==t&&"CB7"!==t||(d=new u.ComicRender((l=e,h=new ArrayBuffer(l.byteLength),new Uint8Array(h).set(new Uint8Array(l)),h),{readerMode:r,format:t,animation:i,convertChinese:o,isDarkMode:a,isMobile:c})),d},bm.initMobileBook=(e,t,r,n,i,o,a,c,u)=>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 d=yield s.arrayBuffer();window.ReactNativeWebView.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=d;let l=gm.getRendtion(d,t,r,n,i,o,a,u,"yes",window.Kookit);window.rendition=l;let h=document.getElementById("page-area");t&&"TXT"===t.toUpperCase()?yield window.rendition.renderTo(h,c):yield window.rendition.renderTo(h),window.rendition.on("rendered",(()=>{console.log("renderedd");let e=window.rendition.getPosition();console.log("post position",e),vm.addMessage(JSON.stringify({event:"content-loaded",bookLocation:e})),window.rendition.tsTransform()})),window.rendition.on("page-changed",(()=>{let e=window.rendition.getPosition();vm.addMessage(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"}))}})),bm.addMobileBook=(e,t,r,n,i,o,a="")=>s(void 0,void 0,void 0,(function*(){var s;try{if("PDF"===r.toUpperCase()&&i>314572800){t=t.replace(/\.[^/.]+$/,"");let e=r.toUpperCase(),s=(new Date).getTime()+"",a=new ym(s,t,"","",n,"",e,"",i,0,o,"");return void window.ReactNativeWebView.postMessage(JSON.stringify({event:"metadata",bookInfo:a}))}const c=yield fetch(e);if(!c.ok)throw new Error(`Failed to download book: ${c.status} ${c.statusText}`);const u=yield c.arrayBuffer();null===(s=window.ReactNativeWebView)||void 0===s||s.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=u;let d=gm.getRendtion(u,r.toUpperCase(),"","","","no",a,"no","yes",window.Kookit);window.rendition=d,t=t.replace(/\.[^/.]+$/,"");let l=yield bm.generateBook(t,r,n,i,o,u,d);if(!l||!l.key)return;window.ReactNativeWebView.postMessage(JSON.stringify({event:"metadata",bookInfo:l}))}catch(e){window.ReactNativeWebView.postMessage(JSON.stringify({event:"error",message:"Parse book failed"}))}})),bm.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 n=`${e}/dav/${"cache-"+t+".zip"}`,i=yield fetch(n,{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 wm=p.devUrl;class km{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(wm+"/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=wm,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 n=(yield e(t)).data;if(402===n.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!==n.code&&this.ConfigService.setItem("errorLog",JSON.stringify({request:t.data,url:t.url,result:n,requestID:r})),n}catch(e){return console.error("Request execution error:",e),{code:503,message:"network error",data:null}}}))}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 n="";try{n=(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,a)=>{const c=new r(wm+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+n,"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(),o(r)):(402===r.code&&(yield this.refreshUserToken()),t(r.data))})))),c.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);o(t),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 n="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((i,o)=>s(this,void 0,void 0,(function*(){const o=yield fetch(wm+e.url,{method:"POST",headers:{"Content-Type":"text/event-stream",Authorization:"Bearer "+r,"X-Request-ID":n},body:JSON.stringify(e.data)});if(!o.body)throw new Error("Response body is null");const s=o.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)}}))}i({code:200,data:{done:!0}})}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}class Sm extends km{constructor(e,t){super(e,t)}getTransStream(e,t,r){return s(this,void 0,void 0,(function*(){const n={method:"post",url:"/api/v1/pro/reader/get_llm_trans_stream",data:e};return yield this.requestWithStream(n,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 n={method:"post",url:"/api/v1/pro/reader/get_llm_sum_stream",data:e};return yield this.requestWithStream(n,t,r)}))}getAnswerStream(e,t,r){return s(this,void 0,void 0,(function*(){const n={method:"post",url:"/api/v1/pro/reader/get_llm_answer_stream",data:e};return yield this.requestWithStream(n,t,r)}))}getAnswerFetch(e,t){return s(this,void 0,void 0,(function*(){const r={method:"post",url:"/api/v1/pro/reader/get_llm_answer_stream",data:e};return yield this.requestWithFetch(r,t)}))}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 Em extends km{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)}))}getSyncData(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/pro/thirdparty/get_sync_data"})}))}updateSyncData(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/update_sync_data",data:e};return yield this.requestWithRetry(t)}))}}class xm extends km{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"})}))}getUserConfig(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/member/user/get_config"})}))}updateUserConfig(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/update_config",data:e};return yield this.requestWithRetry(t)}))}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)}))}deleteAccount(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/delete_account",data:e};return yield this.requestWithRetry(t)}))}}var Am={getAuthUrl:(e,t)=>{let r="";if("github"===e?r=`https://github.com/login/oauth/authorize?client_id=${g.githubClientId}&redirect_uri=${g.callbackUrl}&scope=openid`:"google"===e?r=`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${g.callbackUrl}&prompt=consent&response_type=code&client_id=${g.googleClientId}&scope=openid&access_type=offline`:"facebook"===e?r=`https://www.facebook.com/v12.0/dialog/oauth?client_id=${g.facebookClientId}&redirect_uri=${g.callbackUrl}&scope=&response_type=code`:"microsoft"===e&&(r=`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${g.microsoftClientId}&scope=openid profile User.Read offline_access&response_type=code&redirect_uri=${g.callbackUrl}`),"manual"===t)return r;let n=JSON.stringify({deeplink:"desktop"===t?"koodo-reader://callback":"browser"===t?"https://web.koodoreader.com/#/login":"",service:e});return`${r}&state=${"state|"+encodeURIComponent(n)}`}};class Tm{static CompareDatabase(e,t,r){return s(this,void 0,void 0,(function*(){let n=Object.keys(e).filter((e=>e.startsWith("database.sqlite.books"))),i=Object.keys(e).filter((e=>e.startsWith("database.sqlite.notes"))),o=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"))),u=Object.keys(t).filter((e=>e.startsWith("database.sqlite.notes"))),d=Object.keys(t).filter((e=>e.startsWith("database.sqlite.bookmarks"))),l=Object.keys(t).filter((e=>e.startsWith("database.sqlite.plugins"))),h=Object.keys(t).filter((e=>e.startsWith("database.sqlite.words"))),f={books:Array.from(new Set(n.concat(c))),notes:Array.from(new Set(i.concat(u))),bookmarks:Array.from(new Set(o.concat(d))),plugins:Array.from(new Set(s.concat(l))),words:Array.from(new Set(a.concat(h)))},p={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:[]}},g=["books","notes","bookmarks","plugins","words"];for(let n of g)for(let i of f[n]){let o=i.split(".")[3],s=e[i],a=t[i];s?a?("save"===a.operation&&("update"===s.operation||"delete"===s.operation?p[n].upload.push(o):console.info("ignore",a)),"delete"===a.operation&&("save"===s.operation&&(p[n].delete.push(o),e[i]=a),"update"===s.operation&&(s.timea.time?(p[n].conflict.push(o),"cloud"===r?(p[n].delete.push(o),e[i]=a):p[n].upload.push(o)):console.info("ignore",a)),"delete"===s.operation&&console.info("ignore",a)),"update"===a.operation&&("save"===s.operation&&(p[n].update.push(o),e[i]=a),"update"===s.operation&&(s.timea.time?p[n].upload.push(o):console.info("ignore",a)),"delete"===s.operation&&(s.timea.time?p[n].upload.push(o):console.info("ignore",a)))):p[n].upload.push(o):(p[n].save.push(o),e[i]=a)}return{compareResult:p,syncRecords:e}}))}static CompareConfig(e,t,r){return s(this,void 0,void 0,(function*(){let n=Object.keys(e).filter((e=>e.startsWith("config.readerConfig"))),i=Object.keys(e).filter((e=>e.startsWith("config.listConfig"))),o=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"))),u=Object.keys(t).filter((e=>e.startsWith("config.objectConfig"))),d=Object.keys(t).filter((e=>e.startsWith("config.mapConfig"))),l={readerConfig:Array.from(new Set(n.concat(a))),listConfig:Array.from(new Set(i.concat(c))),objectConfig:Array.from(new Set(o.concat(u))),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:[]}},f=["readerConfig","listConfig"];for(let r of f)for(let n of l[r]){let i=n,o=e[n],s=t[n];o?s?o.times.time?h[r].upload.push(i):console.info("ignore",s):h[r].upload.push(i):(h[r].update.push(i),e[n]=s)}let p=["objectConfig","mapConfig"];for(let n of p)for(let i of l[n]){let o=i,s=e[i],a=t[i];s?a?("delete"===a.operation&&("update"===s.operation&&(s.timea.time?(h[n].conflict.push(o),"cloud"===r?(h[n].delete.push(o),e[i]=a):h[n].upload.push(o)):console.info("ignore",a)),"delete"===s.operation&&console.info("ignore",a)),"update"===a.operation&&("update"===s.operation&&(s.timea.time?h[n].upload.push(o):console.info("ignore",a)),"delete"===s.operation&&(s.timea.time?h[n].upload.push(o):console.info("ignore",a)))):h[n].upload.push(o):(h[n].update.push(o),e[i]=a)}return{compareResult:h,syncRecords:e}}))}static compareAll(e,t,r,n,i){return s(this,void 0,void 0,(function*(){let o="cloud";if("yes"===r.getReaderConfig("isKeepLocal")){o="local";let e=r.getObjectConfig(yield n.getFingerprint(),"cloudSyncTime",{time:0,conflictMode:"cloud"}),t=yield i.getCloudConfig("config"),s=JSON.parse(t.cloudSyncTime||"{}");delete s[yield n.getFingerprint()],Object.values(s).filter((t=>"local"===t.conflictMode&&t.time>e.time)).length>0&&(o="cloud")}let{compareResult:s,syncRecords:a}=yield this.CompareDatabase(e,t,o),{compareResult:c,syncRecords:u}=yield this.CompareConfig(a,t,o),d=Object.assign(Object.assign({},s),c);return r.setAllSyncRecord(u),"local"===o&&(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 n.getFingerprint(),{time:(new Date).getTime(),conflictMode:"local"},"cloudSyncTime"):r.setObjectConfig(yield n.getFingerprint(),{time:(new Date).getTime(),conflictMode:"cloud"},"cloudSyncTime"),d}))}static startSync(e,t,r,n,i,o){return s(this,void 0,void 0,(function*(){return[...yield this.syncConfig(e,t,r,i,n),...yield this.syncCover(t,o,i),...yield this.syncBook(t,i)]}))}static syncConfig(e,t,r,n,i){return s(this,void 0,void 0,(function*(){let o=[];for(let t of c){if(e[t].save.length+e[t].update.length>0){let n=yield i.getCloudDatabase(t);for(let i of e[t].save){let e=n.find((e=>e.key===i));e&&(yield r.saveRecord(e,t))}for(let i of e[t].update){let e=n.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 n.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 n of e.readerConfig.update){let e=n.split(".")[3];r.readerConfig&&t.setReaderConfig(e,JSON.parse(r.readerConfig)[e],!1)}for(let n of e.listConfig.update){let e=n.split(".")[3];r[e]&&t.setAllListConfig(JSON.parse(r[e]),e,!1)}for(let n of e.objectConfig.update){let e=n.split(".")[3],i=n.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 n of e.mapConfig.update){let e=n.split(".")[3],i=n.split(".")[2];if(r[i]&&JSON.parse(r[i])&&JSON.parse(r[i])[e]){let n=JSON.parse(r[i])[e];t.setOneMapConfig(e,n,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],n=r.split(".")[2];t.deleteObjectConfig(e,n)}for(let r of e.mapConfig.delete){let e=r.split(".")[3],n=r.split(".")[2];t.deleteMapConfig(e,n)}}for(let t of c)e[t].upload.length>0&&o.push((()=>i.uploadDatabase(t)));return o.push((()=>i.uploadConfig("config"))),o.push((()=>i.uploadConfig("sync"))),o}))}static syncCover(e,t,r){return s(this,void 0,void 0,(function*(){let r=yield t.getLocalCoverList(),n=yield t.getCloudCoverList(),i=Array.from(new Set([...r,...n])),o=[];for(let s of i)r.includes(s)&&!n.includes(s)&&o.push((()=>t.uploadCover(s))),!r.includes(s)&&n.includes(s)&&"adrive"!==e.getItem("defaultSyncOption")&&o.push((()=>t.downloadCover(s)));return o}))}static syncBook(e,t){return s(this,void 0,void 0,(function*(){let r=yield t.getLocalBookList(),n=yield t.getCloudBookList(),i=[],o=Array.from(new Set([...r,...n]));for(let s of o){if(r.includes(s)&&!n.includes(s)){let e=s.split(".")[0],r=s.split(".")[1];i.push((()=>t.uploadBook(e,r)))}let o="yes"===e.getReaderConfig("autoOffline");if(!r.includes(s)&&n.includes(s)&&o&&"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=[],n=[];for(const i of e){const e=i().then((t=>(n.splice(n.indexOf(e),1),t)));r.push(e),n.push(e),n.length>=t&&(yield Promise.race(n))}return Promise.all(r)}for(let t of e)yield t()}))}}const Cm=(Rm=class{static getItem(e){return localStorage.getItem(e)}static setItem(e,t){localStorage.setItem(e,t)}static removeItem(e){localStorage.removeItem(e)}},Om="browser",class extends Rm{static getReaderConfig(e){return JSON.parse(this.getItem("readerConfig")||"{}")[e]}static setReaderConfig(e,t,r=!0){let n=JSON.parse(this.getItem("readerConfig")||"{}");n[e]=t,this.setItem("readerConfig",JSON.stringify(n)),r&&this.setSyncRecord({type:"config",catergory:"readerConfig",name:Om,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 n=r.indexOf(e);n>-1&&r.splice(n,1),this.setAllListConfig(r,t)}static setListConfig(e,t){let r=this.getAllListConfig(t);const n=r.indexOf(e);n>-1?(r.splice(n,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,n=!0){let i=this.getAllObjectConfig(r);i[e]=t,n&&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 n=this.getAllMapConfig(r);void 0===n[e]&&(n[e]=[]),t&&-1===n[e].indexOf(t)&&n[e].unshift(t),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(n,r)}static setOneMapConfig(e,t,r,n=!0){let i=this.getAllMapConfig(r);i[e]=t,n&&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 n=this.getAllMapConfig(r),i=n[e].indexOf(t);n[e].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(n,r)}static deleteFromAllMapConfig(e,t){let r=this.getAllMapConfig(t);Object.keys(r).forEach((n=>{let i=r[n].indexOf(e);i>-1&&(r[n].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:n},{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),n=[];for(let t in r)r[t]&&r[t].indexOf(e)>-1&&n.push(t);return n}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 Rm,Om;class Pm{static saveAllToken(e){return s(this,void 0,void 0,(function*(){if(e)if(o){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(o){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 Im(t),n="undefined"!=typeof crypto&&crypto.subtle?yield function(e,t,r={alg:"HS256",typ:"JWT"}){return s(this,void 0,void 0,(function*(){const n=_m((new TextEncoder).encode(JSON.stringify(r))),i=_m((new TextEncoder).encode(JSON.stringify(e))),o=(new TextEncoder).encode(`${n}.${i}`),s=yield crypto.subtle.importKey("raw",(new TextEncoder).encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return`${n}.${i}.${_m(yield crypto.subtle.sign("HMAC",s,o))}`}))}(e,r):function(e,t){if(!e||!t)return"";const r=l((new TextEncoder).encode(t)),n=Array.from(new Uint8Array(r)),i=(new TextEncoder).encode(e),o=new Uint8Array(i.length);for(let e=0;e=0&&r<=Ym}}function Cy(e){return function(t){return null==t?void 0:t[e]}}var Ry=Cy("byteLength"),Oy=Ty(Ry),Py=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;var _y=qm?function(e){return Gm?Gm(e)&&!by(e):Oy(e)&&Py.test(jm.call(e))}:Ay(!1),My=Cy("length");function Iy(e,t){t=function(e){for(var t={},r=e.length,n=0;n":">",'"':""","'":"'","`":"`"},Ev=kv(Sv),xv=kv(ev(Sv)),Av=$y.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},Tv=/(.)^/,Cv={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},Rv=/\\|'|\r|\n|\u2028|\u2029/g;function Ov(e){return"\\"+Cv[e]}var Pv=/^\s*(\w|\$)+\s*$/;var _v=0;function Mv(e,t,r,n,i){if(!(n instanceof t))return e.apply(r,i);var o=sv(e.prototype),s=e.apply(o,i);return ty(s)?s:o}var Iv=ey((function(e,t){var r=Iv.placeholder,n=function(){for(var i=0,o=t.length,s=Array(o),a=0;a1)$v(a,t-1,r,n),i=n.length;else for(var c=0,u=a.length;c0&&(r=t.apply(this,arguments)),e<=1&&(t=null),r}}var zv=Iv(jv,2);function qv(e,t,r){t=yv(t,r);for(var n,i=Ny(e),o=0,s=i.length;o0?0:i-1;o>=0&&o0?s=o>=0?o:Math.max(o+a,s):a=o>=0?Math.min(o+1,a):o+a+1;else if(r&&o&&a)return n[o=r(n,i)]===i?o:-1;if(i!=i)return(o=t(Dm.call(n,s,a),xy))>=0?o+s:-1;for(o=e>0?s:a-1;o>=0&&o=3;return function(t,r,n,i){var o=!Fv(t)&&Ny(t),s=(o||t).length,a=e>0?0:s-1;for(i||(n=t[o?o[a]:a],a+=e);a>=0&&a=0}var ab=ey((function(e,t,r){var n,i;return py(t)?i=t:(t=cv(t),n=t.slice(0,-1),t=t[t.length-1]),Yv(e,(function(e){var o=i;if(!o){if(n&&n.length&&(e=uv(e,n)),null==e)return;o=e[t]}return null==o?o:o.apply(e,r)}))}));function cb(e,t){return Yv(e,fv(t))}function ub(e,t,r){var n,i,o=-1/0,s=-1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var a=0,c=(e=Fv(e)?e:Yy(e)).length;ao&&(o=n);else t=yv(t,r),Zv(e,(function(e,r,n){((i=t(e,r,n))>s||i===-1/0&&o===-1/0)&&(o=e,s=i)}));return o}var db=/[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;function lb(e){return e?wy(e)?Dm.call(e):oy(e)?e.match(db):Fv(e)?Yv(e,lv):Yy(e):[]}function hb(e,t,r){if(null==t||r)return Fv(e)||(e=Yy(e)),e[bv(e.length-1)];var n=lb(e),i=My(n);t=Math.max(Math.min(t,i),0);for(var o=i-1,s=0;s1&&(n=pv(n,t[1])),t=jy(e)):(n=vb,t=$v(t,!1,!1),e=Object(e));for(var i=0,o=t.length;i1&&(r=t[1])):(t=Yv($v(t,!1,!1),String),n=function(e,r){return!sb(t,r)}),bb(e,n,r)}));function kb(e,t,r){return Dm.call(e,0,Math.max(0,e.length-(null==t||r?1:t)))}function Sb(e,t,r){return null==e||e.length<1?null==t||r?void 0:[]:null==t||r?e[0]:kb(e,e.length-t)}function Eb(e,t,r){return Dm.call(e,null==t||r?1:t)}var xb=ey((function(e,t){return t=$v(t,!0,!0),nb(e,(function(e){return!sb(t,e)}))})),Ab=ey((function(e,t){return xb(e,t)}));function Tb(e,t,r,n){ny(t)||(n=r,r=t,t=!1),null!=r&&(r=yv(r,n));for(var i=[],o=[],s=0,a=My(e);st?(n&&(clearTimeout(n),n=null),a=u,s=e.apply(i,o),n||(i=o=null)):n||!1===r.trailing||(n=setTimeout(c,d)),s};return u.cancel=function(){clearTimeout(n),a=0,n=i=o=null},u},debounce:function(e,t,r){var n,i,o,s,a,c=function(){var u=wv()-i;t>u?n=setTimeout(c,t-u):(n=null,r||(s=e.apply(a,o)),n||(o=a=null))},u=ey((function(u){return a=this,o=u,i=wv(),n||(n=setTimeout(c,t),r&&(s=e.apply(a,o))),s}));return u.cancel=function(){clearTimeout(n),n=o=a=null},u},wrap:function(e,t){return Iv(t,e)},negate:Dv,compose:function(){var e=arguments,t=e.length-1;return function(){for(var r=t,n=e[t].apply(this,arguments);r--;)n=e[r].call(this,n);return n}},after:function(e,t){return function(){if(--e<1)return t.apply(this,arguments)}},before:jv,once:zv,findKey:qv,findIndex:Wv,findLastIndex:Kv,sortedIndex:Vv,indexOf:Qv,lastIndexOf:Jv,find:Xv,detect:Xv,findWhere:function(e,t){return Xv(e,hv(t))},each:Zv,forEach:Zv,map:Yv,collect:Yv,reduce:tb,foldl:tb,inject:tb,reduceRight:rb,foldr:rb,filter:nb,select:nb,reject:function(e,t,r){return nb(e,Dv(yv(t)),r)},every:ib,all:ib,some:ob,any:ob,contains:sb,includes:sb,include:sb,invoke:ab,pluck:cb,where:function(e,t){return nb(e,hv(t))},max:ub,min:function(e,t,r){var n,i,o=1/0,s=1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var a=0,c=(e=Fv(e)?e:Yy(e)).length;an||void 0===r)return 1;if(re.map((e=>e.name)),Fb=e=>e.map((e=>e.key)),$b=(e,t)=>{let r=[];for(let n=0;n-1&&r.push(t.indexOf(e[n]));return r.length{if(-1===e.indexOf(n))for(let e=0;ee-Math.min(...r))))]};class Ub{static sortBooks(e,t,r){let n=e.map((e=>e.key)),i=(e=>e.getAllListConfig("recentBooks"))(r);if(1===t.sort||0===t.sort)return 1===t.order?$b(i,n).reverse():$b(i,n);if(2===t.sort){let r=Nb(e),n=Nb(e).sort();return 1===t.order?$b(n,r).reverse():$b(n,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=Fb(e);return 1===t.order?$b(Ib.union(n,i),i).reverse():$b(Ib.union(n,i),i)}if(5===t.sort){let r=Fb(e),n=(e=>Ib.sortBy(e.map((e=>({key:e.key,author:e.author}))),"author").map((e=>e.key)))(e);return 1===t.order?$b(n,r).reverse():$b(n,r)}if(6===t.sort){let n=(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=Fb(e);return 1===t.order?$b(n,i).reverse():$b(n,i)}}static sortNotes(e,t,r=[]){if(3===t.sort){let r=Ib.clone(e).reverse(),n=Ib.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:e.chapterIndex}))));n=1===t.order?Ib.sortBy(n,"chapterIndex"):Ib.sortBy(n,"chapterIndex").reverse();let i=Ib.uniq(n.map((e=>e.chapter))),o={};return i.forEach((e=>{o[e]=[]})),r.forEach((e=>{o[e.chapter].push(e)})),i.map((e=>({group:e,notes:o[e]})))||[]}if(2===t.sort){let r=Ib.clone(e).reverse(),n=Ib.uniq(e.map((e=>e.date.year+"-"+e.date.month+"-"+e.date.day)));1===t.order?n.sort():n.sort().reverse();let i={};return n.forEach((e=>{i[e]=[]})),r.forEach((e=>{n.forEach((t=>{t===e.date.year+"-"+e.date.month+"-"+e.date.day&&i[t].push(e)}))})),i||{}}if(1===t.sort){let n=Ib.clone(e).reverse(),i=Ib.uniq(e.map((e=>{let t=Ib.findLastIndex(r,{key:e.bookKey});return t>-1?r[t].name:""})));1===t.order?i.sort():i.sort().reverse();let o={};return i.forEach((e=>{o[e]=[]})),n.forEach((e=>{i.forEach((t=>{let n=Ib.findLastIndex(r,{key:e.bookKey});n>-1&&t===r[n].name&&o[t].push(e)}))})),o||{}}}static sortBookmarks(e,t){if(3===t.sort){let r=Ib.clone(e).reverse(),n=Ib.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:parseInt(JSON.parse(e.cfi).chapterDocIndex)}))));n=1===t.order?Ib.sortBy(n,"chapterIndex"):Ib.sortBy(n,"chapterIndex").reverse();let i=Ib.uniq(n.map((e=>e.chapter))),o={};return i.forEach((e=>{o[e]=[]})),r.forEach((e=>{o[e.chapter].push(e)})),i.map((e=>({group:e,bookmarks:o[e]})))||[]}}}class Lb{static getDefaultCss(e){return`::selection{background:#f3a6a68c}::-moz-selection{background:#f3a6a68c}.kookit-note:hover{cursor:pointer;}img{max-width:100% !important}body,html{margin: 0px !important; padding: 0px !important;}.kookit-text{${this.getCustomCss(e)}}.kookit-title{${this.getCustomCss(e,!0)}}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,t=!1){return`font-size: ${t?"":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 Bb{static mergeArray(e,t){var r=[];for(let t of e)r.push(t);for(let i of t){var n=!0;for(let t of e)if(i===t){n=!1;break}n&&r.push(i)}return r}static fuzzyQuery(e,t){for(var r=[],n=0;n-1&&r.push(n);return r}static mouseSearch(e){let t=document.querySelector(".header-search-box").value.toLowerCase(),r=[],n=[];if(!e)return[];e.forEach((e=>{r.push(e.name.toLowerCase()),n.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,t),o=this.fuzzyQuery(n,t);return this.mergeArray(i,o)}static keywordSearch(e,t){let r=[],n=[];if(!t)return[];t.forEach((e=>{r.push(e.name.toLowerCase()),n.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,e),o=this.fuzzyQuery(n,e);return this.mergeArray(i,o)}static keySearch(e,t){if(e&&13===e.keyCode){let r=[],n=[];if(!t)return[];t.forEach((e=>{r.push(e.name.toLowerCase()),n.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,e.target.value.toLowerCase()),o=this.fuzzyQuery(n,e.target.value.toLowerCase());return this.mergeArray(i,o)}}static mouseNoteSearch(e){let t=document.querySelector(".header-search-box").value.toLowerCase(),r=[],n=[];e.forEach((e=>{r.push(e.notes.toLowerCase()),n.push(e.text.toLowerCase())}));let i=this.fuzzyQuery(r,t),o=this.fuzzyQuery(n,t);return this.mergeArray(i,o)}static keyNoteSearch(e,t){if(e&&13===e.keyCode){let r=[],n=[];t.forEach((e=>{r.push(e.notes.toLowerCase()),n.push(e.text.toLowerCase())}));let i=this.fuzzyQuery(r,e.target.value.toLowerCase()),o=this.fuzzyQuery(n,e.target.value.toLowerCase());return this.mergeArray(i,o)}}}export{bm as BookHelper,f as CommonTool,Cm as ConfigService,m as KookitConfig,Am as LoginHelper,Sm as ReaderRequest,Bb as SearchUtil,Ub as SortUtil,mm as SqlStatement,Lb as StyleHelper,Tm as SyncHelper,um as SyncUtil,Em as ThirdpartyRequest,Pm as TokenService,xm as UserRequest}; +import e from"axios";import{Storage as t}from"megajs";import{Buffer as r}from"buffer";import{createClient as n,AuthType as i}from"webdav/dist/web/index.js";import{isElectron as o}from"react-device-detect";function s(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(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((n=n.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"],u=e=>{const t=atob(e),r=t.length,n=new Uint8Array(r);for(let e=0;e{let t="";const r=new Uint8Array(e),n=r.byteLength;for(let e=0;ee>>>t|e<<32-t,n=(e,t,r)=>e&t^~e&r,i=(e,t,r)=>e&t^e&r^t&r,o=e=>r(e,2)^r(e,13)^r(e,22),s=e=>r(e,6)^r(e,11)^r(e,25),a=e=>r(e,7)^r(e,18)^e>>>3,c=e=>r(e,17)^r(e,19)^e>>>10,u=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],d=8*e.length,l=(960-(8*e.length+1)%512)%512,h=e.length+Math.ceil((l+1)/8)+8,f=new Uint8Array(h);f.set(e),f[e.length]=128;new DataView(f.buffer,f.byteLength-8).setBigUint64(0,BigInt(d),!1);for(let e=0;e>>0;let[l,h,p,g,m,y,v,b]=u;for(let e=0;e<64;e++){const r=b+s(m)+n(m,y,v)+t[e]+d[e]>>>0,a=o(l)+i(l,h,p)>>>0;b=v,v=y,y=m,m=g+r>>>0,g=p,p=h,h=l,l=r+a>>>0}u[0]=u[0]+l>>>0,u[1]=u[1]+h>>>0,u[2]=u[2]+p>>>0,u[3]=u[3]+g>>>0,u[4]=u[4]+m>>>0,u[5]=u[5]+y>>>0,u[6]=u[6]+v>>>0,u[7]=u[7]+b>>>0}const p=new ArrayBuffer(32),g=new DataView(p);return u.forEach(((e,t)=>{g.setUint32(4*t,e,!1)})),p}class h{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 n=()=>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"application/json"===e?"json":e.startsWith("image/")?e.split("/")[1]:"application/zip"===e?"zip":"application/epub+zip"===e?"epub":"text/plain"===e?"txt":"application/pdf"===e?"pdf":"application/x-mobipocket-ebook"===e?"mobi":"application/vnd.amazon.ebook"===e?"azw3":"application/x-cbz"===e?"cbz":"application/x-cbr"===e?"cbr":"application/x-cbt"===e?"cbt":"application/x-cb7"===e?"cb7":"application/x-fictionbook+xml"===e?"fb2":"text/html"===e?"html":"text/css"===e?"css":"application/javascript"===e?"js":"application/xml"===e?"xml":"application/xhtml+xml"===e?"xhtml":"application/oebps-package+xml"===e?"opf":"application/x-dtbncx+xml"===e?"ncx":"audio/mpeg"===e?"mp3":"audio/wav"===e?"wav":"audio/ogg"===e?"ogg":"video/mp4"===e?"mp4":"video/webm"===e?"webm":"video/x-msvideo"===e?"avi":"video/x-ms-wmv"===e?"wmv":"video/x-flv"===e?"flv":"application/x-mpegURL"===e?"m3u8":"video/MP2T"===e?"ts":"video/3gpp"===e?"3gp":"video/3gpp2"===e?"3g2":"application/x-sqlite3"===e?"db":"",databaseList:c,configList:["themeColors","readingTime","cloudSyncTime","recentBooks","recentAdd","deletedBooks","favoriteBooks","shelfList","txtParsers","noteTags","recordLocation","sortedShelfList","kindleDeviceList"],copyArrayBuffer:e=>{var t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e)),t},base64ToArrayBuffer:u,arrayBufferToBase64:d,generateSHA256Hash:function(e){return s(this,void 0,void 0,(function*(){const t=(new TextEncoder).encode(e),r="undefined"!=typeof crypto&&crypto.subtle?yield crypto.subtle.digest("SHA-256",t):l(t),n=Array.from(new Uint8Array(r)).map((e=>e.toString(16).padStart(2,"0"))).join("");return n}))},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 p={publicUrl:"https://api.960960.xyz",cloudUrl:"https://cloud.960960.xyz",devUrl:"http://192.168.28.159:8000"},g={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 m={CloudConfig:p,ThirdpartyConfig:g,LoginAuthRequest:{google:{clientId:g.googleClientId,scopes:["openid"],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{prompt:"consent",scope:"openid"}},microsoft:{clientId:g.microsoftClientId,scopes:["openid","profile","User.Read","offline_access"],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{scope:"openid profile User.Read offline_access"}},facebook:{clientId:g.facebookClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{scope:""}},github:{clientId:g.githubClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{scope:""}},email:{clientId:"",scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.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:g.dropboxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{token_access_type:"offline"}},boxnet:{clientId:g.boxClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}},pcloud:{clientId:g.pcloudClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{grant_type:"authorization_code"}},adrive:{clientId:g.adriveClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}},microsoft:{clientId:g.microsoftClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.callbackUrl,extraParams:{scope:"files.readwrite.appfolder offline_access"}},google:{clientId:g.googleClientId,scopes:[],usePKCE:!1,responseType:"code",redirectUri:g.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 y{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new h(1),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=5){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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(),n=yield this.getDriveId();try{try{const i=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:n,file_path:t},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});if(i.data)return i.data.file_id}catch(i){const o=t.split("/").filter((e=>e));let s="",a="root";for(const t of o){s+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:n,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:n,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(),n=yield this.getDriveId(),i=yield this.getFolderIdByPath(this.baseFolder+"/"+t);let o=[],s="",a=!0;for(;a;){const t=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:n,parent_file_id:i,marker:s||void 0},{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),c=t.data.items||[];o=o.concat(c),s=t.data.next_marker,a=!!s&&100===c.length}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(),n=yield this.getDriveId(),i=yield this.getFolderIdByPath(this.baseFolder+"/"+t);return!i||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:n,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 n=yield this.refreshToken(),i=yield this.getDriveId(),o=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:t},{headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}});(null===(r=o.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:o.data.file_id},{headers:{Authorization:`Bearer ${n}`,"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:g.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:g.adriveClientId,redirect_uri:g.callbackUrl,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class v extends y{constructor(e,t){super(e,t)}uploadFile(t,r){return s(this,void 0,void 0,(function*(){return new Promise(((n,i)=>s(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken(),o=yield this.getDriveId(),s=r.substring(0,r.lastIndexOf("/")),a=r.substring(r.lastIndexOf("/")+1),c=yield this.getFolderIdByPath(this.baseFolder+"/"+s),u=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:o,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:l,part_info_list:h}=u.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:o,file_id:d,upload_id:l},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),n(!0)}catch(e){console.error("Error uploading file:",e),n(!1)}}))))}))}downloadFile(t){return new Promise(((r,n)=>s(this,void 0,void 0,(function*(){try{const n=yield this.refreshToken(),i=yield this.getDriveId(),o=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:i,file_path:this.baseFolder+"/"+t},{headers:{Authorization:`Bearer ${n}`,"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:o},{headers:{Authorization:`Bearer ${n}`,"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 b{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new h(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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*(){if(""==t)return"0";const r=yield this.refreshToken(),n=t.split("/");let i="0";for(const t of n){const n=`https://api.box.com/2.0/folders/${i}/items?fields=id,name&type=folder&limit=1000`;try{const o=(yield e.get(n,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(o)i=o.id;else{const n={name:t,parent:{id:i},type:"folder"};i=(yield e.post("https://api.box.com/2.0/folders",n,{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 n=this.baseFolder+"/"+t;for(;n.startsWith("/");)n=n.substring(1);let i=yield this.getFolderIdByPath(n),o=[],s=0,a=!0;const c=1e3;for(;a;){const t=yield e.get(`https://api.box.com/2.0/folders/${i}/items`,{params:{limit:c,offset:s},headers:{Authorization:`Bearer ${r}`}}),n=t.data.entries||[];o=o.concat(n),s+=n.length,a=n.length===c&&t.data.total_count>s}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(),n=t.substring(0,t.lastIndexOf("/")),i=t.substring(t.lastIndexOf("/")+1);let o=this.baseFolder+"/"+n;for(;o.startsWith("/");)o=o.substring(1);const s=yield this.getFolderIdByPath(o);if(!s)return!0;const a=`https://api.box.com/2.0/folders/${s}/items?fields=id,name&type=file&limit=1000`,c=(yield e.get(a,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));return!c||(yield e.delete(`https://api.box.com/2.0/files/${c.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:g.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:g.boxClientId,redirect_uri:g.callbackUrl,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}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 n=yield this.refreshToken(),i=r.substring(0,r.lastIndexOf("/")),o=r.substring(r.lastIndexOf("/")+1);let s=this.baseFolder+"/"+i;for(;s.startsWith("/");)s=s.substring(1);const a=yield this.getFolderIdByPath(s);if(!a)throw new Error("Folder not found");const c=(yield this.listFiles(i)).find((e=>e===o));c&&(yield this.deleteFileWithoutQueue(i+"/"+o));let u=new File([t],o,{lastModified:(new Date).getTime(),type:t.type});const d=new FormData;d.append("file",u),d.append("parent_id",a);const l=yield e.post("https://upload.box.com/api/2.0/files/content",d,{headers:{Authorization:`Bearer ${n}`,"Content-Type":"multipart/form-data"},params:{if_match:"false",fields:"name,id"},maxContentLength:1/0,maxBodyLength:1/0});return!(l.status>=300)||(console.error("Error occurred during file upload:",l),!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(),n=t.substring(0,t.lastIndexOf("/")),i=t.substring(t.lastIndexOf("/")+1);let o=this.baseFolder+"/"+n;for(;o.startsWith("/");)o=o.substring(1);const s=yield this.getFolderIdByPath(o);if(!s)return console.error("Folder not found"),!0;const a=`https://api.box.com/2.0/folders/${s}/items?fields=id,name&type=file&limit=1000`,c=(yield e.get(a,{headers:{Authorization:`Bearer ${r}`}})).data.entries.find((e=>e.name===i&&"file"===e.type));if(!c)return console.error("File not found:",i),!0;const u=yield e({url:`https://api.box.com/2.0/files/${c.id}/content`,method:"get",headers:{Authorization:`Bearer ${r}`},responseType:"arraybuffer"});return u.status>=300?(console.error("Error occurred during file download:",u),!1):u.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class k{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new h(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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 n=[],i=!0,o=null;for(;i;){let s;s=o?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:o},{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||[];n=n.concat(a),i=s.data.has_more,o=s.data.cursor}return[...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();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:g.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${g.dropboxClientId}&redirect_uri=${g.callbackUrl}`}}class S extends k{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 n=yield this.refreshToken();let i=r.split("/").pop()||"",o=new File([t],i,{lastModified:(new Date).getTime(),type:t.type});const s=yield e.post("https://content.dropboxapi.com/2/files/upload",o,{headers:{Authorization:`Bearer ${n}`,"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(),n=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 n.status>=300?(console.error("Error occurred during file download:",n),!1):n.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class E{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new h(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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 n=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 "+n}});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(),n=yield this.getFolderId(t);if(n)return n;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(),n=`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(n,{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 n=yield this.checkFolder(t),i=[],o="",s=!0;for(;s;){let t=`https://www.googleapis.com/drive/v3/files?q='${n}'+in+parents&spaces=appDataFolder&fields=nextPageToken,files(id,name)&pageSize=1000`;o&&(t+=`&pageToken=${o}`);const a=yield e.get(t,{headers:{Authorization:`Bearer ${r}`}}),c=a.data.files||[];i=i.concat(c),o=a.data.nextPageToken,s=!!o}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],n=t.split("/")[0],i=yield this.getFolderId(n),o=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 ${o}`}});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:g.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${g.callbackUrl}&prompt=consent&response_type=code&client_id=${g.googleClientId}&scope=https://www.googleapis.com/auth/drive.appdata&access_type=offline`}}class x extends E{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 n=yield this.refreshToken();let i=r.split("/").pop()||"",o=new File([t],i,{lastModified:(new Date).getTime(),type:t.type}),s=r.split(".").pop(),c=a(s||""),u=r.split("/")[0],d=yield this.checkFolder(u),l=yield this.getFileId(i||"",d);const h={mimeType:c,name:i,parents:[d]},f=l?`https://www.googleapis.com/upload/drive/v3/files/${l}?uploadType=resumable`:"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",p=(yield e({method:l?"PATCH":"POST",url:f,data:l?null:JSON.stringify(h),headers:{Authorization:"Bearer "+n,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location,g=yield this.getData(o);if(0===Object.keys(g).length)return!1;const m=yield e.put(p,g.data,{headers:{Authorization:"Bearer "+n,"Content-Type":"application/zip","Content-Range":`bytes 0-${g.fileSize-1}/${g.fileSize}`},maxContentLength:1/0,maxBodyLength:1/0});return!(m.status>=300)||(console.error("Error occurred during file download:",m),!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 n=t.split("/").pop(),i=t.split("/")[0],o=yield this.checkFolder(i),s=yield this.getFileId(n||"",o);if(!s)return console.error("File not found:",n),!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 n=new FileReader;n.onload=r=>t({fileName:e.name,mimeType:e.type,fileSize:e.size,data:r.target.result}),n.onerror=e=>r(e),n.readAsArrayBuffer(e)})):{}}))}}class A{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new h(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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;if(""===this.baseFolder)return this.root=e,this.root;let t=e.children.find((e=>e.name===this.baseFolder&&e.directory));return t||(t=yield e.mkdir(this.baseFolder)),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 n=(()=>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,n),yield n}))}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}}const r=t.children.map((e=>e.name));return r}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("/"),n=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===n&&!e.directory));return!i||(yield i.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class T extends A{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 n=yield this.getRoot();const i=t.split("/"),o=i.pop()||"";for(const e of i){if(!e)continue;let t=n.children.find((t=>t.name===e&&t.directory));t||(t=yield this.createFolder(n,e)),n=t}const s=new File([e],o,{lastModified:(new Date).getTime(),type:e.type}),a=yield e.arrayBuffer(),c=new Uint8Array(a),u=r.from(c),d=n.children.find((e=>e.name===o&&!e.directory));return d&&(yield d.delete()),yield n.upload({name:o,size:s.size},u).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("/"),n=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===n&&!e.directory));if(!i)return!0;return(yield i.downloadBuffer()).buffer}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 h(3)}retryOperation(e,t=3){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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 n=[],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 o=t.data.value||[];n=n.concat(o),i=t.data["@odata.nextLink"]||""}return[...new Set(n.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(),n=yield e.delete(`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}`,{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}});return!(n.status>=300)||(console.error("Error deleting file:",n),!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:g.callbackUrl,code:e})).data.refresh_token}))}getAuthUrl(){return`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${g.microsoftClientId}&scope=files.readwrite.appfolder offline_access&response_type=code&redirect_uri=${g.callbackUrl}`}}class R 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 n=yield this.refreshToken();let i=r.split("/").pop()||"",o=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 "+n,"Content-Type":"application/json"},maxContentLength:1/0,maxBodyLength:1/0});let c=o.size;const u=o.type,d=a.data.uploadUrl,l=yield e.put(d,o,{headers:{"Content-Type":u,"Content-Range":`bytes 0-${c-1}/${c}`},maxContentLength:1/0,maxBodyLength:1/0});return!(l.status>=300)||(console.error("Error occurred during file download:",l),!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(),n=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/content`,i=yield e.get(n,{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 O{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 P{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.taskQueue=new h(3)}retryOperation(e,t=5){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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(),n=yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:r,path:"/"+t,recursive:0}});return 0!==n.data.result?[]:n.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(),n=yield e.get("https://api.pcloud.com/deletefile",{params:{access_token:r,path:"/"+t}});return 0===n.data.result||(console.error("Error deleting file:",n.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:g.callbackUrl,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${g.pcloudClientId}&response_type=code&redirect_uri=${g.callbackUrl}`}}class _ extends P{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 n=yield this.refreshToken(),i=r.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(i,n))){if(!(yield this.createFolder(i,n)))return!1}let o=r.split("/").pop()||"",s=new File([t],o,{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:n,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(),n=yield e.get("https://api.pcloud.com/getfilelink",{params:{access_token:r,path:`/${t}`}});if(0!==n.data.result)return console.error("Error getting file link:",n.data),!0;const i=`https://${n.data.hosts[0]}${n.data.path}`,o=yield e.get(i,{responseType:"arraybuffer",maxContentLength:1/0,maxBodyLength:1/0});return o.status>=300?(console.error("Error downloading file:",o),!1):o.data}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}const M=e=>{let t=e.httpHandler;return{setHttpHandler(e){t=e},httpHandler:()=>t,updateHttpClientConfig(e,r){t.updateHttpClientConfig(e,r)},httpHandlerConfigs:()=>t.httpHandlerConfigs()}};var I,N,F,$,U;!function(e){e.HEADER="header",e.QUERY="query"}(I||(I={})),function(e){e.HEADER="header",e.QUERY="query"}(N||(N={})),function(e){e.HTTP="http",e.HTTPS="https"}(F||(F={})),function(e){e.MD5="md5",e.CRC32="crc32",e.CRC32C="crc32c",e.SHA1="sha1",e.SHA256="sha256"}($||($={})),function(e){e[e.HEADER=0]="HEADER",e[e.TRAILER=1]="TRAILER"}(U||(U={}));const L="__smithy_context";var B,D;!function(e){e.PROFILE="profile",e.SSO_SESSION="sso-session",e.SERVICES="services"}(B||(B={})),function(e){e.HTTP_0_9="http/0.9",e.HTTP_1_0="http/1.0",e.TDS_8_0="tds/8.0"}(D||(D={}));class j{constructor(e){this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?":"!==e.protocol.slice(-1)?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?"/"!==e.path.charAt(0)?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){const t=new j({...e,headers:{...e.headers}});var r;return t.query&&(t.query=(r=t.query,Object.keys(r).reduce(((e,t)=>{const n=r[t];return{...e,[t]:Array.isArray(n)?[...n]:n}}),{}))),t}static isInstance(e){if(!e)return!1;const t=e;return"method"in t&&"protocol"in t&&"hostname"in t&&"path"in t&&"object"==typeof t.query&&"object"==typeof t.headers}clone(){return j.clone(this)}}class z{constructor(e){this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){if(!e)return!1;const t=e;return"number"==typeof t.statusCode&&"object"==typeof t.headers}}const q={step:"build",tags:["SET_EXPECT_HEADER","EXPECT_HEADER"],name:"addExpectContinueMiddleware",override:!0},H=e=>({applyToStack:t=>{t.add(function(e){return t=>async r=>{const{request:n}=r;return j.isInstance(n)&&n.body&&"node"===e.runtime&&"FetchHttpHandler"!==e.requestHandler?.constructor?.name&&(n.headers={...n.headers,Expect:"100-continue"}),t({...r,request:n})}}(e),q)}}),W="WHEN_SUPPORTED",K=W,V=W;var G,J;!function(e){e.MD5="MD5",e.CRC32="CRC32",e.CRC32C="CRC32C",e.SHA1="SHA1",e.SHA256="SHA256"}(G||(G={})),function(e){e.HEADER="header",e.TRAILER="trailer"}(J||(J={}));const Q=G.MD5,X=G.CRC32;var Z;function Y(e,t,r){e.__aws_sdk_context?e.__aws_sdk_context.features||(e.__aws_sdk_context.features={}):e.__aws_sdk_context={features:{}},e.__aws_sdk_context.features[t]=r}!function(e){e.ENV="env",e.CONFIG="shared config entry"}(Z||(Z={}));const ee=e=>z.isInstance(e)?e.headers?.date??e.headers?.Date:void 0,te=e=>new Date(Date.now()+e),re=(e,t)=>{const r=Date.parse(e);return((e,t)=>Math.abs(te(t).getTime()-e)>=3e5)(r,t)?r-Date.now():t},ne=(e,t)=>{if(!t)throw new Error(`Property \`${e}\` is not resolved for AWS SDK SigV4Auth`);return t},ie=async e=>{const t=ne("context",e.context),r=ne("config",e.config),n=t.endpointV2?.properties?.authSchemes?.[0],i=ne("signer",r.signer),o=await i(n),s=e?.signingRegion,a=e?.signingRegionSet,c=e?.signingName;return{config:r,signer:o,signingRegion:s,signingRegionSet:a,signingName:c}};class oe{async sign(e,t,r){if(!j.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const n=await ie(r),{config:i,signer:o}=n;let{signingRegion:s,signingName:a}=n;const c=r.context;if(c?.authSchemes?.length){const[e,t]=c.authSchemes;"sigv4a"===e?.name&&"sigv4"===t?.name&&(s=t?.signingRegion??s,a=t?.signingName??a)}return await o.sign(e,{signingDate:te(i.systemClockOffset),signingRegion:s,signingService:a})}errorHandler(e){return t=>{const r=t.ServerTime??ee(t.$response);if(r){const n=ne("config",e.config),i=n.systemClockOffset;n.systemClockOffset=re(r,n.systemClockOffset);n.systemClockOffset!==i&&t.$metadata&&(t.$metadata.clockSkewCorrected=!0)}throw t}}successHandler(e,t){const r=ee(e);if(r){const e=ne("config",t.config);e.systemClockOffset=re(r,e.systemClockOffset)}}}class se extends oe{async sign(e,t,r){if(!j.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const{config:n,signer:i,signingRegion:o,signingRegionSet:s,signingName:a}=await ie(r),c=(await(n.sigv4aSigningRegionSet?.())??s??[o]).join(",");return await i.sign(e,{signingDate:te(n.systemClockOffset),signingRegion:c,signingService:a})}}const ae=e=>e[L]||(e[L]={}),ce=e=>{if("function"==typeof e)return e;const t=Promise.resolve(e);return()=>t};const ue=(e,t)=>(r,n)=>async i=>{const o=e.httpAuthSchemeProvider(await t.httpAuthSchemeParametersProvider(e,n,i.input)),s=function(e){const t=new Map;for(const r of e)t.set(r.schemeId,r);return t}(e.httpAuthSchemes),a=ae(n),c=[];for(const r of o){const i=s.get(r.schemeId);if(!i){c.push(`HttpAuthScheme \`${r.schemeId}\` was not enabled for this service.`);continue}const o=i.identityProvider(await t.identityProviderConfigProvider(e));if(!o){c.push(`HttpAuthScheme \`${r.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties:u={},signingProperties:d={}}=r.propertiesExtractor?.(e,n)||{};r.identityProperties=Object.assign(r.identityProperties||{},u),r.signingProperties=Object.assign(r.signingProperties||{},d),a.selectedHttpAuthScheme={httpAuthOption:r,identity:await o(r.identityProperties),signer:i.signer};break}if(!a.selectedHttpAuthScheme)throw new Error(c.join("\n"));return r(i)},de={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},le={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},he={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function fe(e,t,r){return{applyToStack:n=>{n.add(((e,t)=>r=>async n=>{const{response:i}=await r(n);try{return{response:i,output:await t(i,e)}}catch(e){if(Object.defineProperty(e,"$response",{value:i}),!("$metadata"in e)){const t="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";e.message+="\n "+t,void 0!==e.$responseBodyText&&e.$response&&(e.$response.body=e.$responseBodyText)}throw e}})(e,r),le),n.add(((e,t)=>(r,n)=>async i=>{const o=n.endpointV2?.url&&e.urlParser?async()=>e.urlParser(n.endpointV2.url):e.endpoint;if(!o)throw new Error("No valid endpoint provider available.");const s=await t(i.input,{...e,endpoint:o});return r({...i,request:s})})(e,t),he)}}}const pe=e=>e=>{throw e},ge=(e,t)=>{},me={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},ye=e=>({applyToStack:e=>{e.addRelativeTo(((e,t)=>async r=>{if(!j.isInstance(r.request))return e(r);const n=ae(t).selectedHttpAuthScheme;if(!n)throw new Error("No HttpAuthScheme was selected: unable to sign request");const{httpAuthOption:{signingProperties:i={}},identity:o,signer:s}=n,a=await e({...r,request:await s.sign(r.request,o,i)}).catch((s.errorHandler||pe)(i));return(s.successHandler||ge)(a.response,i),a}),me)}}),ve=e=>{if("function"==typeof e)return e;const t=Promise.resolve(e);return()=>t},be={},we=new Array(64);for(let e=0,t="A".charCodeAt(0),r="Z".charCodeAt(0);e+t<=r;e++){const r=String.fromCharCode(e+t);be[r]=e,we[e]=r}for(let e=0,t="a".charCodeAt(0),r="z".charCodeAt(0);e+t<=r;e++){const r=String.fromCharCode(e+t),n=e+26;be[r]=n,we[n]=r}for(let e=0;e<10;e++){be[e.toString(10)]=e+52;const t=e.toString(10),r=e+52;be[t]=r,we[r]=t}be["+"]=62,we[62]="+",be["/"]=63,we[63]="/";const ke=e=>{let t=e.length/4*3;"=="===e.slice(-2)?t-=2:"="===e.slice(-1)&&t--;const r=new ArrayBuffer(t),n=new DataView(r);for(let t=0;t>=6;const o=t/4*3;r>>=i%8;const s=Math.floor(i/8);for(let e=0;e>t)}}return new Uint8Array(r)},Se=e=>(new TextEncoder).encode(e),Ee=e=>"string"==typeof e?Se(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e),xe=e=>{if("string"==typeof e)return e;if("object"!=typeof e||"number"!=typeof e.byteOffset||"number"!=typeof e.byteLength)throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(e)};function Ae(e){let t;t="string"==typeof e?Se(e):e;const r="object"==typeof t&&"number"==typeof t.length,n="object"==typeof t&&"number"==typeof t.byteOffset&&"number"==typeof t.byteLength;if(!r&&!n)throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let i="";for(let e=0;e>t]}i+="==".slice(0,4-o)}return i}class Te extends Uint8Array{static fromString(e,t="utf-8"){if("string"==typeof e)return function(e,t){return"base64"===t?Te.mutate(ke(e)):Te.mutate(Se(e))}(e,t);throw new Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,Te.prototype),e}transformToString(e="utf-8"){return function(e,t="utf-8"){return"base64"===t?Ae(e):xe(e)}(this,e)}}const Ce=(e,t)=>{const{base64Encoder:r,bodyLengthChecker:n,checksumAlgorithmFn:i,checksumLocationName:o,streamHasher:s}=t,a=void 0!==r&&void 0!==n&&void 0!==i&&void 0!==o&&void 0!==s,c=a?s(i,e):void 0,u=e.getReader();return new ReadableStream({async pull(e){const{value:t,done:i}=await u.read();if(i){if(e.enqueue("0\r\n"),a){const t=r(await c);e.enqueue(`${o}:${t}\r\n`),e.enqueue("\r\n")}e.close()}else e.enqueue(`${(n(t)||0).toString(16)}\r\n${t}\r\n`)}})},Re=e=>encodeURIComponent(e).replace(/[!'()*]/g,Oe),Oe=e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`;function Pe(e,t){return new Request(e,t)}function _e(e=0){return new Promise(((t,r)=>{e&&setTimeout((()=>{const t=new Error(`Request did not complete within ${e} ms`);t.name="TimeoutError",r(t)}),e)}))}const Me={supported:void 0};class Ie{static create(e){return"function"==typeof e?.handle?e:new Ie(e)}constructor(e){"function"==typeof e?this.configProvider=e().then((e=>e||{})):(this.config=e??{},this.configProvider=Promise.resolve(this.config)),void 0===Me.supported&&(Me.supported=Boolean("undefined"!=typeof Request&&"keepalive"in Pe("https://[::1]")))}destroy(){}async handle(e,{abortSignal:t}={}){this.config||(this.config=await this.configProvider);const r=this.config.requestTimeout,n=!0===this.config.keepAlive,i=this.config.credentials;if(t?.aborted){const e=new Error("Request aborted");return e.name="AbortError",Promise.reject(e)}let o=e.path;const s=function(e){const t=[];for(let r of Object.keys(e).sort()){const n=e[r];if(r=Re(r),Array.isArray(n))for(let e=0,i=n.length;e{};const p=Pe(d,h),g=[fetch(p).then((e=>{const t=e.headers,r={};for(const e of t.entries())r[e[0]]=e[1];return null!=e.body?{response:new z({headers:r,reason:e.statusText,statusCode:e.status,body:e.body})}:e.blob().then((t=>({response:new z({headers:r,reason:e.statusText,statusCode:e.status,body:t})})))})),_e(r)];return t&&g.push(new Promise(((e,r)=>{const n=()=>{const e=new Error("Request aborted");e.name="AbortError",r(e)};if("function"==typeof t.addEventListener){const e=t;e.addEventListener("abort",n,{once:!0}),f=()=>e.removeEventListener("abort",n)}else t.onabort=n}))),Promise.race(g).finally(f)}updateHttpClientConfig(e,t){this.config=void 0,this.configProvider=this.configProvider.then((r=>(r[e]=t,r)))}httpHandlerConfigs(){return this.config??{}}}const Ne=async e=>"function"==typeof Blob&&e instanceof Blob||"Blob"===e.constructor?.name?new Uint8Array(await e.arrayBuffer()):async function(e){const t=[],r=e.getReader();let n=!1,i=0;for(;!n;){const{done:e,value:o}=await r.read();o&&(t.push(o),i+=o.length),n=e}const o=new Uint8Array(i);let s=0;for(const e of t)o.set(e,s),s+=e.length;return o}(e);const Fe={},$e={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();1===t.length&&(t=`0${t}`),Fe[e]=t,$e[t]=e}function Ue(e){if(e.length%2!=0)throw new Error("Hex encoded strings must have an even number length");const t=new Uint8Array(e.length/2);for(let r=0;r"function"==typeof ReadableStream&&(e?.constructor?.name===ReadableStream.name||e instanceof ReadableStream),De="The stream has already been transformed.",je=e=>{if(!ze(e)&&!Be(e)){throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${e?.__proto__?.constructor?.name||e}`)}let t=!1;const r=async()=>{if(t)throw new Error(De);return t=!0,await Ne(e)};return Object.assign(e,{transformToByteArray:r,transformToString:async e=>{const t=await r();if("base64"===e)return Ae(t);if("hex"===e)return Le(t);if(void 0===e||"utf8"===e||"utf-8"===e)return xe(t);if("function"==typeof TextDecoder)return new TextDecoder(e).decode(t);throw new Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(t)throw new Error(De);if(t=!0,ze(e))return(e=>{if("function"!=typeof e.stream)throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body");return e.stream()})(e);if(Be(e))return e;throw new Error(`Cannot transform payload to web stream, got ${e}`)}})},ze=e=>"function"==typeof Blob&&e instanceof Blob;const qe="function"==typeof ReadableStream?ReadableStream:function(){};class He extends qe{}const We=({expectedChecksum:e,checksum:t,source:r,checksumSourceLocation:n,base64Encoder:i})=>{if(!Be(r))throw new Error(`@smithy/util-stream: unsupported source type ${r?.constructor?.name??r} in ChecksumStream.`);const o=i??Ae;if("function"!=typeof TransformStream)throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");const s=new TransformStream({start(){},async transform(e,r){t.update(e),r.enqueue(e)},async flush(r){const i=await t.digest(),s=o(i);if(e!==s){const t=new Error(`Checksum mismatch: expected "${e}" but received "${s}" in response header "${n}".`);r.error(t)}else r.terminate()}});r.pipeThrough(s);const a=s.readable;return Object.setPrototypeOf(a,He.prototype),a},Ke=async(e=new Uint8Array,t)=>{if(e instanceof Uint8Array)return Te.mutate(e);if(!e)return Te.mutate(new Uint8Array);const r=t.streamCollector(e);return Te.mutate(await r)};function Ve(e){return encodeURIComponent(e).replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function Ge(e,t){return new Je(e,t)}class Je{constructor(e,t){this.input=e,this.context=t,this.query={},this.method="",this.headers={},this.path="",this.body=null,this.hostname="",this.resolvePathStack=[]}async build(){const{hostname:e,protocol:t="https",port:r,path:n}=await this.context.endpoint();this.path=n;for(const e of this.resolvePathStack)e(this.path);return new j({protocol:t,hostname:this.hostname||e,port:r,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(e){return this.hostname=e,this}bp(e){return this.resolvePathStack.push((t=>{this.path=`${t?.endsWith("/")?t.slice(0,-1):t||""}`+e})),this}p(e,t,r,n){return this.resolvePathStack.push((i=>{this.path=((e,t,r,n,i,o)=>{if(null==t||void 0===t[r])throw new Error("No value provided for input HTTP label: "+r+".");{const t=n();if(t.length<=0)throw new Error("Empty value provided for input HTTP label: "+r+".");e=e.replace(i,o?t.split("/").map((e=>Ve(e))).join("/"):Ve(t))}return e})(i,this.input,e,t,r,n)})),this}h(e){return this.headers=e,this}q(e){return this.query=e,this}b(e){return this.body=e,this}m(e){return this.method=e,this}}class Qe{constructor(e){this.authSchemes=new Map;for(const[t,r]of Object.entries(e))void 0!==r&&this.authSchemes.set(t,r)}getIdentityProvider(e){return this.authSchemes.get(e)}}const Xe=(Ze=3e5,e=>Ye(e)&&e.expiration.getTime()-Date.now()void 0!==e.expiration,et="X-Amz-Date",tt="X-Amz-Signature",rt="X-Amz-Security-Token",nt="authorization",it=et.toLowerCase(),ot=[nt,it,"date"],st=tt.toLowerCase(),at="x-amz-content-sha256",ct=rt.toLowerCase(),ut={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},dt=/^proxy-/,lt=/^sec-/,ht="AWS4-HMAC-SHA256",ft="AWS4-HMAC-SHA256-PAYLOAD",pt="aws4_request",gt={},mt=[],yt=(e,t,r)=>`${e}/${t}/${r}/${pt}`,vt=(e,t,r)=>{const n=new e(t);return n.update(Ee(r)),n.digest()},bt=({headers:e},t,r)=>{const n={};for(const i of Object.keys(e).sort()){if(null==e[i])continue;const o=i.toLowerCase();(o in ut||t?.has(o)||dt.test(o)||lt.test(o))&&(!r||r&&!r.has(o))||(n[o]=e[i].trim().replace(/\s+/g," "))}return n},wt=e=>"function"==typeof ArrayBuffer&&e instanceof ArrayBuffer||"[object ArrayBuffer]"===Object.prototype.toString.call(e),kt=async({headers:e,body:t},r)=>{for(const t of Object.keys(e))if(t.toLowerCase()===at)return e[t];if(null==t)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if("string"==typeof t||ArrayBuffer.isView(t)||wt(t)){const e=new r;return e.update(Ee(t)),Le(await e.digest())}return"UNSIGNED-PAYLOAD"};class St{format(e){const t=[];for(const r of Object.keys(e)){const n=Se(r);t.push(Uint8Array.from([n.byteLength]),n,this.formatHeaderValue(e[r]))}const r=new Uint8Array(t.reduce(((e,t)=>e+t.byteLength),0));let n=0;for(const e of t)r.set(e,n),n+=e.byteLength;return r}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":const t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":const r=new DataView(new ArrayBuffer(5));return r.setUint8(0,4),r.setInt32(1,e.value,!1),new Uint8Array(r.buffer);case"long":const n=new Uint8Array(9);return n[0]=5,n.set(e.value.bytes,1),n;case"binary":const i=new DataView(new ArrayBuffer(3+e.value.byteLength));i.setUint8(0,6),i.setUint16(1,e.value.byteLength,!1);const o=new Uint8Array(i.buffer);return o.set(e.value,3),o;case"string":const s=Se(e.value),a=new DataView(new ArrayBuffer(3+s.byteLength));a.setUint8(0,7),a.setUint16(1,s.byteLength,!1);const c=new Uint8Array(a.buffer);return c.set(s,3),c;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(At.fromNumber(e.value.valueOf()).bytes,1),u;case"uuid":if(!xt.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(Ue(e.value.replace(/\-/g,"")),1),d}}}var Et;!function(e){e[e.boolTrue=0]="boolTrue",e[e.boolFalse=1]="boolFalse",e[e.byte=2]="byte",e[e.short=3]="short",e[e.integer=4]="integer",e[e.long=5]="long",e[e.byteArray=6]="byteArray",e[e.string=7]="string",e[e.timestamp=8]="timestamp",e[e.uuid=9]="uuid"}(Et||(Et={}));const xt=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class At{constructor(e){if(this.bytes=e,8!==e.byteLength)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>0x8000000000000000||e<-0x8000000000000000)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);const t=new Uint8Array(8);for(let r=7,n=Math.abs(Math.round(e));r>-1&&n>0;r--,n/=256)t[r]=n;return e<0&&Tt(t),new At(t)}valueOf(){const e=this.bytes.slice(0),t=128&e[0];return t&&Tt(e),parseInt(Le(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function Tt(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,0===e[t]);t--);}const Ct=e=>{e=j.clone(e);for(const t of Object.keys(e.headers))ot.indexOf(t.toLowerCase())>-1&&delete e.headers[t];return e},Rt=e=>"number"==typeof e?new Date(1e3*e):"string"==typeof e?Number(e)?new Date(1e3*Number(e)):new Date(e):e;class Ot{constructor({applyChecksum:e,credentials:t,region:r,service:n,sha256:i,uriEscapePath:o=!0}){this.headerFormatter=new St,this.service=n,this.sha256=i,this.uriEscapePath=o,this.applyChecksum="boolean"!=typeof e||e,this.regionProvider=ce(r),this.credentialProvider=ce(t)}async presign(e,t={}){const{signingDate:r=new Date,expiresIn:n=3600,unsignableHeaders:i,unhoistableHeaders:o,signableHeaders:s,hoistableHeaders:a,signingRegion:c,signingService:u}=t,d=await this.credentialProvider();this.validateResolvedCredentials(d);const l=c??await this.regionProvider(),{longDate:h,shortDate:f}=Pt(r);if(n>604800)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");const p=yt(f,l,u??this.service),g=((e,t={})=>{const{headers:r,query:n={}}=j.clone(e);for(const e of Object.keys(r)){const i=e.toLowerCase();("x-amz-"===i.slice(0,6)&&!t.unhoistableHeaders?.has(i)||t.hoistableHeaders?.has(i))&&(n[e]=r[e],delete r[e])}return{...e,headers:r,query:n}})(Ct(e),{unhoistableHeaders:o,hoistableHeaders:a});d.sessionToken&&(g.query[rt]=d.sessionToken),g.query["X-Amz-Algorithm"]=ht,g.query["X-Amz-Credential"]=`${d.accessKeyId}/${p}`,g.query[et]=h,g.query["X-Amz-Expires"]=n.toString(10);const m=bt(g,i,s);return g.query["X-Amz-SignedHeaders"]=_t(m),g.query[tt]=await this.getSignature(h,p,this.getSigningKey(d,l,f,u),this.createCanonicalRequest(g,m,await kt(e,this.sha256))),g}async sign(e,t){return"string"==typeof e?this.signString(e,t):e.headers&&e.payload?this.signEvent(e,t):e.message?this.signMessage(e,t):this.signRequest(e,t)}async signEvent({headers:e,payload:t},{signingDate:r=new Date,priorSignature:n,signingRegion:i,signingService:o}){const s=i??await this.regionProvider(),{shortDate:a,longDate:c}=Pt(r),u=yt(a,s,o??this.service),d=await kt({headers:{},body:t},this.sha256),l=new this.sha256;l.update(e);const h=Le(await l.digest()),f=[ft,c,u,n,h,d].join("\n");return this.signString(f,{signingDate:r,signingRegion:s,signingService:o})}async signMessage(e,{signingDate:t=new Date,signingRegion:r,signingService:n}){return this.signEvent({headers:this.headerFormatter.format(e.message.headers),payload:e.message.body},{signingDate:t,signingRegion:r,signingService:n,priorSignature:e.priorSignature}).then((t=>({message:e.message,signature:t})))}async signString(e,{signingDate:t=new Date,signingRegion:r,signingService:n}={}){const i=await this.credentialProvider();this.validateResolvedCredentials(i);const o=r??await this.regionProvider(),{shortDate:s}=Pt(t),a=new this.sha256(await this.getSigningKey(i,o,s,n));return a.update(Ee(e)),Le(await a.digest())}async signRequest(e,{signingDate:t=new Date,signableHeaders:r,unsignableHeaders:n,signingRegion:i,signingService:o}={}){const s=await this.credentialProvider();this.validateResolvedCredentials(s);const a=i??await this.regionProvider(),c=Ct(e),{longDate:u,shortDate:d}=Pt(t),l=yt(d,a,o??this.service);c.headers[it]=u,s.sessionToken&&(c.headers[ct]=s.sessionToken);const h=await kt(c,this.sha256);!((e,t)=>{e=e.toLowerCase();for(const r of Object.keys(t))if(e===r.toLowerCase())return!0;return!1})(at,c.headers)&&this.applyChecksum&&(c.headers[at]=h);const f=bt(c,n,r),p=await this.getSignature(u,l,this.getSigningKey(s,a,d,o),this.createCanonicalRequest(c,f,h));return c.headers[nt]=`${ht} Credential=${s.accessKeyId}/${l}, SignedHeaders=${_t(f)}, Signature=${p}`,c}createCanonicalRequest(e,t,r){const n=Object.keys(t).sort();return`${e.method}\n${this.getCanonicalPath(e)}\n${(({query:e={}})=>{const t=[],r={};for(const n of Object.keys(e)){if(n.toLowerCase()===st)continue;const i=Re(n);t.push(i);const o=e[n];"string"==typeof o?r[i]=`${i}=${Re(o)}`:Array.isArray(o)&&(r[i]=o.slice(0).reduce(((e,t)=>e.concat([`${i}=${Re(t)}`])),[]).sort().join("&"))}return t.sort().map((e=>r[e])).filter((e=>e)).join("&")})(e)}\n${n.map((e=>`${e}:${t[e]}`)).join("\n")}\n\n${n.join(";")}\n${r}`}async createStringToSign(e,t,r){const n=new this.sha256;n.update(Ee(r));const i=await n.digest();return`${ht}\n${e}\n${t}\n${Le(i)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){const t=[];for(const r of e.split("/"))0!==r?.length&&"."!==r&&(".."===r?t.pop():t.push(r));const r=`${e?.startsWith("/")?"/":""}${t.join("/")}${t.length>0&&e?.endsWith("/")?"/":""}`;return Re(r).replace(/%2F/g,"/")}return e}async getSignature(e,t,r,n){const i=await this.createStringToSign(e,t,n),o=new this.sha256(await r);return o.update(Ee(i)),Le(await o.digest())}getSigningKey(e,t,r,n){return(async(e,t,r,n,i)=>{const o=`${r}:${n}:${i}:${Le(await vt(e,t.secretAccessKey,t.accessKeyId))}:${t.sessionToken}`;if(o in gt)return gt[o];for(mt.push(o);mt.length>50;)delete gt[mt.shift()];let s=`AWS4${t.secretAccessKey}`;for(const t of[r,n,i,pt])s=await vt(e,s,t);return gt[o]=s})(this.sha256,e,r,t,n||this.service)}validateResolvedCredentials(e){if("object"!=typeof e||"string"!=typeof e.accessKeyId||"string"!=typeof e.secretAccessKey)throw new Error("Resolved credential object is not valid")}}const Pt=e=>{const t=(r=e,Rt(r).toISOString().replace(/\.\d{3}Z$/,"Z")).replace(/[\-:]/g,"");var r;return{longDate:t,shortDate:t.slice(0,8)}},_t=e=>Object.keys(e).sort().join(";"),Mt=e=>{let t,r=!1;e.credentials&&(r=!0,t=((e,t,r)=>{if(void 0===e)return;const n="function"!=typeof e?async()=>Promise.resolve(e):e;let i,o,s,a=!1;const c=async e=>{o||(o=n(e));try{i=await o,s=!0,a=!1}finally{o=void 0}return i};return void 0===t?async e=>(s&&!e?.forceRefresh||(i=await c(e)),i):async e=>(s&&!e?.forceRefresh||(i=await c(e)),a?i:r(i)?t(i)?(await c(e),i):i:(a=!0,i))})(e.credentials,Xe,Ye)),t||(t=e.credentialDefaultProvider?ve(e.credentialDefaultProvider(Object.assign({},e,{parentClientConfig:e}))):async()=>{throw new Error("`credentials` is missing")});const{signingEscapePath:n=!0,systemClockOffset:i=e.systemClockOffset||0,sha256:o}=e;let s;return s=e.signer?ve(e.signer):e.regionInfoProvider?()=>ve(e.region)().then((async t=>[await e.regionInfoProvider(t,{useFipsEndpoint:await e.useFipsEndpoint(),useDualstackEndpoint:await e.useDualstackEndpoint()})||{},t])).then((([r,i])=>{const{signingRegion:s,signingService:a}=r;e.signingRegion=e.signingRegion||s||i,e.signingName=e.signingName||a||e.serviceId;const c={...e,credentials:t,region:e.signingRegion,service:e.signingName,sha256:o,uriEscapePath:n};return new(e.signerConstructor||Ot)(c)})):async r=>{const i=(r=Object.assign({},{name:"sigv4",signingName:e.signingName||e.defaultSigningName,signingRegion:await ve(e.region)(),properties:{}},r)).signingRegion,s=r.signingName;e.signingRegion=e.signingRegion||i,e.signingName=e.signingName||s||e.serviceId;const a={...e,credentials:t,region:e.signingRegion,service:e.signingName,sha256:o,uriEscapePath:n};return new(e.signerConstructor||Ot)(a)},{...e,systemClockOffset:i,signingEscapePath:n,credentials:r?async()=>t().then((e=>{return r="CREDENTIALS_CODE",n="e",(t=e).$source||(t.$source={}),t.$source[r]=n,t;var t,r,n})):t,signer:s}},It=(e,t)=>{const r=[];if(e&&r.push(e),t)for(const e of t)r.push(e);return r},Nt=(e,t)=>`${e||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`,Ft=()=>{let e=[],t=[],r=!1;const n=new Set,i=r=>(e.forEach((e=>{r.add(e.middleware,{...e})})),t.forEach((e=>{r.addRelativeTo(e.middleware,{...e})})),r.identifyOnResolve?.(a.identifyOnResolve()),r),o=e=>{const t=[];return e.before.forEach((e=>{0===e.before.length&&0===e.after.length?t.push(e):t.push(...o(e))})),t.push(e),e.after.reverse().forEach((e=>{0===e.before.length&&0===e.after.length?t.push(e):t.push(...o(e))})),t},s=(r=!1)=>{const n=[],i=[],s={};e.forEach((e=>{const t={...e,before:[],after:[]};for(const e of It(t.name,t.aliases))s[e]=t;n.push(t)})),t.forEach((e=>{const t={...e,before:[],after:[]};for(const e of It(t.name,t.aliases))s[e]=t;i.push(t)})),i.forEach((e=>{if(e.toMiddleware){const t=s[e.toMiddleware];if(void 0===t){if(r)return;throw new Error(`${e.toMiddleware} is not found when adding ${Nt(e.name,e.aliases)} middleware ${e.relation} ${e.toMiddleware}`)}"after"===e.relation&&t.after.push(e),"before"===e.relation&&t.before.push(e)}}));const a=(c=n,c.sort(((e,t)=>$t[t.step]-$t[e.step]||Ut[t.priority||"normal"]-Ut[e.priority||"normal"]))).map(o).reduce(((e,t)=>(e.push(...t),e)),[]);var c;return a},a={add:(t,r={})=>{const{name:i,override:o,aliases:s}=r,a={step:"initialize",priority:"normal",middleware:t,...r},c=It(i,s);if(c.length>0){if(c.some((e=>n.has(e)))){if(!o)throw new Error(`Duplicate middleware name '${Nt(i,s)}'`);for(const t of c){const r=e.findIndex((e=>e.name===t||e.aliases?.some((e=>e===t))));if(-1===r)continue;const n=e[r];if(n.step!==a.step||a.priority!==n.priority)throw new Error(`"${Nt(n.name,n.aliases)}" middleware with ${n.priority} priority in ${n.step} step cannot be overridden by "${Nt(i,s)}" middleware with ${a.priority} priority in ${a.step} step.`);e.splice(r,1)}}for(const e of c)n.add(e)}e.push(a)},addRelativeTo:(e,r)=>{const{name:i,override:o,aliases:s}=r,a={middleware:e,...r},c=It(i,s);if(c.length>0){if(c.some((e=>n.has(e)))){if(!o)throw new Error(`Duplicate middleware name '${Nt(i,s)}'`);for(const e of c){const r=t.findIndex((t=>t.name===e||t.aliases?.some((t=>t===e))));if(-1===r)continue;const n=t[r];if(n.toMiddleware!==a.toMiddleware||n.relation!==a.relation)throw new Error(`"${Nt(n.name,n.aliases)}" middleware ${n.relation} "${n.toMiddleware}" middleware cannot be overridden by "${Nt(i,s)}" middleware ${a.relation} "${a.toMiddleware}" middleware.`);t.splice(r,1)}}for(const e of c)n.add(e)}t.push(a)},clone:()=>i(Ft()),use:e=>{e.applyToStack(a)},remove:r=>"string"==typeof r?(r=>{let i=!1;const o=e=>{const t=It(e.name,e.aliases);if(t.includes(r)){i=!0;for(const e of t)n.delete(e);return!1}return!0};return e=e.filter(o),t=t.filter(o),i})(r):(r=>{let i=!1;const o=e=>{if(e.middleware===r){i=!0;for(const t of It(e.name,e.aliases))n.delete(t);return!1}return!0};return e=e.filter(o),t=t.filter(o),i})(r),removeByTag:r=>{let i=!1;const o=e=>{const{tags:t,name:o,aliases:s}=e;if(t&&t.includes(r)){const e=It(o,s);for(const t of e)n.delete(t);return i=!0,!1}return!0};return e=e.filter(o),t=t.filter(o),i},concat:e=>{const t=i(Ft());return t.use(e),t.identifyOnResolve(r||t.identifyOnResolve()||(e.identifyOnResolve?.()??!1)),t},applyToStack:i,identify:()=>s(!0).map((e=>{const t=e.step??e.relation+" "+e.toMiddleware;return Nt(e.name,e.aliases)+" - "+t})),identifyOnResolve:e=>("boolean"==typeof e&&(r=e),r),resolve:(e,t)=>{for(const r of s().map((e=>e.middleware)).reverse())e=r(e,t);return r&&console.log(a.identify()),e}};return a},$t={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},Ut={high:3,normal:2,low:1};class Lt{constructor(e){this.config=e,this.middlewareStack=Ft()}send(e,t,r){const n="function"!=typeof t?t:void 0,i="function"==typeof t?t:r;let o;if(void 0===n&&!0===this.config.cacheMiddleware){this.handlers||(this.handlers=new WeakMap);const t=this.handlers;t.has(e.constructor)?o=t.get(e.constructor):(o=e.resolveMiddleware(this.middlewareStack,this.config,n),t.set(e.constructor,o))}else delete this.handlers,o=e.resolveMiddleware(this.middlewareStack,this.config,n);if(!i)return o(e).then((e=>e.output));o(e).then((e=>i(null,e.output)),(e=>i(e))).catch((()=>{}))}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}class Bt{constructor(){this.middlewareStack=Ft()}static classBuilder(){return new Dt}resolveMiddlewareWithContext(e,t,r,{middlewareFn:n,clientName:i,commandName:o,inputFilterSensitiveLog:s,outputFilterSensitiveLog:a,smithyContext:c,additionalContext:u,CommandCtor:d}){for(const i of n.bind(this)(d,e,t,r))this.middlewareStack.use(i);const l=e.concat(this.middlewareStack),{logger:h}=t,f={logger:h,clientName:i,commandName:o,inputFilterSensitiveLog:s,outputFilterSensitiveLog:a,[L]:{commandInstance:this,...c},...u},{requestHandler:p}=t;return l.resolve((e=>p.handle(e.request,r||{})),f)}}class Dt{constructor(){this._init=()=>{},this._ep={},this._middlewareFn=()=>[],this._commandName="",this._clientName="",this._additionalContext={},this._smithyContext={},this._inputFilterSensitiveLog=e=>e,this._outputFilterSensitiveLog=e=>e,this._serializer=null,this._deserializer=null}init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,t,r={}){return this._smithyContext={service:e,operation:t,...r},this}c(e={}){return this._additionalContext=e,this}n(e,t){return this._clientName=e,this._commandName=t,this}f(e=e=>e,t=e=>e){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=t,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}build(){const e=this;let t;return t=class extends Bt{static getEndpointParameterInstructions(){return e._ep}constructor(...[t]){super(),this.serialize=e._serializer,this.deserialize=e._deserializer,this.input=t??{},e._init(this)}resolveMiddleware(r,n,i){return this.resolveMiddlewareWithContext(r,n,i,{CommandCtor:t,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog,outputFilterSensitiveLog:e._outputFilterSensitiveLog,smithyContext:e._smithyContext,additionalContext:e._additionalContext})}}}}const jt="***SensitiveInformation***",zt=e=>{switch(e){case"true":return!0;case"false":return!1;default:throw new Error(`Unable to parse boolean value "${e}"`)}},qt=Math.ceil(2**127*(2-2**-23)),Ht=e=>{const t=(e=>{if(null!=e){if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return String(t)!==String(e)&&sr.warn(or(`Expected number but observed string: ${e}`)),t}if("number"==typeof e)return e;throw new TypeError(`Expected number, got ${typeof e}: ${e}`)}})(e);if(void 0!==t&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0&&Math.abs(t)>qt)throw new TypeError(`Expected 32-bit float, got ${e}`);return t},Wt=e=>{if(null!=e){if(Number.isInteger(e)&&!Number.isNaN(e))return e;throw new TypeError(`Expected integer, got ${typeof e}: ${e}`)}},Kt=e=>Jt(e,32),Vt=e=>Jt(e,16),Gt=e=>Jt(e,8),Jt=(e,t)=>{const r=Wt(e);if(void 0!==r&&Qt(r,t)!==r)throw new TypeError(`Expected ${t}-bit integer, got ${e}`);return r},Qt=(e,t)=>{switch(t){case 32:return Int32Array.of(e)[0];case 16:return Int16Array.of(e)[0];case 8:return Int8Array.of(e)[0]}},Xt=(e,t)=>{if(null==e){if(t)throw new TypeError(`Expected a non-null value for ${t}`);throw new TypeError("Expected a non-null value")}return e},Zt=e=>{if(null==e)return;if("object"==typeof e&&!Array.isArray(e))return e;const t=Array.isArray(e)?"array":typeof e;throw new TypeError(`Expected object, got ${t}: ${e}`)},Yt=e=>{if(null!=e){if("string"==typeof e)return e;if(["boolean","number","bigint"].includes(typeof e))return sr.warn(or(`Expected string, got ${typeof e}: ${e}`)),String(e);throw new TypeError(`Expected string, got ${typeof e}: ${e}`)}},er=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,tr=e=>{const t=e.match(er);if(null===t||t[0].length!==e.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(e)},rr=e=>Wt("string"==typeof e?tr(e):e),nr=e=>Kt("string"==typeof e?tr(e):e),ir=e=>Vt("string"==typeof e?tr(e):e),or=e=>String(new TypeError(e).stack||e).split("\n").slice(0,5).filter((e=>!e.includes("stackTraceWarning"))).join("\n"),sr={warn:console.warn},ar=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],cr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ur(e){const t=e.getUTCFullYear(),r=e.getUTCMonth(),n=e.getUTCDay(),i=e.getUTCDate(),o=e.getUTCHours(),s=e.getUTCMinutes(),a=e.getUTCSeconds(),c=o<10?`0${o}`:`${o}`,u=s<10?`0${s}`:`${s}`,d=a<10?`0${a}`:`${a}`;return`${ar[n]}, ${i<10?`0${i}`:`${i}`} ${cr[r]} ${t} ${c}:${u}:${d} GMT`}const dr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),lr=e=>{if(null==e)return;if("string"!=typeof e)throw new TypeError("RFC-3339 date-times must be expressed as strings");const t=dr.exec(e);if(!t)throw new TypeError("Invalid RFC-3339 date-time value");const[r,n,i,o,s,a,c,u,d]=t,l=ir(Tr(n)),h=Er(i,"month",1,12),f=Er(o,"day",1,31),p=mr(l,h,f,{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u});return"Z"!=d.toUpperCase()&&p.setTime(p.getTime()-Ar(d)),p},hr=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),fr=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),pr=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),gr=e=>{if(null==e)return;if("string"!=typeof e)throw new TypeError("RFC-7231 date-times must be expressed as strings");let t=hr.exec(e);if(t){const[e,r,n,i,o,s,a,c]=t;return mr(ir(Tr(i)),br(n),Er(r,"day",1,31),{hours:o,minutes:s,seconds:a,fractionalMilliseconds:c})}if(t=fr.exec(e),t){const[e,r,n,i,o,s,a,c]=t;return vr(mr(yr(i),br(n),Er(r,"day",1,31),{hours:o,minutes:s,seconds:a,fractionalMilliseconds:c}))}if(t=pr.exec(e),t){const[e,r,n,i,o,s,a,c]=t;return mr(ir(Tr(c)),br(r),Er(n.trimLeft(),"day",1,31),{hours:i,minutes:o,seconds:s,fractionalMilliseconds:a})}throw new TypeError("Invalid RFC-7231 date-time value")},mr=(e,t,r,n)=>{const i=t-1;return kr(e,i,r),new Date(Date.UTC(e,i,r,Er(n.hours,"hour",0,23),Er(n.minutes,"minute",0,59),Er(n.seconds,"seconds",0,60),xr(n.fractionalMilliseconds)))},yr=e=>{const t=(new Date).getUTCFullYear(),r=100*Math.floor(t/100)+ir(Tr(e));return re.getTime()-(new Date).getTime()>15768e8?new Date(Date.UTC(e.getUTCFullYear()-100,e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())):e,br=e=>{const t=cr.indexOf(e);if(t<0)throw new TypeError(`Invalid month: ${e}`);return t+1},wr=[31,28,31,30,31,30,31,31,30,31,30,31],kr=(e,t,r)=>{let n=wr[t];if(1===t&&Sr(e)&&(n=29),r>n)throw new TypeError(`Invalid day for ${cr[t]} in ${e}: ${r}`)},Sr=e=>e%4==0&&(e%100!=0||e%400==0),Er=(e,t,r,n)=>{const i=(e=>Gt("string"==typeof e?tr(e):e))(Tr(e));if(in)throw new TypeError(`${t} must be between ${r} and ${n}, inclusive`);return i},xr=e=>null==e?0:1e3*(e=>Ht("string"==typeof e?tr(e):e))("0."+e),Ar=e=>{const t=e[0];let r=1;if("+"==t)r=1;else{if("-"!=t)throw new TypeError(`Offset direction, ${t}, must be "+" or "-"`);r=-1}return r*(60*Number(e.substring(1,3))+Number(e.substring(4,6)))*60*1e3},Tr=e=>{let t=0;for(;t{Object.entries(t).filter((([,e])=>void 0!==e)).forEach((([t,r])=>{null!=e[t]&&""!==e[t]||(e[t]=r)}));const r=e.message||e.Message||"UnknownError";return e.message=r,delete e.Message,e},Or=e=>({httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}),Pr=e=>{switch(e){case"standard":case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}},_r=e=>{const t=[];for(const r in $){const n=$[r];void 0!==e[n]&&t.push({algorithmId:()=>n,checksumConstructor:()=>e[n]})}return{_checksumAlgorithms:t,addChecksumAlgorithm(e){this._checksumAlgorithms.push(e)},checksumAlgorithms(){return this._checksumAlgorithms}}},Mr=e=>{const t={};return e.checksumAlgorithms().forEach((e=>{t[e.algorithmId()]=e.checksumConstructor()})),t},Ir=e=>{let t=e.retryStrategy;return{setRetryStrategy(e){t=e},retryStrategy:()=>t}},Nr=e=>{const t={};return t.retryStrategy=e.retryStrategy(),t},Fr=e=>({..._r(e),...Ir(e)}),$r=e=>({...Mr(e),...Nr(e)}),Ur=e=>Array.isArray(e)?e:[e],Lr=e=>{const t="#text";for(const r in e)e.hasOwnProperty(r)&&void 0!==e[r][t]?e[r]=e[r][t]:"object"==typeof e[r]&&null!==e[r]&&(e[r]=Lr(e[r]));return e},Br=e=>null!=e,Dr=function(){const e=Object.getPrototypeOf(this).constructor,t=new(Function.bind.apply(String,[null,...arguments]));return Object.setPrototypeOf(t,e.prototype),t};Dr.prototype=Object.create(String.prototype,{constructor:{value:Dr,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf(Dr,String);class jr{trace(){}debug(){}info(){}warn(){}error(){}}function zr(e,t,r){let n,i,o;if(void 0===t&&void 0===r)n={},o=e;else{if(n=e,"function"==typeof t)return i=t,o=r,qr(n,i,o);o=t}for(const e of Object.keys(o))Array.isArray(o[e])?Hr(n,null,o,e):n[e]=o[e];return n}const qr=(e,t,r)=>zr(e,Object.entries(r).reduce(((e,[r,n])=>(Array.isArray(n)?e[r]=n:e[r]="function"==typeof n?[t,n()]:[t,n],e)),{})),Hr=(e,t,r,n)=>{if(null!==t){let i=r[n];"function"==typeof i&&(i=[,i]);const[o=Wr,s=Kr,a=n]=i;return void(("function"==typeof o&&o(t[a])||"function"!=typeof o&&o)&&(e[n]=s(t[a])))}let[i,o]=r[n];if("function"==typeof o){let t;const r=void 0===i&&null!=(t=o()),s="function"==typeof i&&!!i(void 0)||"function"!=typeof i&&!!i;r?e[n]=t:s&&(e[n]=o())}else{const t=void 0===i&&null!=o,r="function"==typeof i&&!!i(o)||"function"!=typeof i&&!!i;(t||r)&&(e[n]=o)}},Wr=e=>null!=e,Kr=e=>e;function Vr(e){return(e.includes(",")||e.includes('"'))&&(e=`"${e.replace(/"/g,'\\"')}"`),e}function Gr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Jr={},Qr={};!function(e){const t=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",r="["+t+"]["+(t+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040")+"]*",n=new RegExp("^"+r+"$");e.isExist=function(e){return void 0!==e},e.isEmptyObject=function(e){return 0===Object.keys(e).length},e.merge=function(e,t,r){if(t){const n=Object.keys(t),i=n.length;for(let o=0;o5&&"xml"===n)return un("InvalidXml","XML declaration allowed only at the start of the document.",ln(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}}return t}function tn(e,t){if(e.length>t+5&&"-"===e[t+1]&&"-"===e[t+2]){for(t+=3;t"===e[t+2]){t+=2;break}}else if(e.length>t+8&&"D"===e[t+1]&&"O"===e[t+2]&&"C"===e[t+3]&&"T"===e[t+4]&&"Y"===e[t+5]&&"P"===e[t+6]&&"E"===e[t+7]){let r=1;for(t+=8;t"===e[t]&&(r--,0===r))break}else if(e.length>t+9&&"["===e[t+1]&&"C"===e[t+2]&&"D"===e[t+3]&&"A"===e[t+4]&&"T"===e[t+5]&&"A"===e[t+6]&&"["===e[t+7])for(t+=8;t"===e[t+2]){t+=2;break}return t}Jr.validate=function(e,t){t=Object.assign({},Zr,t);const r=[];let n=!1,i=!1;"\ufeff"===e[0]&&(e=e.substr(1));for(let s=0;s"!==e[s]&&" "!==e[s]&&"\t"!==e[s]&&"\n"!==e[s]&&"\r"!==e[s];s++)u+=e[s];if(u=u.trim(),"/"===u[u.length-1]&&(u=u.substring(0,u.length-1),s--),o=u,!Xr.isName(o)){let t;return t=0===u.trim().length?"Invalid space after '<'.":"Tag '"+u+"' is an invalid name.",un("InvalidTag",t,ln(e,s))}const d=on(e,s);if(!1===d)return un("InvalidAttr","Attributes for '"+u+"' have open quote.",ln(e,s));let l=d.value;if(s=d.index,"/"===l[l.length-1]){const r=s-l.length;l=l.substring(0,l.length-1);const i=an(l,t);if(!0!==i)return un(i.err.code,i.err.msg,ln(e,r+i.err.line));n=!0}else if(c){if(!d.tagClosed)return un("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",ln(e,s));if(l.trim().length>0)return un("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",ln(e,a));if(0===r.length)return un("InvalidTag","Closing tag '"+u+"' has not been opened.",ln(e,a));{const t=r.pop();if(u!==t.tagName){let r=ln(e,t.tagStartPos);return un("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+r.line+", col "+r.col+") instead of closing tag '"+u+"'.",ln(e,a))}0==r.length&&(i=!0)}}else{const o=an(l,t);if(!0!==o)return un(o.err.code,o.err.msg,ln(e,s-l.length+o.err.line));if(!0===i)return un("InvalidXml","Multiple possible root nodes found.",ln(e,s));-1!==t.unpairedTags.indexOf(u)||r.push({tagName:u,tagStartPos:a}),n=!0}for(s++;s0)||un("InvalidXml","Invalid '"+JSON.stringify(r.map((e=>e.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):un("InvalidXml","Start tag expected.",1)};const rn='"',nn="'";function on(e,t){let r="",n="",i=!1;for(;t"===e[t]&&""===n){i=!0;break}r+=e[t]}return""===n&&{value:r,index:t,tagClosed:i}}const sn=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function an(e,t){const r=Xr.getAllMatches(e,sn),n={};for(let e=0;e!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,r){return e}};fn.buildOptions=function(e){return Object.assign({},pn,e)},fn.defaultOptions=pn;var gn=class{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}add(e,t){"__proto__"===e&&(e="#__proto__"),this.child.push({[e]:t})}addChild(e){"__proto__"===e.tagname&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child})}};const mn=Qr;function yn(e,t){let r="";for(;t"===e[t]){if(o?"-"===e[t-1]&&"-"===e[t-2]&&(o=!1,n--):n--,0===n)break}else"["===e[t]?i=!0:s+=e[t];else{if(i&&bn(e,t))t+=7,[entityName,val,t]=yn(e,t+1),-1===val.indexOf("&")&&(r[En(entityName)]={regx:RegExp(`&${entityName};`,"g"),val:val});else if(i&&wn(e,t))t+=8;else if(i&&kn(e,t))t+=8;else if(i&&Sn(e,t))t+=9;else{if(!vn)throw new Error("Invalid DOCTYPE");o=!0}n++,s=""}if(0!==n)throw new Error("Unclosed DOCTYPE")}return{entities:r,i:t}};const An=/^[-+]?0x[a-fA-F0-9]+$/,Tn=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);const Cn={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};const Rn=Qr,On=gn,Pn=xn,_n=function(e,t={}){if(t=Object.assign({},Cn,t),!e||"string"!=typeof e)return e;let r=e.trim();if(void 0!==t.skipLike&&t.skipLike.test(r))return e;if(t.hex&&An.test(r))return Number.parseInt(r,16);{const n=Tn.exec(r);if(n){const i=n[1],o=n[2];let s=function(e){if(e&&-1!==e.indexOf("."))return"."===(e=e.replace(/0+$/,""))?e="0":"."===e[0]?e="0"+e:"."===e[e.length-1]&&(e=e.substr(0,e.length-1)),e;return e}(n[3]);const a=n[4]||n[6];if(!t.leadingZeros&&o.length>0&&i&&"."!==r[2])return e;if(!t.leadingZeros&&o.length>0&&!i&&"."!==r[1])return e;{const n=Number(r),c=""+n;return-1!==c.search(/[eE]/)||a?t.eNotation?n:e:-1!==r.indexOf(".")?"0"===c&&""===s||c===s||i&&c==="-"+s?n:e:o?s===c||i+s===c?n:e:r===c||r===i+c?n:e}}return e}};function Mn(e){const t=Object.keys(e);for(let r=0;r0)){s||(e=this.replaceEntitiesValue(e));const n=this.options.tagValueProcessor(t,e,r,i,o);if(null==n)return e;if(typeof n!=typeof e||n!==e)return n;if(this.options.trimValues)return Wn(e,this.options.parseTagValue,this.options.numberParseOptions);return e.trim()===e?Wn(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function Nn(e){if(this.options.removeNSPrefix){const t=e.split(":"),r="/"===e.charAt(0)?"/":"";if("xmlns"===t[0])return"";2===t.length&&(e=r+t[1])}return e}const Fn=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function $n(e,t,r){if(!this.options.ignoreAttributes&&"string"==typeof e){const r=Rn.getAllMatches(e,Fn),n=r.length,i={};for(let e=0;e",o,"Closing Tag is not closed.");let s=e.substring(o+2,t).trim();if(this.options.removeNSPrefix){const e=s.indexOf(":");-1!==e&&(s=s.substr(e+1))}this.options.transformTagName&&(s=this.options.transformTagName(s)),r&&(n=this.saveTextToParentTag(n,r,i));const a=i.substring(i.lastIndexOf(".")+1);if(s&&-1!==this.options.unpairedTags.indexOf(s))throw new Error(`Unpaired tag can not be used as closing tag: `);let c=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(c=i.lastIndexOf(".",i.lastIndexOf(".")-1),this.tagsNodeStack.pop()):c=i.lastIndexOf("."),i=i.substring(0,c),r=this.tagsNodeStack.pop(),n="",o=t}else if("?"===e[o+1]){let t=qn(e,o,!1,"?>");if(!t)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,r,i),this.options.ignoreDeclaration&&"?xml"===t.tagName||this.options.ignorePiTags);else{const e=new On(t.tagName);e.add(this.options.textNodeName,""),t.tagName!==t.tagExp&&t.attrExpPresent&&(e[":@"]=this.buildAttributesMap(t.tagExp,i,t.tagName)),this.addChild(r,e,i)}o=t.closeIndex+1}else if("!--"===e.substr(o+1,3)){const t=zn(e,"--\x3e",o+4,"Comment is not closed.");if(this.options.commentPropName){const s=e.substring(o+4,t-2);n=this.saveTextToParentTag(n,r,i),r.add(this.options.commentPropName,[{[this.options.textNodeName]:s}])}o=t}else if("!D"===e.substr(o+1,2)){const t=Pn(e,o);this.docTypeEntities=t.entities,o=t.i}else if("!["===e.substr(o+1,2)){const t=zn(e,"]]>",o,"CDATA is not closed.")-2,s=e.substring(o+9,t);n=this.saveTextToParentTag(n,r,i);let a=this.parseTextData(s,r.tagname,i,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?r.add(this.options.cdataPropName,[{[this.options.textNodeName]:s}]):r.add(this.options.textNodeName,a),o=t+2}else{let s=qn(e,o,this.options.removeNSPrefix),a=s.tagName;const c=s.rawTagName;let u=s.tagExp,d=s.attrExpPresent,l=s.closeIndex;this.options.transformTagName&&(a=this.options.transformTagName(a)),r&&n&&"!xml"!==r.tagname&&(n=this.saveTextToParentTag(n,r,i,!1));const h=r;if(h&&-1!==this.options.unpairedTags.indexOf(h.tagname)&&(r=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf("."))),a!==t.tagname&&(i+=i?"."+a:a),this.isItStopNode(this.options.stopNodes,i,a)){let t="";if(u.length>0&&u.lastIndexOf("/")===u.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),i=i.substr(0,i.length-1),u=a):u=u.substr(0,u.length-1),o=s.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))o=s.closeIndex;else{const r=this.readStopNodeData(e,c,l+1);if(!r)throw new Error(`Unexpected end of ${c}`);o=r.i,t=r.tagContent}const n=new On(a);a!==u&&d&&(n[":@"]=this.buildAttributesMap(u,i,a)),t&&(t=this.parseTextData(t,a,i,!0,d,!0,!0)),i=i.substr(0,i.lastIndexOf(".")),n.add(this.options.textNodeName,t),this.addChild(r,n,i)}else{if(u.length>0&&u.lastIndexOf("/")===u.length-1){"/"===a[a.length-1]?(a=a.substr(0,a.length-1),i=i.substr(0,i.length-1),u=a):u=u.substr(0,u.length-1),this.options.transformTagName&&(a=this.options.transformTagName(a));const e=new On(a);a!==u&&d&&(e[":@"]=this.buildAttributesMap(u,i,a)),this.addChild(r,e,i),i=i.substr(0,i.lastIndexOf("."))}else{const e=new On(a);this.tagsNodeStack.push(r),a!==u&&d&&(e[":@"]=this.buildAttributesMap(u,i,a)),this.addChild(r,e,i),r=e}n="",o=l}}else n+=e[o]}return t.child};function Ln(e,t,r){const n=this.options.updateTag(t.tagname,r,t[":@"]);!1===n||("string"==typeof n?(t.tagname=n,e.addChild(t)):e.addChild(t))}const Bn=function(e){if(this.options.processEntities){for(let t in this.docTypeEntities){const r=this.docTypeEntities[t];e=e.replace(r.regx,r.val)}for(let t in this.lastEntities){const r=this.lastEntities[t];e=e.replace(r.regex,r.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){const r=this.htmlEntities[t];e=e.replace(r.regex,r.val)}e=e.replace(this.ampEntity.regex,this.ampEntity.val)}return e};function Dn(e,t,r,n){return e&&(void 0===n&&(n=0===Object.keys(t.child).length),void 0!==(e=this.parseTextData(e,t.tagname,r,!1,!!t[":@"]&&0!==Object.keys(t[":@"]).length,n))&&""!==e&&t.add(this.options.textNodeName,e),e=""),e}function jn(e,t,r){const n="*."+r;for(const r in e){const i=e[r];if(n===i||t===i)return!0}return!1}function zn(e,t,r,n){const i=e.indexOf(t,r);if(-1===i)throw new Error(n);return i+t.length-1}function qn(e,t,r,n=">"){const i=function(e,t,r=">"){let n,i="";for(let o=t;o",r,`${t} is not closed`);if(e.substring(r+2,o).trim()===t&&(i--,0===i))return{tagContent:e.substring(n,r),i:o};r=o}else if("?"===e[r+1]){r=zn(e,"?>",r+1,"StopNode is not closed.")}else if("!--"===e.substr(r+1,3)){r=zn(e,"--\x3e",r+3,"StopNode is not closed.")}else if("!["===e.substr(r+1,2)){r=zn(e,"]]>",r,"StopNode is not closed.")-2}else{const n=qn(e,r,">");if(n){(n&&n.tagName)===t&&"/"!==n.tagExp[n.tagExp.length-1]&&i++,r=n.closeIndex}}}function Wn(e,t,r){if(t&&"string"==typeof e){const t=e.trim();return"true"===t||"false"!==t&&_n(e,r)}return Rn.isExist(e)?e:""}var Kn=class{constructor(e){this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,t)=>String.fromCharCode(Number.parseInt(t,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,t)=>String.fromCharCode(Number.parseInt(t,16))}},this.addExternalEntities=Mn,this.parseXml=Un,this.parseTextData=In,this.resolveNameSpace=Nn,this.buildAttributesMap=$n,this.isItStopNode=jn,this.replaceEntitiesValue=Bn,this.readStopNodeData=Hn,this.saveTextToParentTag=Dn,this.addChild=Ln}},Vn={};function Gn(e,t,r){let n;const i={};for(let o=0;o0&&(i[t.textNodeName]=n):void 0!==n&&(i[t.textNodeName]=n),i}function Jn(e){const t=Object.keys(e);for(let e=0;e`,o=!1;continue}if(c===t.commentPropName){i+=n+`\x3c!--${a[c][0][t.textNodeName]}--\x3e`,o=!0;continue}if("?"===c[0]){const e=oi(a[":@"],t),r="?xml"===c?"":n;let s=a[c][0][t.textNodeName];s=0!==s.length?" "+s:"",i+=r+`<${c}${s}${e}?>`,o=!0;continue}let d=n;""!==d&&(d+=t.indentBy);const l=n+`<${c}${oi(a[":@"],t)}`,h=ni(a[c],t,u,d);-1!==t.unpairedTags.indexOf(c)?t.suppressUnpairedNode?i+=l+">":i+=l+"/>":h&&0!==h.length||!t.suppressEmptyNode?h&&h.endsWith(">")?i+=l+`>${h}${n}`:(i+=l+">",h&&""!==n&&(h.includes("/>")||h.includes("`):i+=l+"/>",o=!0}return i}function ii(e){const t=Object.keys(e);for(let r=0;r0&&t.processEntities)for(let r=0;r0&&(r="\n"),ni(e,t,"",r)},ui={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function di(e){this.options=Object.assign({},ui,e),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=fi),this.processTextOrObjNode=li,this.options.format?(this.indentate=hi,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function li(e,t,r){const n=this.j2x(e,r+1);return void 0!==e[this.options.textNodeName]&&1===Object.keys(e).length?this.buildTextValNode(e[this.options.textNodeName],t,n.attrStr,r):this.buildObjectNode(n.val,t,n.attrStr,r)}function hi(e){return this.options.indentBy.repeat(e)}function fi(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}di.prototype.build=function(e){return this.options.preserveOrder?ci(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0).val)},di.prototype.j2x=function(e,t){let r="",n="";for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i))if(void 0===e[i])this.isAttribute(i)&&(n+="");else if(null===e[i])this.isAttribute(i)?n+="":"?"===i[0]?n+=this.indentate(t)+"<"+i+"?"+this.tagEndChar:n+=this.indentate(t)+"<"+i+"/"+this.tagEndChar;else if(e[i]instanceof Date)n+=this.buildTextValNode(e[i],i,"",t);else if("object"!=typeof e[i]){const o=this.isAttribute(i);if(o)r+=this.buildAttrPairStr(o,""+e[i]);else if(i===this.options.textNodeName){let t=this.options.tagValueProcessor(i,""+e[i]);n+=this.replaceEntitiesValue(t)}else n+=this.buildTextValNode(e[i],i,"",t)}else if(Array.isArray(e[i])){const r=e[i].length;let o="",s="";for(let a=0;a"+e+i}},di.prototype.closeTag=function(e){let t="";return-1!==this.options.unpairedTags.indexOf(e)?this.options.suppressUnpairedNode||(t="/"):t=this.options.suppressEmptyNode?"/":`>`+this.newLine;if(!1!==this.options.commentPropName&&t===this.options.commentPropName)return this.indentate(n)+`\x3c!--${e}--\x3e`+this.newLine;if("?"===t[0])return this.indentate(n)+"<"+t+r+"?"+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),""===i?this.indentate(n)+"<"+t+r+this.closeTag(t)+this.tagEndChar:this.indentate(n)+"<"+t+r+">"+i+"0&&this.options.processEntities)for(let t=0;t((e,t)=>Ke(e,t).then((e=>t.utf8Encoder(e))))(e,t).then((e=>{if(e.length){const t=new pi.XMLParser({attributeNamePrefix:"",htmlEntities:!0,ignoreAttributes:!1,ignoreDeclaration:!0,parseTagValue:!1,trimValues:!1,tagValueProcessor:(e,t)=>""===t.trim()&&t.includes("\n")?"":void 0});let r;t.addEntity("#xD","\r"),t.addEntity("#10","\n");try{r=t.parse(e,!0)}catch(t){throw t&&"object"==typeof t&&Object.defineProperty(t,"$responseBodyText",{value:e}),t}const n="#text",i=Object.keys(r)[0],o=r[i];return o[n]&&(o[i]=o[n],delete o[n]),Lr(o)}return{}})),mi=async(e,t)=>{const r=await gi(e,t);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r},yi=[G.CRC32,G.CRC32C,G.SHA1,G.SHA256],vi=[G.SHA256,G.SHA1,G.CRC32,G.CRC32C],bi=e=>e===G.MD5?"content-md5":`x-amz-checksum-${e.toLowerCase()}`,wi=e=>void 0!==e&&"string"!=typeof e&&!ArrayBuffer.isView(e)&&!wt(e);function ki(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(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((n=n.apply(e,t||[])).next())}))}function Si(e,t){var r,n,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1](new TextEncoder).encode(e);function xi(e){return e instanceof Uint8Array?e:"string"==typeof e?Ei(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}function Ai(e){return"string"==typeof e?0===e.length:0===e.byteLength}function Ti(e){return new Uint8Array([(4278190080&e)>>24,(16711680&e)>>16,(65280&e)>>8,255&e])}function Ci(e){if(!Uint32Array.from){for(var t=new Uint32Array(e.length),r=0;r=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),i=n.next();!i.done;i=n.next()){var o=i.value;this.checksum=this.checksum>>>8^Pi[255&(this.checksum^o)]}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}return this},e.prototype.digest=function(){return(4294967295^this.checksum)>>>0},e}(),Pi=Ci([0,4067132163,3778769143,324072436,3348797215,904991772,648144872,3570033899,2329499855,2024987596,1809983544,2575936315,1296289744,3207089363,2893594407,1578318884,274646895,3795141740,4049975192,51262619,3619967088,632279923,922689671,3298075524,2592579488,1760304291,2075979607,2312596564,1562183871,2943781820,3156637768,1313733451,549293790,3537243613,3246849577,871202090,3878099393,357341890,102525238,4101499445,2858735121,1477399826,1264559846,3107202533,1845379342,2677391885,2361733625,2125378298,820201905,3263744690,3520608582,598981189,4151959214,85089709,373468761,3827903834,3124367742,1213305469,1526817161,2842354314,2107672161,2412447074,2627466902,1861252501,1098587580,3004210879,2688576843,1378610760,2262928035,1955203488,1742404180,2511436119,3416409459,969524848,714683780,3639785095,205050476,4266873199,3976438427,526918040,1361435347,2739821008,2954799652,1114974503,2529119692,1691668175,2005155131,2247081528,3690758684,697762079,986182379,3366744552,476452099,3993867776,4250756596,255256311,1640403810,2477592673,2164122517,1922457750,2791048317,1412925310,1197962378,3037525897,3944729517,427051182,170179418,4165941337,746937522,3740196785,3451792453,1070968646,1905808397,2213795598,2426610938,1657317369,3053634322,1147748369,1463399397,2773627110,4215344322,153784257,444234805,3893493558,1021025245,3467647198,3722505002,797665321,2197175160,1889384571,1674398607,2443626636,1164749927,3070701412,2757221520,1446797203,137323447,4198817972,3910406976,461344835,3484808360,1037989803,781091935,3705997148,2460548119,1623424788,1939049696,2180517859,1429367560,2807687179,3020495871,1180866812,410100952,3927582683,4182430767,186734380,3756733383,763408580,1053836080,3434856499,2722870694,1344288421,1131464017,2971354706,1708204729,2545590714,2229949006,1988219213,680717673,3673779818,3383336350,1002577565,4010310262,493091189,238226049,4233660802,2987750089,1082061258,1395524158,2705686845,1972364758,2279892693,2494862625,1725896226,952904198,3399985413,3656866545,731699698,4283874585,222117402,510512622,3959836397,3280807620,837199303,582374963,3504198960,68661723,4135334616,3844915500,390545967,1230274059,3141532936,2825850620,1510247935,2395924756,2091215383,1878366691,2644384480,3553878443,565732008,854102364,3229815391,340358836,3861050807,4117890627,119113024,1493875044,2875275879,3090270611,1247431312,2660249211,1828433272,2141937292,2378227087,3811616794,291187481,34330861,4032846830,615137029,3603020806,3314634738,939183345,1776939221,2609017814,2295496738,2058945313,2926798794,1545135305,1330124605,3173225534,4084100981,17165430,307568514,3762199681,888469610,3332340585,3587147933,665062302,2042050490,2346497209,2559330125,1793573966,3190661285,1279665062,1595330642,2910671697]);function _i(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(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((n=n.apply(e,t||[])).next())}))}function Mi(e,t){var r,n,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),i=n.next();!i.done;i=n.next()){var o=i.value;this.checksum=this.checksum>>>8^Fi[255&(this.checksum^o)]}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}return this},e.prototype.digest=function(){return(4294967295^this.checksum)>>>0},e}(),Fi=Ci([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);const $i=(e,t)=>({[G.MD5]:t.md5,[G.CRC32]:Ii,[G.CRC32C]:Ri,[G.SHA1]:t.sha1,[G.SHA256]:t.sha256}[e]),Ui=(e,t)=>{const r=new e;return r.update(Ee(t||"")),r.digest()},Li={name:"flexibleChecksumsMiddleware",step:"build",tags:["BODY_CHECKSUM"],override:!0},Bi=(e,t)=>(r,n)=>async i=>{if(!j.isInstance(i.request))return r(i);const{request:o,input:s}=i,{body:a,headers:c}=o,{base64Encoder:u,streamHasher:d}=e,{requestChecksumRequired:l,requestAlgorithmMember:h}=t,f=((e,{requestChecksumRequired:t,requestAlgorithmMember:r},n)=>{const i=n?X:Q;if(!r||!e[r])return t?i:void 0;const o=e[r];if(!yi.includes(o))throw new Error(`The checksum algorithm "${o}" is not supported by the client. Select one of ${yi}.`);return o})(s,{requestChecksumRequired:l,requestAlgorithmMember:h},!!n.isS3ExpressBucket);let p=a,g=c;if(f){switch(f){case G.CRC32:Y(n,"FLEXIBLE_CHECKSUMS_REQ_CRC32","U");break;case G.CRC32C:Y(n,"FLEXIBLE_CHECKSUMS_REQ_CRC32C","V");break;case G.SHA1:Y(n,"FLEXIBLE_CHECKSUMS_REQ_SHA1","X");break;case G.SHA256:Y(n,"FLEXIBLE_CHECKSUMS_REQ_SHA256","Y")}const t=bi(f),r=$i(f,e);if(wi(a)){const{getAwsChunkedEncodingStream:n,bodyLengthChecker:i}=e;p=n(a,{base64Encoder:u,bodyLengthChecker:i,checksumLocationName:t,checksumAlgorithmFn:r,streamHasher:d}),g={...c,"content-encoding":c["content-encoding"]?`${c["content-encoding"]},aws-chunked`:"aws-chunked","transfer-encoding":"chunked","x-amz-decoded-content-length":c["content-length"],"x-amz-content-sha256":"STREAMING-UNSIGNED-PAYLOAD-TRAILER","x-amz-trailer":t},delete g["content-length"]}else if(!((e,t)=>{const r=e.toLowerCase();for(const e of Object.keys(t))if(r===e.toLowerCase())return!0;return!1})(t,c)){const e=await Ui(r,a);g={...c,[t]:u(e)}}}return await r({...i,request:{...o,headers:g,body:p}})},Di=(e=[])=>{const t=[];for(const r of vi)e.includes(r)&&yi.includes(r)&&t.push(r);return t};function ji(e){return new Blob([e]).stream()}const zi=async(e,{checksumAlgorithmFn:t,base64Encoder:r})=>r(await Ui(t,e)),qi={name:"flexibleChecksumsResponseMiddleware",toMiddleware:"deserializerMiddleware",relation:"after",tags:["BODY_CHECKSUM"],override:!0},Hi=(e,t)=>(r,n)=>async i=>{if(!j.isInstance(i.request))return r(i);const o=i.input,s=await r(i),a=s.response;let c;const{requestValidationModeMember:u,responseAlgorithms:d}=t;if(u&&"ENABLED"===o[u]){const{clientName:t,commandName:r}=n;if("S3Client"===t&&"GetObjectCommand"===r&&Di(d).every((e=>{const t=bi(e),r=a.headers[t];return!r||(e=>{const t=e.lastIndexOf("-");if(-1!==t){const r=e.slice(t+1);if(!r.startsWith("0")){const e=parseInt(r,10);if(!isNaN(e)&&e>=1&&e<=1e4)return!0}}return!1})(r)})))return s;const i=wi(a.body);i&&(c=await e.streamCollector(a.body),a.body=ji(c)),await(async(e,{config:t,responseAlgorithms:r})=>{const n=Di(r),{body:i,headers:o}=e;for(const r of n){const n=bi(r),s=o[n];if(s){const o=$i(r,t),{base64Encoder:a}=t;if(wi(i))return void(e.body=We({expectedChecksum:s,checksumSourceLocation:n,checksum:new o,source:i,base64Encoder:a}));const c=await zi(i,{checksumAlgorithmFn:o,base64Encoder:a});if(c===s)break;throw new Error(`Checksum mismatch: expected "${c}" but received "${s}" in response header "${n}".`)}}})(s.response,{config:e,responseAlgorithms:d}),i&&c&&(a.body=ji(c))}return s},Wi=(e,t)=>({applyToStack:r=>{r.add(Bi(e,t),Li),r.addRelativeTo(Hi(e,t),qi)}});const Ki={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},Vi=e=>({applyToStack:t=>{t.add((e=>t=>async r=>{if(!j.isInstance(r.request))return t(r);const{request:n}=r,{handlerProtocol:i=""}=e.requestHandler.metadata||{};if(i.indexOf("h2")>=0&&!n.headers[":authority"])delete n.headers.host,n.headers[":authority"]=n.hostname+(n.port?":"+n.port:"");else if(!n.headers.host){let e=n.hostname;null!=n.port&&(e+=`:${n.port}`),n.headers.host=e}return t(r)})(e),Ki)}}),Gi={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},Ji="X-Amzn-Trace-Id",Qi={step:"build",tags:["RECURSION_DETECTION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},Xi=e=>({applyToStack:t=>{t.add((e=>t=>async r=>{const{request:n}=r;if(!j.isInstance(n)||"node"!==e.runtime||n.headers.hasOwnProperty(Ji))return t(r);const i=process.env.AWS_LAMBDA_FUNCTION_NAME,o=process.env._X_AMZN_TRACE_ID,s=e=>"string"==typeof e&&e.length>0;return s(i)&&s(o)&&(n.headers[Ji]=o),t({...r,request:n})})(e),Qi)}});const Zi={step:"finalizeRequest",tags:["CHECK_CONTENT_LENGTH_HEADER"],name:"getCheckContentLengthHeaderPlugin",override:!0},Yi=e=>({applyToStack:e=>{e.add(((e,t)=>async r=>{const{request:n}=r;if(j.isInstance(n)&&!("content-length"in n.headers)){const e="Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from @aws-sdk/lib-storage.";"function"!=typeof t?.logger?.warn||t.logger instanceof jr?console.warn(e):t.logger.warn(e)}return e({...r})}),Zi)}}),eo={tags:["REGION_REDIRECT","S3"],name:"regionRedirectEndpointMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"};const to={step:"initialize",tags:["REGION_REDIRECT","S3"],name:"regionRedirectMiddleware",override:!0},ro=e=>({applyToStack:t=>{t.add(function(e){return(t,r)=>async n=>{try{return await t(n)}catch(i){if(e.followRegionRedirects&&(301===i?.$metadata?.httpStatusCode||400===i?.$metadata?.httpStatusCode&&"IllegalLocationConstraintException"===i?.name)){try{const t=i.$response.headers["x-amz-bucket-region"];r.logger?.debug(`Redirecting from ${await e.region()} to ${t}`),r.__s3RegionRedirect=t}catch(e){throw new Error("Region redirect failed: "+e)}return t(n)}throw i}}}(e),to),t.addRelativeTo((e=>(t,r)=>async n=>{const i=await e.region(),o=e.region;let s=()=>{};r.__s3RegionRedirect&&(Object.defineProperty(e,"region",{writable:!1,value:async()=>r.__s3RegionRedirect}),s=()=>Object.defineProperty(e,"region",{writable:!0,value:o}));try{const o=await t(n);if(r.__s3RegionRedirect&&(s(),i!==await e.region()))throw new Error("Region was not restored following S3 region redirect.");return o}catch(e){throw s(),e}})(e),eo)}}),no={tags:["S3"],name:"s3ExpiresMiddleware",override:!0,relation:"after",toMiddleware:"deserializerMiddleware"},io=e=>({applyToStack:e=>{e.addRelativeTo(((e,t)=>async r=>{const n=await e(r),{response:i}=n;if(z.isInstance(i)&&i.headers.expires){i.headers.expiresstring=i.headers.expires;try{gr(i.headers.expires)}catch(e){t.logger?.warn(`AWS SDK Warning for ${t.clientName}::${t.commandName} response parsing (${i.headers.expires}): ${e}`),delete i.headers.expires}}return n}),no)}});class oo{constructor(e={}){this.data=e,this.lastPurgeTime=Date.now()}get(e){const t=this.data[e];if(t)return t}set(e,t){return this.data[e]=t,t}delete(e){delete this.data[e]}async purgeExpired(){const e=Date.now();if(!(this.lastPurgeTime+oo.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS>e))for(const t in this.data){const r=this.data[t];if(!r.isRefreshing){const n=await r.identity;n.expiration&&n.expiration.getTime(){if((e.expiration?.getTime()??0){n.set(r,new so(Promise.resolve(e)))}))),e})):n.set(r,new so(this.getIdentity(r))).identity}async getIdentity(e){await this.cache.purgeExpired().catch((e=>{console.warn("Error while clearing expired entries in S3ExpressIdentityCache: \n"+e)}));const t=await this.createSessionFn(e);if(!t.Credentials?.AccessKeyId||!t.Credentials?.SecretAccessKey)throw new Error("s3#createSession response credential missing AccessKeyId or SecretAccessKey.");return{accessKeyId:t.Credentials.AccessKeyId,secretAccessKey:t.Credentials.SecretAccessKey,sessionToken:t.Credentials.SessionToken,expiration:t.Credentials.Expiration?new Date(t.Credentials.Expiration):void 0}}}var co;ao.REFRESH_WINDOW_MS=6e4,function(e){e.ENV="env",e.CONFIG="shared config entry"}(co||(co={}));const uo="X-Amz-S3session-Token",lo=uo.toLowerCase();class ho extends Ot{async signWithCredentials(e,t,r){const n=fo(t);e.headers[lo]=t.sessionToken;return po(this,n),this.signRequest(e,r??{})}async presignWithCredentials(e,t,r){const n=fo(t);delete e.headers[lo],e.headers[uo]=t.sessionToken,e.query=e.query??{},e.query[uo]=t.sessionToken;return po(this,n),this.presign(e,r)}}function fo(e){return{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,expiration:e.expiration}}function po(e,t){const r=setTimeout((()=>{throw new Error("SignatureV4S3Express credential override was created but not called.")}),10),n=e.credentialProvider;e.credentialProvider=()=>(clearTimeout(r),e.credentialProvider=n,Promise.resolve(t))}const go={name:"s3ExpressMiddleware",step:"build",tags:["S3","S3_EXPRESS"],override:!0},mo=e=>({applyToStack:t=>{t.add((e=>(t,r)=>async n=>{if(r.endpointV2){const t=r.endpointV2,i="sigv4-s3express"===t.properties?.authSchemes?.[0]?.name;if(("S3Express"===t.properties?.backend||"Directory"===t.properties?.bucketType)&&(Y(r,"S3_EXPRESS_BUCKET","J"),r.isS3ExpressBucket=!0),i){const t=n.input.Bucket;if(t){const i=await e.s3ExpressIdentityProvider.getS3ExpressIdentity(await e.credentials(),{Bucket:t});r.s3ExpressIdentity=i,j.isInstance(n.request)&&i.sessionToken&&(n.request.headers[lo]=i.sessionToken)}}}return t(n)})(e),go)}}),yo=e=>e=>{throw e},vo=(e,t)=>{},bo=e=>(t,r)=>async n=>{if(!j.isInstance(n.request))return t(n);const i=ae(r).selectedHttpAuthScheme;if(!i)throw new Error("No HttpAuthScheme was selected: unable to sign request");const{httpAuthOption:{signingProperties:o={}},identity:s,signer:a}=i;let c;c=r.s3ExpressIdentity?await(async(e,t,r,n)=>{const i=await n.signWithCredentials(r,e,{});if(i.headers["X-Amz-Security-Token"]||i.headers["x-amz-security-token"])throw new Error("X-Amz-Security-Token must not be set for s3-express requests.");return i})(r.s3ExpressIdentity,0,n.request,await e.signer()):await a.sign(n.request,s,o);const u=await t({...n,request:c}).catch((a.errorHandler||yo)(o));return(a.successHandler||vo)(u.response,o),u},wo={CopyObjectCommand:!0,UploadPartCopyCommand:!0,CompleteMultipartUploadCommand:!0},ko=e=>(t,r)=>async n=>{const i=await t(n),{response:o}=i;if(!z.isInstance(o))return i;const{statusCode:s,body:a}=o;if(s<200||s>=300)return i;if(!("function"==typeof a?.stream||"function"==typeof a?.pipe||"function"==typeof a?.tee))return i;let c=a,u=a;!a||"object"!=typeof a||a instanceof Uint8Array||([c,u]=await async function(e){return"function"==typeof e.stream&&(e=e.stream()),e.tee()}(a)),o.body=u;const d=await So(c,{streamCollector:async e=>async function(e,t){let r=0;const n=[],i=e.getReader();let o=!1;for(;!o;){const{done:e,value:s}=await i.read();if(s&&(n.push(s),r+=s?.byteLength??0),r>=t)break;o=e}i.releaseLock();const s=new Uint8Array(Math.min(t,r));let a=0;for(const e of n){if(e.byteLength>s.byteLength-a){s.set(e.subarray(0,s.byteLength-a),a);break}s.set(e,a),a+=e.length}return s}(e,3e3)});"function"==typeof c?.destroy&&c.destroy();const l=e.utf8Encoder(d.subarray(d.length-16));if(0===d.length&&wo[r.commandName]){const e=new Error("S3 aborted request");throw e.name="InternalError",e}return l&&l.endsWith("")&&(o.statusCode=400),i},So=(e=new Uint8Array,t)=>e instanceof Uint8Array?Promise.resolve(e):t.streamCollector(e)||Promise.resolve(new Uint8Array),Eo={relation:"after",toMiddleware:"deserializerMiddleware",tags:["THROW_200_EXCEPTIONS","S3"],name:"throw200ExceptionsMiddleware",override:!0},xo=e=>({applyToStack:t=>{t.addRelativeTo(ko(e),Eo)}});const Ao={name:"bucketEndpointMiddleware",override:!0,relation:"after",toMiddleware:"endpointV2Middleware"};const To={step:"initialize",tags:["VALIDATE_BUCKET_NAME"],name:"validateBucketNameMiddleware",override:!0},Co=e=>({applyToStack:t=>{t.add(function({bucketEndpoint:e}){return t=>async r=>{const{input:{Bucket:n}}=r;if(!e&&"string"==typeof n&&!("string"==typeof(i=n)&&0===i.indexOf("arn:")&&i.split(":").length>=6)&&n.indexOf("/")>=0){const e=new Error(`Bucket name shouldn't contain '/', received '${n}'`);throw e.name="InvalidBucketName",e}var i;return t({...r})}}(e),To),t.addRelativeTo(function(e){return(t,r)=>async n=>{if(e.bucketEndpoint){const e=r.endpointV2;if(e){const t=n.input.Bucket;if("string"==typeof t)try{const n=new URL(t);r.endpointV2={...e,url:n}}catch(e){const n=`@aws-sdk/middleware-sdk-s3: bucketEndpoint=true was set but Bucket=${t} could not be parsed as URL.`;throw"NoOpLogger"===r.logger?.constructor?.name?console.warn(n):r.logger?.warn?.(n),e}}}return t(n)}}(e),Ao)}});const Ro=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),Oo=e=>Ro.test(e)||e.startsWith("[")&&e.endsWith("]"),Po=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),_o=(e,t=!1)=>{if(!t)return Po.test(e);const r=e.split(".");for(const e of r)if(!_o(e))return!1;return!0},Mo={},Io="endpoints";function No(e){return"object"!=typeof e||null==e?e:"ref"in e?`$${No(e.ref)}`:"fn"in e?`${e.fn}(${(e.argv||[]).map(No).join(", ")})`:JSON.stringify(e,null,2)}class Fo extends Error{constructor(e){super(e),this.name="EndpointError"}}const $o=(e,t)=>(e=>{const t=e.split("."),r=[];for(const n of t){const t=n.indexOf("[");if(-1!==t){if(n.indexOf("]")!==n.length-1)throw new Fo(`Path: '${e}' does not end with ']'`);const i=n.slice(t+1,-1);if(Number.isNaN(parseInt(i)))throw new Fo(`Invalid array index: '${i}' in path: '${e}'`);0!==t&&r.push(n.slice(0,t)),r.push(i)}else r.push(n)}return r})(t).reduce(((r,n)=>{if("object"!=typeof r)throw new Fo(`Index '${n}' in '${t}' not found in '${JSON.stringify(e)}'`);return Array.isArray(r)?r[parseInt(n)]:r[n]}),e),Uo={[F.HTTP]:80,[F.HTTPS]:443},Lo={booleanEquals:(e,t)=>e===t,getAttr:$o,isSet:e=>null!=e,isValidHostLabel:_o,not:e=>!e,parseURL:e=>{const t=(()=>{try{if(e instanceof URL)return e;if("object"==typeof e&&"hostname"in e){const{hostname:t,port:r,protocol:n="",path:i="",query:o={}}=e,s=new URL(`${n}//${t}${r?`:${r}`:""}${i}`);return s.search=Object.entries(o).map((([e,t])=>`${e}=${t}`)).join("&"),s}return new URL(e)}catch(e){return null}})();if(!t)return console.error(`Unable to parse ${JSON.stringify(e)} as a whatwg URL.`),null;const r=t.href,{host:n,hostname:i,pathname:o,protocol:s,search:a}=t;if(a)return null;const c=s.slice(0,-1);if(!Object.values(F).includes(c))return null;const u=Oo(i);return{scheme:c,authority:`${n}${r.includes(`${n}:${Uo[c]}`)||"string"==typeof e&&e.includes(`${n}:${Uo[c]}`)?`:${Uo[c]}`:""}`,path:o,normalizedPath:o.endsWith("/")?o:`${o}/`,isIp:u}},stringEquals:(e,t)=>e===t,substring:(e,t,r,n)=>t>=r||e.lengthencodeURIComponent(e).replace(/[!*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))},Bo=(e,t)=>{const r=[],n={...t.endpointParams,...t.referenceRecord};let i=0;for(;i{if("string"==typeof e)return Bo(e,r);if(e.fn)return jo(e,r);if(e.ref)return(({ref:e},t)=>({...t.endpointParams,...t.referenceRecord}[e]))(e,r);throw new Fo(`'${t}': ${String(e)} is not a string, function or reference.`)},jo=({fn:e,argv:t},r)=>{const n=t.map((e=>["boolean","number"].includes(typeof e)?e:Do(e,"arg",r))),i=e.split(".");return i[0]in Mo&&null!=i[1]?Mo[i[0]][i[1]](...n):Lo[e](...n)},zo=({assign:e,...t},r)=>{if(e&&e in r.referenceRecord)throw new Fo(`'${e}' is already defined in Reference Record.`);const n=jo(t,r);return r.logger?.debug?.(`${Io} evaluateCondition: ${No(t)} = ${No(n)}`),{result:""===n||!!n,...null!=e&&{toAssign:{name:e,value:n}}}},qo=(e=[],t)=>{const r={};for(const n of e){const{result:e,toAssign:i}=zo(n,{...t,referenceRecord:{...t.referenceRecord,...r}});if(!e)return{result:e};i&&(r[i.name]=i.value,t.logger?.debug?.(`${Io} assign: ${i.name} := ${No(i.value)}`))}return{result:!0,referenceRecord:r}},Ho=(e,t)=>Object.entries(e).reduce(((e,[r,n])=>({...e,[r]:n.map((e=>{const n=Do(e,"Header value entry",t);if("string"!=typeof n)throw new Fo(`Header '${r}' value '${n}' is not a string`);return n}))})),{}),Wo=(e,t)=>{if(Array.isArray(e))return e.map((e=>Wo(e,t)));switch(typeof e){case"string":return Bo(e,t);case"object":if(null===e)throw new Fo(`Unexpected endpoint property: ${e}`);return Ko(e,t);case"boolean":return e;default:throw new Fo("Unexpected endpoint property type: "+typeof e)}},Ko=(e,t)=>Object.entries(e).reduce(((e,[r,n])=>({...e,[r]:Wo(n,t)})),{}),Vo=(e,t)=>{const r=Do(e,"Endpoint URL",t);if("string"==typeof r)try{return new URL(r)}catch(e){throw console.error(`Failed to construct URL with ${r}`,e),e}throw new Fo("Endpoint URL must be a string, got "+typeof r)},Go=(e,t)=>{const{conditions:r,endpoint:n}=e,{result:i,referenceRecord:o}=qo(r,t);if(!i)return;const s={...t,referenceRecord:{...t.referenceRecord,...o}},{url:a,properties:c,headers:u}=n;return t.logger?.debug?.(`${Io} Resolving endpoint from template: ${No(n)}`),{...null!=u&&{headers:Ho(u,s)},...null!=c&&{properties:Ko(c,s)},url:Vo(a,s)}},Jo=(e,t)=>{const{conditions:r,error:n}=e,{result:i,referenceRecord:o}=qo(r,t);if(i)throw new Fo(Do(n,"Error",{...t,referenceRecord:{...t.referenceRecord,...o}}))},Qo=(e,t)=>{const{conditions:r,rules:n}=e,{result:i,referenceRecord:o}=qo(r,t);if(i)return Xo(n,{...t,referenceRecord:{...t.referenceRecord,...o}})},Xo=(e,t)=>{for(const r of e)if("endpoint"===r.type){const e=Go(r,t);if(e)return e}else if("error"===r.type)Jo(r,t);else{if("tree"!==r.type)throw new Fo(`Unknown endpoint rule: ${r}`);{const e=Qo(r,t);if(e)return e}}throw new Fo("Rules evaluation failed")},Zo=(e,t=!1)=>{if(t){for(const t of e.split("."))if(!Zo(t))return!1;return!0}return!!_o(e)&&(!(e.length<3||e.length>63)&&(e===e.toLowerCase()&&!Oo(e)))};let Yo={partitions:[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"aws-global":{description:"AWS Standard global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"AWS China global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"AWS GovCloud (US) global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"c2s.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"AWS ISO (US) global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"sc2s.sgov.gov",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"AWS ISOB (US) global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"cloud.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"csp.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{}}],version:"1.1"};const es={isVirtualHostableS3Bucket:Zo,parseArn:e=>{const t=e.split(":");if(t.length<6)return null;const[r,n,i,o,s,...a]=t;if("arn"!==r||""===n||""===i||""===a.join(":"))return null;return{partition:n,service:i,region:o,accountId:s,resourceId:a.map((e=>e.split("/"))).flat()}},partition:e=>{const{partitions:t}=Yo;for(const r of t){const{regions:t,outputs:n}=r;for(const[r,i]of Object.entries(t))if(r===e)return{...n,...i}}for(const r of t){const{regionRegex:t,outputs:n}=r;if(new RegExp(t).test(e))return{...n}}const r=t.find((e=>"aws"===e.id));if(!r)throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...r.outputs}}};Mo.aws=es;const ts=/\d{12}\.ddb/;const rs="user-agent",ns="x-amz-user-agent",is=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g,os=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;const ss=e=>(t,r)=>async n=>{const{request:i}=n;if(!j.isInstance(i))return t(n);const{headers:o}=i,s=r?.userAgent?.map(as)||[],a=(await e.defaultUserAgentProvider()).map(as);await async function(e,t,r){const n=r.request;if("rpc-v2-cbor"===n?.headers?.["smithy-protocol"]&&Y(e,"PROTOCOL_RPC_V2_CBOR","M"),"function"==typeof t.retryStrategy){const r=await t.retryStrategy();"function"==typeof r.acquireInitialRetryToken?r.constructor?.name?.includes("Adaptive")?Y(e,"RETRY_MODE_ADAPTIVE","F"):Y(e,"RETRY_MODE_STANDARD","E"):Y(e,"RETRY_MODE_LEGACY","D")}if("function"==typeof t.accountIdEndpointMode){const r=e.endpointV2;switch(String(r?.url?.hostname).match(ts)&&Y(e,"ACCOUNT_ID_ENDPOINT","O"),await(t.accountIdEndpointMode?.())){case"disabled":Y(e,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":Y(e,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":Y(e,"ACCOUNT_ID_MODE_REQUIRED","R")}}const i=e.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){const t=i;t.accountId&&Y(e,"RESOLVED_ACCOUNT_ID","T");for(const[r,n]of Object.entries(t.$source??{}))Y(e,r,n)}}(r,e,n);const c=r;a.push(`m/${function(e){let t="";for(const r in e){const n=e[r];if(!(t.length+n.length+1<=1024))break;t.length?t+=","+n:t+=n}return t}(Object.assign({},r.__smithy_context?.features,c.__aws_sdk_context?.features))}`);const u=e?.customUserAgent?.map(as)||[],d=await e.userAgentAppId();d&&a.push(as([`app/${d}`]));const l=[].concat([...a,...s,...u]).join(" "),h=[...a.filter((e=>e.startsWith("aws-sdk-"))),...u].join(" ");return"browser"!==e.runtime?(h&&(o[ns]=o[ns]?`${o[rs]} ${h}`:h),o[rs]=l):o[ns]=l,t({...n,request:i})},as=e=>{const t=e[0].split("/").map((e=>e.replace(is,"-"))).join("/"),r=e[1]?.replace(os,"-"),n=t.indexOf("/"),i=t.substring(0,n);let o=t.substring(n+1);return"api"===i&&(o=o.toLowerCase()),[i,o,r].filter((e=>e&&e.length>0)).reduce(((e,t,r)=>{switch(r){case 0:return t;case 1:return`${e}/${t}`;default:return`${e}#${t}`}}),"")},cs={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},us=e=>"string"==typeof e&&(e.startsWith("fips-")||e.endsWith("-fips")),ds=e=>us(e)?["fips-aws-global","aws-fips"].includes(e)?"us-east-1":e.replace(/fips-(dkr-|prod-)?|-fips/,""):e,ls="content-length";const hs={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},fs=e=>({applyToStack:t=>{var r;t.add((r=e.bodyLengthChecker,e=>async t=>{const n=t.request;if(j.isInstance(n)){const{body:e,headers:t}=n;if(e&&-1===Object.keys(t).map((e=>e.toLowerCase())).indexOf(ls))try{const t=r(e);n.headers={...n.headers,[ls]:String(t)}}catch(e){}}return e({...t,request:n})}),hs)}}),ps=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,gs=/(\d+\.){3}\d+/,ms=/\.\./,ys=e=>ps.test(e)&&!gs.test(e)&&!ms.test(e),vs=e=>{const[t,r,n,,,i]=e.split(":"),o="arn"===t&&e.split(":").length>=6,s=Boolean(o&&r&&n&&i);if(o&&!s)throw new Error(`Invalid ARN: ${e} was an invalid ARN.`);return s},bs=(e,t,r)=>{const n=async()=>{const n=r[e]??r[t];return"function"==typeof n?n():n};return"credentialScope"===e||"CredentialScope"===t?async()=>{const e="function"==typeof r.credentials?await r.credentials():r.credentials;return e?.credentialScope??e?.CredentialScope}:"accountId"===e||"AccountId"===t?async()=>{const e="function"==typeof r.credentials?await r.credentials():r.credentials;return e?.accountId??e?.AccountId}:"endpoint"===e||"endpoint"===t?async()=>{const e=await n();if(e&&"object"==typeof e){if("url"in e)return e.url.href;if("hostname"in e){const{protocol:t,hostname:r,port:n,path:i}=e;return`${t}//${r}${n?":"+n:""}${i}`}}return e}:n},ws=async e=>{};const ks=e=>{if("string"==typeof e)return ks(new URL(e));const{hostname:t,pathname:r,port:n,protocol:i,search:o}=e;let s;return o&&(s=function(e){const t={};if(e=e.replace(/^\?/,""))for(const r of e.split("&")){let[e,n=null]=r.split("=");e=decodeURIComponent(e),n&&(n=decodeURIComponent(n)),e in t?Array.isArray(t[e])?t[e].push(n):t[e]=[t[e],n]:t[e]=n}return t}(o)),{hostname:t,port:n?parseInt(n):void 0,protocol:i,path:r,query:s}},Ss=e=>"object"==typeof e?"url"in e?ks(e.url):e:ks(e),Es=async(e,t,r)=>{const n={},i=t?.getEndpointParameterInstructions?.()||{};for(const[t,o]of Object.entries(i))switch(o.type){case"staticContextParams":n[t]=o.value;break;case"contextParams":n[t]=e[o.name];break;case"clientContextParams":case"builtInParams":n[t]=await bs(o.name,t,r)();break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(o))}return 0===Object.keys(i).length&&Object.assign(n,r),"s3"===String(r.serviceId).toLowerCase()&&await(async e=>{const t=e?.Bucket||"";if("string"==typeof e.Bucket&&(e.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),vs(t)){if(!0===e.ForcePathStyle)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!ys(t)||-1!==t.indexOf(".")&&!String(e.Endpoint).startsWith("http:")||t.toLowerCase()!==t||t.length<3)&&(e.ForcePathStyle=!0);return e.DisableMultiRegionAccessPoints&&(e.disableMultiRegionAccessPoints=!0,e.DisableMRAP=!0),e})(n),n},xs=({config:e,instructions:t})=>(r,n)=>async i=>{e.endpoint&&function(e,t,r){e.__smithy_context?e.__smithy_context.features||(e.__smithy_context.features={}):e.__smithy_context={features:{}},e.__smithy_context.features[t]=r}(n,"ENDPOINT_OVERRIDE","N");const o=await(async(e,t,r,n)=>{if(!r.endpoint){let e;e=r.serviceConfiguredEndpoint?await r.serviceConfiguredEndpoint():await ws(r.serviceId),e&&(r.endpoint=()=>Promise.resolve(Ss(e)))}const i=await Es(e,t,r);if("function"!=typeof r.endpointProvider)throw new Error("config.endpointProvider is not set.");return r.endpointProvider(i,n)})(i.input,{getEndpointParameterInstructions:()=>t},{...e},n);n.endpointV2=o,n.authSchemes=o.properties?.authSchemes;const s=n.authSchemes?.[0];if(s){n.signing_region=s.signingRegion,n.signing_service=s.signingName;const e=ae(n),t=e?.selectedHttpAuthScheme?.httpAuthOption;t&&(t.signingProperties=Object.assign(t.signingProperties||{},{signing_region:s.signingRegion,signingRegion:s.signingRegion,signing_service:s.signingName,signingName:s.signingName,signingRegionSet:s.signingRegionSet},s.properties))}return r({...i})},As={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:he.name},Ts=(e,t)=>({applyToStack:r=>{r.addRelativeTo(xs({config:e,instructions:t}),As)}});var Cs;!function(e){e.STANDARD="standard",e.ADAPTIVE="adaptive"}(Cs||(Cs={}));const Rs=Cs.STANDARD,Os=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],Ps=["TimeoutError","RequestTimeout","RequestTimeoutException"],_s=[500,502,503,504],Ms=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],Is=e=>429===e.$metadata?.httpStatusCode||Os.includes(e.name)||1==e.$retryable?.throttling,Ns=e=>(e=>e.$metadata?.clockSkewCorrected)(e)||Ps.includes(e.name)||Ms.includes(e?.code||"")||_s.includes(e.$metadata?.httpStatusCode||0);class Fs{constructor(e){this.currentCapacity=0,this.enabled=!1,this.lastMaxRate=0,this.measuredTxRate=0,this.requestCount=0,this.lastTimestamp=0,this.timeWindow=0,this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8;const t=this.getCurrentTimeInSeconds();this.lastThrottleTime=t,this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}getCurrentTimeInSeconds(){return Date.now()/1e3}async getSendToken(){return this.acquireTokenBucket(1)}async acquireTokenBucket(e){if(this.enabled){if(this.refillTokenBucket(),e>this.currentCapacity){const t=(e-this.currentCapacity)/this.fillRate*1e3;await new Promise((e=>Fs.setTimeoutFn(e,t)))}this.currentCapacity=this.currentCapacity-e}}refillTokenBucket(){const e=this.getCurrentTimeInSeconds();if(!this.lastTimestamp)return void(this.lastTimestamp=e);const t=(e-this.lastTimestamp)*this.fillRate;this.currentCapacity=Math.min(this.maxCapacity,this.currentCapacity+t),this.lastTimestamp=e}updateClientSendingRate(e){let t;if(this.updateMeasuredRate(),Is(e)){const e=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=e,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(e),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());const r=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(r)}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(e){return this.getPrecise(e*this.beta)}cubicSuccess(e){return this.getPrecise(this.scaleConstant*Math.pow(e-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(e){this.refillTokenBucket(),this.fillRate=Math.max(e,this.minFillRate),this.maxCapacity=Math.max(e,this.minCapacity),this.currentCapacity=Math.min(this.currentCapacity,this.maxCapacity)}updateMeasuredRate(){const e=this.getCurrentTimeInSeconds(),t=Math.floor(2*e)/2;if(this.requestCount++,t>this.lastTxRateBucket){const e=this.requestCount/(t-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(e*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=t}}getPrecise(e){return parseFloat(e.toFixed(8))}}Fs.setTimeoutFn=setTimeout;const $s=({retryDelay:e,retryCount:t,retryCost:r})=>({getRetryCount:()=>t,getRetryDelay:()=>Math.min(2e4,e),getRetryCost:()=>r});class Us{constructor(e){this.maxAttempts=e,this.mode=Cs.STANDARD,this.capacity=500,this.retryBackoffStrategy=(()=>{let e=100;return{computeNextBackoffDelay:t=>Math.floor(Math.min(2e4,Math.random()*2**t*e)),setDelayBase:t=>{e=t}}})(),this.maxAttemptsProvider="function"==typeof e?e:async()=>e}async acquireInitialRetryToken(e){return $s({retryDelay:100,retryCount:0})}async refreshRetryTokenForRetry(e,t){const r=await this.getMaxAttempts();if(this.shouldRetry(e,t,r)){const r=t.errorType;this.retryBackoffStrategy.setDelayBase("THROTTLING"===r?500:100);const n=this.retryBackoffStrategy.computeNextBackoffDelay(e.getRetryCount()),i=t.retryAfterHint?Math.max(t.retryAfterHint.getTime()-Date.now()||0,n):n,o=this.getCapacityCost(r);return this.capacity-=o,$s({retryDelay:i,retryCount:e.getRetryCount()+1,retryCost:o})}throw new Error("No retry token available")}recordSuccess(e){this.capacity=Math.max(500,this.capacity+(e.getRetryCost()??1))}getCapacity(){return this.capacity}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(e){return console.warn("Max attempts provider could not resolve. Using default of 3"),3}}shouldRetry(e,t,r){return e.getRetryCount()+1=this.getCapacityCost(t.errorType)&&this.isRetryableError(t.errorType)}getCapacityCost(e){return"TRANSIENT"===e?10:5}isRetryableError(e){return"THROTTLING"===e||"TRANSIENT"===e}}class Ls{constructor(e,t){this.maxAttemptsProvider=e,this.mode=Cs.ADAPTIVE;const{rateLimiter:r}=t??{};this.rateLimiter=r??new Fs,this.standardRetryStrategy=new Us(e)}async acquireInitialRetryToken(e){return await this.rateLimiter.getSendToken(),this.standardRetryStrategy.acquireInitialRetryToken(e)}async refreshRetryTokenForRetry(e,t){return this.rateLimiter.updateClientSendingRate(t),this.standardRetryStrategy.refreshRetryTokenForRetry(e,t)}recordSuccess(e){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(e)}}let Bs;const Ds=new Uint8Array(16);function js(){if(!Bs&&(Bs="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Bs))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Bs(Ds)}const zs=[];for(let e=0;e<256;++e)zs.push((e+256).toString(16).slice(1));var qs={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Hs(e,t,r){if(qs.randomUUID&&!t&&!e)return qs.randomUUID();const n=(e=e||{}).random||(e.rng||js)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=n[e];return t}return function(e,t=0){return zs[e[t+0]]+zs[e[t+1]]+zs[e[t+2]]+zs[e[t+3]]+"-"+zs[e[t+4]]+zs[e[t+5]]+"-"+zs[e[t+6]]+zs[e[t+7]]+"-"+zs[e[t+8]]+zs[e[t+9]]+"-"+zs[e[t+10]]+zs[e[t+11]]+zs[e[t+12]]+zs[e[t+13]]+zs[e[t+14]]+zs[e[t+15]]}(n)}const Ws=e=>e?.body instanceof ReadableStream,Ks=e=>void 0!==e.acquireInitialRetryToken&&void 0!==e.refreshRetryTokenForRetry&&void 0!==e.recordSuccess,Vs=e=>{const t={error:e,errorType:Gs(e)},r=Xs(e.$response);return r&&(t.retryAfterHint=r),t},Gs=e=>Is(e)?"THROTTLING":Ns(e)?"TRANSIENT":(e=>{if(void 0!==e.$metadata?.httpStatusCode){const t=e.$metadata.httpStatusCode;return 500<=t&&t<=599&&!Ns(e)}return!1})(e)?"SERVER_ERROR":"CLIENT_ERROR",Js={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0},Qs=e=>({applyToStack:t=>{t.add((e=>(t,r)=>async n=>{let i=await e.retryStrategy();const o=await e.maxAttempts();if(!Ks(i))return i?.mode&&(r.userAgent=[...r.userAgent||[],["cfg/retry-mode",i.mode]]),i.retry(t,n);{let e=await i.acquireInitialRetryToken(r.partition_id),a=new Error,c=0,u=0;const{request:d}=n,l=j.isInstance(d);for(l&&(d.headers["amz-sdk-invocation-id"]=Hs());;)try{l&&(d.headers["amz-sdk-request"]=`attempt=${c+1}; max=${o}`);const{response:r,output:s}=await t(n);return i.recordSuccess(e),s.$metadata.attempts=c+1,s.$metadata.totalRetryDelay=u,{response:r,output:s}}catch(t){const n=Vs(t);if(a=(s=t)instanceof Error?s:s instanceof Object?Object.assign(new Error,s):"string"==typeof s?new Error(s):new Error(`AWS SDK error wrapper for ${s}`),l&&Ws(d))throw(r.logger instanceof jr?console:r.logger)?.warn("An error was encountered in a non-retryable streaming request."),a;try{e=await i.refreshRetryTokenForRetry(e,n)}catch(e){throw a.$metadata||(a.$metadata={}),a.$metadata.attempts=c+1,a.$metadata.totalRetryDelay=u,a}c=e.getRetryCount();const o=e.getRetryDelay();u+=o,await new Promise((e=>setTimeout(e,o)))}}var s})(e),Js)}}),Xs=e=>{if(!z.isInstance(e))return;const t=Object.keys(e.headers).find((e=>"retry-after"===e.toLowerCase()));if(!t)return;const r=e.headers[t],n=Number(r);if(!Number.isNaN(n))return new Date(1e3*n);return new Date(r)},Zs=null;class Ys{constructor(e){this.sigv4Signer=new ho(e),this.signerOptions=e}async sign(e,t={}){if("*"===t.signingRegion){if("node"!==this.signerOptions.runtime)throw new Error("This request requires signing with SigV4Asymmetric algorithm. It's only available in Node.js");return this.getSigv4aSigner().sign(e,t)}return this.sigv4Signer.sign(e,t)}async signWithCredentials(e,t,r={}){if("*"===r.signingRegion){if("node"!==this.signerOptions.runtime)throw new Error("This request requires signing with SigV4Asymmetric algorithm. It's only available in Node.js");return this.getSigv4aSigner().signWithCredentials(e,t,r)}return this.sigv4Signer.signWithCredentials(e,t,r)}async presign(e,t={}){if("*"===t.signingRegion){if("node"!==this.signerOptions.runtime)throw new Error("This request requires signing with SigV4Asymmetric algorithm. It's only available in Node.js");return this.getSigv4aSigner().presign(e,t)}return this.sigv4Signer.presign(e,t)}async presignWithCredentials(e,t,r={}){if("*"===r.signingRegion)throw new Error("Method presignWithCredentials is not supported for [signingRegion=*].");return this.sigv4Signer.presignWithCredentials(e,t,r)}getSigv4aSigner(){if(!this.sigv4aSigner){let e=null;try{if(e=Zs,"function"!=typeof e)throw new Error}catch(e){throw e.message=`${e.message}\nPlease check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. \nYou must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. \nFor more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`,e}this.sigv4aSigner=new e({...this.signerOptions,signingAlgorithm:1})}return this.sigv4aSigner}}const ea="required",ta="type",ra="conditions",na="fn",ia="argv",oa="ref",sa="assign",aa="url",ca="properties",ua="backend",da="authSchemes",la="disableDoubleEncoding",ha="signingName",fa="signingRegion",pa="headers",ga="signingRegionSet",ma=!0,ya="isSet",va="booleanEquals",ba="error",wa="aws.partition",ka="stringEquals",Sa="getAttr",Ea="name",xa="substring",Aa="bucketSuffix",Ta="parseURL",Ca="{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",Ra="endpoint",Oa="tree",Pa="aws.isVirtualHostableS3Bucket",_a="{url#scheme}://{Bucket}.{url#authority}{url#path}",Ma="not",Ia="{url#scheme}://{url#authority}{url#path}",Na="hardwareType",Fa="regionPrefix",$a="bucketAliasSuffix",Ua="outpostId",La="isValidHostLabel",Ba="sigv4a",Da="s3-outposts",ja="s3",za="{url#scheme}://{url#authority}{url#normalizedPath}{Bucket}",qa="https://{Bucket}.s3-accelerate.{partitionResult#dnsSuffix}",Ha="https://{Bucket}.s3.{partitionResult#dnsSuffix}",Wa="aws.parseArn",Ka="bucketArn",Va="arnType",Ga="s3-object-lambda",Ja="accesspoint",Qa="accessPointName",Xa="{url#scheme}://{accessPointName}-{bucketArn#accountId}.{url#authority}{url#path}",Za="mrapPartition",Ya="outpostType",ec="arnPrefix",tc="{url#scheme}://{url#authority}{url#normalizedPath}{uri_encoded_bucket}",rc="https://s3.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",nc="https://s3.{partitionResult#dnsSuffix}",ic={[ea]:!1,[ta]:"String"},oc={[ea]:!0,default:!1,[ta]:"Boolean"},sc={[ea]:!1,[ta]:"Boolean"},ac={[na]:va,[ia]:[{[oa]:"Accelerate"},!0]},cc={[na]:va,[ia]:[{[oa]:"UseFIPS"},!0]},uc={[na]:va,[ia]:[{[oa]:"UseDualStack"},!0]},dc={[na]:ya,[ia]:[{[oa]:"Endpoint"}]},lc={[na]:wa,[ia]:[{[oa]:"Region"}],[sa]:"partitionResult"},hc={[na]:ka,[ia]:[{[na]:Sa,[ia]:[{[oa]:"partitionResult"},Ea]},"aws-cn"]},fc={[na]:ya,[ia]:[{[oa]:"Bucket"}]},pc={[oa]:"Bucket"},gc={[na]:Ta,[ia]:[{[oa]:"Endpoint"}],[sa]:"url"},mc={[na]:va,[ia]:[{[na]:Sa,[ia]:[{[oa]:"url"},"isIp"]},!0]},yc={[oa]:"url"},vc={[na]:"uriEncode",[ia]:[pc],[sa]:"uri_encoded_bucket"},bc={[ua]:"S3Express",[da]:[{[la]:!0,[Ea]:"sigv4",[ha]:"s3express",[fa]:"{Region}"}]},wc={},kc={[na]:Pa,[ia]:[pc,!1]},Sc={[ba]:"S3Express bucket name is not a valid virtual hostable name.",[ta]:ba},Ec={[ua]:"S3Express",[da]:[{[la]:!0,[Ea]:"sigv4-s3express",[ha]:"s3express",[fa]:"{Region}"}]},xc={[na]:ya,[ia]:[{[oa]:"UseS3ExpressControlEndpoint"}]},Ac={[na]:va,[ia]:[{[oa]:"UseS3ExpressControlEndpoint"},!0]},Tc={[na]:Ma,[ia]:[dc]},Cc={[ba]:"Unrecognized S3Express bucket name format.",[ta]:ba},Rc={[na]:Ma,[ia]:[fc]},Oc={[oa]:Na},Pc={[ra]:[Tc],[ba]:"Expected a endpoint to be specified but no endpoint was found",[ta]:ba},_c={[da]:[{[la]:!0,[Ea]:Ba,[ha]:Da,[ga]:["*"]},{[la]:!0,[Ea]:"sigv4",[ha]:Da,[fa]:"{Region}"}]},Mc={[na]:va,[ia]:[{[oa]:"ForcePathStyle"},!1]},Ic={[oa]:"ForcePathStyle"},Nc={[na]:va,[ia]:[{[oa]:"Accelerate"},!1]},Fc={[na]:ka,[ia]:[{[oa]:"Region"},"aws-global"]},$c={[da]:[{[la]:!0,[Ea]:"sigv4",[ha]:ja,[fa]:"us-east-1"}]},Uc={[na]:Ma,[ia]:[Fc]},Lc={[na]:va,[ia]:[{[oa]:"UseGlobalEndpoint"},!0]},Bc={[aa]:"https://{Bucket}.s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[ca]:{[da]:[{[la]:!0,[Ea]:"sigv4",[ha]:ja,[fa]:"{Region}"}]},[pa]:{}},Dc={[da]:[{[la]:!0,[Ea]:"sigv4",[ha]:ja,[fa]:"{Region}"}]},jc={[na]:va,[ia]:[{[oa]:"UseGlobalEndpoint"},!1]},zc={[na]:va,[ia]:[{[oa]:"UseDualStack"},!1]},qc={[aa]:"https://{Bucket}.s3-fips.{Region}.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Hc={[na]:va,[ia]:[{[oa]:"UseFIPS"},!1]},Wc={[aa]:"https://{Bucket}.s3-accelerate.dualstack.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Kc={[aa]:"https://{Bucket}.s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Vc={[na]:va,[ia]:[{[na]:Sa,[ia]:[yc,"isIp"]},!1]},Gc={[aa]:za,[ca]:Dc,[pa]:{}},Jc={[aa]:_a,[ca]:Dc,[pa]:{}},Qc={[Ra]:Jc,[ta]:Ra},Xc={[aa]:qa,[ca]:Dc,[pa]:{}},Zc={[aa]:"https://{Bucket}.s3.{Region}.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Yc={[ba]:"Invalid region: region was not a valid DNS name.",[ta]:ba},eu={[oa]:Ka},tu={[oa]:Va},ru={[na]:Sa,[ia]:[eu,"service"]},nu={[oa]:Qa},iu={[ra]:[uc],[ba]:"S3 Object Lambda does not support Dual-stack",[ta]:ba},ou={[ra]:[ac],[ba]:"S3 Object Lambda does not support S3 Accelerate",[ta]:ba},su={[ra]:[{[na]:ya,[ia]:[{[oa]:"DisableAccessPoints"}]},{[na]:va,[ia]:[{[oa]:"DisableAccessPoints"},!0]}],[ba]:"Access points are not supported for this operation",[ta]:ba},au={[ra]:[{[na]:ya,[ia]:[{[oa]:"UseArnRegion"}]},{[na]:va,[ia]:[{[oa]:"UseArnRegion"},!1]},{[na]:Ma,[ia]:[{[na]:ka,[ia]:[{[na]:Sa,[ia]:[eu,"region"]},"{Region}"]}]}],[ba]:"Invalid configuration: region from ARN `{bucketArn#region}` does not match client region `{Region}` and UseArnRegion is `false`",[ta]:ba},cu={[na]:Sa,[ia]:[{[oa]:"bucketPartition"},Ea]},uu={[na]:Sa,[ia]:[eu,"accountId"]},du={[da]:[{[la]:!0,[Ea]:"sigv4",[ha]:Ga,[fa]:"{bucketArn#region}"}]},lu={[ba]:"Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `{accessPointName}`",[ta]:ba},hu={[ba]:"Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `{bucketArn#accountId}`",[ta]:ba},fu={[ba]:"Invalid region in ARN: `{bucketArn#region}` (invalid DNS name)",[ta]:ba},pu={[ba]:"Client was configured for partition `{partitionResult#name}` but ARN (`{Bucket}`) has `{bucketPartition#name}`",[ta]:ba},gu={[ba]:"Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.",[ta]:ba},mu={[ba]:"Invalid ARN: Expected a resource of the format `accesspoint:` but no name was provided",[ta]:ba},yu={[da]:[{[la]:!0,[Ea]:"sigv4",[ha]:ja,[fa]:"{bucketArn#region}"}]},vu={[da]:[{[la]:!0,[Ea]:Ba,[ha]:Da,[ga]:["*"]},{[la]:!0,[Ea]:"sigv4",[ha]:Da,[fa]:"{bucketArn#region}"}]},bu={[na]:Wa,[ia]:[pc]},wu={[aa]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ca]:Dc,[pa]:{}},ku={[aa]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ca]:Dc,[pa]:{}},Su={[aa]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ca]:Dc,[pa]:{}},Eu={[aa]:tc,[ca]:Dc,[pa]:{}},xu={[aa]:"https://s3.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ca]:Dc,[pa]:{}},Au={[oa]:"UseObjectLambdaEndpoint"},Tu={[da]:[{[la]:!0,[Ea]:"sigv4",[ha]:Ga,[fa]:"{Region}"}]},Cu={[aa]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Ru={[aa]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Ou={[aa]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Pu={[aa]:Ia,[ca]:Dc,[pa]:{}},_u={[aa]:"https://s3.{Region}.{partitionResult#dnsSuffix}",[ca]:Dc,[pa]:{}},Mu=[{[oa]:"Region"}],Iu=[{[oa]:"Endpoint"}],Nu=[pc],Fu=[uc],$u=[ac],Uu=[dc,gc],Lu=[{[na]:ya,[ia]:[{[oa]:"DisableS3ExpressSessionAuth"}]},{[na]:va,[ia]:[{[oa]:"DisableS3ExpressSessionAuth"},!0]}],Bu=[mc],Du=[vc],ju=[kc],zu=[cc],qu=[{[na]:xa,[ia]:[pc,6,14,!0],[sa]:"s3expressAvailabilityZoneId"},{[na]:xa,[ia]:[pc,14,16,!0],[sa]:"s3expressAvailabilityZoneDelim"},{[na]:ka,[ia]:[{[oa]:"s3expressAvailabilityZoneDelim"},"--"]}],Hu=[{[ra]:[cc],[Ra]:{[aa]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[ca]:bc,[pa]:{}},[ta]:Ra},{[Ra]:{[aa]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[ca]:bc,[pa]:{}},[ta]:Ra}],Wu=[{[na]:xa,[ia]:[pc,6,15,!0],[sa]:"s3expressAvailabilityZoneId"},{[na]:xa,[ia]:[pc,15,17,!0],[sa]:"s3expressAvailabilityZoneDelim"},{[na]:ka,[ia]:[{[oa]:"s3expressAvailabilityZoneDelim"},"--"]}],Ku=[{[ra]:[cc],[Ra]:{[aa]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[ca]:Ec,[pa]:{}},[ta]:Ra},{[Ra]:{[aa]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",[ca]:Ec,[pa]:{}},[ta]:Ra}],Vu=[fc],Gu=[{[na]:La,[ia]:[{[oa]:Ua},!1]}],Ju=[{[na]:ka,[ia]:[{[oa]:Fa},"beta"]}],Qu=[lc],Xu=[{[na]:La,[ia]:[{[oa]:"Region"},!1]}],Zu=[{[na]:ka,[ia]:[{[oa]:"Region"},"us-east-1"]}],Yu=[{[na]:ka,[ia]:[tu,Ja]}],ed=[{[na]:Sa,[ia]:[eu,"resourceId[1]"],[sa]:Qa},{[na]:Ma,[ia]:[{[na]:ka,[ia]:[nu,""]}]}],td=[eu,"resourceId[1]"],rd=[{[na]:Ma,[ia]:[{[na]:ka,[ia]:[{[na]:Sa,[ia]:[eu,"region"]},""]}]}],nd=[{[na]:Ma,[ia]:[{[na]:ya,[ia]:[{[na]:Sa,[ia]:[eu,"resourceId[2]"]}]}]}],id=[eu,"resourceId[2]"],od=[{[na]:wa,[ia]:[{[na]:Sa,[ia]:[eu,"region"]}],[sa]:"bucketPartition"}],sd=[{[na]:ka,[ia]:[cu,{[na]:Sa,[ia]:[{[oa]:"partitionResult"},Ea]}]}],ad=[{[na]:La,[ia]:[{[na]:Sa,[ia]:[eu,"region"]},!0]}],cd=[{[na]:La,[ia]:[uu,!1]}],ud=[{[na]:La,[ia]:[nu,!1]}],dd=[{[na]:La,[ia]:[{[oa]:"Region"},!0]}],ld={version:"1.0",parameters:{Bucket:ic,Region:ic,UseFIPS:oc,UseDualStack:oc,Endpoint:ic,ForcePathStyle:oc,Accelerate:oc,UseGlobalEndpoint:oc,UseObjectLambdaEndpoint:sc,Key:ic,Prefix:ic,CopySource:ic,DisableAccessPoints:sc,DisableMultiRegionAccessPoints:oc,UseArnRegion:sc,UseS3ExpressControlEndpoint:sc,DisableS3ExpressSessionAuth:sc},rules:[{[ra]:[{[na]:ya,[ia]:Mu}],rules:[{[ra]:[ac,cc],error:"Accelerate cannot be used with FIPS",[ta]:ba},{[ra]:[uc,dc],error:"Cannot set dual-stack in combination with a custom endpoint.",[ta]:ba},{[ra]:[dc,cc],error:"A custom endpoint cannot be combined with FIPS",[ta]:ba},{[ra]:[dc,ac],error:"A custom endpoint cannot be combined with S3 Accelerate",[ta]:ba},{[ra]:[cc,lc,hc],error:"Partition does not support FIPS",[ta]:ba},{[ra]:[fc,{[na]:xa,[ia]:[pc,0,6,ma],[sa]:Aa},{[na]:ka,[ia]:[{[oa]:Aa},"--x-s3"]}],rules:[{[ra]:Fu,error:"S3Express does not support Dual-stack.",[ta]:ba},{[ra]:$u,error:"S3Express does not support S3 Accelerate.",[ta]:ba},{[ra]:Uu,rules:[{[ra]:Lu,rules:[{[ra]:Bu,rules:[{[ra]:Du,rules:[{endpoint:{[aa]:Ca,[ca]:bc,[pa]:wc},[ta]:Ra}],[ta]:Oa}],[ta]:Oa},{[ra]:ju,rules:[{endpoint:{[aa]:_a,[ca]:bc,[pa]:wc},[ta]:Ra}],[ta]:Oa},Sc],[ta]:Oa},{[ra]:Bu,rules:[{[ra]:Du,rules:[{endpoint:{[aa]:Ca,[ca]:Ec,[pa]:wc},[ta]:Ra}],[ta]:Oa}],[ta]:Oa},{[ra]:ju,rules:[{endpoint:{[aa]:_a,[ca]:Ec,[pa]:wc},[ta]:Ra}],[ta]:Oa},Sc],[ta]:Oa},{[ra]:[xc,Ac],rules:[{[ra]:[vc,Tc],rules:[{[ra]:zu,endpoint:{[aa]:"https://s3express-control-fips.{Region}.amazonaws.com/{uri_encoded_bucket}",[ca]:bc,[pa]:wc},[ta]:Ra},{endpoint:{[aa]:"https://s3express-control.{Region}.amazonaws.com/{uri_encoded_bucket}",[ca]:bc,[pa]:wc},[ta]:Ra}],[ta]:Oa}],[ta]:Oa},{[ra]:ju,rules:[{[ra]:Lu,rules:[{[ra]:qu,rules:Hu,[ta]:Oa},{[ra]:Wu,rules:Hu,[ta]:Oa},Cc],[ta]:Oa},{[ra]:qu,rules:Ku,[ta]:Oa},{[ra]:Wu,rules:Ku,[ta]:Oa},Cc],[ta]:Oa},Sc],[ta]:Oa},{[ra]:[Rc,xc,Ac],rules:[{[ra]:Uu,endpoint:{[aa]:Ia,[ca]:bc,[pa]:wc},[ta]:Ra},{[ra]:zu,endpoint:{[aa]:"https://s3express-control-fips.{Region}.amazonaws.com",[ca]:bc,[pa]:wc},[ta]:Ra},{endpoint:{[aa]:"https://s3express-control.{Region}.amazonaws.com",[ca]:bc,[pa]:wc},[ta]:Ra}],[ta]:Oa},{[ra]:[fc,{[na]:xa,[ia]:[pc,49,50,ma],[sa]:Na},{[na]:xa,[ia]:[pc,8,12,ma],[sa]:Fa},{[na]:xa,[ia]:[pc,0,7,ma],[sa]:$a},{[na]:xa,[ia]:[pc,32,49,ma],[sa]:Ua},{[na]:wa,[ia]:Mu,[sa]:"regionPartition"},{[na]:ka,[ia]:[{[oa]:$a},"--op-s3"]}],rules:[{[ra]:Gu,rules:[{[ra]:[{[na]:ka,[ia]:[Oc,"e"]}],rules:[{[ra]:Ju,rules:[Pc,{[ra]:Uu,endpoint:{[aa]:"https://{Bucket}.ec2.{url#authority}",[ca]:_c,[pa]:wc},[ta]:Ra}],[ta]:Oa},{endpoint:{[aa]:"https://{Bucket}.ec2.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[ca]:_c,[pa]:wc},[ta]:Ra}],[ta]:Oa},{[ra]:[{[na]:ka,[ia]:[Oc,"o"]}],rules:[{[ra]:Ju,rules:[Pc,{[ra]:Uu,endpoint:{[aa]:"https://{Bucket}.op-{outpostId}.{url#authority}",[ca]:_c,[pa]:wc},[ta]:Ra}],[ta]:Oa},{endpoint:{[aa]:"https://{Bucket}.op-{outpostId}.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[ca]:_c,[pa]:wc},[ta]:Ra}],[ta]:Oa},{error:'Unrecognized hardware type: "Expected hardware type o or e but got {hardwareType}"',[ta]:ba}],[ta]:Oa},{error:"Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`.",[ta]:ba}],[ta]:Oa},{[ra]:Vu,rules:[{[ra]:[dc,{[na]:Ma,[ia]:[{[na]:ya,[ia]:[{[na]:Ta,[ia]:Iu}]}]}],error:"Custom endpoint `{Endpoint}` was not a valid URI",[ta]:ba},{[ra]:[Mc,kc],rules:[{[ra]:Qu,rules:[{[ra]:Xu,rules:[{[ra]:[ac,hc],error:"S3 Accelerate cannot be used in this region",[ta]:ba},{[ra]:[uc,cc,Nc,Tc,Fc],endpoint:{[aa]:"https://{Bucket}.s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[uc,cc,Nc,Tc,Uc,Lc],rules:[{endpoint:Bc,[ta]:Ra}],[ta]:Oa},{[ra]:[uc,cc,Nc,Tc,Uc,jc],endpoint:Bc,[ta]:Ra},{[ra]:[zc,cc,Nc,Tc,Fc],endpoint:{[aa]:"https://{Bucket}.s3-fips.us-east-1.{partitionResult#dnsSuffix}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,cc,Nc,Tc,Uc,Lc],rules:[{endpoint:qc,[ta]:Ra}],[ta]:Oa},{[ra]:[zc,cc,Nc,Tc,Uc,jc],endpoint:qc,[ta]:Ra},{[ra]:[uc,Hc,ac,Tc,Fc],endpoint:{[aa]:"https://{Bucket}.s3-accelerate.dualstack.us-east-1.{partitionResult#dnsSuffix}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[uc,Hc,ac,Tc,Uc,Lc],rules:[{endpoint:Wc,[ta]:Ra}],[ta]:Oa},{[ra]:[uc,Hc,ac,Tc,Uc,jc],endpoint:Wc,[ta]:Ra},{[ra]:[uc,Hc,Nc,Tc,Fc],endpoint:{[aa]:"https://{Bucket}.s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[uc,Hc,Nc,Tc,Uc,Lc],rules:[{endpoint:Kc,[ta]:Ra}],[ta]:Oa},{[ra]:[uc,Hc,Nc,Tc,Uc,jc],endpoint:Kc,[ta]:Ra},{[ra]:[zc,Hc,Nc,dc,gc,mc,Fc],endpoint:{[aa]:za,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,Hc,Nc,dc,gc,Vc,Fc],endpoint:{[aa]:_a,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,Hc,Nc,dc,gc,mc,Uc,Lc],rules:[{[ra]:Zu,endpoint:Gc,[ta]:Ra},{endpoint:Gc,[ta]:Ra}],[ta]:Oa},{[ra]:[zc,Hc,Nc,dc,gc,Vc,Uc,Lc],rules:[{[ra]:Zu,endpoint:Jc,[ta]:Ra},Qc],[ta]:Oa},{[ra]:[zc,Hc,Nc,dc,gc,mc,Uc,jc],endpoint:Gc,[ta]:Ra},{[ra]:[zc,Hc,Nc,dc,gc,Vc,Uc,jc],endpoint:Jc,[ta]:Ra},{[ra]:[zc,Hc,ac,Tc,Fc],endpoint:{[aa]:qa,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,Hc,ac,Tc,Uc,Lc],rules:[{[ra]:Zu,endpoint:Xc,[ta]:Ra},{endpoint:Xc,[ta]:Ra}],[ta]:Oa},{[ra]:[zc,Hc,ac,Tc,Uc,jc],endpoint:Xc,[ta]:Ra},{[ra]:[zc,Hc,Nc,Tc,Fc],endpoint:{[aa]:Ha,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,Hc,Nc,Tc,Uc,Lc],rules:[{[ra]:Zu,endpoint:{[aa]:Ha,[ca]:Dc,[pa]:wc},[ta]:Ra},{endpoint:Zc,[ta]:Ra}],[ta]:Oa},{[ra]:[zc,Hc,Nc,Tc,Uc,jc],endpoint:Zc,[ta]:Ra}],[ta]:Oa},Yc],[ta]:Oa}],[ta]:Oa},{[ra]:[dc,gc,{[na]:ka,[ia]:[{[na]:Sa,[ia]:[yc,"scheme"]},"http"]},{[na]:Pa,[ia]:[pc,ma]},Mc,Hc,zc,Nc],rules:[{[ra]:Qu,rules:[{[ra]:Xu,rules:[Qc],[ta]:Oa},Yc],[ta]:Oa}],[ta]:Oa},{[ra]:[Mc,{[na]:Wa,[ia]:Nu,[sa]:Ka}],rules:[{[ra]:[{[na]:Sa,[ia]:[eu,"resourceId[0]"],[sa]:Va},{[na]:Ma,[ia]:[{[na]:ka,[ia]:[tu,""]}]}],rules:[{[ra]:[{[na]:ka,[ia]:[ru,Ga]}],rules:[{[ra]:Yu,rules:[{[ra]:ed,rules:[iu,ou,{[ra]:rd,rules:[su,{[ra]:nd,rules:[au,{[ra]:od,rules:[{[ra]:Qu,rules:[{[ra]:sd,rules:[{[ra]:ad,rules:[{[ra]:[{[na]:ka,[ia]:[uu,""]}],error:"Invalid ARN: Missing account id",[ta]:ba},{[ra]:cd,rules:[{[ra]:ud,rules:[{[ra]:Uu,endpoint:{[aa]:Xa,[ca]:du,[pa]:wc},[ta]:Ra},{[ra]:zu,endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ca]:du,[pa]:wc},[ta]:Ra},{endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ca]:du,[pa]:wc},[ta]:Ra}],[ta]:Oa},lu],[ta]:Oa},hu],[ta]:Oa},fu],[ta]:Oa},pu],[ta]:Oa}],[ta]:Oa}],[ta]:Oa},gu],[ta]:Oa},{error:"Invalid ARN: bucket ARN is missing a region",[ta]:ba}],[ta]:Oa},mu],[ta]:Oa},{error:"Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `{arnType}`",[ta]:ba}],[ta]:Oa},{[ra]:Yu,rules:[{[ra]:ed,rules:[{[ra]:rd,rules:[{[ra]:Yu,rules:[{[ra]:rd,rules:[su,{[ra]:nd,rules:[au,{[ra]:od,rules:[{[ra]:Qu,rules:[{[ra]:[{[na]:ka,[ia]:[cu,"{partitionResult#name}"]}],rules:[{[ra]:ad,rules:[{[ra]:[{[na]:ka,[ia]:[ru,ja]}],rules:[{[ra]:cd,rules:[{[ra]:ud,rules:[{[ra]:$u,error:"Access Points do not support S3 Accelerate",[ta]:ba},{[ra]:[cc,uc],endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ca]:yu,[pa]:wc},[ta]:Ra},{[ra]:[cc,zc],endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ca]:yu,[pa]:wc},[ta]:Ra},{[ra]:[Hc,uc],endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ca]:yu,[pa]:wc},[ta]:Ra},{[ra]:[Hc,zc,dc,gc],endpoint:{[aa]:Xa,[ca]:yu,[pa]:wc},[ta]:Ra},{[ra]:[Hc,zc],endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ca]:yu,[pa]:wc},[ta]:Ra}],[ta]:Oa},lu],[ta]:Oa},hu],[ta]:Oa},{error:"Invalid ARN: The ARN was not for the S3 service, found: {bucketArn#service}",[ta]:ba}],[ta]:Oa},fu],[ta]:Oa},pu],[ta]:Oa}],[ta]:Oa}],[ta]:Oa},gu],[ta]:Oa}],[ta]:Oa}],[ta]:Oa},{[ra]:[{[na]:La,[ia]:[nu,ma]}],rules:[{[ra]:Fu,error:"S3 MRAP does not support dual-stack",[ta]:ba},{[ra]:zu,error:"S3 MRAP does not support FIPS",[ta]:ba},{[ra]:$u,error:"S3 MRAP does not support S3 Accelerate",[ta]:ba},{[ra]:[{[na]:va,[ia]:[{[oa]:"DisableMultiRegionAccessPoints"},ma]}],error:"Invalid configuration: Multi-Region Access Point ARNs are disabled.",[ta]:ba},{[ra]:[{[na]:wa,[ia]:Mu,[sa]:Za}],rules:[{[ra]:[{[na]:ka,[ia]:[{[na]:Sa,[ia]:[{[oa]:Za},Ea]},{[na]:Sa,[ia]:[eu,"partition"]}]}],rules:[{endpoint:{[aa]:"https://{accessPointName}.accesspoint.s3-global.{mrapPartition#dnsSuffix}",[ca]:{[da]:[{[la]:ma,name:Ba,[ha]:ja,[ga]:["*"]}]},[pa]:wc},[ta]:Ra}],[ta]:Oa},{error:"Client was configured for partition `{mrapPartition#name}` but bucket referred to partition `{bucketArn#partition}`",[ta]:ba}],[ta]:Oa}],[ta]:Oa},{error:"Invalid Access Point Name",[ta]:ba}],[ta]:Oa},mu],[ta]:Oa},{[ra]:[{[na]:ka,[ia]:[ru,Da]}],rules:[{[ra]:Fu,error:"S3 Outposts does not support Dual-stack",[ta]:ba},{[ra]:zu,error:"S3 Outposts does not support FIPS",[ta]:ba},{[ra]:$u,error:"S3 Outposts does not support S3 Accelerate",[ta]:ba},{[ra]:[{[na]:ya,[ia]:[{[na]:Sa,[ia]:[eu,"resourceId[4]"]}]}],error:"Invalid Arn: Outpost Access Point ARN contains sub resources",[ta]:ba},{[ra]:[{[na]:Sa,[ia]:td,[sa]:Ua}],rules:[{[ra]:Gu,rules:[au,{[ra]:od,rules:[{[ra]:Qu,rules:[{[ra]:sd,rules:[{[ra]:ad,rules:[{[ra]:cd,rules:[{[ra]:[{[na]:Sa,[ia]:id,[sa]:Ya}],rules:[{[ra]:[{[na]:Sa,[ia]:[eu,"resourceId[3]"],[sa]:Qa}],rules:[{[ra]:[{[na]:ka,[ia]:[{[oa]:Ya},Ja]}],rules:[{[ra]:Uu,endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.{url#authority}",[ca]:vu,[pa]:wc},[ta]:Ra},{endpoint:{[aa]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.s3-outposts.{bucketArn#region}.{bucketPartition#dnsSuffix}",[ca]:vu,[pa]:wc},[ta]:Ra}],[ta]:Oa},{error:"Expected an outpost type `accesspoint`, found {outpostType}",[ta]:ba}],[ta]:Oa},{error:"Invalid ARN: expected an access point name",[ta]:ba}],[ta]:Oa},{error:"Invalid ARN: Expected a 4-component resource",[ta]:ba}],[ta]:Oa},hu],[ta]:Oa},fu],[ta]:Oa},pu],[ta]:Oa}],[ta]:Oa}],[ta]:Oa},{error:"Invalid ARN: The outpost Id may only contain a-z, A-Z, 0-9 and `-`. Found: `{outpostId}`",[ta]:ba}],[ta]:Oa},{error:"Invalid ARN: The Outpost Id was not set",[ta]:ba}],[ta]:Oa},{error:"Invalid ARN: Unrecognized format: {Bucket} (type: {arnType})",[ta]:ba}],[ta]:Oa},{error:"Invalid ARN: No ARN type specified",[ta]:ba}],[ta]:Oa},{[ra]:[{[na]:xa,[ia]:[pc,0,4,!1],[sa]:ec},{[na]:ka,[ia]:[{[oa]:ec},"arn:"]},{[na]:Ma,[ia]:[{[na]:ya,[ia]:[bu]}]}],error:"Invalid ARN: `{Bucket}` was not a valid ARN",[ta]:ba},{[ra]:[{[na]:va,[ia]:[Ic,ma]},bu],error:"Path-style addressing cannot be used with ARN buckets",[ta]:ba},{[ra]:Du,rules:[{[ra]:Qu,rules:[{[ra]:[Nc],rules:[{[ra]:[uc,Tc,cc,Fc],endpoint:{[aa]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[uc,Tc,cc,Uc,Lc],rules:[{endpoint:wu,[ta]:Ra}],[ta]:Oa},{[ra]:[uc,Tc,cc,Uc,jc],endpoint:wu,[ta]:Ra},{[ra]:[zc,Tc,cc,Fc],endpoint:{[aa]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,Tc,cc,Uc,Lc],rules:[{endpoint:ku,[ta]:Ra}],[ta]:Oa},{[ra]:[zc,Tc,cc,Uc,jc],endpoint:ku,[ta]:Ra},{[ra]:[uc,Tc,Hc,Fc],endpoint:{[aa]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[uc,Tc,Hc,Uc,Lc],rules:[{endpoint:Su,[ta]:Ra}],[ta]:Oa},{[ra]:[uc,Tc,Hc,Uc,jc],endpoint:Su,[ta]:Ra},{[ra]:[zc,dc,gc,Hc,Fc],endpoint:{[aa]:tc,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,dc,gc,Hc,Uc,Lc],rules:[{[ra]:Zu,endpoint:Eu,[ta]:Ra},{endpoint:Eu,[ta]:Ra}],[ta]:Oa},{[ra]:[zc,dc,gc,Hc,Uc,jc],endpoint:Eu,[ta]:Ra},{[ra]:[zc,Tc,Hc,Fc],endpoint:{[aa]:rc,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[zc,Tc,Hc,Uc,Lc],rules:[{[ra]:Zu,endpoint:{[aa]:rc,[ca]:Dc,[pa]:wc},[ta]:Ra},{endpoint:xu,[ta]:Ra}],[ta]:Oa},{[ra]:[zc,Tc,Hc,Uc,jc],endpoint:xu,[ta]:Ra}],[ta]:Oa},{error:"Path-style addressing cannot be used with S3 Accelerate",[ta]:ba}],[ta]:Oa}],[ta]:Oa}],[ta]:Oa},{[ra]:[{[na]:ya,[ia]:[Au]},{[na]:va,[ia]:[Au,ma]}],rules:[{[ra]:Qu,rules:[{[ra]:dd,rules:[iu,ou,{[ra]:Uu,endpoint:{[aa]:Ia,[ca]:Tu,[pa]:wc},[ta]:Ra},{[ra]:zu,endpoint:{[aa]:"https://s3-object-lambda-fips.{Region}.{partitionResult#dnsSuffix}",[ca]:Tu,[pa]:wc},[ta]:Ra},{endpoint:{[aa]:"https://s3-object-lambda.{Region}.{partitionResult#dnsSuffix}",[ca]:Tu,[pa]:wc},[ta]:Ra}],[ta]:Oa},Yc],[ta]:Oa}],[ta]:Oa},{[ra]:[Rc],rules:[{[ra]:Qu,rules:[{[ra]:dd,rules:[{[ra]:[cc,uc,Tc,Fc],endpoint:{[aa]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[cc,uc,Tc,Uc,Lc],rules:[{endpoint:Cu,[ta]:Ra}],[ta]:Oa},{[ra]:[cc,uc,Tc,Uc,jc],endpoint:Cu,[ta]:Ra},{[ra]:[cc,zc,Tc,Fc],endpoint:{[aa]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[cc,zc,Tc,Uc,Lc],rules:[{endpoint:Ru,[ta]:Ra}],[ta]:Oa},{[ra]:[cc,zc,Tc,Uc,jc],endpoint:Ru,[ta]:Ra},{[ra]:[Hc,uc,Tc,Fc],endpoint:{[aa]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[Hc,uc,Tc,Uc,Lc],rules:[{endpoint:Ou,[ta]:Ra}],[ta]:Oa},{[ra]:[Hc,uc,Tc,Uc,jc],endpoint:Ou,[ta]:Ra},{[ra]:[Hc,zc,dc,gc,Fc],endpoint:{[aa]:Ia,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[Hc,zc,dc,gc,Uc,Lc],rules:[{[ra]:Zu,endpoint:Pu,[ta]:Ra},{endpoint:Pu,[ta]:Ra}],[ta]:Oa},{[ra]:[Hc,zc,dc,gc,Uc,jc],endpoint:Pu,[ta]:Ra},{[ra]:[Hc,zc,Tc,Fc],endpoint:{[aa]:nc,[ca]:$c,[pa]:wc},[ta]:Ra},{[ra]:[Hc,zc,Tc,Uc,Lc],rules:[{[ra]:Zu,endpoint:{[aa]:nc,[ca]:Dc,[pa]:wc},[ta]:Ra},{endpoint:_u,[ta]:Ra}],[ta]:Oa},{[ra]:[Hc,zc,Tc,Uc,jc],endpoint:_u,[ta]:Ra}],[ta]:Oa},Yc],[ta]:Oa}],[ta]:Oa}],[ta]:Oa},{error:"A region must be set when sending requests to S3.",[ta]:ba}]},hd=new class{constructor({size:e,params:t}){this.data=new Map,this.parameters=[],this.capacity=e??50,t&&(this.parameters=t)}get(e,t){const r=this.hash(e);if(!1===r)return t();if(!this.data.has(r)){if(this.data.size>this.capacity+10){const e=this.data.keys();let t=0;for(;;){const{value:r,done:n}=e.next();if(this.data.delete(r),n||++t>10)break}}this.data.set(r,t())}return this.data.get(r)}size(){return this.data.size}hash(e){let t="";const{parameters:r}=this;if(0===r.length)return!1;for(const n of r){const r=String(e[n]??"");if(r.includes("|;"))return!1;t+=r+"|;"}return t}}({size:50,params:["Accelerate","Bucket","DisableAccessPoints","DisableMultiRegionAccessPoints","DisableS3ExpressSessionAuth","Endpoint","ForcePathStyle","Region","UseArnRegion","UseDualStack","UseFIPS","UseGlobalEndpoint","UseObjectLambdaEndpoint","UseS3ExpressControlEndpoint"]}),fd=(e,t={})=>hd.get(e,(()=>((e,t)=>{const{endpointParams:r,logger:n}=t,{parameters:i,rules:o}=e;t.logger?.debug?.(`${Io} Initial EndpointParams: ${No(r)}`);const s=Object.entries(i).filter((([,e])=>null!=e.default)).map((([e,t])=>[e,t.default]));if(s.length>0)for(const[e,t]of s)r[e]=r[e]??t;const a=Object.entries(i).filter((([,e])=>e.required)).map((([e])=>e));for(const e of a)if(null==r[e])throw new Fo(`Missing required parameter: '${e}'`);const c=Xo(o,{endpointParams:r,logger:n,referenceRecord:{}});return t.logger?.debug?.(`${Io} Resolved endpoint: ${No(c)}`),c})(ld,{endpointParams:e,logger:t.logger})));Mo.aws=es;const pd=(gd=async(e,t,r)=>({operation:ae(t).operation,region:await ce(e.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()}),async(e,t,r)=>{if(!r)throw new Error("Could not find `input` for `defaultEndpointRuleSetHttpAuthSchemeParametersProvider`");const n=await gd(e,t,r),i=ae(t)?.commandInstance?.constructor?.getEndpointParameterInstructions;if(!i)throw new Error(`getEndpointParameterInstructions() is not defined on \`${t.commandName}\``);const o=await Es(r,{getEndpointParameterInstructions:i},e);return Object.assign(n,o)});var gd;function md(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"s3",region:e.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}function yd(e){return{schemeId:"aws.auth#sigv4a",signingProperties:{name:"s3",region:e.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}const vd=((e,t,r)=>n=>{const i=e(n),o=i.properties?.authSchemes;if(!o)return t(n);const s=[];for(const e of o){const{name:t,properties:i={},...a}=e,c=t.toLowerCase();let u;if(t!==c&&console.warn(`HttpAuthScheme has been normalized with lowercasing: \`${t}\` to \`${c}\``),"sigv4a"===c){u="aws.auth#sigv4a";const e=o.find((e=>{const t=e.name.toLowerCase();return"sigv4a"!==t&&t.startsWith("sigv4")}));if(e)continue}else{if(!c.startsWith("sigv4"))throw new Error(`Unknown HttpAuthScheme found in \`@smithy.rules#endpointRuleSet\`: \`${c}\``);u="aws.auth#sigv4"}const d=r[u];if(!d)throw new Error(`Could not find HttpAuthOption create function for \`${u}\``);const l=d(n);l.schemeId=u,l.signingProperties={...l.signingProperties||{},...a,...i},s.push(l)}return s})(fd,(e=>{const t=[];return e.operation,t.push(md(e)),t.push(yd(e)),t}),{"aws.auth#sigv4":md,"aws.auth#sigv4a":yd}),bd=e=>{const t=(e=>(e.sigv4aSigningRegionSet=ve(e.sigv4aSigningRegionSet),e))(Mt(e));return{...t}},wd={ForcePathStyle:{type:"clientContextParams",name:"forcePathStyle"},UseArnRegion:{type:"clientContextParams",name:"useArnRegion"},DisableMultiRegionAccessPoints:{type:"clientContextParams",name:"disableMultiregionAccessPoints"},Accelerate:{type:"clientContextParams",name:"useAccelerateEndpoint"},DisableS3ExpressSessionAuth:{type:"clientContextParams",name:"disableS3ExpressSessionAuth"},UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};class kd extends Cr{constructor(e){super(e),Object.setPrototypeOf(this,kd.prototype)}}class Sd extends kd{constructor(e){super({name:"NoSuchUpload",$fault:"client",...e}),this.name="NoSuchUpload",this.$fault="client",Object.setPrototypeOf(this,Sd.prototype)}}class Ed extends kd{constructor(e){super({name:"ObjectNotInActiveTierError",$fault:"client",...e}),this.name="ObjectNotInActiveTierError",this.$fault="client",Object.setPrototypeOf(this,Ed.prototype)}}class xd extends kd{constructor(e){super({name:"BucketAlreadyExists",$fault:"client",...e}),this.name="BucketAlreadyExists",this.$fault="client",Object.setPrototypeOf(this,xd.prototype)}}class Ad extends kd{constructor(e){super({name:"BucketAlreadyOwnedByYou",$fault:"client",...e}),this.name="BucketAlreadyOwnedByYou",this.$fault="client",Object.setPrototypeOf(this,Ad.prototype)}}class Td extends kd{constructor(e){super({name:"NoSuchBucket",$fault:"client",...e}),this.name="NoSuchBucket",this.$fault="client",Object.setPrototypeOf(this,Td.prototype)}}var Cd,Rd;!function(e){e.visit=(e,t)=>void 0!==e.Prefix?t.Prefix(e.Prefix):void 0!==e.Tag?t.Tag(e.Tag):void 0!==e.And?t.And(e.And):t._(e.$unknown[0],e.$unknown[1])}(Cd||(Cd={})),function(e){e.visit=(e,t)=>void 0!==e.Prefix?t.Prefix(e.Prefix):void 0!==e.Tag?t.Tag(e.Tag):void 0!==e.AccessPointArn?t.AccessPointArn(e.AccessPointArn):void 0!==e.And?t.And(e.And):t._(e.$unknown[0],e.$unknown[1])}(Rd||(Rd={}));class Od extends kd{constructor(e){super({name:"InvalidObjectState",$fault:"client",...e}),this.name="InvalidObjectState",this.$fault="client",Object.setPrototypeOf(this,Od.prototype),this.StorageClass=e.StorageClass,this.AccessTier=e.AccessTier}}class Pd extends kd{constructor(e){super({name:"NoSuchKey",$fault:"client",...e}),this.name="NoSuchKey",this.$fault="client",Object.setPrototypeOf(this,Pd.prototype)}}class _d extends kd{constructor(e){super({name:"NotFound",$fault:"client",...e}),this.name="NotFound",this.$fault="client",Object.setPrototypeOf(this,_d.prototype)}}const Md=e=>({...e,...e.SecretAccessKey&&{SecretAccessKey:jt},...e.SessionToken&&{SessionToken:jt}}),Id=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:jt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:jt},...e.Credentials&&{Credentials:Md(e.Credentials)}}),Nd=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:jt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:jt}}),Fd=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:jt}}),$d=e=>({...e,...e.SSECustomerKey&&{SSECustomerKey:jt}});class Ud extends kd{constructor(e){super({name:"EncryptionTypeMismatch",$fault:"client",...e}),this.name="EncryptionTypeMismatch",this.$fault="client",Object.setPrototypeOf(this,Ud.prototype)}}class Ld extends kd{constructor(e){super({name:"InvalidRequest",$fault:"client",...e}),this.name="InvalidRequest",this.$fault="client",Object.setPrototypeOf(this,Ld.prototype)}}class Bd extends kd{constructor(e){super({name:"InvalidWriteOffset",$fault:"client",...e}),this.name="InvalidWriteOffset",this.$fault="client",Object.setPrototypeOf(this,Bd.prototype)}}class Dd extends kd{constructor(e){super({name:"TooManyParts",$fault:"client",...e}),this.name="TooManyParts",this.$fault="client",Object.setPrototypeOf(this,Dd.prototype)}}class jd extends kd{constructor(e){super({name:"ObjectAlreadyInActiveTierError",$fault:"client",...e}),this.name="ObjectAlreadyInActiveTierError",this.$fault="client",Object.setPrototypeOf(this,jd.prototype)}}var zd;!function(e){e.visit=(e,t)=>void 0!==e.Records?t.Records(e.Records):void 0!==e.Stats?t.Stats(e.Stats):void 0!==e.Progress?t.Progress(e.Progress):void 0!==e.Cont?t.Cont(e.Cont):void 0!==e.End?t.End(e.End):t._(e.$unknown[0],e.$unknown[1])}(zd||(zd={}));const qd=e=>({...e,...e.SSEKMSKeyId&&{SSEKMSKeyId:jt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:jt}}),Hd=e=>({...e,...e.SSECustomerKey&&{SSECustomerKey:jt},...e.SSEKMSKeyId&&{SSEKMSKeyId:jt},...e.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:jt}}),Wd=async(e,t)=>{const r=Ge(e,t),n=zr({},Br,{[Zf]:e[Jh],[Sp]:e[Qh],[Ep]:e[tf],[Ap]:e[ef],[xp]:[()=>Br(e[Ol]),()=>e[Ol].toString()]});r.bp("/"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1);const i=zr({[zf]:[,""]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Kd=async(e,t)=>{const r=Ge(e,t),n=zr({},Br,{[cp]:e[wh],[vp]:e[zh],[Kf]:[()=>Br(e[Rl]),()=>e[Rl].toString()],[tp]:e[Zl],[Tf]:e[uh],[sp]:[()=>Br(e[dh]),()=>ur(e[dh]).toString()],[ap]:[()=>Br(e[lh]),()=>e[lh].toString()]});r.bp("/{Key+}"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1),r.p("Key",(()=>e.Key),"{Key+}",!0);const i=zr({[Np]:[,"DeleteObject"],[Hf]:[,e[af]]});return r.m("DELETE").h(n).q(i).b(undefined),r.build()},Vd=async(e,t)=>{const r=Ge(e,t),n=zr({},Br,{[Tf]:e[uh],[Cf]:[()=>Br(e[hh]),()=>ur(e[hh]).toString()],[Rf]:e[fh],[Of]:[()=>Br(e[mh]),()=>ur(e[mh]).toString()],[Ff]:e[Ih],[Tp]:e[Xh],[Cp]:e[Zh],[Rp]:e[Yh],[vp]:e[zh],[tp]:e[Zl],[Jf]:e[Bl]});r.bp("/{Key+}"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1),r.p("Key",(()=>e.Key),"{Key+}",!0);const i=zr({[Np]:[,"GetObject"],[$f]:[,e[Fh]],[Uf]:[,e[$h]],[Lf]:[,e[Uh]],[Bf]:[,e[Lh]],[Df]:[,e[Bh]],[jf]:[()=>void 0!==e.ResponseExpires,()=>ur(e[Dh]).toString()],[Hf]:[,e[af]],[If]:[()=>void 0!==e.PartNumber,()=>e[Mh].toString()]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Gd=async(e,t)=>{const r=Ge(e,t),n=zr({},Br,{[vp]:e[zh],[tp]:e[Zl],[pp]:[()=>Br(e[Oh]),()=>(e[Oh]||[]).map(Vr).join(", ")]});r.bp("/"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1);const i=zr({[_f]:[,"2"],[wf]:[,e[Gl]],[Sf]:[,e[eh]],[Mf]:[()=>void 0!==e.MaxKeys,()=>e[kh].toString()],[Nf]:[,e[Ph]],[bf]:[,e[Kl]],[Af]:[()=>void 0!==e.FetchOwner,()=>e[nh].toString()],[qf]:[,e[Kh]]});return r.m("GET").h(n).q(i).b(undefined),r.build()},Jd=async(e,t)=>{const r=Ge(e,t),n=zr({},Br,{[vf]:e[Wl]||"application/octet-stream",[Wf]:e[xl],[lf]:e[Ml],[hf]:e[Fl],[ff]:e[$l],[pf]:e[Ul],[gf]:[()=>Br(e[Ll]),()=>e[Ll].toString()],[mf]:e[Dl],[kp]:e[_l],[Vf]:e[Il],[Gf]:e[Nl],[Qf]:e[ql],[Xf]:e[Hl],[kf]:[()=>Br(e[Xl]),()=>ur(e[Xl]).toString()],[Tf]:e[uh],[Rf]:e[fh],[rp]:e[ih],[np]:e[oh],[ip]:e[sh],[op]:e[ah],[Mp]:[()=>Br(e[cf]),()=>e[cf].toString()],[Sp]:e[Qh],[wp]:e[Gh],[Ip]:e[uf],[Tp]:e[Xh],[Cp]:e[Zh],[Rp]:e[Yh],[Ep]:e[tf],[Ap]:e[ef],[xp]:[()=>Br(e[Ol]),()=>e[Ol].toString()],[vp]:e[zh],[Op]:e[of],[hp]:e[Ch],[fp]:[()=>Br(e[Rh]),()=>{return(t=e[Rh],t.toISOString().replace(".000Z","Z")).toString();var t}],[lp]:e[Th],[tp]:e[Zl],...void 0!==e.Metadata&&Object.keys(e.Metadata).reduce(((t,r)=>(t[`x-amz-meta-${r.toLowerCase()}`]=e.Metadata[r],t)),{})});r.bp("/{Key+}"),r.p("Bucket",(()=>e.Bucket),"{Bucket}",!1),r.p("Key",(()=>e.Key),"{Key+}",!0);const i=zr({[Np]:[,"PutObject"]});let o,s;return void 0!==e.Body&&(s=e.Body,o=s),r.m("PUT").h(n).q(i).b(o),r.build()},Qd=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return tl(e,t);const r=zr({$metadata:El(e),[Qh]:[,e.headers[Sp]],[tf]:[,e.headers[Ep]],[ef]:[,e.headers[Ap]],[Ol]:[()=>void 0!==e.headers[xp],()=>zt(e.headers[xp])]}),n=Xt(Zt(await gi(e.body,t)),"body");return null!=n[Pl]&&(r[Pl]=Sl(n[Pl])),r},Xd=async(e,t)=>{if(204!==e.statusCode&&e.statusCode>=300)return tl(e,t);const r=zr({$metadata:El(e),[Jl]:[()=>void 0!==e.headers[Yf],()=>zt(e.headers[Yf])],[af]:[,e.headers[_p]],[Nh]:[,e.headers[yp]]});return await Ke(e.body,t),r},Zd=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return tl(e,t);const r=zr({$metadata:El(e),[Jl]:[()=>void 0!==e.headers[Yf],()=>zt(e.headers[Yf])],[Tl]:[,e.headers[df]],[rh]:[,e.headers[ep]],[Wh]:[,e.headers[mp]],[bh]:[()=>void 0!==e.headers[Pf],()=>Xt(gr(e.headers[Pf]))],[Ll]:[()=>void 0!==e.headers[gf],()=>rr(e.headers[gf])],[th]:[,e.headers[Ef]],[Il]:[,e.headers[Vf]],[Nl]:[,e.headers[Gf]],[ql]:[,e.headers[Qf]],[Hl]:[,e.headers[Xf]],[Sh]:[()=>void 0!==e.headers[up],()=>nr(e.headers[up])],[af]:[,e.headers[_p]],[Ml]:[,e.headers[lf]],[Fl]:[,e.headers[hf]],[$l]:[,e.headers[ff]],[Ul]:[,e.headers[pf]],[zl]:[,e.headers[yf]],[Wl]:[,e.headers[vf]],[Xl]:[()=>void 0!==e.headers[kf],()=>Xt(gr(e.headers[kf]))],[Yl]:[,e.headers[xf]],[uf]:[,e.headers[Ip]],[Qh]:[,e.headers[Sp]],[Xh]:[,e.headers[Tp]],[Yh]:[,e.headers[Rp]],[tf]:[,e.headers[Ep]],[Ol]:[()=>void 0!==e.headers[xp],()=>zt(e.headers[xp])],[Gh]:[,e.headers[wp]],[Nh]:[,e.headers[yp]],[qh]:[,e.headers[bp]],[_h]:[()=>void 0!==e.headers[dp],()=>nr(e.headers[dp])],[sf]:[()=>void 0!==e.headers[Pp],()=>nr(e.headers[Pp])],[Ch]:[,e.headers[hp]],[Rh]:[()=>void 0!==e.headers[fp],()=>Xt(lr(e.headers[fp]))],[Th]:[,e.headers[lp]],Metadata:[,Object.keys(e.headers).filter((e=>e.startsWith("x-amz-meta-"))).reduce(((t,r)=>(t[r.substring(11)]=e.headers[r],t)),{})]}),n=e.body;return t.sdkStreamMixin(n),r.Body=n,r},Yd=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return tl(e,t);const r=zr({$metadata:El(e),[Nh]:[,e.headers[yp]]}),n=Xt(Zt(await gi(e.body,t)),"body");return""===n.CommonPrefixes?r[jl]=[]:null!=n[jl]&&(r[jl]=yl(Ur(n[jl]))),""===n.Contents?r[Vl]=[]:null!=n[Vl]&&(r[Vl]=bl(Ur(n[Vl]))),null!=n[Kl]&&(r[Kl]=Yt(n[Kl])),null!=n[Gl]&&(r[Gl]=Yt(n[Gl])),null!=n[eh]&&(r[eh]=Yt(n[eh])),null!=n[gh]&&(r[gh]=zt(n[gh])),null!=n[vh]&&(r[vh]=nr(n[vh])),null!=n[kh]&&(r[kh]=nr(n[kh])),null!=n[Eh]&&(r[Eh]=Yt(n[Eh])),null!=n[xh]&&(r[xh]=Yt(n[xh])),null!=n[Ph]&&(r[Ph]=Yt(n[Ph])),null!=n[Kh]&&(r[Kh]=Yt(n[Kh])),r},el=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return tl(e,t);const r=zr({$metadata:El(e),[rh]:[,e.headers[ep]],[th]:[,e.headers[Ef]],[Il]:[,e.headers[Vf]],[Nl]:[,e.headers[Gf]],[ql]:[,e.headers[Qf]],[Hl]:[,e.headers[Xf]],[Qh]:[,e.headers[Sp]],[af]:[,e.headers[_p]],[Xh]:[,e.headers[Tp]],[Yh]:[,e.headers[Rp]],[tf]:[,e.headers[Ep]],[ef]:[,e.headers[Ap]],[Ol]:[()=>void 0!==e.headers[xp],()=>zt(e.headers[xp])],[nf]:[()=>void 0!==e.headers[gp],()=>rr(e.headers[gp])],[Nh]:[,e.headers[yp]]});return await Ke(e.body,t),r},tl=async(e,t)=>{const r={...e,body:await mi(e.body,t)},n=((e,t)=>void 0!==t?.Error?.Code?t.Error.Code:void 0!==t?.Code?t.Code:404==e.statusCode?"NotFound":void 0)(e,r.body);switch(n){case"NoSuchUpload":case"com.amazonaws.s3#NoSuchUpload":throw await hl(r,t);case"ObjectNotInActiveTierError":case"com.amazonaws.s3#ObjectNotInActiveTierError":throw await gl(r,t);case"BucketAlreadyExists":case"com.amazonaws.s3#BucketAlreadyExists":throw await il(r,t);case"BucketAlreadyOwnedByYou":case"com.amazonaws.s3#BucketAlreadyOwnedByYou":throw await ol(r,t);case"NoSuchBucket":case"com.amazonaws.s3#NoSuchBucket":throw await dl(r,t);case"InvalidObjectState":case"com.amazonaws.s3#InvalidObjectState":throw await al(r,t);case"NoSuchKey":case"com.amazonaws.s3#NoSuchKey":throw await ll(r,t);case"NotFound":case"com.amazonaws.s3#NotFound":throw await fl(r,t);case"EncryptionTypeMismatch":case"com.amazonaws.s3#EncryptionTypeMismatch":throw await sl(r,t);case"InvalidRequest":case"com.amazonaws.s3#InvalidRequest":throw await cl(r,t);case"InvalidWriteOffset":case"com.amazonaws.s3#InvalidWriteOffset":throw await ul(r,t);case"TooManyParts":case"com.amazonaws.s3#TooManyParts":throw await ml(r,t);case"ObjectAlreadyInActiveTierError":case"com.amazonaws.s3#ObjectAlreadyInActiveTierError":throw await pl(r,t);default:const i=r.body;return rl({output:e,parsedBody:i,errorCode:n})}},rl=(nl=kd,({output:e,parsedBody:t,errorCode:r})=>{(({output:e,parsedBody:t,exceptionCtor:r,errorCode:n})=>{const i=Or(e),o=i.httpStatusCode?i.httpStatusCode+"":void 0,s=new r({name:t?.code||t?.Code||n||o||"UnknownError",$fault:"client",$metadata:i});throw Rr(s,t)})({output:e,parsedBody:t,exceptionCtor:nl,errorCode:r})});var nl;const il=async(e,t)=>{const r=zr({});e.body;const n=new xd({$metadata:El(e),...r});return Rr(n,e.body)},ol=async(e,t)=>{const r=zr({});e.body;const n=new Ad({$metadata:El(e),...r});return Rr(n,e.body)},sl=async(e,t)=>{const r=zr({});e.body;const n=new Ud({$metadata:El(e),...r});return Rr(n,e.body)},al=async(e,t)=>{const r=zr({}),n=e.body;null!=n[Cl]&&(r[Cl]=Yt(n[Cl])),null!=n[Gh]&&(r[Gh]=Yt(n[Gh]));const i=new Od({$metadata:El(e),...r});return Rr(i,e.body)},cl=async(e,t)=>{const r=zr({});e.body;const n=new Ld({$metadata:El(e),...r});return Rr(n,e.body)},ul=async(e,t)=>{const r=zr({});e.body;const n=new Bd({$metadata:El(e),...r});return Rr(n,e.body)},dl=async(e,t)=>{const r=zr({});e.body;const n=new Td({$metadata:El(e),...r});return Rr(n,e.body)},ll=async(e,t)=>{const r=zr({});e.body;const n=new Pd({$metadata:El(e),...r});return Rr(n,e.body)},hl=async(e,t)=>{const r=zr({});e.body;const n=new Sd({$metadata:El(e),...r});return Rr(n,e.body)},fl=async(e,t)=>{const r=zr({});e.body;const n=new _d({$metadata:El(e),...r});return Rr(n,e.body)},pl=async(e,t)=>{const r=zr({});e.body;const n=new jd({$metadata:El(e),...r});return Rr(n,e.body)},gl=async(e,t)=>{const r=zr({});e.body;const n=new Ed({$metadata:El(e),...r});return Rr(n,e.body)},ml=async(e,t)=>{const r=zr({});e.body;const n=new Dd({$metadata:El(e),...r});return Rr(n,e.body)},yl=(e,t)=>(e||[]).filter((e=>null!=e)).map((e=>(e=>{const t={};return null!=e[Ph]&&(t[Ph]=Yt(e[Ph])),t})(e))),vl=(e,t)=>{const r={};return null!=e[yh]&&(r[yh]=Yt(e[yh])),null!=e[bh]&&(r[bh]=Xt(lr(e[bh]))),null!=e[th]&&(r[th]=Yt(e[th])),""===e.ChecksumAlgorithm?r[_l]=[]:null!=e[_l]&&(r[_l]=(e=>(e||[]).filter((e=>null!=e)).map((e=>Yt(e))))(Ur(e[_l]))),null!=e[nf]&&(r[nf]=rr(e[nf])),null!=e[Gh]&&(r[Gh]=Yt(e[Gh])),null!=e[Ah]&&(r[Ah]=wl(e[Ah])),null!=e[Hh]&&(r[Hh]=kl(e[Hh])),r},bl=(e,t)=>(e||[]).filter((e=>null!=e)).map((e=>vl(e))),wl=(e,t)=>{const r={};return null!=e[Ql]&&(r[Ql]=Yt(e[Ql])),null!=e[ch]&&(r[ch]=Yt(e[ch])),r},kl=(e,t)=>{const r={};return null!=e[ph]&&(r[ph]=zt(e[ph])),null!=e[jh]&&(r[jh]=Xt(lr(e[jh]))),r},Sl=(e,t)=>{const r={};return null!=e[Al]&&(r[Al]=Yt(e[Al])),null!=e[Vh]&&(r[Vh]=Yt(e[Vh])),null!=e[rf]&&(r[rf]=Yt(e[rf])),null!=e[rh]&&(r[rh]=Xt(lr(e[rh]))),r},El=e=>({httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}),xl="ACL",Al="AccessKeyId",Tl="AcceptRanges",Cl="AccessTier",Rl="BypassGovernanceRetention",Ol="BucketKeyEnabled",Pl="Credentials",_l="ChecksumAlgorithm",Ml="CacheControl",Il="ChecksumCRC32",Nl="ChecksumCRC32C",Fl="ContentDisposition",$l="ContentEncoding",Ul="ContentLanguage",Ll="ContentLength",Bl="ChecksumMode",Dl="ContentMD5",jl="CommonPrefixes",zl="ContentRange",ql="ChecksumSHA1",Hl="ChecksumSHA256",Wl="ContentType",Kl="ContinuationToken",Vl="Contents",Gl="Delimiter",Jl="DeleteMarker",Ql="DisplayName",Xl="Expires",Zl="ExpectedBucketOwner",Yl="ExpiresString",eh="EncodingType",th="ETag",rh="Expiration",nh="FetchOwner",ih="GrantFullControl",oh="GrantRead",sh="GrantReadACP",ah="GrantWriteACP",ch="ID",uh="IfMatch",dh="IfMatchLastModifiedTime",lh="IfMatchSize",hh="IfModifiedSince",fh="IfNoneMatch",ph="IsRestoreInProgress",gh="IsTruncated",mh="IfUnmodifiedSince",yh="Key",vh="KeyCount",bh="LastModified",wh="MFA",kh="MaxKeys",Sh="MissingMeta",Eh="Name",xh="NextContinuationToken",Ah="Owner",Th="ObjectLockLegalHoldStatus",Ch="ObjectLockMode",Rh="ObjectLockRetainUntilDate",Oh="OptionalObjectAttributes",Ph="Prefix",_h="PartsCount",Mh="PartNumber",Ih="Range",Nh="RequestCharged",Fh="ResponseCacheControl",$h="ResponseContentDisposition",Uh="ResponseContentEncoding",Lh="ResponseContentLanguage",Bh="ResponseContentType",Dh="ResponseExpires",jh="RestoreExpiryDate",zh="RequestPayer",qh="ReplicationStatus",Hh="RestoreStatus",Wh="Restore",Kh="StartAfter",Vh="SecretAccessKey",Gh="StorageClass",Jh="SessionMode",Qh="ServerSideEncryption",Xh="SSECustomerAlgorithm",Zh="SSECustomerKey",Yh="SSECustomerKeyMD5",ef="SSEKMSEncryptionContext",tf="SSEKMSKeyId",rf="SessionToken",nf="Size",of="Tagging",sf="TagCount",af="VersionId",cf="WriteOffsetBytes",uf="WebsiteRedirectLocation",df="accept-ranges",lf="cache-control",hf="content-disposition",ff="content-encoding",pf="content-language",gf="content-length",mf="content-md5",yf="content-range",vf="content-type",bf="continuation-token",wf="delimiter",kf="expires",Sf="encoding-type",Ef="etag",xf="expiresstring",Af="fetch-owner",Tf="if-match",Cf="if-modified-since",Rf="if-none-match",Of="if-unmodified-since",Pf="last-modified",_f="list-type",Mf="max-keys",If="partNumber",Nf="prefix",Ff="range",$f="response-cache-control",Uf="response-content-disposition",Lf="response-content-encoding",Bf="response-content-language",Df="response-content-type",jf="response-expires",zf="session",qf="start-after",Hf="versionId",Wf="x-amz-acl",Kf="x-amz-bypass-governance-retention",Vf="x-amz-checksum-crc32",Gf="x-amz-checksum-crc32c",Jf="x-amz-checksum-mode",Qf="x-amz-checksum-sha1",Xf="x-amz-checksum-sha256",Zf="x-amz-create-session-mode",Yf="x-amz-delete-marker",ep="x-amz-expiration",tp="x-amz-expected-bucket-owner",rp="x-amz-grant-full-control",np="x-amz-grant-read",ip="x-amz-grant-read-acp",op="x-amz-grant-write-acp",sp="x-amz-if-match-last-modified-time",ap="x-amz-if-match-size",cp="x-amz-mfa",up="x-amz-missing-meta",dp="x-amz-mp-parts-count",lp="x-amz-object-lock-legal-hold",hp="x-amz-object-lock-mode",fp="x-amz-object-lock-retain-until-date",pp="x-amz-optional-object-attributes",gp="x-amz-object-size",mp="x-amz-restore",yp="x-amz-request-charged",vp="x-amz-request-payer",bp="x-amz-replication-status",wp="x-amz-storage-class",kp="x-amz-sdk-checksum-algorithm",Sp="x-amz-server-side-encryption",Ep="x-amz-server-side-encryption-aws-kms-key-id",xp="x-amz-server-side-encryption-bucket-key-enabled",Ap="x-amz-server-side-encryption-context",Tp="x-amz-server-side-encryption-customer-algorithm",Cp="x-amz-server-side-encryption-customer-key",Rp="x-amz-server-side-encryption-customer-key-md5",Op="x-amz-tagging",Pp="x-amz-tagging-count",_p="x-amz-version-id",Mp="x-amz-write-offset-bytes",Ip="x-amz-website-redirect-location",Np="x-id";class Fp extends(Bt.classBuilder().ep({...wd,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(e,t,r,n){return[fe(r,this.serialize,this.deserialize),Ts(r,e.getEndpointParameterInstructions()),xo(r)]})).s("AmazonS3","CreateSession",{}).n("S3Client","CreateSessionCommand").f(Nd,Id).ser(Wd).de(Qd).build()){}var $p="3.701.0";function Up(e){return"string"==typeof e?0===e.length:0===e.byteLength}var Lp={name:"SHA-1"},Bp={name:"HMAC",hash:Lp},Dp=new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]);const jp={};function zp(){return"undefined"!=typeof window?window:"undefined"!=typeof self?self:jp}var qp=function(){function e(e){this.toHash=new Uint8Array(0),void 0!==e&&(this.key=new Promise((function(t,r){zp().crypto.subtle.importKey("raw",Hp(e),Bp,!1,["sign"]).then(t,r)})),this.key.catch((function(){})))}return e.prototype.update=function(e){if(!Up(e)){var t=Hp(e),r=new Uint8Array(this.toHash.byteLength+t.byteLength);r.set(this.toHash,0),r.set(t,this.toHash.byteLength),this.toHash=r}},e.prototype.digest=function(){var e=this;return this.key?this.key.then((function(t){return zp().crypto.subtle.sign(Bp,t,e.toHash).then((function(e){return new Uint8Array(e)}))})):Up(this.toHash)?Promise.resolve(Dp):Promise.resolve().then((function(){return zp().crypto.subtle.digest(Lp,e.toHash)})).then((function(e){return Promise.resolve(new Uint8Array(e))}))},e.prototype.reset=function(){this.toHash=new Uint8Array(0)},e}();function Hp(e){return"string"==typeof e?(t=e,(new TextEncoder).encode(t)):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e);var t}var Wp=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function Kp(e){return!(!function(e){if("object"==typeof e&&"object"==typeof e.crypto){return"function"==typeof e.crypto.getRandomValues}return!1}(e)||"object"!=typeof e.crypto.subtle)&&function(e){return e&&Wp.every((function(t){return"function"==typeof e[t]}))}(e.crypto.subtle)}var Vp=function(){function e(e){if(!Kp(zp()))throw new Error("SHA1 not supported");this.hash=new qp(e)}return e.prototype.update=function(e,t){this.hash.update(xi(e))},e.prototype.digest=function(){return this.hash.digest()},e.prototype.reset=function(){this.hash.reset()},e}(),Gp={name:"SHA-256"},Jp={name:"HMAC",hash:Gp},Qp=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85]),Xp=function(){function e(e){this.toHash=new Uint8Array(0),this.secret=e,this.reset()}return e.prototype.update=function(e){if(!Ai(e)){var t=xi(e),r=new Uint8Array(this.toHash.byteLength+t.byteLength);r.set(this.toHash,0),r.set(t,this.toHash.byteLength),this.toHash=r}},e.prototype.digest=function(){var e=this;return this.key?this.key.then((function(t){return zp().crypto.subtle.sign(Jp,t,e.toHash).then((function(e){return new Uint8Array(e)}))})):Ai(this.toHash)?Promise.resolve(Qp):Promise.resolve().then((function(){return zp().crypto.subtle.digest(Gp,e.toHash)})).then((function(e){return Promise.resolve(new Uint8Array(e))}))},e.prototype.reset=function(){var e=this;this.toHash=new Uint8Array(0),this.secret&&void 0!==this.secret&&(this.key=new Promise((function(t,r){zp().crypto.subtle.importKey("raw",xi(e.secret),Jp,!1,["sign"]).then(t,r)})),this.key.catch((function(){})))},e}();function Zp(e,t,r,n){return new(r||(r=Promise))((function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(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((n=n.apply(e,t||[])).next())}))}function Yp(e,t){var r,n,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]ng)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;r>0;)this.buffer[this.bufferLength++]=e[t++],r--,this.bufferLength===eg&&(this.hashBuffer(),this.bufferLength=0)},e.prototype.digest=function(){if(!this.finished){var e=8*this.bytesHashed,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),r=this.bufferLength;if(t.setUint8(this.bufferLength++,128),r%eg>=56){for(var n=this.bufferLength;n>>24&255,i[4*n+1]=this.state[n]>>>16&255,i[4*n+2]=this.state[n]>>>8&255,i[4*n+3]=this.state[n]>>>0&255;return i},e.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,r=t[0],n=t[1],i=t[2],o=t[3],s=t[4],a=t[5],c=t[6],u=t[7],d=0;d>>17|l<<15)^(l>>>19|l<<13)^l>>>10,f=((l=this.temp[d-15])>>>7|l<<25)^(l>>>18|l<<14)^l>>>3;this.temp[d]=(h+this.temp[d-7]|0)+(f+this.temp[d-16]|0)}var p=(((s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7))+(s&a^~s&c)|0)+(u+(tg[d]+this.temp[d]|0)|0)|0,g=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&n^r&i^n&i)|0;u=c,c=a,a=s,s=o+p|0,o=i,i=n,n=r,r=p+g|0}t[0]+=r,t[1]+=n,t[2]+=i,t[3]+=o,t[4]+=s,t[5]+=a,t[6]+=c,t[7]+=u},e}(),og=function(){function e(e){this.secret=e,this.hash=new ig,this.reset()}return e.prototype.update=function(e){if(!Ai(e)&&!this.error)try{this.hash.update(xi(e))}catch(e){this.error=e}},e.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},e.prototype.digest=function(){return Zp(this,void 0,void 0,(function(){return Yp(this,(function(e){return[2,this.digestSync()]}))}))},e.prototype.reset=function(){if(this.hash=new ig,this.secret){this.outer=new ig;var e=function(e){var t=xi(e);if(t.byteLength>eg){var r=new ig;r.update(t),t=r.digest()}var n=new Uint8Array(eg);return n.set(t),n}(this.secret),t=new Uint8Array(eg);t.set(e);for(var r=0;r0&&r[1]||""},e.getSecondMatch=function(e,t){var r=t.match(e);return r&&r.length>1&&r[2]||""},e.matchAndReturnConst=function(e,t,r){if(e.test(t))return r},e.getWindowsVersionName=function(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e.getMacOSVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}},e.getAndroidVersionName=function(e){var t=e.split(".").splice(0,2).map((function(e){return parseInt(e,10)||0}));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0},e.getVersionPrecision=function(e){return e.split(".").length},e.compareVersions=function(t,r,n){void 0===n&&(n=!1);var i=e.getVersionPrecision(t),o=e.getVersionPrecision(r),s=Math.max(i,o),a=0,c=e.map([t,r],(function(t){var r=s-e.getVersionPrecision(t),n=t+new Array(r+1).join(".0");return e.map(n.split("."),(function(e){return new Array(20-e.length).join("0")+e})).reverse()}));for(n&&(a=s-Math.min(i,o)),s-=1;s>=a;){if(c[0][s]>c[1][s])return 1;if(c[0][s]===c[1][s]){if(s===a)return 0;s-=1}else if(c[0][s]1?i-1:0),s=1;s0){var s=Object.keys(r),c=a.default.find(s,(function(e){return t.isOS(e)}));if(c){var u=this.satisfies(r[c]);if(void 0!==u)return u}var d=a.default.find(s,(function(e){return t.isPlatform(e)}));if(d){var l=this.satisfies(r[d]);if(void 0!==l)return l}}if(o>0){var h=Object.keys(i),f=a.default.find(h,(function(e){return t.isBrowser(e,!0)}));if(void 0!==f)return this.compareVersion(i[f])}},t.isBrowser=function(e,t){void 0===t&&(t=!1);var r=this.getBrowserName().toLowerCase(),n=e.toLowerCase(),i=a.default.getBrowserTypeByAlias(n);return t&&i&&(n=i.toLowerCase()),n===r},t.compareVersion=function(e){var t=[0],r=e,n=!1,i=this.getBrowserVersion();if("string"==typeof i)return">"===e[0]||"<"===e[0]?(r=e.substr(1),"="===e[1]?(n=!0,r=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?r=e.substr(1):"~"===e[0]&&(n=!0,r=e.substr(1)),t.indexOf(a.default.compareVersions(i,r,n))>-1},t.isOS=function(e){return this.getOSName(!0)===String(e).toLowerCase()},t.isPlatform=function(e){return this.getPlatformType(!0)===String(e).toLowerCase()},t.isEngine=function(e){return this.getEngineName(!0)===String(e).toLowerCase()},t.is=function(e,t){return void 0===t&&(t=!1),this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)},t.some=function(e){var t=this;return void 0===e&&(e=[]),e.some((function(e){return t.is(e)}))},e}();t.default=u,e.exports=t.default},92:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},o=/version\/(\d+(\.?_?\d+)+)/i,s=[{test:[/googlebot/i],describe:function(e){var t={name:"Googlebot"},r=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/opera/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opr\/|opios/i],describe:function(e){var t={name:"Opera"},r=i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:"Samsung Internet for Android"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Whale/i],describe:function(e){var t={name:"NAVER Whale Browser"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MZBrowser/i],describe:function(e){var t={name:"MZ Browser"},r=i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/focus/i],describe:function(e){var t={name:"Focus"},r=i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/swing/i],describe:function(e){var t={name:"Swing"},r=i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/coast/i],describe:function(e){var t={name:"Opera Coast"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(e){var t={name:"Opera Touch"},r=i.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/yabrowser/i],describe:function(e){var t={name:"Yandex Browser"},r=i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:"UC Browser"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Maxthon|mxios/i],describe:function(e){var t={name:"Maxthon"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/epiphany/i],describe:function(e){var t={name:"Epiphany"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/puffin/i],describe:function(e){var t={name:"Puffin"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sleipnir/i],describe:function(e){var t={name:"Sleipnir"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/k-meleon/i],describe:function(e){var t={name:"K-Meleon"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/micromessenger/i],describe:function(e){var t={name:"WeChat"},r=i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/qqbrowser/i],describe:function(e){var t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},r=i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/msie|trident/i],describe:function(e){var t={name:"Internet Explorer"},r=i.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/\sedg\//i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/edg([ea]|ios)/i],describe:function(e){var t={name:"Microsoft Edge"},r=i.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/vivaldi/i],describe:function(e){var t={name:"Vivaldi"},r=i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/seamonkey/i],describe:function(e){var t={name:"SeaMonkey"},r=i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sailfish/i],describe:function(e){var t={name:"Sailfish"},r=i.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return r&&(t.version=r),t}},{test:[/silk/i],describe:function(e){var t={name:"Amazon Silk"},r=i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/phantom/i],describe:function(e){var t={name:"PhantomJS"},r=i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/slimerjs/i],describe:function(e){var t={name:"SlimerJS"},r=i.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t={name:"BlackBerry"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t={name:"WebOS Browser"},r=i.default.getFirstMatch(o,e)||i.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/bada/i],describe:function(e){var t={name:"Bada"},r=i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/tizen/i],describe:function(e){var t={name:"Tizen"},r=i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/qupzilla/i],describe:function(e){var t={name:"QupZilla"},r=i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/firefox|iceweasel|fxios/i],describe:function(e){var t={name:"Firefox"},r=i.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/electron/i],describe:function(e){var t={name:"Electron"},r=i.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MiuiBrowser/i],describe:function(e){var t={name:"Miui"},r=i.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/chromium/i],describe:function(e){var t={name:"Chromium"},r=i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/chrome|crios|crmo/i],describe:function(e){var t={name:"Chrome"},r=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/GSA/i],describe:function(e){var t={name:"Google Search"},r=i.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t={name:"Android Browser"},r=i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/playstation 4/i],describe:function(e){var t={name:"PlayStation 4"},r=i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:"Safari"},r=i.default.getFirstMatch(o,e);return r&&(t.version=r),t}},{test:[/.*/i],describe:function(e){var t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:i.default.getFirstMatch(t,e),version:i.default.getSecondMatch(t,e)}}}];t.default=s,e.exports=t.default},93:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},o=r(18),s=[{test:[/Roku\/DVP/],describe:function(e){var t=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:o.OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe:function(e){var t=i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:o.OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe:function(e){var t=i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),r=i.default.getWindowsVersionName(t);return{name:o.OS_MAP.Windows,version:t,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e){var t={name:o.OS_MAP.iOS},r=i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return r&&(t.version=r),t}},{test:[/macintosh/i],describe:function(e){var t=i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),r=i.default.getMacOSVersionName(t),n={name:o.OS_MAP.MacOS,version:t};return r&&(n.versionName=r),n}},{test:[/(ipod|iphone|ipad)/i],describe:function(e){var t=i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:o.OS_MAP.iOS,version:t}}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t=i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),r=i.default.getAndroidVersionName(t),n={name:o.OS_MAP.Android,version:t};return r&&(n.versionName=r),n}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t=i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),r={name:o.OS_MAP.WebOS};return t&&t.length&&(r.version=t),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t=i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||i.default.getFirstMatch(/\bbb(\d+)/i,e);return{name:o.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:o.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:o.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return{name:o.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:o.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:o.OS_MAP.PlayStation4,version:t}}}];t.default=s,e.exports=t.default},94:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},o=r(18),s=[{test:[/googlebot/i],describe:function(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe:function(e){var t=i.default.getFirstMatch(/(can-l01)/i,e)&&"Nova",r={type:o.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(r.model=t),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:o.PLATFORMS_MAP.tablet}}},{test:function(e){var t=e.test(/ipod|iphone/i),r=e.test(/like (ipod|iphone)/i);return t&&!r},describe:function(e){var t=i.default.getFirstMatch(/(ipod|iphone)/i,e);return{type:o.PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:o.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return{type:o.PLATFORMS_MAP.mobile}}},{test:function(e){return"blackberry"===e.getBrowserName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e){return"bada"===e.getBrowserName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.mobile}}},{test:function(e){return"windows phone"===e.getBrowserName()},describe:function(){return{type:o.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e){var t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:function(){return{type:o.PLATFORMS_MAP.tablet}}},{test:function(e){return"android"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.mobile}}},{test:function(e){return"macos"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e){return"windows"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.desktop}}},{test:function(e){return"linux"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.desktop}}},{test:function(e){return"playstation 4"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.tv}}},{test:function(e){return"roku"===e.getOSName(!0)},describe:function(){return{type:o.PLATFORMS_MAP.tv}}}];t.default=s,e.exports=t.default},95:function(e,t,r){t.__esModule=!0,t.default=void 0;var n,i=(n=r(17))&&n.__esModule?n:{default:n},o=r(18),s=[{test:function(e){return"microsoft edge"===e.getBrowserName(!0)},describe:function(e){if(/\sedg\//i.test(e))return{name:o.ENGINE_MAP.Blink};var t=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:o.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:o.ENGINE_MAP.Trident},r=i.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){return e.test(/presto/i)},describe:function(e){var t={name:o.ENGINE_MAP.Presto},r=i.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=e.test(/gecko/i),r=e.test(/like gecko/i);return t&&!r},describe:function(e){var t={name:o.ENGINE_MAP.Gecko},r=i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:o.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:o.ENGINE_MAP.WebKit},r=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}}];t.default=s,e.exports=t.default}});var cg=Gr(ag.exports);const ug=({serviceId:e,clientVersion:t})=>async r=>{const n="undefined"!=typeof window&&window?.navigator?.userAgent?cg.parse(window.navigator.userAgent):void 0,i=[["aws-sdk-js",t],["ua","2.1"],[`os/${n?.os?.name||"other"}`,n?.os?.version],["lang/js"],["md/browser",`${n?.browser?.name??"unknown"}_${n?.browser?.version??"unknown"}`]];e&&i.push([`api/${e}`,t]);const o=await(r?.userAgentAppId?.());return o&&i.push([`app/${o}`]),i};class dg{constructor(e){if(this.bytes=e,8!==e.byteLength)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>0x8000000000000000||e<-0x8000000000000000)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);const t=new Uint8Array(8);for(let r=7,n=Math.abs(Math.round(e));r>-1&&n>0;r--,n/=256)t[r]=n;return e<0&&lg(t),new dg(t)}valueOf(){const e=this.bytes.slice(0),t=128&e[0];return t&&lg(e),parseInt(Le(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function lg(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,0===e[t]);t--);}class hg{constructor(e,t){this.toUtf8=e,this.fromUtf8=t}format(e){const t=[];for(const r of Object.keys(e)){const n=this.fromUtf8(r);t.push(Uint8Array.from([n.byteLength]),n,this.formatHeaderValue(e[r]))}const r=new Uint8Array(t.reduce(((e,t)=>e+t.byteLength),0));let n=0;for(const e of t)r.set(e,n),n+=e.byteLength;return r}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":const t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":const r=new DataView(new ArrayBuffer(5));return r.setUint8(0,4),r.setInt32(1,e.value,!1),new Uint8Array(r.buffer);case"long":const n=new Uint8Array(9);return n[0]=5,n.set(e.value.bytes,1),n;case"binary":const i=new DataView(new ArrayBuffer(3+e.value.byteLength));i.setUint8(0,6),i.setUint16(1,e.value.byteLength,!1);const o=new Uint8Array(i.buffer);return o.set(e.value,3),o;case"string":const s=this.fromUtf8(e.value),a=new DataView(new ArrayBuffer(3+s.byteLength));a.setUint8(0,7),a.setUint16(1,s.byteLength,!1);const c=new Uint8Array(a.buffer);return c.set(s,3),c;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(dg.fromNumber(e.value.valueOf()).bytes,1),u;case"uuid":if(!Eg.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(Ue(e.value.replace(/\-/g,"")),1),d}}parse(e){const t={};let r=0;for(;re,isEndOfStream:()=>t}}getAvailableMessages(){const e=this.messageBuffer;this.messageBuffer=[];const t=this.isEndOfStream;return{getMessages:()=>e,isEndOfStream:()=>t}}encode({headers:e,body:t}){const r=this.headerMarshaller.format(e),n=r.byteLength+t.byteLength+16,i=new Uint8Array(n),o=new DataView(i.buffer,i.byteOffset,i.byteLength),s=new Ni;return o.setUint32(0,n,!1),o.setUint32(4,r.byteLength,!1),o.setUint32(8,s.update(i.subarray(0,8)).digest(),!1),i.set(r,12),i.set(t,r.byteLength+12),o.setUint32(n-4,s.update(i.subarray(8,n-4)).digest(),!1),i}decode(e){const{headers:t,body:r}=function({byteLength:e,byteOffset:t,buffer:r}){if(e<16)throw new Error("Provided message too short to accommodate event stream message overhead");const n=new DataView(r,t,e),i=n.getUint32(0,!1);if(e!==i)throw new Error("Reported message length does not match received message length");const o=n.getUint32(4,!1),s=n.getUint32(8,!1),a=n.getUint32(e-4,!1),c=(new Ni).update(new Uint8Array(r,t,8));if(s!==c.digest())throw new Error(`The prelude checksum specified in the message (${s}) does not match the calculated CRC32 checksum (${c.digest()})`);if(c.update(new Uint8Array(r,t+8,e-12)),a!==c.digest())throw new Error(`The message checksum (${c.digest()}) did not match the expected value of ${a}`);return{headers:new DataView(r,t+8+4,o),body:new Uint8Array(r,t+8+4+o,i-o-16)}}(e);return{headers:this.headerMarshaller.parse(t),body:r}}formatHeaders(e){return this.headerMarshaller.format(e)}}class Ag{constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.inputStream){const t=this.options.decoder.decode(e);yield t}}}class Tg{constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.messageStream){const t=this.options.encoder.encode(e);yield t}this.options.includeEndFrame&&(yield new Uint8Array(0))}}class Cg{constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.messageStream){const t=await this.options.deserializer(e);void 0!==t&&(yield t)}}}class Rg{constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.inputStream){const t=this.options.serializer(e);yield t}}}function Og(e,t){return async function(r){const{value:n}=r.headers[":message-type"];if("error"===n){const e=new Error(r.headers[":error-message"].value||"UnknownError");throw e.name=r.headers[":error-code"].value,e}if("exception"===n){const n=r.headers[":exception-type"].value,i={[n]:r},o=await e(i);if(o.$unknown){const e=new Error(t(r.body));throw e.name=n,e}throw o[n]}if("event"===n){const t={[r.headers[":event-type"].value]:r},n=await e(t);if(n.$unknown)return;return n}throw Error(`Unrecognizable event type: ${r.headers[":event-type"].value}`)}}class Pg{constructor({utf8Encoder:e,utf8Decoder:t}){this.eventStreamCodec=new xg(e,t),this.utfEncoder=e}deserialize(e,t){const r=function(e){let t=0,r=0,n=null,i=null;const o=e=>{if("number"!=typeof e)throw new Error("Attempted to allocate an event message where size was not a number: "+e);t=e,r=4,n=new Uint8Array(e),new DataView(n.buffer).setUint32(0,e,!1)};return{[Symbol.asyncIterator]:async function*(){const s=e[Symbol.asyncIterator]();for(;;){const{value:e,done:a}=await s.next();if(a){if(!t)return;if(t!==r)throw new Error("Truncated event message received.");return void(yield n)}const c=e.length;let u=0;for(;u{const t=e[Symbol.asyncIterator]();return new ReadableStream({async pull(e){const{done:r,value:n}=await t.next();if(r)return e.close();e.enqueue(n)}})})(r):r}}const Mg=e=>"function"==typeof ReadableStream&&e instanceof ReadableStream,Ig=e=>new _g(e);const Ng=async function(e,t){const r=new e;return await async function(e,t,r=1048576){const n=e.size;let i=0;for(;i{r.update(e)})),r.digest()},Fg=64,$g=[1732584193,4023233417,2562383102,271733878];class Ug{constructor(){this.reset()}update(e){if(function(e){if("string"==typeof e)return 0===e.length;return 0===e.byteLength}(e))return;if(this.finished)throw new Error("Attempted to update an already finished hash.");const t=function(e){if("string"==typeof e)return Se(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(e)}(e);let r=0,{byteLength:n}=t;for(this.bytesHashed+=n;n>0;)this.buffer.setUint8(this.bufferLength++,t[r++]),n--,this.bufferLength===Fg&&(this.hashBuffer(),this.bufferLength=0)}async digest(){if(!this.finished){const{buffer:e,bufferLength:t,bytesHashed:r}=this,n=8*r;if(e.setUint8(this.bufferLength++,128),t%Fg>=56){for(let t=this.bufferLength;t>>0,!0),e.setUint32(60,Math.floor(n/4294967296),!0),this.hashBuffer(),this.finished=!0}const e=new DataView(new ArrayBuffer(16));for(let t=0;t<4;t++)e.setUint32(4*t,this.state[t],!0);return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}hashBuffer(){const{buffer:e,state:t}=this;let r=t[0],n=t[1],i=t[2],o=t[3];r=Bg(r,n,i,o,e.getUint32(0,!0),7,3614090360),o=Bg(o,r,n,i,e.getUint32(4,!0),12,3905402710),i=Bg(i,o,r,n,e.getUint32(8,!0),17,606105819),n=Bg(n,i,o,r,e.getUint32(12,!0),22,3250441966),r=Bg(r,n,i,o,e.getUint32(16,!0),7,4118548399),o=Bg(o,r,n,i,e.getUint32(20,!0),12,1200080426),i=Bg(i,o,r,n,e.getUint32(24,!0),17,2821735955),n=Bg(n,i,o,r,e.getUint32(28,!0),22,4249261313),r=Bg(r,n,i,o,e.getUint32(32,!0),7,1770035416),o=Bg(o,r,n,i,e.getUint32(36,!0),12,2336552879),i=Bg(i,o,r,n,e.getUint32(40,!0),17,4294925233),n=Bg(n,i,o,r,e.getUint32(44,!0),22,2304563134),r=Bg(r,n,i,o,e.getUint32(48,!0),7,1804603682),o=Bg(o,r,n,i,e.getUint32(52,!0),12,4254626195),i=Bg(i,o,r,n,e.getUint32(56,!0),17,2792965006),n=Bg(n,i,o,r,e.getUint32(60,!0),22,1236535329),r=Dg(r,n,i,o,e.getUint32(4,!0),5,4129170786),o=Dg(o,r,n,i,e.getUint32(24,!0),9,3225465664),i=Dg(i,o,r,n,e.getUint32(44,!0),14,643717713),n=Dg(n,i,o,r,e.getUint32(0,!0),20,3921069994),r=Dg(r,n,i,o,e.getUint32(20,!0),5,3593408605),o=Dg(o,r,n,i,e.getUint32(40,!0),9,38016083),i=Dg(i,o,r,n,e.getUint32(60,!0),14,3634488961),n=Dg(n,i,o,r,e.getUint32(16,!0),20,3889429448),r=Dg(r,n,i,o,e.getUint32(36,!0),5,568446438),o=Dg(o,r,n,i,e.getUint32(56,!0),9,3275163606),i=Dg(i,o,r,n,e.getUint32(12,!0),14,4107603335),n=Dg(n,i,o,r,e.getUint32(32,!0),20,1163531501),r=Dg(r,n,i,o,e.getUint32(52,!0),5,2850285829),o=Dg(o,r,n,i,e.getUint32(8,!0),9,4243563512),i=Dg(i,o,r,n,e.getUint32(28,!0),14,1735328473),n=Dg(n,i,o,r,e.getUint32(48,!0),20,2368359562),r=jg(r,n,i,o,e.getUint32(20,!0),4,4294588738),o=jg(o,r,n,i,e.getUint32(32,!0),11,2272392833),i=jg(i,o,r,n,e.getUint32(44,!0),16,1839030562),n=jg(n,i,o,r,e.getUint32(56,!0),23,4259657740),r=jg(r,n,i,o,e.getUint32(4,!0),4,2763975236),o=jg(o,r,n,i,e.getUint32(16,!0),11,1272893353),i=jg(i,o,r,n,e.getUint32(28,!0),16,4139469664),n=jg(n,i,o,r,e.getUint32(40,!0),23,3200236656),r=jg(r,n,i,o,e.getUint32(52,!0),4,681279174),o=jg(o,r,n,i,e.getUint32(0,!0),11,3936430074),i=jg(i,o,r,n,e.getUint32(12,!0),16,3572445317),n=jg(n,i,o,r,e.getUint32(24,!0),23,76029189),r=jg(r,n,i,o,e.getUint32(36,!0),4,3654602809),o=jg(o,r,n,i,e.getUint32(48,!0),11,3873151461),i=jg(i,o,r,n,e.getUint32(60,!0),16,530742520),n=jg(n,i,o,r,e.getUint32(8,!0),23,3299628645),r=zg(r,n,i,o,e.getUint32(0,!0),6,4096336452),o=zg(o,r,n,i,e.getUint32(28,!0),10,1126891415),i=zg(i,o,r,n,e.getUint32(56,!0),15,2878612391),n=zg(n,i,o,r,e.getUint32(20,!0),21,4237533241),r=zg(r,n,i,o,e.getUint32(48,!0),6,1700485571),o=zg(o,r,n,i,e.getUint32(12,!0),10,2399980690),i=zg(i,o,r,n,e.getUint32(40,!0),15,4293915773),n=zg(n,i,o,r,e.getUint32(4,!0),21,2240044497),r=zg(r,n,i,o,e.getUint32(32,!0),6,1873313359),o=zg(o,r,n,i,e.getUint32(60,!0),10,4264355552),i=zg(i,o,r,n,e.getUint32(24,!0),15,2734768916),n=zg(n,i,o,r,e.getUint32(52,!0),21,1309151649),r=zg(r,n,i,o,e.getUint32(16,!0),6,4149444226),o=zg(o,r,n,i,e.getUint32(44,!0),10,3174756917),i=zg(i,o,r,n,e.getUint32(8,!0),15,718787259),n=zg(n,i,o,r,e.getUint32(36,!0),21,3951481745),t[0]=r+t[0]&4294967295,t[1]=n+t[1]&4294967295,t[2]=i+t[2]&4294967295,t[3]=o+t[3]&4294967295}reset(){this.state=Uint32Array.from($g),this.buffer=new DataView(new ArrayBuffer(Fg)),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}}function Lg(e,t,r,n,i,o){return((t=(t+e&4294967295)+(n+o&4294967295)&4294967295)<>>32-i)+r&4294967295}function Bg(e,t,r,n,i,o,s){return Lg(t&r|~t&n,e,t,i,o,s)}function Dg(e,t,r,n,i,o,s){return Lg(t&n|r&~n,e,t,i,o,s)}function jg(e,t,r,n,i,o,s){return Lg(t^r^n,e,t,i,o,s)}function zg(e,t,r,n,i,o,s){return Lg(r^(t|~n),e,t,i,o,s)}const qg="function"==typeof TextEncoder?new TextEncoder:null,Hg=e=>{if("string"==typeof e){if(qg)return qg.encode(e).byteLength;let t=e.length;for(let r=t-1;r>=0;r--){const n=e.charCodeAt(r);n>127&&n<=2047?t++:n>2047&&n<=65535&&(t+=2),n>=56320&&n<=57343&&r--}return t}if("number"==typeof e.byteLength)return e.byteLength;if("number"==typeof e.size)return e.size;throw new Error(`Body Length computation failed for ${e}`)},Wg=["in-region","cross-region","mobile","standard","legacy"],Kg=()=>{const e="undefined"!=typeof window&&window?.navigator?.userAgent?cg.parse(window.navigator.userAgent):void 0,t=e?.platform?.type;return"tablet"===t||"mobile"===t},Vg=e=>{const t=(({defaultsMode:e}={})=>((e,t,r)=>{let n,i,o,s=!1;const a=async()=>{i||(i=e());try{n=await i,o=!0,s=!1}finally{i=void 0}return n};return void 0===t?async e=>(o&&!e?.forceRefresh||(n=await a()),n):async e=>(o&&!e?.forceRefresh||(n=await a()),s?n:r&&!r(n)?(s=!0,n):t(n)?(await a(),n):n)})((async()=>{const t="function"==typeof e?await e():e;switch(t?.toLowerCase()){case"auto":return Promise.resolve(Kg()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(t?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${Wg.join(", ")}, got ${t}`)}})))(e),r=()=>t().then(Pr),n=(e=>({apiVersion:"2006-03-01",base64Decoder:e?.base64Decoder??ke,base64Encoder:e?.base64Encoder??Ae,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??fd,extensions:e?.extensions??[],getAwsChunkedEncodingStream:e?.getAwsChunkedEncodingStream??Ce,httpAuthSchemeProvider:e?.httpAuthSchemeProvider??vd,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new oe},{schemeId:"aws.auth#sigv4a",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4a"),signer:new se}],logger:e?.logger??new jr,sdkStreamMixin:e?.sdkStreamMixin??je,serviceId:e?.serviceId??"S3",signerConstructor:e?.signerConstructor??Ys,signingEscapePath:e?.signingEscapePath??!1,urlParser:e?.urlParser??ks,useArnRegion:e?.useArnRegion??!1,utf8Decoder:e?.utf8Decoder??Se,utf8Encoder:e?.utf8Encoder??xe}))(e);return{...n,...e,runtime:"browser",defaultsMode:t,bodyLengthChecker:e?.bodyLengthChecker??Hg,credentialDefaultProvider:e?.credentialDefaultProvider??(e=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:e?.defaultUserAgentProvider??ug({serviceId:n.serviceId,clientVersion:$p}),eventStreamSerdeProvider:e?.eventStreamSerdeProvider??Ig,maxAttempts:e?.maxAttempts??3,md5:e?.md5??Ug,region:e?.region??(i="Region is missing",()=>Promise.reject(i)),requestHandler:Ie.create(e?.requestHandler??r),retryMode:e?.retryMode??(async()=>(await r()).retryMode||Rs),sha1:e?.sha1??Vp,sha256:e?.sha256??sg,streamCollector:e?.streamCollector??Ne,streamHasher:e?.streamHasher??Ng,useDualstackEndpoint:e?.useDualstackEndpoint??(()=>Promise.resolve(false)),useFipsEndpoint:e?.useFipsEndpoint??(()=>Promise.resolve(false))};var i},Gg=e=>{let t=async()=>{if(void 0===e.region)throw new Error("Region is missing from runtimeConfig");const t=e.region;return"string"==typeof t?t:t()};return{setRegion(e){t=e},region:()=>t}},Jg=e=>{const t=e.httpAuthSchemes;let r=e.httpAuthSchemeProvider,n=e.credentials;return{setHttpAuthScheme(e){const r=t.findIndex((t=>t.schemeId===e.schemeId));-1===r?t.push(e):t.splice(r,1,e)},httpAuthSchemes:()=>t,setHttpAuthSchemeProvider(e){r=e},httpAuthSchemeProvider:()=>r,setCredentials(e){n=e},credentials:()=>n}},Qg=e=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()});class Xg extends Lt{constructor(...[e]){const t=Vg(e||{});var r;const n=function(e){const t=ve(e.userAgentAppId??void 0);return{...e,customUserAgent:"string"==typeof e.customUserAgent?[[e.customUserAgent]]:e.customUserAgent,userAgentAppId:async()=>{const r=await t();if(!function(e){return void 0===e||"string"==typeof e&&e.length<=50}(r)){const t="NoOpLogger"!==e.logger?.constructor?.name&&e.logger?e.logger:console;"string"!=typeof r?t?.warn("userAgentAppId must be a string or undefined."):r.length>50&&t?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return r}}}((r=t,{...r,useFipsEndpoint:r.useFipsEndpoint??!1,useDualstackEndpoint:r.useDualstackEndpoint??!1,forcePathStyle:r.forcePathStyle??!1,useAccelerateEndpoint:r.useAccelerateEndpoint??!1,useGlobalEndpoint:r.useGlobalEndpoint??!1,disableMultiregionAccessPoints:r.disableMultiregionAccessPoints??!1,defaultSigningName:"s3"}));var i;const o=(e=>({...e,eventStreamMarshaller:e.eventStreamSerdeProvider(e)}))((e=>{const t=e.tls??!0,{endpoint:r}=e,n=null!=r?async()=>Ss(await ce(r)()):void 0,i=!!r,o={...e,endpoint:n,tls:t,isCustomEndpoint:i,useDualstackEndpoint:ce(e.useDualstackEndpoint??!1),useFipsEndpoint:ce(e.useFipsEndpoint??!1)};let s;return o.serviceConfiguredEndpoint=async()=>(e.serviceId&&!s&&(s=ws(e.serviceId)),s),o})((e=>{const{region:t,useFipsEndpoint:r}=e;if(!t)throw new Error("Region is missing");return{...e,region:async()=>{if("string"==typeof t)return ds(t);const e=await t();return ds(e)},useFipsEndpoint:async()=>{const e="string"==typeof t?t:await t();return!!us(e)||("function"!=typeof r?Promise.resolve(!!r):r())}}})((e=>{const{retryStrategy:t}=e,r=ce(e.maxAttempts??3);return{...e,maxAttempts:r,retryStrategy:async()=>t||(await ce(e.retryMode)()===Cs.ADAPTIVE?new Ls(r):new Us(r))}})((i=n,{...i,requestChecksumCalculation:ce(i.requestChecksumCalculation??K),responseChecksumValidation:ce(i.responseChecksumValidation??V)}))))),s=((e,{session:t})=>{const[r,n]=t;return{...e,forcePathStyle:e.forcePathStyle??!1,useAccelerateEndpoint:e.useAccelerateEndpoint??!1,disableMultiregionAccessPoints:e.disableMultiregionAccessPoints??!1,followRegionRedirects:e.followRegionRedirects??!1,s3ExpressIdentityProvider:e.s3ExpressIdentityProvider??new ao((async e=>r().send(new n({Bucket:e,SessionMode:"ReadWrite"})))),bucketEndpoint:e.bucketEndpoint??!1}})(bd(o),{session:[()=>this,Fp]}),a=((e,t)=>{const r={...Gg(e),...Fr(e),...M(e),...Jg(e)};return t.forEach((e=>e.configure(r))),{...e,...(i=r,{region:i.region()}),...$r(r),...(n=r,{httpHandler:n.httpHandler()}),...Qg(r)};var n,i})(s,e?.extensions||[]);super(a),this.config=a,this.middlewareStack.use((e=>({applyToStack:t=>{t.add(ss(e),cs)}}))(this.config)),this.middlewareStack.use(Qs(this.config)),this.middlewareStack.use(fs(this.config)),this.middlewareStack.use(Vi(this.config)),this.middlewareStack.use((this.config,{applyToStack:e=>{e.add(((e,t)=>async r=>{try{const n=await e(r),{clientName:i,commandName:o,logger:s,dynamoDbDocumentClientOptions:a={}}=t,{overrideInputFilterSensitiveLog:c,overrideOutputFilterSensitiveLog:u}=a,d=c??t.inputFilterSensitiveLog,l=u??t.outputFilterSensitiveLog,{$metadata:h,...f}=n.output;return s?.info?.({clientName:i,commandName:o,input:d(r.input),output:l(f),metadata:h}),n}catch(e){const{clientName:n,commandName:i,logger:o,dynamoDbDocumentClientOptions:s={}}=t,{overrideInputFilterSensitiveLog:a}=s,c=a??t.inputFilterSensitiveLog;throw o?.error?.({clientName:n,commandName:i,input:c(r.input),error:e,metadata:e.$metadata}),e}}),Gi)}})),this.middlewareStack.use(Xi(this.config)),this.middlewareStack.use(((e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(ue(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r}),de)}}))(this.config,{httpAuthSchemeParametersProvider:pd,identityProviderConfigProvider:async e=>new Qe({"aws.auth#sigv4":e.credentials,"aws.auth#sigv4a":e.credentials})})),this.middlewareStack.use(ye(this.config)),this.middlewareStack.use(Co(this.config)),this.middlewareStack.use(H(this.config)),this.middlewareStack.use(ro(this.config)),this.middlewareStack.use(mo(this.config)),this.middlewareStack.use((e=>({applyToStack:t=>{t.addRelativeTo(bo(e),me)}}))(this.config))}destroy(){super.destroy()}}const Zg={name:"ssecMiddleware",step:"initialize",tags:["SSE"],override:!0},Yg=e=>({applyToStack:t=>{var r;t.add((r=e,e=>async t=>{const n={...t.input},i=[{target:"SSECustomerKey",hash:"SSECustomerKeyMD5"},{target:"CopySourceSSECustomerKey",hash:"CopySourceSSECustomerKeyMD5"}];for(const e of i){const t=n[e.target];if(t){let i;"string"==typeof t?em(t,r)?i=r.base64Decoder(t):(i=r.utf8Decoder(t),n[e.target]=r.base64Encoder(i)):(i=ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),n[e.target]=r.base64Encoder(i));const o=new r.md5;o.update(i),n[e.hash]=r.base64Encoder(await o.digest())}}return e({...t,input:n})}),Zg)}});function em(e,t){if(!/^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return!1;try{return 32===t.base64Decoder(e).length}catch{return!1}}class tm extends(Bt.classBuilder().ep({...wd,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[fe(r,this.serialize,this.deserialize),Ts(r,e.getEndpointParameterInstructions()),xo(r)]})).s("AmazonS3","DeleteObject",{}).n("S3Client","DeleteObjectCommand").f(void 0,void 0).ser(Kd).de(Xd).build()){}class rm extends(Bt.classBuilder().ep({...wd,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[fe(r,this.serialize,this.deserialize),Ts(r,e.getEndpointParameterInstructions()),Wi(r,{requestChecksumRequired:!1,requestValidationModeMember:"ChecksumMode",responseAlgorithms:["CRC32","CRC32C","SHA256","SHA1"]}),Yg(r),io()]})).s("AmazonS3","GetObject",{}).n("S3Client","GetObjectCommand").f($d,Fd).ser(Vd).de(Zd).build()){}class nm extends(Bt.classBuilder().ep({...wd,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m((function(e,t,r,n){return[fe(r,this.serialize,this.deserialize),Ts(r,e.getEndpointParameterInstructions()),xo(r)]})).s("AmazonS3","ListObjectsV2",{}).n("S3Client","ListObjectsV2Command").f(void 0,void 0).ser(Gd).de(Yd).build()){}class im extends(Bt.classBuilder().ep({...wd,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(e,t,r,n){return[fe(r,this.serialize,this.deserialize),Ts(r,e.getEndpointParameterInstructions()),Wi(r,{requestAlgorithmMember:"ChecksumAlgorithm",requestAlgorithmMemberHttpHeader:"x-amz-sdk-checksum-algorithm",requestChecksumRequired:!1}),Yi(),xo(r),Yg(r)]})).s("AmazonS3","PutObject",{}).n("S3Client","PutObjectCommand").f(Hd,qd).ser(Jd).de(el).build()){}class om{constructor(e){this.config=e,this.taskQueue=new h(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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:n,accessKeyId:i,secretAccessKey:o,dir:s}=this.config;s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder;let a=s+"/"+e;for(;a.startsWith("/");)a=a.substring(1);const c=new Xg({endpoint:t,region:r,credentials:{accessKeyId:i,secretAccessKey:o}});try{let e,t=[],r=!0;for(;r;){const i=yield c.send(new nm({Bucket:n,Prefix:a,ContinuationToken:e}));i.Contents&&(t=t.concat(i.Contents)),e=i.NextContinuationToken,r=!!e}if(0===t.length)return[];const i=new Set;""===a||a.endsWith("/")||(a+="/");let o=t.map((e=>e.Key));for(const e of o){const t=e.substring(a.length).split("/")[0];i.add(t)}return Array.from(i)}catch(e){return console.error(e),[]}}))}deleteFile(e){return s(this,void 0,void 0,(function*(){let{endpoint:t,region:r,bucketName:n,accessKeyId:i,secretAccessKey:o,dir:s}=this.config;s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder;const a=new Xg({endpoint:t,region:r,credentials:{accessKeyId:i,secretAccessKey:o}});let c=s+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{return yield a.send(new tm({Bucket:n,Key:c})),!0}catch(e){return console.error(e),!1}}))}}class sm extends om{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*(){let{endpoint:r,region:n,bucketName:i,accessKeyId:o,secretAccessKey:s,dir:a}=this.config;const c=new Xg({endpoint:r,region:n,credentials:{accessKeyId:o,secretAccessKey:s}});a=a&&"KoodoReader"===this.baseFolder?a:this.baseFolder;let u=a+"/"+t;for(;u.startsWith("/");)u=u.substring(1);try{let t=yield c.send(new im({Bucket:i,Key:u,Body:e}));return 200===t.$metadata.httpStatusCode||(console.error("Error uploading file:",t),!1)}catch(e){return console.error("Error: ",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*(){let{endpoint:t,region:r,bucketName:n,accessKeyId:i,secretAccessKey:o,dir:s}=this.config;s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder;const a=new Xg({endpoint:t,region:r,credentials:{accessKeyId:i,secretAccessKey:o}});let c=s+"/"+e;for(;c.startsWith("/");)c=c.substring(1);try{const e=yield a.send(new rm({Bucket:n,Key:c}));if(!e.Body)return console.error("No response body"),!1;return(yield e.Body.transformToByteArray()).buffer}catch(t){return console.error("Error downloading file:",t,e),!1}}))))))}))}}class am{constructor(e){let{username:t,password:r,url:o,dir:s}=e;void 0===e.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=e.baseFolder,s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder,this.client=n(o,{authType:i.Password,username:t,password:r}),this.username=t,this.password=r,this.dir=s,this.taskQueue=new h(5)}retryOperation(e,t=0){return s(this,void 0,void 0,(function*(){let r=0;for(;;){const n=yield e();if(n)return n;if(r>=t)return n;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{yield this.listFiles(r.substring(0,r.lastIndexOf("/")));let n=r.split("/").pop()||"",i=new File([t],n,{lastModified:(new Date).getTime(),type:t.type}),o=this.client.getFileUploadLink(this.dir+"/"+r);const s=new URL(o);s.search="",o=s.toString();const a=btoa(this.username+":"+this.password),c=yield e.put(o,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),n=btoa(this.username+":"+this.password),i=yield e({url:r,method:"get",headers:{Authorization:"Basic "+n},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 cm=["book","config","cover","font"];class um{constructor(e,t,r){this.type=e,this.remote="dropbox"===e?new S(t,r):"microsoft"===e?new R(t,r):"google"===e?new x(t,r):"s3compatible"===e?new sm(t):"webdav"===e?new am(t):"boxnet"===e?new w(t,r):"mega"===e?new T(t):"adrive"===e?new v(t,r):"pcloud"===e?new _(t,r):new O}downloadFile(e,t){return s(this,void 0,void 0,(function*(){if("cover"!==t){if(!(yield this.listFiles(t)).find((t=>e.indexOf(t)>-1)))return!1}return 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.listFiles(t)).find((t=>e.indexOf(t)>-1))||(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 cm){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 dm={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 = ?"},lm={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},hm={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function fm(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const pm={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 gm,mm={sqlStatement:{createTableStatement:fm({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:fm({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:fm({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:fm({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:fm({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:fm({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:fm({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:fm(dm),getByBookKeyStatement:fm(lm),getByBookKeysStatement:fm({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:fm(hm)},jsonToSqlite:fm({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:fm(pm)};class ym{constructor(e,t,r,n,i,o,s,a,c,u,d,l){this.key=e,this.name=t,this.author=r,this.description=n,this.md5=i,this.cover=o,this.format=s,this.publisher=a,this.size=c,this.page=u,this.path=d,this.charset=l}}class vm{static generateBook(e,t,r,n,i,o,a){return new Promise(((c,u)=>s(this,void 0,void 0,(function*(){try{let s,u,d,l,h,f,p,g,m="";switch([u,d,h,l,f,p]=[e,"","","","",0],t){case"pdf":case"epub":case"mobi":case"azw":case"azw3":case"fb2":g=yield a.getMetadata(),[u,d,h,l,m]=[g.name||e,g.author||"",g.description||"",g.publisher||"",g.cover||""];break;case"cbr":case"cbt":case"cbz":case"cb7":g=yield a.getMetadata(),m=g.cover;break;case"txt":g=yield a.getMetadata(o),f=g.charset}let y=t.toUpperCase();s=(new Date).getTime()+"",c(new ym(s,u,d,h,r,m,y,l,n,p,i,f))}catch(e){console.error(e),u(e)}}))))}}gm=vm,vm.getRendtion=(e,t,r,n,i,o,s,a,c,u)=>{let d;var l,h;return"CACHE"===t?d=new u.CacheRender(e,{readerMode:r,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"MOBI"===t||"AZW3"===t||"AZW"===t?d=new u.MobiRender(e,{readerMode:r,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"EPUB"===t?d=new u.EpubRender(e,{readerMode:r,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"TXT"===t?d=new u.TxtRender(e,{readerMode:r,animation:i,charset:n,convertChinese:o,parserRegex:s,isDarkMode:a,isMobile:c}):"MD"===t?d=new u.MdRender(e,{readerMode:r,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"PDF"===t?d=new u.PdfRender(e,{readerMode:r,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"FB2"===t?d=new u.Fb2Render(e,{readerMode:r,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"DOCX"===t?d=new u.DocxRender(e,{readerMode:r,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"HTML"===t||"XHTML"===t||"MHTML"===t||"HTM"===t||"XML"===t?d=new u.HtmlRender(e,{readerMode:r,format:t,animation:i,convertChinese:o,isDarkMode:a,isMobile:c}):"CBR"!==t&&"CBT"!==t&&"CBZ"!==t&&"CB7"!==t||(d=new u.ComicRender((l=e,h=new ArrayBuffer(l.byteLength),new Uint8Array(h).set(new Uint8Array(l)),h),{readerMode:r,format:t,animation:i,convertChinese:o,isDarkMode:a,isMobile:c})),d},vm.initMobileBook=(e,t,r,n,i,o,a,c,u)=>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 d=yield s.arrayBuffer();window.ReactNativeWebView.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=d;let l=gm.getRendtion(d,t,r,n,i,o,a,u,"yes",window.Kookit);window.rendition=l;let h=document.getElementById("page-area");t&&"TXT"===t.toUpperCase()?yield window.rendition.renderTo(h,c):yield window.rendition.renderTo(h),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"}))}})),vm.addMobileBook=(e,t,r,n,i,o,a="")=>s(void 0,void 0,void 0,(function*(){var s;try{if("PDF"===r.toUpperCase()&&i>314572800){t=t.replace(/\.[^/.]+$/,"");let e=r.toUpperCase(),s=(new Date).getTime()+"",a=new ym(s,t,"","",n,"",e,"",i,0,o,"");return void window.ReactNativeWebView.postMessage(JSON.stringify({event:"metadata",bookInfo:a}))}const c=yield fetch(e);if(!c.ok)throw new Error(`Failed to download book: ${c.status} ${c.statusText}`);const u=yield c.arrayBuffer();null===(s=window.ReactNativeWebView)||void 0===s||s.postMessage(JSON.stringify({event:"finish-download"})),window.file_content=u;let d=gm.getRendtion(u,r.toUpperCase(),"","","","no",a,"no","yes",window.Kookit);window.rendition=d,t=t.replace(/\.[^/.]+$/,"");let l=yield vm.generateBook(t,r,n,i,o,u,d);if(!l||!l.key)return;window.ReactNativeWebView.postMessage(JSON.stringify({event:"metadata",bookInfo:l}))}catch(e){window.ReactNativeWebView.postMessage(JSON.stringify({event:"error",message:"Parse book failed"}))}})),vm.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 n=`${e}/dav/${"cache-"+t+".zip"}`,i=yield fetch(n,{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 bm=p.cloudUrl;class wm{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(bm+"/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=bm,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 n=(yield e(t)).data;if(402===n.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!==n.code&&this.ConfigService.setItem("errorLog",JSON.stringify({request:t.data,url:t.url,result:n,requestID:r})),n}catch(e){return console.error("Request execution error:",e),{code:503,message:"network error",data:null}}}))}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 n="";try{n=(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,a)=>{const c=new r(bm+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+n,"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(),o(r)):(402===r.code&&(yield this.refreshUserToken()),t(r.data))})))),c.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);o(t),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 n="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((i,o)=>s(this,void 0,void 0,(function*(){const o=yield fetch(bm+e.url,{method:"POST",headers:{"Content-Type":"text/event-stream",Authorization:"Bearer "+r,"X-Request-ID":n},body:JSON.stringify(e.data)});if(!o.body)throw new Error("Response body is null");const s=o.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)}}))}i({code:200,data:{done:!0}})}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}class km extends wm{constructor(e,t){super(e,t)}getTransStream(e,t,r){return s(this,void 0,void 0,(function*(){const n={method:"post",url:"/api/v1/pro/reader/get_llm_trans_stream",data:e};return yield this.requestWithStream(n,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 n={method:"post",url:"/api/v1/pro/reader/get_llm_sum_stream",data:e};return yield this.requestWithStream(n,t,r)}))}getAnswerStream(e,t,r){return s(this,void 0,void 0,(function*(){const n={method:"post",url:"/api/v1/pro/reader/get_llm_answer_stream",data:e};return yield this.requestWithStream(n,t,r)}))}getAnswerFetch(e,t){return s(this,void 0,void 0,(function*(){const r={method:"post",url:"/api/v1/pro/reader/get_llm_answer_stream",data:e};return yield this.requestWithFetch(r,t)}))}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 Sm extends wm{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)}))}getSyncData(){return s(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/pro/thirdparty/get_sync_data"})}))}updateSyncData(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/update_sync_data",data:e};return yield this.requestWithRetry(t)}))}}class Em extends wm{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"})}))}updateUserConfig(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/update_config",data:e};return yield this.requestWithRetry(t)}))}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)}))}deleteAccount(e){return s(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/member/user/delete_account",data:e};return yield this.requestWithRetry(t)}))}}var xm={getAuthUrl:(e,t)=>{let r="";if("github"===e?r=`https://github.com/login/oauth/authorize?client_id=${g.githubClientId}&redirect_uri=${g.callbackUrl}&scope=openid`:"google"===e?r=`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${g.callbackUrl}&prompt=consent&response_type=code&client_id=${g.googleClientId}&scope=openid&access_type=offline`:"facebook"===e?r=`https://www.facebook.com/v12.0/dialog/oauth?client_id=${g.facebookClientId}&redirect_uri=${g.callbackUrl}&scope=&response_type=code`:"microsoft"===e&&(r=`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=${g.microsoftClientId}&scope=openid profile User.Read offline_access&response_type=code&redirect_uri=${g.callbackUrl}`),"manual"===t)return r;let n=JSON.stringify({deeplink:"desktop"===t?"koodo-reader://callback":"browser"===t?"https://web.koodoreader.com/#/login":"",service:e});return`${r}&state=${"state|"+encodeURIComponent(n)}`}};class Am{static CompareDatabase(e,t,r){return s(this,void 0,void 0,(function*(){let n=Object.keys(e).filter((e=>e.startsWith("database.sqlite.books"))),i=Object.keys(e).filter((e=>e.startsWith("database.sqlite.notes"))),o=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"))),u=Object.keys(t).filter((e=>e.startsWith("database.sqlite.notes"))),d=Object.keys(t).filter((e=>e.startsWith("database.sqlite.bookmarks"))),l=Object.keys(t).filter((e=>e.startsWith("database.sqlite.plugins"))),h=Object.keys(t).filter((e=>e.startsWith("database.sqlite.words"))),f={books:Array.from(new Set(n.concat(c))),notes:Array.from(new Set(i.concat(u))),bookmarks:Array.from(new Set(o.concat(d))),plugins:Array.from(new Set(s.concat(l))),words:Array.from(new Set(a.concat(h)))},p={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:[]}},g=["books","notes","bookmarks","plugins","words"];for(let n of g)for(let i of f[n]){let o=i.split(".")[3],s=e[i],a=t[i];s?a?("save"===a.operation&&("update"===s.operation||"delete"===s.operation?p[n].upload.push(o):console.info("ignore",a)),"delete"===a.operation&&("save"===s.operation&&(p[n].delete.push(o),e[i]=a),"update"===s.operation&&(s.timea.time?(p[n].conflict.push(o),"cloud"===r?(p[n].delete.push(o),e[i]=a):p[n].upload.push(o)):console.info("ignore",a)),"delete"===s.operation&&console.info("ignore",a)),"update"===a.operation&&("save"===s.operation&&(p[n].update.push(o),e[i]=a),"update"===s.operation&&(s.timea.time?p[n].upload.push(o):console.info("ignore",a)),"delete"===s.operation&&(s.timea.time?p[n].upload.push(o):console.info("ignore",a)))):p[n].upload.push(o):(p[n].save.push(o),e[i]=a)}return{compareResult:p,syncRecords:e}}))}static CompareConfig(e,t,r){return s(this,void 0,void 0,(function*(){let n=Object.keys(e).filter((e=>e.startsWith("config.readerConfig"))),i=Object.keys(e).filter((e=>e.startsWith("config.listConfig"))),o=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"))),u=Object.keys(t).filter((e=>e.startsWith("config.objectConfig"))),d=Object.keys(t).filter((e=>e.startsWith("config.mapConfig"))),l={readerConfig:Array.from(new Set(n.concat(a))),listConfig:Array.from(new Set(i.concat(c))),objectConfig:Array.from(new Set(o.concat(u))),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:[]}},f=["readerConfig","listConfig"];for(let r of f)for(let n of l[r]){let i=n,o=e[n],s=t[n];o?s?o.times.time?h[r].upload.push(i):console.info("ignore",s):h[r].upload.push(i):(h[r].update.push(i),e[n]=s)}let p=["objectConfig","mapConfig"];for(let n of p)for(let i of l[n]){let o=i,s=e[i],a=t[i];s?a?("delete"===a.operation&&("update"===s.operation&&(s.timea.time?(h[n].conflict.push(o),"cloud"===r?(h[n].delete.push(o),e[i]=a):h[n].upload.push(o)):console.info("ignore",a)),"delete"===s.operation&&console.info("ignore",a)),"update"===a.operation&&("update"===s.operation&&(s.timea.time?h[n].upload.push(o):console.info("ignore",a)),"delete"===s.operation&&(s.timea.time?h[n].upload.push(o):console.info("ignore",a)))):h[n].upload.push(o):(h[n].update.push(o),e[i]=a)}return{compareResult:h,syncRecords:e}}))}static compareAll(e,t,r,n,i){return s(this,void 0,void 0,(function*(){let o="cloud";if("yes"===r.getReaderConfig("isKeepLocal")){o="local";let e=r.getObjectConfig(yield n.getFingerprint(),"cloudSyncTime",{time:0,conflictMode:"cloud"}),t=yield i.getCloudConfig("config"),s=JSON.parse(t.cloudSyncTime||"{}");delete s[yield n.getFingerprint()],Object.values(s).filter((t=>"local"===t.conflictMode&&t.time>e.time)).length>0&&(o="cloud")}let{compareResult:s,syncRecords:a}=yield this.CompareDatabase(e,t,o),{compareResult:c,syncRecords:u}=yield this.CompareConfig(a,t,o),d=Object.assign(Object.assign({},s),c);return r.setAllSyncRecord(u),"local"===o&&(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 n.getFingerprint(),{time:(new Date).getTime(),conflictMode:"local"},"cloudSyncTime"):r.setObjectConfig(yield n.getFingerprint(),{time:(new Date).getTime(),conflictMode:"cloud"},"cloudSyncTime"),d}))}static startSync(e,t,r,n,i,o){return s(this,void 0,void 0,(function*(){let s=yield this.syncConfig(e,t,r,i,n);if(e.books.save.length>0||e.books.upload.length>0){let e=yield this.syncCover(t,o,i),r=yield this.syncBook(t,i);return[...s,...e,...r]}return s}))}static syncConfig(e,t,r,n,i){return s(this,void 0,void 0,(function*(){let o=[];for(let t of c){if(e[t].save.length+e[t].update.length>0){let n=yield i.getCloudDatabase(t);for(let i of e[t].save){let e=n.find((e=>e.key===i));e&&(yield r.saveRecord(e,t))}for(let i of e[t].update){let e=n.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 n.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 n of e.readerConfig.update){let e=n.split(".")[3];r.readerConfig&&t.setReaderConfig(e,JSON.parse(r.readerConfig)[e],!1)}for(let n of e.listConfig.update){let e=n.split(".")[3];r[e]&&t.setAllListConfig(JSON.parse(r[e]),e,!1)}for(let n of e.objectConfig.update){let e=n.split(".")[3],i=n.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 n of e.mapConfig.update){let e=n.split(".")[3],i=n.split(".")[2];if(r[i]&&JSON.parse(r[i])&&JSON.parse(r[i])[e]){let n=JSON.parse(r[i])[e];t.setOneMapConfig(e,n,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],n=r.split(".")[2];t.deleteObjectConfig(e,n)}for(let r of e.mapConfig.delete){let e=r.split(".")[3],n=r.split(".")[2];t.deleteMapConfig(e,n)}}for(let t of c)e[t].upload.length>0&&o.push((()=>i.uploadDatabase(t)));return o.push((()=>i.uploadConfig("config"))),o.push((()=>i.uploadConfig("sync"))),o}))}static syncCover(e,t,r){return s(this,void 0,void 0,(function*(){let r=yield t.getLocalCoverList(),n=yield t.getCloudCoverList(),i=Array.from(new Set([...r,...n])),o=[];for(let s of i)r.includes(s)&&!n.includes(s)&&o.push((()=>t.uploadCover(s))),!r.includes(s)&&n.includes(s)&&"adrive"!==e.getItem("defaultSyncOption")&&o.push((()=>t.downloadCover(s)));return o}))}static syncBook(e,t){return s(this,void 0,void 0,(function*(){let r=yield t.getLocalBookList(),n=yield t.getCloudBookList(),i=[],o=Array.from(new Set([...r,...n]));for(let s of o){if(r.includes(s)&&!n.includes(s)){let e=s.split(".")[0],r=s.split(".")[1];i.push((()=>t.uploadBook(e,r)))}let o="yes"===e.getReaderConfig("autoOffline");if(!r.includes(s)&&n.includes(s)&&o&&"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=[],n=[];for(const i of e){const e=i().then((t=>(n.splice(n.indexOf(e),1),t)));r.push(e),n.push(e),n.length>=t&&(yield Promise.race(n))}return Promise.all(r)}for(let t of e)yield t()}))}}const Tm=(Cm=class{static getItem(e){return localStorage.getItem(e)}static setItem(e,t){localStorage.setItem(e,t)}static removeItem(e){localStorage.removeItem(e)}},Rm="browser",class extends Cm{static getReaderConfig(e){return JSON.parse(this.getItem("readerConfig")||"{}")[e]}static setReaderConfig(e,t,r=!0){let n=JSON.parse(this.getItem("readerConfig")||"{}");n[e]=t,this.setItem("readerConfig",JSON.stringify(n)),r&&this.setSyncRecord({type:"config",catergory:"readerConfig",name:Rm,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 n=r.indexOf(e);n>-1&&r.splice(n,1),this.setAllListConfig(r,t)}static setListConfig(e,t){let r=this.getAllListConfig(t);const n=r.indexOf(e);n>-1?(r.splice(n,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,n=!0){let i=this.getAllObjectConfig(r);i[e]=t,n&&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 n=this.getAllMapConfig(r);void 0===n[e]&&(n[e]=[]),t&&-1===n[e].indexOf(t)&&n[e].unshift(t),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(n,r)}static setOneMapConfig(e,t,r,n=!0){let i=this.getAllMapConfig(r);i[e]=t,n&&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 n=this.getAllMapConfig(r),i=n[e].indexOf(t);n[e].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:r,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(n,r)}static deleteFromAllMapConfig(e,t){let r=this.getAllMapConfig(t);Object.keys(r).forEach((n=>{let i=r[n].indexOf(e);i>-1&&(r[n].splice(i,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:n},{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),n=[];for(let t in r)r[t]&&r[t].indexOf(e)>-1&&n.push(t);return n}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 Cm,Rm;class Om{static saveAllToken(e){return s(this,void 0,void 0,(function*(){if(e)if(o){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(o){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 Mm(t),n="undefined"!=typeof crypto&&crypto.subtle?yield function(e,t,r={alg:"HS256",typ:"JWT"}){return s(this,void 0,void 0,(function*(){const n=Pm((new TextEncoder).encode(JSON.stringify(r))),i=Pm((new TextEncoder).encode(JSON.stringify(e))),o=(new TextEncoder).encode(`${n}.${i}`),s=yield crypto.subtle.importKey("raw",(new TextEncoder).encode(t),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return`${n}.${i}.${Pm(yield crypto.subtle.sign("HMAC",s,o))}`}))}(e,r):function(e,t){if(!e||!t)return"";const r=l((new TextEncoder).encode(t)),n=Array.from(new Uint8Array(r)),i=(new TextEncoder).encode(e),o=new Uint8Array(i.length);for(let e=0;e=0&&r<=Zm}}function Ty(e){return function(t){return null==t?void 0:t[e]}}var Cy=Ty("byteLength"),Ry=Ay(Cy),Oy=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;var Py=zm?function(e){return Vm?Vm(e)&&!vy(e):Ry(e)&&Oy.test(Dm.call(e))}:xy(!1),_y=Ty("length");function My(e,t){t=function(e){for(var t={},r=e.length,n=0;n":">",'"':""","'":"'","`":"`"},Sv=wv(kv),Ev=wv(Yy(kv)),xv=Fy.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},Av=/(.)^/,Tv={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},Cv=/\\|'|\r|\n|\u2028|\u2029/g;function Rv(e){return"\\"+Tv[e]}var Ov=/^\s*(\w|\$)+\s*$/;var Pv=0;function _v(e,t,r,n,i){if(!(n instanceof t))return e.apply(r,i);var o=ov(e.prototype),s=e.apply(o,i);return ey(s)?s:o}var Mv=Ym((function(e,t){var r=Mv.placeholder,n=function(){for(var i=0,o=t.length,s=Array(o),a=0;a1)Fv(a,t-1,r,n),i=n.length;else for(var c=0,u=a.length;c0&&(r=t.apply(this,arguments)),e<=1&&(t=null),r}}var jv=Mv(Dv,2);function zv(e,t,r){t=mv(t,r);for(var n,i=Iy(e),o=0,s=i.length;o0?0:i-1;o>=0&&o0?s=o>=0?o:Math.max(o+a,s):a=o>=0?Math.min(o+1,a):o+a+1;else if(r&&o&&a)return n[o=r(n,i)]===i?o:-1;if(i!=i)return(o=t(Bm.call(n,s,a),Ey))>=0?o+s:-1;for(o=e>0?s:a-1;o>=0&&o=3;return function(t,r,n,i){var o=!Nv(t)&&Iy(t),s=(o||t).length,a=e>0?0:s-1;for(i||(n=t[o?o[a]:a],a+=e);a>=0&&a=0}var sb=Ym((function(e,t,r){var n,i;return fy(t)?i=t:(t=av(t),n=t.slice(0,-1),t=t[t.length-1]),Zv(e,(function(e){var o=i;if(!o){if(n&&n.length&&(e=cv(e,n)),null==e)return;o=e[t]}return null==o?o:o.apply(e,r)}))}));function ab(e,t){return Zv(e,hv(t))}function cb(e,t,r){var n,i,o=-1/0,s=-1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var a=0,c=(e=Nv(e)?e:Zy(e)).length;ao&&(o=n);else t=mv(t,r),Xv(e,(function(e,r,n){((i=t(e,r,n))>s||i===-1/0&&o===-1/0)&&(o=e,s=i)}));return o}var ub=/[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;function db(e){return e?by(e)?Bm.call(e):iy(e)?e.match(ub):Nv(e)?Zv(e,dv):Zy(e):[]}function lb(e,t,r){if(null==t||r)return Nv(e)||(e=Zy(e)),e[vv(e.length-1)];var n=db(e),i=_y(n);t=Math.max(Math.min(t,i),0);for(var o=i-1,s=0;s1&&(n=fv(n,t[1])),t=Dy(e)):(n=yb,t=Fv(t,!1,!1),e=Object(e));for(var i=0,o=t.length;i1&&(r=t[1])):(t=Zv(Fv(t,!1,!1),String),n=function(e,r){return!ob(t,r)}),vb(e,n,r)}));function wb(e,t,r){return Bm.call(e,0,Math.max(0,e.length-(null==t||r?1:t)))}function kb(e,t,r){return null==e||e.length<1?null==t||r?void 0:[]:null==t||r?e[0]:wb(e,e.length-t)}function Sb(e,t,r){return Bm.call(e,null==t||r?1:t)}var Eb=Ym((function(e,t){return t=Fv(t,!0,!0),rb(e,(function(e){return!ob(t,e)}))})),xb=Ym((function(e,t){return Eb(e,t)}));function Ab(e,t,r,n){ry(t)||(n=r,r=t,t=!1),null!=r&&(r=mv(r,n));for(var i=[],o=[],s=0,a=_y(e);st?(n&&(clearTimeout(n),n=null),a=u,s=e.apply(i,o),n||(i=o=null)):n||!1===r.trailing||(n=setTimeout(c,d)),s};return u.cancel=function(){clearTimeout(n),a=0,n=i=o=null},u},debounce:function(e,t,r){var n,i,o,s,a,c=function(){var u=bv()-i;t>u?n=setTimeout(c,t-u):(n=null,r||(s=e.apply(a,o)),n||(o=a=null))},u=Ym((function(u){return a=this,o=u,i=bv(),n||(n=setTimeout(c,t),r&&(s=e.apply(a,o))),s}));return u.cancel=function(){clearTimeout(n),n=o=a=null},u},wrap:function(e,t){return Mv(t,e)},negate:Bv,compose:function(){var e=arguments,t=e.length-1;return function(){for(var r=t,n=e[t].apply(this,arguments);r--;)n=e[r].call(this,n);return n}},after:function(e,t){return function(){if(--e<1)return t.apply(this,arguments)}},before:Dv,once:jv,findKey:zv,findIndex:Hv,findLastIndex:Wv,sortedIndex:Kv,indexOf:Gv,lastIndexOf:Jv,find:Qv,detect:Qv,findWhere:function(e,t){return Qv(e,lv(t))},each:Xv,forEach:Xv,map:Zv,collect:Zv,reduce:eb,foldl:eb,inject:eb,reduceRight:tb,foldr:tb,filter:rb,select:rb,reject:function(e,t,r){return rb(e,Bv(mv(t)),r)},every:nb,all:nb,some:ib,any:ib,contains:ob,includes:ob,include:ob,invoke:sb,pluck:ab,where:function(e,t){return rb(e,lv(t))},max:cb,min:function(e,t,r){var n,i,o=1/0,s=1/0;if(null==t||"number"==typeof t&&"object"!=typeof e[0]&&null!=e)for(var a=0,c=(e=Nv(e)?e:Zy(e)).length;an||void 0===r)return 1;if(re.map((e=>e.name)),Nb=e=>e.map((e=>e.key)),Fb=(e,t)=>{let r=[];for(let n=0;n-1&&r.push(t.indexOf(e[n]));return r.length{if(-1===e.indexOf(n))for(let e=0;ee-Math.min(...r))))]};class $b{static sortBooks(e,t,r){let n=e.map((e=>e.key)),i=(e=>e.getAllListConfig("recentBooks"))(r);if(1===t.sort||0===t.sort)return 1===t.order?Fb(i,n).reverse():Fb(i,n);if(2===t.sort){let r=Ib(e),n=Ib(e).sort();return 1===t.order?Fb(n,r).reverse():Fb(n,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=Nb(e);return 1===t.order?Fb(Mb.union(n,i),i).reverse():Fb(Mb.union(n,i),i)}if(5===t.sort){let r=Nb(e),n=(e=>Mb.sortBy(e.map((e=>({key:e.key,author:e.author}))),"author").map((e=>e.key)))(e);return 1===t.order?Fb(n,r).reverse():Fb(n,r)}if(6===t.sort){let n=(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=Nb(e);return 1===t.order?Fb(n,i).reverse():Fb(n,i)}}static sortNotes(e,t,r=[]){if(3===t.sort){let r=Mb.clone(e).reverse(),n=Mb.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:e.chapterIndex}))));n=1===t.order?Mb.sortBy(n,"chapterIndex"):Mb.sortBy(n,"chapterIndex").reverse();let i=Mb.uniq(n.map((e=>e.chapter))),o={};return i.forEach((e=>{o[e]=[]})),r.forEach((e=>{o[e.chapter].push(e)})),i.map((e=>({group:e,notes:o[e]})))||[]}if(2===t.sort){let r=Mb.clone(e).reverse(),n=Mb.uniq(e.map((e=>e.date.year+"-"+e.date.month+"-"+e.date.day)));1===t.order?n.sort():n.sort().reverse();let i={};return n.forEach((e=>{i[e]=[]})),r.forEach((e=>{n.forEach((t=>{t===e.date.year+"-"+e.date.month+"-"+e.date.day&&i[t].push(e)}))})),i||{}}if(1===t.sort){let n=Mb.clone(e).reverse(),i=Mb.uniq(e.map((e=>{let t=Mb.findLastIndex(r,{key:e.bookKey});return t>-1?r[t].name:""})));1===t.order?i.sort():i.sort().reverse();let o={};return i.forEach((e=>{o[e]=[]})),n.forEach((e=>{i.forEach((t=>{let n=Mb.findLastIndex(r,{key:e.bookKey});n>-1&&t===r[n].name&&o[t].push(e)}))})),o||{}}}static sortBookmarks(e,t){if(3===t.sort){let r=Mb.clone(e).reverse(),n=Mb.uniq(e.map((e=>({chapter:e.chapter,chapterIndex:parseInt(JSON.parse(e.cfi).chapterDocIndex)}))));n=1===t.order?Mb.sortBy(n,"chapterIndex"):Mb.sortBy(n,"chapterIndex").reverse();let i=Mb.uniq(n.map((e=>e.chapter))),o={};return i.forEach((e=>{o[e]=[]})),r.forEach((e=>{o[e.chapter].push(e)})),i.map((e=>({group:e,bookmarks:o[e]})))||[]}}}class Ub{static getDefaultCss(e){return`::selection{background:#f3a6a68c}::-moz-selection{background:#f3a6a68c}.kookit-note:hover{cursor:pointer;}img{max-width:100% !important}body,html{margin: 0px !important; padding: 0px !important;}.kookit-text{${this.getCustomCss(e)}}.kookit-title{${this.getCustomCss(e,!0)}}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,t=!1){return`font-size: ${t?"":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 Lb{static mergeArray(e,t){var r=[];for(let t of e)r.push(t);for(let i of t){var n=!0;for(let t of e)if(i===t){n=!1;break}n&&r.push(i)}return r}static fuzzyQuery(e,t){for(var r=[],n=0;n-1&&r.push(n);return r}static mouseSearch(e){let t=document.querySelector(".header-search-box").value.toLowerCase(),r=[],n=[];if(!e)return[];e.forEach((e=>{r.push(e.name.toLowerCase()),n.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,t),o=this.fuzzyQuery(n,t);return this.mergeArray(i,o)}static keywordSearch(e,t){let r=[],n=[];if(!t)return[];t.forEach((e=>{r.push(e.name.toLowerCase()),n.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,e),o=this.fuzzyQuery(n,e);return this.mergeArray(i,o)}static keySearch(e,t){if(e&&13===e.keyCode){let r=[],n=[];if(!t)return[];t.forEach((e=>{r.push(e.name.toLowerCase()),n.push(e.author.toLowerCase())}));let i=this.fuzzyQuery(r,e.target.value.toLowerCase()),o=this.fuzzyQuery(n,e.target.value.toLowerCase());return this.mergeArray(i,o)}}static mouseNoteSearch(e){let t=document.querySelector(".header-search-box").value.toLowerCase(),r=[],n=[];e.forEach((e=>{r.push(e.notes.toLowerCase()),n.push(e.text.toLowerCase())}));let i=this.fuzzyQuery(r,t),o=this.fuzzyQuery(n,t);return this.mergeArray(i,o)}static keyNoteSearch(e,t){if(e&&13===e.keyCode){let r=[],n=[];t.forEach((e=>{r.push(e.notes.toLowerCase()),n.push(e.text.toLowerCase())}));let i=this.fuzzyQuery(r,e.target.value.toLowerCase()),o=this.fuzzyQuery(n,e.target.value.toLowerCase());return this.mergeArray(i,o)}}}export{vm as BookHelper,f as CommonTool,Tm as ConfigService,m as KookitConfig,xm as LoginHelper,km as ReaderRequest,Lb as SearchUtil,$b as SortUtil,mm as SqlStatement,Ub as StyleHelper,Am as SyncHelper,um as SyncUtil,Sm as ThirdpartyRequest,Om as TokenService,Em as UserRequest}; diff --git a/src/assets/lib/kookit-extra.min.mjs b/src/assets/lib/kookit-extra.min.mjs index d39cf8be..d4348f6c 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 i from"path";import{promisify as r}from"util";import o from"stream";import{Client as s}from"basic-ftp";import{S3Client as n,ListObjectsV2Command as a,DeleteObjectCommand as d,PutObjectCommand as c,GetObjectCommand 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,i,r){return new(i||(i=Promise))((function(o,s){function n(e){try{d(r.next(e))}catch(e){s(e)}}function a(e){try{d(r.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(n,a)}d((r=r.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,i)=>{const r=()=>v(this,void 0,void 0,(function*(){try{this.runningTasks++;const i=yield e();return this.completedTasks++,t(i),i}catch(e){throw this.completedTasks++,i(e),e}finally{this.runningTasks--,this.runNext()}}));this.runningTasks0&&this.runningTasks=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken();let r=[],o=!0,s=null;for(;o;){let n;n=s?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:s},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}):yield e.post("https://api.dropboxapi.com/2/files/list_folder",{path:"/"+t,limit:2e3},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});const a=n.data.entries||[];r=r.concat(a),o=n.data.has_more,s=n.data.cursor}return[...new Set(r.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 i=yield this.refreshToken();yield e.post("https://api.dropboxapi.com/2/files/delete_v2",{path:"/"+t},{headers:{Authorization:`Bearer ${i}`,"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:b,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${E}&redirect_uri=${b}`}}const O=r(o.pipeline);class C extends _{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=t.createReadStream(i.join(this.storagePath,r));return yield e.post("https://content.dropboxapi.com/2/files/upload",n,{headers:{Authorization:`Bearer ${s}`,"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(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=t.createWriteStream(i.join(this.storagePath,o)),a=yield e({url:"https://content.dropboxapi.com/2/files/download",method:"GET",responseType:"stream",headers:{Authorization:`Bearer ${s}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+r})},maxContentLength:1/0,maxBodyLength:1/0});return yield O(a.data,n),!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),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} 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:i,dir:r,ssl:o,port:n}=this.config;const a=new s;return a.ftp.verbose=!0,yield a.access({host:e,port:parseInt(n),user:t,password:i,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:r}=this.config;r=r&&"KoodoReader"===this.baseFolder?r:this.baseFolder;const o=yield this.getClient(),s=()=>v(this,void 0,void 0,(function*(){yield o.ensureDir(i.dirname(r+"/"+t)),yield o.cd("/"),yield o.uploadFrom(i.join(this.storagePath,e),r+"/"+t)}));try{return yield s(),!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:r}=this.config;r=r&&"KoodoReader"===this.baseFolder?r:this.baseFolder;const o=yield this.getClient(),s=()=>v(this,void 0,void 0,(function*(){yield o.downloadTo(i.join(this.storagePath,t),r+"/"+e)}));try{return yield s(),!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"===this.baseFolder?t:this.baseFolder;const i=yield this.getClient(),r=()=>v(this,void 0,void 0,(function*(){return yield i.list(t+"/"+e)}));try{return(yield r()).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"===this.baseFolder?t:this.baseFolder;const i=yield this.getClient(),r=()=>v(this,void 0,void 0,(function*(){yield i.remove(t+"/"+e)}));try{return yield r(),!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 i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken();let r=[],o=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/children`;for(;o;){const t=yield e.get(o,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(t.status>=300)break;const s=t.data.value||[];r=r.concat(s),o=t.data["@odata.nextLink"]||""}return[...new Set(r.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 i=yield this.refreshToken(),r=yield e.delete(`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});return!(r.status>=300)||(console.error("Error deleting file:",r),!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:b,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=${b}`}}const I=209715200;class L extends P{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){var s;let n=null;try{const s=yield this.refreshToken(),a=i.join(this.storagePath,r),d=yield this.getFileSize(a),c=o.split(".").pop(),l=(k(c||""),`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${o}:/createUploadSession`),h=(yield e.post(l,{item:{"@microsoft.graph.conflictBehavior":"replace"}},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}})).data.uploadUrl;n=yield t.promises.open(a,"r");let u=0,p=Buffer.alloc(I);for(;uthis.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),s=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${e}:/content`;let n=(yield fetch(s,{headers:{Authorization:"Bearer "+o},redirect:"manual"})).headers.get("location");if(n){const e=yield fetch(n,{headers:{}}),o=yield e.arrayBuffer();return t.writeFileSync(i.join(this.storagePath,r),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 ${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 i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getFileId(t,i){return v(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+'${i}'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=yield e.get(o,{headers:{Authorization:"Bearer "+r}});if(0===t.data.files.length)return"";const i=t.data.files;return i.length>0?i[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 i=yield this.refreshToken(),r=yield this.getFolderId(t);if(r)return r;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 ${i}`,"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 i=yield this.refreshToken(),r=`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(r,{headers:{Authorization:`Bearer ${i}`}})).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 i=yield this.refreshToken();let r=yield this.checkFolder(t),o=[],s="",n=!0;for(;n;){let t=`https://www.googleapis.com/drive/v3/files?q='${r}'+in+parents&spaces=appDataFolder&fields=nextPageToken,files(id,name)&pageSize=1000`;s&&(t+=`&pageToken=${s}`);const a=yield e.get(t,{headers:{Authorization:`Bearer ${i}`}}),d=a.data.files||[];o=o.concat(d),s=a.data.nextPageToken,n=!!s}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 i=t.split("/")[1],r=t.split("/")[0],o=yield this.getFolderId(r),s=yield this.refreshToken(),n=yield this.getFileId(i,o);if(""===n)return console.error("File not found:",i),!0;try{const t=yield e.delete(`https://www.googleapis.com/drive/v3/files/${n}`,{headers:{Authorization:`Bearer ${s}`}});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:b,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${b}&prompt=consent&response_type=code&client_id=${R}&scope=https://www.googleapis.com/auth/drive.appdata&access_type=offline`}}class B extends ${constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken();let n=r.split("/").pop(),a=o.split(".").pop(),d=k(a||""),c=o.split("/")[0],l=yield this.checkFolder(c),h=yield this.getFileId(n||"",l);const u={mimeType:d,name:n,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 "+s,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location;let y=yield this.getFileSize(i.join(this.storagePath,r));const g=t.createReadStream(i.join(this.storagePath,r));yield e.put(f,g,{headers:{Authorization:"Bearer "+s,"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(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken();let n=r.split("/").pop(),a=r.split("/")[0],d=yield this.checkFolder(a),c=yield this.getFileId(n||"",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((r=>{const n=t.createWriteStream(i.join(this.storagePath,o));e({url:l,method:"GET",responseType:"stream",headers:{Authorization:"Bearer "+s},maxContentLength:1/0,maxBodyLength:1/0}).then((e=>{e.data.pipe(n),n.on("finish",(()=>{r(!0)})),n.on("error",(()=>{r(!1)}))})).catch((()=>{r(!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){this.config=e,this.taskQueue=new T(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(e){return v(this,void 0,void 0,(function*(){let{endpoint:t,region:i,bucketName:r,accessKeyId:o,secretAccessKey:s,dir:d}=this.config;d=d&&"KoodoReader"===this.baseFolder?d:this.baseFolder;let c=d+"/"+e;for(;c.startsWith("/");)c=c.substring(1);const l=new n({endpoint:t,region:i,credentials:{accessKeyId:o,secretAccessKey:s}});try{let e,t=[],i=!0;for(;i;){const o=yield l.send(new a({Bucket:r,Prefix:c,ContinuationToken:e}));o.Contents&&(t=t.concat(o.Contents)),e=o.NextContinuationToken,i=!!e}if(0===t.length)return[];const o=new Set;""===c||c.endsWith("/")||(c+="/");let s=t.map((e=>e.Key));for(const e of s){const t=e.substring(c.length).split("/")[0];o.add(t)}return console.log("List result:",o),Array.from(o)}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{endpoint:t,region:i,bucketName:r,accessKeyId:o,secretAccessKey:s,dir:a}=this.config;a=a&&"KoodoReader"===this.baseFolder?a:this.baseFolder;const c=new n({endpoint:t,region:i,credentials:{accessKeyId:o,secretAccessKey:s}});let l=a+"/"+e;for(;l.startsWith("/");)l=l.substring(1);try{return yield c.send(new d({Bucket:r,Key:l})),!0}catch(e){return console.error(e),!1}}))}}class M extends j{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,r){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:s,bucketName:a,accessKeyId:d,secretAccessKey:l,dir:h}=this.config;const u=new n({endpoint:o,region:s,credentials:{accessKeyId:d,secretAccessKey:l}});h=h&&"KoodoReader"===this.baseFolder?h:this.baseFolder;let p=h+"/"+r;for(;p.startsWith("/");)p=p.substring(1);try{let r=yield u.send(new c({Bucket:a,Key:p,Body:t.createReadStream(i.join(this.storagePath,e))}));return 200===r.$metadata.httpStatusCode||(console.error("Error uploading file:",r),!1)}catch(e){return console.error("Error: ",e),!1}}))))))}))}downloadFile(e,r){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:s,bucketName:a,accessKeyId:d,secretAccessKey:c,dir:h}=this.config;h=h&&"KoodoReader"===this.baseFolder?h:this.baseFolder;const u=()=>new Promise(((u,p)=>{const f=new n({region:s,endpoint:o,credentials:{accessKeyId:d,secretAccessKey:c}});let y=t.createWriteStream(i.join(this.storagePath,r)),g=h+"/"+e;for(;g.startsWith("/");)g=g.substring(1);(function(e,t,i,r){return new Promise(((o,s)=>v(this,void 0,void 0,(function*(){const s=yield e.send(new l({Bucket:t,Key:i}));s.Body?(s.Body.pipe(r),r.on("finish",(e=>{e&&o(!1),o(!0)}))):o(!1)}))))})(f,a,g,y).then((e=>{u(!0)})).catch((e=>{console.error(e),u(!1)}))}));try{return yield u()}catch(e){return console.error(e),!1}}))))))}))}}class D{constructor(e,t){this.storagePath=t;let{username:i,password:r,url:o,dir:s}=e;void 0===e.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=e.baseFolder,s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder,this.client=h(o,{authType:u.Password,username:i,password:r}),this.username=i,this.password=r,this.dir=s,this.taskQueue=new T(5)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}uploadFile(e,r){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(i.dirname(this.dir+"/"+r)))&&(yield this.client.createDirectory(i.dirname(this.dir+"/"+r)));let o=this.client.createWriteStream(this.dir+"/"+r);return t.createReadStream(i.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,r){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(i.join(this.storagePath,r));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 N{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new T(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} 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:i,dir:r,port:o}=this.config;const s=new p;return yield s.connect({host:e,port:o,username:t,password:i}),this.client=s,s}))}uploadFile(e,r){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"===this.baseFolder?o:this.baseFolder;let s=yield this.getClient();const n=()=>new Promise(((n,a)=>v(this,void 0,void 0,(function*(){let a=t.createReadStream(i.join(this.storagePath,e)),d="/"+o+"/"+r,c="/"+o+"/"+i.dirname(r);(yield s.exists(c))||(yield s.mkdir(c,!0)),s.put(a,d).then((()=>{n(!0)})).catch((e=>{console.error(e.message),n(!1)}))}))));try{return yield n()}catch(e){return console.error(e),!1}}))))))}))}downloadFile(e,r){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"===this.baseFolder?o:this.baseFolder;let s=yield this.getClient();const n=()=>new Promise(((n,a)=>{let d="/"+o+"/"+e,c=t.createWriteStream(i.join(this.storagePath,r));s.get(d,c).then((()=>{n(!0)})).catch((e=>{console.error(e.message),n(!1)}))}));try{return yield n()}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"===this.baseFolder?t:this.baseFolder;let i=yield this.getClient();const r=()=>new Promise(((r,o)=>v(this,void 0,void 0,(function*(){let o="/"+t+"/"+e;(yield i.exists(o))||(yield i.mkdir(o,!0),r([])),i.list(o).then((e=>{r(e.map((e=>e.name)))})).catch((e=>v(this,void 0,void 0,(function*(){console.error(e.message,"list file error"),r([])}))))}))));try{return yield r()}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;let i=yield this.getClient();try{return yield new Promise(((r,o)=>{let s="/"+t+"/"+e;i.delete(s).then((()=>{r(!0)})).catch((e=>{console.error(e.message),r(!1)}))}))}catch(e){return console.error(e),!1}}))}}class z{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 W{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new T(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getFolderIdByPath(t){return v(this,void 0,void 0,(function*(){if(""==t)return"0";const i=yield this.refreshToken(),r=t.split("/");let o="0";for(const t of r){const r=`https://api.box.com/2.0/folders/${o}/items?fields=id,name&type=folder&limit=1000`;try{const s=(yield e.get(r,{headers:{Authorization:`Bearer ${i}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(s)o=s.id;else{const r={name:t,parent:{id:o},type:"folder"};o=(yield e.post("https://api.box.com/2.0/folders",r,{headers:{Authorization:`Bearer ${i}`,"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 i=yield this.refreshToken();let r=this.baseFolder+"/"+t;for(;r.startsWith("/");)r=r.substring(1);let o=yield this.getFolderIdByPath(r),s=[],n=0,a=!0;const d=1e3;for(;a;){const t=yield e.get(`https://api.box.com/2.0/folders/${o}/items`,{params:{limit:d,offset:n},headers:{Authorization:`Bearer ${i}`}}),r=t.data.entries||[];s=s.concat(r),n+=r.length,a=r.length===d&&t.data.total_count>n}return[...new Set(s.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 i=yield this.refreshToken(),r=t.substring(0,t.lastIndexOf("/")),o=t.substring(t.lastIndexOf("/")+1);let s=this.baseFolder+"/"+r;for(;s.startsWith("/");)s=s.substring(1);const n=yield this.getFolderIdByPath(s);if(!n)return!0;const a=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,d=(yield e.get(a,{headers:{Authorization:`Bearer ${i}`}})).data.entries.find((e=>e.name===o&&"file"===e.type));return!d||(yield e.delete(`https://api.box.com/2.0/files/${d.id}`,{headers:{Authorization:`Bearer ${i}`}}),!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 i=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token})});return 200===i.code&&(yield this.thirdpartyRequest.TokenService.setToken("boxnet_token",i.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:b,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:F,redirect_uri:b,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class K extends W{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=o.substring(0,o.lastIndexOf("/")),a=o.substring(o.lastIndexOf("/")+1);let d=this.baseFolder+"/"+n;for(;d.startsWith("/");)d=d.substring(1);const c=yield this.getFolderIdByPath(d);if(!c)throw new Error("Folder not found");const l=yield this.listFiles(n);l.find((e=>e===a))&&(yield this.deleteFileWithoutQueue(n+"/"+a));const h=new f,u=JSON.stringify({name:a,parent:{id:c}});h.append("attributes",u),h.append("file",t.createReadStream(i.join(this.storagePath,r)));const p=yield e.post("https://upload.box.com/api/2.0/files/content",h,{headers:Object.assign({Authorization:`Bearer ${s}`},h.getHeaders()),maxContentLength:1/0,maxBodyLength:1/0});return!(p.status>=300)||(console.error("Error occurred during file upload:",p),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=r.substring(0,r.lastIndexOf("/")),a=r.substring(r.lastIndexOf("/")+1);let d=this.baseFolder+"/"+n;for(;d.startsWith("/");)d=d.substring(1);const c=yield this.getFolderIdByPath(d);if(!c)return console.error("Folder not found"),!0;const l=`https://api.box.com/2.0/folders/${c}/items?fields=id,name&type=file&limit=1000`,h=(yield e.get(l,{headers:{Authorization:`Bearer ${s}`}})).data.entries.find((e=>e.name===a&&"file"===e.type));if(!h)return console.error("File not found:",a),!0;const u=yield e({url:`https://api.box.com/2.0/files/${h.id}/content`,method:"get",responseType:"stream",headers:{Authorization:`Bearer ${s}`}});return yield new Promise(((e,r)=>{const s=t.createWriteStream(i.join(this.storagePath,o));u.data.pipe(s),s.on("finish",e),s.on("error",r)})),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class Q{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new T(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} 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;if(""===this.baseFolder)return this.root=e,this.root;let t=e.children.find((e=>e.name===this.baseFolder&&e.directory));return t||(t=yield e.mkdir(this.baseFolder)),this.root=t,this.root}))}createFolder(e,t){return v(this,void 0,void 0,(function*(){const i=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(i))return yield this.folderCreationLocks.get(i);const r=(()=>v(this,void 0,void 0,(function*(){try{let i=e.children.find((e=>e.name===t&&e.directory));return i||(i=yield e.mkdir(t),i)}finally{this.folderCreationLocks.delete(i)}})))();return this.folderCreationLocks.set(i,r),yield r}))}listFiles(e){return v(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();if(e){const i=e.split("/").filter((e=>e));for(const e of i){const i=t.children.find((t=>t.name===e&&t.directory));if(!i)return[];t=i}}return t.children.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 i=e.split("/"),r=i.pop();for(const e of i){if(!e)continue;const i=t.children.find((t=>t.name===e&&t.directory));if(!i)return!0;t=i}const o=t.children.find((e=>e.name===r&&!e.directory));return!o||(yield o.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class q extends Q{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,r){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 s=r.split("/"),n=s.pop()||"";for(const e of s){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===n&&!e.directory));a&&(yield a.delete());const d=t.createReadStream(i.join(this.storagePath,e)),c=t.statSync(i.join(this.storagePath,e)).size;return yield o.upload({name:n,size:c},d).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e,r){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 s=e.split("/"),n=s.pop()||"";for(const e of s){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===n&&!e.directory));if(!a)return!0;const d=t.createWriteStream(i.join(this.storagePath,r));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 J{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new T(1),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=5){return v(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} 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(),i=yield e.post("https://openapi.alipan.com/adrive/v1.0/user/getDriveInfo",{},{headers:{Authorization:`Bearer ${t}`}});return this.driveId=i.data.default_drive_id,this.driveId}))}getFolderIdByPath(t){return v(this,void 0,void 0,(function*(){const i=yield this.refreshToken(),r=yield this.getDriveId();try{try{const o=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:r,file_path:t},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(o.data)return o.data.file_id}catch(o){const s=t.split("/").filter((e=>e));let n="",a="root";for(const t of s){n+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:r,file_path:n},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}})).data.file_id}catch(o){a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:r,parent_file_id:a,name:t,type:"folder",check_name_mode:"refuse"},{headers:{Authorization:`Bearer ${i}`,"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 i=yield this.refreshToken(),r=yield this.getDriveId(),o=yield this.getFolderIdByPath(this.baseFolder+"/"+t);let s=[],n="",a=!0;for(;a;){const t=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:r,parent_file_id:o,marker:n||void 0},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),d=t.data.items||[];s=s.concat(d),n=t.data.next_marker,a=!!n&&100===d.length}return[...new Set(s.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 i=yield this.refreshToken(),r=yield this.getDriveId(),o=yield this.getFolderIdByPath(this.baseFolder+"/"+t);return!o||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:r,file_id:o},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}checkExists(t){var i;return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield this.getDriveId(),s=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"}});(null===(i=s.data)||void 0===i?void 0:i.file_id)&&(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/recyclebin/trash",{drive_id:o,file_id:s.data.file_id},{headers:{Authorization:`Bearer ${r}`,"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 i=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token})});return 200===i.code&&(yield this.thirdpartyRequest.TokenService.setToken("adrive_token",i.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:b,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:x,redirect_uri:b,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class U extends J{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=yield this.getDriveId(),a=o.substring(0,o.lastIndexOf("/")),d=o.substring(o.lastIndexOf("/")+1);yield this.deleteFileWithoutQueue(o);const c=yield this.getFolderIdByPath(this.baseFolder+"/"+a),l=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:n,parent_file_id:c,name:d,type:"file",check_name_mode:"ignore"},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),{file_id:h,upload_id:u,part_info_list:p}=l.data,f=yield t.promises.readFile(i.join(this.storagePath,r));return yield fetch(p[0].upload_url,{method:"PUT",body:f,headers:{"Content-Length":t.statSync(i.join(this.storagePath,r)).size.toString()}}),yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/complete",{drive_id:n,file_id:h,upload_id:u},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=yield this.getDriveId(),a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:n,file_path:this.baseFolder+"/"+r},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}})).data.file_id,d=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:n,file_id:a},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),c=yield e({url:d.data.url,method:"get",responseType:"stream"}),l=t.createWriteStream(i.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 H{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 i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}checkFolderExists(t,i){return v(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:i,path:`/${t}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(t,i){return v(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/createfolderifnotexists",{params:{access_token:i,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 i=yield this.refreshToken(),r=yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:i,path:"/"+t,recursive:0}});return 0!==r.data.result?[]:r.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 i=yield this.refreshToken(),r=yield e.get("https://api.pcloud.com/deletefile",{params:{access_token:i,path:"/"+t}});return 0===r.data.result||(console.error("Error deleting file:",r.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:b,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${w}&response_type=code&redirect_uri=${b}`}}class V extends H{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=o.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(n,s))){if(!(yield this.createFolder(n,s)))return!1}const a=i.join(this.storagePath,r),d=t.createReadStream(a),c=t.statSync(a),l=i.basename(r),h=yield e({method:"put",url:"https://api.pcloud.com/uploadfile",params:{access_token:s,path:`/${n}`,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(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=yield e.get("https://api.pcloud.com/getfilelink",{params:{access_token:s,path:`/${r}`}});if(0!==n.data.result)return console.error("Error getting file link:",n.data),!1;const a=i.join(this.storagePath,o),d=t.createWriteStream(a),c=`https://${n.data.hosts[0]}${n.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 X=["book","config","cover","font"];class Y{constructor(e,t,i,r){this.type=e,this.storagePath=i,this.remote="dropbox"===e?new C(t,i,r):"microsoft"===e?new L(t,i,r):"google"===e?new B(t,i,r):"s3compatible"===e?new M(t,i):"webdav"===e?new D(t,i):"ftp"===e?new A(t,i):"sftp"===e?new N(t,i):"boxnet"===e?new K(t,i,r):"mega"===e?new q(t,i):"adrive"===e?new U(t,i,r):"pcloud"===e?new V(t,i,r):new z}downloadFile(e,r,o){return v(this,void 0,void 0,(function*(){return t.existsSync(i.join(this.storagePath+"/"+o))||t.mkdirSync(i.join(this.storagePath+"/"+o)),!!(yield this.listFiles(o)).find((t=>e.indexOf(t)>-1))&&(yield this.remote.downloadFile(o+"/"+e,o+"/"+r))}))}uploadFile(e,t,i){return v(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(i+"/"+e,i+"/"+t)}))}deleteFile(e,t){return v(this,void 0,void 0,(function*(){return!!(yield this.listFiles(t)).find((t=>e.indexOf(t)>-1))&&(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 X){let t=yield this.listFiles(e);for(let i of t)yield this.downloadFile(i,i,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 G={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 = ?"},Z={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},ee={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function te(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const ie={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 re={sqlStatement:{createTableStatement:te({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:te({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:te({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:te({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:te({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:te({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:te({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:te(G),getByBookKeyStatement:te(Z),getByBookKeysStatement:te({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:te(ee)},jsonToSqlite:te({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:te(ie)};const oe="http://192.168.28.159:8000";class se{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(oe+"/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,i)=>{this.requestQueue.push({config:e,resolve:t,reject:i}),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 i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);t.baseURL=oe,t.headers?(t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=i):t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":i};let r=(yield e(t)).data;if(402===r.code){let i=yield this.refreshUserToken();if(200===i.code){return t.headers=t.headers||{},t.headers.Authorization="Bearer "+this.accessToken,(yield e(t)).data}return i}return 200!==r.code&&this.ConfigService.setItem("errorLog",JSON.stringify({request:t.data,url:t.url,result:r,requestID:i})),r}catch(e){return console.error("Request execution error:",e),{code:503,message:"network error",data:null}}}))}requestWithStream(e,t,i){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 o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((s,n)=>{const a=new i(oe+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+r,"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 i=JSON.parse(e.data);i.done?(a.close(),s(i)):(402===i.code&&(yield this.refreshUserToken()),t(i.data))})))),a.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);s(t),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 i="";try{i=(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);return new Promise(((o,s)=>v(this,void 0,void 0,(function*(){const s=yield fetch(oe+e.url,{method:"POST",headers:{"Content-Type":"text/event-stream",Authorization:"Bearer "+i,"X-Request-ID":r},body:JSON.stringify(e.data)});if(!s.body)throw new Error("Response body is null");const n=s.body.pipeThrough(new TextDecoderStream).getReader();for(;;){const{value:e,done:i}=yield n.read();if(i){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 i=JSON.parse(e.substring(5));t(i.data)}}))}o({code:200,data:{done:!0}})}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}class ne extends se{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)}))}getSyncData(){return v(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/pro/thirdparty/get_sync_data"})}))}updateSyncData(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/update_sync_data",data:e};return yield this.requestWithRetry(t)}))}}const ae=new g;class de{static encrypt(e,t){let i="";for(let r=0;r-1&&i.splice(r,1),this.setAllListConfig(i,t)}static setListConfig(e,t){let i=this.getAllListConfig(t);const r=i.indexOf(e);r>-1?(i.splice(r,1),i.unshift(e)):i.unshift(e),this.setAllListConfig(i,t)}static setAllListConfig(e,t,i=!0){this.setItem(t,JSON.stringify(e)),i&&this.setSyncRecord({type:"config",catergory:"listConfig",name:"general",key:t},{operation:"update",time:Date.now()})}static setObjectConfig(e,t,i,r=!0){let o=this.getAllObjectConfig(i);o[e]=t,r&&this.setSyncRecord({type:"config",catergory:"objectConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllObjectConfig(o,i)}static getObjectConfig(e,t,i){return this.getAllObjectConfig(t)[e]||i}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 i=this.getAllObjectConfig(t);delete i[e],this.setSyncRecord({type:"config",catergory:"objectConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllObjectConfig(i,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,i){let r=this.getAllMapConfig(i);void 0===r[e]&&(r[e]=[]),t&&-1===r[e].indexOf(t)&&r[e].unshift(t),this.setSyncRecord({type:"config",catergory:"mapConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(r,i)}static setOneMapConfig(e,t,i,r=!0){let o=this.getAllMapConfig(i);o[e]=t,r&&this.setSyncRecord({type:"config",catergory:"mapConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,i)}static deleteFromMapConfig(e,t,i){let r=this.getAllMapConfig(i),o=r[e].indexOf(t);r[e].splice(o,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(r,i)}static deleteFromAllMapConfig(e,t){let i=this.getAllMapConfig(t);Object.keys(i).forEach((r=>{let o=i[r].indexOf(e);o>-1&&(i[r].splice(o,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:r},{operation:"update",time:Date.now()}))})),this.setAllMapConfig(i,t)}static deleteMapConfig(e,t){let i=this.getAllMapConfig(t);delete i[e],this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllMapConfig(i,t)}static getFromAllMapConfig(e,t){let i=this.getAllMapConfig(t),r=[];for(let t in i)i[t]&&i[t].indexOf(e)>-1&&r.push(t);return r}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 i=JSON.parse(this.getItem("syncRecord")||"{}");i[e.type+"."+e.catergory+"."+e.name+"."+e.key]=t,this.setItem("syncRecord",JSON.stringify(i))}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}});var he,ue;export{le as ConfigService,re as SqlStatement,Y as SyncUtil,ne as ThirdpartyRequest,de as TokenService}; +import e from"axios";import t from"fs";import i from"path";import{promisify as r}from"util";import o from"stream";import{Client as s}from"basic-ftp";import{S3Client as n,ListObjectsV2Command as a,DeleteObjectCommand as d,PutObjectCommand as c,GetObjectCommand 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,i,r){return new(i||(i=Promise))((function(o,s){function n(e){try{d(r.next(e))}catch(e){s(e)}}function a(e){try{d(r.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(n,a)}d((r=r.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,i)=>{const r=()=>v(this,void 0,void 0,(function*(){try{this.runningTasks++;const i=yield e();return this.completedTasks++,t(i),i}catch(e){throw this.completedTasks++,i(e),e}finally{this.runningTasks--,this.runNext()}}));this.runningTasks0&&this.runningTasks=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken();let r=[],o=!0,s=null;for(;o;){let n;n=s?yield e.post("https://api.dropboxapi.com/2/files/list_folder/continue",{cursor:s},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}):yield e.post("https://api.dropboxapi.com/2/files/list_folder",{path:"/"+t,limit:2e3},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});const a=n.data.entries||[];r=r.concat(a),o=n.data.has_more,s=n.data.cursor}return[...new Set(r.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 i=yield this.refreshToken();yield e.post("https://api.dropboxapi.com/2/files/delete_v2",{path:"/"+t},{headers:{Authorization:`Bearer ${i}`,"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:b,code:e})).data.refresh_token}))}getAuthUrl(){return`https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=${E}&redirect_uri=${b}`}}const O=r(o.pipeline);class C extends _{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=t.createReadStream(i.join(this.storagePath,r));return yield e.post("https://content.dropboxapi.com/2/files/upload",n,{headers:{Authorization:`Bearer ${s}`,"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(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=t.createWriteStream(i.join(this.storagePath,o)),a=yield e({url:"https://content.dropboxapi.com/2/files/download",method:"GET",responseType:"stream",headers:{Authorization:`Bearer ${s}`,"Dropbox-API-Arg":JSON.stringify({path:"/"+r})},maxContentLength:1/0,maxBodyLength:1/0});return yield O(a.data,n),!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),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} 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:i,dir:r,ssl:o,port:n}=this.config;const a=new s;return a.ftp.verbose=!0,yield a.access({host:e,port:parseInt(n),user:t,password:i,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:r}=this.config;r=r&&"KoodoReader"===this.baseFolder?r:this.baseFolder;const o=yield this.getClient(),s=()=>v(this,void 0,void 0,(function*(){yield o.ensureDir(i.dirname(r+"/"+t)),yield o.cd("/"),yield o.uploadFrom(i.join(this.storagePath,e),r+"/"+t)}));try{return yield s(),!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:r}=this.config;r=r&&"KoodoReader"===this.baseFolder?r:this.baseFolder;const o=yield this.getClient(),s=()=>v(this,void 0,void 0,(function*(){yield o.downloadTo(i.join(this.storagePath,t),r+"/"+e)}));try{return yield s(),!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"===this.baseFolder?t:this.baseFolder;const i=yield this.getClient(),r=()=>v(this,void 0,void 0,(function*(){return yield i.list(t+"/"+e)}));try{return(yield r()).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"===this.baseFolder?t:this.baseFolder;const i=yield this.getClient(),r=()=>v(this,void 0,void 0,(function*(){yield i.remove(t+"/"+e)}));try{return yield r(),!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 i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(t){return v(this,void 0,void 0,(function*(){try{const i=yield this.refreshToken();let r=[],o=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}:/children`;for(;o;){const t=yield e.get(o,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(t.status>=300)break;const s=t.data.value||[];r=r.concat(s),o=t.data["@odata.nextLink"]||""}return[...new Set(r.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 i=yield this.refreshToken(),r=yield e.delete(`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${t}`,{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});return!(r.status>=300)||(console.error("Error deleting file:",r),!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:b,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=${b}`}}const I=209715200;class L extends P{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){var s;let n=null;try{const s=yield this.refreshToken(),a=i.join(this.storagePath,r),d=yield this.getFileSize(a),c=o.split(".").pop(),l=(k(c||""),`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${o}:/createUploadSession`),h=(yield e.post(l,{item:{"@microsoft.graph.conflictBehavior":"replace"}},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}})).data.uploadUrl;n=yield t.promises.open(a,"r");let u=0,p=Buffer.alloc(I);for(;uthis.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const o=yield this.refreshToken(),s=`https://graph.microsoft.com/v1.0/me/drive/special/approot:/${e}:/content`;let n=(yield fetch(s,{headers:{Authorization:"Bearer "+o},redirect:"manual"})).headers.get("location");if(n){const e=yield fetch(n,{headers:{}}),o=yield e.arrayBuffer();return t.writeFileSync(i.join(this.storagePath,r),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 ${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 i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getFileId(t,i){return v(this,void 0,void 0,(function*(){const r=yield this.refreshToken(),o=`https://www.googleapis.com/drive/v3/files?q=name='${t}'+and+'${i}'+in+parents&spaces=appDataFolder&fields=files(id,name)`;try{const t=yield e.get(o,{headers:{Authorization:"Bearer "+r}});if(0===t.data.files.length)return"";const i=t.data.files;return i.length>0?i[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 i=yield this.refreshToken(),r=yield this.getFolderId(t);if(r)return r;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 ${i}`,"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 i=yield this.refreshToken(),r=`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(r,{headers:{Authorization:`Bearer ${i}`}})).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 i=yield this.refreshToken();let r=yield this.checkFolder(t),o=[],s="",n=!0;for(;n;){let t=`https://www.googleapis.com/drive/v3/files?q='${r}'+in+parents&spaces=appDataFolder&fields=nextPageToken,files(id,name)&pageSize=1000`;s&&(t+=`&pageToken=${s}`);const a=yield e.get(t,{headers:{Authorization:`Bearer ${i}`}}),d=a.data.files||[];o=o.concat(d),s=a.data.nextPageToken,n=!!s}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 i=t.split("/")[1],r=t.split("/")[0],o=yield this.getFolderId(r),s=yield this.refreshToken(),n=yield this.getFileId(i,o);if(""===n)return console.error("File not found:",i),!0;try{const t=yield e.delete(`https://www.googleapis.com/drive/v3/files/${n}`,{headers:{Authorization:`Bearer ${s}`}});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:b,code:e})).data.refresh_token}))}getAuthUrl(){return`https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${b}&prompt=consent&response_type=code&client_id=${R}&scope=https://www.googleapis.com/auth/drive.appdata&access_type=offline`}}class B extends ${constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken();let n=r.split("/").pop(),a=o.split(".").pop(),d=k(a||""),c=o.split("/")[0],l=yield this.checkFolder(c),h=yield this.getFileId(n||"",l);const u={mimeType:d,name:n,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 "+s,"Content-Type":"application/json; charset=UTF-8"},maxContentLength:1/0,maxBodyLength:1/0})).headers.location;let y=yield this.getFileSize(i.join(this.storagePath,r));const g=t.createReadStream(i.join(this.storagePath,r));yield e.put(f,g,{headers:{Authorization:"Bearer "+s,"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(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken();let n=r.split("/").pop(),a=r.split("/")[0],d=yield this.checkFolder(a),c=yield this.getFileId(n||"",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((r=>{const n=t.createWriteStream(i.join(this.storagePath,o));e({url:l,method:"GET",responseType:"stream",headers:{Authorization:"Bearer "+s},maxContentLength:1/0,maxBodyLength:1/0}).then((e=>{e.data.pipe(n),n.on("finish",(()=>{r(!0)})),n.on("error",(()=>{r(!1)}))})).catch((()=>{r(!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){this.config=e,this.taskQueue=new T(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}listFiles(e){return v(this,void 0,void 0,(function*(){let{endpoint:t,region:i,bucketName:r,accessKeyId:o,secretAccessKey:s,dir:d}=this.config;d=d&&"KoodoReader"===this.baseFolder?d:this.baseFolder;let c=d+"/"+e;for(;c.startsWith("/");)c=c.substring(1);const l=new n({endpoint:t,region:i,credentials:{accessKeyId:o,secretAccessKey:s}});try{let e,t=[],i=!0;for(;i;){const o=yield l.send(new a({Bucket:r,Prefix:c,ContinuationToken:e}));o.Contents&&(t=t.concat(o.Contents)),e=o.NextContinuationToken,i=!!e}if(0===t.length)return[];const o=new Set;""===c||c.endsWith("/")||(c+="/");let s=t.map((e=>e.Key));for(const e of s){const t=e.substring(c.length).split("/")[0];o.add(t)}return Array.from(o)}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{endpoint:t,region:i,bucketName:r,accessKeyId:o,secretAccessKey:s,dir:a}=this.config;a=a&&"KoodoReader"===this.baseFolder?a:this.baseFolder;const c=new n({endpoint:t,region:i,credentials:{accessKeyId:o,secretAccessKey:s}});let l=a+"/"+e;for(;l.startsWith("/");)l=l.substring(1);try{return yield c.send(new d({Bucket:r,Key:l})),!0}catch(e){return console.error(e),!1}}))}}class M extends j{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,r){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:s,bucketName:a,accessKeyId:d,secretAccessKey:l,dir:h}=this.config;const u=new n({endpoint:o,region:s,credentials:{accessKeyId:d,secretAccessKey:l}});h=h&&"KoodoReader"===this.baseFolder?h:this.baseFolder;let p=h+"/"+r;for(;p.startsWith("/");)p=p.substring(1);try{let r=yield u.send(new c({Bucket:a,Key:p,Body:t.createReadStream(i.join(this.storagePath,e))}));return 200===r.$metadata.httpStatusCode||(console.error("Error uploading file:",r),!1)}catch(e){return console.error("Error: ",e),!1}}))))))}))}downloadFile(e,r){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:s,bucketName:a,accessKeyId:d,secretAccessKey:c,dir:h}=this.config;h=h&&"KoodoReader"===this.baseFolder?h:this.baseFolder;const u=()=>new Promise(((u,p)=>{const f=new n({region:s,endpoint:o,credentials:{accessKeyId:d,secretAccessKey:c}});let y=t.createWriteStream(i.join(this.storagePath,r)),g=h+"/"+e;for(;g.startsWith("/");)g=g.substring(1);(function(e,t,i,r){return new Promise(((o,s)=>v(this,void 0,void 0,(function*(){const s=yield e.send(new l({Bucket:t,Key:i}));s.Body?(s.Body.pipe(r),r.on("finish",(e=>{e&&o(!1),o(!0)}))):o(!1)}))))})(f,a,g,y).then((e=>{u(!0)})).catch((e=>{console.error(e),u(!1)}))}));try{return yield u()}catch(e){return console.error(e),!1}}))))))}))}}class D{constructor(e,t){this.storagePath=t;let{username:i,password:r,url:o,dir:s}=e;void 0===e.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=e.baseFolder,s=s&&"KoodoReader"===this.baseFolder?s:this.baseFolder,this.client=h(o,{authType:u.Password,username:i,password:r}),this.username=i,this.password=r,this.dir=s,this.taskQueue=new T(5)}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}uploadFile(e,r){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(i.dirname(this.dir+"/"+r)))&&(yield this.client.createDirectory(i.dirname(this.dir+"/"+r)));let o=this.client.createWriteStream(this.dir+"/"+r);return t.createReadStream(i.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,r){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(i.join(this.storagePath,r));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 N{constructor(e,t){this.config=e,this.storagePath=t,this.taskQueue=new T(5),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=0){return v(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} 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:i,dir:r,port:o}=this.config;const s=new p;return yield s.connect({host:e,port:o,username:t,password:i}),this.client=s,s}))}uploadFile(e,r){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"===this.baseFolder?o:this.baseFolder;let s=yield this.getClient();const n=()=>new Promise(((n,a)=>v(this,void 0,void 0,(function*(){let a=t.createReadStream(i.join(this.storagePath,e)),d="/"+o+"/"+r,c="/"+o+"/"+i.dirname(r);(yield s.exists(c))||(yield s.mkdir(c,!0)),s.put(a,d).then((()=>{n(!0)})).catch((e=>{console.error(e.message),n(!1)}))}))));try{return yield n()}catch(e){return console.error(e),!1}}))))))}))}downloadFile(e,r){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"===this.baseFolder?o:this.baseFolder;let s=yield this.getClient();const n=()=>new Promise(((n,a)=>{let d="/"+o+"/"+e,c=t.createWriteStream(i.join(this.storagePath,r));s.get(d,c).then((()=>{n(!0)})).catch((e=>{console.error(e.message),n(!1)}))}));try{return yield n()}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"===this.baseFolder?t:this.baseFolder;let i=yield this.getClient();const r=()=>new Promise(((r,o)=>v(this,void 0,void 0,(function*(){let o="/"+t+"/"+e;(yield i.exists(o))||(yield i.mkdir(o,!0),r([])),i.list(o).then((e=>{r(e.map((e=>e.name)))})).catch((e=>v(this,void 0,void 0,(function*(){console.error(e.message,"list file error"),r([])}))))}))));try{return yield r()}catch(e){return console.error(e),[]}}))}deleteFile(e){return v(this,void 0,void 0,(function*(){let{dir:t}=this.config;t=t&&"KoodoReader"===this.baseFolder?t:this.baseFolder;let i=yield this.getClient();try{return yield new Promise(((r,o)=>{let s="/"+t+"/"+e;i.delete(s).then((()=>{r(!0)})).catch((e=>{console.error(e.message),r(!1)}))}))}catch(e){return console.error(e),!1}}))}}class z{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 W{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.refreshTokenPromise=null,this.taskQueue=new T(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}getFolderIdByPath(t){return v(this,void 0,void 0,(function*(){if(""==t)return"0";const i=yield this.refreshToken(),r=t.split("/");let o="0";for(const t of r){const r=`https://api.box.com/2.0/folders/${o}/items?fields=id,name&type=folder&limit=1000`;try{const s=(yield e.get(r,{headers:{Authorization:`Bearer ${i}`}})).data.entries.find((e=>e.name===t&&"folder"===e.type));if(s)o=s.id;else{const r={name:t,parent:{id:o},type:"folder"};o=(yield e.post("https://api.box.com/2.0/folders",r,{headers:{Authorization:`Bearer ${i}`,"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 i=yield this.refreshToken();let r=this.baseFolder+"/"+t;for(;r.startsWith("/");)r=r.substring(1);let o=yield this.getFolderIdByPath(r),s=[],n=0,a=!0;const d=1e3;for(;a;){const t=yield e.get(`https://api.box.com/2.0/folders/${o}/items`,{params:{limit:d,offset:n},headers:{Authorization:`Bearer ${i}`}}),r=t.data.entries||[];s=s.concat(r),n+=r.length,a=r.length===d&&t.data.total_count>n}return[...new Set(s.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 i=yield this.refreshToken(),r=t.substring(0,t.lastIndexOf("/")),o=t.substring(t.lastIndexOf("/")+1);let s=this.baseFolder+"/"+r;for(;s.startsWith("/");)s=s.substring(1);const n=yield this.getFolderIdByPath(s);if(!n)return!0;const a=`https://api.box.com/2.0/folders/${n}/items?fields=id,name&type=file&limit=1000`,d=(yield e.get(a,{headers:{Authorization:`Bearer ${i}`}})).data.entries.find((e=>e.name===o&&"file"===e.type));return!d||(yield e.delete(`https://api.box.com/2.0/files/${d.id}`,{headers:{Authorization:`Bearer ${i}`}}),!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 i=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token})});return 200===i.code&&(yield this.thirdpartyRequest.TokenService.setToken("boxnet_token",i.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:b,code:e})).data.refresh_token}))}getAuthUrl(){return`https://account.box.com/api/oauth2/authorize?${new URLSearchParams({response_type:"code",client_id:F,redirect_uri:b,grant_type:"authorization_code",box_subject_type:"enterprise",scope:"root_readwrite"}).toString()}`}}class K extends W{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=o.substring(0,o.lastIndexOf("/")),a=o.substring(o.lastIndexOf("/")+1);let d=this.baseFolder+"/"+n;for(;d.startsWith("/");)d=d.substring(1);const c=yield this.getFolderIdByPath(d);if(!c)throw new Error("Folder not found");const l=yield this.listFiles(n);l.find((e=>e===a))&&(yield this.deleteFileWithoutQueue(n+"/"+a));const h=new f,u=JSON.stringify({name:a,parent:{id:c}});h.append("attributes",u),h.append("file",t.createReadStream(i.join(this.storagePath,r)));const p=yield e.post("https://upload.box.com/api/2.0/files/content",h,{headers:Object.assign({Authorization:`Bearer ${s}`},h.getHeaders()),maxContentLength:1/0,maxBodyLength:1/0});return!(p.status>=300)||(console.error("Error occurred during file upload:",p),!1)}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=r.substring(0,r.lastIndexOf("/")),a=r.substring(r.lastIndexOf("/")+1);let d=this.baseFolder+"/"+n;for(;d.startsWith("/");)d=d.substring(1);const c=yield this.getFolderIdByPath(d);if(!c)return console.error("Folder not found"),!0;const l=`https://api.box.com/2.0/folders/${c}/items?fields=id,name&type=file&limit=1000`,h=(yield e.get(l,{headers:{Authorization:`Bearer ${s}`}})).data.entries.find((e=>e.name===a&&"file"===e.type));if(!h)return console.error("File not found:",a),!0;const u=yield e({url:`https://api.box.com/2.0/files/${h.id}/content`,method:"get",responseType:"stream",headers:{Authorization:`Bearer ${s}`}});return yield new Promise(((e,r)=>{const s=t.createWriteStream(i.join(this.storagePath,o));u.data.pipe(s),s.on("finish",e),s.on("error",r)})),!0}catch(e){return console.error("Error occurred during file download:",e),!1}}))))))}))}}class Q{constructor(e){this.folderCreationLocks=new Map,this.config=e,this.taskQueue=new T(3),void 0===this.config.baseFolder?this.baseFolder="KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=3){return v(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} 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;if(""===this.baseFolder)return this.root=e,this.root;let t=e.children.find((e=>e.name===this.baseFolder&&e.directory));return t||(t=yield e.mkdir(this.baseFolder)),this.root=t,this.root}))}createFolder(e,t){return v(this,void 0,void 0,(function*(){const i=`${e.nodeId}_${t}`;if(this.folderCreationLocks.has(i))return yield this.folderCreationLocks.get(i);const r=(()=>v(this,void 0,void 0,(function*(){try{let i=e.children.find((e=>e.name===t&&e.directory));return i||(i=yield e.mkdir(t),i)}finally{this.folderCreationLocks.delete(i)}})))();return this.folderCreationLocks.set(i,r),yield r}))}listFiles(e){return v(this,void 0,void 0,(function*(){try{let t=yield this.getRoot();if(e){const i=e.split("/").filter((e=>e));for(const e of i){const i=t.children.find((t=>t.name===e&&t.directory));if(!i)return[];t=i}}return t.children.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 i=e.split("/"),r=i.pop();for(const e of i){if(!e)continue;const i=t.children.find((t=>t.name===e&&t.directory));if(!i)return!0;t=i}const o=t.children.find((e=>e.name===r&&!e.directory));return!o||(yield o.delete(),!0)}catch(e){return console.error("Error deleting MEGA file:",e),!1}}))}}class q extends Q{constructor(e,t){super(e),this.storagePath=t}uploadFile(e,r){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 s=r.split("/"),n=s.pop()||"";for(const e of s){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===n&&!e.directory));a&&(yield a.delete());const d=t.createReadStream(i.join(this.storagePath,e)),c=t.statSync(i.join(this.storagePath,e)).size;return yield o.upload({name:n,size:c},d).complete,!0}catch(e){return console.error("Error occurred during MEGA file upload:",e),!1}}))))))}))}downloadFile(e,r){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 s=e.split("/"),n=s.pop()||"";for(const e of s){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===n&&!e.directory));if(!a)return!0;const d=t.createWriteStream(i.join(this.storagePath,r));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 J{constructor(e,t){this.config=e,this.thirdpartyRequest=t,this.driveId="",this.refreshTokenPromise=null,this.taskQueue=new T(1),void 0===this.config.baseFolder?this.baseFolder="/KoodoReader":this.baseFolder=this.config.baseFolder}retryOperation(e,t=5){return v(this,void 0,void 0,(function*(){let i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} 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(),i=yield e.post("https://openapi.alipan.com/adrive/v1.0/user/getDriveInfo",{},{headers:{Authorization:`Bearer ${t}`}});return this.driveId=i.data.default_drive_id,this.driveId}))}getFolderIdByPath(t){return v(this,void 0,void 0,(function*(){const i=yield this.refreshToken(),r=yield this.getDriveId();try{try{const o=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:r,file_path:t},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}});if(o.data)return o.data.file_id}catch(o){const s=t.split("/").filter((e=>e));let n="",a="root";for(const t of s){n+="/"+t;try{a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:r,file_path:n},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}})).data.file_id}catch(o){a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:r,parent_file_id:a,name:t,type:"folder",check_name_mode:"refuse"},{headers:{Authorization:`Bearer ${i}`,"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 i=yield this.refreshToken(),r=yield this.getDriveId(),o=yield this.getFolderIdByPath(this.baseFolder+"/"+t);let s=[],n="",a=!0;for(;a;){const t=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/list",{drive_id:r,parent_file_id:o,marker:n||void 0},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),d=t.data.items||[];s=s.concat(d),n=t.data.next_marker,a=!!n&&100===d.length}return[...new Set(s.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 i=yield this.refreshToken(),r=yield this.getDriveId(),o=yield this.getFolderIdByPath(this.baseFolder+"/"+t);return!o||(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/delete",{drive_id:r,file_id:o},{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}}),!0)}catch(e){return console.error("Error deleting file:",e),!1}}))}checkExists(t){var i;return v(this,void 0,void 0,(function*(){try{const r=yield this.refreshToken(),o=yield this.getDriveId(),s=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"}});(null===(i=s.data)||void 0===i?void 0:i.file_id)&&(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/recyclebin/trash",{drive_id:o,file_id:s.data.file_id},{headers:{Authorization:`Bearer ${r}`,"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 i=yield this.thirdpartyRequest.encryptToken({token:JSON.stringify({refresh_token:t.data.refresh_token})});return 200===i.code&&(yield this.thirdpartyRequest.TokenService.setToken("adrive_token",i.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:b,code:e})).data.refresh_token}))}getAuthUrl(){return`https://openapi.alipan.com/oauth/authorize?${new URLSearchParams({response_type:"code",client_id:x,redirect_uri:b,grant_type:"authorization_code",scope:"user:base,file:all:write,file:all:read"}).toString()}`}}class U extends J{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=yield this.getDriveId(),a=o.substring(0,o.lastIndexOf("/")),d=o.substring(o.lastIndexOf("/")+1);yield this.deleteFileWithoutQueue(o);const c=yield this.getFolderIdByPath(this.baseFolder+"/"+a),l=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/create",{drive_id:n,parent_file_id:c,name:d,type:"file",check_name_mode:"ignore"},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),{file_id:h,upload_id:u,part_info_list:p}=l.data,f=yield t.promises.readFile(i.join(this.storagePath,r));return yield fetch(p[0].upload_url,{method:"PUT",body:f,headers:{"Content-Length":t.statSync(i.join(this.storagePath,r)).size.toString()}}),yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/complete",{drive_id:n,file_id:h,upload_id:u},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),!0}catch(e){return console.error("Error uploading file:",e),!1}}))))))}))}downloadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=yield this.getDriveId(),a=(yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/get_by_path",{drive_id:n,file_path:this.baseFolder+"/"+r},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}})).data.file_id,d=yield e.post("https://openapi.alipan.com/adrive/v1.0/openFile/getDownloadUrl",{drive_id:n,file_id:a},{headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}),c=yield e({url:d.data.url,method:"get",responseType:"stream"}),l=t.createWriteStream(i.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 H{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 i=0;for(;;){const r=yield e();if(r)return r;if(i>=t)return r;i++;const o=1e3*Math.pow(2,i);console.info(`Retry attempt ${i} after ${o}ms`),yield new Promise((e=>setTimeout(e,o)))}}))}checkFolderExists(t,i){return v(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:i,path:`/${t}`}})).data.result}catch(e){return console.error("Error checking folder:",e),!1}}))}createFolder(t,i){return v(this,void 0,void 0,(function*(){try{return 0===(yield e.get("https://api.pcloud.com/createfolderifnotexists",{params:{access_token:i,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 i=yield this.refreshToken(),r=yield e.get("https://api.pcloud.com/listfolder",{params:{access_token:i,path:"/"+t,recursive:0}});return 0!==r.data.result?[]:r.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 i=yield this.refreshToken(),r=yield e.get("https://api.pcloud.com/deletefile",{params:{access_token:i,path:"/"+t}});return 0===r.data.result||(console.error("Error deleting file:",r.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:b,code:e})).data.access_token}))}getAuthUrl(){return`https://my.pcloud.com/oauth2/authorize?client_id=${w}&response_type=code&redirect_uri=${b}`}}class V extends H{constructor(e,t,i){super(e,i),this.storagePath=t}uploadFile(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=o.split("/").slice(0,-1).join("/");if(!(yield this.checkFolderExists(n,s))){if(!(yield this.createFolder(n,s)))return!1}const a=i.join(this.storagePath,r),d=t.createReadStream(a),c=t.statSync(a),l=i.basename(r),h=yield e({method:"put",url:"https://api.pcloud.com/uploadfile",params:{access_token:s,path:`/${n}`,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(r,o){return v(this,void 0,void 0,(function*(){return this.taskQueue.addTask((()=>this.retryOperation((()=>v(this,void 0,void 0,(function*(){try{const s=yield this.refreshToken(),n=yield e.get("https://api.pcloud.com/getfilelink",{params:{access_token:s,path:`/${r}`}});if(0!==n.data.result)return console.error("Error getting file link:",n.data),!1;const a=i.join(this.storagePath,o),d=t.createWriteStream(a),c=`https://${n.data.hosts[0]}${n.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 X=["book","config","cover","font"];class Y{constructor(e,t,i,r){this.type=e,this.storagePath=i,this.remote="dropbox"===e?new C(t,i,r):"microsoft"===e?new L(t,i,r):"google"===e?new B(t,i,r):"s3compatible"===e?new M(t,i):"webdav"===e?new D(t,i):"ftp"===e?new A(t,i):"sftp"===e?new N(t,i):"boxnet"===e?new K(t,i,r):"mega"===e?new q(t,i):"adrive"===e?new U(t,i,r):"pcloud"===e?new V(t,i,r):new z}downloadFile(e,r,o){return v(this,void 0,void 0,(function*(){if(t.existsSync(i.join(this.storagePath+"/"+o))||t.mkdirSync(i.join(this.storagePath+"/"+o)),"cover"!==o){if(!(yield this.listFiles(o)).find((t=>e.indexOf(t)>-1)))return!1}return yield this.remote.downloadFile(o+"/"+e,o+"/"+r)}))}uploadFile(e,t,i){return v(this,void 0,void 0,(function*(){return yield this.remote.uploadFile(i+"/"+e,i+"/"+t)}))}deleteFile(e,t){return v(this,void 0,void 0,(function*(){return!!(yield this.listFiles(t)).find((t=>e.indexOf(t)>-1))&&(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 X){let t=yield this.listFiles(e);for(let i of t)yield this.downloadFile(i,i,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 G={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 = ?"},Z={notes:"SELECT * FROM notes WHERE bookKey = ?",bookmarks:"SELECT * FROM bookmarks WHERE bookKey = ?",words:"SELECT * FROM words WHERE bookKey = ?",books:"SELECT * FROM books WHERE key = ?"},ee={notes:"DELETE FROM notes WHERE bookKey = ?",bookmarks:"DELETE FROM bookmarks WHERE bookKey = ?",words:"DELETE FROM words WHERE bookKey = ?"};function te(e){for(const t in e)e.hasOwnProperty(t)&&(e[`temp-${t}`]=e[t]);return e}const ie={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 re={sqlStatement:{createTableStatement:te({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:te({notes:"SELECT * FROM notes",bookmarks:"SELECT * FROM bookmarks",books:"SELECT * FROM books",plugins:"SELECT * FROM plugins",words:"SELECT * FROM words"}),saveStatement:te({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:te({notes:"DELETE FROM notes",bookmarks:"DELETE FROM bookmarks",books:"DELETE FROM books",plugins:"DELETE FROM plugins",words:"DELETE FROM words"}),updateStatement:te({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:te({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:te({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:te(G),getByBookKeyStatement:te(Z),getByBookKeysStatement:te({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:te(ee)},jsonToSqlite:te({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:te(ie)};const oe="https://cloud.960960.xyz";class se{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(oe+"/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,i)=>{this.requestQueue.push({config:e,resolve:t,reject:i}),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 i="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);t.baseURL=oe,t.headers?(t.headers.Authorization="Bearer "+this.accessToken,t.headers["X-Request-ID"]=i):t.headers={Authorization:"Bearer "+this.accessToken,"X-Request-ID":i};let r=(yield e(t)).data;if(402===r.code){let i=yield this.refreshUserToken();if(200===i.code){return t.headers=t.headers||{},t.headers.Authorization="Bearer "+this.accessToken,(yield e(t)).data}return i}return 200!==r.code&&this.ConfigService.setItem("errorLog",JSON.stringify({request:t.data,url:t.url,result:r,requestID:i})),r}catch(e){return console.error("Request execution error:",e),{code:503,message:"network error",data:null}}}))}requestWithStream(e,t,i){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 o="req-"+Date.now().toString(36)+"-"+Math.random().toString(36).substring(2,11);return new Promise(((s,n)=>{const a=new i(oe+e.url,{headers:{"Content-Type":"application/json",Authorization:"Bearer "+r,"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 i=JSON.parse(e.data);i.done?(a.close(),s(i)):(402===i.code&&(yield this.refreshUserToken()),t(i.data))})))),a.addEventListener("error",(e=>{if(console.info("Error:",e),!e.data)return;const t=JSON.parse(e.data);s(t),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 i="";try{i=(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);return new Promise(((o,s)=>v(this,void 0,void 0,(function*(){const s=yield fetch(oe+e.url,{method:"POST",headers:{"Content-Type":"text/event-stream",Authorization:"Bearer "+i,"X-Request-ID":r},body:JSON.stringify(e.data)});if(!s.body)throw new Error("Response body is null");const n=s.body.pipeThrough(new TextDecoderStream).getReader();for(;;){const{value:e,done:i}=yield n.read();if(i){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 i=JSON.parse(e.substring(5));t(i.data)}}))}o({code:200,data:{done:!0}})}))))}finally{this.streamPromise=null}})))()),this.streamPromise}))}}class ne extends se{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)}))}getSyncData(){return v(this,void 0,void 0,(function*(){return yield this.requestWithRetry({method:"get",url:"/api/v1/pro/thirdparty/get_sync_data"})}))}updateSyncData(e){return v(this,void 0,void 0,(function*(){const t={method:"post",url:"/api/v1/pro/thirdparty/update_sync_data",data:e};return yield this.requestWithRetry(t)}))}}const ae=new g;class de{static encrypt(e,t){let i="";for(let r=0;r-1&&i.splice(r,1),this.setAllListConfig(i,t)}static setListConfig(e,t){let i=this.getAllListConfig(t);const r=i.indexOf(e);r>-1?(i.splice(r,1),i.unshift(e)):i.unshift(e),this.setAllListConfig(i,t)}static setAllListConfig(e,t,i=!0){this.setItem(t,JSON.stringify(e)),i&&this.setSyncRecord({type:"config",catergory:"listConfig",name:"general",key:t},{operation:"update",time:Date.now()})}static setObjectConfig(e,t,i,r=!0){let o=this.getAllObjectConfig(i);o[e]=t,r&&this.setSyncRecord({type:"config",catergory:"objectConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllObjectConfig(o,i)}static getObjectConfig(e,t,i){return this.getAllObjectConfig(t)[e]||i}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 i=this.getAllObjectConfig(t);delete i[e],this.setSyncRecord({type:"config",catergory:"objectConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllObjectConfig(i,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,i){let r=this.getAllMapConfig(i);void 0===r[e]&&(r[e]=[]),t&&-1===r[e].indexOf(t)&&r[e].unshift(t),this.setSyncRecord({type:"config",catergory:"mapConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(r,i)}static setOneMapConfig(e,t,i,r=!0){let o=this.getAllMapConfig(i);o[e]=t,r&&this.setSyncRecord({type:"config",catergory:"mapConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(o,i)}static deleteFromMapConfig(e,t,i){let r=this.getAllMapConfig(i),o=r[e].indexOf(t);r[e].splice(o,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:i,key:e},{operation:"update",time:Date.now()}),this.setAllMapConfig(r,i)}static deleteFromAllMapConfig(e,t){let i=this.getAllMapConfig(t);Object.keys(i).forEach((r=>{let o=i[r].indexOf(e);o>-1&&(i[r].splice(o,1),this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:r},{operation:"update",time:Date.now()}))})),this.setAllMapConfig(i,t)}static deleteMapConfig(e,t){let i=this.getAllMapConfig(t);delete i[e],this.setSyncRecord({type:"config",catergory:"mapConfig",name:t,key:e},{operation:"delete",time:Date.now()}),this.setAllMapConfig(i,t)}static getFromAllMapConfig(e,t){let i=this.getAllMapConfig(t),r=[];for(let t in i)i[t]&&i[t].indexOf(e)>-1&&r.push(t);return r}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 i=JSON.parse(this.getItem("syncRecord")||"{}");i[e.type+"."+e.catergory+"."+e.name+"."+e.key]=t,this.setItem("syncRecord",JSON.stringify(i))}static setAllSyncRecord(e){this.setItem("syncRecord",JSON.stringify(e))}});var he,ue;export{le as ConfigService,re as SqlStatement,Y as SyncUtil,ne as ThirdpartyRequest,de as TokenService}; diff --git a/src/assets/lib/kookit.min.js b/src/assets/lib/kookit.min.js index 8a8f2b44..662eceac 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.id="kookit-iframe",i.style.verticalAlign="baseline",e.innerHTML="",e.appendChild(i)},y=(e,t,i)=>{let r=Math.floor(i.clientWidth/12),n=r%2==0?r:r-1;return{totalPage:"scroll"===e?1:"single"===e?Math.round(parseFloat(t.body.scrollWidth/(t.body.clientWidth+n)+"")):2*Math.round(parseFloat(t.body.scrollWidth/(t.body.clientWidth+n)+"")),currentPage:Math.round(parseFloat(h(t.body.scrollLeft)/(t.body.clientWidth+n)+""))+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})),w=(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 v(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:none; overscroll-behavior: none;max-width: inherit;column-fill: auto;column-gap: ${s}px; column-width: ${(e.clientWidth-s)/n}px;`)};function L(e){const t=e.getSelection();if(!t)return null;if(t.rangeCount>0){return t.getRangeAt(0).startContainer.parentElement}return null}const C=e=>"string"==typeof e||e instanceof String;class T{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 M=(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/,D=/^epubcfi\((.*)\)$/,k=e=>e.replace(/[\^[\](),;=]/g,"^$&"),A=(e,t)=>{return i=([e])=>e===t,e.map(((e,t,r)=>i(e,t,r)?t:null)).filter((e=>null!=e));var i},I=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},E=e=>M(e,A(e,"!")).map(I),N=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(D)?.[1]??i));var i;const r=A(t,",");if(!r.length)return E(t);const[n,o,s]=M(t,r).map(E);return{parent:n,start:o,end:s}},R=({index:e,id:t,offset:i,temporal:r,spatial:n,text:o,side:s})=>{const a=s?`;s=${s}`:"";return`/${e}`+(t?`[${k(t)}${a}]`:"")+(null!=i&&e%2?`:${i}`:"")+(r?`~${r}`:"")+(n?`@${n.join(":")}`:"")+(o||!t&&s?"["+(o?.map(k)?.join(",")??"")+a+"]":"")},B=e=>e.parent?[e.parent,e.start,e.end].map(B).join(","):e.map((e=>e.map(R).join(""))).join("!"),O=e=>{return t=B(e),D.test(t)?t:`epubcfi(${t})`;var t},P=(e,t)=>{return"string"==typeof e?O(P(N(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,F=({nodeType:e})=>1===e,W=e=>{const t=Array.from(e.childNodes).filter((e=>H(e)||F(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):F(i)?e.push(null,t):e.push(t):e.push(t),e}),[]);return F(t[0])&&t.unshift("first"),F(t[t.length-1])&&t.push("last"),t.unshift("before"),t.push("after"),t},$=(e,t)=>e?W(e)[t]:null,j=(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}},U=(e,t)=>{const{parentNode:i,id:r}=e,n=W(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?U(i).concat(a):[a]},q=(e,t)=>j(e.documentElement,P(t)).node,z="urn:oasis:names:tc:opendocument:xmlns:container",X="http://www.w3.org/1999/xhtml",V="http://www.idpf.org/2007/opf",J="http://www.idpf.org/2007/ops",G="http://purl.org/dc/elements/1.1/",_="http://www.w3.org/2001/04/xmlenc#",Y="http://www.daisy.org/z3986/2005/ncx/",Z="http://www.w3.org/1999/xlink",K="http://www.w3.org/ns/SMIL",Q={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)/},ee=e=>e.toLowerCase().replace(/[-:](.)/g,((e,t)=>t.toUpperCase())),te=(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,ie=(...e)=>t=>t?Object.fromEntries(e.map((e=>[ee(e),t.getAttribute(e)]))):null,re=e=>{return t=e?.textContent,t?t.trim().replace(/\s{2,}/g," "):"";var t},ne=(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)]}},oe=(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}},se=e=>/^(?!blob)\w+:/i.test(e),ae=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()))},le=e=>e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),ce={attrs:["dir","xml:lang"]},de={name:"alternate-script",many:!0,...ce,props:["file-as"]},he={many:!0,...ce,props:[{name:"role",many:!0,attrs:["scheme"]},"file-as",de]},ue=[{name:"title",many:!0,...ce,props:["title-type","display-seq","file-as",de]},{name:"identifier",many:!0,props:[{name:"identifier-type",attrs:["scheme"]}]},{name:"language",many:!0},{name:"creator",...he},{name:"contributor",...he},{name:"publisher",...ce,props:["file-as",de]},{name:"description",...ce,props:[de]},{name:"rights",...ce,props:[de]},{name:"date"},{name:"dcterms:modified",type:"meta"},{name:"subject",many:!0,...ce,props:["term","authority",de]},{name:"belongs-to-collection",type:"meta",many:!0,...ce,props:["collection-type","group-position","dcterms:identifier","file-as",de,{name:"belongs-to-collection",recursive:!0}]}],fe=(e,t=e=>e)=>{const{$:i,$$:r,$$$:n}=ne(e,X),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:re(n)||n?.getAttribute("title"),href:a,subitems:s(o)};return e&&(l.type=n?.getAttributeNS(J,"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(J,"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:re(e.firstElementChild),type:t,list:a(e)})}return{toc:c,pageList:d,landmarks:h,others:u}},pe=(e,t=e=>e)=>{const{$:i,$$:r}=ne(e,Y),n=e=>{const o=i(e,"navLabel"),s=i(e,"content"),a=re(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:re(i(e,"navLabel")),list:o(e,"navTarget")})))}},ge=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)},me=/([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/,ye=e=>re(e.getElementById(e.documentElement.getAttribute("unique-identifier"))??e.getElementsByTagNameNS(G,"identifier")[0]),be=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=ve)=>({"http://www.idpf.org/2008/embedding":{key:t=>e(ye(t).replaceAll(/[\u0020\u0009\u000d\u000a]/g,"")),decode:(e,t)=>be(e,1040,t)},"http://ns.adobe.com/pdf/enc#RC":{key:e=>{const t=(e=>{for(const t of e.getElementsByTagNameNS(G,"identifier")){const[e]=re(t).split(":").slice(-1);if(me.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)=>be(e,1024,t)}});class xe{#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(_,"EncryptedData"),(e=>({algorithm:e.getElementsByTagNameNS(_,"EncryptionMethod")[0]?.getAttribute("Algorithm"),uri:e.getElementsByTagNameNS(_,"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 Le{constructor({opf:e,resolveHref:t}){this.opf=e;const{$:i,$$:r,$$$:n}=ne(e,V),o=i(e.documentElement,"manifest"),s=i(e.documentElement,"spine"),a=r(s,"itemref");this.manifest=r(o,"item").map(ie("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(ie("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===Q.NCX)))?.href;const l=i(e.documentElement,"guide");l&&(this.guide=r(l,"reference").map(ie("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(te("name","cover"))?.getAttribute("content"))??this.getItemByID("cover")??this.getItemByID("cover.jpg")??this.getItemByID("cover.png")??this.getItemByID("cover.jpeg")??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=U(i);for(const[n,o]of W(i).entries()){const i=e[t.length];o===i&&t.push(O([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=N(e),i=(t.parent??t).shift();let r=q(this.opf,i);r&&"idref"!==r.nodeName&&(i.at(-1).id=null,r=q(this.opf,i));const n=r?.getAttribute("idref");return{index:this.spine.findIndex((e=>e.idref===n)),anchor:e=>((e,t)=>{const i=P(t),r=P(t,!0),n=e.documentElement,o=j(n,i[0]),s=j(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=Q.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||[Q.XHTML,Q.HTML,Q.CSS,Q.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(se(e))return e;const r=oe(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([Q.XHTML,Q.HTML,Q.SVG].includes(r)){let s=(new DOMParser).parseFromString(o,r);if(r===Q.XHTML&&s.querySelector("parsererror")&&(console.warn(s.querySelector("parsererror").innerText),e.mediaType=Q.HTML,s=(new DOMParser).parseFromString(o,e.mediaType)),[Q.XHTML,Q.SVG].includes(e.mediaType)){let e=s.firstChild;for(;e instanceof ProcessingInstruction;){if(e.data){const r=await ae(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(Z,"href",await this.loadHref(e.getAttributeNS(Z,"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===Q.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 ae(e,/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,((e,r)=>this.loadHref(r,t,i).then((e=>`url("${e}")`)))),n=await ae(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(le).join("|"),"g");return ae(e,o,(async e=>this.loadItem(r.get(e.replace(/^\//,"")),i.concat(t))))}unloadItem(e){this.unref(e?.href)}}const Te=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 Me{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 xe(we(r))}#a(e){return e&&e.includes("opf:scheme")&&(e=e.replaceAll("opf:scheme","scheme")),e?this.parser.parseFromString(e,Q.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(z,"rootfile"),ie("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 Le({opf:r,resolveHref:e=>oe(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:Te(n),resolveHref:e=>oe(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=>oe(e,s),t=fe(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=>oe(e,a),t=pe(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}=ne(e,V),r=t(e.documentElement,"metadata"),n=Array.from(r.children),o=(e,t)=>{if(!t)return null;const{props:i=[],attrs:r=[]}=e,s=re(t);if(!i.length&&!r.length)return s;const a=t.getAttribute("id"),l=a?n.filter(te("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=te("property",n),a=r?e:t;return[ee(n),i?l.filter(s).map((e=>o(a,e))):o(a,l.find(s))]}))).concat(r.map((e=>[ee(e),t.getAttribute(e)]))))},s=n.filter(te("refines",null)),a=e=>Object.fromEntries(i(r,"meta").filter(te("property",(t=>t?.startsWith(e)))).map((t=>[t.getAttribute("property").replace(e,""),re(t)])));return{metadata:Object.fromEntries(ue.map((e=>{const{type:t,name:i,many:r}=e,n="meta"===t?e=>e.namespaceURI===V&&e.getAttribute("property")===i:e=>e.namespaceURI===G&&e.localName===i;return[ee(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=ge(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:ye(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}=ne(e,K);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:ge(n.getAttribute("clipBegin")),clipEnd:ge(n.getAttribute("clipEnd"))}}:{id:r};var o}))})(await this.#l(i.href),(e=>oe(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 se(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="",r)=>{const n=(new DOMParser).parseFromString(t?$e(e,i,r):e,"text/html");let o=Ee(n);0===o.length&&(o=qe(n));for(let e=0;e""};return c.sections=l.map((e=>({id:e.index,load:()=>{return t=e.index,d(void 0,void 0,void 0,(function*(){return URL.createObjectURL(new Blob([l[t].text],{type:"text/html"}))}));var t},unload:()=>{e.index}}))),c.toc=l.map((e=>({label:e.label,href:"title"+e.index}))).filter((e=>""!==e.label)),c.rendition={layout:"pre-paginated"},c.resolveHref=e=>({index:parseInt(e.substring(5,e.length))}),c.splitTOCHref=e=>[e,null],c.getTOCFragment=e=>e.documentElement,c};let De=["章","节","回","節","卷","部","輯","辑","話","集","话","篇"," "," "],ke=[],Ae=["CHAPTER","Chapter","序章","前言","声明","写在前面的话","后记","楔子","后序","章节目录","尾声"],Ie=[" "," ","、","·",".",":",":"];const Ee=e=>Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,title")),Ne=e=>e.trim().replace(/(\r\n|\n|\r|\t)/gm,"").substring(0,100).split("").filter((e=>"="!==e&&"-"!==e&&"_"!==e&&"+"!==e)).join(""),Re=(e,t="")=>t?new RegExp(t).test(e):e&&e.length<40&&!Be(e)&&(Oe(e)||e.startsWith("第")&&He(e)||e.startsWith("卷")&&Fe(e)||e.indexOf("第")>-1&&e.lastIndexOf("第")<4&&He(e.substr(e.indexOf("第")))||Pe(e)),Be=e=>ke.filter((t=>e.indexOf(t)>-1)).length>0,Oe=t=>Ae.filter((i=>t.startsWith(i)||t.startsWith(e.s2t(i))||t.startsWith(e.t2s(i)))).length>0,Pe=e=>Ie.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)))),We=e=>{let t=[],i=e.split(" ").filter((e=>""!==e.trim())),r=i.map((e=>je(e)||Ue(e)));return t=i.map(((e,t)=>({index:t,label:r[t],text:e,href:"title"+t}))),t},$e=(e,t,i)=>{let r=e.split("\n");1===r.length&&(r=e.split("\r"));const n=[];let o=!1;if(i&&i.refresh&&(o=!0),r.length>1e4&&!o){i&&i.text||(i={text:r[0],chapterTitle:"",chapterDocIndex:0});let e=r.findIndex((e=>Ne(e)===Ne(i.text)));-1===e&&(e=0);const o=Math.max(e-1e3,0),s=Math.min(e+1e3,r.length),a=r.slice(o,s),l=a.filter((e=>{const i=Ne(e);return i&&Re(i,t)})),c=new Set(l.map((e=>Ne(e))));let d=l.findIndex((e=>Ne(e)===Ne(i.chapterTitle)));if(-1===d&&(d=0),d0)for(let t=0;tChapter ${t}`),n.push(`

Chapter ${t}

`)}for(const e of a){const t=Ne(e);t&&c.has(t)?n.push(`

${t}

`):n.push(`

${e}

`)}}else for(const e of r){const i=Ne(e);i&&Re(i,t)?n.push(`

${i}

`):n.push(`

${e}

`)}const s=n.join("");return s||`

Title

${e}

`},je=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())||""},Ue=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())||""},qe=e=>{let t=e.getElementsByTagName("*"),i=Array.from(t).filter((e=>1===e.childNodes.length&&e.childNodes[0].nodeType===Node.TEXT_NODE&&Re(Ne(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,kookitmarker")),Ve=(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"})})),Je=(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})},Ge=(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=Je(t,l,i,"prev");c&&(o.text="prevChapter",o.page="",yield _e(c.index,c.label,c.href,i,e,r,n,o,s,a))})),_e=(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)}(-1===e||e>n.length-1)&&(e=0);let f=yield u(n[e].text,!1),p=function(e){const t=e.match(/]*)>/i);if(!t)return{};const i=t[1],r={},n=/([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^>\s]+))/g;let o;for(;null!==(o=n.exec(i));){const e=o[2]||o[3]||o[4]||"";r[o[1]]=e}return r}(f);c.body.innerHTML=f,p.style?c.body.setAttribute("style",p.style+" "+c.body.getAttribute("style")):p.class?c.body.setAttribute("class",p.class):p.id?c.body.setAttribute("id",p.id):p.class?p.id||c.body.removeAttribute("id"):c.body.removeAttribute("class"),yield Ye(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.race([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)))}))))),new Promise(((e,t)=>{setTimeout((()=>{console.info("image load timeout"),e("image load timeout")}),3e3)}))]),yield w(e,t,i,n),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 r.height=n.body.scrollHeight+"px",r.height=n.body.scrollHeight+300+"px"})))(o,s,a,h,c),yield Ze(o,s,"","","","",c)}));const Ye=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)}})),Ze=(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=Xe(a.body).filter(((t,i)=>Ne(t.textContent)&&(Ne(t.textContent)===Ne(r)||Ne(t.textContent)===e.t2s(Ne(r))||Ne(t.textContent)===e.s2t(Ne(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}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}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(ze)return;let l=Xe(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{ze=!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=Je(t,l,i,"next");c&&(o.page="",yield _e(c.index,c.label,c.href,i,e,r,n,o,s,a))})),nt=(e,t,i)=>Xe(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|kookitmarker|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};class at{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 lt=Node.ELEMENT_NODE,ct=Node.TEXT_NODE,dt=Node.CDATA_SECTION_NODE;function ht(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 ct:case dt: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===ct||e.nodeType===dt)}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===lt){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 gt=["color-0","color-1","color-2","color-3","line-0","line-1","line-2","line-3"],mt=["#FEF3CD","#FBFACC","#CEFACD","#CDE9FA"],yt=["#FF0000","#000080","#0000FF","#2EFF2E"],bt=["#fac106","#ebe702","#0be603","#0493e6"],vt=(e,t,r,n,o,s)=>{var a,l;i.init();let c=gt[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=Tt(f),g=0;g{let a=gt[t],l=s.querySelector(".noteLayer"),c=s.querySelector("#koodoPDFLayer");var d=n.getViewport({scale:o});for(let t=0;t-1?"background-color: ":"border-bottom: ")+(a.indexOf("color")>-1?bt[a.split("-")[1]]:`2px solid ${yt[a.split("-")[1]]}`)+"; left:"+(Math.min(h[0],h[2])+parseFloat(getComputedStyle(c).marginLeft))+"px; top:"+Math.min(h[1],h[3])+"px;width:"+Math.abs(h[0]-h[2])+"px; height:"+Math.abs(h[1]-h[3])+"px; z-index: 1; cursor: pointer; opacity: "+(a.indexOf("color")>-1?.3:1)+";"),null==u||u.setAttribute("data-key",i),null==u||u.setAttribute("class","kookit-note"),null==u||u.addEventListener("click",(e=>{e&&e.target&&e.target.dataset&&e.target.dataset.key&&r(e)})),u.ontouchend=e=>{e&&e.target&&e.target.dataset&&e.target.dataset.key&&r(e),e.preventDefault(),e.stopPropagation()},l.appendChild(u))}}},xt=e=>{const t=e.querySelectorAll(".kookit-note");for(let e=0;e{const o=Ct(e.getClientRects());for(let e=0;e-1?"background-color: ":"border-bottom: ")+(t.indexOf("color")>-1?mt[t.split("-")[1]]+";opacity: 1":`2px solid ${yt[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;opacity: "+(t.indexOf("color")>-1?.8:1)+"; cursor: pointer;"),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)}},Ct=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"),u+1{console.info("flipToPrevPage"),u-1>=0&&(m[u-1].target=1,u=Math.max(u-1,0))},mouseDownHandler:L,mouseUpHandler:C,mouseMoveHandler:x}}}function x(e){if(!y)return;const t=e.touches[0],i=t.screenX,r=t.screenY;g.x=i-y.offsetLeft-o/2,g.y=r-y.offsetTop}function L(e){const t=e.touches[0];c=t.screenX,t.screenX=0?m[u-1].dragging=!0:t.screenX>window.screen.width/2&&u+1a/4*1&&d-c>0?(m[i].target=1,u=Math.max(u-1,0)):i===u?m[i].target=1:i===u-1&&(m[i].target=-1)),m[i].dragging=!1}function T(e){var r=1-Math.abs(e.progress),n=.5*a*(1-e.progress),s=a*e.progress+n,c=20*r,d=.5*a*Math.max(Math.min(1-e.progress,.5),0),u=.5*a*Math.max(Math.min(r,.5),0),f=.5*a*Math.max(Math.min(r,.5),0);e.page.style.width=Math.max(s,0)+"px",p.save(),p.translate(0+o/2,h+0),p.strokeStyle=("no"===t?"rgba(0,0,0,":"rgba(255,255,255,")+.05*r+")",p.lineWidth=30*r,p.beginPath(),p.moveTo(s-n,.5*-c),p.lineTo(s-n,l+.5*c),p.stroke();var g=p.createLinearGradient(s,0,s+u,0);g.addColorStop(0,("no"===t?"rgba(0,0,0,":"rgba(255,255,255,")+.2*r+")"),g.addColorStop(.8,("no"===t?"rgba(0,0,0,":"rgba(255,255,255,")+"0.0)"),p.fillStyle=g,p.beginPath(),p.moveTo(s,0),p.lineTo(s+u,0),p.lineTo(s+u,l),p.lineTo(s,l),p.fill();var m=p.createLinearGradient(s-n-f,0,s-n,0);m.addColorStop(0,("no"===t?"rgba(0,0,0,":"rgba(255,255,255,")+"0.0)"),m.addColorStop(1,("no"===t?"rgba(0,0,0,":"rgba(255,255,255,")+.15*+r+")"),p.fillStyle=m,p.beginPath(),p.moveTo(s-n-f,0),p.lineTo(s-n,0),p.lineTo(s-n,l),p.lineTo(s-n-f,l),p.fill();var y=p.createLinearGradient(s-d,0,s,0);i?(y.addColorStop(.35,i),y.addColorStop(.73,i),y.addColorStop(.9,i),y.addColorStop(1,i)):"no"===t?(y.addColorStop(.35,"#fafafa"),y.addColorStop(.73,"#eeeeee"),y.addColorStop(.9,"#fafafa"),y.addColorStop(1,"#e2e2e2")):(y.addColorStop(.35,"#333"),y.addColorStop(.73,"#444"),y.addColorStop(.9,"#333"),y.addColorStop(1,"#444")),p.fillStyle=y,p.strokeStyle=("no"===t?"rgba(0,0,0,":"rgba(255,255,255,")+"0.06)",p.lineWidth=.5,p.beginPath(),p.moveTo(s,0),p.lineTo(s,l),p.quadraticCurveTo(s,l+2*c,s-n,l+c),p.lineTo(s-n,-c),p.quadraticCurveTo(s,2*-c,s,0),p.fill(),p.stroke(),p.restore()}},St=(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})),Dt=(e,t)=>{var i;const r=t.getElementById("pdf-container-"+e);if(!r)return;let n=document.createElement("iframe");n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",n.style.height="100%",n.style.border="0",n.style.margin="0",n.style.padding="0",n.style.fontSize="100%",n.style.font="inherit",n.scrolling="no",n.tabIndex=0,n.id="pdf-iframe-"+e;let o=document.createElement("style");return o.id="default-style",o.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}",r.appendChild(n),null===(i=n.contentDocument)||void 0===i||i.head.appendChild(o),n},kt=(e,t,i)=>d(void 0,void 0,void 0,(function*(){let r=i.getElementById("pdf-container-"+e);if(r){if("scroll"!==t){let e=r?h(r.offsetLeft)-h(r.marginLeft||parseFloat(getComputedStyle(r).marginLeft)):0;i.body.scrollTo(e,0)}else r.scrollIntoView();r.scrollIntoView()}})),At=(e,t,i)=>{var r=!1,n=t.getBoundingClientRect();if("scroll"!==i){let t=n.left;r=t>-10&&t<=e.clientWidth}else{let t=n.top,i=n.bottom;r=t-10>=e.scrollTop&&t+10<=e.scrollTop+e.clientHeight||i-10>=e.scrollTop&&i+10<=e.scrollTop+e.clientHeight||t+10<=e.scrollTop&&i-10>=e.scrollTop+e.clientHeight}return r},It=(e,t,i,r,n,o,s,a,l)=>d(void 0,void 0,void 0,(function*(){let c=Math.floor(e.clientWidth/12),d=c%2==0?c:c-1;const h=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))}if(i>0)if("single"===l){let e=r.querySelector("#pdf-container-"+(a-1));e&&e.scrollIntoView()}else r.body.scrollBy(-(h+d)/2,0);else if(i<0)if("single"===l){let e=r.querySelector("#pdf-container-"+(a+1));e&&e.scrollIntoView()}else r.body.scrollBy((h+d)/2,0)}));function Et(){return window.visualViewport?window.visualViewport.offsetLeft:window.pageXOffset||document.documentElement.scrollLeft||0}function Nt(){return window.visualViewport?window.visualViewport.offsetTop:window.pageYOffset||document.documentElement.scrollTop||0}const Rt=e=>{const t=e.target;if(!t)return;const i=function(e){if("A"===e.tagName)return e;let t=e;for(;t&&"BODY"!==t.tagName;){if("A"===t.tagName)return t;t=t.parentElement}return null}(t);if(i){e.preventDefault(),e.stopPropagation();const t=i.getAttribute("href");return window.ReactNativeWebView.postMessage(JSON.stringify({event:"link-clicked",href:t})),!1}};const Bt=(e,t,r,n,o,s,a)=>{var l;let c=t.contentWindow||(null===(l=t.contentDocument)||void 0===l?void 0:l.defaultView),h=a.getDocument(),u=0,f=0,p=0,g=0;let m=Math.floor(r.clientWidth/12),y=m%2==0?m:m-1,b=!1,v=0;e.addEventListener("touchend",(function(t){console.info("touchend");let i=(new Date).getTime();if(i-g<=300)return void t.preventDefault();g=i;const l=t.changedTouches[0],d=Date.now();let m=l.screenX,v=l.screenY;const x=d-u,L=m-f,C=v-p;if(b&&"mimical"===o&&"scroll"!==n)return b=!1,a.mouseUpHandler(t),l.screenXwindow.screen.width/4*1&&m-f>0&&a.prev(),void setTimeout((()=>{let e=document.getElementById("book");e&&(e.style.display="none")}),400);if(b&&"sliding"===o&&"scroll"!==n){let I="PDF"===s?h:e;if(window.scrollAnimationId&&cancelAnimationFrame(window.scrollAnimationId),Math.abs(I.body.scrollWidth-I.body.scrollLeft-r.clientWidth)<10)return w&&clearTimeout(w),void(w=setTimeout((()=>{a.next()}),300));if(0===I.body.scrollLeft)return w&&clearTimeout(w),void(w=setTimeout((()=>{a.prev()}),300));I.body.style.transform="";let E,N=r.clientWidth+y,R=I.body.scrollLeft;const B=Math.round(R/N),O=Math.abs(L)/window.screen.width,P=.1;E=L>0&&O>P?(B-1)*N:L<0&&O>P?(B+1)*N:B*N,E=Math.max(0,Math.min(E,I.body.scrollWidth-N)),I.body.scrollWidth-E1-Math.pow(1-e,3);function U(e){const t=e-H;if(t>=$)return I.body.scrollLeft=E,I.body.style.willChange="auto",a.record(),void(b=!1);const i=j(t/$),r=F+W*i;I.body.scrollLeft=r,window.scrollAnimationId=requestAnimationFrame(U)}window.scrollAnimationId=requestAnimationFrame(U)}else{var T=c.getSelection().toString();if(T)window.ReactNativeWebView.postMessage(JSON.stringify({event:"select-text-after-touch",selectedText:T}));else if(x<500&&Math.abs(L)<30&&Math.abs(C)<30){var M=window.screen.width/3,S=window.screen.height/3,D=Math.floor(m/M),k=Math.floor(v/S),A="";0===k&&(0===D||1===D)||1===k&&0===D||2===k&&0===D||0===k&&1===D?A="left":1===k&&1===D?A="center":(0===k&&2===D||1===k&&2===D||2===k&&2===D||2===k&&1===D)&&(A="right"),window.ReactNativeWebView.postMessage(JSON.stringify({event:A}))}else(Math.abs(L)>=30||Math.abs(C)>=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"})))}}),!1),e.addEventListener("touchstart",(function(e){if(!1===Rt(e))return;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];u=Date.now(),f=i.screenX,p=i.screenY}),!1),e.addEventListener("touchmove",(function(t){if(!b&&Math.abs(t.touches[0].screenX-f)<=10)return;if(t.preventDefault(),window.visualViewport.scale>1&&"PDF"===s)return void t.preventDefault();const i=t.touches[0],r=i.screenX,l=i.screenY,c=r-f,d=l-p;if(!b&&Math.abs(c)>Math.abs(d)&&Math.abs(c)>10){if(b=!0,v=r,e.body.style.transform="translateZ(0)","mimical"===o&&"scroll"!==n){window.ReactNativeWebView.postMessage(JSON.stringify({event:"swipe-start"}));let e=document.getElementById("book");e&&(e.style.display="block",a.mouseDownHandler(t))}}else if(b&&"mimical"===o&&"scroll"!==n&&a.mouseMoveHandler(t),b&&"sliding"===o&&"scroll"!==n){let t="PDF"===s?h:e;const i=r-v,n=t.body.scrollLeft;t.body.scrollLeft=n-i,v=r,requestAnimationFrame((()=>{}))}}),!1),e.addEventListener("click",Rt,!0);let w=null;e.body.oncontextmenu=function(e){return e.preventDefault(),e.stopPropagation(),!1};let x=0,L=0,C=0;e.addEventListener("selectstart",(t=>{L=Et(),C=Nt(),"scroll"!==n&&(x=e.body.scrollLeft)}),!1),e.addEventListener("selectionchange",(t=>{x>0&&(e.body.scrollLeft=x),w&&clearTimeout(w),w=setTimeout((()=>d(void 0,void 0,void 0,(function*(){var e;const n=c.getSelection().toString().trim();if(n){var o=c.getSelection().getRangeAt(0);let h=a.getPageSize();var l=o.getBoundingClientRect();if("PDF"===s){let e=o.getClientRects();if(e.length>0){e=Array.from(e).filter((e=>Math.abs(e.height-h.sectionHeight)>10&&Math.abs(e.width-h.sectionWidth)>10&&e.height>0&&e.width>0));let t=1/0,i=1/0,r=-1/0,n=-1/0;for(let o=0;o{var l;let c=t.contentWindow||(null===(l=t.contentDocument)||void 0===l?void 0:l.defaultView),h=a.getDocument(),u=0,f=0,p=0,g=0;let m=Math.floor(r.clientWidth/12),y=m%2==0?m:m-1,b=!1,v=0;e.addEventListener("touchend",(function(t){var l,m;return d(this,void 0,void 0,(function*(){let d=(new Date).getTime();if(d-g<=300)return void t.preventDefault();g=d;const v=t.changedTouches[0],x=Date.now(),L=v.screenX,C=v.screenY,T=x-u,M=L-f,S=C-p;if(b&&"mimical"===o&&"scroll"!==n)return b=!1,a.mouseUpHandler(t),Lwindow.screen.width/4*1&&L-f>0&&a.prev(),void setTimeout((()=>{let e=document.getElementById("book");e&&(e.style.display="none")}),400);if(b&&"sliding"===o&&"scroll"!==n){let E="PDF"===s?h:e;if(window.scrollAnimationId&&cancelAnimationFrame(window.scrollAnimationId),Math.abs(E.body.scrollWidth-E.body.scrollLeft-r.clientWidth)<10)return w&&clearTimeout(w),void(w=setTimeout((()=>{a.next()}),300));if(0===E.body.scrollLeft)return w&&clearTimeout(w),void(w=setTimeout((()=>{a.prev()}),300));E.body.style.transform="";let N,R=r.clientWidth+y,B=E.body.scrollLeft;const O=Math.round(B/R),P=Math.abs(M)/window.screen.width,H=.1;N=M>0&&P>H?(O-1)*R:M<0&&P>H?(O+1)*R:O*R,N=Math.max(0,Math.min(N,E.body.scrollWidth-R)),E.body.scrollWidth-N1-Math.pow(1-e,3);function q(e){const t=e-F;if(t>=j)return E.body.scrollLeft=N,E.body.style.willChange="auto",a.record(),void(b=!1);const i=U(t/j),r=W+$*i;E.body.scrollLeft=r,window.scrollAnimationId=requestAnimationFrame(q)}return void(window.scrollAnimationId=requestAnimationFrame(q))}const D=c.getSelection().toString().trim();if(D){var k=c.getSelection().getRangeAt(0).getBoundingClientRect(),A=a.getPageSize(),I={top:k.top-r.scrollTop,left:k.left,width:k.width,height:k.height,screenWidth:window.innerWidth,screenHeight:window.innerHeight,sectionHeight:A.sectionHeight,chapterDocIndex:0,sectionWidth:A.sectionWidth,gap:A.gap,scale:window.visualViewport.scale,offsetLeft:Et(),offsetTop:Nt()};i.init();let z=null;if("PDF"===s){let X=t.target.ownerDocument,V=null===(l=null==X?void 0:X.defaultView)||void 0===l?void 0:l.frameElement,J=(null==V?void 0:V.getAttribute("id"))||"",G=J?parseInt(J.split("-").reverse()[0]):0;I.chapterDocIndex=G,z=yield a.getHightlightCoords(G);let _=V.parentElement;_&&(I.top=I.top+parseFloat(getComputedStyle(_).top))}else z=yield a.getHightlightCoords();window.ReactNativeWebView.postMessage(JSON.stringify({event:"select-text",selectedText:D,position:I,range:z}))}else if(T<500&&Math.abs(M)<30&&Math.abs(S)<30){const Y=document.documentElement.clientWidth;document.documentElement.clientHeight;let Z=Math.min(Math.max(L,0),Y);if("PDF"===s&&"double"===n){let te=t.target.ownerDocument,ie=null===(m=null==te?void 0:te.defaultView)||void 0===m?void 0:m.frameElement,re=(null==ie?void 0:ie.getAttribute("id"))||"";(re?parseInt(re.split("-").reverse()[0]):0)%2==1&&(Z+=Y/2)}let K="";const Q=Y/3,ee=Math.min(Math.floor(Z/Q),2);0===ee?K="left":1===ee?K="center":2===ee&&(K="right"),window.ReactNativeWebView.postMessage(JSON.stringify({event:K}))}else(Math.abs(M)>=30||Math.abs(S)>=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"})))}))}),!1),e.addEventListener("touchstart",(function(e){if(!1===Rt(e))return;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];u=Date.now(),f=i.screenX,p=i.screenY}),!1),e.addEventListener("touchmove",(function(t){const i=c.getSelection().toString().trim();if(!b&&Math.abs(t.touches[0].screenX-f)<=10||i)return;if(window.visualViewport.scale>1&&"PDF"===s)return void t.preventDefault();t.preventDefault();const r=t.touches[0],l=r.screenX,d=r.screenY,u=l-f,g=d-p;if(!b&&Math.abs(u)>Math.abs(g)&&Math.abs(u)>10){if(b=!0,v=l,"mimical"===o&&"scroll"!==n){window.ReactNativeWebView.postMessage(JSON.stringify({event:"swipe-start"}));let e=document.getElementById("book");e&&(e.style.display="block",a.mouseDownHandler(t))}}else if(b&&"mimical"===o&&"scroll"!==n&&a.mouseMoveHandler(t),b&&"sliding"===o&&"scroll"!==n){let t="PDF"===s?h:e;const i=l-v,r=t.body.scrollLeft;t.body.scrollLeft=r-i,v=l,requestAnimationFrame((()=>{}))}}),!1),e.addEventListener("click",Rt,!0);let w=null;e.addEventListener("touchmove",(e=>{}),!1),e.body.oncontextmenu=function(e){return e.preventDefault(),e.stopPropagation(),!1}};class Pt extends at{constructor(t){super(),this.tsTransform=()=>{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,kookitmarker").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,kookitmarker").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=>{},this.touchEventSet={},"yes"===this.isMobile&&(console.log=function(...e){window.ReactNativeWebView.postMessage(e.map((e=>String(e))).join(", "))},console.info=function(...e){window.ReactNativeWebView.postMessage(e.map((e=>String(e))).join(", "))},console.error=function(...e){window.ReactNativeWebView.postMessage(e.map((e=>String(e))).join(", "))})}getPageSize(){let e="double"===this.readerMode?2:1,t=Math.floor(this.element.clientWidth/12),i=t%2==0?t:t-1,r=this.getIframe();if(!r)return;let n=null==r?void 0:r.getBoundingClientRect().height;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,sectionHeight:n,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 _e(parseInt(e),i,t,this.chapterDocList,this.element,this.readerMode,this.format,this.tempLocation,r,n),t&&t.indexOf("#")>-1&&(yield Ze(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,percentage:r.percentage};let{text:n,chapterTitle:o,chapterDocIndex:s,chapterHref:a,count:l,page:c,cfi:d}=r;if(yield _e(parseInt(s),o,a,this.chapterDocList,this.element,this.readerMode,this.format,this.tempLocation,t,i),d){const e=new pt(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,kookitmarker".indexOf(i.tagName.toLowerCase())>-1){e=i;break}t=t.parentNode}e&&(l="ignore",n=e.textContent)}}yield Ze(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 Ge(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 Ve(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)<20&&"scroll"!==this.readerMode||Math.abs(this.element.scrollHeight-h(this.element.scrollTop)-this.element.clientHeight)<20&&"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 Ve(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 Ge(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(){return d(this,void 0,void 0,(function*(){let e=this.getDocument();return e?nt(this.element,this.readerMode,e):""}))}audioText(){return d(this,void 0,void 0,(function*(){let e=this.getDocument();return e?((e,t,i)=>{let r=Xe(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(){return d(this,void 0,void 0,(function*(){let e=this.getDocument();return e&&e.body.textContent||""}))}highlightNode(e,t){let i=this.getDocument();i&&((e,t,i)=>{let r=Xe(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"PDF"===this.format?yield((e,i)=>d(void 0,void 0,void 0,(function*(){let r=[];for(let t=0;tt.str.indexOf(e)>-1));o>-1&&r.push({excerpt:n.items[o].str,cfi:JSON.stringify({text:n.items[o].str+"#"+t,chapterTitle:i[t].label,chapterDocIndex:t,chapterHref:i[t].href,count:"search",percentage:t/i.length})})}return t.uniq(r,"excerpt")})))(e,this.chapterDocList):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,this.element)}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=L(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){xt(i);for(let n=0;n{let t=e.contentDocument;t&&i.push(t)})),[e,...i]}getAllIframes(){let e=this.getIframe();if(!e)return[];if("PDF"!==this.format)return[e];let t=this.getDocument();if(!t)return[];let i=t.querySelectorAll("iframe"),r=[];return i.forEach((e=>{let t=e;r.push(t)})),[e,...r]}addTouchEvent(e){let t=this.getAllDocuments(),i=this.getAllIframes();for(let r=0;r{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 Ht={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"},Ft={"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"},Wt=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:Ht[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})),$t=e=>new Promise(((t,i)=>d(void 0,void 0,void 0,(function*(){let i=new T(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+"."+Ft[o.type],o);let s="imgs/"+e+"/"+t+"."+Ft[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+"."+Ft[r.type],r),i.href="css/"+e+"/"+t+"."+Ft[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 jt extends Pt{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 T(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 Me(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 $t(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 T(this.book);return yield e.getMetadata()}catch(e){throw console.error(e,"error"),e}}))}}const Ut=e=>{if(!e)return"";const t=document.createElement("textarea");return t.innerHTML=e,t.value},qt={XML:"application/xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml"},zt={name:[0,32,"string"],type:[60,4,"string"],creator:[64,4,"string"],numRecords:[76,2,"uint"]},Xt={compression:[0,2,"uint"],numTextRecords:[8,2,"uint"],recordSize:[10,2,"uint"],encryption:[12,2,"uint"]},Vt={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"]},Jt={resourceStart:[108,4,"uint"],fdst:[192,4,"uint"],numFdst:[196,4,"uint"],frag:[248,4,"uint"],skel:[252,4,"uint"],guide:[260,4,"uint"]},Gt={magic:[0,4,"string"],length:[4,4,"uint"],count:[8,4,"uint"]},_t={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"]},Yt={magic:[0,4,"string"],length:[4,4,"uint"],numControlBytes:[8,4,"uint"]},Zt={magic:[0,4,"string"],offset1:[8,4,"uint"],offset2:[12,4,"uint"]},Kt={magic:[0,4,"string"],length:[4,4,"uint"],numEntries:[8,4,"uint"],codeLength:[12,4,"uint"]},Qt={magic:[0,4,"string"],numEntries:[8,4,"uint"]},ei={flags:[8,4,"uint"],dataStart:[12,4,"uint"],keyLength:[16,4,"uint"],keyStart:[20,4,"uint"]},ti={1252:"windows-1252",65001:"utf-8"},ii={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"]},ri={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"]},ni=(e,t)=>{const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},oi=(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},si=new TextDecoder,ai=e=>si.decode(e),li=e=>{if(!e)return;const t=e.byteLength,i=4===t?"getUint32":2===t?"getUint16":"getUint8";return new DataView(e)[i](0)},ci=(e,t)=>Object.fromEntries(Array.from(Object.entries(e)).map((([e,[i,r,n]])=>[e,("string"===n?ai:li)(t.slice(i,i+r))]))),di=e=>new TextDecoder(ti[e]),hi=(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}},ui=e=>{let t=0;for(const i of e.subarray(-4))128&i&&(t=0),t=t<<7|127&i;return t},fi=e=>{let t=0;for(;e>0;e>>=1)1&~e||t++;return t},pi=e=>{let t=0;for(;!(1&e);)e>>=1,t++;return t},gi=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},yi=async(e,t)=>{const i=await t(e),r=ci(_t,i);if("INDX"!==r.magic)throw new Error("Invalid INDX record");const n=di(r.encoding),o=i.slice(r.length),s=ci(Yt,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}=hi(n,p);d.push([e,null,i,t]),p+=r}else d.push([e,1,null,t]);else d.push([e,a>>pi(i),null,t])}const g={};for(const[e,t,i,r]of d){const o=[];if(null!=t)for(let e=0;eli(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 ai(await this.#c.slice(t,t+4).arrayBuffer())}}class vi extends bi{#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 Ai(this).init():new Li(this).init()}#y(e){const t=ci(Xt,e),i=ci(Vt,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=ri[o];i.language=a?.[s>>2]??a?.[0];const l=64&i.exthFlag?((e,t)=>{const{magic:i,count:r}=ci(Gt,e);if("EXTH"!==i)throw new Error("Invalid EXTH header");const n=di(t),o={};let s=12;for(let t=0;t=8?ci(Jt,e):null}}async#b(){const{palmdoc:e,mobi:t}=this.headers;this.#f=di(t.encoding),this.#p=new TextEncoder;const{compression:i}=e;if(this.#g=1===i?e=>e:2===i?gi:17480===i?await(async(e,t)=>{const i=await t(e.huffcdic),{magic:r,offset1:n,offset2:o}=ci(Zt,i);if("HUFF"!==r)throw new Error("Invalid HUFF record");const s=Array.from({length:256},((e,t)=>n+4*t)).map((e=>li(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=>[li(i.slice(e,e+4)),li(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=ni(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=fi(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=ai(t.slice(0,4));return"FONT"===i?(async(e,t)=>{const{flags:i,dataStart:r,keyLength:n,keyStart:o}=ci(ei,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 yi(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:Ut(t?.title||this.decode(e.title)),author:t?.creator?.map(Ut),publisher:Ut(t?.publisher),language:t?.language??e.language,published:t?.date,description:Ut(t?.description),subject:t?.subject?.map(Ut),rights:Ut(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 wi=/<\s*(?:mbp:)?pagebreak[^>]*>/gi,xi=/<[^<>]+filepos=['"]{0,1}(\d+)[^<>]*>/gi;class Li{parser=new DOMParser;serializer=new XMLSerializer;#v=new Map;#w=new Map;#r=new Map;#x;#L=[];#C=qt.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(wi),(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.#L=[...new Set(Array.from(t.matchAll(xi),(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.#v.has(e))return this.#v.get(e);const t=await this.mobi.loadResource(e),i=URL.createObjectURL(new Blob([t]));return this.#v.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.#w.has(e))return this.#w.get(e);const{raw:t}=e,i=this.#L.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=oi(r,a,t.subarray(n,s?.offset))})));const n=this.mobi.decode(r).replaceAll(wi,"");return this.#w.set(e,n),n}async createDocument(e){const t=await this.loadText(e);return this.parser.parseFromString(t,this.#C)}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.#C}));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.#v.values())URL.revokeObjectURL(e);for(const e of this.#r.values())URL.revokeObjectURL(e)}}const Ci=/kindle:(flow|embed):(\w+)(?:\?mime=(\w+\/[-+.\w]+))?/,Ti=/kindle:pos:fid:(\w+):off:(\w+)/,Mi=e=>{const[t,i]=e.match(Ti).slice(1);return{fid:parseInt(t,32),off:parseInt(i,32)}},Si=(e=0,t=0)=>`kindle:pos:fid:${e.toString(32).toUpperCase().padStart(4,"0")}:off:${t.toString(32).toUpperCase().padStart(10,"0")}`,Di=e=>{const t=e.match(/\s(id|name|aid)\s*=\s*['"]([^'"]*)['"]/i);if(!t)return;const[,i,r]=t;return`[${i}="${CSS.escape(r)}"]`},ki=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 Ai{parser=new DOMParser;serializer=new XMLSerializer;#r=new Map;#T=new Map;#M=new Map;#S={};#x;#D;#k=new Uint8Array;#A=new Uint8Array;#I=-1;#E=-1;#C=qt.XHTML;#N=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=ci(Qt,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=>[li(i.slice(e,e+4)),li(i.slice(e+4,e+8))]));this.#S.fdstTable=n,this.#D=n[n.length-1][1]}catch{}const i=(await yi(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 yi(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.#S.skelTable=i,this.#S.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,qt.XML);for(const e of n.querySelectorAll("spine > itemref")){const t=parseInt(e.getAttribute("skelid"));s.set(t,ki(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=Si(n,o),a=this.#T.get(n);return a?a.push(o):this.#T.set(n,[o]),{label:Ut(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 yi(e,t);return i.map((({name:e,tagMap:t})=>({label:r[t[1][0]]??"",type:e?.split(/\s/),href:Si(t[6]?.[0]??t[3]?.[0])})))}}async loadResourceBlob(e){const{resourceType:t,id:i,type:r}=(e=>{const[t,i,r]=e.match(Ci).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=[qt.XHTML,qt.HTML,qt.CSS,qt.SVG].includes(r)?await this.replaceResources(this.mobi.decode(n)):n,s=r===qt.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.#N.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(Ci,"g"),this.loadResource.bind(this))}async loadRaw(e,t){const i=t-this.#k.length,r=null==this.#D?1/0:this.#D-this.#A.length-e;if(i<0||ie;){const e=this.mobi.headers.palmdoc.numTextRecords-1-++this.#E,t=await this.mobi.loadText(e);this.#A=ni(t,this.#A)}const n=this.#D-this.#A.length;return this.#A.slice(e-n,t-n)}loadFlow(e){if(e<4294967295)return this.loadRaw(...this.#S.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=oi(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=Di(i);this.#R(e.index,t,r)}}return this.mobi.decode(o)}async createDocument(e){const t=await this.loadText(e);return this.parser.parseFromString(t,this.#C)}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.#C);r.querySelector("parsererror")&&(this.#C=qt.HTML,r=this.parser.parseFromString(i,this.#C));for(const[e,t]of this.#N)for(const i of r.querySelectorAll(`img[src="${e}"]`))i.replaceWith(t);const n=URL.createObjectURL(new Blob([this.serializer.serializeToString(r)],{type:this.#C}));return this.#r.set(e,n),n}getIndexByFID(e){return this.#x.findIndex((t=>t.frags.some((t=>t.index===e))))}#R(e,t,i){const r=this.#M.get(e);if(r)r.set(t,i);else{const r=new Map;this.#M.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.#M.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=Di(d);this.#R(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.#M.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 Ii extends Pt{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 T(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"===ai(await e.slice(60,68).arrayBuffer()))(t))&&(this.book=yield new vi({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 $t(this.book)}))}getMetadata(){return d(this,void 0,void 0,(function*(){try{this.book||(yield this.parse());let e=new T(this.book);return yield e.getMetadata()}catch(e){throw console.error(e),e}}))}}const Ei=e=>`${Bi()?".":""}/lib/pdfjs/${e}`,Ni=window.pdfjsLib,Ri=async e=>await(await fetch(e)).text(),Bi=()=>"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),Oi=async()=>await Ri(Ei("text_layer_builder.css")),Pi=async()=>await Ri(Ei("annotation_layer_builder.css")),Hi=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 `],{type:"text/html"}))},Fi=e=>({label:e.title,href:e.dest?JSON.stringify(e.dest):null,subitems:e.items.length?e.items.map(Fi):null}),Wi=async(e,t)=>{const i=new Ni.PDFDataRangeTransport(e.size,[]);i.requestDataRange=(t,r)=>{e.slice(t,r).arrayBuffer().then((e=>{i.onDataRange(t,e)}))};const r=await Ni.getDocument({range:i,cMapUrl:Ei("cmaps/"),standardFontDataUrl:Ei("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(Fi);const l=new Map;return n.sections=Array.from({length:r.numPages}).map(((e,t)=>({id:t,load:async()=>{const e=l.get(t);if(e)return e;const i=await Hi(await r.getPage(t+1));return l.set(t,i),i},unload:async()=>{(await r.getPage(t+1)).cleanup()},render:async(e,i,n)=>{await(async(e,t,i,r)=>{let n=window.devicePixelRatio*("yes"===r?1/i*1.5:1);const o=i*n;let s=t.querySelector("#koodoPDFLayer");s.style.visibility="hidden",s.style.transform=`scale(${1/n})`,s.style.transformOrigin="top left",s.style.setProperty("--scale-factor",o);const a=e.getViewport({scale:o}),l=document.createElement("canvas");s.style.width=`${a.width}px`,s.style.height=`${a.height}px`,l.height=a.height,l.width=a.width;const c=l.getContext("2d");await e.render({canvasContext:c,viewport:a,background:"rgba(0,0,0,0)"}).promise,t.querySelector("#canvas").replaceChildren(t.adoptNode(l)),s.style.overflow="hidden";const d=t.querySelector("#textLayer"),h=new Ni.TextLayer({textContentSource:await e.streamTextContent(),container:d,viewport:a});await h.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 u=document.createElement("div");u.className="endOfContent",d.append(u);let f=!1,p=null;d.onpointerdown=()=>{d.classList.add("selecting"),f=!0},"yes"!==r?(d.onpointerup=()=>{d.classList.remove("selecting"),f=!1,u.remove(),d.append(u)},d.onpointermove=e=>{if(!f)return;let t=e.target.closest(".textLayer > span");const i=null!==t;d.style.cursor=i?"text":"default",i&&(p=t),u.remove(),d.insertBefore(u,p)}):t.addEventListener("selectionchange",(e=>{if(!f)return;let i=t?.defaultView;var r=i.getSelection().getRangeAt(0).endContainer;let n=r.nodeType===Node.TEXT_NODE?r.parentNode:r;n=n.closest(".textLayer > span");const o=null!==n;d.style.cursor=o?"text":"default",o&&(p=n),u.remove(),d.insertBefore(u,p.nextSibling)}));const g=t.querySelector("#annotationLayer");await new Ni.AnnotationLayer({page:e,viewport:a,div:g}).render({annotations:await e.getAnnotations(),linkService:{goToDestination:()=>{},getDestinationHash:e=>JSON.stringify(e),addLinkAttributes:(e,t)=>e.href=t}}),s.style.marginLeft=`calc(50% - ${s.getBoundingClientRect().width/2}px)`,s.style.visibility="visible"})(await r.getPage(t+1),e,i,n)},getTextContent:async()=>{const e=await r.getPage(t+1);return await e.getTextContent()},size:1e3,getDimension:async()=>{let e=(await r.getPage(t+1)).getViewport({scale:1});return{width:e.width,height:e.height}},getPage:async()=>await r.getPage(t+1)}))),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()=>Hi(await r.getPage(1),!0),n.destroy=()=>r.destroy(),n};class $i extends Pt{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 T(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);const r=yield this.chapterDocList[0].text.getDimension();let n=this.getDocument();if(!n)return;((e,t,i,r)=>{for(let n=0;n{o&&clearTimeout(o),o=setTimeout((()=>d(this,void 0,void 0,(function*(){yield this.handlePDFScrollEvent(n),yield this.record()}))),200)})):n.addEventListener("scroll",(e=>{o&&clearTimeout(o),o=setTimeout((()=>d(this,void 0,void 0,(function*(){yield this.handlePDFScrollEvent(n),yield this.record()}))),200)})),((e,t,i)=>{if("scroll"===t)return;let r="double"===t?2:1,n=Math.floor(e.clientWidth/12),o=n%2==0?n:n-1;i.body.setAttribute("style",e.getAttribute("style")+`height: 100%;overflow-y: hidden;overflow-X: hidden;padding-left: 0px;padding-right: 0px;margin: 0px;box-sizing: border-box;touch-action: manipulation; overscroll-behavior: none;max-width: inherit;column-fill: auto;column-gap: ${o}px; column-width: ${(e.clientWidth-o)/r}px;`)})(e,this.readerMode,n),t()}))))}handlePDFScrollEvent(e){return d(this,void 0,void 0,(function*(){let t=e.querySelectorAll(".pdf-container");for(let i=0;i{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 Wi(t,this.readerMode))}catch(e){throw console.error(e),e}}))}preCache(){return d(this,void 0,void 0,(function*(){return""}))}goToChapterIndex(e){return d(this,void 0,void 0,(function*(){this.chapterDocList.length>0&&(yield this.goToChapter(e,this.chapterDocList[e].href,this.chapterDocList[e].label))}))}getPageSize(){let e="double"===this.readerMode?2:1,t=Math.floor(this.element.clientWidth/12),i=t%2==0?t:t-1,r=this.getDocument();if(!r)return;let n=r.querySelectorAll("iframe")[0],o=null==n?void 0:n.getBoundingClientRect().height;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,sectionHeight:o,gap:i}}goToChapter(e,t,i){return d(this,void 0,void 0,(function*(){"double"===this.readerMode&&e%2==1&&e--;let t=this.getDocument(),i=this.getIframe();t&&i&&(yield this.renderPdfPage(e,t),yield kt(parseInt(e),this.readerMode,t),yield this.record())}))}getPositionByChapter(e){return{percentage:e/this.chapterDocList.length,chapterDocIndex:e+"",chapterHref:this.chapterDocList[e].href,chapterTitle:this.chapterDocList[e].label,text:""}}goToPercentage(e){return d(this,void 0,void 0,(function*(){if(this.chapterDocList.length>0){let t=1===e?this.chapterDocList.length-1:Math.floor(this.chapterDocList.length*e);yield this.goToChapter(t,this.chapterDocList[t].href,this.chapterDocList[t].label)}}))}goToPosition(e){var t;return d(this,void 0,void 0,(function*(){let i=this.getDocument(),r=this.getIframe();if(!i||!r)return;let n=JSON.parse(e);void 0===n.chapterDocIndex&&(n.chapterDocIndex=0),this.tempLocation={text:n.text,chapterTitle:n.chapterTitle,chapterDocIndex:n.chapterDocIndex,chapterHref:n.chapterHref,count:n.count,page:n.page,percentage:n.percentage};let{chapterTitle:o,chapterDocIndex:s,chapterHref:a}=n;if("double"===this.readerMode&&s%2==1&&s--,yield this.renderPdfPage(parseInt(s),i),"scroll"===this.readerMode){let e=this.getSubIframe(void 0!==s?s:parseInt(this.tempLocation.chapterDocIndex));if(!e)return;let i=(null===(t=e.parentElement)||void 0===t?void 0:t.getBoundingClientRect().height)||0;r.style.height=i*this.chapterDocList.length+"px"}if("single"===this.readerMode||"double"===this.readerMode){let e=i.querySelectorAll(".pdf-container");for(let t=0;tparseFloat(getComputedStyle(i).paddingTop)?i.style.height=this.element.clientHeight-parseFloat(getComputedStyle(i).paddingTop)+"px":i.style.marginBottom=this.element.clientHeight-parseFloat(getComputedStyle(i).paddingTop)+"px")}}yield kt(parseInt(s),this.readerMode,i),yield this.record(),this.trigger("page-changed")}))}prev(e){return d(this,void 0,void 0,(function*(){let t=this.getDocument(),i=this.getIframe();t&&i&&("scroll"===this.readerMode?this.element.scrollBy({left:0,top:-(this.element.clientHeight-50),behavior:"smooth"}):("ios"===e?yield It(this.element,this.animation,1,t,this.flipToNextPage,this.flipToPrevPage,this.isMobile,parseInt(this.tempLocation.chapterDocIndex||"0"),this.readerMode):yield Ve(this.element,this.animation,1,t,this.flipToNextPage,this.flipToPrevPage,this.isMobile),yield this.renderPdfPage(parseInt(this.tempLocation.chapterDocIndex)-("double"===this.readerMode?2:1),t)),yield this.record())}))}next(e){return d(this,void 0,void 0,(function*(){let t=this.getDocument(),i=this.getIframe();t&&i&&("scroll"===this.readerMode?this.element.scrollBy({left:0,top:this.element.clientHeight-50,behavior:"smooth"}):("ios"===e?yield It(this.element,this.animation,-1,t,this.flipToNextPage,this.flipToPrevPage,this.isMobile,parseInt(this.tempLocation.chapterDocIndex||"0"),this.readerMode):yield Ve(this.element,this.animation,-1,t,this.flipToNextPage,this.flipToPrevPage,this.isMobile),yield this.renderPdfPage(parseInt(this.tempLocation.chapterDocIndex)+("double"===this.readerMode?2:1),t)),yield this.record())}))}prevChapter(){return d(this,void 0,void 0,(function*(){yield this.prev()}))}nextChapter(){return d(this,void 0,void 0,(function*(){yield this.next()}))}visibleText(){return d(this,void 0,void 0,(function*(){return this.getDocument()?yield(e=parseInt(this.tempLocation.chapterDocIndex||"0"),t=this.chapterDocList,i=this.readerMode,d(void 0,void 0,void 0,(function*(){let r=(yield t[e].text.getTextContent()).items.map((e=>e.str));if("double"===i){let i=(yield t[e+1].text.getTextContent()).items.map((e=>e.str));r=r.concat(i)}return r}))):"";var e,t,i}))}audioText(){return d(this,void 0,void 0,(function*(){return yield this.visibleText()}))}chapterText(){return d(this,void 0,void 0,(function*(){return(yield this.visibleText()).join(" ")}))}record(){return d(this,void 0,void 0,(function*(){""!==this.animation&&(yield new Promise((e=>setTimeout(e,1e3))));let e=this.getDocument();e&&(yield this.handlePDFRecord(e))}))}handlePDFRecord(e){return d(this,void 0,void 0,(function*(){let t=e.querySelectorAll(".pdf-container");if(t.length>0&&At(this.element,t[t.length-1],this.readerMode))this.handleRecord(t[t.length-1]);else for(let e=0;e{let r=parseInt(e.split("#").reverse()[0]),n=e.split("#").slice(0,-1).join("#"),o=i.getElementById("pdf-iframe-"+r);o||(o=Dt(r,i));let s=null==o?void 0:o.contentDocument;if(!s)return;let a=s.querySelectorAll("p,span"),l=Array.from(a).filter(((e,t)=>(e.textContent||"").trim()&&e.textContent===n));l.length>0&&l[0].setAttribute("style",l[0].getAttribute("style")+t)})(e,t,i)}getProgress(){return{totalPage:this.chapterDocList.length,currentPage:parseInt(this.tempLocation.chapterDocIndex||"0")+1}}getNotePosition(){var e;return d(this,void 0,void 0,(function*(){let t=this.getDocument();if(!t)return;let i=L(t);if(!i)return;let r=i.ownerDocument,n=null===(e=null==r?void 0:r.defaultView)||void 0===e?void 0:e.frameElement,o=(null==n?void 0:n.getAttribute("id"))||"",s=o?parseInt(o.split("-").reverse()[0]):0;return Object.assign(Object.assign({},this.tempLocation),{chapterDocIndex:s})}))}getSubDocument(e){let t=document.getElementById("page-area");if(!t)return null;let i=t.getElementsByTagName("iframe")[0];if(!i)return null;let r=i.contentDocument;if(!r)return null;let n=r.getElementById("pdf-iframe-"+e);return n||(Dt(e||0,r),n=r.getElementById("pdf-iframe-"+e)),n.contentDocument}getSubIframe(e){let t=document.getElementById("page-area");if(!t)return null;let i=t.getElementsByTagName("iframe")[0];if(!i)return null;let r=i.contentDocument;return r?(i=r.getElementById("pdf-iframe-"+e),i||(Dt(e||0,r),i=r.getElementById("pdf-iframe-"+e)),i):null}getHightlightCoords(e){return d(this,void 0,void 0,(function*(){let t=void 0!==e?e:parseInt(this.tempLocation.chapterDocIndex),i=this.getSubDocument(e);if(!i)return;var r=i.getSelection().getRangeAt(0).getClientRects();let n=yield this.chapterDocList[t].text.getPage(),o=yield St(this.element,this.readerMode,this.chapterDocList,t);var s=n.getViewport({scale:o});let a=i.querySelector("canvas");var l=null==a?void 0:a.getClientRects()[0];let c=[];for(let e=0;er[e].left&&(c[c.length-1].left=r[e].left),c[c.length-1].right=this.chapterDocList.length||e<0)return;let i=t.getElementById("pdf-iframe-"+e);i||(i=Dt(e,t));let r=null==i?void 0:i.contentDocument;if(!r)return;if(r.body.innerHTML)return;r.body.innerHTML="";let n=yield fetch(yield this.chapterDocList[e].text.load()).then((e=>e.blob())),o=yield n.text();r.body.innerHTML=o;let s=yield St(this.element,this.readerMode,this.chapterDocList,e);yield this.chapterDocList[e].text.render(r,s,this.isMobile),this.trigger("rendered")}))}handleUnloadPDFChapter(e,t){return d(this,void 0,void 0,(function*(){if(e>=this.chapterDocList.length||e<0)return;let i=t.getElementById("pdf-iframe-"+e),r=null==i?void 0:i.contentDocument;r&&""!==r.body.innerHTML&&(yield this.chapterDocList[e].text.unload(),r.body.innerHTML="")}))}renderPdfPage(e,t){return d(this,void 0,void 0,(function*(){yield this.handleRenderPDFChapter(e,t),yield this.handleRenderPDFChapter(e+1,t)}))}}class ji extends Pt{constructor(e,t){super(Object.assign({format:"TXT"},t)),this.txtBuffer=e,this.charset=t.charset,this.parserRegex=t.parserRegex}renderTo(e,t){return new Promise(((i,r)=>d(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse(t));let r=new T(this.book);this.chapterList=yield r.getChapter(this.book.toc),this.chapterDocList=yield r.getChapterDoc(),m(e);let n=this.getDocument();n&&(x(e,this.readerMode,n),i())}))))}parse(e){return d(this,void 0,void 0,(function*(){try{const t=new TextDecoder(this.charset),i=new Uint8Array(this.txtBuffer);let r=t.decode(i);this.book=Se(r,!0,this.parserRegex,e)}catch(e){throw console.error(e),e}}))}refreshContent(){return d(this,void 0,void 0,(function*(){yield this.parse({refresh:!0});let e=new T(this.book);return this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),this.chapterList}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield $t(this.book)}))}getMetadata(e){return d(this,void 0,void 0,(function*(){try{const t=4096,i=e.byteLength,r=Math.min(i,t),n=new Uint8Array(e,0,r);const s=o.detect(n)||"utf8";return this.charset=s,{charset:s}}catch(e){return console.error("Error detecting charset:",e),this.charset="utf8",{charset:"utf8"}}}))}}const Ui=({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(((e,t)=>{const i=parseInt(e.replace(/\D/g,"")),r=parseInt(t.replace(/\D/g,""));return isNaN(i)||isNaN(r)?isNaN(i)?isNaN(r)?e.localeCompare(t):1:-1:i-r})),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 qi extends Pt{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 T(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=Ui(e,t,this.readerMode)}else if("CBT"===this.format){const e=yield this.makeTarLoader();this.book=Ui(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=Ui(e,t,this.readerMode)}else if("CB7"===this.format){const e=yield this.make7zLoader();this.book=Ui(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 $t(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 zi=e=>e?.trim()?.replace(/\s{2,}/g," "),Xi=e=>zi(e?.textContent),Vi={XLINK:"http://www.w3.org/1999/xlink",EPUB:"http://www.idpf.org/2007/ops"},Ji="application/xml",Gi="application/xhtml+xml",_i={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"},Yi={epigraph:["blockquote"],subtitle:["h2",_i],"text-author":["p",_i],date:["p",_i],stanza:"stanza"},Zi={title:["header",{p:["h1",_i],"empty-line":["br"]}],epigraph:["blockquote","self"],image:"image",annotation:["aside"],section:["section","self"],p:["p",_i],poem:["blockquote",Yi],subtitle:["h2",_i],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",_i]};Yi.epigraph.push(Zi);const Ki={image:"image",title:["section",{p:["h1",_i],"empty-line":["br"]}],epigraph:["section",Zi],section:["section",Zi]},Qi=e=>{const t=e.getAttributeNS(Vi.XLINK,"href"),[,i]=t.split("#"),r=e.getRootNode().getElementById(i);return r?`data:${r.getAttribute("content-type")};base64,${r.textContent}`:t};class er{constructor(e){this.fb2=e,this.doc=document.implementation.createDocument(Vi.XHTML,"html")}image(e){const t=this.doc.createElement("img");return t.alt=e.getAttribute("alt"),t.title=e.getAttribute("title"),t.setAttribute("src",Qi(e)),t}anchor(e){const t=this.convert(e,{a:["a",_i]});return t.setAttribute("href",e.getAttributeNS(Vi.XLINK,"href")),"note"===e.getAttribute("type")&&t.setAttributeNS(Vi.EPUB,"epub:type","noteref"),t}stanza(e){const t=this.convert(e,{stanza:["p",{title:["header",{p:["strong",_i],"empty-line":["br"]}],subtitle:["p",_i]}]});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 tr=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"})),ir="data-foliate-id",rr=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,Ji),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,Ji)}return n})(e),r=new er(i),n=e=>i.querySelector(e),o=e=>[...i.querySelectorAll(e)],s=e=>{const t=Xi(e.querySelector("nickname"));if(t)return t;const i=Xi(e.querySelector("first-name")),r=Xi(e.querySelector("middle-name")),n=Xi(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")??Xi(e),l=n("title-info annotation");t.metadata={title:Xi(n("title-info book-title")),identifier:Xi(n("document-info id")),language:Xi(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(Xi)),publisher:Xi(n("publish-info publisher")),published:a(n("title-info date")),modified:a(n("document-info date")),description:l?r.convert(l,{annotation:["div",Zi]}).innerHTML:null,subject:o("title-info genre").map(Xi)},t.getCover=()=>fetch(Qi(n("coverpage image"))).then((e=>e.blob()));const c=Array.from(i.querySelectorAll("body"),(e=>{const t=r.convert(e,{body:["body",Ki]});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(ir,t),{title:Xi(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:Gi}),a=URL.createObjectURL(s);return{ids:e,title:zi(i.querySelector(".title, .subtitle, p")?.textContent??(i.classList.contains("title")?i.textContent:"")),titles:t,load:()=>a,createDocument:()=>(new DOMParser).parseFromString(n,Gi),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(`[${ir}="${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(`[${ir}="${t}"]`),t};class nr extends Pt{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 T(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 rr(e)}catch(e){throw console.error(e),e}}))}preCache(){return d(this,void 0,void 0,(function*(){return this.book||(yield this.parse()),yield $t(this.book)}))}getMetadata(){return d(this,void 0,void 0,(function*(){try{this.book||(yield this.parse());let e=new T(this.book);return yield e.getMetadata()}catch(e){throw console.error(e),e}}))}}class or extends Pt{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 Wt(this.cacheBuffer);let i=new T(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 sr extends Pt{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 T(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 $t(this.book)}))}}class ar extends Pt{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 T(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 $t(this.book)}))}}class lr extends Pt{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 T(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:Ht[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 $t(this.book)}))}}export{or as CacheRender,qi as ComicRender,sr as DocxRender,jt as EpubRender,nr as Fb2Render,lr as HtmlRender,ar as MdRender,Ii as MobiRender,$i as PdfRender,ji 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.id="kookit-iframe",i.style.verticalAlign="baseline",e.innerHTML="",e.appendChild(i)},y=(e,t,i)=>{let r=Math.floor(i.clientWidth/12),n=r%2==0?r:r-1;return{totalPage:"scroll"===e?1:"single"===e?Math.round(parseFloat(t.body.scrollWidth/(t.body.clientWidth+n)+"")):2*Math.round(parseFloat(t.body.scrollWidth/(t.body.clientWidth+n)+"")),currentPage:Math.round(parseFloat(h(t.body.scrollLeft)/(t.body.clientWidth+n)+""))+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})),w=(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 v(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:none; overscroll-behavior: none;max-width: inherit;column-fill: auto;column-gap: ${s}px; column-width: ${(e.clientWidth-s)/n}px;`)};function L(e){const t=e.getSelection();if(!t)return null;if(t.rangeCount>0){return t.getRangeAt(0).startContainer.parentElement}return null}const C=e=>"string"==typeof e||e instanceof String;class T{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 M=(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/,D=/^epubcfi\((.*)\)$/,k=e=>e.replace(/[\^[\](),;=]/g,"^$&"),A=(e,t)=>{return i=([e])=>e===t,e.map(((e,t,r)=>i(e,t,r)?t:null)).filter((e=>null!=e));var i},I=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},E=e=>M(e,A(e,"!")).map(I),N=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(D)?.[1]??i));var i;const r=A(t,",");if(!r.length)return E(t);const[n,o,s]=M(t,r).map(E);return{parent:n,start:o,end:s}},R=({index:e,id:t,offset:i,temporal:r,spatial:n,text:o,side:s})=>{const a=s?`;s=${s}`:"";return`/${e}`+(t?`[${k(t)}${a}]`:"")+(null!=i&&e%2?`:${i}`:"")+(r?`~${r}`:"")+(n?`@${n.join(":")}`:"")+(o||!t&&s?"["+(o?.map(k)?.join(",")??"")+a+"]":"")},B=e=>e.parent?[e.parent,e.start,e.end].map(B).join(","):e.map((e=>e.map(R).join(""))).join("!"),O=e=>{return t=B(e),D.test(t)?t:`epubcfi(${t})`;var t},P=(e,t)=>{return"string"==typeof e?O(P(N(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,F=({nodeType:e})=>1===e,W=e=>{const t=Array.from(e.childNodes).filter((e=>H(e)||F(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):F(i)?e.push(null,t):e.push(t):e.push(t),e}),[]);return F(t[0])&&t.unshift("first"),F(t[t.length-1])&&t.push("last"),t.unshift("before"),t.push("after"),t},$=(e,t)=>e?W(e)[t]:null,j=(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}},U=(e,t)=>{const{parentNode:i,id:r}=e,n=W(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?U(i).concat(a):[a]},q=(e,t)=>j(e.documentElement,P(t)).node,z="urn:oasis:names:tc:opendocument:xmlns:container",X="http://www.w3.org/1999/xhtml",V="http://www.idpf.org/2007/opf",J="http://www.idpf.org/2007/ops",G="http://purl.org/dc/elements/1.1/",_="http://www.w3.org/2001/04/xmlenc#",Y="http://www.daisy.org/z3986/2005/ncx/",Z="http://www.w3.org/1999/xlink",K="http://www.w3.org/ns/SMIL",Q={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)/},ee=e=>e.toLowerCase().replace(/[-:](.)/g,((e,t)=>t.toUpperCase())),te=(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,ie=(...e)=>t=>t?Object.fromEntries(e.map((e=>[ee(e),t.getAttribute(e)]))):null,re=e=>{return t=e?.textContent,t?t.trim().replace(/\s{2,}/g," "):"";var t},ne=(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)]}},oe=(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}},se=e=>/^(?!blob)\w+:/i.test(e),ae=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()))},le=e=>e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),ce={attrs:["dir","xml:lang"]},de={name:"alternate-script",many:!0,...ce,props:["file-as"]},he={many:!0,...ce,props:[{name:"role",many:!0,attrs:["scheme"]},"file-as",de]},ue=[{name:"title",many:!0,...ce,props:["title-type","display-seq","file-as",de]},{name:"identifier",many:!0,props:[{name:"identifier-type",attrs:["scheme"]}]},{name:"language",many:!0},{name:"creator",...he},{name:"contributor",...he},{name:"publisher",...ce,props:["file-as",de]},{name:"description",...ce,props:[de]},{name:"rights",...ce,props:[de]},{name:"date"},{name:"dcterms:modified",type:"meta"},{name:"subject",many:!0,...ce,props:["term","authority",de]},{name:"belongs-to-collection",type:"meta",many:!0,...ce,props:["collection-type","group-position","dcterms:identifier","file-as",de,{name:"belongs-to-collection",recursive:!0}]}],fe=(e,t=e=>e)=>{const{$:i,$$:r,$$$:n}=ne(e,X),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:re(n)||n?.getAttribute("title"),href:a,subitems:s(o)};return e&&(l.type=n?.getAttributeNS(J,"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(J,"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:re(e.firstElementChild),type:t,list:a(e)})}return{toc:c,pageList:d,landmarks:h,others:u}},pe=(e,t=e=>e)=>{const{$:i,$$:r}=ne(e,Y),n=e=>{const o=i(e,"navLabel"),s=i(e,"content"),a=re(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:re(i(e,"navLabel")),list:o(e,"navTarget")})))}},ge=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)},me=/([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/,ye=e=>re(e.getElementById(e.documentElement.getAttribute("unique-identifier"))??e.getElementsByTagNameNS(G,"identifier")[0]),be=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=ve)=>({"http://www.idpf.org/2008/embedding":{key:t=>e(ye(t).replaceAll(/[\u0020\u0009\u000d\u000a]/g,"")),decode:(e,t)=>be(e,1040,t)},"http://ns.adobe.com/pdf/enc#RC":{key:e=>{const t=(e=>{for(const t of e.getElementsByTagNameNS(G,"identifier")){const[e]=re(t).split(":").slice(-1);if(me.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)=>be(e,1024,t)}});class xe{#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(_,"EncryptedData"),(e=>({algorithm:e.getElementsByTagNameNS(_,"EncryptionMethod")[0]?.getAttribute("Algorithm"),uri:e.getElementsByTagNameNS(_,"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 Le{constructor({opf:e,resolveHref:t}){this.opf=e;const{$:i,$$:r,$$$:n}=ne(e,V),o=i(e.documentElement,"manifest"),s=i(e.documentElement,"spine"),a=r(s,"itemref");this.manifest=r(o,"item").map(ie("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(ie("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===Q.NCX)))?.href;const l=i(e.documentElement,"guide");l&&(this.guide=r(l,"reference").map(ie("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(te("name","cover"))?.getAttribute("content"))??this.getItemByID("cover")??this.getItemByID("cover.jpg")??this.getItemByID("cover.png")??this.getItemByID("cover.jpeg")??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=U(i);for(const[n,o]of W(i).entries()){const i=e[t.length];o===i&&t.push(O([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=N(e),i=(t.parent??t).shift();let r=q(this.opf,i);r&&"idref"!==r.nodeName&&(i.at(-1).id=null,r=q(this.opf,i));const n=r?.getAttribute("idref");return{index:this.spine.findIndex((e=>e.idref===n)),anchor:e=>((e,t)=>{const i=P(t),r=P(t,!0),n=e.documentElement,o=j(n,i[0]),s=j(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=Q.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||[Q.XHTML,Q.HTML,Q.CSS,Q.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(se(e))return e;const r=oe(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([Q.XHTML,Q.HTML,Q.SVG].includes(r)){let s=(new DOMParser).parseFromString(o,r);if(r===Q.XHTML&&s.querySelector("parsererror")&&(console.warn(s.querySelector("parsererror").innerText),e.mediaType=Q.HTML,s=(new DOMParser).parseFromString(o,e.mediaType)),[Q.XHTML,Q.SVG].includes(e.mediaType)){let e=s.firstChild;for(;e instanceof ProcessingInstruction;){if(e.data){const r=await ae(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(Z,"href",await this.loadHref(e.getAttributeNS(Z,"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===Q.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 ae(e,/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,((e,r)=>this.loadHref(r,t,i).then((e=>`url("${e}")`)))),n=await ae(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(le).join("|"),"g");return ae(e,o,(async e=>this.loadItem(r.get(e.replace(/^\//,"")),i.concat(t))))}unloadItem(e){this.unref(e?.href)}}const Te=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 Me{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 xe(we(r))}#a(e){return e&&e.includes("opf:scheme")&&(e=e.replaceAll("opf:scheme","scheme")),e?this.parser.parseFromString(e,Q.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(z,"rootfile"),ie("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 Le({opf:r,resolveHref:e=>oe(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:Te(n),resolveHref:e=>oe(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=>oe(e,s),t=fe(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=>oe(e,a),t=pe(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}=ne(e,V),r=t(e.documentElement,"metadata"),n=Array.from(r.children),o=(e,t)=>{if(!t)return null;const{props:i=[],attrs:r=[]}=e,s=re(t);if(!i.length&&!r.length)return s;const a=t.getAttribute("id"),l=a?n.filter(te("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=te("property",n),a=r?e:t;return[ee(n),i?l.filter(s).map((e=>o(a,e))):o(a,l.find(s))]}))).concat(r.map((e=>[ee(e),t.getAttribute(e)]))))},s=n.filter(te("refines",null)),a=e=>Object.fromEntries(i(r,"meta").filter(te("property",(t=>t?.startsWith(e)))).map((t=>[t.getAttribute("property").replace(e,""),re(t)])));return{metadata:Object.fromEntries(ue.map((e=>{const{type:t,name:i,many:r}=e,n="meta"===t?e=>e.namespaceURI===V&&e.getAttribute("property")===i:e=>e.namespaceURI===G&&e.localName===i;return[ee(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=ge(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:ye(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}=ne(e,K);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:ge(n.getAttribute("clipBegin")),clipEnd:ge(n.getAttribute("clipEnd"))}}:{id:r};var o}))})(await this.#l(i.href),(e=>oe(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 se(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)}}}let Se=["章","节","回","節","卷","部","輯","辑","話","集","话","篇"," "," "],De=[],ke=["CHAPTER","Chapter","序章","前言","声明","写在前面的话","后记","楔子","后序","章节目录","尾声","聲明","寫在前面的話","後記","後序","章節目錄","尾聲"],Ae=[" "," ","、","·",".",":",":"];const Ie=e=>e.trim().replace(/(\r\n|\n|\r|\t)/gm,"").substring(0,100).split("").filter((e=>"="!==e&&"-"!==e&&"_"!==e&&"+"!==e)).join(""),Ee=(e,t="")=>t?new RegExp(t).test(e):e&&e.length<40&&!Ne(e)&&(Re(e)||e.startsWith("第")&&Oe(e)||e.startsWith("卷")&&Pe(e)||e.indexOf("第")>-1&&e.lastIndexOf("第")<7&&Oe(e.substr(e.indexOf("第")))||Be(e)),Ne=e=>De.filter((t=>e.indexOf(t)>-1)).length>0,Re=e=>ke.filter((t=>e.startsWith(t))).length>0,Be=e=>Ae.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,Oe=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))));let He=!1;const Fe=e=>Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,p,div,ul,dl,ol,pre,blockquote,address,kookitmarker")),We=(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"})})),$e=(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=$e(t,l,i,"prev");c&&(o.text="prevChapter",o.page="",yield Ue(c.index,c.label,c.href,i,e,r,n,o,s,a))})),Ue=(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)}(-1===e||e>n.length-1)&&(e=0);let f=yield u(n[e].text,!1),p=function(e){const t=e.match(/]*)>/i);if(!t)return{};const i=t[1],r={},n=/([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^>\s]+))/g;let o;for(;null!==(o=n.exec(i));){const e=o[2]||o[3]||o[4]||"";r[o[1]]=e}return r}(f);c.body.innerHTML=f,p.style?c.body.setAttribute("style",p.style+" "+c.body.getAttribute("style")):p.class?c.body.setAttribute("class",p.class):p.id?c.body.setAttribute("id",p.id):p.class?p.id||c.body.removeAttribute("id"):c.body.removeAttribute("class"),yield qe(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.race([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)))}))))),new Promise(((e,t)=>{setTimeout((()=>{console.info("image load timeout"),e("image load timeout")}),3e3)}))]),yield w(e,t,i,n),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 r.height=n.body.scrollHeight+"px",r.height=n.body.scrollHeight+300+"px"})))(o,s,a,h,c),yield ze(o,s,"","","","",c)}));const qe=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)}})),ze=(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=Fe(a.body).filter(((t,i)=>Ie(t.textContent)&&(Ie(t.textContent)===Ie(r)||Ie(t.textContent)===e.t2s(Ie(r))||Ie(t.textContent)===e.s2t(Ie(r)))&&(Math.abs(i-parseInt(n))<2||"search"===n||"ignore"===n||"next"===n)));if(0===o.length)return void console.info("failed");c=Xe(o[0],t,i),l=c?h(c.offsetLeft)-h(c.marginLeft||parseFloat(getComputedStyle(c).marginLeft)):"prevChapter"===r?a.body.scrollWidth:0}else if(o&&o.indexOf("#")>-1){let e=CSS.escape(o.split("#").reverse()[0]);if(!a.body.querySelector("#"+e))return;c=Xe(a.body.querySelector("#"+e)||a.body,t,i),l=c?h(c.offsetLeft)-h(c.marginLeft||parseFloat(getComputedStyle(c).marginLeft)):0}var d;"scroll"!==i?a.body.scrollTo(l,0):c.scrollIntoView()})),Xe=(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&&Ve(parseInt(o+""),(t.clientWidth+n)/2)?e:e.parentElement?Xe(e.parentElement,t,i):e},Ve=(e,t)=>{for(let i=e-10;i<=e+10;i++)if(i%t==0)return!0;return!1},Je=(e,t,i,r,n,o,s)=>d(void 0,void 0,void 0,(function*(){var a;if(He)return;let l=Fe(o.body),c=l.filter((i=>Qe(e,i,t)&&(i.textContent||"").trim())),d=c[0];s&&(d=s);let h=0;for(let i=0;i{He=!1}),100)})),Ge=(e,t,i)=>{let r=Math.floor(t.clientWidth/12),n=r%2==0?r:r-1;return Math.abs(e.offsetLeft-Xe(e,t,i).offsetLeft)>(t.clientWidth+n)/2},_e=(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)}}},Ye=(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=$e(t,l,i,"next");c&&(o.page="",yield Ue(c.index,c.label,c.href,i,e,r,n,o,s,a))})),Ze=(e,t,i)=>Fe(i.body).filter((e=>!Ke(e))).filter((i=>Qe(e,i,t)&&(i.textContent||"").trim())).filter((e=>"img"!==e.textContent)).map((e=>e.textContent)),Ke=e=>{var t=e.children;let i=!1;var r=/^(address|kookitmarker|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};class et{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 tt=Node.ELEMENT_NODE,it=Node.TEXT_NODE,rt=Node.CDATA_SECTION_NODE;function nt(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 it:case rt: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===it||e.nodeType===rt)}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===tt){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 lt=["color-0","color-1","color-2","color-3","line-0","line-1","line-2","line-3"],ct=["#FEF3CD","#FBFACC","#CEFACD","#CDE9FA"],dt=["#FF0000","#000080","#0000FF","#2EFF2E"],ht=["#fac106","#ebe702","#0be603","#0493e6"],ut=(e,t,r,n,o,s)=>{var a,l;i.init();let c=lt[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=yt(f),g=0;g{let a=lt[t],l=s.querySelector(".noteLayer"),c=s.querySelector("#koodoPDFLayer");var d=n.getViewport({scale:o});for(let t=0;t-1?"background-color: ":"border-bottom: ")+(a.indexOf("color")>-1?ht[a.split("-")[1]]:`2px solid ${dt[a.split("-")[1]]}`)+"; left:"+(Math.min(h[0],h[2])+parseFloat(getComputedStyle(c).marginLeft))+"px; top:"+Math.min(h[1],h[3])+"px;width:"+Math.abs(h[0]-h[2])+"px; height:"+Math.abs(h[1]-h[3])+"px; z-index: 1; cursor: pointer; opacity: "+(a.indexOf("color")>-1?.3:1)+";"),null==u||u.setAttribute("data-key",i),null==u||u.setAttribute("class","kookit-note"),null==u||u.addEventListener("click",(e=>{e&&e.target&&e.target.dataset&&e.target.dataset.key&&r(e)})),u.ontouchend=e=>{e&&e.target&&e.target.dataset&&e.target.dataset.key&&r(e),e.preventDefault(),e.stopPropagation()},l.appendChild(u))}}},pt=e=>{const t=e.querySelectorAll(".kookit-note");for(let e=0;e{const o=mt(e.getClientRects());for(let e=0;e-1?"background-color: ":"border-bottom: ")+(t.indexOf("color")>-1?ct[t.split("-")[1]]+";opacity: 1":`2px solid ${dt[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;opacity: "+(t.indexOf("color")>-1?.8:1)+"; cursor: pointer;"),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)}},mt=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 bt=(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"),u+1{console.info("flipToPrevPage"),u-1>=0&&(m[u-1].target=1,u=Math.max(u-1,0))},mouseDownHandler:L,mouseUpHandler:C,mouseMoveHandler:x}}}function x(e){if(!y)return;const t=e.touches[0],i=t.screenX,r=t.screenY;g.x=i-y.offsetLeft-o/2,g.y=r-y.offsetTop}function L(e){const t=e.touches[0];c=t.screenX,t.screenX=0?m[u-1].dragging=!0:t.screenX>window.screen.width/2&&u+1a/4*1&&d-c>0?(m[i].target=1,u=Math.max(u-1,0)):i===u?m[i].target=1:i===u-1&&(m[i].target=-1)),m[i].dragging=!1}function T(e){var r=1-Math.abs(e.progress),n=.5*a*(1-e.progress),s=a*e.progress+n,c=20*r,d=.5*a*Math.max(Math.min(1-e.progress,.5),0),u=.5*a*Math.max(Math.min(r,.5),0),f=.5*a*Math.max(Math.min(r,.5),0);e.page.style.width=Math.max(s,0)+"px",p.save(),p.translate(0+o/2,h+0),p.strokeStyle=("no"===t?"rgba(0,0,0,":"rgba(255,255,255,")+.05*r+")",p.lineWidth=30*r,p.beginPath(),p.moveTo(s-n,.5*-c),p.lineTo(s-n,l+.5*c),p.stroke();var g=p.createLinearGradient(s,0,s+u,0);g.addColorStop(0,("no"===t?"rgba(0,0,0,":"rgba(255,255,255,")+.2*r+")"),g.addColorStop(.8,("no"===t?"rgba(0,0,0,":"rgba(255,255,255,")+"0.0)"),p.fillStyle=g,p.beginPath(),p.moveTo(s,0),p.lineTo(s+u,0),p.lineTo(s+u,l),p.lineTo(s,l),p.fill();var m=p.createLinearGradient(s-n-f,0,s-n,0);m.addColorStop(0,("no"===t?"rgba(0,0,0,":"rgba(255,255,255,")+"0.0)"),m.addColorStop(1,("no"===t?"rgba(0,0,0,":"rgba(255,255,255,")+.15*+r+")"),p.fillStyle=m,p.beginPath(),p.moveTo(s-n-f,0),p.lineTo(s-n,0),p.lineTo(s-n,l),p.lineTo(s-n-f,l),p.fill();var y=p.createLinearGradient(s-d,0,s,0);i?(y.addColorStop(.35,i),y.addColorStop(.73,i),y.addColorStop(.9,i),y.addColorStop(1,i)):"no"===t?(y.addColorStop(.35,"#fafafa"),y.addColorStop(.73,"#eeeeee"),y.addColorStop(.9,"#fafafa"),y.addColorStop(1,"#e2e2e2")):(y.addColorStop(.35,"#333"),y.addColorStop(.73,"#444"),y.addColorStop(.9,"#333"),y.addColorStop(1,"#444")),p.fillStyle=y,p.strokeStyle=("no"===t?"rgba(0,0,0,":"rgba(255,255,255,")+"0.06)",p.lineWidth=.5,p.beginPath(),p.moveTo(s,0),p.lineTo(s,l),p.quadraticCurveTo(s,l+2*c,s-n,l+c),p.lineTo(s-n,-c),p.quadraticCurveTo(s,2*-c,s,0),p.fill(),p.stroke(),p.restore()}},vt=(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})),wt=(e,t)=>{var i;const r=t.getElementById("pdf-container-"+e);if(!r)return;let n=document.createElement("iframe");n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",n.style.height="100%",n.style.border="0",n.style.margin="0",n.style.padding="0",n.style.fontSize="100%",n.style.font="inherit",n.scrolling="no",n.tabIndex=0,n.id="pdf-iframe-"+e;let o=document.createElement("style");return o.id="default-style",o.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}",r.appendChild(n),null===(i=n.contentDocument)||void 0===i||i.head.appendChild(o),n},xt=(e,t,i)=>d(void 0,void 0,void 0,(function*(){let r=i.getElementById("pdf-container-"+e);if(r){if("scroll"!==t){let e=r?h(r.offsetLeft)-h(r.marginLeft||parseFloat(getComputedStyle(r).marginLeft)):0;i.body.scrollTo(e,0)}else r.scrollIntoView();r.scrollIntoView()}})),Lt=(e,t,i)=>{var r=!1,n=t.getBoundingClientRect();if("scroll"!==i){let t=n.left;r=t>-10&&t<=e.clientWidth}else{let t=n.top,i=n.bottom;r=t-10>=e.scrollTop&&t+10<=e.scrollTop+e.clientHeight||i-10>=e.scrollTop&&i+10<=e.scrollTop+e.clientHeight||t+10<=e.scrollTop&&i-10>=e.scrollTop+e.clientHeight}return r},Ct=(e,t,i,r,n,o,s,a,l)=>d(void 0,void 0,void 0,(function*(){let c=Math.floor(e.clientWidth/12),d=c%2==0?c:c-1;const h=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))}if(i>0)if("single"===l){let e=r.querySelector("#pdf-container-"+(a-1));e&&e.scrollIntoView()}else r.body.scrollBy(-(h+d)/2,0);else if(i<0)if("single"===l){let e=r.querySelector("#pdf-container-"+(a+1));e&&e.scrollIntoView()}else r.body.scrollBy((h+d)/2,0)}));function Tt(){return window.visualViewport?window.visualViewport.offsetLeft:window.pageXOffset||document.documentElement.scrollLeft||0}function Mt(){return window.visualViewport?window.visualViewport.offsetTop:window.pageYOffset||document.documentElement.scrollTop||0}const St=e=>{const t=e.target;if(!t)return;const i=function(e){if("A"===e.tagName)return e;let t=e;for(;t&&"BODY"!==t.tagName;){if("A"===t.tagName)return t;t=t.parentElement}return null}(t);if(i){e.preventDefault(),e.stopPropagation();const t=i.getAttribute("href");return window.ReactNativeWebView.postMessage(JSON.stringify({event:"link-clicked",href:t})),!1}};const Dt=(e,t,r,n,o,s,a)=>{var l;let c=t.contentWindow||(null===(l=t.contentDocument)||void 0===l?void 0:l.defaultView),h=a.getDocument(),u=0,f=0,p=0,g=0;let m=Math.floor(r.clientWidth/12),y=m%2==0?m:m-1,b=!1,v=0;e.addEventListener("touchend",(function(t){console.info("touchend");let i=(new Date).getTime();if(i-g<=300)return void t.preventDefault();g=i;const l=t.changedTouches[0],d=Date.now();let m=l.screenX,v=l.screenY;const x=d-u,L=m-f,C=v-p;if(b&&"mimical"===o&&"scroll"!==n)return b=!1,a.mouseUpHandler(t),l.screenXwindow.screen.width/4*1&&m-f>0&&a.prev(),void setTimeout((()=>{let e=document.getElementById("book");e&&(e.style.display="none")}),400);if(b&&"sliding"===o&&"scroll"!==n){let I="PDF"===s?h:e;if(window.scrollAnimationId&&cancelAnimationFrame(window.scrollAnimationId),Math.abs(I.body.scrollWidth-I.body.scrollLeft-r.clientWidth)<10)return w&&clearTimeout(w),void(w=setTimeout((()=>{a.next()}),300));if(0===I.body.scrollLeft)return w&&clearTimeout(w),void(w=setTimeout((()=>{a.prev()}),300));I.body.style.transform="";let E,N=r.clientWidth+y,R=I.body.scrollLeft;const B=Math.round(R/N),O=Math.abs(L)/window.screen.width,P=.1;E=L>0&&O>P?(B-1)*N:L<0&&O>P?(B+1)*N:B*N,E=Math.max(0,Math.min(E,I.body.scrollWidth-N)),I.body.scrollWidth-E1-Math.pow(1-e,3);function U(e){const t=e-H;if(t>=$)return I.body.scrollLeft=E,I.body.style.willChange="auto",a.record(),void(b=!1);const i=j(t/$),r=F+W*i;I.body.scrollLeft=r,window.scrollAnimationId=requestAnimationFrame(U)}window.scrollAnimationId=requestAnimationFrame(U)}else{var T=c.getSelection().toString();if(T)window.ReactNativeWebView.postMessage(JSON.stringify({event:"select-text-after-touch",selectedText:T}));else if(x<500&&Math.abs(L)<30&&Math.abs(C)<30){var M=window.screen.width/3,S=window.screen.height/3,D=Math.floor(m/M),k=Math.floor(v/S),A="";0===k&&(0===D||1===D)||1===k&&0===D||2===k&&0===D||0===k&&1===D?A="left":1===k&&1===D?A="center":(0===k&&2===D||1===k&&2===D||2===k&&2===D||2===k&&1===D)&&(A="right"),window.ReactNativeWebView.postMessage(JSON.stringify({event:A}))}else(Math.abs(L)>=30||Math.abs(C)>=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"})))}}),!1),e.addEventListener("touchstart",(function(e){if(!1===St(e))return;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];u=Date.now(),f=i.screenX,p=i.screenY}),!1),e.addEventListener("touchmove",(function(t){if(!b&&Math.abs(t.touches[0].screenX-f)<=10)return;if(t.preventDefault(),window.visualViewport.scale>1&&"PDF"===s)return void t.preventDefault();const i=t.touches[0],r=i.screenX,l=i.screenY,c=r-f,d=l-p;if(!b&&Math.abs(c)>Math.abs(d)&&Math.abs(c)>10){if(b=!0,v=r,e.body.style.transform="translateZ(0)","mimical"===o&&"scroll"!==n){window.ReactNativeWebView.postMessage(JSON.stringify({event:"swipe-start"}));let e=document.getElementById("book");e&&(e.style.display="block",a.mouseDownHandler(t))}}else if(b&&"mimical"===o&&"scroll"!==n&&a.mouseMoveHandler(t),b&&"sliding"===o&&"scroll"!==n){let t="PDF"===s?h:e;const i=r-v,n=t.body.scrollLeft;t.body.scrollLeft=n-i,v=r,requestAnimationFrame((()=>{}))}}),!1),e.addEventListener("click",St,!0);let w=null;e.body.oncontextmenu=function(e){return e.preventDefault(),e.stopPropagation(),!1};let x=0,L=0,C=0;e.addEventListener("selectstart",(t=>{L=Tt(),C=Mt(),"scroll"!==n&&(x=e.body.scrollLeft)}),!1),e.addEventListener("selectionchange",(t=>{x>0&&(e.body.scrollLeft=x),w&&clearTimeout(w),w=setTimeout((()=>d(void 0,void 0,void 0,(function*(){var e;const n=c.getSelection().toString().trim();if(n){var o=c.getSelection().getRangeAt(0);let h=a.getPageSize();var l=o.getBoundingClientRect();if("PDF"===s){let e=o.getClientRects();if(e.length>0){e=Array.from(e).filter((e=>Math.abs(e.height-h.sectionHeight)>10&&Math.abs(e.width-h.sectionWidth)>10&&e.height>0&&e.width>0));let t=1/0,i=1/0,r=-1/0,n=-1/0;for(let o=0;o{var l;let c=t.contentWindow||(null===(l=t.contentDocument)||void 0===l?void 0:l.defaultView),h=a.getDocument(),u=0,f=0,p=0,g=0;let m=Math.floor(r.clientWidth/12),y=m%2==0?m:m-1,b=!1,v=0;e.addEventListener("touchend",(function(t){var l,m;return d(this,void 0,void 0,(function*(){let d=(new Date).getTime();if(d-g<=300)return void t.preventDefault();g=d;const v=t.changedTouches[0],x=Date.now(),L=v.screenX,C=v.screenY,T=x-u,M=L-f,S=C-p;if(b&&"mimical"===o&&"scroll"!==n)return b=!1,a.mouseUpHandler(t),Lwindow.screen.width/4*1&&L-f>0&&a.prev(),void setTimeout((()=>{let e=document.getElementById("book");e&&(e.style.display="none")}),400);if(b&&"sliding"===o&&"scroll"!==n){let E="PDF"===s?h:e;if(window.scrollAnimationId&&cancelAnimationFrame(window.scrollAnimationId),Math.abs(E.body.scrollWidth-E.body.scrollLeft-r.clientWidth)<10)return w&&clearTimeout(w),void(w=setTimeout((()=>{a.next()}),300));if(0===E.body.scrollLeft)return w&&clearTimeout(w),void(w=setTimeout((()=>{a.prev()}),300));E.body.style.transform="";let N,R=r.clientWidth+y,B=E.body.scrollLeft;const O=Math.round(B/R),P=Math.abs(M)/window.screen.width,H=.1;N=M>0&&P>H?(O-1)*R:M<0&&P>H?(O+1)*R:O*R,N=Math.max(0,Math.min(N,E.body.scrollWidth-R)),E.body.scrollWidth-N1-Math.pow(1-e,3);function q(e){const t=e-F;if(t>=j)return E.body.scrollLeft=N,E.body.style.willChange="auto",a.record(),void(b=!1);const i=U(t/j),r=W+$*i;E.body.scrollLeft=r,window.scrollAnimationId=requestAnimationFrame(q)}return void(window.scrollAnimationId=requestAnimationFrame(q))}const D=c.getSelection().toString().trim();if(D){var k=c.getSelection().getRangeAt(0).getBoundingClientRect(),A=a.getPageSize(),I={top:k.top-r.scrollTop,left:k.left,width:k.width,height:k.height,screenWidth:window.innerWidth,screenHeight:window.innerHeight,sectionHeight:A.sectionHeight,chapterDocIndex:0,sectionWidth:A.sectionWidth,gap:A.gap,scale:window.visualViewport.scale,offsetLeft:Tt(),offsetTop:Mt()};i.init();let z=null;if("PDF"===s){let X=t.target.ownerDocument,V=null===(l=null==X?void 0:X.defaultView)||void 0===l?void 0:l.frameElement,J=(null==V?void 0:V.getAttribute("id"))||"",G=J?parseInt(J.split("-").reverse()[0]):0;I.chapterDocIndex=G,z=yield a.getHightlightCoords(G);let _=V.parentElement;_&&(I.top=I.top+parseFloat(getComputedStyle(_).top))}else z=yield a.getHightlightCoords();window.ReactNativeWebView.postMessage(JSON.stringify({event:"select-text",selectedText:D,position:I,range:z}))}else if(T<500&&Math.abs(M)<30&&Math.abs(S)<30){const Y=document.documentElement.clientWidth;document.documentElement.clientHeight;let Z=Math.min(Math.max(L,0),Y);if("PDF"===s&&"double"===n){let te=t.target.ownerDocument,ie=null===(m=null==te?void 0:te.defaultView)||void 0===m?void 0:m.frameElement,re=(null==ie?void 0:ie.getAttribute("id"))||"";(re?parseInt(re.split("-").reverse()[0]):0)%2==1&&(Z+=Y/2)}let K="";const Q=Y/3,ee=Math.min(Math.floor(Z/Q),2);0===ee?K="left":1===ee?K="center":2===ee&&(K="right"),window.ReactNativeWebView.postMessage(JSON.stringify({event:K}))}else(Math.abs(M)>=30||Math.abs(S)>=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"})))}))}),!1),e.addEventListener("touchstart",(function(e){if(!1===St(e))return;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];u=Date.now(),f=i.screenX,p=i.screenY}),!1),e.addEventListener("touchmove",(function(t){const i=c.getSelection().toString().trim();if(!b&&Math.abs(t.touches[0].screenX-f)<=10||i)return;if(window.visualViewport.scale>1&&"PDF"===s)return void t.preventDefault();t.preventDefault();const r=t.touches[0],l=r.screenX,d=r.screenY,u=l-f,g=d-p;if(!b&&Math.abs(u)>Math.abs(g)&&Math.abs(u)>10){if(b=!0,v=l,"mimical"===o&&"scroll"!==n){window.ReactNativeWebView.postMessage(JSON.stringify({event:"swipe-start"}));let e=document.getElementById("book");e&&(e.style.display="block",a.mouseDownHandler(t))}}else if(b&&"mimical"===o&&"scroll"!==n&&a.mouseMoveHandler(t),b&&"sliding"===o&&"scroll"!==n){let t="PDF"===s?h:e;const i=l-v,r=t.body.scrollLeft;t.body.scrollLeft=r-i,v=l,requestAnimationFrame((()=>{}))}}),!1),e.addEventListener("click",St,!0);let w=null;e.addEventListener("touchmove",(e=>{}),!1),e.body.oncontextmenu=function(e){return e.preventDefault(),e.stopPropagation(),!1}};class At extends et{constructor(t){super(),this.tsTransform=()=>{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,kookitmarker").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,kookitmarker").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=bt(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=>{},this.touchEventSet={},"yes"===this.isMobile&&(console.log=function(...e){window.ReactNativeWebView.postMessage(e.map((e=>String(e))).join(", "))},console.info=function(...e){window.ReactNativeWebView.postMessage(e.map((e=>String(e))).join(", "))},console.error=function(...e){window.ReactNativeWebView.postMessage(e.map((e=>String(e))).join(", "))})}getPageSize(){let e="double"===this.readerMode?2:1,t=Math.floor(this.element.clientWidth/12),i=t%2==0?t:t-1,r=this.getIframe();if(!r)return;let n=null==r?void 0:r.getBoundingClientRect().height;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,sectionHeight:n,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 Ue(parseInt(e),i,t,this.chapterDocList,this.element,this.readerMode,this.format,this.tempLocation,r,n),t&&t.indexOf("#")>-1&&(yield ze(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,percentage:r.percentage};let{text:n,chapterTitle:o,chapterDocIndex:s,chapterHref:a,count:l,page:c,cfi:d}=r;if(yield Ue(parseInt(s),o,a,this.chapterDocList,this.element,this.readerMode,this.format,this.tempLocation,t,i),d){const e=new at(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,kookitmarker".indexOf(i.tagName.toLowerCase())>-1){e=i;break}t=t.parentNode}e&&(l="ignore",n=e.textContent)}}yield ze(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=Xe(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;"mimical"===this.animation&&"scroll"!==this.readerMode&&"yes"===this.isMobile&&(yield new Promise((e=>setTimeout(e,500)))),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 We(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)<20&&"scroll"!==this.readerMode||Math.abs(this.element.scrollHeight-h(this.element.scrollTop)-this.element.clientHeight)<20&&"scroll"===this.readerMode?("mimical"===this.animation&&"scroll"!==this.readerMode&&"yes"===this.isMobile&&(yield new Promise((e=>setTimeout(e,500)))),yield Ye(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 We(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 Ye(this.element,this.flatChapter(this.chapterList),this.chapterDocList,this.readerMode,this.format,this.tempLocation,e,t),yield this.record(),this.trigger("rendered"))}))}visibleText(){return d(this,void 0,void 0,(function*(){let e=this.getDocument();return e?Ze(this.element,this.readerMode,e):""}))}audioText(){return d(this,void 0,void 0,(function*(){let e=this.getDocument();return e?((e,t,i)=>{let r=Fe(i.body).filter((e=>!Ke(e))).filter((e=>(e.textContent||"").trim())).filter((e=>"img"!==e.textContent)).map((e=>e.textContent)),n=0,o=Ze(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(){return d(this,void 0,void 0,(function*(){let e=this.getDocument();return e&&e.body.textContent||""}))}highlightNode(e,t){let i=this.getDocument();i&&((e,t,i)=>{let r=Fe(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"PDF"===this.format?yield((e,i)=>d(void 0,void 0,void 0,(function*(){let r=[];for(let t=0;tt.str.indexOf(e)>-1));o>-1&&r.push({excerpt:n.items[o].str,cfi:JSON.stringify({text:n.items[o].str+"#"+t,chapterTitle:i[t].label,chapterDocIndex:t,chapterHref:i[t].href,count:"search",percentage:t/i.length})})}return t.uniq(r,"excerpt")})))(e,this.chapterDocList):yield((e,i)=>d(void 0,void 0,void 0,(function*(){var r;let n=[];for(let t=0;t!Ke(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,this.element)}record(){return d(this,void 0,void 0,(function*(){""!==this.animation&&(yield new Promise((e=>setTimeout(e,1e3))));let e=this.getDocument();e&&(yield Je(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=L(e);return t?(yield Je(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){pt(i);for(let n=0;n{let t=e.contentDocument;t&&i.push(t)})),[e,...i]}getAllIframes(){let e=this.getIframe();if(!e)return[];if("PDF"!==this.format)return[e];let t=this.getDocument();if(!t)return[];let i=t.querySelectorAll("iframe"),r=[];return i.forEach((e=>{let t=e;r.push(t)})),[e,...r]}addTouchEvent(e){let t=this.getAllDocuments(),i=this.getAllIframes();for(let r=0;r{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 It={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"},Nt=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:It[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 T(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 Bt 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 T(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 Me(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 T(this.book);return yield e.getMetadata()}catch(e){throw console.error(e,"error"),e}}))}}const Ot=e=>{if(!e)return"";const t=document.createElement("textarea");return t.innerHTML=e,t.value},Pt={XML:"application/xml",XHTML:"application/xhtml+xml",HTML:"text/html",CSS:"text/css",SVG:"image/svg+xml"},Ht={name:[0,32,"string"],type:[60,4,"string"],creator:[64,4,"string"],numRecords:[76,2,"uint"]},Ft={compression:[0,2,"uint"],numTextRecords:[8,2,"uint"],recordSize:[10,2,"uint"],encryption:[12,2,"uint"]},Wt={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"]},$t={resourceStart:[108,4,"uint"],fdst:[192,4,"uint"],numFdst:[196,4,"uint"],frag:[248,4,"uint"],skel:[252,4,"uint"],guide:[260,4,"uint"]},jt={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"]},qt={magic:[0,4,"string"],length:[4,4,"uint"],numControlBytes:[8,4,"uint"]},zt={magic:[0,4,"string"],offset1:[8,4,"uint"],offset2:[12,4,"uint"]},Xt={magic:[0,4,"string"],length:[4,4,"uint"],numEntries:[8,4,"uint"],codeLength:[12,4,"uint"]},Vt={magic:[0,4,"string"],numEntries:[8,4,"uint"]},Jt={flags:[8,4,"uint"],dataStart:[12,4,"uint"],keyLength:[16,4,"uint"],keyStart:[20,4,"uint"]},Gt={1252:"windows-1252",65001:"utf-8"},_t={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"]},Yt={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},Kt=(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},Qt=new TextDecoder,ei=e=>Qt.decode(e),ti=e=>{if(!e)return;const t=e.byteLength,i=4===t?"getUint32":2===t?"getUint16":"getUint8";return new DataView(e)[i](0)},ii=(e,t)=>Object.fromEntries(Array.from(Object.entries(e)).map((([e,[i,r,n]])=>[e,("string"===n?ei:ti)(t.slice(i,i+r))]))),ri=e=>new TextDecoder(Gt[e]),ni=(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}},oi=e=>{let t=0;for(const i of e.subarray(-4))128&i&&(t=0),t=t<<7|127&i;return t},si=e=>{let t=0;for(;e>0;e>>=1)1&~e||t++;return t},ai=e=>{let t=0;for(;!(1&e);)e>>=1,t++;return t},li=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},di=async(e,t)=>{const i=await t(e),r=ii(Ut,i);if("INDX"!==r.magic)throw new Error("Invalid INDX record");const n=ri(r.encoding),o=i.slice(r.length),s=ii(qt,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}=ni(n,p);d.push([e,null,i,t]),p+=r}else d.push([e,1,null,t]);else d.push([e,a>>ai(i),null,t])}const g={};for(const[e,t,i,r]of d){const o=[];if(null!=t)for(let e=0;eti(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 ei(await this.#c.slice(t,t+4).arrayBuffer())}}class ui extends hi{#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 Li(this).init():new gi(this).init()}#y(e){const t=ii(Ft,e),i=ii(Wt,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=Yt[o];i.language=a?.[s>>2]??a?.[0];const l=64&i.exthFlag?((e,t)=>{const{magic:i,count:r}=ii(jt,e);if("EXTH"!==i)throw new Error("Invalid EXTH header");const n=ri(t),o={};let s=12;for(let t=0;t=8?ii($t,e):null}}async#b(){const{palmdoc:e,mobi:t}=this.headers;this.#f=ri(t.encoding),this.#p=new TextEncoder;const{compression:i}=e;if(this.#g=1===i?e=>e:2===i?li:17480===i?await(async(e,t)=>{const i=await t(e.huffcdic),{magic:r,offset1:n,offset2:o}=ii(zt,i);if("HUFF"!==r)throw new Error("Invalid HUFF record");const s=Array.from({length:256},((e,t)=>n+4*t)).map((e=>ti(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=>[ti(i.slice(e,e+4)),ti(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=si(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=ei(t.slice(0,4));return"FONT"===i?(async(e,t)=>{const{flags:i,dataStart:r,keyLength:n,keyStart:o}=ii(Jt,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 di(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:Ot(t?.title||this.decode(e.title)),author:t?.creator?.map(Ot),publisher:Ot(t?.publisher),language:t?.language??e.language,published:t?.date,description:Ot(t?.description),subject:t?.subject?.map(Ot),rights:Ot(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 fi=/<\s*(?:mbp:)?pagebreak[^>]*>/gi,pi=/<[^<>]+filepos=['"]{0,1}(\d+)[^<>]*>/gi;class gi{parser=new DOMParser;serializer=new XMLSerializer;#v=new Map;#w=new Map;#r=new Map;#x;#L=[];#C=Pt.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(fi),(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.#L=[...new Set(Array.from(t.matchAll(pi),(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.#v.has(e))return this.#v.get(e);const t=await this.mobi.loadResource(e),i=URL.createObjectURL(new Blob([t]));return this.#v.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.#w.has(e))return this.#w.get(e);const{raw:t}=e,i=this.#L.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=Kt(r,a,t.subarray(n,s?.offset))})));const n=this.mobi.decode(r).replaceAll(fi,"");return this.#w.set(e,n),n}async createDocument(e){const t=await this.loadText(e);return this.parser.parseFromString(t,this.#C)}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.#C}));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.#v.values())URL.revokeObjectURL(e);for(const e of this.#r.values())URL.revokeObjectURL(e)}}const mi=/kindle:(flow|embed):(\w+)(?:\?mime=(\w+\/[-+.\w]+))?/,yi=/kindle:pos:fid:(\w+):off:(\w+)/,bi=e=>{const[t,i]=e.match(yi).slice(1);return{fid:parseInt(t,32),off:parseInt(i,32)}},vi=(e=0,t=0)=>`kindle:pos:fid:${e.toString(32).toUpperCase().padStart(4,"0")}:off:${t.toString(32).toUpperCase().padStart(10,"0")}`,wi=e=>{const t=e.match(/\s(id|name|aid)\s*=\s*['"]([^'"]*)['"]/i);if(!t)return;const[,i,r]=t;return`[${i}="${CSS.escape(r)}"]`},xi=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 Li{parser=new DOMParser;serializer=new XMLSerializer;#r=new Map;#T=new Map;#M=new Map;#S={};#x;#D;#k=new Uint8Array;#A=new Uint8Array;#I=-1;#E=-1;#C=Pt.XHTML;#N=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=ii(Vt,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=>[ti(i.slice(e,e+4)),ti(i.slice(e+4,e+8))]));this.#S.fdstTable=n,this.#D=n[n.length-1][1]}catch{}const i=(await di(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 di(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.#S.skelTable=i,this.#S.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,Pt.XML);for(const e of n.querySelectorAll("spine > itemref")){const t=parseInt(e.getAttribute("skelid"));s.set(t,xi(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=vi(n,o),a=this.#T.get(n);return a?a.push(o):this.#T.set(n,[o]),{label:Ot(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 di(e,t);return i.map((({name:e,tagMap:t})=>({label:r[t[1][0]]??"",type:e?.split(/\s/),href:vi(t[6]?.[0]??t[3]?.[0])})))}}async loadResourceBlob(e){const{resourceType:t,id:i,type:r}=(e=>{const[t,i,r]=e.match(mi).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=[Pt.XHTML,Pt.HTML,Pt.CSS,Pt.SVG].includes(r)?await this.replaceResources(this.mobi.decode(n)):n,s=r===Pt.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.#N.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(mi,"g"),this.loadResource.bind(this))}async loadRaw(e,t){const i=t-this.#k.length,r=null==this.#D?1/0:this.#D-this.#A.length-e;if(i<0||ie;){const e=this.mobi.headers.palmdoc.numTextRecords-1-++this.#E,t=await this.mobi.loadText(e);this.#A=Zt(t,this.#A)}const n=this.#D-this.#A.length;return this.#A.slice(e-n,t-n)}loadFlow(e){if(e<4294967295)return this.loadRaw(...this.#S.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=Kt(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=wi(i);this.#R(e.index,t,r)}}return this.mobi.decode(o)}async createDocument(e){const t=await this.loadText(e);return this.parser.parseFromString(t,this.#C)}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.#C);r.querySelector("parsererror")&&(this.#C=Pt.HTML,r=this.parser.parseFromString(i,this.#C));for(const[e,t]of this.#N)for(const i of r.querySelectorAll(`img[src="${e}"]`))i.replaceWith(t);const n=URL.createObjectURL(new Blob([this.serializer.serializeToString(r)],{type:this.#C}));return this.#r.set(e,n),n}getIndexByFID(e){return this.#x.findIndex((t=>t.frags.some((t=>t.index===e))))}#R(e,t,i){const r=this.#M.get(e);if(r)r.set(t,i);else{const r=new Map;this.#M.set(e,r),r.set(t,i)}}async resolveHref(e){const{fid:t,off:i}=bi(e),r=this.getIndexByFID(t);if(r<0)return;const n=this.#M.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=wi(d);this.#R(t,i,h);return{index:r,anchor:e=>e.querySelector(h)}}splitTOCHref(e){const t=bi(e);return[this.getIndexByFID(t.fid),t]}getTOCFragment(e,{fid:t,off:i}){const r=this.#M.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 Ci 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 T(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"===ei(await e.slice(60,68).arrayBuffer()))(t))&&(this.book=yield new ui({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 T(this.book);return yield e.getMetadata()}catch(e){throw console.error(e),e}}))}}const Ti=e=>`${Di()?".":""}/lib/pdfjs/${e}`,Mi=window.pdfjsLib,Si=async e=>await(await fetch(e)).text(),Di=()=>"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),ki=async()=>await Si(Ti("text_layer_builder.css")),Ai=async()=>await Si(Ti("annotation_layer_builder.css")),Ii=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 `],{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}),Ni=async(e,t)=>{const i=new Mi.PDFDataRangeTransport(e.size,[]);i.requestDataRange=(t,r)=>{e.slice(t,r).arrayBuffer().then((e=>{i.onDataRange(t,e)}))};const r=await Mi.getDocument({range:i,cMapUrl:Ti("cmaps/"),standardFontDataUrl:Ti("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);const l=new Map;return n.sections=Array.from({length:r.numPages}).map(((e,t)=>({id:t,load:async()=>{const e=l.get(t);if(e)return e;const i=await Ii(await r.getPage(t+1));return l.set(t,i),i},unload:async()=>{(await r.getPage(t+1)).cleanup()},render:async(e,i,n)=>{await(async(e,t,i,r)=>{let n=window.devicePixelRatio*("yes"===r?1/i*1.5:1);const o=i*n;let s=t.querySelector("#koodoPDFLayer");s.style.visibility="hidden",s.style.transform=`scale(${1/n})`,s.style.transformOrigin="top left",s.style.setProperty("--scale-factor",o);const a=e.getViewport({scale:o}),l=document.createElement("canvas");s.style.width=`${a.width}px`,s.style.height=`${a.height}px`,l.height=a.height,l.width=a.width;const c=l.getContext("2d");await e.render({canvasContext:c,viewport:a,background:"rgba(0,0,0,0)"}).promise,t.querySelector("#canvas").replaceChildren(t.adoptNode(l)),s.style.overflow="hidden";const d=t.querySelector("#textLayer"),h=new Mi.TextLayer({textContentSource:await e.streamTextContent(),container:d,viewport:a});await h.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 u=document.createElement("div");u.className="endOfContent",d.append(u);let f=!1,p=null;d.onpointerdown=()=>{d.classList.add("selecting"),f=!0},"yes"!==r?(d.onpointerup=()=>{d.classList.remove("selecting"),f=!1,u.remove(),d.append(u)},d.onpointermove=e=>{if(!f)return;let t=e.target.closest(".textLayer > span");const i=null!==t;d.style.cursor=i?"text":"default",i&&(p=t),u.remove(),d.insertBefore(u,p)}):t.addEventListener("selectionchange",(e=>{if(!f)return;let i=t?.defaultView;var r=i.getSelection().getRangeAt(0).endContainer;let n=r.nodeType===Node.TEXT_NODE?r.parentNode:r;n=n.closest(".textLayer > span");const o=null!==n;d.style.cursor=o?"text":"default",o&&(p=n),u.remove(),d.insertBefore(u,p.nextSibling.nextSibling.nextSibling)}));const g=t.querySelector("#annotationLayer");await new Mi.AnnotationLayer({page:e,viewport:a,div:g}).render({annotations:await e.getAnnotations(),linkService:{goToDestination:()=>{},getDestinationHash:e=>JSON.stringify(e),addLinkAttributes:(e,t)=>e.href=t}}),s.style.marginLeft=`calc(50% - ${s.getBoundingClientRect().width/2}px)`,s.style.visibility="visible"})(await r.getPage(t+1),e,i,n)},getTextContent:async()=>{const e=await r.getPage(t+1);return await e.getTextContent()},size:1e3,getDimension:async()=>{let e=(await r.getPage(t+1)).getViewport({scale:1});return{width:e.width,height:e.height}},getPage:async()=>await r.getPage(t+1)}))),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()=>Ii(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 T(this.book);this.chapterList=yield i.getChapter(this.book.toc),this.chapterDocList=yield i.getChapterDoc(),m(e);const r=yield this.chapterDocList[0].text.getDimension();let n=this.getDocument();if(!n)return;((e,t,i,r)=>{for(let n=0;n{o&&clearTimeout(o),o=setTimeout((()=>d(this,void 0,void 0,(function*(){yield this.handlePDFScrollEvent(n),yield this.record()}))),200)})):n.addEventListener("scroll",(e=>{o&&clearTimeout(o),o=setTimeout((()=>d(this,void 0,void 0,(function*(){yield this.handlePDFScrollEvent(n),yield this.record()}))),200)})),((e,t,i)=>{if("scroll"===t)return;let r="double"===t?2:1,n=Math.floor(e.clientWidth/12),o=n%2==0?n:n-1;i.body.setAttribute("style",e.getAttribute("style")+`height: 100%;overflow-y: hidden;overflow-X: hidden;padding-left: 0px;padding-right: 0px;margin: 0px;box-sizing: border-box;touch-action: manipulation; overscroll-behavior: none;max-width: inherit;column-fill: auto;column-gap: ${o}px; column-width: ${(e.clientWidth-o)/r}px;`)})(e,this.readerMode,n),t()}))))}handlePDFScrollEvent(e){return d(this,void 0,void 0,(function*(){let t=e.querySelectorAll(".pdf-container");for(let i=0;i{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 Ni(t,this.readerMode))}catch(e){throw console.error(e),e}}))}preCache(){return d(this,void 0,void 0,(function*(){return""}))}goToChapterIndex(e){return d(this,void 0,void 0,(function*(){this.chapterDocList.length>0&&(yield this.goToChapter(e,this.chapterDocList[e].href,this.chapterDocList[e].label))}))}getPageSize(){let e="double"===this.readerMode?2:1,t=Math.floor(this.element.clientWidth/12),i=t%2==0?t:t-1,r=this.getDocument();if(!r)return;let n=r.querySelectorAll("iframe")[0],o=null==n?void 0:n.getBoundingClientRect().height;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,sectionHeight:o,gap:i}}goToChapter(e,t,i){return d(this,void 0,void 0,(function*(){"double"===this.readerMode&&e%2==1&&e--;let t=this.getDocument(),i=this.getIframe();t&&i&&(yield this.renderPdfPage(e,t),yield xt(parseInt(e),this.readerMode,t),yield this.record())}))}getPositionByChapter(e){return{percentage:e/this.chapterDocList.length,chapterDocIndex:e+"",chapterHref:this.chapterDocList[e].href,chapterTitle:this.chapterDocList[e].label,text:""}}goToPercentage(e){return d(this,void 0,void 0,(function*(){if(this.chapterDocList.length>0){let t=1===e?this.chapterDocList.length-1:Math.floor(this.chapterDocList.length*e);yield this.goToChapter(t,this.chapterDocList[t].href,this.chapterDocList[t].label)}}))}goToPosition(e){var t;return d(this,void 0,void 0,(function*(){let i=this.getDocument(),r=this.getIframe();if(!i||!r)return;let n=JSON.parse(e);void 0===n.chapterDocIndex&&(n.chapterDocIndex=0),this.tempLocation={text:n.text,chapterTitle:n.chapterTitle,chapterDocIndex:n.chapterDocIndex,chapterHref:n.chapterHref,count:n.count,page:n.page,percentage:n.percentage};let{chapterTitle:o,chapterDocIndex:s,chapterHref:a}=n;if("double"===this.readerMode&&s%2==1&&s--,yield this.renderPdfPage(parseInt(s),i),"scroll"===this.readerMode){let e=this.getSubIframe(void 0!==s?s:parseInt(this.tempLocation.chapterDocIndex));if(!e)return;let i=(null===(t=e.parentElement)||void 0===t?void 0:t.getBoundingClientRect().height)||0;r.style.height=i*this.chapterDocList.length+"px"}yield xt(parseInt(s),this.readerMode,i),yield this.record(),this.trigger("page-changed")}))}prev(e){return d(this,void 0,void 0,(function*(){let t=this.getDocument(),i=this.getIframe();t&&i&&("scroll"===this.readerMode?this.element.scrollBy({left:0,top:-(this.element.clientHeight-50),behavior:"smooth"}):("ios"===e?yield Ct(this.element,this.animation,1,t,this.flipToNextPage,this.flipToPrevPage,this.isMobile,parseInt(this.tempLocation.chapterDocIndex||"0"),this.readerMode):yield We(this.element,this.animation,1,t,this.flipToNextPage,this.flipToPrevPage,this.isMobile),yield this.renderPdfPage(parseInt(this.tempLocation.chapterDocIndex)-("double"===this.readerMode?2:1),t)),yield this.record())}))}next(e){return d(this,void 0,void 0,(function*(){let t=this.getDocument(),i=this.getIframe();t&&i&&("scroll"===this.readerMode?this.element.scrollBy({left:0,top:this.element.clientHeight-50,behavior:"smooth"}):("ios"===e?yield Ct(this.element,this.animation,-1,t,this.flipToNextPage,this.flipToPrevPage,this.isMobile,parseInt(this.tempLocation.chapterDocIndex||"0"),this.readerMode):yield We(this.element,this.animation,-1,t,this.flipToNextPage,this.flipToPrevPage,this.isMobile),yield this.renderPdfPage(parseInt(this.tempLocation.chapterDocIndex)+("double"===this.readerMode?2:1),t)),yield this.record())}))}prevChapter(){return d(this,void 0,void 0,(function*(){yield this.prev()}))}nextChapter(){return d(this,void 0,void 0,(function*(){yield this.next()}))}visibleText(){return d(this,void 0,void 0,(function*(){return this.getDocument()?yield(e=parseInt(this.tempLocation.chapterDocIndex||"0"),t=this.chapterDocList,i=this.readerMode,d(void 0,void 0,void 0,(function*(){let r=(yield t[e].text.getTextContent()).items.map((e=>e.str));if("double"===i){let i=(yield t[e+1].text.getTextContent()).items.map((e=>e.str));r=r.concat(i)}return r}))):"";var e,t,i}))}audioText(){return d(this,void 0,void 0,(function*(){return yield this.visibleText()}))}chapterText(){return d(this,void 0,void 0,(function*(){return(yield this.visibleText()).join(" ")}))}record(){return d(this,void 0,void 0,(function*(){""!==this.animation&&(yield new Promise((e=>setTimeout(e,1e3))));let e=this.getDocument();e&&(yield this.handlePDFRecord(e))}))}handlePDFRecord(e){return d(this,void 0,void 0,(function*(){let t=e.querySelectorAll(".pdf-container");if(t.length>0&&Lt(this.element,t[t.length-1],this.readerMode))this.handleRecord(t[t.length-1]);else for(let e=0;e{let r=parseInt(e.split("#").reverse()[0]),n=e.split("#").slice(0,-1).join("#"),o=i.getElementById("pdf-iframe-"+r);o||(o=wt(r,i));let s=null==o?void 0:o.contentDocument;if(!s)return;let a=s.querySelectorAll("p,span"),l=Array.from(a).filter(((e,t)=>(e.textContent||"").trim()&&e.textContent===n));l.length>0&&l[0].setAttribute("style",l[0].getAttribute("style")+t)})(e,t,i)}getProgress(){return{totalPage:this.chapterDocList.length,currentPage:parseInt(this.tempLocation.chapterDocIndex||"0")+1}}getNotePosition(){var e;return d(this,void 0,void 0,(function*(){let t=this.getDocument();if(!t)return;let i=L(t);if(!i)return;let r=i.ownerDocument,n=null===(e=null==r?void 0:r.defaultView)||void 0===e?void 0:e.frameElement,o=(null==n?void 0:n.getAttribute("id"))||"",s=o?parseInt(o.split("-").reverse()[0]):0;return Object.assign(Object.assign({},this.tempLocation),{chapterDocIndex:s})}))}getSubDocument(e){let t=document.getElementById("page-area");if(!t)return null;let i=t.getElementsByTagName("iframe")[0];if(!i)return null;let r=i.contentDocument;if(!r)return null;let n=r.getElementById("pdf-iframe-"+e);return n||(wt(e||0,r),n=r.getElementById("pdf-iframe-"+e)),n.contentDocument}getSubIframe(e){let t=document.getElementById("page-area");if(!t)return null;let i=t.getElementsByTagName("iframe")[0];if(!i)return null;let r=i.contentDocument;return r?(i=r.getElementById("pdf-iframe-"+e),i||(wt(e||0,r),i=r.getElementById("pdf-iframe-"+e)),i):null}getHightlightCoords(e){return d(this,void 0,void 0,(function*(){let t=void 0!==e?e:parseInt(this.tempLocation.chapterDocIndex),i=this.getSubDocument(e);if(!i)return;var r=i.getSelection().getRangeAt(0).getClientRects();let n=yield this.chapterDocList[t].text.getPage(),o=yield vt(this.element,this.readerMode,this.chapterDocList,t);var s=n.getViewport({scale:o});let a=i.querySelector("canvas");var l=null==a?void 0:a.getClientRects()[0];let c=[];for(let e=0;er[e].left&&(c[c.length-1].left=r[e].left),c[c.length-1].right=this.chapterDocList.length||e<0)return;let i=t.getElementById("pdf-iframe-"+e);i||(i=wt(e,t));let r=null==i?void 0:i.contentDocument;if(!r)return;if(r.body.innerHTML)return;r.body.innerHTML="";let n=yield fetch(yield this.chapterDocList[e].text.load()).then((e=>e.blob())),o=yield n.text();r.body.innerHTML=o;let s=yield vt(this.element,this.readerMode,this.chapterDocList,e);if("single"===this.readerMode||"double"===this.readerMode){let i=t.querySelector("#pdf-container-"+e);if(!i)return;i.style.top=`calc(${this.element.clientHeight/2}px - ${i.getBoundingClientRect().height/2}px)`,"single"===this.readerMode&&(this.element.clientHeight>parseFloat(getComputedStyle(i).paddingTop)?i.style.height=this.element.clientHeight-parseFloat(getComputedStyle(i).paddingTop)+"px":i.style.marginBottom=this.element.clientHeight-parseFloat(getComputedStyle(i).paddingTop)+"px")}yield this.chapterDocList[e].text.render(r,s,this.isMobile),this.trigger("rendered")}))}handleUnloadPDFChapter(e,t){return d(this,void 0,void 0,(function*(){if(e>=this.chapterDocList.length||e<0)return;let i=t.getElementById("pdf-iframe-"+e),r=null==i?void 0:i.contentDocument;r&&""!==r.body.innerHTML&&(yield this.chapterDocList[e].text.unload(),r.body.innerHTML="")}))}renderPdfPage(e,t){return d(this,void 0,void 0,(function*(){yield this.handleRenderPDFChapter(e,t),yield this.handleRenderPDFChapter(e+1,t)}))}}const Bi=(e,t=!1,i="",r)=>{const n=(new DOMParser).parseFromString(t?((e,t,i)=>{let r=e.split("\n");1===r.length&&(r=e.split("\r"));const n=[];let o=!1;if(i&&i.refresh&&(o=!0),r.length>1e4&&!o){i&&i.text||(i={text:r[0],chapterTitle:"",chapterDocIndex:0});let e=r.findIndex((e=>Ie(e)===Ie(i.text)));-1===e&&(e=0);const o=Math.max(e-1e3,0),s=Math.min(e+1e3,r.length),a=r.slice(o,s),l=a.filter((e=>{const i=Ie(e);return i&&Ee(i,t)})),c=new Set(l.map((e=>Ie(e))));let d=l.findIndex((e=>Ie(e)===Ie(i.chapterTitle)));if(-1===d&&(d=0),d0)for(let t=0;tChapter ${t}`),n.push(`

Chapter ${t}

`)}for(const e of a){const t=Ie(e);t&&c.has(t)?n.push(`

${t}

`):n.push(`

${e}

`)}}else for(const e of r){const i=Ie(e);i&&Ee(i,t)?n.push(`

${i}

`):n.push(`

${e}

`)}return n.join("")||`

Title

${e}

`})(e,i,r):e,"text/html");let o=Oi(n);0===o.length&&(o=Wi(n));for(let e=0;e""};return c.sections=l.map((e=>({id:e.index,load:()=>{return t=e.index,d(void 0,void 0,void 0,(function*(){return URL.createObjectURL(new Blob([l[t].text],{type:"text/html"}))}));var t},unload:()=>{e.index}}))),c.toc=l.map((e=>({label:e.label,href:"title"+e.index}))).filter((e=>""!==e.label)),c.rendition={layout:"pre-paginated"},c.resolveHref=e=>({index:parseInt(e.substring(5,e.length))}),c.splitTOCHref=e=>[e,null],c.getTOCFragment=e=>e.documentElement,c},Oi=e=>Array.from(e.querySelectorAll("h1,h2,h3,h4,h5,h6,title")),Pi=e=>{let t=[],i=e.split(" ").filter((e=>""!==e.trim())),r=i.map((e=>Hi(e)||Fi(e)));return t=i.map(((e,t)=>({index:t,label:r[t],text:e,href:"title"+t}))),t},Hi=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())||""},Fi=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())||""},Wi=e=>{let t=e.getElementsByTagName("*"),i=Array.from(t).filter((e=>1===e.childNodes.length&&e.childNodes[0].nodeType===Node.TEXT_NODE&&Ee(Ie(e.textContent)))),r=[];for(let e=0;ed(this,void 0,void 0,(function*(){this.element=e,this.book||(yield this.parse(t));let r=new T(this.book);this.chapterList=yield r.getChapter(this.book.toc),this.chapterDocList=yield r.getChapterDoc(),m(e);let n=this.getDocument();n&&(x(e,this.readerMode,n),i())}))))}parse(e){return d(this,void 0,void 0,(function*(){try{const t=new TextDecoder(this.charset),i=new Uint8Array(this.txtBuffer);let r=t.decode(i);this.book=Bi(r,!0,this.parserRegex,e)}catch(e){throw console.error(e),e}}))}refreshContent(){return d(this,void 0,void 0,(function*(){yield this.parse({refresh:!0});let e=new T(this.book);return this.chapterList=yield e.getChapter(this.book.toc),this.chapterDocList=yield e.getChapterDoc(),this.chapterList}))}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=4096,i=e.byteLength,r=Math.min(i,t),n=new Uint8Array(e,0,r);const s=o.detect(n)||"utf8";return this.charset=s,{charset:s}}catch(e){return console.error("Error detecting charset:",e),this.charset="utf8",{charset:"utf8"}}}))}}const ji=({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(((e,t)=>{const i=parseInt(e.replace(/\D/g,"")),r=parseInt(t.replace(/\D/g,""));return isNaN(i)||isNaN(r)?isNaN(i)?isNaN(r)?e.localeCompare(t):1:-1:i-r})),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 Ui 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 T(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=ji(e,t,this.readerMode)}else if("CBT"===this.format){const e=yield this.makeTarLoader();this.book=ji(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=ji(e,t,this.readerMode)}else if("CB7"===this.format){const e=yield this.make7zLoader();this.book=ji(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 qi=e=>e?.trim()?.replace(/\s{2,}/g," "),zi=e=>qi(e?.textContent),Xi={XLINK:"http://www.w3.org/1999/xlink",EPUB:"http://www.idpf.org/2007/ops"},Vi="application/xml",Ji="application/xhtml+xml",Gi={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"},_i={epigraph:["blockquote"],subtitle:["h2",Gi],"text-author":["p",Gi],date:["p",Gi],stanza:"stanza"},Yi={title:["header",{p:["h1",Gi],"empty-line":["br"]}],epigraph:["blockquote","self"],image:"image",annotation:["aside"],section:["section","self"],p:["p",Gi],poem:["blockquote",_i],subtitle:["h2",Gi],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",Gi]};_i.epigraph.push(Yi);const Zi={image:"image",title:["section",{p:["h1",Gi],"empty-line":["br"]}],epigraph:["section",Yi],section:["section",Yi]},Ki=e=>{const t=e.getAttributeNS(Xi.XLINK,"href"),[,i]=t.split("#"),r=e.getRootNode().getElementById(i);return r?`data:${r.getAttribute("content-type")};base64,${r.textContent}`:t};class Qi{constructor(e){this.fb2=e,this.doc=document.implementation.createDocument(Xi.XHTML,"html")}image(e){const t=this.doc.createElement("img");return t.alt=e.getAttribute("alt"),t.title=e.getAttribute("title"),t.setAttribute("src",Ki(e)),t}anchor(e){const t=this.convert(e,{a:["a",Gi]});return t.setAttribute("href",e.getAttributeNS(Xi.XLINK,"href")),"note"===e.getAttribute("type")&&t.setAttributeNS(Xi.EPUB,"epub:type","noteref"),t}stanza(e){const t=this.convert(e,{stanza:["p",{title:["header",{p:["strong",Gi],"empty-line":["br"]}],subtitle:["p",Gi]}]});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 er=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"})),tr="data-foliate-id",ir=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,Vi),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,Vi)}return n})(e),r=new Qi(i),n=e=>i.querySelector(e),o=e=>[...i.querySelectorAll(e)],s=e=>{const t=zi(e.querySelector("nickname"));if(t)return t;const i=zi(e.querySelector("first-name")),r=zi(e.querySelector("middle-name")),n=zi(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")??zi(e),l=n("title-info annotation");t.metadata={title:zi(n("title-info book-title")),identifier:zi(n("document-info id")),language:zi(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(zi)),publisher:zi(n("publish-info publisher")),published:a(n("title-info date")),modified:a(n("document-info date")),description:l?r.convert(l,{annotation:["div",Yi]}).innerHTML:null,subject:o("title-info genre").map(zi)},t.getCover=()=>fetch(Ki(n("coverpage image"))).then((e=>e.blob()));const c=Array.from(i.querySelectorAll("body"),(e=>{const t=r.convert(e,{body:["body",Zi]});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(tr,t),{title:zi(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:Ji}),a=URL.createObjectURL(s);return{ids:e,title:qi(i.querySelector(".title, .subtitle, p")?.textContent??(i.classList.contains("title")?i.textContent:"")),titles:t,load:()=>a,createDocument:()=>(new DOMParser).parseFromString(n,Ji),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(`[${tr}="${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(`[${tr}="${t}"]`),t};class rr 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 T(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 ir(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 T(this.book);return yield e.getMetadata()}catch(e){throw console.error(e),e}}))}}class nr 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 Nt(this.cacheBuffer);let i=new T(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 or 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 T(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=Bi(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 sr 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 T(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=Bi(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 ar 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 T(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:It[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=Bi(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{nr as CacheRender,Ui as ComicRender,or as DocxRender,Bt as EpubRender,rr as Fb2Render,ar as HtmlRender,sr as MdRender,Ci as MobiRender,Ri as PdfRender,$i as TxtRender}; diff --git a/src/assets/locales/zh-CN/translation.json b/src/assets/locales/zh-CN/translation.json index f84c6838..90290d81 100644 --- a/src/assets/locales/zh-CN/translation.json +++ b/src/assets/locales/zh-CN/translation.json @@ -341,6 +341,7 @@ "Beta pharse": "内测期间", "Trial user": "试用用户", "Paid user": "付费用户", + "Pro user": "专业版用户", "Free user": "免费用户", "Get device identifier": "获取设备标识符", "Sync failed": "同步失败", @@ -588,7 +589,9 @@ "Reset": "重置", "Pro version": "升级专业版", "Upgrade to Pro": "升级专业版", - "To ensure a smooth synchronization experience, your reading progress, notes, highlights, bookmarks, and other data will be stored and synced through our cloud service": "为了确保流畅的同步体验,您的阅读进度、笔记、高亮、书签等数据将通过我们的云服务进行存储和同步", + "Enable this option to increase synchronization speed. Your reading progress, notes, highlights, bookmarks, and other reading-related data will be stored and synced via our cloud service. Turning off this option will remove the above data from our cloud.": "启用此选项以提高同步速度。您的阅读进度、笔记、高亮、书签等阅读相关数据将通过我们的云服务进行存储和同步。关闭此选项将从我们的云端删除上述数据", + "Access may be unstable in China": "国内网络访问可能不稳定", + "Only WebDAV service provided by Alist is directly supported in Browser, Other WebDAV services need to enable CORS to work properly": "由于浏览器的限制,仅支持 Alist 提供的 WebDAV 服务,其他 WebDAV 服务需要开启 CORS 才能正常使用", "Enable Koodo Sync": "启用 Koodo Sync", "Disable automatic sync": "禁用自动同步", "By default, Koodo Reader will automatically synchronize your data when you open the app and exit reading": "默认情况下,Koodo Reader 会在您打开应用和退出阅读时自动同步数据", diff --git a/src/components/popups/popupDict/popupDict.css b/src/components/popups/popupDict/popupDict.css index 3e8c1ad4..9d985a36 100644 --- a/src/components/popups/popupDict/popupDict.css +++ b/src/components/popups/popupDict/popupDict.css @@ -106,7 +106,7 @@ /* .dict-container li div { display: inline; } */ -.dict-container ul { +/* .dict-container ul { counter-reset: my-counter; } @@ -117,6 +117,37 @@ .dict-container li::before { content: counter(my-counter) ". "; font-weight: bold; +} */ +/* 在 popupDict.css 中添加这些规则,它们会覆盖 reset.css 中的全局规则 */ +.dict-container ul { + list-style-type: disc !important; /* 实心圆点 */ + padding-left: 2em !important; /* 添加缩进 */ + margin: 1em 0 !important; /* 添加上下边距 */ +} + +.dict-container ol { + list-style-type: decimal !important; /* 数字编号 */ + padding-left: 2em !important; /* 添加缩进 */ + margin: 1em 0 !important; /* 添加上下边距 */ +} + +.dict-container li { + list-style: inherit !important; /* 继承父元素的列表样式 */ + display: list-item !important; /* 显示为列表项 */ + margin: 0.5em 0 !important; /* 添加上下边距 */ +} + +/* 定义嵌套列表的样式 */ +.dict-container ul ul { + list-style-type: circle !important; /* 二级列表使用空心圆点 */ +} + +.dict-container ul ul ul { + list-style-type: square !important; /* 三级列表使用方块 */ +} + +.dict-container ol ol { + list-style-type: lower-alpha !important; /* 二级有序列表使用小写字母 */ } .audio-player { width: 100px; diff --git a/src/constants/driveList.tsx b/src/constants/driveList.tsx index 5175bb17..33e01eec 100644 --- a/src/constants/driveList.tsx +++ b/src/constants/driveList.tsx @@ -4,10 +4,9 @@ export const driveList = [ value: "webdav", icon: "icon-webdav", isPro: false, - support: ["desktop", "phone"], + support: ["desktop", "browser", "phone"], scoped: false, }, - { label: "Dropbox", value: "dropbox", diff --git a/src/constants/settingList.tsx b/src/constants/settingList.tsx index 1d52433d..3a69bf95 100644 --- a/src/constants/settingList.tsx +++ b/src/constants/settingList.tsx @@ -82,7 +82,7 @@ export const syncSettingList = [ { isElectron: false, title: "Enable Koodo Sync", - desc: "To ensure a smooth synchronization experience, your reading progress, notes, highlights, bookmarks, and other data will be stored and synced through our cloud service", + desc: "Enable this option to increase synchronization speed. Your reading progress, notes, highlights, bookmarks, and other reading-related data will be stored and synced via our cloud service. Turning off this option will remove the above data from our cloud.", propName: "isEnableKoodoSync", }, { diff --git a/src/containers/header/component.tsx b/src/containers/header/component.tsx index cdcb3642..a016cb15 100644 --- a/src/containers/header/component.tsx +++ b/src/containers/header/component.tsx @@ -114,6 +114,21 @@ class Header extends React.Component { this.props.handleFetchNotes(); this.props.handleFetchBookmarks(); }); + this.props.handleCloudSyncFunc(this.handleCloudSync); + document.addEventListener("visibilitychange", () => { + if (document.visibilityState === "visible") { + if (ConfigService.getItem("isFinshReading") === "yes") { + ConfigService.setItem("isFinshReading", "no"); + if ( + this.state.isAutoSync && + ConfigService.getItem("defaultSyncOption") + ) { + this.setState({ isSync: true }); + this.handleCloudSync(); + } + } + } + }); } async UNSAFE_componentWillReceiveProps( nextProps: Readonly, @@ -136,11 +151,10 @@ class Header extends React.Component { console.error(error); } } - if (this.state.isAutoSync) { + if (this.state.isAutoSync && ConfigService.getItem("defaultSyncOption")) { this.setState({ isSync: true }); await this.handleCloudSync(); } - nextProps.handleFetchUserConfig(); } if (!nextProps.isAuthed && nextProps.isAuthed !== this.props.isAuthed) { if (isElectron) { @@ -338,9 +352,9 @@ class Header extends React.Component { if (ConfigService.getReaderConfig("isEnableKoodoSync") === "yes") { ConfigUtil.updateSyncData(); } - setTimeout(() => { - this.props.history.push("/manager/home"); - }, 1000); + // setTimeout(() => { + // this.props.history.push("/manager/home"); + // }, 1000); }; handleSync = async (compareResult) => { try { diff --git a/src/containers/header/index.tsx b/src/containers/header/index.tsx index 13689139..8c814c29 100644 --- a/src/containers/header/index.tsx +++ b/src/containers/header/index.tsx @@ -13,7 +13,7 @@ import { handleFetchDefaultSyncOption, handleFetchLoginOptionList, handleFetchDataSourceList, - handleFetchUserConfig, + handleCloudSyncFunc, } from "../../store/actions"; import { stateType } from "../../store"; import Header from "./component"; @@ -46,7 +46,7 @@ const actionCreator = { handleFetchDefaultSyncOption, handleFetchLoginOptionList, handleFetchDataSourceList, - handleFetchUserConfig, + handleCloudSyncFunc, }; export default connect( mapStateToProps, diff --git a/src/containers/header/interface.tsx b/src/containers/header/interface.tsx index 83abc280..08adb6d0 100644 --- a/src/containers/header/interface.tsx +++ b/src/containers/header/interface.tsx @@ -20,7 +20,6 @@ export interface HeaderProps extends RouteComponentProps { handleImportDialog: (isOpenImportDialog: boolean) => void; handleFeedbackDialog: (isShow: boolean) => void; handleFetchAuthed: () => void; - handleFetchUserConfig: () => void; handleFetchDefaultSyncOption: () => void; handleFetchLoginOptionList: () => void; handleFetchDataSourceList: () => void; @@ -29,6 +28,9 @@ export interface HeaderProps extends RouteComponentProps { t: (title: string) => string; handleFetchNotes: () => void; handleFetchBookmarks: () => void; + handleCloudSyncFunc: ( + cloudSyncFunc: () => Promise + ) => void; } export interface HeaderState { diff --git a/src/containers/panels/operationPanel/component.tsx b/src/containers/panels/operationPanel/component.tsx index 4fcfcb10..9a0fe82b 100644 --- a/src/containers/panels/operationPanel/component.tsx +++ b/src/containers/panels/operationPanel/component.tsx @@ -75,8 +75,9 @@ class OperationPanel extends React.Component< ConfigService.setReaderConfig("isFullscreen", "yes"); } } - handleExit() { + async handleExit() { ConfigService.setReaderConfig("isFullscreen", "no"); + ConfigService.setItem("isFinshReading", "yes"); this.props.handleReadingState(false); this.props.handleSearch(false); window.speechSynthesis && window.speechSynthesis.cancel(); @@ -85,7 +86,6 @@ class OperationPanel extends React.Component< if (this.props.htmlBook) { this.props.handleHtmlBook(null); } - if (isElectron) { if (ConfigService.getReaderConfig("isOpenInMain") === "yes") { window.require("electron").ipcRenderer.invoke("exit-tab", "ping"); diff --git a/src/containers/panels/operationPanel/interface.tsx b/src/containers/panels/operationPanel/interface.tsx index 791d44a7..69ac09a1 100644 --- a/src/containers/panels/operationPanel/interface.tsx +++ b/src/containers/panels/operationPanel/interface.tsx @@ -21,7 +21,6 @@ export interface OperationPanelProps extends RouteComponentProps { handleOpenMenu: (isOpenMenu: boolean) => void; handleShowBookmark: (isShowBookmark: boolean) => void; handleReadingBook: (currentBook: BookModel | object) => void; - t: (title: string) => string; handleHtmlBook: (htmlBook: HtmlBookModel | null) => void; } diff --git a/src/containers/settings/accountSetting/component.tsx b/src/containers/settings/accountSetting/component.tsx index c17c7e75..364e48f3 100644 --- a/src/containers/settings/accountSetting/component.tsx +++ b/src/containers/settings/accountSetting/component.tsx @@ -647,7 +647,7 @@ class AccountSetting extends React.Component< {this.props.userInfo.type === "trial" ? "Trial user" : this.props.userInfo.type === "pro" - ? "Paid user" + ? "Pro user" : "Free user"} <> diff --git a/src/containers/settings/syncSetting/component.tsx b/src/containers/settings/syncSetting/component.tsx index e90d25e3..85c43f89 100644 --- a/src/containers/settings/syncSetting/component.tsx +++ b/src/containers/settings/syncSetting/component.tsx @@ -11,6 +11,7 @@ import toast from "react-hot-toast"; import { handleContextMenu, openExternalUrl, + testConnection, WEBSITE_URL, } from "../../../utils/common"; import { getStorageLocation } from "../../../utils/common"; @@ -89,12 +90,13 @@ class SyncSetting extends React.Component { this.handleRest(this.state[stateName]); }; handleAddDataSource = (event: any) => { - if (!event.target.value) { + let targetDrive = event.target.value; + if (!targetDrive) { return; } if ( !driveList - .find((item) => item.value === event.target.value) + .find((item) => item.value === targetDrive) ?.support.includes("browser") && !isElectron ) { @@ -106,14 +108,14 @@ class SyncSetting extends React.Component { return; } if ( - driveList.find((item) => item.value === event.target.value)?.isPro && + driveList.find((item) => item.value === targetDrive)?.isPro && !this.props.isAuthed ) { toast(this.props.t("This feature is not available in the free version")); return; } - this.props.handleSettingDrive(event.target.value); - let settingDrive = event.target.value; + this.props.handleSettingDrive(targetDrive); + let settingDrive = targetDrive; if ( settingDrive === "dropbox" || settingDrive === "google" || @@ -126,20 +128,25 @@ class SyncSetting extends React.Component { } }; handleDeleteDataSource = async (event: any) => { - if (!event.target.value) { + let targetDrive = event.target.value; + if (!targetDrive) { return; } - await TokenService.setToken(event.target.value + "_token", ""); - SyncService.removeSyncUtil(event.target.value); - removeCloudConfig(event.target.value); + await TokenService.setToken(targetDrive + "_token", ""); + SyncService.removeSyncUtil(targetDrive); + removeCloudConfig(targetDrive); if (isElectron) { const { ipcRenderer } = window.require("electron"); await ipcRenderer.invoke("cloud-close", { - service: event.target.value, + service: targetDrive, }); } - ConfigService.deleteListConfig(event.target.value, "dataSourceList"); + ConfigService.deleteListConfig(targetDrive, "dataSourceList"); this.props.handleFetchDataSourceList(); + if (targetDrive === ConfigService.getItem("defaultSyncOption")) { + ConfigService.removeItem("defaultSyncOption"); + this.props.handleFetchDefaultSyncOption(); + } toast.success(this.props.t("Deletion successful")); }; handleSetDefaultSyncOption = (event: any) => { @@ -328,10 +335,37 @@ class SyncSetting extends React.Component { /> )} + {this.props.settingDrive === "webdav" && !isElectron && ( +
+ {this.props.t( + "Only WebDAV service provided by Alist is directly supported in Browser, Other WebDAV services need to enable CORS to work properly" + )} +
+ )}
{ + if ( + this.props.settingDrive === "webdav" || + this.props.settingDrive === "s3compatible" + ) { + let result = await testConnection( + this.props.settingDrive, + this.state.driveConfig + ); + if (!result) { + return; + } + } this.handleConfirmDrive(); }} > @@ -365,62 +399,24 @@ class SyncSetting extends React.Component { Authorize
)} - {isElectron && - (this.props.settingDrive === "webdav" || - this.props.settingDrive === "ftp" || - this.props.settingDrive === "sftp" || - this.props.settingDrive === "mega" || - this.props.settingDrive === "s3compatible") && ( -
{ - toast.loading(this.props.t("Testing connection..."), { - id: "testing-connection-id", - }); - const { ipcRenderer } = window.require("electron"); - const fs = window.require("fs"); - fs.writeFileSync( - getStorageLocation() + "/config/test.txt", - "Hello world!" - ); - let driveConfig: any = {}; - for (let item in this.state.driveConfig) { - driveConfig[item] = this.state.driveConfig[item]; - } - let result = await ipcRenderer.invoke("cloud-upload", { - ...driveConfig, - fileName: "test.txt", - service: this.props.settingDrive, - type: "config", - storagePath: getStorageLocation(), - isUseCache: false, - }); - if (result) { - toast.success(this.props.t("Connection successful"), { - id: "testing-connection-id", - }); - await ipcRenderer.invoke("cloud-delete", { - ...driveConfig, - fileName: "test.txt", - service: this.props.settingDrive, - type: "config", - storagePath: getStorageLocation(), - isUseCache: false, - }); - } else { - toast.error(this.props.t("Connection failed"), { - id: "testing-connection-id", - }); - } - fs.unlinkSync( - getStorageLocation() + "/config/test.txt" - ); - }} - > - Test -
- )} + {(this.props.settingDrive === "webdav" || + this.props.settingDrive === "ftp" || + this.props.settingDrive === "sftp" || + this.props.settingDrive === "mega" || + this.props.settingDrive === "s3compatible") && ( +
{ + testConnection( + this.props.settingDrive, + this.state.driveConfig + ); + }} + > + Test +
+ )} {(this.props.settingDrive === "webdav" || this.props.settingDrive === "ftp" || this.props.settingDrive === "s3compatible" || diff --git a/src/pages/login/component.tsx b/src/pages/login/component.tsx index 601aab40..47f7c081 100644 --- a/src/pages/login/component.tsx +++ b/src/pages/login/component.tsx @@ -401,6 +401,15 @@ class Login extends React.Component { {this.props.t("Recommended (use with Nutstore)")}
)} + {ConfigService.getReaderConfig("lang") && + ConfigService.getReaderConfig("lang").startsWith( + "zh" + ) && + item.value === "microsoft" && ( +
+ {this.props.t("Access may be unstable in China")} +
+ )}
{item.support.map((support) => { diff --git a/src/pages/reader/component.tsx b/src/pages/reader/component.tsx index d08a1f43..44f8e0bb 100644 --- a/src/pages/reader/component.tsx +++ b/src/pages/reader/component.tsx @@ -65,6 +65,9 @@ class Reader extends React.Component { ); } }, 1000); + window.addEventListener("beforeunload", function (event) { + ConfigService.setItem("isFinshReading", "yes"); + }); } UNSAFE_componentWillMount() { let url = document.location.href; diff --git a/src/store/actions/book.tsx b/src/store/actions/book.tsx index 3865fbe4..c0a2557c 100644 --- a/src/store/actions/book.tsx +++ b/src/store/actions/book.tsx @@ -14,6 +14,9 @@ export function handleRenderBookFunc(renderBookFunc: () => void) { export function handleImportBookFunc(importBookFunc: () => void) { return { type: "HANDLE_IMPORT_BOOK_FUNC", payload: importBookFunc }; } +export function handleCloudSyncFunc(cloudSyncFunc: () => void) { + return { type: "HANDLE_CLOUD_SYNC_FUNC", payload: cloudSyncFunc }; +} export function handleRenderNoteFunc(renderNoteFunc: () => void) { return { type: "HANDLE_RENDER_NOTE_FUNC", payload: renderNoteFunc }; } diff --git a/src/store/actions/manager.tsx b/src/store/actions/manager.tsx index 770c62c0..10f04586 100644 --- a/src/store/actions/manager.tsx +++ b/src/store/actions/manager.tsx @@ -6,7 +6,7 @@ import BookModel from "../../models/Book"; import PluginModel from "../../models/Plugin"; import { Dispatch } from "redux"; import DatabaseService from "../../utils/storage/databaseService"; -import { fetchUserConfig, fetchUserInfo } from "../../utils/request/user"; +import { fetchUserInfo } from "../../utils/request/user"; import { officialDictList, officialTranList, @@ -30,9 +30,6 @@ export function handleSearch(isSearch: boolean) { export function handleUserInfo(userInfo: any) { return { type: "HANDLE_USER_INFO", payload: userInfo }; } -export function handleUserConfig(userConfig: any) { - return { type: "HANDLE_USER_CONFIG", payload: userConfig }; -} export function handleDetailDialog(isDetailDialog: boolean) { return { type: "HANDLE_DETAIL_DIALOG", payload: isDetailDialog }; } @@ -115,6 +112,10 @@ export function handleFetchUserInfo() { let userInfo: any = null; if (response.code === 200) { userInfo = response.data; + ConfigService.setReaderConfig( + "isEnableKoodoSync", + userInfo.is_enable_koodo_sync || "no" + ); } if ( userInfo && @@ -125,21 +126,6 @@ export function handleFetchUserInfo() { dispatch(handleUserInfo(userInfo)); }; } -export function handleFetchUserConfig() { - return async (dispatch: Dispatch) => { - let response = await fetchUserConfig(); - let userConfig: any = null; - if (response.code === 200) { - userConfig = response.data; - console.log("UserConfig", userConfig); - ConfigService.setReaderConfig( - "isEnableKoodoSync", - userConfig.is_enable_koodo_sync - ); - } - dispatch(handleUserConfig(userConfig)); - }; -} export function handleFetchPlugins() { return async (dispatch: Dispatch) => { DatabaseService.getAllRecords("plugins").then((pluginList) => { diff --git a/src/store/index.tsx b/src/store/index.tsx index acface73..a6fb3beb 100644 --- a/src/store/index.tsx +++ b/src/store/index.tsx @@ -47,7 +47,6 @@ export type stateType = { isShowSupport: boolean; isShowNew: boolean; userInfo: any; - userConfig: any; isAuthed: boolean; isNewWarning: boolean; isSelectBook: boolean; @@ -72,6 +71,7 @@ export type stateType = { currentBook: BookModel; renderBookFunc: () => void; importBookFunc: (file: any) => Promise; + cloudSyncFunc: () => Promise; renderNoteFunc: () => void; }; backupPage: { diff --git a/src/store/reducers/book.tsx b/src/store/reducers/book.tsx index 962061da..84fbb1aa 100644 --- a/src/store/reducers/book.tsx +++ b/src/store/reducers/book.tsx @@ -10,6 +10,7 @@ const initState = { totalPage: 1, renderBookFunc: () => {}, importBookFunc: () => {}, + cloudSyncFunc: () => {}, renderNoteFunc: () => {}, }; export function book( @@ -42,6 +43,11 @@ export function book( ...state, importBookFunc: action.payload, }; + case "HANDLE_CLOUD_SYNC_FUNC": + return { + ...state, + cloudSyncFunc: action.payload, + }; case "HANDLE_RENDER_NOTE_FUNC": return { ...state, diff --git a/src/utils/common.ts b/src/utils/common.ts index aac8bdbd..d00c7510 100644 --- a/src/utils/common.ts +++ b/src/utils/common.ts @@ -5,12 +5,16 @@ import { BookHelper, CommonTool, ConfigService, + SyncUtil, } from "../assets/lib/kookit-extra-browser.min"; import Book from "../models/Book"; import BookUtil from "./file/bookUtil"; import * as Kookit from "../assets/lib/kookit.min"; import DatabaseService from "./storage/databaseService"; import packageJson from "../../package.json"; +import toast from "react-hot-toast"; +import i18n from "../i18n"; +import { getThirdpartyRequest } from "./request/thirdparty"; declare var window: any; export const calculateFileMD5 = (file: File): Promise => { return new Promise((resolve, reject) => { @@ -494,3 +498,62 @@ export const checkMissingBook = (bookList: Book[]) => { } } }; +export const testConnection = async (driveName: string, driveConfig: any) => { + toast.loading(i18n.t("Testing connection..."), { + id: "testing-connection-id", + }); + if (isElectron) { + const { ipcRenderer } = window.require("electron"); + const fs = window.require("fs"); + fs.writeFileSync(getStorageLocation() + "/config/test.txt", "Hello world!"); + let result = await ipcRenderer.invoke("cloud-upload", { + ...driveConfig, + fileName: "test.txt", + service: driveName, + type: "config", + storagePath: getStorageLocation(), + isUseCache: false, + }); + if (result) { + toast.success(i18n.t("Connection successful"), { + id: "testing-connection-id", + }); + await ipcRenderer.invoke("cloud-delete", { + ...driveConfig, + fileName: "test.txt", + service: driveName, + type: "config", + storagePath: getStorageLocation(), + isUseCache: false, + }); + } else { + toast.error(i18n.t("Connection failed"), { + id: "testing-connection-id", + }); + } + fs.unlinkSync(getStorageLocation() + "/config/test.txt"); + return result; + } else { + let thirdpartyRequest = await getThirdpartyRequest(); + let syncUtil = new SyncUtil(driveName, driveConfig, thirdpartyRequest); + // 上传到云端 + let result = await syncUtil.uploadFile( + "test.txt", + "config", + new Blob(["Hello world!"]) + ); + if (!result) { + toast.error(i18n.t("Connection failed"), { + id: "testing-connection-id", + }); + return false; + } else { + toast.success(i18n.t("Connection successful"), { + id: "testing-connection-id", + }); + } + + // 删除云端文件 + return await syncUtil.deleteFile("test.txt", "config"); + } +}; diff --git a/src/utils/file/configUtil.ts b/src/utils/file/configUtil.ts index 6fb93fff..3860e75d 100644 --- a/src/utils/file/configUtil.ts +++ b/src/utils/file/configUtil.ts @@ -116,7 +116,6 @@ class ConfigUtil { let response = await thirdpartyRequest.getSyncData(); if (response.code === 200) { let syncData = response.data; - console.log("getSyncData", syncData); this.syncData = syncData; return JSON.parse(this.syncData[type] || defaultValue); } else if (response.code === 401) { @@ -130,8 +129,6 @@ class ConfigUtil { } } static async updateSyncData() { - console.log("updateSyncData", this.updateData); - let thirdpartyRequest = await getThirdpartyRequest(); let response = await thirdpartyRequest.updateSyncData(this.updateData); @@ -159,7 +156,6 @@ class ConfigUtil { static async getCloudDatabase(database: string) { if (ConfigService.getReaderConfig("isEnableKoodoSync") === "yes") { let data = await this.getSyncData(database); - console.log("getCloudDatabase", database, data); return data || []; } if (isElectron) { @@ -210,7 +206,6 @@ class ConfigUtil { return record; }); } - console.log("uploadDatabase", type, data); this.updateData[type] = JSON.stringify(data); return; } diff --git a/src/utils/request/user.ts b/src/utils/request/user.ts index fff77747..20d845de 100644 --- a/src/utils/request/user.ts +++ b/src/utils/request/user.ts @@ -54,14 +54,6 @@ export const fetchUserInfo = async () => { } return response; }; -export const fetchUserConfig = async () => { - let userRequest = await getUserRequest(); - let response = await userRequest.getUserConfig(); - if (response.code === 401) { - handleExitApp(); - } - return response; -}; export const updateUserConfig = async (config: any) => { let userRequest = await getUserRequest(); let response = await userRequest.updateUserConfig(config);